diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..afe81bb0f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +node_modules +print/node_modules +front/node_modules +services \ No newline at end of file diff --git a/.env.json b/.env.json deleted file mode 100644 index 0fa6162d9..000000000 --- a/.env.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "salixHost": "localhost", - "salixPort": "3306", - "salixUser": "root", - "salixPassword": "root" -} \ No newline at end of file diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 000000000..b512c09d4 --- /dev/null +++ b/.eslintignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/.eslintrc.yml b/.eslintrc.yml index 022c3d6fa..163ff22a7 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -1,12 +1,12 @@ extends: [eslint:recommended, google, plugin:jasmine/recommended] parserOptions: - ecmaVersion: 2017 + ecmaVersion: 2018 + sourceType: "module" plugins: - jasmine env: jasmine: true rules: - indent: [error, 4] require-jsdoc: 0 no-undef: 0 max-len: 0 @@ -20,3 +20,15 @@ rules: no-console: 0 no-warning-comments: 0 no-empty: [error, allowEmptyCatch: true] + complexity: 0 + max-depth: 0 + comma-dangle: 0 + bracketSpacing: 0 + space-infix-ops: 1 + no-invalid-this: 0 + space-before-function-paren: [error, never] + prefer-const: 0 + curly: [error, multi-or-nest] + indent: [error, 4] + arrow-parens: [error, as-needed] + jasmine/no-focused-tests: 0 diff --git a/.gitignore b/.gitignore index 0f92907cc..8cb76a829 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,13 @@ +coverage node_modules -build +dist +e2e/dms/*/ +!e2e/dms/c4c +!e2e/dms/c81 +!e2e/dms/ecc npm-debug.log -docker-compose.yml +.eslintcache +datasources.*.json +print.*.json +db.json +junit.xml \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index c3b70b7f0..c919f6d71 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,7 +4,13 @@ { "type": "node", "request": "attach", - "name": "Attach by Process ID", + "name": "Attach", + "restart": true, + "timeout": 50000 + }, { + "type": "node", + "request": "attach", + "name": "Attach by process ID", "processId": "${command:PickProcess}" } ] diff --git a/.vscode/settings.json b/.vscode/settings.json index b88a6ec8c..2298e4846 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,6 +1,10 @@ -// Coloque su configuración en este archivo para sobrescribir la configuración predeterminada y de usuario. -{ - // Carácter predeterminado de final de línea. - "files.eol": "\n", - "vsicons.presets.angular": false +// Coloque su configuración en este archivo para sobrescribir la configuración predeterminada y de usuario. +{ + // Carácter predeterminado de final de línea. + "files.eol": "\n", + "vsicons.presets.angular": false, + "eslint.autoFixOnSave": true, + "editor.codeActionsOnSave": { + "source.fixAll.eslint": true + } } \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 098642bfb..5a65b9b18 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,13 +1,38 @@ -FROM node:8.9.4 +FROM debian:stretch-slim +ENV TZ Europe/Madrid -COPY . /app -COPY ../loopback /loopback +ARG DEBIAN_FRONTEND=noninteractive +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + curl \ + ca-certificates \ + gnupg2 \ + libfontconfig \ + && curl -sL https://deb.nodesource.com/setup_10.x | bash - \ + && apt-get install -y --no-install-recommends \ + nodejs \ + && apt-get purge -y --auto-remove \ + gnupg2 \ + && rm -rf /var/lib/apt/lists/* \ + && npm -g install pm2 -WORKDIR /app - -RUN npm install -RUN npm -g install pm2 +WORKDIR /salix +COPY package.json package-lock.json ./ +COPY loopback/package.json loopback/ +COPY print/package.json print/ +RUN npm install --only=prod +RUN npm --prefix ./print install --only=prod ./print -CMD ["pm2-docker", "./server/server.js"] +COPY loopback loopback +COPY back back +COPY modules modules +COPY print print +COPY \ + LICENSE \ + README.md \ + ./ -EXPOSE 3000 +CMD ["pm2-runtime", "./back/process.yml"] + +HEALTHCHECK --interval=15s --timeout=10s \ + CMD curl -f http://localhost:3000/api/Applications/status || exit 1 diff --git a/Jenkinsfile b/Jenkinsfile index 617a4f8f9..1fa6a49ea 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,60 +1,146 @@ #!/usr/bin/env groovy -def branchName = "${env.BRANCH_NAME}"; -def branchProduction = "master" -def branchTest = "test"; - -env.BRANCH_NAME = branchName; -env.TAG = "${env.BUILD_NUMBER}"; -env.salixUser="${env.salixUser}"; -env.salixPassword="${env.salixPassword}"; -env.salixHost = "${env.productionSalixHost}"; -env.salixPort = "${env.productionSalixPort}"; - -switch (branchName){ - case branchTest: - env.NODE_ENV = "test"; - env.salixHost = "${env.testSalixHost}"; - env.salixPort = "${env.testSalixPort}"; - break; - case branchProduction: - env.DOCKER_HOST = "tcp://172.16.255.29:2375"; - env.NODE_ENV = "production" - break; -} - -node -{ - stage ('Print environment variables'){ - echo "Branch ${branchName}, Build ${env.TAG}, salixHost ${env.salixHost}, NODE_ENV ${env.NODE_ENV} en docker Host ${env.DOCKER_HOST}" +pipeline { + agent any + options { + disableConcurrentBuilds() } - stage ('Checkout') { - checkout scm + environment { + PROJECT_NAME = 'salix' + STACK_NAME = "${env.PROJECT_NAME}-${env.BRANCH_NAME}" } + stages { + stage('Checkout') { + steps { + script { + if (!env.GIT_COMMITTER_EMAIL) { + env.COMMITTER_EMAIL = sh( + script: 'git --no-pager show -s --format="%ae"', + returnStdout: true + ).trim() + } else { + env.COMMITTER_EMAIL = env.GIT_COMMITTER_EMAIL; + } - stage ('install modules'){ - sh "npm install" - } - - stage ('build Project'){ - sh "gulp build" - } + switch (env.BRANCH_NAME) { + case 'master': + env.NODE_ENV = 'production' + break + case 'test': + env.NODE_ENV = 'test' + break + } + } - stage ("docker") - { - stage ("install modules loopback service") - { - sh "cd ./services/loopback && npm install" + configFileProvider([ + configFile(fileId: "salix.groovy", + variable: 'GROOVY_FILE') + ]) { + load env.GROOVY_FILE + } + + sh 'printenv' + } } - - stage ("Stopping/Removing Docker") - { - sh "docker-compose down --rmi 'all'" + stage('Install') { + environment { + NODE_ENV = "" + } + steps { + nodejs('node-lts') { + sh 'npm install --no-audit --prefer-offline' + sh 'gulp install --ci' + } + } } + stage('Test') { + environment { + NODE_ENV = "" + } + parallel { + stage('Frontend') { + steps { + nodejs('node-lts') { + sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=1' + } + } + } + stage('Backend') { + steps { + nodejs('node-lts') { + sh 'gulp backTestDockerOnce --junit --random' + } + } + } + } + } + stage('Build') { + when { anyOf { + branch 'test' + branch 'master' + }} + environment { + CREDS = credentials('docker-registry') + } + steps { + nodejs('node-lts') { + sh 'gulp build' + } - stage ("Generar dockers") - { - sh "docker-compose up -d --build" - } + sh 'docker login --username $CREDS_USR --password $CREDS_PSW $REGISTRY' + sh 'docker-compose build --parallel' + sh 'docker-compose push' + } + } + stage('Deploy') { + when { anyOf { + branch 'test' + branch 'master' + }} + steps { + sh "docker stack deploy --with-registry-auth --compose-file docker-compose.yml ${env.STACK_NAME}" + } + } + stage('Database') { + when { anyOf { + branch 'test' + branch 'master' + }} + steps { + configFileProvider([ + configFile(fileId: "config.${env.NODE_ENV}.ini", + variable: 'MYSQL_CONFIG') + ]) { + sh 'cp "$MYSQL_CONFIG" db/config.$NODE_ENV.ini' + } + + sh 'db/import-changes.sh -f $NODE_ENV' + } + } + } + post { + always { + script { + if (!['master', 'test'].contains(env.BRANCH_NAME)) { + try { + junit 'junitresults.xml' + junit 'junit.xml' + } catch (e) { + echo e.toString() + } + } + + if (!env.COMMITTER_EMAIL) return + try { + mail( + to: env.COMMITTER_EMAIL, + subject: "Pipeline: ${env.JOB_NAME} (${env.BUILD_NUMBER}): ${currentBuild.currentResult}", + body: "Check status at ${env.BUILD_URL}" + ) + } catch (e) { + echo e.toString() + } + } + } } } diff --git a/README.md b/README.md index 176f0761e..ae3d01f1d 100644 --- a/README.md +++ b/README.md @@ -8,13 +8,24 @@ Salix is also the scientific name of a beautifull tree! :) Required applications. -* Node.js = 8.9.4 -* NGINX +* Visual Studio Code +* Node.js = 10.15.3 LTS * Docker +In Visual Studio Code we use the ESLint extension. Open Visual Studio Code, press Ctrl+P and paste the following command. +``` +ext install dbaeumer.vscode-eslint +``` + You will need to install globally the following items. ``` -$ npm install -g karma-cli gulp webpack nodemon +# npm install -g jest gulp-cli nodemon +``` +## Linux Only Prerequisites + +Your user must be on the docker group to use it so you will need to run this command: +``` +$ sudo usermod -a -G docker yourusername ``` ## Getting Started // Installing @@ -32,12 +43,6 @@ Launch application in developer environment. $ gulp ``` -Also you can run backend and frontend as separately gulp tasks (including NGINX). -``` -$ gulp client -$ gulp services -``` - Manually reset fixtures. ``` $ gulp docker @@ -47,12 +52,12 @@ $ gulp docker For client-side unit tests run from project's root. ``` -$ karma start +$ jest ``` For server-side unit tests run from project's root. ``` -$ npm run test +$ gulp backTest ``` For end-to-end tests run from project's root. @@ -68,6 +73,6 @@ $ gulp e2e * [loopback](https://loopback.io/) * [docker](https://www.docker.com/) * [gulp.js](https://gulpjs.com/) -* [Karma](https://karma-runner.github.io/) +* [jest](https://jestjs.io/) * [Jasmine](https://jasmine.github.io/) * [Nightmare](http://www.nightmarejs.org/) diff --git a/babel.config.js b/babel.config.js new file mode 100644 index 000000000..1ed9a4e6e --- /dev/null +++ b/babel.config.js @@ -0,0 +1,5 @@ +module.exports = { + presets: [ + '@babel/preset-env', + ], +}; diff --git a/back/methods/account/acl.js b/back/methods/account/acl.js new file mode 100644 index 000000000..c1dcdc11b --- /dev/null +++ b/back/methods/account/acl.js @@ -0,0 +1,45 @@ +module.exports = Self => { + Self.remoteMethod('acl', { + description: 'Get the user information and permissions', + accepts: [ + { + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + } + ], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/acl`, + verb: 'GET' + } + }); + + Self.acl = async function(ctx) { + let userId = ctx.req.accessToken.userId; + let models = Self.app.models; + + let user = await models.Account.findById(userId, { + fields: ['id', 'name', 'nickname', 'email'] + }); + + let roles = await models.RoleMapping.find({ + fields: ['roleId'], + where: { + principalId: userId, + principalType: 'USER' + }, + include: [{ + relation: 'role', + scope: { + fields: ['name'] + } + }] + }); + + return {roles, user}; + }; +}; diff --git a/back/methods/account/login.js b/back/methods/account/login.js new file mode 100644 index 000000000..075d3669c --- /dev/null +++ b/back/methods/account/login.js @@ -0,0 +1,67 @@ +const md5 = require('md5'); + +module.exports = Self => { + Self.remoteMethod('login', { + description: 'Login a user with username/email and password', + accepts: [ + { + arg: 'user', + type: 'String', + description: 'The user name or email', + required: true + }, { + arg: 'password', + type: 'String', + description: 'The user name or email' + } + ], + returns: { + type: 'object', + root: true + }, + http: { + path: `/login`, + verb: 'POST' + } + }); + + Self.login = async function(user, password) { + let token; + let usesEmail = user.indexOf('@') !== -1; + let User = Self.app.models.User; + + let loginInfo = {password}; + + if (usesEmail) + loginInfo.email = user; + else + loginInfo.username = user; + + try { + token = await User.login(loginInfo, 'user'); + } catch (err) { + if (err.code != 'LOGIN_FAILED' || usesEmail) + throw err; + + let filter = {where: {name: user}}; + let instance = await Self.findOne(filter); + + if (!instance || instance.password !== md5(password || '')) + throw err; + + let where = {id: instance.id}; + let userData = { + id: instance.id, + username: user, + password: password, + email: instance.email, + created: instance.created, + updated: instance.updated + }; + await User.upsertWithWhere(where, userData); + token = await User.login(loginInfo, 'user'); + } + + return {token: token.id}; + }; +}; diff --git a/back/methods/account/logout.js b/back/methods/account/logout.js new file mode 100644 index 000000000..515855267 --- /dev/null +++ b/back/methods/account/logout.js @@ -0,0 +1,25 @@ +module.exports = Self => { + Self.remoteMethod('logout', { + description: 'Logout a user with access token', + accepts: [ + { + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + } + ], + returns: { + type: 'Boolean', + root: true + }, + http: { + path: `/logout`, + verb: 'POST' + } + }); + + Self.logout = async function(ctx) { + await Self.app.models.User.logout(ctx.req.accessToken.id); + return true; + }; +}; diff --git a/back/methods/account/specs/login.spec.js b/back/methods/account/specs/login.spec.js new file mode 100644 index 000000000..ffb19637f --- /dev/null +++ b/back/methods/account/specs/login.spec.js @@ -0,0 +1,33 @@ +const app = require('vn-loopback/server/server'); + +describe('account login()', () => { + describe('when credentials are correct', () => { + it('should return the token', async() => { + let response = await app.models.Account.login('employee', 'nightmare'); + + expect(response.token).toBeDefined(); + }); + + it('should return the token if the user doesnt exist but the client does', async() => { + let response = await app.models.Account.login('PetterParker', 'nightmare'); + + expect(response.token).toBeDefined(); + }); + }); + + describe('when credentials are incorrect', () => { + it('should throw a 401 error', async() => { + let error; + + try { + await app.models.Account.login('IDontExist', 'TotallyWrongPassword'); + } catch (e) { + error = e; + } + + expect(error).toBeDefined(); + expect(error.statusCode).toBe(401); + expect(error.code).toBe('LOGIN_FAILED'); + }); + }); +}); diff --git a/back/methods/account/specs/logout.spec.js b/back/methods/account/specs/logout.spec.js new file mode 100644 index 000000000..5770be91f --- /dev/null +++ b/back/methods/account/specs/logout.spec.js @@ -0,0 +1,42 @@ +const app = require('vn-loopback/server/server'); + +describe('account logout()', () => { + it('should logout and remove token after valid login', async() => { + let loginResponse = await app.models.Account.login('employee', 'nightmare'); + let accessToken = await app.models.AccessToken.findById(loginResponse.token); + let ctx = {req: {accessToken: accessToken}}; + + let response = await app.models.Account.logout(ctx); + let afterToken = await app.models.AccessToken.findById(loginResponse.token); + + expect(response).toBeTruthy(); + expect(afterToken).toBeNull(); + }); + + it('should throw a 401 error when token is invalid', async() => { + let error; + let ctx = {req: {accessToken: {id: 'invalidToken'}}}; + + try { + response = await app.models.Account.logout(ctx); + } catch (e) { + error = e; + } + + expect(error).toBeDefined(); + expect(error.statusCode).toBe(401); + }); + + it('should throw an error when no token is passed', async() => { + let error; + let ctx = {req: {accessToken: null}}; + + try { + response = await app.models.Account.logout(ctx); + } catch (e) { + error = e; + } + + expect(error).toBeDefined(); + }); +}); diff --git a/back/methods/account/validate-token.js b/back/methods/account/validate-token.js new file mode 100644 index 000000000..7bccfe0b1 --- /dev/null +++ b/back/methods/account/validate-token.js @@ -0,0 +1,17 @@ +module.exports = Self => { + Self.remoteMethod('validateToken', { + description: 'Validates the current logged user token', + returns: { + type: 'Boolean', + root: true + }, + http: { + path: `/validateToken`, + verb: 'GET' + } + }); + + Self.validateToken = async function() { + return true; + }; +}; diff --git a/back/methods/chat/sendMessage.js b/back/methods/chat/sendMessage.js new file mode 100644 index 000000000..2ab07af8c --- /dev/null +++ b/back/methods/chat/sendMessage.js @@ -0,0 +1,96 @@ +const request = require('request-promise-native'); +module.exports = Self => { + Self.remoteMethodCtx('sendMessage', { + description: 'Send a RocketChat message', + accessType: 'WRITE', + accepts: [{ + arg: 'to', + type: 'String', + required: true, + description: 'user (@) or channel (#) to send the message' + }, { + arg: 'message', + type: 'String', + required: true, + description: 'The message' + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/sendMessage`, + verb: 'POST' + } + }); + + Self.sendMessage = async(ctx, to, message) => { + const models = Self.app.models; + const accessToken = ctx.req.accessToken; + const sender = await models.Account.findById(accessToken.userId); + const recipient = to.replace('@', ''); + + if (sender.name != recipient) + return sendMessage(to, `@${sender.name}: ${message}`); + }; + + async function sendMessage(name, message) { + const models = Self.app.models; + const chatConfig = await models.ChatConfig.findOne(); + + if (!Self.token) + Self.token = await login(); + + const uri = `${chatConfig.uri}/chat.postMessage`; + return send(uri, { + 'channel': name, + 'text': message + }).catch(async error => { + if (error.statusCode === 401 && !Self.loginAttempted) { + Self.token = await login(); + Self.loginAttempted = true; + + return sendMessage(name, message); + } + + throw new Error(error.message); + }); + } + + /** + * Returns a rocketchat token + * @return {Object} userId and authToken + */ + async function login() { + const models = Self.app.models; + const chatConfig = await models.ChatConfig.findOne(); + const uri = `${chatConfig.uri}/login`; + return send(uri, { + user: chatConfig.user, + password: chatConfig.password + }).then(res => res.data); + } + + function send(uri, body) { + if (process.env.NODE_ENV !== 'production') { + return new Promise(resolve => { + return resolve({statusCode: 200, message: 'Fake notification sent'}); + }); + } + + const options = { + method: 'POST', + uri: uri, + body: body, + headers: {'content-type': 'application/json'}, + json: true + }; + + if (Self.token) { + options.headers['X-Auth-Token'] = Self.token.authToken; + options.headers['X-User-Id'] = Self.token.userId; + } + + return request(options); + } +}; diff --git a/back/methods/chat/spec/send.spec.js b/back/methods/chat/spec/send.spec.js new file mode 100644 index 000000000..ebb62a0c8 --- /dev/null +++ b/back/methods/chat/spec/send.spec.js @@ -0,0 +1,18 @@ +const app = require('vn-loopback/server/server'); + +describe('chat sendMessage()', () => { + it('should return a "Fake notification sent" as response', async() => { + let ctx = {req: {accessToken: {userId: 1}}}; + let response = await app.models.Chat.sendMessage(ctx, '@salesPerson', 'I changed something'); + + expect(response.statusCode).toEqual(200); + expect(response.message).toEqual('Fake notification sent'); + }); + + it('should not return a response', async() => { + let ctx = {req: {accessToken: {userId: 18}}}; + let response = await app.models.Chat.sendMessage(ctx, '@salesPerson', 'I changed something'); + + expect(response).toBeUndefined(); + }); +}); diff --git a/back/methods/dms/downloadFile.js b/back/methods/dms/downloadFile.js new file mode 100644 index 000000000..f3096aabb --- /dev/null +++ b/back/methods/dms/downloadFile.js @@ -0,0 +1,62 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('downloadFile', { + description: 'Download a document', + accessType: 'READ', + accepts: [ + { + arg: 'id', + type: 'Number', + description: 'The document id', + http: {source: 'path'} + } + ], + returns: [ + { + arg: 'body', + type: 'file', + root: true + }, { + arg: 'Content-Type', + type: 'String', + http: {target: 'header'} + }, { + arg: 'Content-Disposition', + type: 'String', + http: {target: 'header'} + } + ], + http: { + path: `/:id/downloadFile`, + verb: 'GET' + } + }); + + Self.downloadFile = async function(ctx, id) { + const storageConnector = Self.app.dataSources.storage.connector; + const models = Self.app.models; + const dms = await Self.findById(id); + + const hasReadRole = await models.DmsType.hasReadRole(ctx, dms.dmsTypeFk); + if (!hasReadRole) + throw new UserError(`You don't have enough privileges`); + + const pathHash = storageConnector.getPathHash(dms.id); + try { + await models.Container.getFile(pathHash, dms.file); + } catch (e) { + if (e.code != 'ENOENT') + throw e; + + const error = new UserError(`File doesn't exists`); + error.statusCode = 404; + + throw error; + } + + const stream = models.Container.downloadStream(pathHash, dms.file); + + return [stream, dms.contentType, `filename="${dms.file}"`]; + }; +}; diff --git a/back/methods/dms/removeFile.js b/back/methods/dms/removeFile.js new file mode 100644 index 000000000..350bea6bc --- /dev/null +++ b/back/methods/dms/removeFile.js @@ -0,0 +1,34 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('removeFile', { + description: 'Makes a logical delete moving a file to a trash folder', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'Number', + description: 'The document id', + http: {source: 'path'} + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/removeFile`, + verb: 'POST' + } + }); + + Self.removeFile = async(ctx, id) => { + const models = Self.app.models; + const trashDmsType = await models.DmsType.findOne({where: {code: 'trash'}}); + const dms = await models.Dms.findById(id); + + const hasWriteRole = await models.DmsType.hasWriteRole(ctx, dms.dmsTypeFk); + if (!hasWriteRole) + throw new UserError(`You don't have enough privileges`); + + return dms.updateAttribute('dmsTypeFk', trashDmsType.id); + }; +}; diff --git a/back/methods/dms/specs/downloadFile.spec.js b/back/methods/dms/specs/downloadFile.spec.js new file mode 100644 index 000000000..ae8a4fe53 --- /dev/null +++ b/back/methods/dms/specs/downloadFile.spec.js @@ -0,0 +1,26 @@ +const app = require('vn-loopback/server/server'); + +describe('dms downloadFile()', () => { + let dmsId = 1; + it('should return a response for an employee with text content-type', async() => { + let workerId = 107; + let ctx = {req: {accessToken: {userId: workerId}}}; + const result = await app.models.Dms.downloadFile(ctx, dmsId); + + expect(result[1]).toEqual('text/plain'); + }); + + it(`should return an error for a user without enough privileges`, async() => { + let clientId = 101; + let ctx = {req: {accessToken: {userId: clientId}}}; + + let error; + await app.models.Dms.downloadFile(ctx, dmsId).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`You don't have enough privileges`); + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/back/methods/dms/specs/removeFile.spec.js b/back/methods/dms/specs/removeFile.spec.js new file mode 100644 index 000000000..1006d1329 --- /dev/null +++ b/back/methods/dms/specs/removeFile.spec.js @@ -0,0 +1,19 @@ +const app = require('vn-loopback/server/server'); + +describe('dms removeFile()', () => { + let dmsId = 1; + + it(`should return an error for a user without enough privileges`, async() => { + let clientId = 101; + let ctx = {req: {accessToken: {userId: clientId}}}; + + let error; + await app.models.Dms.removeFile(ctx, dmsId).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`You don't have enough privileges`); + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/back/methods/dms/specs/updateFile.spec.js b/back/methods/dms/specs/updateFile.spec.js new file mode 100644 index 000000000..2945b1ac9 --- /dev/null +++ b/back/methods/dms/specs/updateFile.spec.js @@ -0,0 +1,22 @@ +const app = require('vn-loopback/server/server'); + +describe('dms updateFile()', () => { + it(`should return an error for a user without enough privileges`, async() => { + let clientId = 101; + let companyId = 442; + let warehouseId = 1; + let dmsTypeId = 14; + + let dmsId = 1; + let ctx = {req: {accessToken: {userId: clientId}}, args: {dmsTypeId: dmsTypeId}}; + + let error; + await app.models.Dms.updateFile(ctx, dmsId, warehouseId, companyId, dmsTypeId).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`You don't have enough privileges`); + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/back/methods/dms/specs/uploadFile.spec.js b/back/methods/dms/specs/uploadFile.spec.js new file mode 100644 index 000000000..afd70d068 --- /dev/null +++ b/back/methods/dms/specs/uploadFile.spec.js @@ -0,0 +1,18 @@ +const app = require('vn-loopback/server/server'); + +describe('dms uploadFile()', () => { + it(`should return an error for a user without enough privileges`, async() => { + let clientId = 101; + let ticketDmsTypeId = 14; + let ctx = {req: {accessToken: {userId: clientId}}, args: {dmsTypeId: ticketDmsTypeId}}; + + let error; + await app.models.Dms.uploadFile(ctx).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`You don't have enough privileges`); + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/back/methods/dms/updateFile.js b/back/methods/dms/updateFile.js new file mode 100644 index 000000000..dff45f640 --- /dev/null +++ b/back/methods/dms/updateFile.js @@ -0,0 +1,150 @@ +const UserError = require('vn-loopback/util/user-error'); +const fs = require('fs-extra'); + +module.exports = Self => { + Self.remoteMethodCtx('updateFile', { + description: 'updates a file properties or file', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'Number', + description: 'The document id', + http: {source: 'path'} + }, + { + arg: 'warehouseId', + type: 'Number', + description: 'The warehouse id' + }, { + arg: 'companyId', + type: 'Number', + description: 'The company id' + }, { + arg: 'dmsTypeId', + type: 'Number', + description: 'The dms type id' + }, { + arg: 'reference', + type: 'String' + }, { + arg: 'description', + type: 'String' + }, { + arg: 'hasFileAttached', + type: 'Boolean', + description: 'True if has an attached file' + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/updateFile`, + verb: 'POST' + } + }); + + Self.updateFile = async(ctx, id, warehouseId, companyId, + dmsTypeId, reference, description, hasFileAttached, options) => { + const models = Self.app.models; + + let tx; + let myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const hasWriteRole = await models.DmsType.hasWriteRole(ctx, dmsTypeId); + if (!hasWriteRole) + throw new UserError(`You don't have enough privileges`); + + const dms = await Self.findById(id, null, myOptions); + await dms.updateAttributes({ + dmsTypeFk: dmsTypeId, + companyFk: companyId, + warehouseFk: warehouseId, + reference: reference, + description: description + }, myOptions); + + if (hasFileAttached) + await uploadNewFile(ctx, dms, myOptions); + + if (tx) await tx.commit(); + return dms; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; + + async function uploadNewFile(ctx, dms, myOptions) { + const storageConnector = Self.app.dataSources.storage.connector; + const models = Self.app.models; + const fileOptions = {}; + + const tempContainer = await getContainer('temp'); + const makeUpload = await models.Container.upload(tempContainer.name, ctx.req, ctx.result, fileOptions); + const keys = Object.values(makeUpload.files); + const files = keys.map(file => file[0]); + const file = files[0]; + + if (file) { + const oldExtension = storageConnector.getFileExtension(dms.file); + const newExtension = storageConnector.getFileExtension(file.name); + const fileName = `${dms.id}.${newExtension}`; + + try { + if (oldExtension != newExtension) { + const pathHash = storageConnector.getPathHash(dms.id); + + await models.Container.removeFile(pathHash, dms.file); + } + } catch (err) {} + + const updatedDms = await dms.updateAttributes({ + contentType: file.type, + file: fileName + }, myOptions); + + const pathHash = storageConnector.getPathHash(updatedDms.id); + const container = await getContainer(pathHash); + + const originPath = `${tempContainer.client.root}/${tempContainer.name}/${file.name}`; + const destinationPath = `${container.client.root}/${pathHash}/${updatedDms.file}`; + + fs.rename(originPath, destinationPath); + + return updatedDms; + } + } + + /** + * Returns a container instance + * If doesn't exists creates a new one + * + * @param {String} name Container name + * @return {Object} Container instance + */ + async function getContainer(name) { + const models = Self.app.models; + let container; + try { + container = await models.Container.getContainer(name); + } catch (err) { + if (err.code === 'ENOENT') { + container = await models.Container.createContainer({ + name: name + }); + } else throw err; + } + + return container; + } +}; diff --git a/back/methods/dms/uploadFile.js b/back/methods/dms/uploadFile.js new file mode 100644 index 000000000..27e5169c9 --- /dev/null +++ b/back/methods/dms/uploadFile.js @@ -0,0 +1,147 @@ +const UserError = require('vn-loopback/util/user-error'); +const fs = require('fs-extra'); + +module.exports = Self => { + Self.remoteMethodCtx('uploadFile', { + description: 'Uploads a file and inserts into dms model', + accessType: 'WRITE', + accepts: [ + { + arg: 'warehouseId', + type: 'Number', + description: 'The warehouse id', + required: true + }, { + arg: 'companyId', + type: 'Number', + description: 'The company id', + required: true + }, { + arg: 'dmsTypeId', + type: 'Number', + description: 'The dms type id', + required: true + }, { + arg: 'reference', + type: 'String', + required: true + }, { + arg: 'description', + type: 'String', + required: true + }, { + arg: 'hasFile', + type: 'Boolean', + description: 'True if has an attached file', + required: true + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/uploadFile`, + verb: 'POST' + } + }); + + Self.uploadFile = async(ctx, options) => { + const storageConnector = Self.app.dataSources.storage.connector; + const models = Self.app.models; + const fileOptions = {}; + const args = ctx.args; + + let tx; + let myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const hasWriteRole = await models.DmsType.hasWriteRole(ctx, args.dmsTypeId, myOptions); + if (!hasWriteRole) + throw new UserError(`You don't have enough privileges`); + + // Upload file to temporary path + const tempContainer = await getContainer('temp'); + const uploaded = await models.Container.upload(tempContainer.name, ctx.req, ctx.result, fileOptions); + const files = Object.values(uploaded.files).map(file => { + return file[0]; + }); + + const addedDms = []; + for (const file of files) { + const newDms = await createDms(ctx, file, myOptions); + const pathHash = storageConnector.getPathHash(newDms.id); + const container = await getContainer(pathHash); + + const originPath = `${tempContainer.client.root}/${tempContainer.name}/${file.name}`; + const destinationPath = `${container.client.root}/${pathHash}/${newDms.file}`; + + await fs.rename(originPath, destinationPath); + + addedDms.push(newDms); + } + + if (tx) await tx.commit(); + return addedDms; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; + + async function createDms(ctx, file, myOptions) { + const models = Self.app.models; + const storageConnector = Self.app.dataSources.storage.connector; + const myUserId = ctx.req.accessToken.userId; + const myWorker = await models.Worker.findOne({where: {userFk: myUserId}}, myOptions); + const args = ctx.args; + + const newDms = await Self.create({ + workerFk: myWorker.id, + dmsTypeFk: args.dmsTypeId, + companyFk: args.companyId, + warehouseFk: args.warehouseId, + reference: args.reference, + description: args.description, + contentType: file.type, + hasFile: args.hasFile + }, myOptions); + + let fileName = file.name; + const extension = storageConnector.getFileExtension(fileName); + fileName = `${newDms.id}.${extension}`; + + return newDms.updateAttribute('file', fileName, myOptions); + } + + + /** + * Returns a container instance + * If doesn't exists creates a new one + * + * @param {String} name Container name + * @return {Object} Container instance + */ + async function getContainer(name) { + const models = Self.app.models; + let container; + try { + container = await models.Container.getContainer(name); + } catch (err) { + if (err.code === 'ENOENT') { + container = await models.Container.createContainer({ + name: name + }); + } else throw err; + } + + return container; + } +}; diff --git a/back/methods/message/send.js b/back/methods/message/send.js new file mode 100644 index 000000000..c8849774b --- /dev/null +++ b/back/methods/message/send.js @@ -0,0 +1,48 @@ +module.exports = Self => { + Self.remoteMethodCtx('send', { + description: 'Send message to user', + accessType: 'WRITE', + accepts: [{ + arg: 'data', + type: 'object', + required: true, + description: 'recipientFk, message', + http: {source: 'body'} + }, { + arg: 'context', + type: 'object', + http: function(ctx) { + return ctx; + } + }], + returns: { + type: 'boolean', + root: true + }, + http: { + path: `/:recipient/send`, + verb: 'post' + } + }); + + Self.send = async(ctx, data, options) => { + const accessToken = ctx.options && ctx.options.accessToken || ctx.req && ctx.req.accessToken; + const userId = accessToken.userId; + const models = Self.app.models; + const sender = await models.Account.findById(userId, null, options); + const recipient = await models.Account.findById(data.recipientFk, null, options); + + await Self.create({ + sender: sender.name, + recipient: recipient.name, + message: data.message + }, options); + + return await models.MessageInbox.create({ + sender: sender.name, + recipient: recipient.name, + finalRecipient: recipient.name, + message: data.message + }, options); + }; +}; diff --git a/back/methods/message/specs/send.spec.js b/back/methods/message/specs/send.spec.js new file mode 100644 index 000000000..6749bd7cd --- /dev/null +++ b/back/methods/message/specs/send.spec.js @@ -0,0 +1,14 @@ +const app = require('vn-loopback/server/server'); + +describe('message send()', () => { + it('should return a response containing the same message in params', async() => { + let ctx = {req: {accessToken: {userId: 1}}}; + let params = { + recipientFk: 1, + message: 'I changed something' + }; + let response = await app.models.Message.send(ctx, params, {transaction: 'You'}); + + expect(response.message).toEqual(params.message); + }); +}); diff --git a/back/methods/user-config-view/getConfig.js b/back/methods/user-config-view/getConfig.js new file mode 100644 index 000000000..f61a54d8d --- /dev/null +++ b/back/methods/user-config-view/getConfig.js @@ -0,0 +1,32 @@ +module.exports = function(Self) { + Self.remoteMethodCtx('getConfig', { + description: 'returns the information from UserConfig model for the active user', + accepts: [ + { + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + }, { + arg: 'tableCode', + type: 'String', + description: `Code of the table you ask its configuration` + } + ], + returns: { + type: 'object', + root: true + }, + http: { + path: `/getConfig`, + verb: 'get' + } + }); + + Self.getConfig = async ctx => { + let userView = await Self.app.models.UserConfigView.findOne({ + where: {tableCode: ctx.args.tableCode, userFk: ctx.req.accessToken.userId} + }); + + return userView; + }; +}; diff --git a/back/methods/user-config-view/save.js b/back/methods/user-config-view/save.js new file mode 100644 index 000000000..da8a27083 --- /dev/null +++ b/back/methods/user-config-view/save.js @@ -0,0 +1,34 @@ +module.exports = function(Self) { + Self.remoteMethodCtx('save', { + description: 'returns the information from UserConfig model for the active user', + accepts: [{ + arg: 'config', + type: 'Object', + required: true, + description: `Code of the table you ask its configuration`, + http: {source: 'body'} + } + ], + returns: { + type: 'object', + root: true + }, + http: { + path: `/save`, + verb: 'post' + } + }); + + Self.save = async(ctx, config) => { + let userView = await Self.app.models.UserConfigView.findOne({ + where: {tableCode: config.tableCode, userFk: ctx.req.accessToken.userId} + }); + + if (userView) + return userView.updateAttributes(config); + + config.userFk = ctx.req.accessToken.userId; + + return await Self.app.models.UserConfigView.create(config); + }; +}; diff --git a/back/methods/user-config/getUserConfig.js b/back/methods/user-config/getUserConfig.js new file mode 100644 index 000000000..192d973c2 --- /dev/null +++ b/back/methods/user-config/getUserConfig.js @@ -0,0 +1,31 @@ +module.exports = function(Self) { + Self.remoteMethodCtx('getUserConfig', { + description: 'returns the information from UserConfig model for the active user', + accepts: [], + returns: { + type: 'object', + root: true + }, + http: { + path: `/getUserConfig`, + verb: 'get' + } + }); + + Self.getUserConfig = async ctx => { + let userConfig = await Self.app.models.UserConfig.findOne({ + where: {userFk: ctx.req.accessToken.userId} + }); + + if (!userConfig) { + let newConfig = { + warehouseFk: 1, + companyFk: 442, + userFk: ctx.req.accessToken.userId + }; + + userConfig = await Self.app.models.UserConfig.create(newConfig); + } + return userConfig; + }; +}; diff --git a/back/methods/user-config/setUserConfig.js b/back/methods/user-config/setUserConfig.js new file mode 100644 index 000000000..098ba9866 --- /dev/null +++ b/back/methods/user-config/setUserConfig.js @@ -0,0 +1,28 @@ +module.exports = function(Self) { + Self.remoteMethodCtx('setUserConfig', { + description: 'Change worker of tickets state', + accepts: [{ + arg: 'params', + type: 'object', + required: true, + description: 'warehouseFk, companyFk', + http: {source: 'body'} + }], + returns: { + arg: 'response', + type: 'object' + }, + http: { + path: `/setUserConfig`, + verb: 'post' + } + }); + + Self.setUserConfig = async(ctx, params) => { + let token = ctx.req.accessToken; + let currentUserId = token && token.userId; + params.userFk = currentUserId; + + return await Self.app.models.UserConfig.upsertWithWhere({userFk: currentUserId}, params); + }; +}; diff --git a/back/methods/user-config/specs/getUserConfig.spec.js b/back/methods/user-config/specs/getUserConfig.spec.js new file mode 100644 index 000000000..da3fc958f --- /dev/null +++ b/back/methods/user-config/specs/getUserConfig.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('userConfig getUserConfig()', () => { + it(`should return the configuration data of a given user`, async() => { + await app.models.UserConfig.getUserConfig({req: {accessToken: {userId: 9}}}) + .then(response => { + expect(response.warehouseFk).toEqual(1); + }); + }); +}); diff --git a/back/model-config.json b/back/model-config.json new file mode 100644 index 000000000..a770a200a --- /dev/null +++ b/back/model-config.json @@ -0,0 +1,74 @@ +{ + "Account": { + "dataSource": "vn" + }, + "Bank": { + "dataSource": "vn" + }, + "Country": { + "dataSource": "vn" + }, + "Company": { + "dataSource": "vn" + }, + "Container": { + "dataSource": "storage" + }, + "Chat": { + "dataSource": "vn" + }, + "ChatConfig": { + "dataSource": "vn" + }, + "Delivery": { + "dataSource": "vn" + }, + "Message": { + "dataSource": "vn" + }, + "MessageInbox": { + "dataSource": "vn" + }, + "Province": { + "dataSource": "vn" + }, + "UserConfig": { + "dataSource": "vn" + }, + "Warehouse": { + "dataSource": "vn" + }, + "Sip": { + "dataSource": "vn" + }, + "UserConfigView": { + "dataSource": "vn" + }, + "EmailUser": { + "dataSource": "vn" + }, + "Dms": { + "dataSource": "vn" + }, + "DmsType": { + "dataSource": "vn" + }, + "Town": { + "dataSource": "vn" + }, + "Postcode": { + "dataSource": "vn" + }, + "UserPhoneType": { + "dataSource": "vn" + }, + "UserPhone": { + "dataSource": "vn" + }, + "UserLog": { + "dataSource": "vn" + } +} + + + diff --git a/back/models/account.js b/back/models/account.js new file mode 100644 index 000000000..64b59e704 --- /dev/null +++ b/back/models/account.js @@ -0,0 +1,90 @@ +const md5 = require('md5'); + +module.exports = Self => { + require('../methods/account/login')(Self); + require('../methods/account/logout')(Self); + require('../methods/account/acl')(Self); + require('../methods/account/validate-token')(Self); + + // Validations + + Self.validatesUniquenessOf('name', { + message: `A client with that Web User name already exists` + }); + + Self.observe('before save', (ctx, next) => { + if (ctx.currentInstance && ctx.currentInstance.id && ctx.data && ctx.data.password) + ctx.data.password = md5(ctx.data.password); + + next(); + }); + + Self.remoteMethod('getCurrentUserData', { + description: 'Gets the current user data', + accepts: [ + { + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + } + ], + returns: { + type: 'Object', + root: true + }, + http: { + verb: 'GET', + path: '/getCurrentUserData' + } + }); + + Self.getCurrentUserData = async function(ctx) { + let userId = ctx.req.accessToken.userId; + + let account = await Self.findById(userId, { + fields: ['id', 'name', 'nickname'] + }); + + let worker = await Self.app.models.Worker.findOne({ + fields: ['id'], + where: {userFk: userId} + }); + + return Object.assign(account, {workerId: worker.id}); + }; + + /** + * Checks if user has a role. + * + * @param {Integer} userId The user id + * @param {String} name The role name + * @param {Object} options Options + * @return {Boolean} %true if user has the role, %false otherwise + */ + Self.hasRole = async function(userId, name, options) { + let roles = await Self.getRoles(userId, options); + return roles.some(role => role == name); + }; + + /** + * Get all user roles. + * + * @param {Integer} userId The user id + * @param {Object} options Options + * @return {Object} User role list + */ + Self.getRoles = async(userId, options) => { + let result = await Self.rawSql( + `SELECT r.name + FROM account.user u + JOIN account.roleRole rr ON rr.role = u.role + JOIN account.role r ON r.id = rr.inheritsFrom + WHERE u.id = ?`, [userId], options); + + let roles = []; + for (role of result) + roles.push(role.name); + + return roles; + }; +}; diff --git a/back/models/account.json b/back/models/account.json new file mode 100644 index 000000000..7186621b4 --- /dev/null +++ b/back/models/account.json @@ -0,0 +1,84 @@ +{ + "name": "Account", + "base": "VnModel", + "options": { + "mysql": { + "table": "account.user" + } + }, + "properties": { + "id": { + "type": "number", + "required": true + }, + "name": { + "type": "string", + "required": true + }, + "roleFk": { + "type": "number", + "mysql": { + "columnName": "role" + } + }, + "nickname": { + "type": "string" + }, + "password": { + "type": "string", + "required": true + }, + "active": { + "type": "boolean" + }, + "email": { + "type": "string" + }, + "created": { + "type": "date" + }, + "updated": { + "type": "date" + } + }, + "relations": { + "role": { + "type": "belongsTo", + "model": "Role", + "foreignKey": "roleFk" + }, + "emailUser": { + "type": "hasOne", + "model": "EmailUser", + "foreignKey": "userFk" + }, + "worker": { + "type": "hasOne", + "model": "Worker", + "foreignKey": "userFk" + } + }, + "acls": [ + { + "property": "login", + "accessType": "EXECUTE", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }, + { + "property": "logout", + "accessType": "EXECUTE", + "principalType": "ROLE", + "principalId": "$authenticated", + "permission": "ALLOW" + }, + { + "property": "validateToken", + "accessType": "EXECUTE", + "principalType": "ROLE", + "principalId": "$authenticated", + "permission": "ALLOW" + } + ] +} diff --git a/back/models/bank.json b/back/models/bank.json new file mode 100644 index 000000000..119ea9743 --- /dev/null +++ b/back/models/bank.json @@ -0,0 +1,40 @@ +{ + "name": "Bank", + "base": "VnModel", + "options": { + "mysql": { + "table": "bank" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "bank": { + "type": "string", + "required": true + }, + "account": { + "type": "string", + "required": true + }, + "cash": { + "type": "string", + "required": true + }, + "entityFk": { + "type": "string", + "required": true + }, + "isActive": { + "type": "string", + "required": true + }, + "currencyFk": { + "type": "string", + "required": true + } + } + } \ No newline at end of file diff --git a/back/models/chat-config.json b/back/models/chat-config.json new file mode 100644 index 000000000..12cd021cb --- /dev/null +++ b/back/models/chat-config.json @@ -0,0 +1,32 @@ +{ + "name": "ChatConfig", + "description": "Chat API config", + "base": "VnModel", + "options": { + "mysql": { + "table": "chatConfig" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "uri": { + "type": "String" + }, + "user": { + "type": "String" + }, + "password": { + "type": "String" + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} \ No newline at end of file diff --git a/back/models/chat.js b/back/models/chat.js new file mode 100644 index 000000000..8086c6d3d --- /dev/null +++ b/back/models/chat.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/chat/sendMessage')(Self); +}; diff --git a/back/models/chat.json b/back/models/chat.json new file mode 100644 index 000000000..697d8c181 --- /dev/null +++ b/back/models/chat.json @@ -0,0 +1,12 @@ +{ + "name": "Chat", + "base": "VnModel", + "acls": [{ + "property": "validations", + "accessType": "EXECUTE", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} + \ No newline at end of file diff --git a/back/models/company.json b/back/models/company.json new file mode 100644 index 000000000..eb349477b --- /dev/null +++ b/back/models/company.json @@ -0,0 +1,29 @@ +{ + "name": "Company", + "description": "Companies", + "base": "VnModel", + "options": { + "mysql": { + "table": "company" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "code": { + "type": "String" + }, + "expired": { + "type": "date" + } + }, + + "scope": { + "where" :{ + "expired": null + } + } +} \ No newline at end of file diff --git a/back/models/container.json b/back/models/container.json new file mode 100644 index 000000000..eca4c30c7 --- /dev/null +++ b/back/models/container.json @@ -0,0 +1,13 @@ +{ + "name": "Container", + "base": "VnModel", + "idInjection": true, + "options": { + "validateUpsert": true + }, + "properties": {}, + "validations": [], + "relations": {}, + "acls": [], + "methods": [] + } \ No newline at end of file diff --git a/back/models/country.json b/back/models/country.json new file mode 100644 index 000000000..bf8486b4a --- /dev/null +++ b/back/models/country.json @@ -0,0 +1,39 @@ +{ + "name": "Country", + "description": "Worldwide countries", + "base": "VnModel", + "options": { + "mysql": { + "table": "country" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "country": { + "type": "string", + "required": true + }, + "code": { + "type": "string" + } + }, + "relations": { + "currency": { + "type": "belongsTo", + "model": "Currency", + "foreignKey": "currencyFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/services/route/common/models/delivery.json b/back/models/delivery.json similarity index 100% rename from services/route/common/models/delivery.json rename to back/models/delivery.json diff --git a/back/models/dms.js b/back/models/dms.js new file mode 100644 index 000000000..9a06928db --- /dev/null +++ b/back/models/dms.js @@ -0,0 +1,6 @@ +module.exports = Self => { + require('../methods/dms/downloadFile')(Self); + require('../methods/dms/uploadFile')(Self); + require('../methods/dms/removeFile')(Self); + require('../methods/dms/updateFile')(Self); +}; diff --git a/back/models/dms.json b/back/models/dms.json new file mode 100644 index 000000000..bf6e44311 --- /dev/null +++ b/back/models/dms.json @@ -0,0 +1,61 @@ + +{ + "name": "Dms", + "description": "Documental Managment system", + "base": "VnModel", + "options": { + "mysql": { + "table": "dms" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "file": { + "type": "string" + }, + "contentType": { + "type": "string" + }, + "reference": { + "type": "string" + }, + "description": { + "type": "string" + }, + "hardCopyNumber": { + "type": "Number" + }, + "hasFile": { + "type": "boolean" + }, + "created": { + "type": "Date" + } + }, + "relations": { + "dmsType": { + "type": "belongsTo", + "model": "DmsType", + "foreignKey": "dmsTypeFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "warehouse": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseFk" + }, + "company": { + "type": "belongsTo", + "model": "Company", + "foreignKey": "companyFk" + } + } +} \ No newline at end of file diff --git a/back/models/dmsType.js b/back/models/dmsType.js new file mode 100644 index 000000000..267c905e9 --- /dev/null +++ b/back/models/dmsType.js @@ -0,0 +1,65 @@ +module.exports = Self => { + /** + * Checks if current user has + * read privileges over a dms + * + * @param {Object} ctx - Request context + * @param {Interger} id - DmsType id + * @param {Object} options - Query options + * @return {Boolean} True for user with read privileges + */ + Self.hasReadRole = async(ctx, id, options) => { + const models = Self.app.models; + const dmsType = await models.DmsType.findById(id, { + include: { + relation: 'readRole' + } + }, options); + + return await hasRole(ctx, dmsType, options); + }; + + /** + * Checks if current user has + * write privileges over a dms + * + * @param {Object} ctx - Request context + * @param {Interger} id - DmsType id + * @param {Object} options - Query options + * @return {Boolean} True for user with write privileges + */ + Self.hasWriteRole = async(ctx, id, options) => { + const models = Self.app.models; + const dmsType = await models.DmsType.findById(id, { + include: { + relation: 'writeRole' + } + }, options); + + return await hasRole(ctx, dmsType, options); + }; + + /** + * Checks if current user has + * read or write privileges + * @param {Object} ctx - Context + * @param {Object} dmsType - Dms type [read/write] + * @param {Object} options - Query options + */ + async function hasRole(ctx, dmsType, options) { + const models = Self.app.models; + const myUserId = ctx.req.accessToken.userId; + + const readRole = dmsType.readRole() && dmsType.readRole().name; + const writeRole = dmsType.writeRole() && dmsType.writeRole().name; + const requiredRole = readRole || writeRole; + + const hasRequiredRole = await models.Account.hasRole(myUserId, requiredRole, options); + const isRoot = await models.Account.hasRole(myUserId, 'root', options); + + if (isRoot || hasRequiredRole) + return true; + + return false; + } +}; diff --git a/back/models/dmsType.json b/back/models/dmsType.json new file mode 100644 index 000000000..b51c810ac --- /dev/null +++ b/back/models/dmsType.json @@ -0,0 +1,47 @@ +{ + "name": "DmsType", + "description": "Documental Managment system types", + "base": "VnModel", + "options": { + "mysql": { + "table": "dmsType" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "name": { + "type": "string", + "required": true + }, + "path": { + "type": "string", + "required": true + }, + "code": { + "type": "string", + "required": true + } + }, + "relations": { + "readRole": { + "type": "belongsTo", + "model": "Role", + "foreignKey": "readRoleFk" + }, + "writeRole": { + "type": "belongsTo", + "model": "Role", + "foreignKey": "writeRoleFk" + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} \ No newline at end of file diff --git a/back/models/emailUser.json b/back/models/emailUser.json new file mode 100644 index 000000000..d612d5d29 --- /dev/null +++ b/back/models/emailUser.json @@ -0,0 +1,27 @@ +{ + "name": "EmailUser", + "base": "VnModel", + "options": { + "mysql": { + "table": "account.emailUser" + } + }, + "properties": { + "userFk": { + "id": true, + "type": "Number", + "required": true + }, + "email": { + "type": "string", + "required": true + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + } + } +} diff --git a/back/models/message-inbox.json b/back/models/message-inbox.json new file mode 100644 index 000000000..238f3e590 --- /dev/null +++ b/back/models/message-inbox.json @@ -0,0 +1,43 @@ +{ + "name": "MessageInbox", + "base": "VnModel", + "options": { + "mysql": { + "table": "messageInbox" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "sender": { + "type": "String", + "required": true + }, + "recipient": { + "type": "String", + "required": true + }, + "finalRecipient": { + "type": "String", + "required": true + }, + "message": { + "type": "String" + } + }, + "relations": { + "remitter": { + "type": "belongsTo", + "model": "User", + "foreignKey": "sender" + }, + "receptor": { + "type": "belongsTo", + "model": "User", + "foreignKey": "recipient" + } + } +} \ No newline at end of file diff --git a/back/models/message.js b/back/models/message.js new file mode 100644 index 000000000..6a53476f9 --- /dev/null +++ b/back/models/message.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/message/send')(Self); +}; diff --git a/back/models/message.json b/back/models/message.json new file mode 100644 index 000000000..2a855c907 --- /dev/null +++ b/back/models/message.json @@ -0,0 +1,39 @@ +{ + "name": "Message", + "base": "VnModel", + "options": { + "mysql": { + "table": "message" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "sender": { + "type": "String", + "required": true + }, + "recipient": { + "type": "String", + "required": true + }, + "message": { + "type": "String" + } + }, + "relations": { + "remitter": { + "type": "belongsTo", + "model": "User", + "foreignKey": "sender" + }, + "receptor": { + "type": "belongsTo", + "model": "User", + "foreignKey": "recipient" + } + } +} \ No newline at end of file diff --git a/back/models/postcode.js b/back/models/postcode.js new file mode 100644 index 000000000..b08fdaa40 --- /dev/null +++ b/back/models/postcode.js @@ -0,0 +1,9 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError(`This postcode already exists`); + return err; + }); +}; diff --git a/back/models/postcode.json b/back/models/postcode.json new file mode 100644 index 000000000..e28a77dc4 --- /dev/null +++ b/back/models/postcode.json @@ -0,0 +1,50 @@ +{ + "name": "Postcode", + "base": "VnModel", + "options": { + "mysql": { + "table": "postCode" + } + }, + "properties": { + "code": { + "id": true, + "type": "String" + } + }, + "relations": { + "town": { + "type": "belongsTo", + "model": "Town", + "foreignKey": "townFk" + }, + "geo": { + "type": "belongsTo", + "model": "ZoneGeo", + "foreignKey": "geoFk" + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }], + "scopes": { + "location": { + "include": { + "relation": "town", + "scope": { + "include": { + "relation": "province", + "scope": { + "include": { + "relation": "country" + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/services/loopback/common/models/province.json b/back/models/province.json similarity index 100% rename from services/loopback/common/models/province.json rename to back/models/province.json diff --git a/back/models/sip.js b/back/models/sip.js new file mode 100644 index 000000000..f6b007314 --- /dev/null +++ b/back/models/sip.js @@ -0,0 +1,5 @@ +module.exports = Self => { + Self.validatesUniquenessOf('extension', { + message: `The extension must be unique` + }); +}; diff --git a/back/models/sip.json b/back/models/sip.json new file mode 100644 index 000000000..7a7cb8605 --- /dev/null +++ b/back/models/sip.json @@ -0,0 +1,31 @@ +{ + "name": "Sip", + "base": "VnModel", + "options": { + "mysql": { + "table": "pbx.sip" + } + }, + "properties": { + "userFk": { + "type": "Number", + "id": true, + "description": "The user id", + "mysql": { + "columnName": "user_id" + } + }, + "extension": { + "type": "String", + "required": true + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "user_id" + } + } +} + \ No newline at end of file diff --git a/back/models/specs/account.spec.js b/back/models/specs/account.spec.js new file mode 100644 index 000000000..c52bc4378 --- /dev/null +++ b/back/models/specs/account.spec.js @@ -0,0 +1,15 @@ +const app = require('vn-loopback/server/server'); + +describe('loopback model Account', () => { + it('should return true if the user has the given role', async() => { + let result = await app.models.Account.hasRole(1, 'employee'); + + expect(result).toBeTruthy(); + }); + + it('should return false if the user doesnt have the given role', async() => { + let result = await app.models.Account.hasRole(1, 'administrator'); + + expect(result).toBeFalsy(); + }); +}); diff --git a/back/models/specs/company.spec.js b/back/models/specs/company.spec.js new file mode 100644 index 000000000..4adc6d96b --- /dev/null +++ b/back/models/specs/company.spec.js @@ -0,0 +1,9 @@ +const app = require('vn-loopback/server/server'); + +describe('loopback model Company', () => { + it('should check that the company FTH doesnt exists', async() => { + let result = await app.models.Company.findOne({where: {code: 'FTH'}}); + + expect(result).toBeFalsy(); + }); +}); diff --git a/back/models/town.json b/back/models/town.json new file mode 100644 index 000000000..41633fe0a --- /dev/null +++ b/back/models/town.json @@ -0,0 +1,57 @@ +{ + "name": "Town", + "base": "VnModel", + "options": { + "mysql": { + "table": "town" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "name": { + "type": "String" + } + }, + "relations": { + "province": { + "type": "belongsTo", + "model": "Province", + "foreignKey": "provinceFk" + }, + "postcodes": { + "type": "hasMany", + "model": "Postcode", + "foreignKey": "townFk" + }, + "geo": { + "type": "belongsTo", + "model": "ZoneGeo", + "foreignKey": "geoFk" + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }], + "scopes": { + "location": { + "include": [{ + "relation": "postcodes" + }, + { + "relation": "province", + "scope": { + "include": { + "relation": "country" + } + } + }], + "fields": ["id", "name", "provinceFk"] + } + } +} \ No newline at end of file diff --git a/back/models/user-config-view.js b/back/models/user-config-view.js new file mode 100644 index 000000000..4c43c1bab --- /dev/null +++ b/back/models/user-config-view.js @@ -0,0 +1,4 @@ +module.exports = Self => { + require('../methods/user-config-view/getConfig')(Self); + require('../methods/user-config-view/save')(Self); +}; diff --git a/back/models/user-config-view.json b/back/models/user-config-view.json new file mode 100644 index 000000000..8ffbc6f48 --- /dev/null +++ b/back/models/user-config-view.json @@ -0,0 +1,33 @@ +{ + "name": "UserConfigView", + "base": "VnModel", + "options": { + "mysql": { + "table": "salix.userConfigView" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "userFk": { + "type": "String", + "required": true + }, + "tableCode": { + "type": "String", + "required": true + }, + "configuration": { + "type": "Object" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + } + } +} diff --git a/back/models/user-config.js b/back/models/user-config.js new file mode 100644 index 000000000..19e1789cb --- /dev/null +++ b/back/models/user-config.js @@ -0,0 +1,4 @@ +module.exports = Self => { + require('../methods/user-config/setUserConfig')(Self); + require('../methods/user-config/getUserConfig')(Self); +}; diff --git a/back/models/user-config.json b/back/models/user-config.json new file mode 100644 index 000000000..336f26f63 --- /dev/null +++ b/back/models/user-config.json @@ -0,0 +1,45 @@ +{ + "name": "UserConfig", + "base": "VnModel", + "options": { + "mysql": { + "table": "userConfig" + } + }, + "properties": { + "userFk": { + "id": true, + "type": "Number", + "required": true + }, + "warehouseFk": { + "type": "Number" + }, + "companyFk": { + "type": "Number" + }, + "created": { + "type": "Date" + }, + "updated": { + "type": "Date" + } + }, + "relations": { + "warehouse": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseFk" + }, + "company": { + "type": "belongsTo", + "model": "Company", + "foreignKey": "companyFk" + }, + "account": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + } + } +} diff --git a/back/models/user-log.json b/back/models/user-log.json new file mode 100644 index 000000000..e3e3a6752 --- /dev/null +++ b/back/models/user-log.json @@ -0,0 +1,58 @@ +{ + "name": "UserLog", + "base": "VnModel", + "options": { + "mysql": { + "table": "userLog" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "forceId": false + }, + "originFk": { + "type": "Number", + "required": true + }, + "userFk": { + "type": "Number" + }, + "action": { + "type": "String", + "required": true + }, + "changedModel": { + "type": "String" + }, + "oldInstance": { + "type": "Object" + }, + "newInstance": { + "type": "Object" + }, + "creationDate": { + "type": "Date" + }, + "changedModelId": { + "type": "Number" + }, + "changedModelValue": { + "type": "String" + }, + "description": { + "type": "String" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + } + }, + "scope": { + "order": ["creationDate DESC", "id DESC"] + } +} diff --git a/back/models/user-phone-type.json b/back/models/user-phone-type.json new file mode 100644 index 000000000..479f02d6f --- /dev/null +++ b/back/models/user-phone-type.json @@ -0,0 +1,18 @@ +{ + "name": "UserPhoneType", + "base": "VnModel", + "options": { + "mysql": { + "table": "userPhoneType" + } + }, + "properties": { + "code": { + "id": true, + "type": "String" + }, + "description": { + "type": "String" + } + } +} diff --git a/back/models/user-phone.js b/back/models/user-phone.js new file mode 100644 index 000000000..6f6c20049 --- /dev/null +++ b/back/models/user-phone.js @@ -0,0 +1,9 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError(`This phone already exists`); + return err; + }); +}; diff --git a/back/models/user-phone.json b/back/models/user-phone.json new file mode 100644 index 000000000..f264ff28f --- /dev/null +++ b/back/models/user-phone.json @@ -0,0 +1,39 @@ +{ + "name": "UserPhone", + "base": "Loggable", + "log": { + "model":"UserLog", + "relation": "user" + }, + "options": { + "mysql": { + "table": "userPhone" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "phone": { + "type": "Number", + "required": true + }, + "typeFk": { + "type": "String", + "required": true + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + }, + "type": { + "type": "belongsTo", + "model": "UserPhoneType", + "foreignKey": "typeFk" + } + } +} diff --git a/back/models/user.json b/back/models/user.json new file mode 100644 index 000000000..0756d2093 --- /dev/null +++ b/back/models/user.json @@ -0,0 +1,19 @@ +{ + "name": "user", + "base": "User", + "options": { + "mysql": { + "table": "salix.user" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "forceId": false + }, + "username":{ + "type": "string" + } + } +} \ No newline at end of file diff --git a/back/models/warehouse.json b/back/models/warehouse.json new file mode 100644 index 000000000..fc6baacbc --- /dev/null +++ b/back/models/warehouse.json @@ -0,0 +1,38 @@ +{ + "name": "Warehouse", + "description": "Warehouses from where orders are sent", + "base": "VnModel", + "options": { + "mysql": { + "table": "warehouse" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "forceId": false + }, + "name": { + "type": "String" + }, + "isInventory": { + "type": "Number" + }, + "isManaged":{ + "type": "boolean" + }, + "hasStowaway":{ + "type": "boolean" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ], + "scope" : {"where": {"isForTicket": {"neq": 0}}} +} diff --git a/back/process.yml b/back/process.yml new file mode 100644 index 000000000..41a2fafff --- /dev/null +++ b/back/process.yml @@ -0,0 +1,6 @@ +apps: + - script: ./loopback/server/server.js + name: salix-back + instances: 1 + max_restarts: 3 + restart_delay: 15000 diff --git a/back/tests.js b/back/tests.js new file mode 100644 index 000000000..c715c96bf --- /dev/null +++ b/back/tests.js @@ -0,0 +1,39 @@ +require('require-yaml'); + +process.on('warning', warning => { + console.log(warning.name); + console.log(warning.message); + console.log(warning.stack); +}); + +let verbose = false; + +if (process.argv[2] === '--v') + verbose = true; + +let Jasmine = require('jasmine'); +let jasmine = new Jasmine(); +let SpecReporter = require('jasmine-spec-reporter').SpecReporter; + +let serviceSpecs = [ + `${__dirname}/**/*[sS]pec.js`, + `${__dirname}/../loopback/**/*[sS]pec.js`, + `${__dirname}/../modules/*/back/**/*.[sS]pec.js` +]; + +jasmine.loadConfig({ + spec_dir: '.', + spec_files: serviceSpecs, + helpers: [] +}); + +jasmine.addReporter(new SpecReporter({ + spec: { + // displayStacktrace: 'summary', + displaySuccessful: verbose, + displayFailedSpec: true, + displaySpecDuration: true + } +})); + +jasmine.execute(); diff --git a/client/auth/index.js b/client/auth/index.js deleted file mode 100644 index 2bd8c57de..000000000 --- a/client/auth/index.js +++ /dev/null @@ -1 +0,0 @@ -export * from './src/auth'; diff --git a/client/auth/src/auth.js b/client/auth/src/auth.js deleted file mode 100644 index d15aa496a..000000000 --- a/client/auth/src/auth.js +++ /dev/null @@ -1,2 +0,0 @@ -import './module'; -import './login/login'; diff --git a/client/auth/src/login/login.html b/client/auth/src/login/login.html deleted file mode 100644 index 0f0bcec35..000000000 --- a/client/auth/src/login/login.html +++ /dev/null @@ -1,29 +0,0 @@ -
-
-
- -
- - - - - -
-
-
- -
diff --git a/client/auth/src/login/login.js b/client/auth/src/login/login.js deleted file mode 100644 index 47ab77baf..000000000 --- a/client/auth/src/login/login.js +++ /dev/null @@ -1,84 +0,0 @@ -import ngModule from '../module'; -import './style.scss'; - -/** - * A simple login form. - */ -export default class Controller { - constructor($element, $scope, $window, $http) { - this.$element = $element; - this.$ = $scope; - this.$window = $window; - this.$http = $http; - } - submit() { - if (!this.user) { - this.focusUser(); - this.showError('Please insert your user and password'); - return; - } - - this.loading = true; - let params = { - user: this.user, - password: this.password, - location: this.$window.location.href - }; - this.$http.post('/auth/login', params).then( - json => this.onLoginOk(json), - json => this.onLoginErr(json) - ); - } - onLoginOk(json) { - this.loading = false; - let data = json.data; - let params = { - token: data.token, - continue: data.continue - }; - this.$window.location = `${data.loginUrl}?${this.encodeUri(params)}`; - } - encodeUri(object) { - let uri = ''; - for (var key in object) - if (object[key]) { - if (uri.length > 0) - uri += '&'; - uri += encodeURIComponent(key) + '=' + encodeURIComponent(object[key]); - } - return uri; - } - onLoginErr(json) { - this.loading = false; - this.password = ''; - - let message; - - switch (json.status) { - case 401: - message = 'Invalid credentials'; - break; - case -1: - message = 'Can\'t contact with server'; - break; - default: - message = 'Something went wrong'; - } - - this.showError(message); - this.focusUser(); - } - focusUser() { - this.$.userField.select(); - this.$.userField.focus(); - } - showError(message) { - this.$.snackbar.showError({message: message}); - } -} -Controller.$inject = ['$element', '$scope', '$window', '$http']; - -ngModule.component('vnLogin', { - template: require('./login.html'), - controller: Controller -}); diff --git a/client/auth/src/login/logo.svg b/client/auth/src/login/logo.svg deleted file mode 100644 index a6eae7841..000000000 --- a/client/auth/src/login/logo.svg +++ /dev/null @@ -1,119 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/client/auth/src/login/style.scss b/client/auth/src/login/style.scss deleted file mode 100644 index d152c84ba..000000000 --- a/client/auth/src/login/style.scss +++ /dev/null @@ -1,50 +0,0 @@ - -vn-login > div { - position: absolute; - height: 100%; - width: 100%; - margin: 0; - padding: 0; - color: #333; - font-size: 1.1em; - font-weight: normal; - background-color: #3c393b; - - .box-wrapper { - position: relative; - max-width: 19em; - margin: auto; - height: inherit; - } - - .box { - box-sizing: border-box; - position: absolute; - top: 50%; - width: 100%; - margin-top: -13.5em; - padding: 3em; - background-color: white; - box-shadow: 0 0 1em 0 rgba(1,1,1,.6); - border-radius: .5em; - } - - img { - width: 100%; - padding-bottom: 1em; - } - - .footer { - margin-top: 1em; - text-align: center; - position: relative; - } - - .spinner-wrapper { - position: absolute; - width: 0; - top: .3em; - right: 4em; - overflow: visible; - } -} diff --git a/client/auth/src/module.js b/client/auth/src/module.js deleted file mode 100644 index 8339bc998..000000000 --- a/client/auth/src/module.js +++ /dev/null @@ -1,14 +0,0 @@ -import {ng} from 'vendor'; -import 'core'; - -let ngModule = ng.module('vnAuth', ['vnCore']); -export default ngModule; - -config.$inject = ['$translatePartialLoaderProvider', '$httpProvider']; -export function config($translatePartialLoaderProvider, $httpProvider) { - $translatePartialLoaderProvider.addPart('auth'); - - $httpProvider.defaults.useXDomain = true; - delete $httpProvider.defaults.headers.common['X-Requested-With']; -} -ngModule.config(config); diff --git a/client/client/index.js b/client/client/index.js deleted file mode 100644 index cf9881312..000000000 --- a/client/client/index.js +++ /dev/null @@ -1 +0,0 @@ -export * from './src/client'; diff --git a/client/client/routes.json b/client/client/routes.json deleted file mode 100644 index c466ad7f9..000000000 --- a/client/client/routes.json +++ /dev/null @@ -1,225 +0,0 @@ -{ - "module": "client", - "name": "Clients", - "icon": "person", - "validations" : true, - "routes": [ - { - "url": "/clients?q", - "state": "clients", - "component": "vn-client-index", - "acl": ["employee"] - }, - { - "url": "/create", - "state": "create", - "component": "vn-client-create" - }, - { - "url": "/clients/:id", - "state": "clientCard", - "abstract": true, - "component": "vn-client-card" - }, - { - "url": "/basic-data", - "state": "clientCard.basicData", - "component": "vn-client-basic-data", - "params": { - "client": "$ctrl.client" - }, - "menu": { - "description": "Basic data", - "icon": "settings" - } - }, - { - "url": "/fiscal-data", - "state": "clientCard.fiscalData", - "component": "vn-client-fiscal-data", - "params": { - "client": "$ctrl.client" - }, - "menu": { - "description": "Fiscal data", - "icon": "account_balance" - } - }, - { - "url": "/billing-data", - "state": "clientCard.billingData", - "component": "vn-client-billing-data", - "params": { - "client": "$ctrl.client" - }, - "menu": { - "description": "Pay method", - "icon": "icon-payment" - } - }, - { - "url": "/addresses", - "state": "clientCard.addresses", - "component": "ui-view", - "abstract": true - }, - { - "url": "/list", - "state": "clientCard.addresses.list", - "component": "vn-client-addresses", - "params": { - "client": "$ctrl.client" - }, - "menu": { - "description": "Addresses", - "icon": "local_shipping" - } - }, - { - "url": "/create", - "state": "clientCard.addresses.create", - "component": "vn-address-create" - }, - { - "url": "/:addressId/edit", - "state": "clientCard.addresses.edit", - "component": "vn-address-edit" - }, - { - "url": "/web-access", - "state": "clientCard.webAccess", - "component": "vn-client-web-access", - "params": { - "client": "$ctrl.client" - }, - "menu": { - "description": "Web access", - "icon": "cloud" - } - }, - { - "url": "/notes", - "state": "clientCard.notes", - "component": "ui-view", - "abstract": true - }, - { - "url": "/list", - "state": "clientCard.notes.list", - "component": "vn-client-notes", - "params": { - "client": "$ctrl.client" - }, - "menu": { - "description": "Notes", - "icon": "insert_drive_file" - } - }, - { - "url": "/create", - "state": "clientCard.notes.create", - "component": "vn-note-create" - }, - { - "url": "/credit", - "abstract": true, - "state": "clientCard.credit", - "component": "ui-view" - }, - { - "url": "/list", - "state": "clientCard.credit.list", - "component": "vn-client-credit-list", - "params": { - "client": "$ctrl.client" - }, - "menu": { - "description": "Credit", - "icon": "credit_card" - } - }, { - "url": "/create", - "state": "clientCard.credit.create", - "component": "vn-client-credit-create", - "params": { - "client": "$ctrl.client" - } - }, - { - "url": "/greuge", - "abstract": true, - "state": "clientCard.greuge", - "component": "ui-view" - }, - { - "url": "/list", - "state": "clientCard.greuge.list", - "component": "vn-client-greuge-list", - "params": { - "client": "$ctrl.client" - }, - "menu": { - "description": "Greuge", - "icon": "work" - } - }, - { - "url": "/create", - "state": "clientCard.greuge.create", - "component": "vn-client-greuge-create", - "params": { - "client": "$ctrl.client" - } - }, - { - "url": "/mandate", - "state": "clientCard.mandate", - "component": "vn-client-mandate", - "menu": { - "description": "Mandate", - "icon": "pan_tool" - } - }, - { - "url": "/invoices", - "state": "clientCard.invoices", - "component": "vn-client-invoices", - "menu": { - "description": "Invoices", - "icon": "icon-invoices" - } - }, - { - "url": "/recovery", - "abstract": true, - "state": "clientCard.recovery", - "component": "ui-view" - }, - { - "url": "/list", - "state": "clientCard.recovery.list", - "component": "vn-client-recovery-list", - "params": { - "client": "$ctrl.client" - }, - "menu": { - "description": "Recovery", - "icon": "icon-recovery" - } - }, { - "url": "/create", - "state": "clientCard.recovery.create", - "component": "vn-client-recovery-create", - "params": { - "client": "$ctrl.client" - } - }, { - "url": "/summary", - "state": "clientCard.summary", - "component": "vn-client-summary", - "params": { - "client": "$ctrl.client" - } - } - ] -} diff --git a/client/client/src/address-create/address-create.html b/client/client/src/address-create/address-create.html deleted file mode 100644 index 514457fb6..000000000 --- a/client/client/src/address-create/address-create.html +++ /dev/null @@ -1,45 +0,0 @@ - - -
- - Address - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/client/client/src/address-create/address-create.js b/client/client/src/address-create/address-create.js deleted file mode 100644 index a8326b3c7..000000000 --- a/client/client/src/address-create/address-create.js +++ /dev/null @@ -1,16 +0,0 @@ -import ngModule from '../module'; - -export default class Controller { - constructor($state) { - this.address = { - clientFk: parseInt($state.params.id), - isActive: true - }; - } -} -Controller.$inject = ['$state']; - -ngModule.component('vnAddressCreate', { - template: require('./address-create.html'), - controller: Controller -}); diff --git a/client/client/src/address-create/address-create.spec.js b/client/client/src/address-create/address-create.spec.js deleted file mode 100644 index 4d17111ef..000000000 --- a/client/client/src/address-create/address-create.spec.js +++ /dev/null @@ -1,25 +0,0 @@ -import './address-create.js'; - -describe('Client', () => { - describe('Component vnAddressCreate', () => { - let controller; - let $componentController; - let $state; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, _$state_) => { - $componentController = _$componentController_; - $state = _$state_; - $state.params.id = '1234'; - controller = $componentController('vnAddressCreate', {$state}); - })); - - it('should define and set address property', () => { - expect(controller.address.clientFk).toBe(1234); - expect(controller.address.isActive).toBe(true); - }); - }); -}); diff --git a/client/client/src/address-edit/address-edit.html b/client/client/src/address-edit/address-edit.html deleted file mode 100644 index 84f00a579..000000000 --- a/client/client/src/address-edit/address-edit.html +++ /dev/null @@ -1,100 +0,0 @@ - - - - -
- - Address - - - - - - - - - - - - - - - - - - - - - - - Notes - - - - {{$parent.$parent.item.description}} - - - - - - - - - - - - - - - - - -
diff --git a/client/client/src/address-edit/address-edit.js b/client/client/src/address-edit/address-edit.js deleted file mode 100644 index a715dc8a4..000000000 --- a/client/client/src/address-edit/address-edit.js +++ /dev/null @@ -1,134 +0,0 @@ -import ngModule from '../module'; - -export default class Controller { - constructor($state, $scope, $http, $q, $translate, vnApp) { - this.$state = $state; - this.$scope = $scope; - this.$http = $http; - this.$q = $q; - this.$translate = $translate; - this.vnApp = vnApp; - - this.address = { - id: parseInt($state.params.addressId) - }; - this.observations = []; - this.observationsOld = {}; - this.observationsRemoved = []; - } - - _setDirtyForm() { - if (this.$scope.form) { - this.$scope.form.$setDirty(); - } - } - _unsetDirtyForm() { - if (this.$scope.form) { - this.$scope.form.$setPristine(); - } - } - - addObservation() { - this.observations.push({observationTypeFk: null, addressFk: this.address.id, description: null}); - } - - removeObservation(index) { - let item = this.observations[index]; - if (item) { - this.observations.splice(index, 1); - if (item.id) { - this.observationsRemoved.push(item.id); - this._setDirtyForm(); - } - } - if (this.observations.length === 0 && Object.keys(this.observationsOld).length === 0) { - this._unsetDirtyForm(); - } - } - _submitObservations(objectObservations) { - return this.$http.post(`/client/api/AddressObservations/crudAddressObservations`, objectObservations); - } - - _observationsEquals(ob1, ob2) { - return ob1.id === ob2.id && ob1.observationTypeFk === ob2.observationTypeFk && ob1.description === ob2.description; - } - - submit() { - if (this.$scope.form.$invalid) { - return false; - } - - let canWatcherSubmit = this.$scope.watcher.dataChanged(); - let canObservationsSubmit; - let repeatedTypes = false; - let types = []; - let observationsObj = { - delete: this.observationsRemoved, - create: [], - update: [] - }; - - for (let i = 0; i < this.observations.length; i++) { - let observation = this.observations[i]; - let isNewObservation = observation.id === undefined; - - if (observation.observationTypeFk && types.indexOf(observation.observationTypeFk) !== -1) { - repeatedTypes = true; - break; - } - - if (observation.observationTypeFk) - types.push(observation.observationTypeFk); - - if (isNewObservation && observation.observationTypeFk && observation.description) { - observationsObj.create.push(observation); - } else if (!isNewObservation && !this._observationsEquals(this.observationsOld[observation.id], observation)) { - observationsObj.update.push(observation); - } - } - - canObservationsSubmit = observationsObj.update.length > 0 || observationsObj.create.length > 0 || observationsObj.delete.length > 0; - - if (repeatedTypes) { - this.vnApp.showMessage( - this.$translate.instant('The observation type must be unique') - ); - } else if (canWatcherSubmit && !canObservationsSubmit) { - this.$scope.watcher.submit().then(() => { - this.$state.go('clientCard.addresses.list', {id: this.$state.params.id}); - }); - } else if (!canWatcherSubmit && canObservationsSubmit) { - this._submitObservations(observationsObj).then(() => { - this.$state.go('clientCard.addresses.list', {id: this.$state.params.id}); - }); - } else if (canWatcherSubmit && canObservationsSubmit) { - this.$q.all([this.$scope.watcher.submit(), this._submitObservations(observationsObj)]).then(() => { - this.$state.go('clientCard.addresses.list', {id: this.$state.params.id}); - }); - } else { - this.vnApp.showMessage( - this.$translate.instant('No changes to save') - ); - } - this._unsetDirtyForm(); - } - - $onInit() { - let filter = { - where: {addressFk: this.address.id}, - include: {relation: 'observationType'} - }; - this.$http.get(`/client/api/AddressObservations?filter=${JSON.stringify(filter)}`).then(res => { - this.observations = res.data; - res.data.forEach(item => { - this.observationsOld[item.id] = Object.assign({}, item); - }); - }); - } -} -Controller.$inject = ['$state', '$scope', '$http', '$q', '$translate', 'vnApp']; - -ngModule.component('vnAddressEdit', { - template: require('./address-edit.html'), - controller: Controller -}); diff --git a/client/client/src/address-edit/address-edit.spec.js b/client/client/src/address-edit/address-edit.spec.js deleted file mode 100644 index 23499bd33..000000000 --- a/client/client/src/address-edit/address-edit.spec.js +++ /dev/null @@ -1,55 +0,0 @@ -import './address-edit.js'; - -describe('Client', () => { - describe('Component vnAddressEdit', () => { - let $componentController; - let $state; - let controller; - let $httpBackend; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, _$state_, _$httpBackend_) => { - $componentController = _$componentController_; - $state = _$state_; - $httpBackend = _$httpBackend_; - $state.params.addressId = '1'; - controller = $componentController('vnAddressEdit', {$state: $state}); - })); - - it('should define and set address property', () => { - expect(controller.address.id).toEqual(1); - }); - - describe('_observationsEquals', () => { - it('should return true if two observations are equals independent of control attributes', () => { - let ob1 = {id: 1, observationTypeFk: 1, description: 'Spiderman rocks', showAddIcon: true}; - let ob2 = {id: 1, observationTypeFk: 1, description: 'Spiderman rocks', showAddIcon: false}; - let equals = controller._observationsEquals(ob2, ob1); - - expect(equals).toBeTruthy(); - }); - - it('should return false if two observations are not equals independent of control attributes', () => { - let ob1 = {id: 1, observationTypeFk: 1, description: 'Spiderman rocks', showAddIcon: true}; - let ob2 = {id: 1, observationTypeFk: 1, description: 'Spiderman sucks', showAddIcon: true}; - let equals = controller._observationsEquals(ob2, ob1); - - expect(equals).toBeFalsy(); - }); - }); - - describe('$onInit()', () => { - it('should perform a GET query to receive the address observations', () => { - let filter = {where: {addressFk: 1}, include: {relation: 'observationType'}}; - let res = ['some notes']; - $httpBackend.when('GET', `/client/api/AddressObservations?filter=${JSON.stringify(filter)}`).respond(res); - $httpBackend.expectGET(`/client/api/AddressObservations?filter=${JSON.stringify(filter)}`); - controller.$onInit(); - $httpBackend.flush(); - }); - }); - }); -}); diff --git a/client/client/src/address-edit/locale/es.yml b/client/client/src/address-edit/locale/es.yml deleted file mode 100644 index aa9c23ef0..000000000 --- a/client/client/src/address-edit/locale/es.yml +++ /dev/null @@ -1,7 +0,0 @@ -Enabled: Activo -Is equalizated: Recargo de equivalencia -Observation type: Tipo de observación -Description: Descripción -The observation type must be unique: El tipo de observación ha de ser único -Add note: Añadir nota -Remove note: Quitar nota \ No newline at end of file diff --git a/client/client/src/addresses/addresses.html b/client/client/src/addresses/addresses.html deleted file mode 100644 index 2e5bb98c5..000000000 --- a/client/client/src/addresses/addresses.html +++ /dev/null @@ -1,47 +0,0 @@ - - - - Addresses - - - - - star - star_border - star_border - - -
{{::address.nickname}}
-
{{::address.street}}
-
{{::address.city}}, {{::address.province}}
-
{{::address.phone}}, {{::address.mobile}}
-
- - - {{::observation.observationType.description}}: - {{::observation.description}} - - - - - -
-
-
-
- - - -
diff --git a/client/client/src/addresses/addresses.js b/client/client/src/addresses/addresses.js deleted file mode 100644 index e42bad3fd..000000000 --- a/client/client/src/addresses/addresses.js +++ /dev/null @@ -1,22 +0,0 @@ -import ngModule from '../module'; - -class ClientAddresses { - constructor($http, $scope) { - this.$http = $http; - this.$scope = $scope; - } - setDefault(address) { - if (address.isActive) { - let params = {isDefaultAddress: true}; - this.$http.patch(`/client/api/Addresses/${address.id}`, params).then( - () => this.$scope.index.accept() - ); - } - } -} -ClientAddresses.$inject = ['$http', '$scope']; - -ngModule.component('vnClientAddresses', { - template: require('./addresses.html'), - controller: ClientAddresses -}); diff --git a/client/client/src/basic-data/basic-data.html b/client/client/src/basic-data/basic-data.html deleted file mode 100644 index 77865c4f6..000000000 --- a/client/client/src/basic-data/basic-data.html +++ /dev/null @@ -1,46 +0,0 @@ - - - -
- - Basic data - - - - - - - - - - - - - - - - - - - - -
diff --git a/client/client/src/basic-data/basic-data.js b/client/client/src/basic-data/basic-data.js deleted file mode 100644 index e7d877432..000000000 --- a/client/client/src/basic-data/basic-data.js +++ /dev/null @@ -1,8 +0,0 @@ -import ngModule from '../module'; - -ngModule.component('vnClientBasicData', { - template: require('./basic-data.html'), - bindings: { - client: '<' - } -}); diff --git a/client/client/src/basic-data/locale/es.yml b/client/client/src/basic-data/locale/es.yml deleted file mode 100644 index 34edb5986..000000000 --- a/client/client/src/basic-data/locale/es.yml +++ /dev/null @@ -1,14 +0,0 @@ -Comercial Name: Nombre comercial -Tax number: NIF/CIF -Social name: Razón social -Phone: Teléfono -Mobile: Móvil -Fax: Fax -Email: Correo electrónico -Salesperson: Comercial -Channel: Canal -You can save multiple emails: >- - Puede guardar varios correos electrónicos encadenándolos mediante comas - sin espacios, ejemplo: user@dominio.com, user2@dominio.com siendo el primer - correo electrónico el principal -Contact: Contacto \ No newline at end of file diff --git a/client/client/src/billing-data/billing-data.html b/client/client/src/billing-data/billing-data.html deleted file mode 100644 index 2a097179a..000000000 --- a/client/client/src/billing-data/billing-data.html +++ /dev/null @@ -1,64 +0,0 @@ - - - -
- - Pay method - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - \ No newline at end of file diff --git a/client/client/src/billing-data/billing-data.js b/client/client/src/billing-data/billing-data.js deleted file mode 100644 index 43595bc88..000000000 --- a/client/client/src/billing-data/billing-data.js +++ /dev/null @@ -1,57 +0,0 @@ -import ngModule from '../module'; - -export default class Controller { - constructor($scope, $http, vnApp, $translate) { - this.$ = $scope; - this.$http = $http; - this.vnApp = vnApp; - this.translate = $translate; - this.billData = {}; - this.copyData(); - } - $onChanges() { - this.copyData(); - } - copyData() { - if (this.client) { - this.billData.payMethodFk = this.client.payMethodFk; - this.billData.iban = this.client.iban; - this.billData.dueDay = this.client.dueDay; - } - } - submit() { - return this.$.watcher.submit().then( - () => this.checkPaymentChanges()); - } - checkPaymentChanges() { - let equals = true; - Object.keys(this.billData).forEach( - val => { - if (this.billData[val] !== this.client[val]) { - this.billData[val] = this.client[val]; - equals = false; - } - } - ); - - if (!equals) { - this.$.sendMail.show(); - } - } - returnDialog(response) { - if (response === 'ACCEPT') { - this.$http.post(`/mailer/notification/payment-update/${this.client.id}`).then( - () => this.vnApp.showMessage(this.translate.instant('Notification sent!')) - ); - } - } -} -Controller.$inject = ['$scope', '$http', 'vnApp', '$translate']; - -ngModule.component('vnClientBillingData', { - template: require('./billing-data.html'), - controller: Controller, - bindings: { - client: '<' - } -}); diff --git a/client/client/src/billing-data/billing-data.spec.js b/client/client/src/billing-data/billing-data.spec.js deleted file mode 100644 index 9cdf03cac..000000000 --- a/client/client/src/billing-data/billing-data.spec.js +++ /dev/null @@ -1,80 +0,0 @@ -import './billing-data.js'; - -describe('Client', () => { - describe('Component vnClientBillingData', () => { - let $componentController; - let $httpBackend; - let $scope; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_) => { - $componentController = _$componentController_; - $httpBackend = _$httpBackend_; - $httpBackend.when('GET', /\/locale\/\w+\/[a-z]{2}\.json/).respond({}); - $scope = $rootScope.$new(); - let submit = jasmine.createSpy('submit').and.returnValue(Promise.resolve()); - $scope.watcher = {submit}; - let show = jasmine.createSpy('show'); - $scope.sendMail = {show}; - controller = $componentController('vnClientBillingData', {$scope: $scope}); - })); - - describe('copyData()', () => { - it(`should define billData using client's data`, () => { - controller.client = { - dueDay: 0, - iban: null, - payMethodFk: 1 - }; - controller.billData = {}; - controller.copyData(controller.client); - - expect(controller.billData).toEqual(controller.client); - }); - }); - - describe('submit()', () => { - it(`should call submit() on the watcher then receive a callback`, done => { - spyOn(controller, 'checkPaymentChanges'); - controller.submit() - .then(() => { - expect(controller.$.watcher.submit).toHaveBeenCalledWith(); - expect(controller.checkPaymentChanges).toHaveBeenCalledWith(); - done(); - }); - }); - }); - - describe('checkPaymentChanges()', () => { - it(`should not call sendMail.show() if there are no changes on billing data`, () => { - controller.billData = {marvelHero: 'Silver Surfer'}; - controller.client = {marvelHero: 'Silver Surfer'}; - controller.checkPaymentChanges(); - - expect(controller.$.sendMail.show).not.toHaveBeenCalled(); - }); - - it(`should call sendMail.show() if there are changes on billing data object`, () => { - controller.billData = {marvelHero: 'Silver Surfer'}; - controller.client = {marvelHero: 'Spider-Man'}; - controller.checkPaymentChanges(); - - expect(controller.$.sendMail.show).toHaveBeenCalledWith(); - }); - }); - - describe('returnDialog()', () => { - it('should request to send notification email', () => { - controller.client = {id: '123'}; - $httpBackend.when('POST', `/mailer/notification/payment-update/${controller.client.id}`).respond('done'); - $httpBackend.expectPOST(`/mailer/notification/payment-update/${controller.client.id}`); - controller.returnDialog('ACCEPT'); - $httpBackend.flush(); - }); - }); - }); -}); diff --git a/client/client/src/billing-data/locale/en.yml b/client/client/src/billing-data/locale/en.yml deleted file mode 100644 index 20f5272b6..000000000 --- a/client/client/src/billing-data/locale/en.yml +++ /dev/null @@ -1,15 +0,0 @@ -Changed terms: Payment terms have changed -Notify customer?: Do you want to notify customer? -No: No -Yes, notify: Yes, notify -Notification sent!: Notification sent! -Notification error: Error while sending notification -Yes, propagate: Yes, propagate -Equivalent tax spreaded: Equivalent tax spreaded -Invoice by address: Invoice by address -Equalization tax: Equalization tax -Due day: Due day -Received core VNH: VNH core received -Received core VNL: VNL core received -Received B2B VNL: VNL B2B received -Save: Save \ No newline at end of file diff --git a/client/client/src/billing-data/locale/es.yml b/client/client/src/billing-data/locale/es.yml deleted file mode 100644 index ed4725ac2..000000000 --- a/client/client/src/billing-data/locale/es.yml +++ /dev/null @@ -1,15 +0,0 @@ -Changed terms: Has modificado las condiciones de pago -Notify customer?: ¿Deseas notificar al cliente de dichos cambios? -No: No -Yes, notify: Sí, notificar -Notification sent!: ¡Notificación enviada! -Notification error: Error al enviar notificación -Yes, propagate: Si, propagar -Equivalent tax spreaded: Recargo de equivalencia propagado -Invoice by address: Facturar por consignatario -Equalization tax: Recargo de equivalencia -Due day: Vencimiento -Received core VNH: Recibido core VNH -Received core VNL: Recibido core VNL -Received B2B VNL: Recibido B2B VNL -Save: Guardar \ No newline at end of file diff --git a/client/client/src/card/card.html b/client/client/src/card/card.html deleted file mode 100644 index 9894bcbb5..000000000 --- a/client/client/src/card/card.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - diff --git a/client/client/src/card/card.js b/client/client/src/card/card.js deleted file mode 100644 index 9660ce3ce..000000000 --- a/client/client/src/card/card.js +++ /dev/null @@ -1,12 +0,0 @@ -import ngModule from '../module'; - -export default class Controller { - constructor() { - this.client = null; - } -} - -ngModule.component('vnClientCard', { - template: require('./card.html'), - controller: Controller -}); diff --git a/client/client/src/card/card.spec.js b/client/client/src/card/card.spec.js deleted file mode 100644 index f29d318b4..000000000 --- a/client/client/src/card/card.spec.js +++ /dev/null @@ -1,24 +0,0 @@ -import './card.js'; - -describe('Client', () => { - describe('Component vnClientCard', () => { - let $componentController; - let $scope; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope) => { - $componentController = _$componentController_; - $scope = $rootScope; - controller = $componentController('vnClientCard', {$scope: $scope}); - })); - - it('should define and set client property to null in the module instance', () => { - expect(controller.client).toBeDefined(); - expect(controller.client).toBe(null); - }); - }); -}); diff --git a/client/client/src/client.js b/client/client/src/client.js deleted file mode 100644 index 935a33b43..000000000 --- a/client/client/src/client.js +++ /dev/null @@ -1,25 +0,0 @@ -export * from './module'; - -import './index/index'; -import './card/card'; -import './create/create'; -import './basic-data/basic-data'; -import './fiscal-data/fiscal-data'; -import './billing-data/billing-data'; -import './descriptor/descriptor'; -import './search-panel/search-panel'; -import './addresses/addresses'; -import './address-create/address-create'; -import './address-edit/address-edit'; -import './notes/notes'; -import './note-create/note-create'; -import './web-access/web-access'; -import './credit-list/credit-list'; -import './credit-create/credit-create'; -import './greuge-list/greuge-list'; -import './greuge-create/greuge-create'; -import './mandate/mandate'; -import './invoices/invoices'; -import './summary/client-summary'; -import './recovery-list/recovery-list'; -import './recovery-create/recovery-create'; diff --git a/client/client/src/create/create.html b/client/client/src/create/create.html deleted file mode 100644 index adb4f08d2..000000000 --- a/client/client/src/create/create.html +++ /dev/null @@ -1,37 +0,0 @@ - - - -
-
- - Create client - - - - - - - - - - - - - - - - - -
-
diff --git a/client/client/src/create/create.js b/client/client/src/create/create.js deleted file mode 100644 index 601bab71b..000000000 --- a/client/client/src/create/create.js +++ /dev/null @@ -1,22 +0,0 @@ -import ngModule from '../module'; - -export default class Controller { - constructor($scope, $state) { - this.$ = $scope; - this.$state = $state; - this.client = { - active: true - }; - } - onSubmit() { - this.$.watcher.submit().then( - json => this.$state.go('clientCard.basicData', {id: json.data.id}) - ); - } -} -Controller.$inject = ['$scope', '$state']; - -ngModule.component('vnClientCreate', { - template: require('./create.html'), - controller: Controller -}); diff --git a/client/client/src/create/create.spec.js b/client/client/src/create/create.spec.js deleted file mode 100644 index 491f273bb..000000000 --- a/client/client/src/create/create.spec.js +++ /dev/null @@ -1,45 +0,0 @@ -import './create.js'; - -describe('Client', () => { - describe('Component vnClientCreate', () => { - let $componentController; - let $scope; - let $state; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$state_) => { - $componentController = _$componentController_; - $scope = $rootScope.$new(); - $state = _$state_; - $scope.watcher = { - submit: () => { - return { - then: callback => { - callback({data: {id: '1234'}}); - } - }; - } - }; - controller = $componentController('vnClientCreate', {$scope: $scope}); - })); - - it('should define and set scope, state and client properties', () => { - expect(controller.$).toBe($scope); - expect(controller.$state).toBe($state); - expect(controller.client.active).toBe(true); - }); - - describe('onSubmit()', () => { - it(`should call submit() on the watcher then expect a callback`, () => { - spyOn($state, 'go'); - controller.onSubmit(); - - expect(controller.$state.go).toHaveBeenCalledWith('clientCard.basicData', {id: '1234'}); - }); - }); - }); -}); diff --git a/client/client/src/create/locale/es.yml b/client/client/src/create/locale/es.yml deleted file mode 100644 index e48239855..000000000 --- a/client/client/src/create/locale/es.yml +++ /dev/null @@ -1,11 +0,0 @@ -Name: Nombre -Tax number: NIF/CIF -Business name: Razón social -Web user: Usuario Web -Email: Correo electrónico -Create and edit: Crear y editar -Create: Crear -You can save multiple emails: >- - Puede guardar varios correos electrónicos encadenándolos mediante comas - sin espacios, ejemplo: user@dominio.com, user2@dominio.com siendo el primer - correo electrónico el principal \ No newline at end of file diff --git a/client/client/src/credit-create/credit-create.html b/client/client/src/credit-create/credit-create.html deleted file mode 100644 index 04fd7ab13..000000000 --- a/client/client/src/credit-create/credit-create.html +++ /dev/null @@ -1,18 +0,0 @@ - - - -
- - Add credit - - - - - - - -
diff --git a/client/client/src/credit-create/credit-create.js b/client/client/src/credit-create/credit-create.js deleted file mode 100644 index 2d0bccf56..000000000 --- a/client/client/src/credit-create/credit-create.js +++ /dev/null @@ -1,8 +0,0 @@ -import ngModule from '../module'; - -ngModule.component('vnClientCreditCreate', { - template: require('./credit-create.html'), - bindings: { - client: '<' - } -}); diff --git a/client/client/src/credit-create/locale/es.yml b/client/client/src/credit-create/locale/es.yml deleted file mode 100644 index e6151420c..000000000 --- a/client/client/src/credit-create/locale/es.yml +++ /dev/null @@ -1 +0,0 @@ -Add credit: Añadir crédito \ No newline at end of file diff --git a/client/client/src/credit-list/credit-list.html b/client/client/src/credit-list/credit-list.html deleted file mode 100644 index f3a0f5e11..000000000 --- a/client/client/src/credit-list/credit-list.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - Credit - - - - - - - - {{::credit.amount | number:2}} € - {{::credit.created | date:'dd/MM/yyyy HH:mm' }} - {{::credit.worker.firstName}} {{::credit.worker.name}} - - - No results - - - - - - - - \ No newline at end of file diff --git a/client/client/src/credit-list/credit-list.js b/client/client/src/credit-list/credit-list.js deleted file mode 100644 index b545df2da..000000000 --- a/client/client/src/credit-list/credit-list.js +++ /dev/null @@ -1,7 +0,0 @@ -import ngModule from '../module'; -import FilterClientList from '../filter-client-list'; - -ngModule.component('vnClientCreditList', { - template: require('./credit-list.html'), - controller: FilterClientList -}); diff --git a/client/client/src/credit-list/locale/es.yml b/client/client/src/credit-list/locale/es.yml deleted file mode 100644 index b4b5940cf..000000000 --- a/client/client/src/credit-list/locale/es.yml +++ /dev/null @@ -1,3 +0,0 @@ -Since : Desde -Employee : Empleado -No results: Sin resultados \ No newline at end of file diff --git a/client/client/src/descriptor/descriptor.html b/client/client/src/descriptor/descriptor.html deleted file mode 100644 index 950baf89c..000000000 --- a/client/client/src/descriptor/descriptor.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - -
-
{{$ctrl.client.name}}
-
- Id {{$ctrl.client.id}} -
-
- Phone {{$ctrl.client.phone | phone}} -
-
- Credit {{$ctrl.client.credit | currency:'€':2}} -
-
- Secured credit - {{$ctrl.client.creditInsurance | currency:'€':2}} - - -
-
- -
\ No newline at end of file diff --git a/client/client/src/descriptor/descriptor.js b/client/client/src/descriptor/descriptor.js deleted file mode 100644 index b8d68c493..000000000 --- a/client/client/src/descriptor/descriptor.js +++ /dev/null @@ -1,36 +0,0 @@ -import ngModule from '../module'; - -class ClientDescriptor { - constructor($http) { - this.$http = $http; - } - _getClientDebt(clientFk) { - this.$http.get(`/client/api/Clients/${clientFk}/getDebt`) - .then(response => { - this.clientDebt = response.data.debt; - }); - } - - _getClient(clientFk) { - this.$http.get(`/client/api/Clients/${clientFk}/card`) - .then(response => { - Object.assign(this.client, response.data); - }); - } - - $onChanges(changes) { - if (changes.client && this.client) { - this._getClient(this.client.id); - this._getClientDebt(this.client.id); - } - } -} -ClientDescriptor.$inject = ['$http']; - -ngModule.component('vnClientDescriptor', { - template: require('./descriptor.html'), - bindings: { - client: '<' - }, - controller: ClientDescriptor -}); diff --git a/client/client/src/descriptor/descriptor.spec.js b/client/client/src/descriptor/descriptor.spec.js deleted file mode 100644 index 19e2d2c7c..000000000 --- a/client/client/src/descriptor/descriptor.spec.js +++ /dev/null @@ -1,45 +0,0 @@ -import './descriptor.js'; - -describe('Descriptor', () => { - describe('Component vnClientDescriptor', () => { - let $componentController; - let $httpBackend; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, _$httpBackend_) => { - $componentController = _$componentController_; - $httpBackend = _$httpBackend_; - controller = $componentController('vnClientDescriptor'); - })); - - describe('_getClientDebt()', () => { - it(`should call _getClientDebt() and define the clientDebt value on the controller`, () => { - controller.client = {}; - let response = {debt: 100}; - $httpBackend.whenGET(`/client/api/Clients/101/getDebt`).respond(response); - $httpBackend.expectGET(`/client/api/Clients/101/getDebt`); - controller._getClientDebt(101); - $httpBackend.flush(); - - expect(controller.clientDebt).toEqual(100); - }); - }); - - describe('_getClient()', () => { - it(`should call _getClient() and define the client value on the controller`, () => { - controller.client = {}; - let response = {id: 101, name: 'Batman'}; - $httpBackend.whenGET(`/client/api/Clients/101/card`).respond(response); - $httpBackend.expectGET(`/client/api/Clients/101/card`); - controller._getClient(101); - $httpBackend.flush(); - - expect(controller.client.name).toEqual('Batman'); - }); - }); - }); -}); diff --git a/client/client/src/filter-client-list.js b/client/client/src/filter-client-list.js deleted file mode 100644 index 6e6b007cb..000000000 --- a/client/client/src/filter-client-list.js +++ /dev/null @@ -1,9 +0,0 @@ -import FilterList from 'core/src/lib/filter-list'; - -export default class FilterClientList extends FilterList { - constructor($scope, $timeout, $state) { - super($scope, $timeout, $state); - this.modelName = 'clientFk'; - } -} -FilterClientList.$inject = ['$scope', '$timeout', '$state']; diff --git a/client/client/src/fiscal-data/fiscal-data.html b/client/client/src/fiscal-data/fiscal-data.html deleted file mode 100644 index b70dd319f..000000000 --- a/client/client/src/fiscal-data/fiscal-data.html +++ /dev/null @@ -1,141 +0,0 @@ - - - -
- - Fiscal data - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - diff --git a/client/client/src/fiscal-data/fiscal-data.js b/client/client/src/fiscal-data/fiscal-data.js deleted file mode 100644 index 27e314ca7..000000000 --- a/client/client/src/fiscal-data/fiscal-data.js +++ /dev/null @@ -1,60 +0,0 @@ -import ngModule from '../module'; - -export default class ClientFiscalData { - constructor($scope, $http, vnApp, $translate) { - this.$ = $scope; - this.$http = $http; - this.vnApp = vnApp; - this.translate = $translate; - this.isEqualizated = undefined; - this.copyData(); - } - - $onChanges() { - this.copyData(); - } - - copyData() { - if (this.client) { - this.isEqualizated = this.client.isEqualizated; - } - } - - buyerHaspermissions() { - if (!this.client) return true; - return !this.client.isTaxDataChecked; - } - - submit() { - return this.$.watcher.submit().then( - () => this.checkEtChanges()); - } - - checkEtChanges() { - let equals = this.isEqualizated == this.client.isEqualizated; - this.isEqualizated = this.client.isEqualizated; - - if (!equals) - this.$.propagateIsEqualizated.show(); - } - - returnDialogEt(response) { - if (response === 'ACCEPT') { - this.$http.patch(`/client/api/Clients/${this.client.id}/addressesPropagateRe`, {isEqualizated: this.client.isEqualizated}).then( - res => { - if (res.data) - this.vnApp.showMessage(this.translate.instant('Equivalent tax spreaded')); - } - ); - } - } -} -ClientFiscalData.$inject = ['$scope', '$http', 'vnApp', '$translate']; - -ngModule.component('vnClientFiscalData', { - template: require('./fiscal-data.html'), - controller: ClientFiscalData, - bindings: { - client: '<' - } -}); diff --git a/client/client/src/fiscal-data/fiscal-data.spec.js b/client/client/src/fiscal-data/fiscal-data.spec.js deleted file mode 100644 index 653029c6f..000000000 --- a/client/client/src/fiscal-data/fiscal-data.spec.js +++ /dev/null @@ -1,31 +0,0 @@ -import './fiscal-data.js'; - -describe('Client', () => { - describe('Component vnClientFiscalData', () => { - let $componentController; - let $httpBackend; - let $scope; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_) => { - $componentController = _$componentController_; - $httpBackend = _$httpBackend_; - $scope = $rootScope.$new(); - controller = $componentController('vnClientFiscalData', {$scope: $scope}); - })); - - describe('returnDialogEt()', () => { - it('should request to patch the propagation of tax status', () => { - controller.client = {id: 123, isEqualizated: false}; - $httpBackend.when('PATCH', `/client/api/Clients/${controller.client.id}/addressesPropagateRe`, {isEqualizated: controller.client.isEqualizated}).respond('done'); - $httpBackend.expectPATCH(`/client/api/Clients/${controller.client.id}/addressesPropagateRe`, {isEqualizated: controller.client.isEqualizated}); - controller.returnDialogEt('ACCEPT'); - $httpBackend.flush(); - }); - }); - }); -}); diff --git a/client/client/src/fiscal-data/locale/es.yml b/client/client/src/fiscal-data/locale/es.yml deleted file mode 100644 index a31826cdd..000000000 --- a/client/client/src/fiscal-data/locale/es.yml +++ /dev/null @@ -1,4 +0,0 @@ -No: No -Yes, notify: Sí, notificar -You changed the equalization tax: Has cambiado el recargo de equivalencia -Do you want to spread the change: ¿Deseas propagar el cambio a sus consignatarios? \ No newline at end of file diff --git a/client/client/src/greuge-create/greuge-create.html b/client/client/src/greuge-create/greuge-create.html deleted file mode 100644 index 0be11eb26..000000000 --- a/client/client/src/greuge-create/greuge-create.html +++ /dev/null @@ -1,44 +0,0 @@ - - - -
- - Add Greuge - - - - - - - - - - - - - - - - -
\ No newline at end of file diff --git a/client/client/src/greuge-create/greuge-create.js b/client/client/src/greuge-create/greuge-create.js deleted file mode 100644 index 3e8aa96a8..000000000 --- a/client/client/src/greuge-create/greuge-create.js +++ /dev/null @@ -1,25 +0,0 @@ -import ngModule from '../module'; - -class ClientGreugeCreate { - constructor($scope, $state, $filter) { - this.$ = $scope; - this.$state = $state; - this.greuge = { - shipped: $filter('date')(new Date(), 'yyyy-MM-dd HH:mm') - }; - } - onSubmit() { - this.greuge.clientFk = this.$state.params.id; - this.$.watcher.submit().then( - () => { - this.$state.go('clientCard.greuge.list'); - } - ); - } -} -ClientGreugeCreate.$inject = ['$scope', '$state', '$filter']; - -ngModule.component('vnClientGreugeCreate', { - template: require('./greuge-create.html'), - controller: ClientGreugeCreate -}); diff --git a/client/client/src/greuge-create/greuge-create.spec.js b/client/client/src/greuge-create/greuge-create.spec.js deleted file mode 100644 index 1cc408088..000000000 --- a/client/client/src/greuge-create/greuge-create.spec.js +++ /dev/null @@ -1,39 +0,0 @@ -import './greuge-create.js'; - -describe('Client', () => { - describe('Component vnClientGreugeCreate', () => { - let $componentController; - let $scope; - let $state; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$state_) => { - $componentController = _$componentController_; - $scope = $rootScope.$new(); - $state = _$state_; - $scope.watcher = { - submit: () => { - return { - then: callback => { - callback(); - } - }; - } - }; - controller = $componentController('vnClientGreugeCreate', {$scope: $scope}); - })); - - describe('onSubmit()', () => { - it('should call the function go() on $state to go to the greuges list', () => { - spyOn($state, 'go'); - controller.onSubmit(); - - expect(controller.$state.go).toHaveBeenCalledWith('clientCard.greuge.list'); - }); - }); - }); -}); diff --git a/client/client/src/greuge-list/greuge-list.html b/client/client/src/greuge-list/greuge-list.html deleted file mode 100644 index f6d5b8344..000000000 --- a/client/client/src/greuge-list/greuge-list.html +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - Greuge - - - - - - - - - {{::greuge.shipped | date:'dd/MM/yyyy HH:mm' }} - {{::greuge.description}} - {{::greuge.amount | number:2}} € - {{::greuge.greugeType.name}} - - - No results - - - - {{edit.model.sumAmount | number:2}} € - - - - - - - - - - \ No newline at end of file diff --git a/client/client/src/greuge-list/greuge-list.js b/client/client/src/greuge-list/greuge-list.js deleted file mode 100644 index 9bb863721..000000000 --- a/client/client/src/greuge-list/greuge-list.js +++ /dev/null @@ -1,7 +0,0 @@ -import ngModule from '../module'; -import FilterClientList from '../filter-client-list'; - -ngModule.component('vnClientGreugeList', { - template: require('./greuge-list.html'), - controller: FilterClientList -}); diff --git a/client/client/src/greuge-list/locale/es.yml b/client/client/src/greuge-list/locale/es.yml deleted file mode 100644 index 5038e95d1..000000000 --- a/client/client/src/greuge-list/locale/es.yml +++ /dev/null @@ -1,5 +0,0 @@ -Date: Fecha -Comment: Comentario -Amount: Importe -Type: Tipo -Add Greuge: Añadir Greuge \ No newline at end of file diff --git a/client/client/src/index/index.html b/client/client/src/index/index.html deleted file mode 100644 index 76953e618..000000000 --- a/client/client/src/index/index.html +++ /dev/null @@ -1,32 +0,0 @@ - -
-
- - - - - - - - - - - -
-
- - - - - - - - diff --git a/client/client/src/index/index.js b/client/client/src/index/index.js deleted file mode 100644 index 6f49f2626..000000000 --- a/client/client/src/index/index.js +++ /dev/null @@ -1,22 +0,0 @@ -import ngModule from '../module'; -import './item-client'; - -export default class Controller { - constructor($scope) { - this.$scope = $scope; - this.clientSelected = null; - } - search(index) { - index.accept(); - } - openSummary(client) { - this.clientSelected = client; - this.$scope.dialogSummaryClient.show(); - } -} -Controller.$inject = ['$scope']; - -ngModule.component('vnClientIndex', { - template: require('./index.html'), - controller: Controller -}); diff --git a/client/client/src/index/index.spec.js b/client/client/src/index/index.spec.js deleted file mode 100644 index 1836029e0..000000000 --- a/client/client/src/index/index.spec.js +++ /dev/null @@ -1,36 +0,0 @@ -import './index.js'; - -describe('Client', () => { - describe('Component vnClientIndex', () => { - let $componentController; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject(_$componentController_ => { - $componentController = _$componentController_; - controller = $componentController('vnClientIndex'); - })); - - it('should define and set clientSelected property as null', () => { - expect(controller.clientSelected).toEqual(null); - }); - - // describe('search()', () => { - // it(`should set model's search to the search input`, () => { - // controller.model.search = 'batman'; - // let index = { - // filter: {}, - // accept: () => { - // return 'accepted'; - // } - // }; - // controller.search(index); - - // expect(index.filter.search).toBe('batman'); - // }); - // }); - }); -}); diff --git a/client/client/src/index/item-client.html b/client/client/src/index/item-client.html deleted file mode 100644 index 7ebb6b8f0..000000000 --- a/client/client/src/index/item-client.html +++ /dev/null @@ -1,21 +0,0 @@ - - - -
{{::$ctrl.client.name}}
-
Id {{::$ctrl.client.id}}
-
Phone {{::$ctrl.client.phone | phone}}
-
Town/City {{::$ctrl.client.city}}
-
Email {{::$ctrl.client.email}}
-
- - - - -
-
diff --git a/client/client/src/index/item-client.js b/client/client/src/index/item-client.js deleted file mode 100644 index 5bacee25d..000000000 --- a/client/client/src/index/item-client.js +++ /dev/null @@ -1,24 +0,0 @@ -import ngModule from '../module'; - -class Controller { - onClick(event) { - if (event.defaultPrevented) - event.stopImmediatePropagation(); - } - - preview(event) { - event.preventDefault(); - this.list.openSummary(this.client); - } -} - -ngModule.component('vnItemClient', { - template: require('./item-client.html'), - controller: Controller, - bindings: { - client: '<' - }, - require: { - list: '^vnClientIndex' - } -}); diff --git a/client/client/src/index/locale/es.yml b/client/client/src/index/locale/es.yml deleted file mode 100644 index c221de7f6..000000000 --- a/client/client/src/index/locale/es.yml +++ /dev/null @@ -1,5 +0,0 @@ -Client id: Id cliente -Phone: Teléfono -Town/City: Ciudad -Email: Correo electrónico -Create client: Crear cliente \ No newline at end of file diff --git a/client/client/src/index/style.scss b/client/client/src/index/style.scss deleted file mode 100644 index 0f2ee429f..000000000 --- a/client/client/src/index/style.scss +++ /dev/null @@ -1,3 +0,0 @@ -vn-item-client { - display: block; -} \ No newline at end of file diff --git a/client/client/src/invoices/invoices.html b/client/client/src/invoices/invoices.html deleted file mode 100644 index fcbb36b97..000000000 --- a/client/client/src/invoices/invoices.html +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - Invoices - - - - - - - - - - - {{::invoice.ref}} - {{::invoice.issued | date:'dd/MM/yyyy' }} - {{::invoice.dued | date:'dd/MM/yyyy' }} - {{::invoice.amount | currency:'€':2}} - - - - No results - - - - - {{edit.model.sumAmount | currency:'€':2}} - - - - - - \ No newline at end of file diff --git a/client/client/src/invoices/invoices.js b/client/client/src/invoices/invoices.js deleted file mode 100644 index 6f1ea5df1..000000000 --- a/client/client/src/invoices/invoices.js +++ /dev/null @@ -1,15 +0,0 @@ -import ngModule from '../module'; -import FilterClientList from '../filter-client-list'; - -class Controller extends FilterClientList { - constructor($scope, $timeout, $state, $stateParams) { - super($scope, $timeout, $state); - $scope.$stateParams = $stateParams; - } -} -Controller.$inject = ['$scope', '$timeout', '$state', '$stateParams']; - -ngModule.component('vnClientInvoices', { - template: require('./invoices.html'), - controller: Controller -}); diff --git a/client/client/src/invoices/locale/es.yml b/client/client/src/invoices/locale/es.yml deleted file mode 100644 index 1f03f6318..000000000 --- a/client/client/src/invoices/locale/es.yml +++ /dev/null @@ -1,5 +0,0 @@ -Invoices: Facturas -Reference: Referencia -Issue date: Fecha de emisión -Due date: Vencimiento -Amount: Total \ No newline at end of file diff --git a/client/client/src/locale/en.yml b/client/client/src/locale/en.yml deleted file mode 100644 index 3dec4a7ed..000000000 --- a/client/client/src/locale/en.yml +++ /dev/null @@ -1,2 +0,0 @@ -Client: Client -Clients: Clients \ No newline at end of file diff --git a/client/client/src/locale/es.yml b/client/client/src/locale/es.yml deleted file mode 100644 index bb2984d9b..000000000 --- a/client/client/src/locale/es.yml +++ /dev/null @@ -1,23 +0,0 @@ -Active: Activo -Client: Cliente -Clients: Clientes -Basic data: Datos básicos -Fiscal data: Datos Fiscales -Addresses: Consignatarios -Web access: Acceso web -Notes: Notas -Has to invoice: Factura -Invoice by mail: Factura impresa -Country: País -Street: Domicilio fiscal -City: Municipio -Postcode: Código postal -Province: Provincia -Save: Guardar -Pay method : Forma de pago -Address: Consignatario -Credit : Crédito -Secured credit: Crédito asegurado -Verified data: Datos comprobados -Mandate: Mandato -Amount: Importe \ No newline at end of file diff --git a/client/client/src/mandate/mandate.html b/client/client/src/mandate/mandate.html deleted file mode 100644 index ef706ece6..000000000 --- a/client/client/src/mandate/mandate.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - - Mandate - - - - - - - - - - {{::mandate.id}} - {{::mandate.company.code}} - {{::mandate.mandateType.name}} - {{::mandate.created | date:'dd/MM/yyyy HH:mm' }} - {{::mandate.finished | date:'dd/MM/yyyy HH:mm' || '-'}} - - - No results - - - - - \ No newline at end of file diff --git a/client/client/src/mandate/mandate.js b/client/client/src/mandate/mandate.js deleted file mode 100644 index f21f83d28..000000000 --- a/client/client/src/mandate/mandate.js +++ /dev/null @@ -1,7 +0,0 @@ -import ngModule from '../module'; -import FilterClientList from '../filter-client-list'; - -ngModule.component('vnClientMandate', { - template: require('./mandate.html'), - controller: FilterClientList -}); diff --git a/client/client/src/module.js b/client/client/src/module.js deleted file mode 100644 index aabcb4d82..000000000 --- a/client/client/src/module.js +++ /dev/null @@ -1,5 +0,0 @@ -import {ng} from 'vendor'; -import 'core'; - -const ngModule = ng.module('client', ['vnCore']); -export default ngModule; diff --git a/client/client/src/note-create/note-create.html b/client/client/src/note-create/note-create.html deleted file mode 100644 index 6ad907794..000000000 --- a/client/client/src/note-create/note-create.html +++ /dev/null @@ -1,25 +0,0 @@ - - -
- - New note - - - - - - - - -
\ No newline at end of file diff --git a/client/client/src/note-create/note-create.js b/client/client/src/note-create/note-create.js deleted file mode 100644 index 3f5c68ce2..000000000 --- a/client/client/src/note-create/note-create.js +++ /dev/null @@ -1,16 +0,0 @@ -import ngModule from '../module'; - -export default class Controller { - constructor($state) { - this.note = { - clientFk: parseInt($state.params.id), - text: null - }; - } -} -Controller.$inject = ['$state']; - -ngModule.component('vnNoteCreate', { - template: require('./note-create.html'), - controller: Controller -}); diff --git a/client/client/src/note-create/note-create.spec.js b/client/client/src/note-create/note-create.spec.js deleted file mode 100644 index 1414835fd..000000000 --- a/client/client/src/note-create/note-create.spec.js +++ /dev/null @@ -1,25 +0,0 @@ -import './note-create.js'; - -describe('Client', () => { - describe('Component vnNoteCreate', () => { - let $componentController; - let $state; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, _$state_) => { - $componentController = _$componentController_; - $state = _$state_; - $state.params.id = '1234'; - controller = $componentController('vnNoteCreate', {$state: $state}); - })); - - it('should define clientFk using $state.params.id', () => { - expect(controller.note.clientFk).toBe(1234); - expect(controller.note.client).toBe(undefined); - }); - }); -}); diff --git a/client/client/src/notes/notes.html b/client/client/src/notes/notes.html deleted file mode 100644 index 213a4fecb..000000000 --- a/client/client/src/notes/notes.html +++ /dev/null @@ -1,24 +0,0 @@ - - - Notes - - - {{::n.worker.firstName}} {{::n.worker.name}} - {{::n.created | date:'dd/MM/yyyy HH:mm'}} - - - {{::n.text}} - - - - - - \ No newline at end of file diff --git a/client/client/src/notes/notes.js b/client/client/src/notes/notes.js deleted file mode 100644 index 7e0ec424a..000000000 --- a/client/client/src/notes/notes.js +++ /dev/null @@ -1,37 +0,0 @@ -import ngModule from '../module'; -import './style.css'; - -export default class Controller { - constructor($http, $state) { - this.$http = $http; - this.$state = $state; - } - - $onChanges() { - if (this.client) { - this.getObservation(this.client.id); - } - } - - getObservation(clientId) { - let json = JSON.stringify({where: {clientFk: this.client.id}, order: 'created DESC'}); - this.$http.get(`/client/api/clientObservations?filter=${json}`).then( - json => { - this.observations = json.data; - } - ); - } - - newObservation() { - this.$state.go("clientCard.notes.create", {id: this.client.id}); - } -} -Controller.$inject = ['$http', '$state']; - -ngModule.component('vnClientNotes', { - template: require('./notes.html'), - controller: Controller, - bindings: { - client: '<' - } -}); diff --git a/client/client/src/notes/notes.spec.js b/client/client/src/notes/notes.spec.js deleted file mode 100644 index 1ec7744de..000000000 --- a/client/client/src/notes/notes.spec.js +++ /dev/null @@ -1,58 +0,0 @@ -import './notes.js'; - -describe('Client', () => { - describe('Component vnClientNotes', () => { - let $componentController; - let $state; - let $httpBackend; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, _$state_, _$httpBackend_) => { - $componentController = _$componentController_; - $state = _$state_; - $httpBackend = _$httpBackend_; - $httpBackend.when('GET', /\/locale\/\w+\/[a-z]{2}\.json/).respond({}); - controller = $componentController('vnClientNotes', {$state: $state}); - })); - - describe('$onChanges()', () => { - it(`should call getObservation() with the client id`, () => { - controller.client = { - id: 1234 - }; - spyOn(controller, 'getObservation').and.returnValue(); - controller.$onChanges(); - - expect(controller.getObservation).toHaveBeenCalledWith(1234); - }); - }); - - describe('$getObservation()', () => { - it(`should request to GET the client notes`, () => { - controller.client = {id: '1234'}; - let jsonString = JSON.stringify({where: {clientFk: '1234'}, order: 'created DESC'}); - let json = {data: 'some data'}; - $httpBackend.when('GET', `/client/api/clientObservations?filter=${jsonString}`).respond(json); - $httpBackend.expectGET(`/client/api/clientObservations?filter=${jsonString}`, {Accept: 'application/json, text/plain, */*'}); - controller.getObservation(); - $httpBackend.flush(); - - expect(controller.observations).toEqual(json); - }); - }); - - describe('$newObservation()', () => { - it(`should redirect the user to the newObservation view`, () => { - controller.client = {id: '1234'}; - spyOn(controller.$state, 'go'); - controller.newObservation(); - - expect(controller.$state.go).toHaveBeenCalledWith('clientCard.notes.create', Object({id: '1234'})); - }); - }); - }); -}); diff --git a/client/client/src/recovery-create/locale/es.yml b/client/client/src/recovery-create/locale/es.yml deleted file mode 100644 index 64e15cd43..000000000 --- a/client/client/src/recovery-create/locale/es.yml +++ /dev/null @@ -1,2 +0,0 @@ -Add recovery: Añadir recobro -Period: Periodo \ No newline at end of file diff --git a/client/client/src/recovery-create/recovery-create.html b/client/client/src/recovery-create/recovery-create.html deleted file mode 100644 index a9ea4933d..000000000 --- a/client/client/src/recovery-create/recovery-create.html +++ /dev/null @@ -1,42 +0,0 @@ - - - -
- - Add recovery - - - - - - - - - - - - - - -
diff --git a/client/client/src/recovery-create/recovery-create.js b/client/client/src/recovery-create/recovery-create.js deleted file mode 100644 index 67e4421a2..000000000 --- a/client/client/src/recovery-create/recovery-create.js +++ /dev/null @@ -1,25 +0,0 @@ -import ngModule from '../module'; - -class ClientRecoveryCreate { - constructor($scope, $state, $filter) { - this.$ = $scope; - this.$state = $state; - this.recovery = { - started: $filter('date')(new Date(), 'yyyy-MM-dd HH:mm') - }; - } - onSubmit() { - this.recovery.clientFk = this.$state.params.id; - this.$.watcher.submit().then( - () => { - this.$state.go('clientCard.recovery.list'); - } - ); - } -} -ClientRecoveryCreate.$inject = ['$scope', '$state', '$filter']; - -ngModule.component('vnClientRecoveryCreate', { - template: require('./recovery-create.html'), - controller: ClientRecoveryCreate -}); diff --git a/client/client/src/recovery-create/recovery-create.spec.js b/client/client/src/recovery-create/recovery-create.spec.js deleted file mode 100644 index eede3a8f9..000000000 --- a/client/client/src/recovery-create/recovery-create.spec.js +++ /dev/null @@ -1,39 +0,0 @@ -import './recovery-create.js'; - -describe('Client', () => { - describe('Component vnClientRecoveryCreate', () => { - let $componentController; - let $scope; - let $state; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$state_) => { - $componentController = _$componentController_; - $scope = $rootScope.$new(); - $state = _$state_; - $scope.watcher = { - submit: () => { - return { - then: callback => { - callback(); - } - }; - } - }; - controller = $componentController('vnClientRecoveryCreate', {$scope: $scope}); - })); - - describe('onSubmit()', () => { - it('should call the function go() on $state to go to the recovery list', () => { - spyOn($state, 'go'); - controller.onSubmit(); - - expect(controller.$state.go).toHaveBeenCalledWith('clientCard.recovery.list'); - }); - }); - }); -}); diff --git a/client/client/src/recovery-list/locale/es.yml b/client/client/src/recovery-list/locale/es.yml deleted file mode 100644 index 3ad385a5c..000000000 --- a/client/client/src/recovery-list/locale/es.yml +++ /dev/null @@ -1,6 +0,0 @@ -Since: Desde -Employee: Empleado -No results: Sin resultados -To: Hasta -Recovery: Recobros -Finish that recovery period: Terminar el recobro \ No newline at end of file diff --git a/client/client/src/recovery-list/recovery-list.html b/client/client/src/recovery-list/recovery-list.html deleted file mode 100644 index b8d083e99..000000000 --- a/client/client/src/recovery-list/recovery-list.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - Recovery - - - - - - - - - - lock - - {{recovery.started | date:'dd/MM/yyyy' }} - {{recovery.finished | date:'dd/MM/yyyy' }} - {{recovery.amount | currency:'€':0}} - {{recovery.period}} - - - No results - - - - - - - - \ No newline at end of file diff --git a/client/client/src/recovery-list/recovery-list.js b/client/client/src/recovery-list/recovery-list.js deleted file mode 100644 index 5996f2d50..000000000 --- a/client/client/src/recovery-list/recovery-list.js +++ /dev/null @@ -1,24 +0,0 @@ -import ngModule from '../module'; -import FilterClientList from '../filter-client-list'; - -class ClientRecoveryList extends FilterClientList { - constructor($scope, $timeout, $state, $http) { - super($scope, $timeout, $state); - this.$http = $http; - } - setFinished(recovery) { - if (!recovery.finished) { - let params = {finished: Date.now()}; - this.$http.patch(`/client/api/Recoveries/${recovery.id}`, params).then( - () => this.$.index.accept() - ); - } - } -} - -ClientRecoveryList.$inject = ['$scope', '$timeout', '$state', '$http']; - -ngModule.component('vnClientRecoveryList', { - template: require('./recovery-list.html'), - controller: ClientRecoveryList -}); diff --git a/client/client/src/search-panel/locale/es.yml b/client/client/src/search-panel/locale/es.yml deleted file mode 100644 index 590d0e6d8..000000000 --- a/client/client/src/search-panel/locale/es.yml +++ /dev/null @@ -1,8 +0,0 @@ -Client id: Id cliente -Tax number: NIF/CIF -Name: Nombre -Social name: Razon social -Town/City: Ciudad -Postcode: Código postal -Email: Correo electrónico -Phone: Teléfono \ No newline at end of file diff --git a/client/client/src/search-panel/search-panel.html b/client/client/src/search-panel/search-panel.html deleted file mode 100644 index 2cb6a5aeb..000000000 --- a/client/client/src/search-panel/search-panel.html +++ /dev/null @@ -1,25 +0,0 @@ -
-
- - - - - - - - - - - - - - - - - - - - - -
-
diff --git a/client/client/src/search-panel/search-panel.js b/client/client/src/search-panel/search-panel.js deleted file mode 100644 index 74c4647ba..000000000 --- a/client/client/src/search-panel/search-panel.js +++ /dev/null @@ -1,18 +0,0 @@ -import ngModule from '../module'; - -export default class Controller { - constructor() { - // onSubmit() is defined by @vnSearchbar - this.onSubmit = () => {}; - } - - onSearch() { - this.onSubmit(this.filter); - } -} -Controller.$inject = []; - -ngModule.component('vnClientSearchPanel', { - template: require('./search-panel.html'), - controller: Controller -}); diff --git a/client/client/src/summary/client-summary.html b/client/client/src/summary/client-summary.html deleted file mode 100644 index e506ae23e..000000000 --- a/client/client/src/summary/client-summary.html +++ /dev/null @@ -1,155 +0,0 @@ - - - - -
{{$ctrl.summary.name}} - {{$ctrl.summary.id}} - {{$ctrl.summary.salesPerson.name}}
-
- - -
Basic data
-

Comercial Name {{$ctrl.summary.name}}

-

Contact {{$ctrl.summary.contact}}

-

Phone {{$ctrl.summary.phone}}

-

Mobile {{$ctrl.summary.mobile}}

-

Email {{$ctrl.summary.email}}

-

Salesperson {{$ctrl.summary.salesPerson.name}}

-

Channel {{$ctrl.summary.contactChannel.name}}

-
- -
Fiscal data
-

Social name {{$ctrl.summary.socialName}}

-

NIF / CIF {{$ctrl.summary.fi}}

-

Street {{$ctrl.summary.street}}

-

City {{$ctrl.summary.city}}

-

Postcode {{$ctrl.summary.postcode}}

-

Province {{$ctrl.summary.province.name}}

-

Country {{$ctrl.summary.country.country}}

-

- - -

-

- - -

-

- - -

-

- - -

-

- - -

-

- - -

-

- - -

-
- -
Pay method
-

Pay method {{$ctrl.summary.payMethod.name}}

-

IBAN {{$ctrl.summary.iban}}

-

Due day {{$ctrl.summary.dueDay}}

-

- - -

-

- - -

-

- - -

-
-
- - -
Default address
-

{{$ctrl.address.nickname}}

-

{{$ctrl.address.street}}

-

{{$ctrl.address.city}}

-
- -
Web access
-

User {{$ctrl.summary.account.name}}

-

- - -

-
- -
Recovery
- -

Since {{$ctrl.recovery.started}}

-

To {{$ctrl.recovery.finished}}

-

Amount {{$ctrl.recovery.amount | currency:'€':2}}

-

Period {{$ctrl.recovery.period}}

-
-
- -
- - -
Total greuge
-

Total {{$ctrl.greuge.sumAmount | currency:'€':2}}

-
- - -
Credit
-

- Credit - {{$ctrl.summary.credit | currency:'€':2}} -

-

- Secured credit - - - {{$ctrl.summary.creditInsurance | currency:'€':2}} -

-
-
-
-
-
\ No newline at end of file diff --git a/client/client/src/summary/client-summary.js b/client/client/src/summary/client-summary.js deleted file mode 100644 index a3e7c7bae..000000000 --- a/client/client/src/summary/client-summary.js +++ /dev/null @@ -1,100 +0,0 @@ -import ngModule from '../module'; - -class ClientSummary { - - constructor($http) { - this.$http = $http; - } - - set client(value) { - if (!value) - return; - - let filter = { - include: [ - { - relation: 'account', - scope: { - fields: ['name', 'active'] - } - }, - { - relation: 'salesPerson', - scope: { - fields: ['name'] - } - }, - { - relation: 'country', - scope: { - fields: ['country'] - } - }, - { - relation: 'province', - scope: { - fields: ['name'] - } - }, - { - relation: 'contactChannel', - scope: { - fields: ['name'] - } - }, - { - relation: 'payMethod', - scope: { - fields: ['name'] - } - }, - { - relation: 'addresses', - scope: { - where: {isDefaultAddress: true}, - fields: ['nickname', 'street', 'city', 'postalCode'] - } - } - ] - }; - - let clientSummary = `/client/api/Clients/${value.id}?filter=${JSON.stringify(filter)}`; - - this.$http.get(encodeURIComponent(clientSummary)).then(res => { - if (res.data) { - this.summary = res.data; - this.address = res.data.addresses[0]; - } - }); - - let greugeSum = `/client/api/Greuges/${value.id}/sumAmount`; - - this.$http.get(encodeURIComponent(greugeSum)).then(res => { - if (res.data) - this.greuge = res.data; - }); - - let recoveryFilter = { - where: { - and: [{clientFk: value.id}, {or: [{finished: null}, {finished: {gt: Date.now()}}]}] - }, - limit: 1 - }; - - let recovery = `/client/api/Recoveries?filter=${JSON.stringify(recoveryFilter)}`; - - this.$http.get(encodeURIComponent(recovery)).then(res => { - if (res.data) - this.recovery = res.data[0]; - }); - } -} -ClientSummary.$inject = ['$http']; - -ngModule.component('vnClientSummary', { - template: require('./client-summary.html'), - controller: ClientSummary, - bindings: { - client: '<' - } -}); diff --git a/client/client/src/summary/locale/es.yml b/client/client/src/summary/locale/es.yml deleted file mode 100644 index 27ebf6e37..000000000 --- a/client/client/src/summary/locale/es.yml +++ /dev/null @@ -1,2 +0,0 @@ -Default address: Consignatario pred. -Total greuge: Greuge total \ No newline at end of file diff --git a/client/client/src/web-access/locale/es.yml b/client/client/src/web-access/locale/es.yml deleted file mode 100644 index 2d1905c16..000000000 --- a/client/client/src/web-access/locale/es.yml +++ /dev/null @@ -1,5 +0,0 @@ -User: Usuario -Enable web access: Habilitar acceso web -New password: Nueva contraseña -Repeat password: Repetir contraseña -Change password: Cambiar contraseña \ No newline at end of file diff --git a/client/client/src/web-access/web-access.html b/client/client/src/web-access/web-access.html deleted file mode 100644 index 47e05759a..000000000 --- a/client/client/src/web-access/web-access.html +++ /dev/null @@ -1,55 +0,0 @@ - - -
- - Web access - - - - - - - - - - - - - -
- - - - - - - - - - - - diff --git a/client/client/src/web-access/web-access.js b/client/client/src/web-access/web-access.js deleted file mode 100644 index 5545b96f8..000000000 --- a/client/client/src/web-access/web-access.js +++ /dev/null @@ -1,70 +0,0 @@ -import ngModule from '../module'; - -export default class Controller { - constructor($scope, $http, vnApp) { - this.$ = $scope; - this.$http = $http; - this.vnApp = vnApp; - this.canChangePassword = false; - this.canEnableCheckBox = true; - } - - $onChanges() { - if (this.client) { - this.account = this.client.account; - this.isCustomer(); - this.checkConditions(); - } - } - - isCustomer() { - if (this.client.id) { - this.$http.get(`/client/api/Clients/${this.client.id}/hasCustomerRole`).then(res => { - this.canChangePassword = res.data && res.data.isCustomer; - }); - } - } - - checkConditions() { - if (this.client.id) { - this.$http.get(`/client/api/Clients/${this.client.id}/isValidClient`).then(res => { - this.canEnableCheckBox = res.data; - }); - } - } - - onPassOpen() { - this.newPassword = ''; - this.repeatPassword = ''; - this.$.$apply(); - } - - onPassChange(response) { - if (response == 'ACCEPT') - try { - if (!this.newPassword) - throw new Error(`Passwords can't be empty`); - if (this.newPassword != this.repeatPassword) - throw new Error(`Passwords don't match`); - let account = { - password: this.newPassword - }; - - this.$http.patch(`/client/api/Accounts/${this.client.id}`, account); - } catch (e) { - this.vnApp.showError(e.message); - return false; - } - - return true; - } -} -Controller.$inject = ['$scope', '$http', 'vnApp']; - -ngModule.component('vnClientWebAccess', { - template: require('./web-access.html'), - controller: Controller, - bindings: { - client: '<' - } -}); diff --git a/client/client/src/web-access/web-access.spec.js b/client/client/src/web-access/web-access.spec.js deleted file mode 100644 index a700f4c8b..000000000 --- a/client/client/src/web-access/web-access.spec.js +++ /dev/null @@ -1,93 +0,0 @@ -import './web-access.js'; - -describe('Component VnClientWebAccess', () => { - let $componentController; - let $httpBackend; - let $scope; - let vnApp; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_, _vnApp_) => { - $componentController = _$componentController_; - $scope = $rootScope.$new(); - $httpBackend = _$httpBackend_; - $httpBackend.when('GET', /\/locale\/\w+\/[a-z]{2}\.json/).respond({}); - vnApp = _vnApp_; - spyOn(vnApp, 'showError'); - controller = $componentController('vnClientWebAccess', {$scope: $scope}); - })); - - describe('$onChanges()', () => { - it(`should pass client's account data to account then call isCustomer function`, () => { - spyOn(controller, 'isCustomer'); - controller.client = {client: 'Bruce Wayne', account: 'Wayne Industries'}; - controller.account = {}; - controller.$onChanges(); - - expect(controller.account).toBe('Wayne Industries'); - expect(controller.isCustomer).toHaveBeenCalledWith(); - }); - }); - - describe('isCustomer()', () => { - it(`should perform a query if client is defined with an ID`, () => { - controller.client = {id: '1234'}; - controller.isCustomer(); - - $httpBackend.when('GET', `/client/api/Clients/${controller.client.id}/hasCustomerRole`).respond('ok'); - $httpBackend.expectGET(`/client/api/Clients/${controller.client.id}/hasCustomerRole`); - $httpBackend.flush(); - }); - }); - - describe('onPassOpen()', () => { - it('should set passwords to empty values', () => { - controller.newPassword = 'm24x8'; - controller.repeatPassword = 'm24x8'; - controller.onPassOpen(); - - expect(controller.newPassword).toBe(''); - expect(controller.repeatPassword).toBe(''); - }); - }); - - describe('onPassChange()', () => { - it('should request to update the password', () => { - controller.client = {id: '1234'}; - controller.newPassword = 'm24x8'; - controller.repeatPassword = 'm24x8'; - controller.canChangePassword = true; - $httpBackend.when('PATCH', '/client/api/Accounts/1234').respond('done'); - $httpBackend.expectPATCH('/client/api/Accounts/1234', {password: 'm24x8'}); - controller.onPassChange('ACCEPT'); - $httpBackend.flush(); - }); - - describe(`when password is empty`, () => { - it(`should throw Passwords can't be empty error`, () => { - controller.client = {id: '1234'}; - controller.newPassword = ''; - controller.canChangePassword = true; - controller.onPassChange('ACCEPT'); - - expect(vnApp.showError).toHaveBeenCalledWith(`Passwords can't be empty`); - }); - }); - - describe(`when passwords don't match`, () => { - it(`should throw Passwords don't match error`, () => { - controller.client = {id: '1234'}; - controller.newPassword = 'm24x8'; - controller.canChangePassword = true; - controller.repeatPassword = 'notMatchingPassword'; - controller.onPassChange('ACCEPT'); - - expect(vnApp.showError).toHaveBeenCalledWith(`Passwords don't match`); - }); - }); - }); -}); diff --git a/client/core/index.js b/client/core/index.js deleted file mode 100644 index 59d36b6af..000000000 --- a/client/core/index.js +++ /dev/null @@ -1 +0,0 @@ -export * from './src/core'; diff --git a/client/core/src/components/autocomplete/autocomplete.html b/client/core/src/components/autocomplete/autocomplete.html deleted file mode 100755 index 0ee10c5ae..000000000 --- a/client/core/src/components/autocomplete/autocomplete.html +++ /dev/null @@ -1,23 +0,0 @@ -
-
- - -
- - -
- -
- - -
\ No newline at end of file diff --git a/client/core/src/components/autocomplete/autocomplete.js b/client/core/src/components/autocomplete/autocomplete.js deleted file mode 100755 index 5c216d21d..000000000 --- a/client/core/src/components/autocomplete/autocomplete.js +++ /dev/null @@ -1,255 +0,0 @@ -import ngModule from '../../module'; -import Component from '../../lib/component'; -import './style.scss'; - -/** - * Input with option selector. - * - * @property {String} valueField The data field name that should be shown - * @property {String} showFiled The data field name that should be used as value - * @property {Array} data Static data for the autocomplete - * @property {Object} intialData A initial data to avoid the server request used to get the selection - * @property {Boolean} multiple Wether to allow multiple selection - */ -export default class Autocomplete extends Component { - constructor($element, $scope, $http, $transclude) { - super($element, $scope); - this.$http = $http; - this.$transclude = $transclude; - - this._field = undefined; - this._selection = null; - this.valueField = 'id'; - this.showField = 'name'; - this._multiField = []; - this.readonly = true; - this.form = null; - this.input = this.element.querySelector('.mdl-textfield__input'); - - componentHandler.upgradeElement( - this.element.querySelector('.mdl-textfield')); - } - - /** - * @type {any} The autocomplete value. - */ - get field() { - return this._field; - } - - set field(value) { - if (angular.equals(value, this._field)) - return; - - this._field = value; - this.refreshSelection(); - - if (this.onChange) - this.onChange(value); - } - - /** - * @type {Object} The selected data object, you can use this property - * to prevent requests to display the initial value. - */ - get selection() { - return this._selection; - } - - set selection(value) { - this._selection = value; - this.refreshDisplayed(); - } - - selectionIsValid(selection) { - return selection - && selection[this.valueField] == this._field - && selection[this.showField] != null; - } - - refreshSelection() { - if (this.selectionIsValid(this._selection)) - return; - - let value = this._field; - - if (value && this.valueField && this.showField) { - if (this.selectionIsValid(this.initialData)) { - this.selection = this.initialData; - return; - } - - let data = this.data; - - if (!data && this.$.dropDown) - data = this.$.dropDown.$.model.data; - - if (data) - for (let i = 0; i < data.length; i++) - if (data[i][this.valueField] === value) { - this.selection = data[i]; - return; - } - - if (this.url) { - this.requestSelection(value); - return; - } - } else - this.selection = null; - } - - requestSelection(value) { - let where = {}; - - if (this.multiple) - where[this.valueField] = {inq: this.field}; - else - where[this.valueField] = value; - - let filter = { - fields: this.getFields(), - where: where - }; - - let json = encodeURIComponent(JSON.stringify(filter)); - this.$http.get(`${this.url}?filter=${json}`).then( - json => this.onSelectionRequest(json.data), - () => this.onSelectionRequest(null) - ); - } - - onSelectionRequest(data) { - if (data && data.length > 0) { - if (this.multiple) - this.selection = data; - else - this.selection = data[0]; - } else - this.selection = null; - } - - refreshDisplayed() { - let display = ''; - - if (this._selection && this.showField) { - if (this.multiple && Array.isArray(this._selection)) { - for (var item of this._selection) { - if (display.length > 0) display += ', '; - display += item[this.showField]; - } - } else { - display = this._selection[this.showField]; - } - } - - this.input.value = display; - this.mdlUpdate(); - } - - getFields() { - let fields = []; - fields.push(this.valueField); - fields.push(this.showField); - - if (this.selectFields) - for (let field of this.selectFields) - fields.push(field); - - return fields; - } - - mdlUpdate() { - let field = this.element.querySelector('.mdl-textfield'); - let mdlField = field.MaterialTextfield; - if (mdlField) mdlField.updateClasses_(); - } - - setValue(value) { - this.field = value; - if (this.form) this.form.$setDirty(); - } - - onDropDownSelect(value) { - this.setValue(value); - this.field = value; - } - - onClearClick(event) { - event.preventDefault(); - this.setValue(null); - } - - onKeyDown(event) { - if (event.defaultPrevented) return; - - switch (event.keyCode) { - case 38: // Up - case 40: // Down - case 13: // Enter - this.showDropDown(); - break; - default: - if (event.key.length == 1) - this.showDropDown(event.key); - else - return; - } - - event.preventDefault(); - } - - onMouseDown(event) { - event.preventDefault(); - this.showDropDown(); - } - - showDropDown(search) { - Object.assign(this.$.dropDown.$.model, { - url: this.url, - staticData: this.data - }); - - Object.assign(this.$.dropDown, { - valueField: this.valueField, - showField: this.showField, - selectFields: this.getFields(), - where: this.where, - order: this.order, - parent: this.input, - multiple: this.multiple, - limit: this.limit, - $transclude: this.$transclude - }); - this.$.dropDown.show(search); - } -} -Autocomplete.$inject = ['$element', '$scope', '$http', '$transclude']; - -ngModule.component('vnAutocomplete', { - template: require('./autocomplete.html'), - controller: Autocomplete, - bindings: { - url: '@?', - data: ' { - let $element; - let $scope; - let $httpBackend; - let controller; - - let data = {id: 1, name: 'Bruce Wayne'}; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_, _$timeout_) => { - $scope = $rootScope.$new(); - $element = angular.element(`
${template}
`); - $httpBackend = _$httpBackend_; - $httpBackend.when('GET', /\/locale\/\w+\/[a-z]{2}\.json/).respond({}); - controller = _$componentController_('vnAutocomplete', {$element, $scope, $httpBackend, $transclude: null}); - })); - - describe('field() setter/getter', () => { - it(`should set field controllers property`, () => { - controller.field = data.id; - - expect(controller.field).toEqual(data.id); - }); - - it(`should set selection finding an existing item in the initialData property`, () => { - controller.valueField = 'id'; - controller.showField = 'name'; - controller.initialData = data; - controller.field = data.id; - - expect(controller.selection).toEqual(data); - }); - - it(`should set selection finding an existing item in the data property`, () => { - controller.valueField = 'id'; - controller.showField = 'name'; - controller.data = [data]; - controller.field = data.id; - - expect(controller.selection).toEqual(data); - }); - - it(`should set selection to null when can't find an existing item in the data property`, () => { - controller.valueField = 'id'; - controller.showField = 'name'; - controller.field = data.id; - - expect(controller.selection).toEqual(null); - }); - - it(`should perform a query if the item id isn't present in the data property`, () => { - controller.valueField = 'id'; - controller.showField = 'name'; - controller.url = 'localhost'; - controller.field = data.id; - - let filter = { - fields: ['id', 'name'], - where: {id: data.id} - }; - let json = encodeURIComponent(JSON.stringify(filter)); - - $httpBackend.expectGET(`localhost?filter=${json}`); - controller.field = data.id; - $httpBackend.flush(); - }); - }); -}); diff --git a/client/core/src/components/autocomplete/style.scss b/client/core/src/components/autocomplete/style.scss deleted file mode 100755 index 2dda27653..000000000 --- a/client/core/src/components/autocomplete/style.scss +++ /dev/null @@ -1,62 +0,0 @@ - -vn-autocomplete > div > .mdl-textfield { - position: relative; - width: 100%; - - & > input { - cursor: pointer; - height: 26px; - text-overflow: ellipsis; - white-space: nowrap; - overflow: hidden; - } - & > .icons { - display: none; - position: absolute; - right: 0; - top: 1.3em; - height: 1em; - color: #888; - border-radius: .2em; - background-color: rgba(255, 255, 255, .8); - - & > vn-icon { - cursor: pointer; - font-size: 18px; - - &:hover { - color: #333; - } - } - } - &:hover > .icons, - & > input:focus + .icons { - display: block; - } -} - -ul.vn-autocomplete { - list-style-type: none; - padding: 1em; - margin: 0; - padding: 0; - overflow: auto; - max-height: 300px; - - li { - display: block; - padding: .8em; - margin: 0; - cursor: pointer; - - &.active, - &:hover { - background-color: rgba(1, 1, 1, .1); - } - &.load-more { - color: #ffa410; - font-family: vn-font-bold; - padding: .4em .8em; - } - } -} \ No newline at end of file diff --git a/client/core/src/components/button/button.html b/client/core/src/components/button/button.html deleted file mode 100644 index dd0f7acc6..000000000 --- a/client/core/src/components/button/button.html +++ /dev/null @@ -1,3 +0,0 @@ - \ No newline at end of file diff --git a/client/core/src/components/button/button.js b/client/core/src/components/button/button.js deleted file mode 100644 index 6247bb77b..000000000 --- a/client/core/src/components/button/button.js +++ /dev/null @@ -1,17 +0,0 @@ -import ngModule from '../../module'; -import template from './button.html'; - -directive.$inject = ['vnTemplate']; -export default function directive(vnTemplate) { - return { - restrict: 'E', - template: (_, $attrs) => - vnTemplate.get(template, $attrs, { - label: 'Submit', - className: 'mdl-button mdl-js-button mdl-button--raised mdl-button--colored', - enabled: 'true', - typeName: 'button' - }) - }; -} -ngModule.directive('vnButton', directive); diff --git a/client/core/src/components/card/card.html b/client/core/src/components/card/card.html deleted file mode 100644 index e608d6fa9..000000000 --- a/client/core/src/components/card/card.html +++ /dev/null @@ -1 +0,0 @@ -
diff --git a/client/core/src/components/card/card.js b/client/core/src/components/card/card.js deleted file mode 100644 index 12df8da7d..000000000 --- a/client/core/src/components/card/card.js +++ /dev/null @@ -1,15 +0,0 @@ -import ngModule from '../../module'; -require('./style.scss'); - -directive.$inject = ['vnTemplate']; -export default function directive(vnTemplate) { - return { - restrict: 'E', - transclude: true, - template: require('./card.html'), - link: function(_, $element) { - $element.addClass('demo-card-wide mdl-shadow--2dp bg-panel'); - } - }; -} -ngModule.directive('vnCard', directive); diff --git a/client/core/src/components/card/style.scss b/client/core/src/components/card/style.scss deleted file mode 100644 index c2fe4e1ea..000000000 --- a/client/core/src/components/card/style.scss +++ /dev/null @@ -1,3 +0,0 @@ -vn-card { - display: block; -} \ No newline at end of file diff --git a/client/core/src/components/check/check.html b/client/core/src/components/check/check.html deleted file mode 100644 index b261a53a7..000000000 --- a/client/core/src/components/check/check.html +++ /dev/null @@ -1,4 +0,0 @@ - diff --git a/client/core/src/components/check/check.js b/client/core/src/components/check/check.js deleted file mode 100644 index 5b1a276d6..000000000 --- a/client/core/src/components/check/check.js +++ /dev/null @@ -1,50 +0,0 @@ -import ngModule from '../../module'; -import Input from '../../lib/input'; -import './style.scss'; - -export default class Controller extends Input { - constructor($element, $scope) { - super($element, $scope); - componentHandler.upgradeElement(this.element.firstChild); - this.mdlElement = this.element.firstChild.MaterialCheckbox; - this.input.addEventListener('change', () => this.onChange()); - } - set field(value) { - this.input.checked = value == true; - this.mdlUpdate(); - } - get field() { - return this.input.checked == true; - } - $onInit() { - if (this.model) { - this.model.$render = () => { - this.input.checked = this.model.$viewValue || false; - this.mdlUpdate(); - }; - this.$element.on('blur keyup change', () => { - this.$.$evalAsync(() => { - this.model.$setViewValue(this.input.checked); - }); - }); - } - } - onChange() { - this.$.$applyAsync(); - } -} -Controller.$inject = ['$element', '$scope', '$injector']; - -ngModule.component('vnCheck', { - template: require('./check.html'), - controller: Controller, - require: { - model: '?ngModel' - }, - bindings: { - field: '=?', - label: '@?', - disabled: ' - - - {{::$ctrl.text}} - - - - - - - - \ No newline at end of file diff --git a/client/core/src/components/column-header/column-header.js b/client/core/src/components/column-header/column-header.js deleted file mode 100644 index dc32e7e49..000000000 --- a/client/core/src/components/column-header/column-header.js +++ /dev/null @@ -1,56 +0,0 @@ -import ngModule from '../../module'; - -export default class ColumnHeader { - constructor($attrs) { - this.order = undefined; - this.mouseIsOver = false; - this.orderLocked = ($attrs.orderLocked !== undefined); - } - onClick(event, order) { - if (!this.orderLocked) { - if (order) { - this.order = order; - } else if (this.order === 'ASC') { - this.order = 'DESC'; - } else { - this.order = 'ASC'; - } - this.gridHeader.selectColum(this); - } - if (event) - event.preventDefault(); - } - showArrow(type) { - if (this.orderLocked) - return false; - - let showArrow = (this.gridHeader && this.gridHeader.currentColumn && this.gridHeader.currentColumn.field === this.field && this.order === type); - let showOther = (this.gridHeader && this.gridHeader.currentColumn && this.gridHeader.currentColumn.field === this.field && this.order !== type); - if (type === 'DESC' && this.mouseIsOver && !showOther) { - showArrow = true; - } - return showArrow; - } - $onInit() { - if (this.defaultOrder && !this.orderLocked) { - this.order = this.defaultOrder; - this.onClick(); - } - } -} -ColumnHeader.$inject = ['$attrs']; - -ngModule.component('vnColumnHeader', { - template: require('./column-header.html'), - bindings: { - field: '@?', - text: '@?', - className: '@?', - defaultOrder: '@?' - }, - require: { - gridHeader: '^^vnGridHeader' - }, - controller: ColumnHeader, - transclude: true -}); diff --git a/client/core/src/components/column-header/column-header.spec.js b/client/core/src/components/column-header/column-header.spec.js deleted file mode 100644 index 2291094b3..000000000 --- a/client/core/src/components/column-header/column-header.spec.js +++ /dev/null @@ -1,94 +0,0 @@ -import './column-header.js'; - -describe('Component vnColumnHeader', () => { - let $componentController; - let controller; - let $event; - let $attrs; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject(_$componentController_ => { - $componentController = _$componentController_; - $event = { - preventDefault: () => {} - }; - $attrs = {}; - controller = $componentController('vnColumnHeader', {$attrs}); - })); - - describe('onClick()', () => { - it(`should change the ordenation to DESC (descendant) if it was ASC (ascendant)`, () => { - controller.gridHeader = {selectColum: () => {}}; - controller.order = 'ASC'; - controller.onClick($event); - - expect(controller.order).toEqual('DESC'); - }); - - it(`should change the ordenation to ASC (ascendant) if it wasnt ASC`, () => { - controller.gridHeader = {selectColum: () => {}}; - controller.order = 'DESC or any other value that might occur'; - controller.onClick($event); - - expect(controller.order).toEqual('ASC'); - }); - - it(`should call the selectColum() function after changing a value`, () => { - controller.gridHeader = {selectColum: () => {}}; - controller.order = 'Change me!'; - spyOn(controller.gridHeader, 'selectColum'); - controller.onClick($event); - - expect(controller.gridHeader.selectColum).toHaveBeenCalledWith(controller); - }); - }); - - describe('showArrow()', () => { - it(`should return true when the type is DESC and MouseIsOver`, () => { - controller.gridHeader = {selectColum: () => {}}; - controller.mouseIsOver = true; - let result = controller.showArrow('DESC'); - - expect(result).toEqual(true); - }); - - it(`should return true if many conditions are true`, () => { - controller.gridHeader = {currentColumn: {field: 'fields should be identical'}}; - controller.field = 'fields should be identical'; - controller.order = 'ASC'; - let result = controller.showArrow('ASC'); - - expect(result).toEqual(true); - }); - - it(`should return false without type being DESC or any other values being true`, () => { - controller.gridHeader = {currentColumn: {field: 'fields should be identical'}}; - controller.field = 'I am the controllers field'; - controller.order = 'ASC'; - let result = controller.showArrow('ASC'); - - expect(result).toEqual(false); - }); - }); - - describe('onInit()', () => { - it(`should never call onClick()`, () => { - spyOn(controller, 'onClick'); - controller.$onInit(); - - expect(controller.onClick).not.toHaveBeenCalledWith(); - }); - - it(`should define controllers order as per defaultOrder then call onClick()`, () => { - controller.defaultOrder = 'ASC'; - spyOn(controller, 'onClick'); - controller.$onInit(); - - expect(controller.order).toEqual('ASC'); - expect(controller.onClick).toHaveBeenCalledWith(); - }); - }); -}); diff --git a/client/core/src/components/combo/combo.html b/client/core/src/components/combo/combo.html deleted file mode 100644 index 7b434fa62..000000000 --- a/client/core/src/components/combo/combo.html +++ /dev/null @@ -1,11 +0,0 @@ -
- - -
diff --git a/client/core/src/components/combo/combo.js b/client/core/src/components/combo/combo.js deleted file mode 100644 index 94c493379..000000000 --- a/client/core/src/components/combo/combo.js +++ /dev/null @@ -1,25 +0,0 @@ -import ngModule from '../../module'; -import template from './combo.html'; - -directive.$inject = ['vnTemplate']; -export function directive(vnTemplate) { - return { - restrict: 'E', - transclude: true, - template: (_, $attrs) => - vnTemplate.getNormalized(template, $attrs, { - label: 'Label', - enabled: 'enabled', - class: 'mdl-textfield__input' - }), - link: function(scope, element, attrs) { - scope.$watch(attrs.model, () => { - let mdlField = element[0].firstChild.MaterialTextfield; - if (mdlField) - mdlField.updateClasses_(); - }); - componentHandler.upgradeElement(element[0].firstChild); - } - }; -} -ngModule.directive('vnCombo', directive); diff --git a/client/core/src/components/confirm/confirm.html b/client/core/src/components/confirm/confirm.html deleted file mode 100644 index 3cdbb4a34..000000000 --- a/client/core/src/components/confirm/confirm.html +++ /dev/null @@ -1,10 +0,0 @@ - - -
{{::$ctrl.question}}
- {{::$ctrl.message}} -
- - - - -
\ No newline at end of file diff --git a/client/core/src/components/confirm/confirm.js b/client/core/src/components/confirm/confirm.js deleted file mode 100644 index 1431cf28a..000000000 --- a/client/core/src/components/confirm/confirm.js +++ /dev/null @@ -1,24 +0,0 @@ -import ngModule from '../../module'; -import Dialog from '../dialog/dialog'; -import template from './confirm.html'; - -export default class Confirm extends Dialog { - constructor($element, $scope, $compile) { - super($element); - let cTemplate = $compile(template)($scope)[0]; - this.body = cTemplate.querySelector('tpl-body'); - this.buttons = cTemplate.querySelector('tpl-buttons'); - } -} -Confirm.$inject = ['$element', '$scope', '$compile']; - -ngModule.component('vnConfirm', { - template: require('../dialog/dialog.html'), - bindings: { - onOpen: '&?', - onResponse: '&', - question: '@', - message: '@?' - }, - controller: Confirm -}); diff --git a/client/core/src/components/date-picker/date-picker.html b/client/core/src/components/date-picker/date-picker.html deleted file mode 100644 index 299d9df4b..000000000 --- a/client/core/src/components/date-picker/date-picker.html +++ /dev/null @@ -1,31 +0,0 @@ -
- - -
- - query_builder - - - clear - -
- -
\ No newline at end of file diff --git a/client/core/src/components/date-picker/date-picker.js b/client/core/src/components/date-picker/date-picker.js deleted file mode 100644 index db5e59d6f..000000000 --- a/client/core/src/components/date-picker/date-picker.js +++ /dev/null @@ -1,252 +0,0 @@ -import ngModule from '../../module'; -import Component from '../../lib/component'; -import Flatpickr from 'vendor/src/flatpickr'; -import './style.scss'; - -// equivalences to format date between flatpicker and angularjs -export const formatEquivalence = { - d: 'dd', // Day of the month, 2 digits with leading zeros (01 to 31) - j: 'd', // Day of the month without leading zeros (1 to 31) - m: 'MM', // Month in year, padded (01-12) - n: 'M', // Month in year (1-12) - y: 'yy', // A two digit representation of a year (00-99) - Y: 'yyyy', // A full numeric representation of a year, 4 digits (1999 or 2003) - H: 'HH', // Hour in AM/PM, padded (01-12) - h: 'H', // Hour in AM/PM, (1-12) - i: 'mm', // Minutes (00 to 59) - s: 'ss' // Seconds (00 to 59) -}; - -class DatePicker extends Component { - constructor($element, $translate, $filter, $timeout, $attrs) { - super($element); - this.input = $element[0].querySelector('input'); - this.$translate = $translate; - this.$filter = $filter; - this.$timeout = $timeout; - this.$attrs = $attrs; - - this.enabled = true; - this._modelView = null; - this._model = undefined; - this._optionsChecked = false; - this._waitingInit = 0; - this.hasFocus = false; - this.hasMouseIn = false; - componentHandler.upgradeElement($element[0].firstChild); - } - - get model() { - return this._model; - } - set model(value) { - if (this._optionsChecked) { - this._waitingInit = 0; - this._model = value; - if (value && !this.modelView) { - let options = this._getOptions(); - let initialDateFormat; - if (options && options.dateFormat) { - initialDateFormat = options.dateFormat; - } else { - initialDateFormat = this.$translate.use() === 'es' ? 'd-m-Y' : 'Y-m-d'; - if (options.enableTime) { - initialDateFormat += ' H:i:s'; - } - } - - let format = this._formatFlat2Angular(initialDateFormat); - this._modelView = this.$filter('date')(new Date(this._model), format); - this.mdlUpdate(); - } - } else if (this._waitingInit < 4) { - this._waitingInit++; - this.$timeout(() => { - this.model = value; - }, 250); - } else { - this.model = null; - this.modelView = ''; - this._waitingInit = 0; - } - } - get modelView() { - return this._modelView; - } - set modelView(value) { - this._modelView = value; - this.input.value = value; - this._setModel(value); - this.mdlUpdate(); - } - - onClear() { - this.modelView = null; - } - onClick() { - if (this.vp) { - this.vp.open(); - } - } - mdlUpdate() { - this.$timeout(() => { - let mdlField = this.element.firstChild.MaterialTextfield; - if (mdlField) - mdlField.updateClasses_(); - }, 500); - } - - _formatFlat2Angular(string) { // change string Flatpickr format to angular format (d-m-Y -> dd-MM-yyyy) - let aux = string.split(/[ZT.,/ :-]/); - let parts = []; - aux.forEach( - val => { - parts.push(formatEquivalence[val]); - } - ); - if (string.indexOf(' ') !== -1 || string.indexOf('T') !== -1) { // datetime format - let dates = parts.slice(0, 3).join('-'); - let hours = parts.slice(3, parts.length).join(':'); - return `${dates} ${hours}`.trim(); - } else if (string.indexOf(':') !== -1) { // only time format - return parts.join(':'); - } // only date format - return parts.join('-'); - } - - _string2BackFormat(value) { - let formats = this.iniOptions.dateFormat.split(/[ZT.,/ :-]/); - let aux = value.split(/[ZT.,/ :-]/); - let date = {}; - formats.forEach( - (k, i) => { - if (k.toLowerCase() === 'y') { - date.year = aux[i]; - } else if (k === 'm' || k === 'n') { - date.month = aux[i]; - } else if (k === 'd' || k === 'j') { - date.day = aux[i]; - } else if (k.toLowerCase() === 'h') { - date.hour = aux[i]; - } else if (k === 'i') { - date.minutes = aux[i]; - } else if (k === 's') { - date.seccons = aux[i]; - } - } - ); - - let dateStr = ''; - let hourStr = ''; - - if (date.year && date.month && date.day) { - dateStr = `${date.year}-${date.month}-${date.day}`; - } - if (date.hour) { - hourStr = date.hour; - if (date.minutes) { - hourStr += ':' + date.minutes; - } else { - hourStr += ':00'; - } - if (date.seccons) { - hourStr += ':' + date.seccons; - } else { - hourStr += ':00'; - } - } - return `${dateStr} ${hourStr}`.trim(); - } - - _setModel(value) { - let model; - let options = this._getOptions(); - if (!value) { - model = undefined; - } else if (!options || (options.dateFormat && options.dateFormat.startsWith('Y-m-d'))) { - model = value; - } else { - model = this._string2BackFormat(value); - } - - if (this.model !== model) { - this.model = model; - } - } - - _getOptions() { - if (this.iniOptions && this._optionsChecked) { - return this.iniOptions; - } else if (!this.iniOptions) { - this.iniOptions = {}; - } - - if (!this.iniOptions.locale) - this.iniOptions.locale = this.$translate.use(); - - if (!this.iniOptions.dateFormat) - this.iniOptions.dateFormat = this.iniOptions.locale === 'es' ? 'd-m-Y' : 'Y-m-d'; - else if (this.iniOptions.dateFormat) { - let format = this.iniOptions.dateFormat.split(/[ZT.,/ :-]/); - if (format.length <= 1) { - throw new Error(`Error: Invalid string format ${format}`); - } - format.forEach( - val => { - if (!formatEquivalence[val]) { - throw new Error(`Error in dateFormat ${this.iniOptions.dateFormat}: is not like Flatpickr Formatting Token https://chmln.github.io/flatpickr/formatting/`); - } - } - ); - } - - if (this.$attrs.hasOwnProperty('today')) { - this.iniOptions.defaultDate = new Date(); - } - - this._optionsChecked = true; - return this.iniOptions; - } - - initPicker() { - this.iniOptions = this._getOptions(); - this.isTimePicker = (this.iniOptions && this.iniOptions.enableTime && this.iniOptions.noCalendar); - this.vp = new Flatpickr(this.input, this.iniOptions); - if (this.iniOptions.defaultDate) { - this.modelView = this.vp.formatDate(this.iniOptions.defaultDate, this.iniOptions.dateFormat); - } - } - destroyPicker() { - if (this.vp) - this.vp.destroy(); - this.vp = undefined; - } - - $onChanges(objChange) { - if (objChange.iniOptions && objChange.iniOptions.currentValue) { - this.iniOptions = Object.assign(this.iniOptions, objChange.iniOptions.currentValue); - } - } - - $onInit() { - this.initPicker(); - } - - $onDestroy() { - this.destroyPicker(); - } -} -DatePicker.$inject = ['$element', '$translate', '$filter', '$timeout', '$attrs']; - -ngModule.component('vnDatePicker', { - template: require('./date-picker.html'), - bindings: { - model: '=', - label: '@?', - name: '@?', - enabled: ' { - let $componentController; - let $filter; - let $timeout; - let $element; - let $attrs; - let $translate; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, _$filter_, _$timeout_, _$translate_) => { - $componentController = _$componentController_; - $filter = _$filter_; - $timeout = _$timeout_; - $element = angular.element(`
`); - $translate = _$translate_; - $attrs = {}; - controller = $componentController('vnDatePicker', {$element, $translate, $filter, $timeout, $attrs}); - })); - - describe('_formatFlat2Angular()', () => { - it(`should format date from Y-m-d to yyyy-MM-dd`, () => { - let formatedDate = controller._formatFlat2Angular(`Y-m-d`); - - expect(formatedDate).toBe('yyyy-MM-dd'); - }); - - it(`should format date from d-m-Y to dd-MM-yyyy`, () => { - let formatedDate = controller._formatFlat2Angular(`d-m-Y`); - - expect(formatedDate).toBe('dd-MM-yyyy'); - }); - - it(`should split the given string into parts`, () => { - controller.iniOptions = {dateFormat: 'd/m/Y'}; - controller._optionsChecked = true; - controller.model = '2017-12-23'; - - expect(controller.modelView).toBe('23-12-2017'); - }); - }); -}); diff --git a/client/core/src/components/date-picker/style.scss b/client/core/src/components/date-picker/style.scss deleted file mode 100644 index 99f1cbc1b..000000000 --- a/client/core/src/components/date-picker/style.scss +++ /dev/null @@ -1,15 +0,0 @@ -vn-date-picker { - .mdl-chip__action { - position: absolute; - width: auto; - top: 0px; - right: -6px; - margin: 22px 0px; - background-color: white; - } - .material-icons { - font-size: 18px; - float: right; - margin-right: 5px; - } -} \ No newline at end of file diff --git a/client/core/src/components/dialog/dialog.html b/client/core/src/components/dialog/dialog.html deleted file mode 100644 index 1ce4eea58..000000000 --- a/client/core/src/components/dialog/dialog.html +++ /dev/null @@ -1,17 +0,0 @@ -
- -
-
-
-
-
-
-
\ No newline at end of file diff --git a/client/core/src/components/dialog/dialog.js b/client/core/src/components/dialog/dialog.js deleted file mode 100644 index 401a13e11..000000000 --- a/client/core/src/components/dialog/dialog.js +++ /dev/null @@ -1,120 +0,0 @@ -import ngModule from '../../module'; -import Component from '../../lib/component'; -import './style.scss'; - -/** - * Dialog component. - * - * @property {HTMLElement} body The dialog HTML body - * @property {HTMLElement} buttons The dialog HTML buttons - */ -export default class Dialog extends Component { - constructor($element, $transclude) { - super($element); - this.shown = false; - this.$element.addClass('vn-dialog'); - this.element.addEventListener('mousedown', - e => this.onBackgroundMouseDown(e)); - - if ($transclude) { - $transclude(tClone => { - this.body = tClone[0]; - }, null, 'body'); - $transclude(tClone => { - this.buttons = tClone[0]; - }, null, 'buttons'); - } - } - set body(value) { - this.element.querySelector('.body').appendChild(value); - } - set buttons(value) { - this.element.querySelector('.buttons').appendChild(value); - } - /** - * Displays the dialog to the user. - */ - show() { - if (this.shown) return; - this.shown = true; - this.keyDownHandler = e => this.onkeyDown(e); - this.document.addEventListener('keydown', this.keyDownHandler); - this.element.style.display = 'flex'; - this.transitionTimeout = setTimeout(() => this.$element.addClass('shown'), 30); - - if (this.onOpen) - this.onOpen(); - - let firstFocusable = this.element.querySelector('input, textarea'); - if (firstFocusable) firstFocusable.focus(); - } - /** - * Hides the dialog calling the response handler. - */ - hide() { - this.fireResponse(); - this.realHide(); - } - /** - * Calls the response handler. - * - * @param {String} response The response code - * @return {Boolean} %true if response was canceled, %false otherwise - */ - fireResponse(response) { - let cancel = false; - if (this.onResponse) - cancel = this.onResponse({response: response}); - return cancel; - } - realHide() { - if (!this.shown) return; - this.element.style.display = 'none'; - this.document.removeEventListener('keydown', this.keyDownHandler); - this.lastEvent = null; - this.shown = false; - this.transitionTimeout = - setTimeout(() => this.$element.removeClass('shown'), 30); - } - onButtonClick(event) { - let buttons = this.element.querySelector('.buttons'); - let tplButtons = buttons.querySelector('tpl-buttons'); - let node = event.target; - while (node.parentNode != tplButtons) { - if (node == buttons) return; - node = node.parentNode; - } - - let response = node.getAttribute('response'); - let cancel = this.fireResponse(response); - if (cancel !== false) this.realHide(); - } - onDialogMouseDown(event) { - this.lastEvent = event; - } - onBackgroundMouseDown(event) { - if (event != this.lastEvent) - this.hide(); - } - onkeyDown(event) { - if (event.keyCode == 27) // Esc - this.hide(); - } - $onDestroy() { - clearTimeout(this.transitionTimeout); - } -} -Dialog.$inject = ['$element', '$transclude']; - -ngModule.component('vnDialog', { - template: require('./dialog.html'), - transclude: { - body: 'tplBody', - buttons: '?tplButtons' - }, - bindings: { - onOpen: '&?', - onResponse: '&?' - }, - controller: Dialog -}); diff --git a/client/core/src/components/dialog/dialog.spec.js b/client/core/src/components/dialog/dialog.spec.js deleted file mode 100644 index 8cb1ad4a9..000000000 --- a/client/core/src/components/dialog/dialog.spec.js +++ /dev/null @@ -1,53 +0,0 @@ -describe('Component vnDialog', () => { - let $componentController; - let $element; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject(_$componentController_ => { - $componentController = _$componentController_; - $element = angular.element(''); - controller = $componentController('vnDialog', {$element: $element, $transclude: null}); - })); - - describe('show()', () => { - it(`should handle escape keypress event, define element.style.display to not none and call onOpen function`, () => { - window.innerHeight = 600; - window.innerWidth = 800; - controller.dialog = {style: {display: 'none'}}; - controller.onOpen = () => {}; - spyOn(controller, 'onOpen'); - controller.show(); - - expect(controller.element.style.display).not.toEqual('none'); - expect(controller.onOpen).toHaveBeenCalledWith(); - }); - }); - - describe('hide()', () => { - it(`should call onResponse()`, () => { - controller.onResponse = () => {}; - spyOn(controller, 'onResponse'); - controller.hide(); - - expect(controller.onResponse).toHaveBeenCalled(); - }); - }); - - describe('fireResponse()', () => { - it(`should call onResponse()`, () => { - let responseRes; - controller.onResponse = response => { - responseRes = response; - return false; - }; - let responseRet = controller.fireResponse('answer'); - - expect(responseRes).toEqual({response: 'answer'}); - expect(responseRet).toEqual(false); - }); - }); -}); diff --git a/client/core/src/components/dialog/style.scss b/client/core/src/components/dialog/style.scss deleted file mode 100644 index de13f0f7c..000000000 --- a/client/core/src/components/dialog/style.scss +++ /dev/null @@ -1,73 +0,0 @@ -.vn-dialog { - display: none; - justify-content: center; - align-items: center; - z-index: 11; - position: fixed; - left: 0; - top: 0; - height: 100%; - width: 100%; - background-color: rgba(1, 1, 1, .6); - opacity: 0; - transition: opacity 300ms ease-in-out; - - &.shown { - opacity: 1; - } - & > div { - position: relative; - box-shadow: 0 0 .4em rgba(1,1,1,.4); - background-color: white; - border-radius: .2em; - overflow: auto; - padding: 2em; - box-sizing: border-box; - - tpl-body { - display: block; - width: 20em; - } - button, - input[type="button"], - input[type="submit"], - input[type="reset"] { - text-transform: uppercase; - background-color: transparent; - border: none; - cursor: pointer; - transition: background-color 250ms; - border-radius: .1em; - - &:hover { - background-color: rgba(1,1,1,.1); - } - } - & > button.close { - position: absolute; - top: 0; - right: 0; - padding: .3em; - - & > vn-icon { - display: block; - color: #666; - } - } - & > form > .buttons { - margin-top: 1.5em; - text-align: right; - - button, - input[type="button"], - input[type="submit"], - input[type="reset"] { - color: #ffa410; - font-family: vn-font-bold; - padding: .7em; - margin: -0.7em; - margin-left: .7em; - } - } - } -} diff --git a/client/core/src/components/drop-down/drop-down.html b/client/core/src/components/drop-down/drop-down.html deleted file mode 100755 index 560ef77fa..000000000 --- a/client/core/src/components/drop-down/drop-down.html +++ /dev/null @@ -1,38 +0,0 @@ - - - - - diff --git a/client/core/src/components/drop-down/drop-down.js b/client/core/src/components/drop-down/drop-down.js deleted file mode 100755 index 482297618..000000000 --- a/client/core/src/components/drop-down/drop-down.js +++ /dev/null @@ -1,375 +0,0 @@ -import ngModule from '../../module'; -import Component from '../../lib/component'; -import './style.scss'; -import './model'; - -export default class DropDown extends Component { - constructor($element, $scope, $transclude, $timeout, $http) { - super($element, $scope); - this.$transclude = $transclude; - this.$timeout = $timeout; - - this.valueField = 'id'; - this.showField = 'name'; - this._search = undefined; - this._activeOption = -1; - this.showLoadMore = true; - this.showFilter = true; - - this.docKeyDownHandler = e => this.onDocKeyDown(e); - } - - $postLink() { - this.input = this.element.querySelector('.search'); - this.ul = this.element.querySelector('ul'); - this.list = this.element.querySelector('.list'); - this.list.addEventListener('scroll', e => this.onScroll(e)); - } - - get shown() { - return this.$.popover.shown; - } - - set shown(value) { - this.$.popover.shown = value; - } - - get search() { - return this._search; - } - - set search(value) { - value = value == '' || value == null ? null : value; - if (value === this._search) return; - - this._search = value; - this.$.model.clear(); - - this.$timeout.cancel(this.searchTimeout); - this.searchTimeout = this.$timeout(() => { - this.refreshModel(); - this.searchTimeout = null; - }, 350); - - this.buildList(); - } - - get statusText() { - let model = this.$.model; - let data = model.data; - let statusText = null; - - if (model.isLoading || this.searchTimeout) - statusText = 'Loading...'; - else if (data == null) - statusText = 'No data'; - else if (model.moreRows) - statusText = 'Load More'; - else if (data.length === 0) - statusText = 'No results found'; - - return statusText; - } - - get model() { - return this.$.model; - } - - get activeOption() { - return this._activeOption; - } - - /** - * Shows the drop-down. If a parent is specified it is shown in a visible - * relative position to it. - * - * @param {String} search The initial search term or %null - */ - show(search) { - this.search = search; - this._activeOption = -1; - this.buildList(); - this.$.popover.parent = this.parent; - this.$.popover.show(); - } - - /** - * Hides the drop-down. - */ - hide() { - this.$.popover.hide(); - } - - /** - * Activates a option and scrolls the drop-down to that option. - * - * @param {Number} option The option index - */ - moveToOption(option) { - this.activateOption(option); - - let list = this.list; - let li = this.activeLi; - if (!li) return; - - let liRect = li.getBoundingClientRect(); - let listRect = list.getBoundingClientRect(); - - if (liRect.bottom > listRect.bottom) - list.scrollTop += liRect.bottom - listRect.bottom; - else if (liRect.top < listRect.top) - list.scrollTop -= listRect.top - liRect.top; - } - - /** - * Activates a option. - * - * @param {Number} option The option index - */ - activateOption(option) { - this._activeOption = option; - - if (this.activeLi) - this.activeLi.className = ''; - - let data = this.$.model.data; - - if (option >= 0 && data && option < data.length) { - this.activeLi = this.ul.children[option]; - this.activeLi.className = 'active'; - } - } - - /** - * Selects an option. - * - * @param {Number} option The option index - */ - selectOption(option) { - if (option != -1) { - let data = this.$.model.data; - let item = data ? data[option] : null; - let value = item ? item[this.valueField] : null; - - if (this.multiple) { - if (!Array.isArray(this.selection)) { - this.selection = []; - this.field = []; - } - - this.selection.push(item); - this.field.push(value); - } else { - this.selection = item; - this.field = value; - } - - if (this.onSelect) - this.onSelect({value: value}); - } - - if (!this.multiple) - this.$.popover.hide(); - } - - refreshModel() { - this.$.model.filter = { - fields: this.selectFields, - where: this.getWhere(this._search), - order: this.getOrder(), - limit: this.limit || 8 - }; - this.$.model.refresh(this._search); - } - - getWhere(search) { - if (search == '' || search == null) - return undefined; - - if (this.where) { - let jsonFilter = this.where.replace(/search/g, search); - return this.$.$eval(jsonFilter); - } - - let where = {}; - where[this.showField] = {regexp: search}; - return where; - } - - getOrder() { - if (this.order) - return this.order; - else if (this.showField) - return `${this.showField} ASC`; - - return undefined; - } - - onOpen() { - this.document.addEventListener('keydown', this.docKeyDownHandler); - this.list.scrollTop = 0; - this.input.focus(); - } - - onClose() { - this.document.removeEventListener('keydown', this.docKeyDownHandler); - } - - onClearClick() { - this.search = null; - } - - onScroll() { - let list = this.list; - let shouldLoad = - list.scrollTop + list.clientHeight >= (list.scrollHeight - 40) - && !this.$.model.isLoading; - - if (shouldLoad) - this.$.model.loadMore(); - } - - onLoadMoreClick(event) { - event.preventDefault(); - this.$.model.loadMore(); - } - - onContainerClick(event) { - if (event.defaultPrevented) return; - let index = getPosition(this.ul, event); - if (index != -1) this.selectOption(index); - } - - onModelDataChange() { - this.buildList(); - } - - onDocKeyDown(event) { - if (event.defaultPrevented) return; - - let data = this.$.model.data; - let option = this.activeOption; - let nOpts = data ? data.length - 1 : 0; - - switch (event.keyCode) { - case 13: // Enter - this.selectOption(option); - break; - case 38: // Up - this.moveToOption(option <= 0 ? nOpts : option - 1); - break; - case 40: // Down - this.moveToOption(option >= nOpts ? 0 : option + 1); - break; - case 35: // End - this.moveToOption(nOpts); - break; - case 36: // Start - this.moveToOption(0); - break; - default: - return; - } - - event.preventDefault(); - this.$.$applyAsync(); - } - - buildList() { - this.destroyList(); - - let hasTemplate = this.$transclude && - this.$transclude.isSlotFilled('tplItem'); - let fragment = this.document.createDocumentFragment(); - let data = this.$.model.data; - - if (data) { - for (let i = 0; i < data.length; i++) { - let li = this.document.createElement('li'); - fragment.appendChild(li); - - if (this.multiple) { - let check = this.document.createElement('input'); - check.type = 'checkbox'; - li.appendChild(check); - - if (this.field && this.field.indexOf(data[i][this.valueField]) != -1) - check.checked = true; - } - - if (hasTemplate) { - this.$transclude((clone, scope) => { - Object.assign(scope, data[i]); - li.appendChild(clone[0]); - this.scopes[i] = scope; - }, null, 'tplItem'); - } else { - let text = this.document.createTextNode(data[i][this.showField]); - li.appendChild(text); - } - } - } - - this.ul.appendChild(fragment); - this.activateOption(this._activeOption); - this.$.$applyAsync(() => this.$.popover.relocate()); - } - - destroyList() { - this.ul.innerHTML = ''; - - if (this.scopes) - for (let scope of this.scopes) - scope.$destroy(); - - this.scopes = []; - } - - $onDestroy() { - this.destroyList(); - } -} -DropDown.$inject = ['$element', '$scope', '$transclude', '$timeout', '$http']; - -/** - * Gets the position of an event element relative to a parent. - * - * @param {HTMLElement} parent The parent element - * @param {Event} event The event object - * @return {Number} The element index - */ -function getPosition(parent, event) { - let target = event.target; - let children = parent.children; - - if (target === parent) - return -1; - - while (target.parentNode !== parent) - target = target.parentNode; - - for (let i = 0; i < children.length; i++) - if (children[i] === target) - return i; - - return -1; -} - -ngModule.component('vnDropDown', { - template: require('./drop-down.html'), - controller: DropDown, - bindings: { - field: '=?', - data: ' { - let $componentController; - let $timeout; - let $element; - let $scope; - let $httpBackend; - let $transitions; - let $q; - let $filter; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$timeout_, _$httpBackend_, _$q_, _$filter_, _$transitions_) => { - $componentController = _$componentController_; - $element = angular.element(`
${template}
`); - $timeout = _$timeout_; - $transitions = _$transitions_; - $q = _$q_; - $filter = _$filter_; - $scope = $rootScope.$new(); - $httpBackend = _$httpBackend_; - $httpBackend.when('GET', /\/locale\/\w+\/[a-z]{2}\.json/).respond({}); - - let popoverTemplate = require('../popover/popover.html'); - let $popover = angular.element(`
${popoverTemplate}
`); - $scope.popover = $componentController('vnPopover', {$element: $popover, $scope, $timeout, $transitions}); - $scope.popover.$postLink(); - - $scope.model = $componentController('vnModel', {$httpBackend, $q, $filter}); - controller = $componentController('vnDropDown', {$element, $scope, $transclude: null, $timeout, $httpBackend, $translate: null}); - controller.$postLink(); - controller.parent = angular.element('')[0]; - })); - - describe('show() method', () => { - it(`should define controllers _show using the value received as argument`, () => { - controller.show(); - - expect(controller.shown).toEqual(true); - }); - }); - - describe('hide() method', () => { - it(`should define controllers _show using the value received as argument`, () => { - controller.hide(); - - expect(controller.shown).toEqual(false); - }); - }); -}); diff --git a/client/core/src/components/drop-down/model.js b/client/core/src/components/drop-down/model.js deleted file mode 100644 index 12888563c..000000000 --- a/client/core/src/components/drop-down/model.js +++ /dev/null @@ -1,107 +0,0 @@ -import ngModule from '../../module'; - -export default class Model { - constructor($http, $q, $filter) { - this.$http = $http; - this.$q = $q; - this.$filter = $filter; - this.filter = null; - this.clear(); - } - - get isLoading() { - return this.canceler != null; - } - - loadMore() { - if (this.moreRows) { - let filter = Object.assign({}, this.myFilter); - filter.skip += filter.limit; - this.sendRequest(filter, true); - } - } - - clear() { - this.cancelRequest(); - this.data = null; - this.moreRows = false; - this.dataChanged(); - } - - refresh(search) { - if (this.url) { - let filter = Object.assign({}, this.filter); - - if (filter.limit) - filter.skip = 0; - - this.clear(); - this.sendRequest(filter); - } else if (this.staticData) { - if (search) - this.data = this.$filter('filter')(this.staticData, search); - else - this.data = this.staticData; - this.dataChanged(); - } - } - - cancelRequest() { - if (this.canceler) { - this.canceler.resolve(); - this.canceler = null; - this.request = null; - } - } - - sendRequest(filter, append) { - this.cancelRequest(); - this.canceler = this.$q.defer(); - let options = {timeout: this.canceler.promise}; - let json = encodeURIComponent(JSON.stringify(filter)); - this.request = this.$http.get(`${this.url}?filter=${json}`, options).then( - json => this.onRemoteDone(json, filter, append), - json => this.onRemoteError(json) - ); - } - - onRemoteDone(json, filter, append) { - let data = json.data; - - if (append) - this.data = this.data.concat(data); - else - this.data = data; - - this.myFilter = filter; - this.moreRows = filter.limit && data.length == filter.limit; - this.onRequestEnd(); - this.dataChanged(); - } - - onRemoteError(json) { - this.onRequestEnd(); - } - - onRequestEnd() { - this.request = null; - this.canceler = null; - } - - dataChanged() { - if (this.onDataChange) - this.onDataChange(); - } -} -Model.$inject = ['$http', '$q', '$filter']; - -ngModule.component('vnModel', { - controller: Model, - bindings: { - url: '@?', - staticData: ' .filter { - position: relative; - - & > .search { - display: block; - width: 100%; - box-sizing: border-box; - border: none; - border-bottom: 1px solid #ccc; - font-size: inherit; - padding: .6em; - } - & > vn-icon[icon=clear] { - display: none; - cursor: pointer; - position: absolute; - right: .5em; - top: .6em; - height: 1em; - color: #888; - border-radius: 50%; - background-color: rgba(255, 255, 255, .8); - font-size: 18px; - - &:hover { - color: #333; - } - } - &:hover > vn-icon[icon=clear] { - display: block; - } - } - & > .list { - max-height: 12.8em; - overflow: auto; - - ul { - padding: 0; - margin: 0; - list-style-type: none; - } - li, .status { - padding: .6em; - cursor: pointer; - white-space: nowrap; - transition: background-color 250ms ease-out; - display: flex; - - & > input[type=checkbox] { - margin: 0; - margin-right: .6em; - } - &:hover { - background-color: rgba(0, 0, 0, .1); - } - &.active { - background-color: #3D3A3B; - color: white; - } - } - .status { - color: #ffab40; - font-weight: bold; - } - } - } -} diff --git a/client/core/src/components/float-button/float-button.html b/client/core/src/components/float-button/float-button.html deleted file mode 100644 index d9467b5ce..000000000 --- a/client/core/src/components/float-button/float-button.html +++ /dev/null @@ -1,3 +0,0 @@ - \ No newline at end of file diff --git a/client/core/src/components/float-button/float-button.js b/client/core/src/components/float-button/float-button.js deleted file mode 100644 index d655a721b..000000000 --- a/client/core/src/components/float-button/float-button.js +++ /dev/null @@ -1,14 +0,0 @@ -import ngModule from '../../module'; -import template from './float-button.html'; - -directive.$inject = ['vnTemplate']; -export function directive(vnTemplate) { - return { - restrict: 'E', - template: (_, $attrs) => - vnTemplate.get(template, $attrs, { - className: 'mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--colored' - }) - }; -} -ngModule.directive('vnFloatButton', directive); diff --git a/client/core/src/components/grid-header/grid-header.html b/client/core/src/components/grid-header/grid-header.html deleted file mode 100644 index 02c0e4101..000000000 --- a/client/core/src/components/grid-header/grid-header.html +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/client/core/src/components/grid-header/grid-header.js b/client/core/src/components/grid-header/grid-header.js deleted file mode 100644 index 41d96602d..000000000 --- a/client/core/src/components/grid-header/grid-header.js +++ /dev/null @@ -1,27 +0,0 @@ -import ngModule from '../../module'; -import './style.scss'; - -export default class GridHeader { - constructor() { - this.currentColumn = undefined; - } - - selectColum(col) { - if (this.currentColumn && this.currentColumn.field != col.field) - this.currentColumn.order = undefined; - - this.currentColumn = col; - if (this.onOrder) - this.onOrder(this.currentColumn); - } - -} - -ngModule.component('vnGridHeader', { - template: require('./grid-header.html'), - transclude: true, - bindings: { - onOrder: '&?' - }, - controller: GridHeader -}); diff --git a/client/core/src/components/grid-header/grid-header.spec.js b/client/core/src/components/grid-header/grid-header.spec.js deleted file mode 100644 index 03294a348..000000000 --- a/client/core/src/components/grid-header/grid-header.spec.js +++ /dev/null @@ -1,43 +0,0 @@ -import './grid-header.js'; - -describe('Component vnGridHeader', () => { - let $componentController; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject(_$componentController_ => { - $componentController = _$componentController_; - controller = $componentController('vnGridHeader', {}); - })); - - describe('selectColum()', () => { - it(`should set controller currentColumn to equal the argument received`, () => { - let col = {columnStuff: 'some stuff'}; - controller.selectColum(col); - - expect(controller.currentColumn).toEqual(col); - }); - - it(`should set controller currentColumn.order to undefined then set currentColumn to equal the argument received`, () => { - controller.currentColumn = {field: 'some field', order: 'ordered'}; - let col = {columnStuff: 'some stuff'}; - controller.selectColum(col); - - expect(controller.currentColumn.order).not.toBeDefined(); - expect(controller.currentColumn).toEqual(col); - }); - - it(`should set controller currentColumn.order to undefined then call onOrder passing currentColumn as argument`, () => { - controller.onOrder = () => {}; - spyOn(controller, 'onOrder'); - let col = {columnStuff: 'some stuff'}; - controller.selectColum(col); - - expect(controller.currentColumn).toEqual(col); - expect(controller.onOrder).toHaveBeenCalledWith(col); - }); - }); -}); diff --git a/client/core/src/components/grid-header/style.scss b/client/core/src/components/grid-header/style.scss deleted file mode 100644 index 8f3475b35..000000000 --- a/client/core/src/components/grid-header/style.scss +++ /dev/null @@ -1,30 +0,0 @@ -vn-grid-header { - border-bottom: 3px solid #9D9D9D; - font-weight: bold; - .orderly{ - text-align: center; - white-space: nowrap; - justify-content: center; - vn-none{ - min-width: 17px; - } - } - vn-icon{ - margin: 0; - padding: 0; - i { - padding: 0; - margin: -2px -17px 0 0; - opacity: 0.2; - cursor: pointer; - } - &.active { - i { - opacity: 1; - } - } - } - [min-none]{ - min-width: 60px; - } -} \ No newline at end of file diff --git a/client/core/src/components/icon-button/icon-button.html b/client/core/src/components/icon-button/icon-button.html deleted file mode 100644 index fdd022710..000000000 --- a/client/core/src/components/icon-button/icon-button.html +++ /dev/null @@ -1,5 +0,0 @@ - \ No newline at end of file diff --git a/client/core/src/components/icon-button/icon-button.js b/client/core/src/components/icon-button/icon-button.js deleted file mode 100644 index c257b9da9..000000000 --- a/client/core/src/components/icon-button/icon-button.js +++ /dev/null @@ -1,12 +0,0 @@ -import ngModule from '../../module'; - -ngModule.component('vnIconButton', { - template: require('./icon-button.html'), - bindings: { - icon: '@', - className: '@?', - enabled: ' - -
- -
-
- -
- \ No newline at end of file diff --git a/client/core/src/components/icon-menu/icon-menu.js b/client/core/src/components/icon-menu/icon-menu.js deleted file mode 100644 index fc0e57432..000000000 --- a/client/core/src/components/icon-menu/icon-menu.js +++ /dev/null @@ -1,131 +0,0 @@ -import ngModule from '../../module'; -import './style.scss'; - -export default class IconMenu { - constructor($element, $http, $timeout) { - this.$element = $element; - this.$http = $http; - this.$timeout = $timeout; - this._showDropDown = false; - this.finding = false; - this.findMore = false; - this.element = $element[0]; - } - - get showDropDown() { - return this._showDropDown; - } - - set showDropDown(value) { - this._showDropDown = value; - } - - findItems(search) { - if (!this.url) - return this.items ? this.items : []; - - if (search && !this.finding) { - let filter = {where: {name: {regexp: search}}}; - let json = JSON.stringify(filter); - this.finding = true; - this.$http.get(`${this.url}?filter=${json}`).then( - json => { - this.items = json.data; - this.finding = false; - }, - () => { - this.finding = false; - } - ); - } else if (!search && !this.finding) { - this.maxRow = 10; - this.items = []; - this.getItems(); - } - } - - getItems() { - let filter = {}; - - if (this.maxRow) { - if (this.items) { - filter.skip = this.items.length; - } - filter.limit = this.maxRow; - filter.order = 'name ASC'; - } - - let json = JSON.stringify(filter); - - this.$http.get(`${this.url}?filter=${json}`).then( - json => { - if (json.data.length) - json.data.forEach( - el => { - this.items.push(el); - } - ); - else - this.maxRow = false; - } - ); - } - - $onInit() { - if (!this.items && this.url) { - this.items = []; - this.getItems(); - } - - this.findMore = this.url && this.maxRow; - - this.mouseFocus = false; - this.focused = false; - - this.$element.bind('mouseover', e => { - this.$timeout(() => { - this.mouseFocus = true; - this.showDropDown = this.focused; - }); - }); - - this.$element.bind('mouseout', () => { - this.$timeout(() => { - this.mouseFocus = false; - this.showDropDown = this.focused; - }); - }); - this.$element.bind('focusin', e => { - this.$timeout(() => { - this.focused = true; - this.showDropDown = true; - }); - }); - this.$element.bind('focusout', e => { - this.$timeout(() => { - this.focused = false; - this.showDropDown = this.mouseFocus; - }); - }); - } - - $onDestroy() { - this.$element.unbind('mouseover'); - this.$element.unbind('mouseout'); - this.$element.unbind('focusin'); - this.$element.unbind('focusout'); - } -} -IconMenu.$inject = ['$element', '$http', '$timeout']; - -ngModule.component('vnIconMenu', { - template: require('./icon-menu.html'), - bindings: { - url: '@?', - items: ' { - let $componentController; - let $element; - let $httpBackend; - let $timeout; - let $scope; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_, _$timeout_) => { - $componentController = _$componentController_; - $httpBackend = _$httpBackend_; - $httpBackend.when('GET', /\/locale\/\w+\/[a-z]{2}\.json/).respond({}); - $timeout = _$timeout_; - $scope = $rootScope.$new(); - $element = angular.element('
'); - controller = $componentController('vnIconMenu', {$scope, $element, $httpBackend, $timeout}, {url: 'test.com'}); - })); - - describe('component vnIconMenu', () => { - describe('findItem()', () => { - it(`should return items empty array if the controller does not provide a url and have no items defined`, () => { - controller.url = undefined; - controller.items = undefined; - let result = controller.findItems('some search value'); - - expect(result).toEqual([]); - }); - - it(`should return items array if the controller does not provide a url`, () => { - controller.url = undefined; - controller.items = ['Batman', 'Bruce Wayne']; - controller.findItems('some search value'); - - expect(controller.items.length).toEqual(2); - }); - - it(`should perform a search and store the result in controller items`, () => { - let search = 'The Joker'; - let json = JSON.stringify({where: {name: {regexp: search}}}); - $httpBackend.whenGET(`${controller.url}?filter=${json}`).respond([{id: 3, name: 'The Joker'}]); - $httpBackend.expectGET(`${controller.url}?filter=${json}`); - controller.findItems(search); - $httpBackend.flush(); - - expect(controller.items[0]).toEqual({id: 3, name: 'The Joker'}); - }); - - it(`should call getItems function if there's no search value`, () => { - spyOn(controller, 'getItems'); - controller.findItems(); - - expect(controller.getItems).toHaveBeenCalledWith(); - }); - }); - - describe('getItems()', () => { - it(`should perform a query and then push elements found into controller.items`, () => { - controller.items = []; - $httpBackend.whenGET(`${controller.url}?filter={}`).respond([{id: 1, name: 'Batman'}, {id: 2, name: 'Bruce Wayne'}]); - $httpBackend.expectGET(`${controller.url}?filter={}`); - controller.getItems(); - $httpBackend.flush(); - - expect(controller.items).toEqual([{id: 1, name: 'Batman'}, {id: 2, name: 'Bruce Wayne'}]); - }); - - it(`should perform a query and then set controller.maxRow to false if there are no items in the controller`, () => { - controller.items = []; - controller.maxRow = true; - $httpBackend.whenGET(`${controller.url}?filter={"skip":0,"limit":true,"order":"name ASC"}`).respond(controller.items); - $httpBackend.expectGET(`${controller.url}?filter={"skip":0,"limit":true,"order":"name ASC"}`); - controller.getItems(); - $httpBackend.flush(); - - expect(controller.maxRow).toBeFalsy(); - }); - }); - }); -}); diff --git a/client/core/src/components/icon-menu/style.scss b/client/core/src/components/icon-menu/style.scss deleted file mode 100644 index 2d3919f4d..000000000 --- a/client/core/src/components/icon-menu/style.scss +++ /dev/null @@ -1,12 +0,0 @@ -vn-icon-menu{ - position: relative; - .icon-menu__button { - padding: 0 10px; - } - vn-icon{ - float: left; - } - vn-icon.icon-menu__arrow_down{ - margin:2px 0 0 5px; - } -} \ No newline at end of file diff --git a/client/core/src/components/icon/style.scss b/client/core/src/components/icon/style.scss deleted file mode 100644 index e9764adec..000000000 --- a/client/core/src/components/icon/style.scss +++ /dev/null @@ -1,10 +0,0 @@ -vn-icon { - display: inline-block; - font-size: 18pt; - - & > i, - & > i.material-icons { - display: block; - font-size: inherit; - } -} diff --git a/client/core/src/components/index.js b/client/core/src/components/index.js deleted file mode 100644 index 774971572..000000000 --- a/client/core/src/components/index.js +++ /dev/null @@ -1,30 +0,0 @@ -import './textfield/textfield'; -import './watcher/watcher'; -import './paging/paging'; -import './icon/icon'; -import './dialog/dialog'; -import './confirm/confirm'; -import './title/title'; -import './subtitle/subtitle'; -import './spinner/spinner'; -import './snackbar/snackbar'; -import './tooltip/tooltip'; -import './icon-menu/icon-menu'; -import './popover/popover'; -import './autocomplete/autocomplete'; -import './drop-down/drop-down'; -import './menu/menu'; -import './column-header/column-header'; -import './grid-header/grid-header'; -import './multi-check/multi-check'; -import './date-picker/date-picker'; -import './button/button'; -import './check/check'; -import './radio/radio'; -import './textarea/textarea'; -import './icon-button/icon-button'; -import './submit/submit'; -import './combo/combo'; -import './card/card'; -import './switch/switch'; -import './float-button/float-button'; diff --git a/client/core/src/components/menu/menu.js b/client/core/src/components/menu/menu.js deleted file mode 100755 index ce32502d9..000000000 --- a/client/core/src/components/menu/menu.js +++ /dev/null @@ -1,24 +0,0 @@ -import ngModule from '../../module'; -import Popover from '../popover/popover'; - -export default class Menu extends Popover { - $postLink() { - super.$postLink(); - this.element.addEventListener('click', - () => this.onClick()); - } - - onClick() { - this.hide(); - } -} - -ngModule.component('vnMenu', { - template: require('../popover/popover.html'), - controller: Menu, - transclude: true, - bindings: { - onOpen: '&?', - onClose: '&?' - } -}); diff --git a/client/core/src/components/multi-check/multi-check.html b/client/core/src/components/multi-check/multi-check.html deleted file mode 100644 index 36f7f3ec7..000000000 --- a/client/core/src/components/multi-check/multi-check.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/client/core/src/components/multi-check/multi-check.js b/client/core/src/components/multi-check/multi-check.js deleted file mode 100644 index 21f60ec63..000000000 --- a/client/core/src/components/multi-check/multi-check.js +++ /dev/null @@ -1,106 +0,0 @@ -import ngModule from '../../module'; -import './multi-check.scss'; - -/** - * Draw checkbox with a drop-down and multi options - * @param {SmallInt} checkAll Primary input-check state: 0 -> uncheck, 1 -> checked, 2 -> indeterminate checked - * @param {Array} options List of options shown in drop-down - * @param {Array} models Elements to check / unCheck - * @param {String} className Optional css class name - */ -export default class MultiCheck { - constructor($timeout) { - this.$timeout = $timeout; - this._checkAll = 0; - this._models = []; - this._type = {}; - this.showDropDown = false; - } - - get type() { - return this._type; - } - - set type(value) { - if (value && value.id) { - this._type = value; - switch (value.id) { - case 'all': - this.checkAll = 1; - break; - case 'any': - this.checkAll = 0; - break; - default: - this.checkAll = 2; - break; - } - } - this._type = {}; - this.showDropDown = false; - } - - get models() { - return this._models; - } - - set models(value) { - this._models = value; - } - - get checkAll() { - return this._checkAll; - } - - set checkAll(value) { - this._checkAll = value; - this.switchChecks(); - } - - switchChecks() { - if (this.models) - this.models.forEach( - el => { - let checked; - if (this.type.id && this.type.id !== 'all' && this.type.id !== 'any') { - if (this.type.id.length > 3 && this.type.id.substr(0, 3) === 'no-') { - let label = this.type.id.replace('no-', ''); - checked = Boolean(el[label]) === false; - } else if (this.type.id.length > 6 && this.type.id.substr(0, 6) === 'equal-') { - let label = this.type.id.replace('equal-', ''); - checked = (el[label] && el[label] === this.type.name); - } else { - checked = Boolean(el[this.type.id]) === true; - } - } else { - checked = this.checkAll === 1; - } - el.checked = checked; - } - ); - } - - $onChanges() { - this.type = {}; - this.checkAll = 0; - } - - onBlur() { - this.$timeout(() => { - this.showDropDown = false; - }, 200); - } -} -MultiCheck.$inject = ['$timeout']; - -ngModule.component('vnMultiCheck', { - template: require('./multi-check.html'), - controller: MultiCheck, - bindings: { - checkAll: '=', - options: '<', - models: '<', - className: '@?' - } -}); - diff --git a/client/core/src/components/multi-check/multi-check.scss b/client/core/src/components/multi-check/multi-check.scss deleted file mode 100644 index c253bbde6..000000000 --- a/client/core/src/components/multi-check/multi-check.scss +++ /dev/null @@ -1,24 +0,0 @@ -.multi-check { - vn-icon{ - cursor: pointer; - } - .primaryCheckbox { - vn-icon{ - font-size: 22px; - margin-left: -4px; - i{ - color: rgba(0,0,0,.54); - } - } - &.color { - i{ - color: rgb(255,152,0); - } - } - } - .arrow_down{ - i{ - padding-top: 8px; - } - } -} \ No newline at end of file diff --git a/client/core/src/components/multi-check/multi-check.spec.js b/client/core/src/components/multi-check/multi-check.spec.js deleted file mode 100644 index a221e3cc7..000000000 --- a/client/core/src/components/multi-check/multi-check.spec.js +++ /dev/null @@ -1,163 +0,0 @@ -import './multi-check.js'; - -describe('Component vnMultiCheck', () => { - let $componentController; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject(_$componentController_ => { - $componentController = _$componentController_; - controller = $componentController('vnMultiCheck', {}); - })); - - describe('models()', () => { - it(`should set controller _models property with the argument received`, () => { - let argument = 'I am the model'; - controller.models = argument; - - expect(controller._models).toEqual(argument); - }); - }); - - describe('checkAll()', () => { - it(`should set controller _checkAll property with the argument received then call switchChecks()`, () => { - let argument = 'I am the model'; - spyOn(controller, 'switchChecks'); - controller.checkAll = argument; - - expect(controller._checkAll).toEqual(argument); - expect(controller.switchChecks).toHaveBeenCalledWith(); - }); - }); - - describe('switchChecks()', () => { - it(`should set checked property inside each existing elemenet when id begings with no-`, () => { - controller.type = {id: 'no-name'}; - controller.models = [ - {name: 'name'}, - {name: null} - ]; - - expect(controller._models[0].checked).not.toBeDefined(); - expect(controller._models[1].checked).not.toBeDefined(); - controller._checkAll = 1; - controller.switchChecks(); - - expect(controller._models[0].checked).toBeTruthy(); - expect(controller._models[1].checked).toBeTruthy(); - }); - - it(`should set checked property inside each existing elemenet when id begings with equal-`, () => { - controller.type = {id: 'equal-name', name: 'name'}; - controller.models = [ - {name: null}, - {name: 'name'} - ]; - - expect(controller._models[0].checked).not.toBeDefined(); - expect(controller._models[1].checked).not.toBeDefined(); - controller._checkAll = 1; - controller.switchChecks(); - - expect(controller._models[0].checked).toBeTruthy(); - expect(controller._models[1].checked).toBeTruthy(); - }); - - it(`should set checked property inside each existing elemenet when begings with anything but any, all, no- or equal-`, () => { - controller.type = {id: 'name'}; - controller.models = [ - {name: null}, - {name: 'name'} - ]; - - expect(controller._models[0].checked).not.toBeDefined(); - expect(controller._models[1].checked).not.toBeDefined(); - controller._checkAll = 1; - controller.switchChecks(); - - expect(controller._models[0].checked).toBeTruthy(); - expect(controller._models[1].checked).toBeTruthy(); - }); - - describe('when id is any', () => { - it('should set element checked property based on controller._checkAll', () => { - controller.type = {id: 'any'}; - controller.models = [ - {name: 'name'} - ]; - - expect(controller._models[0].checked).not.toBeDefined(); - controller._checkAll = 1; - controller.switchChecks(); - - expect(controller._models[0].checked).toBeTruthy(); - controller._checkAll = 0; - controller.switchChecks(); - - expect(controller._models[0].checked).toBeFalsy(); - controller._checkAll = 2; - controller.switchChecks(); - - expect(controller._models[0].checked).toBeFalsy(); - }); - }); - - describe('when id is all', () => { - it('should set element checked property based on controller._checkAll property', () => { - controller.type = {id: 'all'}; - controller.models = [ - {name: 'name'} - ]; - - expect(controller._models[0].checked).not.toBeDefined(); - controller._checkAll = 1; - controller.switchChecks(); - - expect(controller._models[0].checked).toBeTruthy(); - controller._checkAll = 0; - controller.switchChecks(); - - expect(controller._models[0].checked).toBeFalsy(); - controller._checkAll = 2; - controller.switchChecks(); - - expect(controller._models[0].checked).toBeFalsy(); - }); - }); - }); - - describe('$onChanges()', () => { - it('should set controller.type to empty object and checkAll to zero', () => { - controller.type = {id: 'all'}; - controller._checkAll = 1; - controller.$onChanges(); - - expect(controller.type).toEqual({}); - expect(controller._checkAll).toEqual(0); - }); - }); - - describe('type setter', () => { - it('should set controller.type to empty object and checkAll based on controller.type.id', () => { - let value = {id: 'all'}; - controller._checkAll = 0; - controller.type = value; - - expect(controller.type).toEqual({}); - expect(controller._checkAll).toEqual(1); - value = {id: 'any'}; - controller.type = value; - - expect(controller.type).toEqual({}); - expect(controller._checkAll).toEqual(0); - value = {id: 'any other id name'}; - controller.type = value; - - expect(controller.type).toEqual({}); - expect(controller._checkAll).toEqual(2); - }); - }); -}); diff --git a/client/core/src/components/paging/paging.html b/client/core/src/components/paging/paging.html deleted file mode 100644 index 6e71f321d..000000000 --- a/client/core/src/components/paging/paging.html +++ /dev/null @@ -1,11 +0,0 @@ - - \ No newline at end of file diff --git a/client/core/src/components/paging/paging.js b/client/core/src/components/paging/paging.js deleted file mode 100644 index 850b9c722..000000000 --- a/client/core/src/components/paging/paging.js +++ /dev/null @@ -1,58 +0,0 @@ -import ngModule from '../../module'; -import './style.scss'; - -export default class Paging { - get numPages() { - return Math.ceil(this.numItems / this.numPerPage); - } - - constructor($http, $scope) { - this.$http = $http; - this.$scope = $scope; - this.where = this.filter; - this.numPerPage = null; - this.numItems = 0; - $scope.$watch('$ctrl.index.model.length', () => this.onModelUpdated()); - } - - $onChanges(changes) { - if (!this.index) return; - this.numPerPage = this.index.filter.size; - this.currentPage = this.index.filter.page; - if (changes.total) - this.numItems = changes.total.currentValue; - } - - onModelUpdated() { - let index = this.index; - let filter = index.filter; - - if (filter.page >= this.numPages && index.model.length >= this.numPerPage) - this.numItems = filter.page * filter.size + 1; - } - - onPageChange(page) { - this.index.filter.page = page; - if (typeof this.pageChange === 'undefined') { - this.index.accept(); - } else { - this.pageChange(); - } - } - $doCheck() { - if (this.index && this.index.filter && this.index.filter.page && this.index.filter.page != this.currentPage) { - this.currentPage = this.index.filter.page; - } - } -} -Paging.$inject = ['$http', '$scope']; - -ngModule.component('vnPaging', { - template: require('./paging.html'), - bindings: { - index: '<', - pageChange: '&?', - total: '<' - }, - controller: Paging -}); diff --git a/client/core/src/components/paging/paging.spec.js b/client/core/src/components/paging/paging.spec.js deleted file mode 100644 index ab36635d5..000000000 --- a/client/core/src/components/paging/paging.spec.js +++ /dev/null @@ -1,69 +0,0 @@ -import './paging.js'; - -describe('Component vnPaging', () => { - let $componentController; - let $scope; - let $httpBackend; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_) => { - $componentController = _$componentController_; - $scope = $rootScope.$new(); - $httpBackend = _$httpBackend_; - controller = $componentController('vnPaging', {$scope, $httpBackend}); - })); - - describe('$onChanges()', () => { - it(`should define numberPage and currentPage based on index.filter properties`, () => { - controller.index = {filter: {size: 'something', page: 'something else'}}; - controller.$onChanges({index: 'simpleChange', currentValue: 'current value', previousValue: 'previous value'}); - - expect(controller.numPerPage).toBe(controller.index.filter.size); - expect(controller.currentPage).toEqual(controller.index.filter.page); - }); - - it(`should define numItems based on changes.total.currentValue`, () => { - controller.index = {filter: {size: 'something', page: 'something else'}}; - controller.$onChanges({total: {currentValue: 'current value'}}); - - expect(controller.numItems).toEqual('current value'); - }); - }); - - describe('onModelUpdated()', () => { - it(`should define controllers numItems as the result of page times size plus one`, () => { - controller.numPerPage = 2; - controller.index = { - filter: {size: 10, page: 10}, - model: ['one mother..', 'another model..', 'last model..'] - }; - controller.onModelUpdated(); - - expect(controller.numItems).toBe(101); - }); - }); - - describe('onPageChange()', () => { - it(`should call accept() since pageChange property is undefined`, () => { - controller.index = {accept: () => {}, filter: {page: 0}}; - spyOn(controller.index, 'accept'); - controller.onPageChange(100); - - expect(controller.index.accept).toHaveBeenCalledWith(); - }); - - it(`should call pageChange() since pageChange property isn't undefined`, () => { - controller.index = {accept: () => {}, filter: {page: 0}}; - controller.pageChange = true; - spyOn(controller, 'pageChange'); - controller.onPageChange(100); - - expect(controller.pageChange).toHaveBeenCalledWith(); - }); - }); -}); - diff --git a/client/core/src/components/paging/style.scss b/client/core/src/components/paging/style.scss deleted file mode 100644 index f52828dc1..000000000 --- a/client/core/src/components/paging/style.scss +++ /dev/null @@ -1,38 +0,0 @@ -vn-paging { - display: block; - text-align: center; - - ul { - box-shadow: 0 0 .4em rgba(1,1,1,.4); - background-color: #fff; - display: inline-block; - margin: 20px 0; - border-radius: .1em; - padding: 0; - } - li { - display: inline; - - &:first-child > a, - &:first-child > span { - margin-left: 0; - } - &.active > a { - background: #3c393b; - color: #fff; - } - & > a, - & > span { - position: relative; - float: left; - padding: 6px 12px; - margin-left: -1px; - line-height: 1.42857143; - color: inherit; - text-decoration: none; - } - &:not(.active) > a:hover { - background-color: #ddd; - } - } -} diff --git a/client/core/src/components/popover/popover.html b/client/core/src/components/popover/popover.html deleted file mode 100644 index 3e3e6ca59..000000000 --- a/client/core/src/components/popover/popover.html +++ /dev/null @@ -1,4 +0,0 @@ -
-
-
-
\ No newline at end of file diff --git a/client/core/src/components/popover/popover.js b/client/core/src/components/popover/popover.js deleted file mode 100644 index 4e2326c77..000000000 --- a/client/core/src/components/popover/popover.js +++ /dev/null @@ -1,223 +0,0 @@ -import ngModule from '../../module'; -import Component from '../../lib/component'; -import './style.scss'; - -/** - * A simple popover. - */ -export default class Popover extends Component { - constructor($element, $scope, $timeout, $transitions) { - super($element, $scope); - this.$timeout = $timeout; - this.$transitions = $transitions; - this._shown = false; - } - - $postLink() { - this.$element.addClass('vn-popover'); - - this.docKeyDownHandler = e => this.onDocKeyDown(e); - this.docFocusInHandler = e => this.onDocFocusIn(e); - - this.element.addEventListener('mousedown', - e => this.onBackgroundMouseDown(e)); - this.element.addEventListener('focusin', - e => this.onFocusIn(e)); - - this.popover = this.element.querySelector('.popover'); - this.popover.addEventListener('mousedown', - e => this.onMouseDown(e)); - - this.arrow = this.element.querySelector('.arrow'); - this.content = this.element.querySelector('.content'); - } - - set child(value) { - this.content.appendChild(value); - } - - get child() { - return this.content.firstChild; - } - - get shown() { - return this._shown; - } - - set shown(value) { - if (value) - this.show(); - else - this.hide(); - } - - /** - * Shows the popover. If a parent is specified it is shown in a visible - * relative position to it. - */ - show() { - if (this._shown) return; - - this._shown = true; - this.element.style.display = 'block'; - this.$timeout.cancel(this.showTimeout); - this.showTimeout = this.$timeout(() => { - this.$element.addClass('shown'); - this.showTimeout = null; - }, 30); - - this.document.addEventListener('keydown', this.docKeyDownHandler); - this.document.addEventListener('focusin', this.docFocusInHandler); - - this.deregisterCallback = this.$transitions.onStart({}, () => this.hide()); - this.relocate(); - - if (this.onOpen) - this.onOpen(); - } - - /** - * Hides the popover. - */ - hide() { - if (!this._shown) return; - - this._shown = false; - this.$element.removeClass('shown'); - this.$timeout.cancel(this.showTimeout); - this.showTimeout = this.$timeout(() => { - this.element.style.display = 'none'; - this.showTimeout = null; - }, 250); - - this.document.removeEventListener('keydown', this.docKeyDownHandler); - this.document.removeEventListener('focusin', this.docFocusInHandler); - - if (this.deregisterCallback) - this.deregisterCallback(); - - if (this.parent) - this.parent.focus(); - - if (this.onClose) - this.onClose(); - } - - /** - * Repositions the popover to a correct location relative to the parent. - */ - relocate() { - if (!(this.parent && this._shown)) return; - - let style = this.popover.style; - style.width = ''; - style.height = ''; - - let arrowStyle = this.arrow.style; - arrowStyle.top = ''; - arrowStyle.bottom = ''; - - let parentRect = this.parent.getBoundingClientRect(); - let popoverRect = this.popover.getBoundingClientRect(); - let arrowRect = this.arrow.getBoundingClientRect(); - - let arrowHeight = Math.sqrt(Math.pow(arrowRect.height, 2) * 2) / 2; - - let top = parentRect.top + parentRect.height + arrowHeight; - let left = parentRect.left; - let height = popoverRect.height; - let width = Math.max(popoverRect.width, parentRect.width); - - let margin = 10; - let showTop = top + height + margin > window.innerHeight; - - if (showTop) - top = Math.max(parentRect.top - height - arrowHeight, margin); - if (left + width + margin > window.innerWidth) - left = window.innerWidth - width - margin; - - if (showTop) - arrowStyle.bottom = `0`; - else - arrowStyle.top = `0`; - - arrowStyle.left = `${(parentRect.left - left) + parentRect.width / 2}px`; - - style.top = `${top}px`; - style.left = `${left}px`; - style.width = `${width}px`; - - if (height + margin * 2 + arrowHeight > window.innerHeight) - style.height = `${window.innerHeight - margin * 2 - arrowHeight}px`; - } - - onDocKeyDown(event) { - if (event.defaultPrevented) return; - - if (event.keyCode == 27) { // Esc - event.preventDefault(); - this.hide(); - } - } - - onMouseDown(event) { - this.lastMouseEvent = event; - } - - onBackgroundMouseDown(event) { - if (event != this.lastMouseEvent) - this.hide(); - } - - onFocusIn(event) { - this.lastFocusEvent = event; - } - - onDocFocusIn(event) { - if (event !== this.lastFocusEvent) - this.hide(); - } -} -Popover.$inject = ['$element', '$scope', '$timeout', '$transitions']; - -ngModule.component('vnPopover', { - template: require('./popover.html'), - controller: Popover, - transclude: true, - bindings: { - onOpen: '&?', - onClose: '&?' - } -}); - -class PopoverService { - constructor($document, $compile, $transitions, $rootScope) { - this.$compile = $compile; - this.$rootScope = $rootScope; - this.$document = $document; - this.stack = []; - } - show(child, parent, $scope) { - let element = this.$compile('')($scope || this.$rootScope)[0]; - let popover = element.$ctrl; - popover.parent = parent; - popover.child = child; - popover.show(); - popover.onClose = () => { - this.$document[0].body.removeChild(element); - if ($scope) $scope.$destroy(); - }; - this.$document[0].body.appendChild(element); - return popover; - } - - showComponent(componentTag, $scope, parent) { - let $newScope = $scope.$new(); - let childElement = this.$compile(`<${componentTag}/>`)($newScope)[0]; - this.show(childElement, parent, $newScope); - return childElement; - } -} -PopoverService.$inject = ['$document', '$compile', '$transitions', '$rootScope']; - -ngModule.service('vnPopover', PopoverService); diff --git a/client/core/src/components/popover/style.scss b/client/core/src/components/popover/style.scss deleted file mode 100644 index 458a47df9..000000000 --- a/client/core/src/components/popover/style.scss +++ /dev/null @@ -1,43 +0,0 @@ -.vn-popover { - display: none; - z-index: 10; - position: fixed; - top: 0; - left: 0; - right: 0; - bottom: 0; - - opacity: 0; - transform: translateY(-.6em); - transition-property: opacity, transform; - transition-duration: 200ms; - transition-timing-function: ease-in-out; - - &.shown { - transform: translateY(0); - opacity: 1; - } - & > .popover { - position: absolute; - display: flex; - box-shadow: 0 .1em .4em rgba(1, 1, 1, .4); - - & > .arrow { - width: 1em; - height: 1em; - margin: -.5em; - background-color: white; - box-shadow: 0 .1em .4em rgba(1, 1, 1, .4); - position: absolute; - transform: rotate(45deg); - z-index: 0; - } - & > .content { - width: 100%; - border-radius: .1em; - overflow: auto; - background-color: white; - z-index: 1; - } - } -} \ No newline at end of file diff --git a/client/core/src/components/radio/radio.html b/client/core/src/components/radio/radio.html deleted file mode 100644 index 887a97c04..000000000 --- a/client/core/src/components/radio/radio.html +++ /dev/null @@ -1,7 +0,0 @@ - -*[text]* diff --git a/client/core/src/components/radio/radio.js b/client/core/src/components/radio/radio.js deleted file mode 100644 index 70dbc059d..000000000 --- a/client/core/src/components/radio/radio.js +++ /dev/null @@ -1,15 +0,0 @@ -import ngModule from '../../module'; -import template from './radio.html'; - -directive.$inject = ['vnTemplate']; -export default function directive(vnTemplate) { - return { - restrict: 'E', - template: (_, $attrs) => - vnTemplate.get(template, $attrs, { - enabled: 'true', - className: 'mdl-radio mdl-js-radio mdl-js-ripple-effect' - }) - }; -} -ngModule.directive('vnRadio', directive); diff --git a/client/core/src/components/snackbar/snackbar.html b/client/core/src/components/snackbar/snackbar.html deleted file mode 100644 index 60eff1e46..000000000 --- a/client/core/src/components/snackbar/snackbar.html +++ /dev/null @@ -1,4 +0,0 @@ -
- -
-
diff --git a/client/core/src/components/snackbar/snackbar.js b/client/core/src/components/snackbar/snackbar.js deleted file mode 100644 index 387442f83..000000000 --- a/client/core/src/components/snackbar/snackbar.js +++ /dev/null @@ -1,99 +0,0 @@ -import ngModule from '../../module'; -import Component from '../../lib/component'; -import './style.scss'; - -/** - * A simple component to show non-obstructive notifications to the user. - */ -export default class Controller extends Component { - constructor($element, $translate) { - super($element); - this.$translate = $translate; - this.shown = false; - this.snackbar = $element[0].firstChild; - this.$snackbar = angular.element(this.snackbar); - this.button = $element[0].querySelector('button'); - this.textNode = this.snackbar.querySelector('.text'); - } - - /** - * Shows a notification. - * - * @param {Object} data The message data - */ - show(data) { - this.clearTimeouts(); - this.shown = true; - this.textNode.textContent = data.message; - this.actionHandler = data.actionHandler; - - this.button.textContent = - data.actionText || this.$translate.instant('Hide'); - - this.timeoutId = setTimeout(() => - this.hide(), data.timeout || 6000); - - this.transitionTimeout = setTimeout(() => - this.$snackbar.addClass('shown'), 30); - } - - /** - * Shows an error. - * - * @param {Object} data The message data - */ - showError(data) { - this.$snackbar.addClass('error'); - this.show(data); - } - - /** - * Hides the snackbar. - */ - hide() { - if (!this.shown) return; - clearTimeout(this.timeoutId); - this.shown = false; - this.hideTimeout = setTimeout(() => this.onTransitionEnd(), 250); - - this.transitionTimeout = - setTimeout(() => this.$snackbar.removeClass('shown'), 30); - } - - onTransitionEnd() { - this.$snackbar.removeClass('error'); - this.textNode.textContent = ''; - this.button.textContent = ''; - this.actionHandler = null; - } - - onSnackbarClick(event) { - this.event = event; - } - - onButtonClick() { - if (this.actionHandler) - this.actionHandler(); - else - this.hide(); - } - - clearTimeouts() { - clearTimeout(this.timeoutId); - clearTimeout(this.hideTimeout); - clearTimeout(this.transitionTimeout); - this.timeoutId = null; - this.hideTimeout = null; - this.transitionTimeout = null; - } - - $onDestroy() { - this.clearTimeouts(); - } -} -Controller.$inject = ['$element', '$translate']; - -ngModule.component('vnSnackbar', { - template: require('./snackbar.html'), - controller: Controller -}); diff --git a/client/core/src/components/snackbar/style.scss b/client/core/src/components/snackbar/style.scss deleted file mode 100644 index 513280243..000000000 --- a/client/core/src/components/snackbar/style.scss +++ /dev/null @@ -1,48 +0,0 @@ -vn-snackbar > div { - box-sizing: border-box; - background-color: #333; - color: white; - position: fixed; - bottom: 0; - left: 50%; - width: 20em; - margin-left: -10em; - padding: 1em; - border-top-left-radius: .2em; - border-top-right-radius: .2em; - transform: translateY(10em); - transition: transform 300ms ease-in-out; - z-index: 100; - box-shadow: 0 0 .4em rgba(1,1,1,.4); - - &.shown { - transform: translateY(0); - } - &.notice { - background-color: #1e88e5; - - & > button { - color: rgba(1, 1, 1, 0.6); - } - } - &.error { - background-color: #c62828; - - & > button { - color: rgba(1, 1, 1, 0.6); - } - } - & > button { - cursor: pointer; - float: right; - text-transform: uppercase; - border: none; - background-color: transparent; - font-weight: bold; - color: #ffab40; - padding: 1em; - margin: -1em; - padding-left: 1.5em; - margin-left: 0; - } -} \ No newline at end of file diff --git a/client/core/src/components/spinner/spinner.html b/client/core/src/components/spinner/spinner.html deleted file mode 100644 index 47b6e42fe..000000000 --- a/client/core/src/components/spinner/spinner.html +++ /dev/null @@ -1,2 +0,0 @@ -
-
\ No newline at end of file diff --git a/client/core/src/components/spinner/spinner.spec.js b/client/core/src/components/spinner/spinner.spec.js deleted file mode 100644 index d5bad0746..000000000 --- a/client/core/src/components/spinner/spinner.spec.js +++ /dev/null @@ -1,63 +0,0 @@ -import './spinner.js'; - -describe('Component vnSpinner', () => { - let $componentController; - let $scope; - let $element; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope) => { - $componentController = _$componentController_; - $scope = $rootScope.$new(); - $element = angular.element('
'); - controller = $componentController('vnSpinner', {$scope, $element}); - })); - - describe('enable()', () => { - it(`should call start() based on a boolean value passed as argument`, () => { - spyOn(controller, 'start'); - spyOn(controller, 'stop'); - controller.enable = true; - - expect(controller.start).toHaveBeenCalledWith(); - expect(controller.stop).not.toHaveBeenCalledWith(); - }); - - it(`should call stop() based on a boolean value passed as argument`, () => { - spyOn(controller, 'start'); - spyOn(controller, 'stop'); - controller.enable = false; - - expect(controller.start).not.toHaveBeenCalledWith(); - expect(controller.stop).toHaveBeenCalledWith(); - }); - }); - - describe('start()', () => { - it(`should call start() on the controller.materialSpinner then set controllers._enable to be truthy`, () => { - controller.spinner = {MaterialSpinner: {start: () => {}}}; - spyOn(controller.spinner.MaterialSpinner, 'start'); - controller._enable = false; - controller.start(); - - expect(controller.spinner.MaterialSpinner.start).toHaveBeenCalledWith(); - expect(controller._enable).toBeTruthy(); - }); - }); - - describe('stop()', () => { - it(`should call stop() on the controller.materialSpinner then set controllers._enable to be truthy`, () => { - controller.spinner = {MaterialSpinner: {stop: () => {}}}; - spyOn(controller.spinner.MaterialSpinner, 'stop'); - controller._enable = true; - controller.stop(); - - expect(controller.spinner.MaterialSpinner.stop).toHaveBeenCalledWith(); - expect(controller._enable).toBeFalsy(); - }); - }); -}); diff --git a/client/core/src/components/spinner/style.css b/client/core/src/components/spinner/style.css deleted file mode 100644 index fbcd1a0bf..000000000 --- a/client/core/src/components/spinner/style.css +++ /dev/null @@ -1,3 +0,0 @@ -vn-spinner { - display: inline-block; -} \ No newline at end of file diff --git a/client/core/src/components/submit/submit.html b/client/core/src/components/submit/submit.html deleted file mode 100644 index 378920de0..000000000 --- a/client/core/src/components/submit/submit.html +++ /dev/null @@ -1,7 +0,0 @@ - - diff --git a/client/core/src/components/submit/submit.js b/client/core/src/components/submit/submit.js deleted file mode 100644 index 6eb67dea8..000000000 --- a/client/core/src/components/submit/submit.js +++ /dev/null @@ -1,16 +0,0 @@ -import ngModule from '../../module'; -import template from './submit.html'; - -directive.$inject = ['vnTemplate']; -export default function directive(vnTemplate) { - return { - restrict: 'E', - template: (_, $attrs) => - vnTemplate.get(template, $attrs, { - label: 'Submit', - className: 'mdl-button mdl-js-button mdl-button--raised mdl-button--colored', - enabled: 'true' - }) - }; -} -ngModule.directive('vnSubmit', directive); diff --git a/client/core/src/components/subtitle/subtitle.html b/client/core/src/components/subtitle/subtitle.html deleted file mode 100644 index ac00ac0c2..000000000 --- a/client/core/src/components/subtitle/subtitle.html +++ /dev/null @@ -1,2 +0,0 @@ -
-
\ No newline at end of file diff --git a/client/core/src/components/switch/switch.html b/client/core/src/components/switch/switch.html deleted file mode 100644 index 5b6e08ca3..000000000 --- a/client/core/src/components/switch/switch.html +++ /dev/null @@ -1,4 +0,0 @@ - \ No newline at end of file diff --git a/client/core/src/components/switch/switch.js b/client/core/src/components/switch/switch.js deleted file mode 100644 index c86d6f665..000000000 --- a/client/core/src/components/switch/switch.js +++ /dev/null @@ -1,26 +0,0 @@ -import ngModule from '../../module'; - -directive.$inject = ['vnTemplate']; -export default function directive(vnTemplate) { - return { - restrict: 'E', - template: (_, $attrs) => - vnTemplate.getNormalized(template, $attrs, { - className: 'mdl-switch__input', - label: '' - }), - link: function(scope, element, attrs) { - scope.$watch(attrs.model, () => { - let mdlField = element[0].firstChild.MaterialSwitch; - if (mdlField) - mdlField.updateClasses_(); - }); - componentHandler.upgradeElement(element[0].firstChild); - } - }; -} -ngModule.directive('vnSwitch', directive); - -export function factory() { -} -ngModule.factory('vnSwitchMdlFactory', factory); diff --git a/client/core/src/components/textarea/style.scss b/client/core/src/components/textarea/style.scss deleted file mode 100644 index 91b29b3cf..000000000 --- a/client/core/src/components/textarea/style.scss +++ /dev/null @@ -1,6 +0,0 @@ -vn-textarea { - & > .mdl-textfield { - width: initial; - display: block; - } -} \ No newline at end of file diff --git a/client/core/src/components/textarea/textarea.html b/client/core/src/components/textarea/textarea.html deleted file mode 100644 index 04102cd5e..000000000 --- a/client/core/src/components/textarea/textarea.html +++ /dev/null @@ -1,10 +0,0 @@ -
- - -
\ No newline at end of file diff --git a/client/core/src/components/textarea/textarea.js b/client/core/src/components/textarea/textarea.js deleted file mode 100644 index 122259ff3..000000000 --- a/client/core/src/components/textarea/textarea.js +++ /dev/null @@ -1,24 +0,0 @@ -import ngModule from '../../module'; -import template from './textarea.html'; -import './style.scss'; - -directive.$inject = ['vnTemplate']; -export function directive(vnTemplate) { - return { - restrict: 'E', - template: (_, $attrs) => - vnTemplate.getNormalized(template, $attrs, { - label: '', - rows: 3 - }), - link: function(scope, element, attrs) { - scope.$watch(attrs.model, () => { - let mdlField = element[0].firstChild.MaterialTextfield; - if (mdlField) - mdlField.updateClasses_(); - }); - componentHandler.upgradeElement(element[0].firstChild); - } - }; -} -ngModule.directive('vnTextarea', directive); diff --git a/client/core/src/components/textfield/style.scss b/client/core/src/components/textfield/style.scss deleted file mode 100644 index 181ad8d8b..000000000 --- a/client/core/src/components/textfield/style.scss +++ /dev/null @@ -1,45 +0,0 @@ -vn-textfield { - .mdl-chip__action { - position: absolute; - width: auto; - top: 0px; - right: -6px; - margin: 21px 0px; - background: white; - opacity: 1; - z-index: 1; - color: #aaa; - } - .mdl-textfield { - width: 100%; - } - .mdl-textfield__error { - visibility: visible; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - width: 100%; - } - .mdl-textfield.invalid { - .mdl-textfield__input { - border-color: #d50000; - box-shadow: none; - } - .mdl-textfield__label::after { - background-color: #d50000; - } - } - .mdl-textfield--floating-label.invalid .mdl-textfield__label { - color: #d50000; - font-size: 12px; - top: 4px; - } - .material-icons { - font-size: 18px; - float: right; - margin-right: 5px; - } - .material-icons:hover { - color: rgba(0,0,0, .87); - } -} \ No newline at end of file diff --git a/client/core/src/components/textfield/textfield.html b/client/core/src/components/textfield/textfield.html deleted file mode 100644 index 43599186b..000000000 --- a/client/core/src/components/textfield/textfield.html +++ /dev/null @@ -1,29 +0,0 @@ -
- -
- - info_outline - - - clear - -
- -
diff --git a/client/core/src/components/textfield/textfield.js b/client/core/src/components/textfield/textfield.js deleted file mode 100644 index feb5b98a9..000000000 --- a/client/core/src/components/textfield/textfield.js +++ /dev/null @@ -1,54 +0,0 @@ -import ngModule from '../../module'; -import Input from '../../lib/input'; -import './style.scss'; - -export default class Textfield extends Input { - constructor($element, $scope, $attrs, vnTemplate) { - super($element, $scope); - vnTemplate.normalizeInputAttrs($attrs); - this._value = null; - this.type = $attrs.type || 'text'; - this.showActions = false; - this.hasInfo = Boolean($attrs.info); - this.info = $attrs.info || null; - this.hasFocus = false; - this.hasMouseIn = false; - componentHandler.upgradeElement($element[0].firstChild); - } - get value() { - return this._value; - } - set value(value) { - this._value = (value === undefined || value === '') ? null : value; - this.input.value = this._value; - this.hasValue = Boolean(this._value); - this.mdlUpdate(); - } - set tabIndex(value) { - this.input.tabIndex = value; - } - clear() { - this.value = null; - this.input.focus(); - } - mdlUpdate() { - let mdlElement = this.element.firstChild.MaterialTextfield; - if (mdlElement) mdlElement.updateClasses_(); - } -} -Textfield.$inject = ['$element', '$scope', '$attrs', 'vnTemplate']; - -ngModule.component('vnTextfield', { - template: require('./textfield.html'), - controller: Textfield, - bindings: { - value: '=model', - label: '@?', - name: '@?', - disabled: ' { - let $componentController; - let $scope; - let $attrs; - let $timeout; - let $element; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_, _$timeout_) => { - $componentController = _$componentController_; - $scope = $rootScope.$new(); - $attrs = {}; - $timeout = _$timeout_; - $element = angular.element('
'); - controller = $componentController('vnTextfield', {$scope, $element, $attrs, $timeout}); - })); - - describe('value() setter', () => { - it(`should set _value, input.value and hasValue properties to null, '' and false then call mdlUpdate()`, () => { - spyOn(controller, 'mdlUpdate'); - let testValue = ''; - controller.value = testValue; - - expect(controller._value).toEqual(null); - expect(controller.input.value).toEqual(testValue); - expect(controller.hasValue).toEqual(Boolean(testValue)); - expect(controller.mdlUpdate).toHaveBeenCalledWith(); - }); - - it(`should set _value, input.value and hasValue propertiest to test, test and true then call mdlUpdate()`, () => { - spyOn(controller, 'mdlUpdate'); - let testValue = 'test'; - controller.value = testValue; - - expect(controller._value).toEqual(testValue); - expect(controller.input.value).toEqual(testValue); - expect(controller.hasValue).toEqual(Boolean(testValue)); - expect(controller.mdlUpdate).toHaveBeenCalledWith(); - }); - }); -}); diff --git a/client/core/src/components/title/title.html b/client/core/src/components/title/title.html deleted file mode 100644 index 773b40040..000000000 --- a/client/core/src/components/title/title.html +++ /dev/null @@ -1,3 +0,0 @@ -

- -

\ No newline at end of file diff --git a/client/core/src/components/tooltip/style.css b/client/core/src/components/tooltip/style.css deleted file mode 100644 index 0a5ca7e23..000000000 --- a/client/core/src/components/tooltip/style.css +++ /dev/null @@ -1,60 +0,0 @@ -.tooltip { - display: none; - position: fixed; - background-color: #fff; - padding: 20px; - color: #424242; - z-index: 999; - border: 1px solid #A7A7A7; - text-align: justify; -} - -.tooltip-show { - display: inherit; -} - -.tooltip-arrow { - position: absolute; - width: 0; - height: 0; -} - -.tooltip-text{ - max-width: 320px; -} - -.tooltip-down .tooltip-arrow { - top: -15px; - left: 50%; - margin-left: -10px; - border-left: 10px solid transparent; - border-right: 10px solid transparent; - border-bottom: 15px solid #A7A7A7; -} - -.tooltip-up .tooltip-arrow { - bottom: -15px; - left: 50%; - margin-left: -10px; - border-left: 10px solid transparent; - border-right: 10px solid transparent; - border-top: 15px solid #A7A7A7; -} - -.tooltip-right .tooltip-arrow { - left: -15px; - top: 50%; - margin-top: -10px; - border-top: 10px solid transparent; - border-bottom: 10px solid transparent; - border-right: 15px solid #A7A7A7; -} - -.tooltip-left .tooltip-arrow { - right: -15px; - top: 50%; - margin-top: -10px; - border-top: 10px solid transparent; - border-bottom: 10px solid transparent; - border-left: 15px solid #A7A7A7; -} diff --git a/client/core/src/components/tooltip/tooltip.js b/client/core/src/components/tooltip/tooltip.js deleted file mode 100644 index 052e30267..000000000 --- a/client/core/src/components/tooltip/tooltip.js +++ /dev/null @@ -1,159 +0,0 @@ -import ngModule from '../../module'; -import './style.css'; - -tooltip.$inject = ['$document', '$compile', '$interpolate', '$sce', '$templateCache', '$http', '$q']; -function tooltip($document, $compile, $interpolate, $sce, $templateCache, $http, $q) { - var promise; - - function _getTemplate(tooltipTemplateUrl) { - var template = $templateCache.get(tooltipTemplateUrl); - if (typeof template === 'undefined') { - template = $http.get(tooltipTemplateUrl).then(function onGetTemplateSuccess(response) { - if (promise) { - promise.resolve(response.data); - } - promise = undefined; - return response.data; - }); - $templateCache.put(tooltipTemplateUrl, template); - } - return template; - } - - function getTemplate(tooltipTemplateUrl) { - var _promise = $q.defer(); - var template = _getTemplate(tooltipTemplateUrl); - if (template) { - _promise.resolve(template); - } else { - promise = _promise; - } - return _promise.promise; - } - - return { - restrict: 'A', - priority: -1, - link: function($scope, element, attrs) { - let tipHtml = '
{{::text}}
'; - let tip; - let tipClassName = 'tooltip'; - let tipActiveClassName = 'tooltip-show'; - let scope = $scope.$new(); - - scope.tipClass = [tipClassName]; - scope.text = attrs.vnTooltip || ''; - - if (attrs.tooltipHtml) { - scope.isHtmlContent = true; - scope.htmlContent = $sce.trustAsHtml(attrs.tooltipHtml); - _compileTip(); - } else if (attrs.tooltipTemplate) { - getTemplate(attrs.tooltipTemplate).then(template => { - scope.isHtmlContent = true; - scope.htmlContent = $sce.trustAsHtml($interpolate(template)(scope)); - _compileTip(); - }); - } else { - scope.isHtmlContent = false; - scope.htmlContent = null; - _compileTip(); - } - - if (attrs.tooltipPosition) { - scope.tipClass.push('tooltip-' + attrs.tooltipPosition); - } else { - scope.tipClass.push('tooltip-down'); - } - - function _compileTip() { - tip = $compile(tipHtml)(scope); - $document.find('body').append(tip); - _bindEvents(); - } - - function _bindEvents() { - element.bind('mouseover', function(e) { - _showTooltip(e); - }); - - element.on('mouseout', function() { - _hideTooltip(); - }); - - tip.on('mouseover', function(e) { - _showTooltip(e); - }); - - tip.on('mouseout', function() { - _hideTooltip(); - }); - - element.on('$destroy', function() { - tip.remove(); - scope.$destroy(); - }); - } - - function _calculatePosition(e) { - let pos = element[0].getBoundingClientRect(); - let tipPos = tip[0].getBoundingClientRect(); - let offset = {top: 0, left: 0}; - let tipWidth = tipPos.width || tipPos.right - tipPos.left; - let tipHeight = tipPos.height || tipPos.bottom - tipPos.top; - let elWidth = pos.width || pos.right - pos.left; - let elHeight = pos.height || pos.bottom - pos.top; - let tipOffset = 10; - - if (tip.hasClass('tooltip-right')) { - offset.top = pos.top - (tipHeight / 2) + (elHeight / 2); - offset.left = pos.right + tipOffset; - } else if (tip.hasClass('tooltip-left')) { - offset.top = pos.top - (tipHeight / 2) + (elHeight / 2); - offset.left = pos.left - tipWidth - tipOffset; - } else if (tip.hasClass('tooltip-down')) { - offset.top = pos.top + elHeight + tipOffset; - offset.left = pos.left - (tipWidth / 2) + (elWidth / 2); - } else { - offset.top = pos.top - tipHeight - tipOffset; - offset.left = pos.left - (tipWidth / 2) + (elWidth / 2); - } - // outsides - if (offset.left + tipPos.width > window.innerWidth) { // right outside - let diffLeft = (offset.left + tipPos.width) - window.innerWidth; - offset.left -= diffLeft + 10; - - let arrow = tip[0].querySelector('.tooltip-arrow'); - if (arrow) { - angular.element(arrow).css('margin-left', diffLeft + 'px'); - } - } else if (offset.left < 10) { // left outside - offset.left = 10; - let arrow = tip[0].querySelector('.tooltip-arrow'); - if (arrow) { - angular.element(arrow).css('margin-left', '10px'); - } - } - if (offset.top > window.innerHeight) { // down outside - offset.top = pos.top - tipHeight - tipOffset; - } else if (offset.top < 10) { // top outside - offset.top = pos.top + elHeight + tipOffset; - } - - tip.css('top', offset.top + 'px'); - tip.css('left', offset.left + 'px'); - } - - function _showTooltip(e) { - tip.addClass(tipActiveClassName); - _calculatePosition(e); - } - - function _hideTooltip() { - tip.removeClass(tipActiveClassName); - } - } - }; -} - -ngModule.directive('vnTooltip', tooltip); diff --git a/client/core/src/components/watcher/watcher.html b/client/core/src/components/watcher/watcher.html deleted file mode 100644 index 76315ece8..000000000 --- a/client/core/src/components/watcher/watcher.html +++ /dev/null @@ -1,6 +0,0 @@ - - \ No newline at end of file diff --git a/client/core/src/components/watcher/watcher.js b/client/core/src/components/watcher/watcher.js deleted file mode 100644 index 7b5317ca4..000000000 --- a/client/core/src/components/watcher/watcher.js +++ /dev/null @@ -1,235 +0,0 @@ -import ngModule from '../../module'; -import Component from '../../lib/component'; -import getModifiedData from '../../lib/modified'; -import copyObject from '../../lib/copy'; -import isEqual from '../../lib/equals'; -import isFullEmpty from '../../lib/full-empty'; - -/** - * Component that checks for changes on a specific model property and - * asks the user to save or discard it when the state changes. - * Also it can save the data to the server when the @url and @idField - * properties are provided. - */ -export default class Watcher extends Component { - constructor($element, $scope, $state, $transitions, $http, vnApp, $translate, $attrs) { - super($element); - this.$scope = $scope; - this.$state = $state; - this.$http = $http; - this.$translate = $translate; - this.$attrs = $attrs; - this.vnApp = vnApp; - - this.state = null; - this.deregisterCallback = $transitions.onStart({}, - transition => this.callback(transition)); - this.updateOriginalData(); - } - - $onInit() { - if (this.get && this.url) { - this.fetchData(); - } else if (this.get && !this.url) { - throw new Error('Error: Parameter url ommitted'); - } - } - - $onChanges(changes) { - if (this.data) { - this.updateOriginalData(); - } - } - - $onDestroy() { - this.deregisterCallback(); - } - - fetchData() { - let id = this.data[this.idField]; - // return new Promise((resolve, reject) => { - this.$http.get(`${this.url}/${id}`).then( - json => { - this.data = copyObject(json.data); - this.updateOriginalData(); - } - // json => reject(json) - ); - // }); - } - - /** - * Submits the data and goes back in the history. - * - * @return {Promise} The request promise - */ - submitBack() { - return this.submit().then( - () => this.window.history.back() - ); - } - - /** - * Submits the data and goes another state. - * - * @param {String} state The state name - * @param {Object} params The request params - * @return {Promise} The request promise - */ - submitGo(state, params) { - return this.submit().then( - () => this.$state.go(state, params || {}) - ); - } - - /** - * Submits the data to the server. - * - * @return {Promise} The http request promise - */ - submit() { - if (this.form) { - this.form.$setSubmitted(); - - if (!this.form.$valid) - return new Promise( - (resolve, reject) => this.invalidForm(reject) - ); - } - if (!this.dataChanged()) { - return new Promise( - (resolve, reject) => this.noChanges(reject) - ); - } - let isPost = (this.$attrs.save && this.$attrs.save.toLowerCase() === 'post'); - let changedData = isPost - ? this.copyInNewObject(this.data) - : getModifiedData(this.data, this.orgData); - - if (this.requiredField && !changedData[this.requiredField]) { - let required = this.data[this.requiredField] || this.orgData[this.requiredField]; - if (required === undefined) { - return new Promise( - (resolve, reject) => this.invalidForm(reject) - ); - } - changedData[this.requiredField] = required; - } - - if (this.save && this.save.accept) { - this.save.model = changedData; // this.copyInNewObject(changedData); - return new Promise((resolve, reject) => { - this.save.accept().then( - json => this.writeData({data: json}, resolve), - json => reject(json) - ); - }); - } - - // XXX: Alternative when mgCrud is not used - - let id = this.idField ? this.orgData[this.idField] : null; - - if (id) { - return new Promise((resolve, reject) => { - this.$http.patch(`${this.url}/${id}`, changedData).then( - json => this.writeData(json, resolve), - json => reject(json) - ); - }); - } - - return new Promise((resolve, reject) => { - this.$http.post(this.url, changedData).then( - json => this.writeData(json, resolve), - json => reject(json) - ); - }); - } - - writeData(json, resolve) { - Object.assign(this.data, json.data); - this.updateOriginalData(); - resolve(json); - } - - noChanges(resolve) { - this.vnApp.showMessage( - this.$translate.instant('No changes to save') - ); - resolve(); - } - - invalidForm(resolve) { - this.vnApp.showMessage( - this.$translate.instant('Some fields are invalid') - ); - resolve(); - } - - updateOriginalData() { - this.orgData = this.copyInNewObject(this.data); - if (this.form && this.form.$dirty) - this.form.$setPristine(); - } - - copyInNewObject(data) { - let newCopy = {}; - if (data && typeof data === 'object') { - Object.keys(data).forEach( - val => { - if (!isFullEmpty(data[val])) { - if (typeof data[val] === 'object') { - newCopy[val] = this.copyInNewObject(data[val]); - } else { - newCopy[val] = data[val]; - } - } - } - ); - } - return newCopy; - } - - callback(transition) { - let dataChanged = this.dataChanged(); - if (!this.state && dataChanged) { - this.state = transition.to().name; - this.$scope.confirm.show(); - return false; - } - - return true; - } - - dataChanged() { - if (this.form && this.form.$dirty) return true; - let newData = this.copyInNewObject(this.data); - return !isEqual(newData, this.orgData); - } - - onConfirmResponse(response) { - if (response === 'ACCEPT') { - if (this.data) - Object.assign(this.data, this.orgData); - this.$state.go(this.state); - } else { - this.state = null; - } - } -} -Watcher.$inject = ['$element', '$scope', '$state', '$transitions', '$http', 'vnApp', '$translate', '$attrs']; - -ngModule.component('vnWatcher', { - template: require('./watcher.html'), - bindings: { - url: '@?', - idField: '@?', - requiredField: '@?', - data: '<', - form: '<', - save: '<', - get: '=?' - }, - controller: Watcher -}); diff --git a/client/core/src/components/watcher/watcher.spec.js b/client/core/src/components/watcher/watcher.spec.js deleted file mode 100644 index 88305c819..000000000 --- a/client/core/src/components/watcher/watcher.spec.js +++ /dev/null @@ -1,297 +0,0 @@ -import './watcher.js'; -import getModifiedData from '../../lib/modified'; - -describe('Component vnWatcher', () => { - let $componentController; - let $scope; - let $element; - let $state; - let $transitions; - let $httpBackend; - let vnApp; - let $translate; - let controller; - let $attrs; - - beforeEach(() => { - angular.mock.module('client'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$state_, _$transitions_, _$httpBackend_, _vnApp_, _$translate_) => { - $componentController = _$componentController_; - $scope = $rootScope.$new(); - $element = angular.element('
'); - $state = _$state_; - vnApp = _vnApp_; - $transitions = _$transitions_; - $httpBackend = _$httpBackend_; - $httpBackend.when('GET', /\/locale\/\w+\/[a-z]{2}\.json/).respond({}); - $translate = _$translate_; - $attrs = { - save: "patch" - }; - controller = $componentController('vnWatcher', {$scope, $element, $state, vnApp, $transitions, $httpBackend, $translate, $attrs}); - })); - - describe('$onInit()', () => { - it(`should call fetchData() if controllers get and url properties are defined`, () => { - controller.get = () => {}; - controller.url = 'test.com'; - spyOn(controller, 'fetchData'); - controller.$onInit(); - - expect(controller.fetchData).toHaveBeenCalledWith(); - }); - - it(`should throw an error if $onInit is called without url defined`, () => { - controller.get = () => {}; - - expect(function() { - controller.$onInit(); - }).toThrow(new Error('Error: Parameter url ommitted')); - }); - }); - - describe('$onChanges()', () => { - it(`should call updateOriginalData() if controllers data is defined`, () => { - controller.data = []; - spyOn(controller, 'updateOriginalData'); - controller.$onChanges(); - - expect(controller.updateOriginalData).toHaveBeenCalledWith(); - }); - }); - - describe('$onDestroy()', () => { - it(`should call deregisterCallback()`, () => { - spyOn(controller, 'deregisterCallback'); - controller.$onDestroy(); - - expect(controller.deregisterCallback).toHaveBeenCalledWith(); - }); - }); - - describe('fetchData()', () => { - it(`should perform a query then store the received data into controller.data and call updateOriginalData()`, () => { - spyOn(controller, 'updateOriginalData'); - let json = {data: 'some data'}; - controller.data = [1]; - controller.idField = 0; - controller.url = 'test.com'; - $httpBackend.whenGET('test.com/1').respond(json); - $httpBackend.expectGET('test.com/1'); - controller.fetchData(); - $httpBackend.flush(); - - expect(controller.data).toEqual({data: 'some data'}); - expect(controller.updateOriginalData).toHaveBeenCalledWith(); - }); - }); - - describe('submitBack()', () => { - it(`should call controller.window.history.back() function after calling controllers submit() function`, done => { - spyOn(controller, 'submit').and.returnValue(Promise.resolve()); - spyOn(controller.window.history, 'back'); - controller.submitBack() - .then(() => { - expect(controller.submit).toHaveBeenCalledWith(); - expect(controller.window.history.back).toHaveBeenCalledWith(); - done(); - }); - }); - }); - - describe('submitGo()', () => { - it(`should call controller.$state.go() function after calling controllers submit() function`, done => { - spyOn(controller, 'submit').and.returnValue(Promise.resolve()); - spyOn(controller.$state, 'go'); - let state = 'the.State'; - controller.submitGo(state) - .then(() => { - expect(controller.submit).toHaveBeenCalledWith(); - expect(controller.$state.go).toHaveBeenCalledWith(state, {}); - done(); - }); - }); - }); - - describe('submit()', () => { - describe('when controller.form', () => { - it(`should call controller.form.setSubminted if controller.form is defined`, () => { - controller.form = {$setSubmitted: () => {}}; - spyOn(controller.form, '$setSubmitted'); - controller.submit(); - - expect(controller.form.$setSubmitted).toHaveBeenCalledWith(); - }); - - it(`should call controller.invalidForm if controller.form.$valid is not defined`, () => { - controller.form = {$setSubmitted: () => {}}; - spyOn(controller, 'invalidForm'); - controller.submit(); - - expect(controller.invalidForm).toHaveBeenCalledWith(jasmine.any(Function)); - }); - }); - - describe('when !controller.dataChanged()', () => { - it(`should call controller.noChanges()`, () => { - spyOn(controller, 'noChanges'); - controller.submit(); - - expect(controller.noChanges).toHaveBeenCalledWith(jasmine.any(Function)); - }); - }); - - describe('when controller.save()', () => { - it(`should set controller.save.model property`, () => { - controller.save = {accept: () => {}}; - controller.data = {originalInfo: 'original data', info: 'new data'}; - controller.orgData = {originalInfo: 'original data'}; - controller.submit(); - - expect(controller.save.model).toEqual({info: 'new data'}); - }); - - it(`should call controller.save.accept() then controller.writeData`, done => { - controller.save = {accept: () => {}}; - controller.data = {originalInfo: 'original data', info: 'new data'}; - controller.orgData = {originalInfo: 'original data'}; - spyOn(controller.save, 'accept').and.returnValue(Promise.resolve()); - spyOn(controller, 'writeData').and.callThrough(); - controller.submit() - .then(() => { - expect(controller.save.accept).toHaveBeenCalledWith(); - expect(controller.writeData).toHaveBeenCalledWith(jasmine.any(Object), jasmine.any(Function)); - done(); - }); - }); - }); - - describe('when id is defined', () => { - it(`should perform a query then call controller.writeData()`, () => { - controller.dataChanged = () => { - return true; - }; - controller.data = {id: 2}; - controller.orgData = {id: 1}; - let changedData = getModifiedData(controller.data, controller.orgData); - controller.idField = 'id'; - controller.url = 'test.com'; - let json = {data: 'some data'}; - spyOn(controller, 'writeData').and.callThrough(); - $httpBackend.whenPATCH(`${controller.url}/1`, changedData).respond(json); - $httpBackend.expectPATCH(`${controller.url}/1`); - controller.submit() - .then(() => { - expect(controller.writeData).toHaveBeenCalledWith(jasmine.any(Object), jasmine.any(Function)); - done(); - }); - $httpBackend.flush(); - }); - }); - - it(`should perform a POST query then call controller.writeData()`, () => { - controller.dataChanged = () => { - return true; - }; - controller.data = {id: 2}; - controller.orgData = {id: 1}; - controller.url = 'test.com'; - let json = {data: 'some data'}; - spyOn(controller, 'writeData').and.callThrough(); - $httpBackend.whenPOST(`${controller.url}`, controller.data).respond(json); - $httpBackend.expectPOST(`${controller.url}`, controller.data); - controller.submit() - .then(() => { - expect(controller.writeData).toHaveBeenCalledWith(jasmine.any(Object), jasmine.any(Function)); - done(); - }); - $httpBackend.flush(); - }); - }); - - describe('writeData()', () => { - it(`should call Object.asssign() function over controllers.data with json.data, then call updateOriginalData function and finally call resolve() function`, () => { - spyOn(controller, 'updateOriginalData'); - controller.data = {}; - let json = {data: 'some data'}; - let resolve = jasmine.createSpy('resolve'); - controller.writeData(json, resolve); - - expect(controller.updateOriginalData).toHaveBeenCalledWith(); - expect(resolve).toHaveBeenCalledWith(json); - }); - }); - - describe('copyInNewObject()', () => { - it(`should return newCopy object if data was an object`, () => { - let data = {id: 1, Heroname: 'Batman', name: 'Bruce Wayne'}; - let result = controller.copyInNewObject(data); - - expect(result).toEqual(data); - }); - }); - - describe('callback()', () => { - describe(`when dataChanged() returns true and there's no state in the controller`, () => { - it(`should define controller.state, call controller.$scope.confirm.show() and return false`, () => { - $scope.confirm = {show: jasmine.createSpy('show')}; - controller.dataChanged = () => { - return true; - }; - controller.state = undefined; - let transition = {to: () => { - return {name: 'Batman'}; - }}; - let result = controller.callback(transition); - - expect(controller.state).toEqual('Batman'); - expect(controller.$scope.confirm.show).toHaveBeenCalledWith(); - expect(result).toBeFalsy(); - }); - }); - - describe(`when dataChanged() returns false and/or there's a state in the controller`, () => { - it(`should return true`, () => { - $scope.confirm = {show: jasmine.createSpy('show')}; - controller.dataChanged = () => { - return false; - }; - controller.state = 'the state'; - let transition = {to: () => { - return {name: 'Batman'}; - }}; - let result = controller.callback(transition); - - expect(result).toBeTruthy(); - }); - }); - }); - - describe(`onConfirmResponse()`, () => { - describe(`when response is ACCEPT`, () => { - it(`should call Object.assing on controlle.data with controller.orgData then call go() on state`, () => { - let response = 'ACCEPT'; - controller.data = {}; - controller.orgData = {name: 'Batman'}; - controller.$state = {go: jasmine.createSpy('go')}; - controller.state = 'Batman'; - controller.onConfirmResponse(response); - - expect(controller.data).toEqual(controller.orgData); - expect(controller.$state.go).toHaveBeenCalledWith(controller.state); - }); - }); - - describe(`when response is not ACCEPT`, () => { - it(`should set controller.state to null`, () => { - let response = 'anything but ACCEPT'; - controller.state = 'Batman'; - controller.onConfirmResponse(response); - - expect(controller.state).toBeFalsy(); - }); - }); - }); -}); diff --git a/client/core/src/core.js b/client/core/src/core.js deleted file mode 100644 index d3601a8e1..000000000 --- a/client/core/src/core.js +++ /dev/null @@ -1,7 +0,0 @@ -import './styles'; - -export * from './module'; -export * from './directives'; -export * from './filters'; -export * from './lib'; -export * from './components'; diff --git a/client/core/src/directives/acl.js b/client/core/src/directives/acl.js deleted file mode 100644 index c32b02830..000000000 --- a/client/core/src/directives/acl.js +++ /dev/null @@ -1,103 +0,0 @@ -import ngModule from '../module'; - -function vnAcl(aclService, $timeout) { - let acls = []; - - function getMaterialType(className) { - let type = ''; - if (className) { - type = className.replace('mdl-', '').replace('__input', ''); - type = type.charAt(0).toUpperCase() + type.slice(1); - } - return type; - } - function updateMaterial(input) { - if (input && input.className) { - let find = input.className.match(/mdl-[\w]+input/g); - if (find && find.length && find[0]) { - let type = getMaterialType(find[0]); - if (type && input.parentNode[`Material${type}`] && input.parentNode[`Material${type}`].updateClasses_) { - input.parentNode[`Material${type}`].updateClasses_(); - } - } - } - } - function getDynamicConditions($attrs) { - let atributes = $attrs.$attr; - let conditions = {}; - - Object.keys(atributes).forEach(atribute => { - if (atribute.startsWith('aclConditionalTo')) { - let role = atributes[atribute].split('-').slice(-1)[0]; - conditions[atribute] = { - role: role - }; - } - }); - return conditions; - } - - function permissionElement($element, action) { - if (!aclService.aclPermission(acls)) { - if (action === 'disabled') { - let input = $element[0]; - let selector = 'input, textarea, button, submit'; - - if (!input.matches(selector)) - input = input.querySelector(selector); - - if (input) { - $timeout(() => { - input.setAttribute("disabled", "true"); - updateMaterial(input); - }); - $element[0].querySelectorAll('i, vn-drop-down').forEach(element => { - element.parentNode.removeChild(element); - }); - } - } else { - $element.remove(); - } - } - } - - function updateAcls(role, toAdd) { - let position = acls.indexOf(role); - - if (!toAdd && position > -1) { - acls.splice(position, 1); - } // todo: add acl and enabled element if previusly was disabled - } - - return { - restrict: 'A', - priority: -1, - link: function($scope, $element, $attrs) { - acls = $attrs.vnAcl.split(',').map(element => element.trim().toLowerCase()); - let action = $attrs.vnAclAction || 'disabled'; - let conditions = getDynamicConditions($attrs); - permissionElement($element, action); - - if (Object.keys(conditions).length) { - let watchConditions = $scope.$watch(() => { - Object.keys(conditions).forEach(attrName => { - let hasPermission = $scope.$eval($attrs[attrName]); - if (!hasPermission) { - updateAcls(conditions[attrName].role, hasPermission); - permissionElement($element, action); - delete conditions[attrName]; - } - }); - - if (Object.keys(conditions).length === 0) { - // unWacth - watchConditions(); - } - }); - } - } - }; -} -vnAcl.$inject = ['aclService', '$timeout']; - -ngModule.directive('vnAcl', vnAcl); diff --git a/client/core/src/directives/dialog.js b/client/core/src/directives/dialog.js deleted file mode 100644 index 7e51a8e9e..000000000 --- a/client/core/src/directives/dialog.js +++ /dev/null @@ -1,25 +0,0 @@ -import ngModule from '../module'; -import Dialog from '../components/dialog/dialog'; -import {kebabToCamel} from '../lib/string'; - -/** - * Registers a click handler on the element that opens the dialog id - * specified as value. - * - * @return {Object} The directive - */ -export function directive() { - return { - restrict: 'A', - link: function($scope, $element, $attrs) { - $element.on('click', function(event) { - let dialogKey = kebabToCamel($attrs.vnDialog); - let dialog = $scope[dialogKey]; - if (dialog instanceof Dialog) - dialog.show(); - event.preventDefault(); - }); - } - }; -} -ngModule.directive('vnDialog', directive); diff --git a/client/core/src/directives/focus.js b/client/core/src/directives/focus.js deleted file mode 100644 index 26376a260..000000000 --- a/client/core/src/directives/focus.js +++ /dev/null @@ -1,32 +0,0 @@ -import ngModule from '../module'; - -/** - * Sets the focus and selects the text on the input. - * - * @return {Object} The directive - */ -export function directive() { - return { - restrict: 'A', - link: function($scope, $element, $attrs) { - $scope.$watch('', function() { - let input = $element[0]; - let selector = 'input, textarea, button, submit'; - - if (!input.matches(selector)) - input = input.querySelector(selector); - - if (!input) { - console.warn(`vnFocus: Can't find a focusable element`); - return; - } - - input.focus(); - - if (input.select) - input.select(); - }); - } - }; -} -ngModule.directive('vnFocus', directive); diff --git a/client/core/src/directives/id.js b/client/core/src/directives/id.js deleted file mode 100644 index 193d84781..000000000 --- a/client/core/src/directives/id.js +++ /dev/null @@ -1,27 +0,0 @@ -import ngModule from '../module'; -import {kebabToCamel} from '../lib/string'; - -/** - * Registers the element controller into the scope as a property whose name is - * the directive value transformed to lowerCamelCase. - * - * @return {Object} The directive - */ -export function directive() { - return { - restrict: 'A', - link: function($scope, $element, $attrs) { - let id = kebabToCamel($attrs.vnId); - let controller = $element[0].$ctrl ? - $element[0].$ctrl : $element.controller($element[0].tagName.toLowerCase()); - - if (!id) - throw new Error(`vnId: Attribute can't be null`); - if (!controller) - throw new Error(`vnId: Can't find controller for element '${id}'`); - - $scope[id] = controller; - } - }; -} -ngModule.directive('vnId', directive); diff --git a/client/core/src/directives/index.js b/client/core/src/directives/index.js deleted file mode 100644 index 23392e5e0..000000000 --- a/client/core/src/directives/index.js +++ /dev/null @@ -1,9 +0,0 @@ -import './id'; -import './focus'; -import './dialog'; -import './popover'; -import './validation'; -import './acl'; -import './on-error-src'; -import './zoom-image'; -import './visible-by'; diff --git a/client/core/src/directives/on-error-src.js b/client/core/src/directives/on-error-src.js deleted file mode 100644 index 1462063d6..000000000 --- a/client/core/src/directives/on-error-src.js +++ /dev/null @@ -1,16 +0,0 @@ -import ngModule from '../module'; - -function onErrorSrc() { - return { - restrict: 'A', - link: (scope, element, attrs) => { - let imgError = '/static/images/no-image200x200.png'; - element.bind('error', function() { - if (attrs.src != imgError) { - attrs.$set('src', imgError); - } - }); - } - }; -} -ngModule.directive('onErrorSrc', onErrorSrc); diff --git a/client/core/src/directives/popover.js b/client/core/src/directives/popover.js deleted file mode 100644 index 437d93783..000000000 --- a/client/core/src/directives/popover.js +++ /dev/null @@ -1,26 +0,0 @@ -import ngModule from '../module'; -import Popover from '../components/popover/popover'; -import {kebabToCamel} from '../lib/string'; - -/** - * Directive used to open a popover. - * - * @return {Object} The directive - */ -export function directive() { - return { - restrict: 'A', - link: function($scope, $element, $attrs) { - $element.on('click', function(event) { - let popoverKey = kebabToCamel($attrs.vnPopover); - let popover = $scope[popoverKey]; - if (popover instanceof Popover) { - popover.parent = $element[0]; - popover.show(); - } - event.preventDefault(); - }); - } - }; -} -ngModule.directive('vnPopover', directive); diff --git a/client/core/src/directives/specs/acl.spec.js b/client/core/src/directives/specs/acl.spec.js deleted file mode 100644 index a8c1afc42..000000000 --- a/client/core/src/directives/specs/acl.spec.js +++ /dev/null @@ -1,55 +0,0 @@ -describe('Directive acl', () => { - let scope; - let element; - let compile; - let $timeout; - - beforeEach(() => { - angular.mock.module('client'); - }); - - compile = (hasPermissions, _element) => { - inject(($compile, $rootScope, aclService, _$timeout_, _$httpBackend_) => { - _$httpBackend_.when('GET', /\/locale\/\w+\/[a-z]{2}\.json/).respond({}); - spyOn(aclService, 'aclPermission').and.returnValue(hasPermissions); - scope = $rootScope.$new(); - $timeout = _$timeout_; - element = angular.element(_element); - $compile(element)(scope); - scope.$digest(); - }); - }; - - it('should not disable the input element as the user has permision', () => { - let html = `
`; - compile(true, html); - let input = element.find('input'); - - expect(input).toBeDefined(); - expect(input.attr('disabled')).toBeFalsy(); - }); - - it('should delete the element as the user does not have permission and there is no action', () => { - let html = `
`; - compile(false, html); - - expect(element.children().length).toEqual(0); - }); - - it('should disable the element as the action is to disable it but the user has no permission but present', () => { - let html = `
`; - compile(false, html); - let input = element.find('input'); - $timeout.flush(); - - expect(input).toBeDefined(); - expect(input.attr('disabled')).toBeTruthy(); - }); - - it('should delete any element with the tag i and vn-drop-down', () => { - let html = `
`; - compile(false, html); - - expect(element.find('i').length).toBe(0); - }); -}); diff --git a/client/core/src/directives/specs/dialog.spec.js b/client/core/src/directives/specs/dialog.spec.js deleted file mode 100644 index 12616fc19..000000000 --- a/client/core/src/directives/specs/dialog.spec.js +++ /dev/null @@ -1,38 +0,0 @@ -describe('Directive dialog', () => { - let $scope; - let $element; - let element; - let compile; - let $componentController; - let controller; - - beforeEach(() => { - angular.mock.module('client'); - }); - - compile = _element => { - inject(($compile, $rootScope) => { - $scope = $rootScope.$new(); - $scope.myDialog = controller; - element = angular.element(_element); - $compile(element)($scope); - $scope.$digest(); - }); - }; - - beforeEach(angular.mock.inject((_$componentController_, _$httpBackend_) => { - $componentController = _$componentController_; - _$httpBackend_.when('GET', /\/locale\/\w+\/[a-z]{2}\.json/).respond({}); - $element = angular.element('
'); - controller = $componentController('vnDialog', {$element: $element, $transclude: null}); - })); - - it('should call show() function if dialog is a instance of vnDialog', () => { - let html = `
`; - spyOn(controller, 'show'); - compile(html); - element[0].click(); - - expect(controller.show).toHaveBeenCalledWith(); - }); -}); diff --git a/client/core/src/directives/specs/focus.spec.js b/client/core/src/directives/specs/focus.spec.js deleted file mode 100644 index 6b13c98a3..000000000 --- a/client/core/src/directives/specs/focus.spec.js +++ /dev/null @@ -1,54 +0,0 @@ -describe('Directive focus', () => { - let $scope; - let $element; - let compile; - - beforeEach(() => { - angular.mock.module('client'); - }); - - compile = (_element, _childElement) => { - inject(($compile, $rootScope, _$httpBackend_) => { - $scope = $rootScope.$new(); - _$httpBackend_.when('GET', /\/locale\/\w+\/[a-z]{2}\.json/).respond({}); - $element = angular.element(_element); - if (_childElement) { - $element[0].firstChild.focus = jasmine.createSpy(focus); - } - $element[0].focus = jasmine.createSpy('focus'); - $element[0].select = jasmine.createSpy('select'); - $compile($element)($scope); - $scope.$digest(); - }); - }; - - it('should call the querySelector function upon the input to redefine it with the expected selector then call focus', () => { - let html = `
`; - let childHtml = ''; - compile(html, childHtml); - - expect($element[0].firstChild.focus).toHaveBeenCalled(); - }); - - it('should print a warning message on console', () => { - let html = ``; - console.warn = jasmine.createSpy('warn'); - compile(html); - - expect(console.warn).toHaveBeenCalledWith(`vnFocus: Can't find a focusable element`); - }); - - it('should call focus function on the element', () => { - let html = ``; - compile(html); - - expect($element[0].focus).toHaveBeenCalledWith(); - }); - - it('should call select function on the element', () => { - let html = ``; - compile(html); - - expect($element[0].select).toHaveBeenCalledWith(); - }); -}); diff --git a/client/core/src/directives/specs/id.spec.js b/client/core/src/directives/specs/id.spec.js deleted file mode 100644 index 5c6fb0baa..000000000 --- a/client/core/src/directives/specs/id.spec.js +++ /dev/null @@ -1,44 +0,0 @@ -describe('Directive vnId', () => { - let $scope; - let $element; - let compile; - - beforeEach(() => { - angular.mock.module('client'); - }); - - compile = _element => { - inject(($compile, $rootScope, _$httpBackend_) => { - $scope = $rootScope.$new(); - _$httpBackend_.when('GET', /\/locale\/\w+\/[a-z]{2}\.json/).respond({}); - $element = angular.element(_element); - $compile($element)($scope); - $scope.$digest(); - }); - }; - - it(`should throw an error when there's no id defined`, () => { - let html = `
`; - - expect(() => { - compile(html); - }).toThrow(new Error(`vnId: Attribute can't be null`)); - }); - - it(`should throw an error when these's no controller defined in $element[0]`, () => { - let html = `
`; - - expect(() => { - compile(html); - }).toThrow(new Error(`vnId: Can't find controller for element '1'`)); - }); - - it(`should set the controller into the $scope as there are no errors being thrown`, () => { - let html = `
`; - - expect($scope['1']).not.toBeDefined(); - compile(html); - - expect($scope['1']).toBeDefined(); - }); -}); diff --git a/client/core/src/directives/specs/validation.spec.js b/client/core/src/directives/specs/validation.spec.js deleted file mode 100644 index 26208e34b..000000000 --- a/client/core/src/directives/specs/validation.spec.js +++ /dev/null @@ -1,187 +0,0 @@ -describe('Directive validation', () => { - let scope; - let element; - let compile; - - beforeEach(() => { - angular.mock.module('client'); - }); - - compile = (_element, validations, value) => { - inject(($compile, $rootScope, aclService, _$timeout_, $window, _$httpBackend_) => { - $window.validations = validations; - _$httpBackend_.when('GET', /\/locale\/\w+\/[a-z]{2}\.json/).respond({}); - scope = $rootScope.$new(); - scope.user = {name: value}; - element = angular.element(_element); - $compile(element)(scope); - scope.$digest(); - }); - }; - - it(`should throw an error if the vnValidation doesn't have the right syntax`, () => { - let html = ``; - - expect(() => { - compile(html, {}); - }).toThrow(new Error(`vnValidation: Attribute must have this syntax: [entity].[field]`)); - }); - - it('should throw an error if the window.validations aint defined', () => { - let html = ``; - - expect(() => { - compile(html, {}); - }).toThrow(new Error(`vnValidation: Entity 'User' doesn't exist`)); - }); - - describe('Validator presence()', () => { - it('should not validate the user name as it is an empty string', () => { - let html = `
`; - let validations = {User: {validations: {name: [{validation: 'presence'}]}}}; - compile(html, validations, 'Spiderman'); - scope.user.name = ''; - scope.$digest(); - - expect(element[0].classList).toContain('ng-invalid'); - expect(element[0].classList).not.toContain('ng-valid'); - }); - }); - - describe('Validator absence()', () => { - it('should not validate the entity as it should be an empty string', () => { - let html = `
`; - let validations = {User: {validations: {name: [{validation: 'absence'}]}}}; - compile(html, validations, 'Spiderman'); - scope.$digest(); - - expect(element[0].classList).toContain('ng-invalid'); - expect(element[0].classList).not.toContain('ng-valid'); - }); - - it('should validate the entity as it is an empty string', () => { - let html = `
`; - let validations = {User: {validations: {name: [{validation: 'absence'}]}}}; - compile(html, validations, ''); - scope.$digest(); - - expect(element[0].classList).toContain('ng-valid'); - expect(element[0].classList).not.toContain('ng-invalid'); - }); - }); - - describe('Validator length()', () => { - it('should not validate the user name as it should have min length of 15', () => { - let html = `
`; - let validations = {User: {validations: {name: [{validation: 'length', min: 10, max: 50, is: 15}]}}}; - compile(html, validations, 'fifteen!'); - scope.$digest(); - - expect(element[0].classList).toContain('ng-invalid'); - expect(element[0].classList).not.toContain('ng-valid'); - }); - - it('should validate the user name as it has length of 15', () => { - let html = `
`; - let validations = {User: {validations: {name: [{validation: 'length', min: 10, max: 50, is: 15}]}}}; - compile(html, validations, 'fifteen length!'); - scope.$digest(); - - expect(element[0].classList).toContain('ng-valid'); - expect(element[0].classList).not.toContain('ng-invalid'); - }); - - it('should not validate the user name as it should have min length of 10', () => { - let html = `
`; - let validations = {User: {validations: {name: [{validation: 'length', min: 10}]}}}; - compile(html, validations, 'shortname'); - scope.$digest(); - - expect(element[0].classList).toContain('ng-invalid'); - expect(element[0].classList).not.toContain('ng-valid'); - }); - - it('should validate the user name as its length is greater then the minimum', () => { - let html = `
`; - let validations = {User: {validations: {name: [{validation: 'length', min: 10}]}}}; - compile(html, validations, 'verylongname'); - scope.$digest(); - - expect(element[0].classList).toContain('ng-valid'); - expect(element[0].classList).not.toContain('ng-invalid'); - }); - - it('should not validate the user name as its length is greater then the maximum', () => { - let html = `
`; - let validations = {User: {validations: {name: [{validation: 'length', max: 10}]}}}; - compile(html, validations, 'toolongname'); - scope.$digest(); - - expect(element[0].classList).toContain('ng-invalid'); - expect(element[0].classList).not.toContain('ng-valid'); - }); - }); - - describe('Validator numericality()', () => { - it('should not validate the phone number as it should a integer', () => { - let html = `
`; - let validations = {User: {validations: {phone: [{validation: 'numericality', is: 'what is this?'}]}}}; - compile(html, validations, 'spiderman'); - scope.user.phone = 'this is not a phone number!'; - scope.$digest(); - - expect(element[0].classList).toContain('ng-invalid'); - expect(element[0].classList).not.toContain('ng-valid'); - }); - - it('should validate the phone number as it an integer', () => { - let html = `
`; - let validations = {User: {validations: {phone: [{validation: 'numericality', is: 'what is this?'}]}}}; - compile(html, validations, 'spiderman'); - scope.user.phone = '555555555'; - scope.$digest(); - - expect(element[0].classList).toContain('ng-valid'); - expect(element[0].classList).not.toContain('ng-invalid'); - }); - }); - - describe('Validator inclusion()', () => { - it('should not validate the phone number as it is not an integer', () => { - let html = `
`; - let validations = {User: {validations: {phone: [{validation: 'inclusion'}]}}}; - compile(html, validations, 'spiderman'); - scope.user.phone = 'this is not a phone number!'; - scope.$digest(); - - expect(element[0].classList).toContain('ng-invalid'); - expect(element[0].classList).not.toContain('ng-valid'); - }); - }); - - describe('Validator exclusion()', () => { - it('should validate the phone number as it is an integer', () => { - let html = `
`; - let validations = {User: {validations: {phone: [{validation: 'exclusion'}]}}}; - compile(html, validations, 'spiderman'); - scope.user.phone = '555555555'; - scope.$digest(); - - expect(element[0].classList).toContain('ng-valid'); - expect(element[0].classList).not.toContain('ng-invalid'); - }); - }); - - describe('Validator format()', () => { - it('should not validate the email number as it doesnt contain @', () => { - let html = `
`; - let validations = {User: {validations: {email: [{validation: 'format', with: '@'}]}}}; - compile(html, validations, 'spiderman'); - scope.user.email = 'userverdnatura.es'; - scope.$digest(); - - expect(element[0].classList).toContain('ng-invalid'); - expect(element[0].classList).not.toContain('ng-valid'); - }); - }); -}); diff --git a/client/core/src/directives/validation.js b/client/core/src/directives/validation.js deleted file mode 100644 index 76a94da3b..000000000 --- a/client/core/src/directives/validation.js +++ /dev/null @@ -1,80 +0,0 @@ -import ngModule from '../module'; -import {validateAll} from '../lib/validator'; -import {firstUpper} from '../lib/string'; - -directive.$inject = ['$interpolate', '$compile', '$window']; -export function directive(interpolate, compile, $window) { - return { - restrict: 'A', - require: ['ngModel', '^^?form'], - link: link - }; - - function link(scope, element, attrs, ctrl) { - let vnValidations = $window.validations; - - if (!attrs.vnValidation || !vnValidations) - return; - - let split = attrs.vnValidation.split('.'); - - if (split.length !== 2) - throw new Error(`vnValidation: Attribute must have this syntax: [entity].[field]`); - - let entityName = firstUpper(split[0]); - let fieldName = split[1]; - let entity = vnValidations[entityName]; - - if (!entity) - throw new Error(`vnValidation: Entity '${entityName}' doesn't exist`); - - let validations = entity.validations[fieldName]; - if (!validations || validations.length == 0) - return; - - let ngModel = ctrl[0]; - let form = ctrl[1]; - let errorSpan = angular.element(''); - let errorMsg; - let errorShown = false; - - ngModel.$options.$$options.allowInvalid = true; - ngModel.$validators.entity = value => { - try { - validateAll(value, validations); - return true; - } catch (e) { - errorMsg = e.message; - if (errorShown) changeError(); - return false; - } - }; - - scope.$watch(() => { - return (form.$submitted || ngModel.$dirty) && ngModel.$invalid; - }, value => { - let parent = element.parent(); - - if (value) { - changeError(); - parent.addClass('invalid'); - element.after(errorSpan); - } else if (errorShown) { - parent.removeClass('invalid'); - parent.removeAttr('title'); - errorSpan.remove(); - errorSpan.empty(); - } - - errorShown = value; - }); - - function changeError() { - let parent = element.parent(); - errorSpan.text(errorMsg); - parent.attr('title', errorMsg); - } - } -} -ngModule.directive('vnValidation', directive); - diff --git a/client/core/src/directives/visible-by.js b/client/core/src/directives/visible-by.js deleted file mode 100644 index e05079fb5..000000000 --- a/client/core/src/directives/visible-by.js +++ /dev/null @@ -1,17 +0,0 @@ -import ngModule from '../module'; - -function vnVisibleBy(aclService) { - return { - restrict: 'A', - priority: -1, - link: function($scope, $element, $attrs) { - let acls = $attrs.vnVisibleBy.split(','); - if (!aclService.aclPermission(acls)) { - $element[0].style.visibility = 'hidden'; - } - } - }; -} -vnVisibleBy.$inject = ['aclService']; - -ngModule.directive('vnVisibleBy', vnVisibleBy); diff --git a/client/core/src/filters/index.js b/client/core/src/filters/index.js deleted file mode 100644 index 885f3cd66..000000000 --- a/client/core/src/filters/index.js +++ /dev/null @@ -1,2 +0,0 @@ -import './phone'; -import './ucwords'; diff --git a/client/core/src/lib/acl-service.js b/client/core/src/lib/acl-service.js deleted file mode 100644 index ae4c865bf..000000000 --- a/client/core/src/lib/acl-service.js +++ /dev/null @@ -1,43 +0,0 @@ -import ngModule from '../module'; - -var acl = window.salix ? window.salix.acl : {}; -ngModule.constant('aclConstant', acl); - -aclService.$inject = ['aclConstant']; -function aclService(aclConstant) { - if (aclConstant.roles) { - this.roles = {}; - Object.keys(aclConstant.roles).forEach(role => { - this.roles[role.toLowerCase()] = aclConstant.roles[role]; - }); - } else { - this.roles = undefined; - } - - this.routeHasPermission = function(route) { - let hasPermission; - if (!this.roles) - hasPermission = false; - else if (!route.acl) - hasPermission = true; - else if (!this.roles || !Object.keys(this.roles).length) - hasPermission = false; - else - hasPermission = this.aclPermission(route.acl); - return hasPermission; - }; - this.aclPermission = function(aclCollection) { - let hasPermission = false; - let total = aclCollection.length; - for (let i = 0; i < total; i++) { - let role = aclCollection[i].trim().toLowerCase(); - if (this.roles[role]) { - hasPermission = true; - break; - } - } - return hasPermission; - }; -} - -ngModule.service('aclService', aclService); diff --git a/client/core/src/lib/app.js b/client/core/src/lib/app.js deleted file mode 100644 index 5a41d209c..000000000 --- a/client/core/src/lib/app.js +++ /dev/null @@ -1,35 +0,0 @@ -import ngModule from '../module'; - -/** - * The main application class. - * - * @property {String} name The application name. - * @property {Snackbar} snackbar The main object to show messages. - */ -export default class App { - constructor($rootScope) { - this.loaderStatus = 0; - this.$rootScope = $rootScope; - } - showMessage(message) { - if (this.snackbar) - this.snackbar.show({message: message}); - } - showError(message) { - if (this.snackbar) - this.snackbar.showError({message: `Error: ${message}`}); - } - pushLoader() { - this.loaderStatus++; - if (this.loaderStatus === 1) - this.$rootScope.loading = true; - } - popLoader() { - this.loaderStatus--; - if (this.loaderStatus === 0) - this.$rootScope.loading = false; - } -} -App.$inject = ['$rootScope']; - -ngModule.service('vnApp', App); diff --git a/client/core/src/lib/component.js b/client/core/src/lib/component.js deleted file mode 100644 index 36380a5ed..000000000 --- a/client/core/src/lib/component.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Base class for component controllers. - */ -export default class Component { - /** - * The component owner window. - */ - get window() { - return this.document.defaultView; - } - /** - * The component owner document. - */ - get document() { - return this.element.ownerDocument; - } - /** - * Contructor. - * - * @param {HTMLElement} $element The main component element - * @param {$rootScope.Scope} $scope The element scope - */ - constructor($element, $scope) { - this.element = $element[0]; - this.element.$ctrl = this; - this.$element = $element; - this.$ = $scope; - } -} -Component.$inject = ['$element', '$scope']; diff --git a/client/core/src/lib/filter-list.js b/client/core/src/lib/filter-list.js deleted file mode 100644 index 1c63414d7..000000000 --- a/client/core/src/lib/filter-list.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Generic class to list models. - */ -export default class FilterList { - constructor($scope, $timeout, $state) { - this.$ = $scope; - this.$timeout = $timeout; - this.$state = $state; - - this.waitingMgCrud = 0; - this.modelId = $state.params.id; - } - onOrder(field, order) { - this.filter(`${field} ${order}`); - } - filter(order) { - if (this.$.index && this.modelId && this.modelName) { - this.waitingMgCrud = 0; - this.$.index.filter = { - page: 1, - size: 10 - }; - - this.$.index.filter[this.modelName] = this.modelId; - - if (order) { - this.$.index.filter.order = order; - } - - this.$.index.accept(); - } else if (!this.modelId || !this.modelName) { - throw new Error('Error: model not found'); - } else if (this.waitingMgCrud > 3) { - throw new Error('Error: Magic Crud is not loaded'); - } else { - this.waitingMgCrud++; - this.$timeout(() => { - this.filter(order); - }, 250); - } - } -} diff --git a/client/core/src/lib/index.js b/client/core/src/lib/index.js deleted file mode 100644 index 9df4b6911..000000000 --- a/client/core/src/lib/index.js +++ /dev/null @@ -1,14 +0,0 @@ -import './module-loader'; -import './crud'; -import './app'; -import './interceptor'; -import './acl-service'; -import './storage-services'; -import './filter-list'; -import './template'; -import './spliting-register'; -import './interpolate'; -import './copy'; -import './equals'; -import './modified'; -import './key-codes'; diff --git a/client/core/src/lib/input.js b/client/core/src/lib/input.js deleted file mode 100644 index 9e428e675..000000000 --- a/client/core/src/lib/input.js +++ /dev/null @@ -1,29 +0,0 @@ -import Component from './component'; - -/** - * Component that host an input. - */ -export default class Input extends Component { - constructor($element, $scope) { - super($element, $scope); - this.input = this.element.querySelector('input'); - } - set disabled(value) { - this.input.disabled = value == true; - this.mdlUpdate(); - } - get disabled() { - return this.input.disabled; - } - select() { - this.input.select(); - } - focus() { - this.input.focus(); - } - mdlUpdate() { - if (this.mdlElement) - this.mdlElement.updateClasses_(); - } -} -Input.$inject = ['$element', '$scope']; diff --git a/client/core/src/lib/interceptor.js b/client/core/src/lib/interceptor.js deleted file mode 100644 index d6a2b4b59..000000000 --- a/client/core/src/lib/interceptor.js +++ /dev/null @@ -1,52 +0,0 @@ -import ngModule from '../module'; - -interceptor.$inject = ['$q', '$window', 'vnApp', '$translate', '$cookies']; -function interceptor($q, $window, vnApp, $translate, $cookies) { - return { - request: function(config) { - vnApp.pushLoader(); - let token = $cookies.get('vnToken'); - - if (token) - config.headers.Authorization = token; - - return config; - }, - requestError: function(rejection) { - return $q.reject(rejection); - }, - response: function(response) { - switch (response.config.method) { - case 'PUT': - case 'POST': - case 'PATCH': - vnApp.showMessage($translate.instant('Data saved!')); - } - vnApp.popLoader(); - return response; - }, - responseError: function(rejection) { - vnApp.popLoader(); - let data = rejection.data; - let error; - - if (data && data.error instanceof Object) - error = data.error.message; - else if (rejection.status === -1) - error = $translate.instant(`Can't contact with server`); - else - error = `${rejection.status}: ${rejection.statusText}`; - - if (rejection.status === 401) { - let location = $window.location; - let continueUrl = location.pathname + location.search + location.hash; - continueUrl = encodeURIComponent(continueUrl); - $window.location = `/auth/?apiKey=${vnApp.name}&continue=${continueUrl}`; - } - - vnApp.showError(error); - return $q.reject(rejection); - } - }; -} -ngModule.factory('vnInterceptor', interceptor); diff --git a/client/core/src/lib/interpolate.js b/client/core/src/lib/interpolate.js deleted file mode 100644 index 6321ce813..000000000 --- a/client/core/src/lib/interpolate.js +++ /dev/null @@ -1,189 +0,0 @@ -import ngModule from '../module'; -import {ng} from 'vendor'; - -function stringify(value) { - if (value === null) { // null || undefined - return ''; - } - switch (typeof value) { - case 'string': - break; - case 'number': - value = String(value); - break; - default: - value = angular.toJson(value); - } - - return value; -} - -var $interpolateMinErr = ng.angular.$interpolateMinErr = ng.$$minErr('$interpolate'); - -$interpolateMinErr.throwNoconcat = function(text) { - throw $interpolateMinErr('noconcat', - 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' + - 'interpolations that concatenate multiple expressions when a trusted value is ' + - 'required. See http://docs.angularjs.org/api/ng.$sce', text); -}; - -$interpolateMinErr.interr = function(text, err) { - return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString()); -}; - -function $get($parse, $exceptionHandler, $sce) { - let startSymbolLength = this._startSymbol.length; - let endSymbolLength = this._endSymbol.length; - let escapedStartRegexp = new RegExp(this._startSymbol.replace(/./g, escape), 'g'); - let escapedEndRegexp = new RegExp(this._endSymbol.replace(/./g, escape), 'g'); - let self = this; - - function escape(ch) { - return '\\\\\\' + ch; - } - - function unescapeText(text) { - return text.replace(escapedStartRegexp, self._startSymbol) - .replace(escapedEndRegexp, self._endSymbol); - } - - // TODO: this is the same as the constantWatchDelegate in parse.js - function constantWatchDelegate(scope, listener, objectEquality, constantInterp) { - var unwatch = scope.$watch(function constantInterpolateWatch(scope) { - unwatch(); - return constantInterp(scope); - }, listener, objectEquality); - return unwatch; - } - - function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) { - // Provide a quick exit and simplified result function for text with no interpolation - if (!text.length || text.indexOf(self._startSymbol) === -1) { - var constantInterp; - if (!mustHaveExpression) { - var unescapedText = unescapeText(text); - constantInterp = valueFn(unescapedText); - constantInterp.exp = text; - constantInterp.expressions = []; - constantInterp.$$watchDelegate = constantWatchDelegate; - } - return constantInterp; - } - - allOrNothing = Boolean(allOrNothing); - let startIndex; - let endIndex; - let index = 0; - let expressions = []; - let parseFns = []; - let textLength = text.length; - let exp; - let concat = []; - let expressionPositions = []; - - while (index < textLength) { - if (((startIndex = text.indexOf(self._startSymbol, index)) !== -1) && - ((endIndex = text.indexOf(self._endSymbol, startIndex + startSymbolLength)) !== -1)) { - if (index !== startIndex) - concat.push(unescapeText(text.substring(index, startIndex))); - exp = text.substring(startIndex + startSymbolLength, endIndex); - expressions.push(exp); - parseFns.push($parse(exp, parseStringifyInterceptor)); - index = endIndex + endSymbolLength; - expressionPositions.push(concat.length); - concat.push(''); - } else { - // we did not find an interpolation, so we have to add the remainder to the separators array - if (index !== textLength) - concat.push(unescapeText(text.substring(index))); - break; - } - } - - if (trustedContext && concat.length > 1) { - $interpolateMinErr.throwNoconcat(text); - } - - var getValue = function(value) { - return trustedContext ? - $sce.getTrusted(trustedContext, value) : - $sce.valueOf(value); - }; - - if (!mustHaveExpression || expressions.length) { - var compute = function(values) { - for (var i = 0, ii = expressions.length; i < ii; i++) { - if (allOrNothing && isUndefined(values[i])) return; - concat[expressionPositions[i]] = values[i]; - } - return concat.join(''); - }; - - return angular.extend(function interpolationFn(context) { - var i = 0; - var ii = expressions.length; - var values = new Array(ii); - - try { - for (; i < ii; i++) { - values[i] = parseFns[i](context); - } - - return compute(values); - } catch (err) { - $exceptionHandler($interpolateMinErr.interr(text, err)); - } - }, { - // all of these properties are undocumented for now - exp: text, // just for compatibility with regular watchers created via $watch - expressions: expressions - }); - } - - function parseStringifyInterceptor(value) { - try { - value = getValue(value); - return allOrNothing && !isDefined(value) ? value : stringify(value); - } catch (err) { - $exceptionHandler($interpolateMinErr.interr(text, err)); - } - } - } - - $interpolate.startSymbol = function() { - return startSymbol; - }; - - $interpolate.endSymbol = function() { - return endSymbol; - }; - - return $interpolate; -} - -$get.$inject = ['$parse', '$exceptionHandler', '$sce']; - -export class Interpolate { - constructor() { - this._startSymbol = '*['; - this._endSymbol = ']*'; - } - set startSymbol(value) { - if (value) { - this._startSymbol = value; - return this; - } - return this._startSymbol; - } - set endSymbol(value) { - if (value) { - this._endSymbol = value; - return this; - } - return this._endSymbol; - } -} - -Interpolate.prototype.$get = $get; -var interpolate = new Interpolate(); -ngModule.provider('vnInterpolate', () => interpolate); diff --git a/client/core/src/lib/modified.js b/client/core/src/lib/modified.js deleted file mode 100644 index f142126fb..000000000 --- a/client/core/src/lib/modified.js +++ /dev/null @@ -1,22 +0,0 @@ -import isEqual from './equals'; - -export default function getModifiedData(object, objectOld) { - var newObject = {}; - if (objectOld === null) { - return object; - } - for (var k in object) { - var val = object[k]; - var valOld = objectOld[k] === undefined ? null : objectOld[k]; - - if (!isEqual(val, valOld)) { - if (val instanceof Object) { - newObject[k] = getModifiedData(val, valOld); - } else { - newObject[k] = val; - } - } - } - - return Object.keys(newObject).length ? newObject : undefined; -} diff --git a/client/core/src/lib/module-loader.js b/client/core/src/lib/module-loader.js deleted file mode 100644 index 57cca1753..000000000 --- a/client/core/src/lib/module-loader.js +++ /dev/null @@ -1,96 +0,0 @@ -import ngModule from '../module'; -import splitingRegister from './spliting-register'; - -factory.$inject = ['$http', '$window', '$ocLazyLoad', '$translatePartialLoader', '$translate']; -export function factory($http, $window, $ocLazyLoad, $translatePartialLoader, $translate) { - class ModuleLoader { - constructor() { - this._loaded = {}; - } - load(moduleName, validations) { - let loaded = this._loaded; - - if (loaded[moduleName] === true) - return Promise.resolve(true); - if (loaded[moduleName] instanceof Promise) - return loaded[moduleName]; - if (loaded[moduleName] === false) - return Promise.reject( - new Error(`Module dependency loop detected: ${moduleName}`)); - - loaded[moduleName] = false; - - let deps = splitingRegister.getDependencies(moduleName); - let depPromises = []; - - if (deps) - for (let dep of deps) - depPromises.push(this.load(dep, validations)); - - loaded[moduleName] = new Promise((resolve, reject) => { - Promise.all(depPromises) - .then(() => { - let promises = []; - - $translatePartialLoader.addPart(moduleName); - promises.push(new Promise(resolve => { - $translate.refresh().then( - () => resolve(), - () => resolve() - ); - })); - - if (validations) - promises.push(new Promise(resolve => { - $http.get(`/${moduleName}/validations`).then( - json => this.onValidationsReady(json, resolve), - () => resolve() - ); - })); - - promises.push(new Promise(resolve => { - splitingRegister.modules[moduleName](resolve); - })); - - Promise.all(promises) - .then(() => { - loaded[moduleName] = true; - resolve($ocLazyLoad.load({name: moduleName})); - }) - .catch(reject); - }) - .catch(reject); - }); - - return loaded[moduleName]; - } - onValidationsReady(json, resolve) { - let entities = json.data; - for (let entity in entities) { - let fields = entities[entity].validations; - for (let field in fields) { - let validations = fields[field]; - for (let validation of validations) - this.parseValidation(validation); - } - } - - Object.assign($window.validations, json.data); - resolve(); - } - parseValidation(val) { - switch (val.validation) { - case 'custom': - // TODO: Replace eval - val.bindedFunction = eval(`(${val.bindedFunction})`); - break; - case 'format': - val.with = new RegExp(val.with); - break; - } - } - } - - return new ModuleLoader(); -} -ngModule.factory('vnModuleLoader', factory); diff --git a/client/core/src/lib/specs/acl-service.spec.js b/client/core/src/lib/specs/acl-service.spec.js deleted file mode 100644 index 45a820acc..000000000 --- a/client/core/src/lib/specs/acl-service.spec.js +++ /dev/null @@ -1,50 +0,0 @@ -describe('Service acl', () => { - let aclService; - - beforeEach(() => { - angular.mock.module('vnCore'); - }); - - beforeEach(angular.mock.module($provide => { - $provide.value('aclConstant', {}); - })); - - beforeEach(inject((_aclService_, $httpBackend) => { - aclService = _aclService_; - })); - - it("should return false as the service doesn't have roles", () => { - expect(aclService.routeHasPermission('http://www.verdnatura.es')).toBeFalsy(); - }); - - it("should return true as the service has roles but the route has no acl", () => { - aclService.roles = {customer: true}; - - expect(aclService.routeHasPermission('http://www.verdnatura.es')).toBeTruthy(); - }); - - it("should return false as the service roles have no length", () => { - aclService.roles = {}; - let route = {url: 'http://www.verdnatura.es', acl: []}; - - expect(aclService.routeHasPermission(route)).toBeFalsy(); - }); - - it("should call the service aclPermission() function and return false as the service has roles and the rote has acl without length", () => { - aclService.roles = {customer: true, employee: true}; - let route = {url: 'http://www.verdnatura.es', acl: []}; - spyOn(aclService, 'aclPermission').and.callThrough(); - - expect(aclService.routeHasPermission(route)).toBeFalsy(); - expect(aclService.aclPermission).toHaveBeenCalledWith(route.acl); - }); - - it("should call the service aclPermission() function to return true as the service has roles matching with the ones in acl", () => { - aclService.roles = {customer: true, employee: true}; - let route = {url: 'http://www.verdnatura.es', acl: ['customer']}; - spyOn(aclService, 'aclPermission').and.callThrough(); - - expect(aclService.routeHasPermission(route)).toBeTruthy(); - expect(aclService.aclPermission).toHaveBeenCalledWith(route.acl); - }); -}); diff --git a/client/core/src/lib/spliting-register.js b/client/core/src/lib/spliting-register.js deleted file mode 100644 index d6af3de64..000000000 --- a/client/core/src/lib/spliting-register.js +++ /dev/null @@ -1,12 +0,0 @@ - -class SplitingRegister { - constructor() { - this.graph = null; - this.modules = {}; - } - getDependencies(moduleName) { - return this.graph[moduleName]; - } -} - -export default new SplitingRegister(); diff --git a/client/core/src/lib/storage-services.js b/client/core/src/lib/storage-services.js deleted file mode 100644 index bb766215e..000000000 --- a/client/core/src/lib/storage-services.js +++ /dev/null @@ -1,66 +0,0 @@ -import ngModule from '../module'; - -class VnStorage { - constructor() { - this._type = ''; - this.prefix = 'vn'; - } - set type(value) { - this._type = value; - this.checkSupport(); - } - get type() { - return this._type; - } - get webStorage() { - return window[this.type]; - } - checkSupport() { - try { - let supported = (this.type in window && window[this.type] !== null); - if (supported) { - let key = '__' + Math.round(Math.random() * 1e7); - let webStorage = window[this.type]; - webStorage.setItem(key, ''); - webStorage.removeItem(key); - } - } catch (e) { - console.error('VnStorage.notification.error', e.message); - return false; - } - } - get(param) { - let toRead = this.webStorage.getItem(`${this.prefix}.${param}`); - if (toRead && toRead.startsWith('jsonObject:')) { - toRead = JSON.parse(toRead.replace('jsonObject:', '')); - } - return toRead; - } - set(param, data) { - let toStorage = typeof data === 'object' ? `jsonObject:${JSON.stringify(data)}` : data; - this.webStorage.setItem(`${this.prefix}.${param}`, toStorage); - } - remove(param) { - this.webStorage.removeItem(`${this.prefix}.${param}`); - } - clear() { - this.webStorage.clear(); - } -} - -class SessionStorage extends VnStorage { - constructor() { - super(); - this.type = 'sessionStorage'; - } -} - -class LocalStorage extends VnStorage { - constructor() { - super(); - this.type = 'localStorage'; - } -} - -ngModule.service('sessionStorage', SessionStorage); -ngModule.service('localStorage', LocalStorage); diff --git a/client/core/src/lib/string.js b/client/core/src/lib/string.js deleted file mode 100644 index 920640a95..000000000 --- a/client/core/src/lib/string.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Transforms a kebab-case string to camelCase. A kebab-case string - * is a string with hyphen character as word separator. - * - * @param {String} str The hyphenized string - * @return {String} The camelized string - */ -export function kebabToCamel(str) { - var camelCased = str.replace(/-([a-z])/g, function(g) { - return g[1].toUpperCase(); - }); - return camelCased; -} - -/** - * Transforms the first letter of a string to uppercase. - * - * @param {String} str The input string - * @return {String} The transformed string - */ -export function firstUpper(str) { - return str.charAt(0).toUpperCase() + str.substr(1); -} diff --git a/client/core/src/lib/template.js b/client/core/src/lib/template.js deleted file mode 100644 index b8aa1b30e..000000000 --- a/client/core/src/lib/template.js +++ /dev/null @@ -1,46 +0,0 @@ -import ngModule from '../module'; - -export default class Template { - constructor(vnInterpolate) { - this.vnInterpolate = vnInterpolate; - } - get(template, $attrs, defaults) { - let scope = Object.assign({}, defaults, $attrs); - return template && this.vnInterpolate(template)(scope); - } - getNormalized(template, $attrs, defaults) { - this.normalizeInputAttrs($attrs); - return this.get(template, $attrs, defaults); - } - normalizeInputAttrs($attrs) { - if ($attrs.field) { - let split = $attrs.field.split('.'); - let len = split.length; - - if (len == 0) - throw new Error(`Attribute 'field' can not be empty`); - if (len > 3) - throw new Error(`Attribute 'field' must have this syntax: [ctrl].[entity].[field]`); - - let i = len - 1; - let field = split[i--]; - let entity = i >= 0 ? split[i--] : 'model'; - let ctrl = i >= 0 ? split[i--] : '$ctrl'; - - if ($attrs.model === undefined) - $attrs.model = `${ctrl}.${entity}.${field}`; - if ($attrs.rule === undefined && len >= 2) - $attrs.rule = `${entity}.${field}`; - if ($attrs.label === undefined && len >= 2) - $attrs.label = `${entity}.${field}`; - if ($attrs.name === undefined) - $attrs.name = field; - } - - if ($attrs.focus !== undefined) - $attrs.focus = 'vn-focus'; - } -} -Template.$inject = ['vnInterpolate']; - -ngModule.service('vnTemplate', Template); diff --git a/client/core/src/lib/validator.js b/client/core/src/lib/validator.js deleted file mode 100644 index e1a3dd1ed..000000000 --- a/client/core/src/lib/validator.js +++ /dev/null @@ -1,98 +0,0 @@ -import {validator} from 'vendor'; - -export const validators = { - presence: value => { - if (validator.isEmpty(value ? String(value) : '')) - throw new Error(`Value can't be empty`); - }, - absence: value => { - if (!validator.isEmpty(value)) - throw new Error(`Value should be empty`); - }, - length: (value, conf) => { - let options = { - min: conf.min || conf.is, - max: conf.max || conf.is - }; - let val = value ? String(value) : ''; - if (!validator.isLength(val, options)) { - if (conf.is) { - throw new Error(`Value should be ${conf.is} characters long`); - } else if (conf.min && conf.max) { - throw new Error(`Value should have a length between ${conf.min} and ${conf.max}`); - } else if (conf.min) { - throw new Error(`Value should have at least ${conf.min} characters`); - } else { - throw new Error(`Value should have at most ${conf.max} characters`); - } - } - }, - numericality: (value, conf) => { - if (conf.int) { - if (!validator.isInt(value)) - throw new Error(`Value should be integer`); - } else if (!validator.isNumeric(value)) - throw new Error(`Value should be a number`); - }, - inclusion: (value, conf) => { - if (!validator.isIn(value, conf.in)) - throw new Error(`Invalid value`); - }, - exclusion: (value, conf) => { - if (validator.isIn(value, conf.in)) - throw new Error(`Invalid value`); - }, - format: (value, conf) => { - if (!validator.matches(value, conf.with)) - throw new Error(`Invalid value`); - }, - custom: (value, conf) => { - if (!conf.bindedFunction(value)) - throw new Error(`Invalid value`); - } -}; - -/** - * Checks if value satisfies a set of validations. - * - * @param {*} value The value - * @param {Array} validations Array with validations - */ -export function validateAll(value, validations) { - for (let conf of validations) - validate(value, conf); -} - -/** - * Checks if value satisfies a validation. - * - * @param {*} value The value - * @param {Object} conf The validation configuration - */ -export function validate(value, conf) { - let validator = validators[conf.validation]; - try { - let isEmpty = value == null || value === ''; - - if (isEmpty) - checkNull(value, conf); - if (validator && (!isEmpty || conf.validation == 'presence')) - validator(value, conf); - } catch (e) { - let message = conf.message ? conf.message : e.message; - throw new Error(message); - } -} - -/** - * Checks if value satisfies a blank or not null validation. - * - * @param {*} value The value - * @param {Object} conf The validation configuration - */ -export function checkNull(value, conf) { - if (conf.allowBlank === false && value === '') - throw new Error(`Value can't be blank`); - else if (conf.allowNull === false && value == null) - throw new Error(`Value can't be null`); -} diff --git a/client/core/src/locale/en.yml b/client/core/src/locale/en.yml deleted file mode 100644 index a89a8ca8d..000000000 --- a/client/core/src/locale/en.yml +++ /dev/null @@ -1,10 +0,0 @@ -Accept: Accept -Cancel: Cancel -Close: Close -Clear: Clear -Save: Save -Add: Add -Search: Search -Show More: Show More -No more results: No more results -Hide: Hide \ No newline at end of file diff --git a/client/core/src/locale/es.yml b/client/core/src/locale/es.yml deleted file mode 100644 index 2b6386570..000000000 --- a/client/core/src/locale/es.yml +++ /dev/null @@ -1,10 +0,0 @@ -Accept: Aceptar -Cancel: Cancelar -Close: Cerrar -Clear: Borrar -Save: Guardar -Add: Añadir -Search: Buscar -Show More: Ver más -No more results: No hay más resultados -Hide: Ocultar \ No newline at end of file diff --git a/client/core/src/module.js b/client/core/src/module.js deleted file mode 100644 index 81fb84f00..000000000 --- a/client/core/src/module.js +++ /dev/null @@ -1,43 +0,0 @@ -import * as vendors from 'vendor'; - -let deps = []; -Object.keys(vendors).forEach(vendor => { - let name = vendors[vendor].name; - if (name) - deps.push(name); -}); - -const ngModule = vendors.ng.module('vnCore', deps); -export default ngModule; - -config.$inject = ['$translateProvider', '$translatePartialLoaderProvider']; -export function config($translateProvider, $translatePartialLoaderProvider) { - $translatePartialLoaderProvider.addPart('core'); - - let conf = {urlTemplate: '/static/locale/{part}/{lang}.json'}; - - let fallbackLang = 'es'; - let langs = ['en', 'es']; - let langAliases = { - en_US: 'en', - en_UK: 'en', - es_ES: 'es', - es_AR: 'es' - }; - - $translateProvider - .useSanitizeValueStrategy('escape') - .useLoader('$translatePartialLoader', conf) - .registerAvailableLanguageKeys(langs, langAliases) - // FIXME: Circular dependency due to vnInterceptor - // .fallbackLanguage(fallbackLang) - .determinePreferredLanguage(() => { - let locale = $translateProvider.resolveClientLocale(); - if (langs.indexOf(locale) !== -1) - return locale; - if (langAliases[locale]) - return langAliases[locale]; - return fallbackLang; - }); -} -ngModule.config(config); diff --git a/client/core/src/styles/fontello-head.css b/client/core/src/styles/fontello-head.css deleted file mode 100644 index 7761cfac0..000000000 --- a/client/core/src/styles/fontello-head.css +++ /dev/null @@ -1,30 +0,0 @@ -@font-face { - font-family: 'fontello'; - - src: url('./fontello.woff2') format('woff2'); - font-weight: normal; - font-style: normal; -} - -[class^="icon-"]:before, [class*=" icon-"]:before { - font-family: "fontello"; - font-style: normal; - font-weight: 400; - speak: none; - - display: inline-block; - text-decoration: inherit; - - text-align: center; - /* opacity: .8; */ - - /* For safety - reset parent styles, that can break glyph codes*/ - font-variant: normal; - text-transform: none; - - /* Font smoothing. That was taken from TWBS */ - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - - } - \ No newline at end of file diff --git a/client/core/src/styles/fontello-icons.css b/client/core/src/styles/fontello-icons.css deleted file mode 100644 index 03698f3cf..000000000 --- a/client/core/src/styles/fontello-icons.css +++ /dev/null @@ -1,18 +0,0 @@ - -.icon-barcode:before { content: '\e800'; } /* '' */ -.icon-volume:before { content: '\e801'; } /* '' */ -.icon-bucket:before { content: '\e802'; } /* '' */ -.icon-disabled:before { content: '\e80b'; } /* '' */ -.icon-invoices:before { content: '\e80c'; } /* '' */ -.icon-noweb:before { content: '\e812'; } /* '' */ -.icon-payment:before { content: '\e813'; } /* '' */ -.icon-recovery:before { content: '\e815'; } /* '' */ -.icon-risk:before { content: '\e816'; } /* '' */ -.icon-lines:before { content: '\e819'; } /* '' */ -.icon-volum:before { content: '\e81b'; } /* '' */ -.icon-components:before { content: '\e81c'; } /* '' */ -.icon-clone:before { content: '\e81d'; } /* '' */ -.icon-addperson:before { content: '\e81e'; } /* '' */ -.icon-bin:before { content: '\e81f'; } /* '' */ -.icon-sms:before { content: '\e820'; } /* '' */ -.icon-tags:before { content: '\e821'; } /* '' */ \ No newline at end of file diff --git a/client/core/src/styles/fontello.woff2 b/client/core/src/styles/fontello.woff2 deleted file mode 100644 index eea564017..000000000 Binary files a/client/core/src/styles/fontello.woff2 and /dev/null differ diff --git a/client/core/src/styles/index.js b/client/core/src/styles/index.js deleted file mode 100644 index a8ed4b937..000000000 --- a/client/core/src/styles/index.js +++ /dev/null @@ -1,5 +0,0 @@ -import './mdl-override.css'; -import './mdi-override.css'; -import './zoom-image.scss'; -import './fontello-head.css'; -import './fontello-icons.css'; diff --git a/client/core/src/styles/mdi-override.css b/client/core/src/styles/mdi-override.css deleted file mode 100644 index b63750edf..000000000 --- a/client/core/src/styles/mdi-override.css +++ /dev/null @@ -1,6 +0,0 @@ -@font-face { - font-family: 'Material Icons'; - font-style: normal; - font-weight: 400; - src: url('./Material-Design-Icons.woff2') format('woff2'); -} \ No newline at end of file diff --git a/client/core/src/styles/mdl-override.css b/client/core/src/styles/mdl-override.css deleted file mode 100644 index d781e5817..000000000 --- a/client/core/src/styles/mdl-override.css +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Rewrited CSS rules from Material Design Lite. - * FIXME: don't use !important - */ -body { - line-height: initial; - font-size: 12pt; -} -.mdl-button { - font-weight: bolder; - color: #ffa410; -} -.mdl-button--colored { - color: white !important; -} -.mdl-button--colored, -.mdl-button--colored:focus, -.mdl-button--colored:active { - background-color: #ffa410 !important; -} -.mdl-button--colored:hover, -.mdl-button--raised:hover { - background-color: #ffa410 !important; -} -.mdl-button--fab{ - color: white !important; - background-color: #ff9400 !important; -} - diff --git a/client/item/index.js b/client/item/index.js deleted file mode 100644 index c94fde7de..000000000 --- a/client/item/index.js +++ /dev/null @@ -1 +0,0 @@ -export * from './src/item'; diff --git a/client/item/routes.json b/client/item/routes.json deleted file mode 100644 index d6cb65da6..000000000 --- a/client/item/routes.json +++ /dev/null @@ -1,122 +0,0 @@ -{ - "module": "item", - "name": "Items", - "icon": "inbox", - "validations" : true, - "routes": [ - { - "url": "/item", - "state": "item", - "abstract": true, - "component": "ui-view" - }, - { - "url": "/list?q", - "state": "item.index", - "component": "vn-item-list" - }, - { - "url": "/create", - "state": "item.create", - "component": "vn-item-create" - }, - { - "url": "/:id", - "state": "item.card", - "abstract": true, - "component": "vn-item-card" - }, - { - "url" : "/data", - "state": "item.card.data", - "component": "vn-item-data", - "params": { - "item": "$ctrl.item" - }, - "menu": { - "description": "Basic data", - "icon": "settings" - }, - "acl": ["buyer"] - }, - { - "url" : "/tags", - "state": "item.card.tags", - "component": "vn-item-tags", - "params": { - "item-tags": "$ctrl.itemTags" - }, - "menu": { - "description": "Tags", - "icon": "icon-tags" - }, - "acl": ["buyer"] - }, - { - "url" : "/tax", - "state": "item.card.tax", - "component": "vn-item-tax", - "menu": { - "description": "Tax", - "icon": "folder" - } - }, - { - "url" : "/history", - "state": "item.card.history", - "component": "vn-item-history", - "params": { - "item": "$ctrl.item" - }, - "menu": { - "description": "History", - "icon": "history" - } - }, - { - "url" : "/niche", - "state": "item.card.niche", - "component": "vn-item-niche", - "params": { - "item": "$ctrl.item" - }, - "menu": { - "description": "Niche", - "icon": "folder" - }, - "acl": ["buyer","replenisher"] - }, - { - "url" : "/botanical", - "state": "item.card.botanical", - "component": "vn-item-botanical", - "params": { - "item": "$ctrl.item" - }, - "menu": { - "description": "Botanical", - "icon": "folder" - }, - "acl": ["buyer"] - },{ - "url" : "/barcode", - "state": "item.card.itemBarcode", - "component": "vn-item-barcode", - "params": { - "item": "$ctrl.item" - }, - "menu": { - "description": "Barcode", - "icon": "icon-barcode" - }, - "acl": ["buyer","replenisher"] - },{ - "url" : "/summary", - "state": "item.card.summary", - "component": "vn-item-summary", - "params": { - "item": "$ctrl.item" - } - } - ] -} \ No newline at end of file diff --git a/client/item/src/barcode/item-barcode.html b/client/item/src/barcode/item-barcode.html deleted file mode 100644 index 3bd4c875b..000000000 --- a/client/item/src/barcode/item-barcode.html +++ /dev/null @@ -1,34 +0,0 @@ -
- - Item Barcodes - - - - - - - - - - - - - -
diff --git a/client/item/src/barcode/item-barcode.js b/client/item/src/barcode/item-barcode.js deleted file mode 100644 index eac4ab6cb..000000000 --- a/client/item/src/barcode/item-barcode.js +++ /dev/null @@ -1,127 +0,0 @@ -import ngModule from '../module'; - -export default class Controller { - constructor($state, $scope, $http, $q, $translate, vnApp) { - this.$state = $state; - this.$scope = $scope; - this.$http = $http; - this.$q = $q; - this.$translate = $translate; - this.vnApp = vnApp; - - this.barcodes = []; - this.removedBarcodes = []; - this.oldBarcodes = {}; - } - _setIconAdd() { - if (this.barcodes.length) { - this.barcodes.map(element => { - element.showAddIcon = false; - return true; - }); - this.barcodes[this.barcodes.length - 1].showAddIcon = true; - } else { - this.addBarcode(); - } - } - - _setDirtyForm() { - if (this.$scope.form) { - this.$scope.form.$setDirty(); - } - } - _unsetDirtyForm() { - if (this.$scope.form) { - this.$scope.form.$setPristine(); - } - } - _equalBarcodes(oldBarcode, newBarcode) { - return oldBarcode.id === newBarcode.id && oldBarcode.code === newBarcode.code; - } - - addBarcode() { - this.barcodes.push({code: null, itemFk: this.$state.params.id, showAddIcon: true}); - this._setIconAdd(); - } - - removeBarcode(index) { - let item = this.barcodes[index]; - if (item) { - this.barcodes.splice(index, 1); - this._setIconAdd(); - if (item.id) { - this.removedBarcodes.push(item.id); - this._setDirtyForm(); - } - } - } - - submit() { - let codes = []; - let repeatedBarcodes = false; - let canSubmit; - let barcodesObj = { - delete: this.removedBarcodes, - create: [], - update: [] - }; - for (let i = 0; i < this.barcodes.length; i++) { - let barcode = this.barcodes[i]; - let isNewBarcode = barcode.id === undefined; - - if (barcode.code && codes.indexOf(barcode.code) !== -1) { - repeatedBarcodes = true; - break; - } - if (barcode.code) codes.push(barcode.code); - - if (isNewBarcode && barcode.code) { - barcodesObj.create.push(barcode); - } else if (!isNewBarcode && !this._equalBarcodes(this.oldBarcodes[barcode.id], barcode)) { - barcodesObj.update.push(barcode); - } - } - - if (repeatedBarcodes) { - return this.vnApp.showMessage(this.$translate.instant('The barcode must be unique')); - } - - canSubmit = barcodesObj.update.length > 0 || barcodesObj.create.length > 0 || barcodesObj.delete.length > 0; - - if (canSubmit) { - return this.$http.post(`/item/api/ItemBarcodes/crudItemBarcodes`, barcodesObj).then(() => { - this.getBarcodes(); - this._unsetDirtyForm(); - }); - } - this.vnApp.showMessage(this.$translate.instant('No changes to save')); - } - - setOldBarcodes(response) { - this._setIconAdd(); - response.data.forEach(barcode => { - this.oldBarcodes[barcode.id] = Object.assign({}, barcode); - }); - } - - getBarcodes() { - let filter = { - where: {itemFk: this.$state.params.id} - }; - this.$http.get(`/item/api/ItemBarcodes?filter=${JSON.stringify(filter)}`).then(response => { - this.barcodes = response.data; - this.setOldBarcodes(response); - }); - } - - $onInit() { - this.getBarcodes(); - } -} - -Controller.$inject = ['$state', '$scope', '$http', '$q', '$translate', 'vnApp']; - -ngModule.component('vnItemBarcode', { - template: require('./item-barcode.html'), - controller: Controller -}); diff --git a/client/item/src/barcode/item-barcode.spec.js b/client/item/src/barcode/item-barcode.spec.js deleted file mode 100644 index 98e645c26..000000000 --- a/client/item/src/barcode/item-barcode.spec.js +++ /dev/null @@ -1,142 +0,0 @@ -import './item-barcode.js'; - -describe('Item', () => { - describe('Component vnItemBarcode', () => { - let $componentController; - let $state; - let controller; - let $httpBackend; - - beforeEach(() => { - angular.mock.module('item'); - }); - - beforeEach(angular.mock.inject((_$componentController_, _$state_, _$httpBackend_) => { - $componentController = _$componentController_; - $state = _$state_; - $httpBackend = _$httpBackend_; - $state.params.id = '1'; - controller = $componentController('vnItemBarcode', {$state: $state}); - })); - - describe('add / remove barcode()', () => { - it('should add one empty barcode into controller barcodes collection and call _setIconAdd()', () => { - controller.barcodes = []; - spyOn(controller, '_setIconAdd').and.callThrough(); - controller.addBarcode(); - - expect(controller._setIconAdd).toHaveBeenCalledWith(); - expect(controller.barcodes.length).toEqual(1); - expect(controller.barcodes[0].id).toBe(undefined); - expect(controller.barcodes[0].showAddIcon).toBeTruthy(); - }); - - it('should remove a barcode that occupies the position in the index given and call _setIconAdd()', () => { - let index = 2; - controller.barcodes = [ - {id: 1, code: '1111', showAddIcon: false}, - {id: 2, code: '2222', showAddIcon: false}, - {id: 3, code: '3333', showAddIcon: true} - ]; - - spyOn(controller, '_setIconAdd').and.callThrough(); - - controller.removeBarcode(index); - - expect(controller._setIconAdd).toHaveBeenCalledWith(); - expect(controller.barcodes.length).toEqual(2); - expect(controller.barcodes[0].showAddIcon).toBeFalsy(); - expect(controller.barcodes[1].showAddIcon).toBeTruthy(); - expect(controller.barcodes[index]).toBe(undefined); - }); - }); - - describe('_equalBarcodes()', () => { - it('should return true if two barcodes are equals independent of control attributes', () => { - let code1 = {id: 1, code: '1111', showAddIcon: true}; - let code2 = {id: 1, code: '1111', showAddIcon: false}; - let equals = controller._equalBarcodes(code2, code1); - - expect(equals).toBeTruthy(); - }); - - it('should return false if two barcodes aint equals independent of control attributes', () => { - let code1 = {id: 1, code: '1111', showAddIcon: true}; - let code2 = {id: 1, code: '2222', showAddIcon: true}; - let equals = controller._equalBarcodes(code2, code1); - - expect(equals).toBeFalsy(); - }); - }); - - describe('getBarcodes()', () => { - it('should perform a GET query to receive the item barcodes', () => { - let filter = { - where: {itemFk: '1'} - }; - let res = [{id: 1, code: '1111'}]; - $httpBackend.when('GET', `/item/api/ItemBarcodes?filter=${JSON.stringify(filter)}`).respond(res); - $httpBackend.expectGET(`/item/api/ItemBarcodes?filter=${JSON.stringify(filter)}`); - controller.getBarcodes(); - $httpBackend.flush(); - }); - }); - - describe('submit()', () => { - it("should return an error message 'The barcode must be unique' when the code isnt unique", () => { - spyOn(controller.vnApp, 'showMessage').and.callThrough(); - controller.barcodes = [ - {code: 123454, itemFk: 1, id: 1}, - {code: 123454, itemFk: 1} - ]; - controller.oldBarcodes = {1: {id: 1, code: 123454, itemFk: 1}}; - controller.submit(); - - expect(controller.vnApp.showMessage).toHaveBeenCalledWith('The barcode must be unique'); - }); - - it("should perfom a query to delete barcodes", () => { - controller.removedBarcodes = [1, 2, 3]; - - $httpBackend.when('GET', `/item/api/ItemBarcodes?filter={"where":{"itemFk":"1"}}`).respond([{code: 123454, itemFk: 1, id: 1}]); - $httpBackend.when('POST', `/item/api/ItemBarcodes/crudItemBarcodes`).respond('ok!'); - $httpBackend.expectPOST(`/item/api/ItemBarcodes/crudItemBarcodes`); - controller.submit(); - $httpBackend.flush(); - }); - - it("should perfom a query to update barcodes", () => { - controller.barcodes = [{code: 2222, itemFk: 1, id: 1}]; - controller.oldBarcodes = {1: {id: 1, code: 1111, itemFk: 1}}; - - $httpBackend.when('GET', `/item/api/ItemBarcodes?filter={"where":{"itemFk":"1"}}`).respond([{}]); - $httpBackend.when('POST', `/item/api/ItemBarcodes/crudItemBarcodes`).respond('ok!'); - $httpBackend.expectPOST(`/item/api/ItemBarcodes/crudItemBarcodes`); - controller.submit(); - $httpBackend.flush(); - }); - - it("should perfom a query to create new barcode", () => { - controller.barcodes = [{code: 1111, itemFk: 1}]; - - $httpBackend.when('GET', `/item/api/ItemBarcodes?filter={"where":{"itemFk":"1"}}`).respond([{}]); - $httpBackend.when('POST', `/item/api/ItemBarcodes/crudItemBarcodes`).respond('ok!'); - $httpBackend.expectPOST(`/item/api/ItemBarcodes/crudItemBarcodes`); - controller.submit(); - $httpBackend.flush(); - }); - - it("should return a message 'No changes to save' when there are no changes to apply", () => { - spyOn(controller.vnApp, 'showMessage').and.callThrough(); - controller.oldBarcodes = [ - {code: 1, itemFk: 1, id: 1}, - {code: 2, itemFk: 1, id: 2} - ]; - controller.barcodes = []; - controller.submit(); - - expect(controller.vnApp.showMessage).toHaveBeenCalledWith('No changes to save'); - }); - }); - }); -}); diff --git a/client/item/src/botanical/item-botanical.html b/client/item/src/botanical/item-botanical.html deleted file mode 100644 index c95511be8..000000000 --- a/client/item/src/botanical/item-botanical.html +++ /dev/null @@ -1,47 +0,0 @@ - - - - -
- - Botanical - - - - - - - - - - - - - - -
\ No newline at end of file diff --git a/client/item/src/botanical/item-botanical.js b/client/item/src/botanical/item-botanical.js deleted file mode 100644 index c747b6b0d..000000000 --- a/client/item/src/botanical/item-botanical.js +++ /dev/null @@ -1,36 +0,0 @@ -import ngModule from '../module'; - -class ItemBotanical { - constructor($http, $state) { - this.$http = $http; - this.$state = $state; - } - _getBotanical() { - let filter = { - where: {itemFk: this.$state.params.id}, - include: [{relation: 'genus'}, {relation: 'specie'}] - }; - this.$http.get(`/item/api/ItemBotanicals?filter=${JSON.stringify(filter)}`) - .then(res => { - if (res.data.length) { - this.botanical = res.data[0]; - } else { - this.botanical = { - itemFk: this.$state.params.id, - botanical: null, - genusFk: null, - specieFk: null - }; - } - }); - } - $onInit() { - this._getBotanical(); - } -} -ItemBotanical.$inject = ['$http', '$state']; - -ngModule.component('vnItemBotanical', { - template: require('./item-botanical.html'), - controller: ItemBotanical -}); diff --git a/client/item/src/botanical/item-botanical.spec.js b/client/item/src/botanical/item-botanical.spec.js deleted file mode 100644 index f4e0e52d9..000000000 --- a/client/item/src/botanical/item-botanical.spec.js +++ /dev/null @@ -1,34 +0,0 @@ -import './item-botanical.js'; - -describe('ItemBotanical', () => { - describe('Component vnItemBotanical', () => { - let $componentController; - let $httpBackend; - let $state; - let controller; - - beforeEach(() => { - angular.mock.module('item'); - }); - - beforeEach(angular.mock.inject((_$componentController_, _$state_, _$httpBackend_) => { - $componentController = _$componentController_; - $httpBackend = _$httpBackend_; - $state = { - params: { - id: 123 - } - }; - controller = $componentController('vnItemBotanical', {$state: $state}); - })); - - describe('_getBotanical()', () => { - it('should request to patch the propagation of botanical status', () => { - $httpBackend.whenGET('/item/api/ItemBotanicals?filter={"where":{"itemFk":123},"include":[{"relation":"genus"},{"relation":"specie"}]}').respond({data: 'item'}); - $httpBackend.expectGET('/item/api/ItemBotanicals?filter={"where":{"itemFk":123},"include":[{"relation":"genus"},{"relation":"specie"}]}'); - controller.$onInit(); - $httpBackend.flush(); - }); - }); - }); -}); diff --git a/client/item/src/card/item-card.html b/client/item/src/card/item-card.html deleted file mode 100644 index 34ecff4a5..000000000 --- a/client/item/src/card/item-card.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/client/item/src/card/item-card.js b/client/item/src/card/item-card.js deleted file mode 100644 index a1e4d9994..000000000 --- a/client/item/src/card/item-card.js +++ /dev/null @@ -1,65 +0,0 @@ -import ngModule from '../module'; - -class ItemCard { - constructor($http, $state, $timeout) { - this.$http = $http; - this.$state = $state; - this.$timeout = $timeout; - - this.item = null; - this.tags = {}; - this.itemTags = null; - } - _getItemTags() { - let filter = { - where: {itemFk: this.$state.params.id}, - order: "priority ASC", - include: {relation: "tag"} - }; - this.$http.get(`/item/api/ItemTags?filter=${JSON.stringify(filter)}`).then(response => { - this.itemTags = response.data; - }); - } - - _getTags() { - this.$http.get(`/item/api/Tags`).then(response => { - response.data.forEach(tag => { - this.tags[tag.id] = Object.assign({}, tag); - }); - }); - } - - _getItem() { - let filter = { - include: [ - {relation: "itemType"}, - {relation: "origin"}, - {relation: "ink"}, - {relation: "producer"}, - {relation: "intrastat"}, - {relation: "expence"} - ] - }; - this.$http.get(`/item/api/Items/${this.$state.params.id}?filter=${JSON.stringify(filter)}`) - .then(res => { - if (res.data && res.data.id) { - this.$timeout(() => { - this.item = res.data; - }); - } - } - ); - } - - $onInit() { - this._getItem(); - this._getTags(); - this._getItemTags(); - } -} -ItemCard.$inject = ['$http', '$state', '$timeout']; - -ngModule.component('vnItemCard', { - template: require('./item-card.html'), - controller: ItemCard -}); diff --git a/client/item/src/card/item-card.spec.js b/client/item/src/card/item-card.spec.js deleted file mode 100644 index 50e3e0542..000000000 --- a/client/item/src/card/item-card.spec.js +++ /dev/null @@ -1,43 +0,0 @@ -import './item-card.js'; - -describe('Item', () => { - describe('Component vnItemCard', () => { - let $componentController; - let $httpBackend; - let $state; - let controller; - - beforeEach(() => { - angular.mock.module('item'); - }); - - beforeEach(angular.mock.inject((_$componentController_, _$state_, _$httpBackend_) => { - $componentController = _$componentController_; - $httpBackend = _$httpBackend_; - $state = { - params: { - id: 123 - } - }; - controller = $componentController('vnItemCard', {$state: $state}); - })); - - describe('_getItem()', () => { - it('should request to get the item', () => { - $httpBackend.whenGET('/item/api/Items/123?filter={"include":[{"relation":"itemType"},{"relation":"origin"},{"relation":"ink"},{"relation":"producer"},{"relation":"intrastat"},{"relation":"expence"}]}').respond({data: 'item'}); - $httpBackend.expectGET('/item/api/Items/123?filter={"include":[{"relation":"itemType"},{"relation":"origin"},{"relation":"ink"},{"relation":"producer"},{"relation":"intrastat"},{"relation":"expence"}]}'); - controller._getItem(); - $httpBackend.flush(); - }); - }); - - describe('_getItemTags()', () => { - it('should request to get the ItemTags', () => { - $httpBackend.whenGET('/item/api/ItemTags?filter={"where":{"itemFk":123},"order":"priority ASC","include":{"relation":"tag"}}').respond({data: 'item'}); - $httpBackend.expectGET('/item/api/ItemTags?filter={"where":{"itemFk":123},"order":"priority ASC","include":{"relation":"tag"}}'); - controller._getItemTags(); - $httpBackend.flush(); - }); - }); - }); -}); diff --git a/client/item/src/create/item-create.html b/client/item/src/create/item-create.html deleted file mode 100644 index d537fe7f6..000000000 --- a/client/item/src/create/item-create.html +++ /dev/null @@ -1,51 +0,0 @@ - - - -
-
- - New item - - - - - - - - - - - - - - - - - - - -
-
diff --git a/client/item/src/create/item-create.js b/client/item/src/create/item-create.js deleted file mode 100644 index 415e67c4f..000000000 --- a/client/item/src/create/item-create.js +++ /dev/null @@ -1,23 +0,0 @@ -import ngModule from '../module'; - -class ItemCreate { - constructor($scope, $state) { - this.$ = $scope; - this.$state = $state; - this.item = { - relevancy: 0 - }; - } - - onSubmit() { - this.$.watcher.submit().then( - json => this.$state.go('item.card.data', {id: json.data.id}) - ); - } -} -ItemCreate.$inject = ['$scope', '$state']; - -ngModule.component('vnItemCreate', { - template: require('./item-create.html'), - controller: ItemCreate -}); diff --git a/client/item/src/create/item-create.spec.js b/client/item/src/create/item-create.spec.js deleted file mode 100644 index e63265ee7..000000000 --- a/client/item/src/create/item-create.spec.js +++ /dev/null @@ -1,40 +0,0 @@ -import './item-create.js'; - -describe('Item', () => { - describe('Component vnItemCreate', () => { - let $componentController; - let $scope; - let $state; - let controller; - - beforeEach(() => { - angular.mock.module('item'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$state_) => { - $componentController = _$componentController_; - $scope = $rootScope.$new(); - $state = _$state_; - $scope.watcher = { - submit: () => { - return { - then: callback => { - callback({data: {id: 1}}); - } - }; - } - }; - controller = $componentController('vnItemCreate', {$scope: $scope}); - })); - - describe('onSubmit()', () => { - it(`should call submit() on the watcher then expect a callback`, () => { - spyOn($state, 'go'); - controller.onSubmit(); - - expect(controller.$state.go).toHaveBeenCalledWith('item.card.data', {id: 1}); - }); - }); - }); -}); - diff --git a/client/item/src/data/item-data.html b/client/item/src/data/item-data.html deleted file mode 100644 index 507fdc2b2..000000000 --- a/client/item/src/data/item-data.html +++ /dev/null @@ -1,59 +0,0 @@ - - - - -
- - Basic data - - - - - - - - {{id}} : {{description}} - - - - - - - - - - - - - -
diff --git a/client/item/src/data/item-data.js b/client/item/src/data/item-data.js deleted file mode 100644 index d9e7c551b..000000000 --- a/client/item/src/data/item-data.js +++ /dev/null @@ -1,23 +0,0 @@ -import ngModule from '../module'; - -class ItemData { - constructor($scope, $timeout) { - this.$scope = $scope; - this.$timeout = $timeout; - } - $onChanges(data) { - this.$timeout(() => { - this.$scope.watcher.data = data.item.currentValue; - }); - } -} - -ItemData.$inject = ['$scope', '$timeout']; - -ngModule.component('vnItemData', { - template: require('./item-data.html'), - bindings: { - item: '<' - }, - controller: ItemData -}); diff --git a/client/item/src/descriptor/item-descriptor.html b/client/item/src/descriptor/item-descriptor.html deleted file mode 100644 index 38002ed5a..000000000 --- a/client/item/src/descriptor/item-descriptor.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - -
{{$ctrl.item.name}}
-
Id {{$ctrl.item.id}}
-
-
{{$ctrl.tags[itemTag.tagFk].name}} {{itemTag.value}}
-
-
-
-
diff --git a/client/item/src/descriptor/item-descriptor.js b/client/item/src/descriptor/item-descriptor.js deleted file mode 100644 index 910895848..000000000 --- a/client/item/src/descriptor/item-descriptor.js +++ /dev/null @@ -1,10 +0,0 @@ -import ngModule from '../module'; - -ngModule.component('vnItemDescriptor', { - template: require('./item-descriptor.html'), - bindings: { - item: '<', - itemTags: '<', - tags: '<' - } -}); diff --git a/client/item/src/filter-item-list.js b/client/item/src/filter-item-list.js deleted file mode 100644 index e170186bd..000000000 --- a/client/item/src/filter-item-list.js +++ /dev/null @@ -1,9 +0,0 @@ -import FilterList from 'core/src/lib/filter-list'; - -export default class FilterItemList extends FilterList { - constructor($scope, $timeout, $state) { - super($scope, $timeout, $state); - this.modelName = 'itemFk'; - } -} -FilterItemList.$inject = ['$scope', '$timeout', '$state']; diff --git a/client/item/src/filter-panel/filter-panel.html b/client/item/src/filter-panel/filter-panel.html deleted file mode 100644 index 2f09c471c..000000000 --- a/client/item/src/filter-panel/filter-panel.html +++ /dev/null @@ -1,47 +0,0 @@ -
-
- - - - - - - - - - - - - - - - - - - - - - - -
-
diff --git a/client/item/src/filter-panel/filter-panel.js b/client/item/src/filter-panel/filter-panel.js deleted file mode 100644 index 608918b51..000000000 --- a/client/item/src/filter-panel/filter-panel.js +++ /dev/null @@ -1,16 +0,0 @@ -import ngModule from '../module'; - -class ItemFilterPanel { - constructor() { - this.onSubmit = () => {}; - } - - onSearch() { - this.onSubmit(this.filter); - } -} - -ngModule.component('vnItemFilterPanel', { - template: require('./filter-panel.html'), - controller: ItemFilterPanel -}); diff --git a/client/item/src/history/item-history.html b/client/item/src/history/item-history.html deleted file mode 100644 index 9854894ce..000000000 --- a/client/item/src/history/item-history.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - Item history - - - - - - - - - {{::itemLog.description}} - {{::itemLog.action}} - {{::itemLog.user.name}} - {{::itemLog.creationDate | date:'dd/MM/yyyy HH:mm'}} - - - - - - - - - - - diff --git a/client/item/src/history/item-history.js b/client/item/src/history/item-history.js deleted file mode 100644 index b89dca928..000000000 --- a/client/item/src/history/item-history.js +++ /dev/null @@ -1,7 +0,0 @@ -import ngModule from '../module'; -import FilterItemList from '../filter-item-list'; - -ngModule.component('vnItemHistory', { - template: require('./item-history.html'), - controller: FilterItemList -}); diff --git a/client/item/src/item.js b/client/item/src/item.js deleted file mode 100644 index 504933d06..000000000 --- a/client/item/src/item.js +++ /dev/null @@ -1,17 +0,0 @@ -export * from './module'; - -import './filter-item-list'; -import './list/list'; -import './filter-panel/filter-panel'; -import './create/item-create'; -import './card/item-card'; -import './descriptor/item-descriptor'; -import './data/item-data'; -import './tags/item-tags'; -import './tax/item-tax'; -import './history/item-history'; -import './niche/item-niche'; -import './botanical/item-botanical'; -import './barcode/item-barcode'; -import './summary/item-summary'; - diff --git a/client/item/src/list/item-product.html b/client/item/src/list/item-product.html deleted file mode 100644 index 30663314c..000000000 --- a/client/item/src/list/item-product.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - -
{{::$ctrl.item.name}}
-
Id {{::$ctrl.item.id}}
-
Description {{::$ctrl.item.description}}
-
Size {{::$ctrl.item.size}}
-
Type {{::$ctrl.item.itemType.name}}
-
- - - - - - -
-
- diff --git a/client/item/src/list/item-product.js b/client/item/src/list/item-product.js deleted file mode 100644 index 728b0cd80..000000000 --- a/client/item/src/list/item-product.js +++ /dev/null @@ -1,29 +0,0 @@ -import ngModule from '../module'; - -class ItemProduct { - onClick(event) { - if (event.defaultPrevented) - event.stopImmediatePropagation(); - } - - clone(event) { - event.preventDefault(); - this.ItemList.cloneItem(this.item); - } - - preview(event) { - event.preventDefault(); - this.ItemList.showItemPreview(this.item); - } -} - -ngModule.component('vnItemProduct', { - template: require('./item-product.html'), - bindings: { - item: '<' - }, - controller: ItemProduct, - require: { - ItemList: '^vnItemList' - } -}); diff --git a/client/item/src/list/list.html b/client/item/src/list/list.html deleted file mode 100644 index 5604b1039..000000000 --- a/client/item/src/list/list.html +++ /dev/null @@ -1,37 +0,0 @@ - -
-
- - - - - - - - - - - -
-
- - - - - - - - - - \ No newline at end of file diff --git a/client/item/src/list/list.js b/client/item/src/list/list.js deleted file mode 100644 index 388b89012..000000000 --- a/client/item/src/list/list.js +++ /dev/null @@ -1,40 +0,0 @@ -import ngModule from '../module'; -import './item-product'; -import './style.scss'; - -class ItemList { - constructor($http, $state, $scope) { - this.$http = $http; - this.$state = $state; - this.$scope = $scope; - this.model = {}; - this.itemSelected = null; - } - search(index) { - index.accept(); - } - cloneItem(item) { - this.itemSelected = item; - this.$scope.clone.show(); - } - onCloneAccept(response) { - if (response == 'ACCEPT' && this.itemSelected) { - this.$http.post(`/item/api/Items/${this.itemSelected.id}/clone`).then(res => { - if (res && res.data && res.data.id) { - this.$state.go('item.card.tags', {id: res.data.id}); - } - }); - } - this.itemSelected = null; - } - showItemPreview(item) { - this.itemSelected = item; - this.$scope.preview.show(); - } -} -ItemList.$inject = ['$http', '$state', '$scope']; - -ngModule.component('vnItemList', { - template: require('./list.html'), - controller: ItemList -}); diff --git a/client/item/src/list/style.scss b/client/item/src/list/style.scss deleted file mode 100644 index 86f7f3ea1..000000000 --- a/client/item/src/list/style.scss +++ /dev/null @@ -1,15 +0,0 @@ - -vn-item-product { - display: block; - - .image { - height: 7em; - width: 7em; - - & > img { - max-height: 100%; - max-width: 100%; - border-radius: .2em; - } - } -} \ No newline at end of file diff --git a/client/item/src/locale/en.yml b/client/item/src/locale/en.yml deleted file mode 100644 index 03f1b1f7f..000000000 --- a/client/item/src/locale/en.yml +++ /dev/null @@ -1 +0,0 @@ -Artículo: Items \ No newline at end of file diff --git a/client/item/src/locale/es.yml b/client/item/src/locale/es.yml deleted file mode 100644 index ac2411e96..000000000 --- a/client/item/src/locale/es.yml +++ /dev/null @@ -1,29 +0,0 @@ -Items: Artículos -Item: Artículo -View item: Ver artículo -Category: Categoría -Description: Descripción -Size: Tamaño -Type: Tipo -Name: Nombre -Relevancy: Relevancia -New item: Nuevo artículo -Basic data: Datos básicos -History: Historial -Item history: Historial del artículo -Item tags: Tags del artículo -Tax: IVA -Niche: Nicho -Picture: Foto -Barcode: Código barras -Item barcode: Código de barras del artículo -Changed by: Cambiado por -Action: Acción -Date: Fecha -Preview: Vista previa -Clone: Clonar -Do you want to clone this item?: ¿Desea clonar este artículo? -All it's properties will be copied: Todas sus propiedades serán copiadas -Yes, clone: Si, clonar -Value: Valor -Priority: Prioridad \ No newline at end of file diff --git a/client/item/src/module.js b/client/item/src/module.js deleted file mode 100644 index b44509fb2..000000000 --- a/client/item/src/module.js +++ /dev/null @@ -1,5 +0,0 @@ -import {ng} from 'vendor'; -import 'core'; - -const ngModule = ng.module('item', ['vnCore']); -export default ngModule; diff --git a/client/item/src/niche/item-niche.html b/client/item/src/niche/item-niche.html deleted file mode 100644 index ae30034db..000000000 --- a/client/item/src/niche/item-niche.html +++ /dev/null @@ -1,50 +0,0 @@ - - -
- - Item Niches - - - - - - - - - - - - - - - - -
\ No newline at end of file diff --git a/client/item/src/niche/item-niche.js b/client/item/src/niche/item-niche.js deleted file mode 100644 index e762bcf90..000000000 --- a/client/item/src/niche/item-niche.js +++ /dev/null @@ -1,146 +0,0 @@ -import ngModule from '../module'; - -export default class Controller { - constructor($stateParams, $scope, $http, $translate, vnApp) { - this.params = $stateParams; - this.$scope = $scope; - this.$http = $http; - this.$translate = $translate; - this.vnApp = vnApp; - - this.warehouses = []; - this.niches = []; - this.removedNiches = []; - this.oldNiches = {}; - } - - _setIconAdd() { - if (this.niches.length) { - this.niches.map(element => { - element.showAddIcon = false; - return true; - }); - this.niches[this.niches.length - 1].showAddIcon = true; - } else { - this.addNiche(); - } - } - - _setDirtyForm() { - if (this.$scope.form) { - this.$scope.form.$setDirty(); - } - } - _unsetDirtyForm() { - if (this.$scope.form) { - this.$scope.form.$setPristine(); - } - } - - addNiche() { - this.niches.push({code: null, itemFk: this.params.id, showAddIcon: true}); - this._setIconAdd(); - } - - removeNiche(index) { - let item = this.niches[index]; - if (item) { - this.niches.splice(index, 1); - this._setIconAdd(); - if (item.id) { - this.removedNiches.push(item.id); - this._setDirtyForm(); - } - } - } - - _equalNiches(oldNiche, newNiche) { - return oldNiche.id === newNiche.id && oldNiche.code === newNiche.code && oldNiche.warehouseFk === newNiche.warehouseFk; - } - - setOldNiches(response) { - this._setIconAdd(); - response.data.forEach(niche => { - this.oldNiches[niche.id] = Object.assign({}, niche); - }); - } - - getNiches() { - let filter = { - where: {itemFk: this.params.id}, - include: {relation: 'warehouse'} - }; - this.$http.get(`/item/api/ItemNiches?filter=${JSON.stringify(filter)}`).then(response => { - this.niches = response.data; - this.setOldNiches(response); - }); - } - - getWarehouse(id, warehouses) { - return warehouses.find(warehouse => warehouse.id === id); - } - - getWarehouses() { - this.$http.get(`/item/api/Warehouses`).then(response => { - this.warehouses = response.data; - }); - } - - submit() { - let warehousesDefined = []; - let repeatedWarehouse = false; - let canSubmit; - let nichesObj = { - delete: this.removedNiches, - create: [], - update: [] - }; - this.niches.forEach(niche => { - let isNewNiche = !niche.id; - - if (warehousesDefined.indexOf(niche.warehouseFk) !== -1) { - repeatedWarehouse = true; - return; - } - warehousesDefined.push(niche.warehouseFk); - - if (isNewNiche) { - nichesObj.create.push(niche); - } - - if (!isNewNiche && !this._equalNiches(this.oldNiches[niche.id], niche)) { - nichesObj.update.push(niche); - } - }); - - if (this.$scope.form.$invalid) { - return this.vnApp.showMessage(this.$translate.instant('Some fields are invalid')); - } - - if (repeatedWarehouse) { - return this.vnApp.showMessage(this.$translate.instant('The niche must be unique')); - } - - canSubmit = nichesObj.update.length > 0 || nichesObj.create.length > 0 || nichesObj.delete.length > 0; - - if (canSubmit) { - return this.$http.post(`/item/api/ItemNiches/crudItemNiches`, nichesObj).then(() => { - this.getNiches(); - this._unsetDirtyForm(); - }); - } - this.vnApp.showMessage(this.$translate.instant('No changes to save')); - } - - $onInit() { - this.getNiches(); - this.getWarehouses(); - } -} - -Controller.$inject = ['$stateParams', '$scope', '$http', '$translate', 'vnApp']; - -ngModule.component('vnItemNiche', { - template: require('./item-niche.html'), - controller: Controller -}); diff --git a/client/item/src/niche/item-niche.spec.js b/client/item/src/niche/item-niche.spec.js deleted file mode 100644 index 3218f262e..000000000 --- a/client/item/src/niche/item-niche.spec.js +++ /dev/null @@ -1,155 +0,0 @@ -import './item-niche.js'; - -describe('Item', () => { - describe('Component vnItemNiche', () => { - let $componentController; - let $state; - let controller; - let $httpBackend; - - beforeEach(() => { - angular.mock.module('item'); - }); - - beforeEach(angular.mock.inject((_$componentController_, _$state_, _$httpBackend_) => { - $componentController = _$componentController_; - $state = _$state_; - $httpBackend = _$httpBackend_; - controller = $componentController('vnItemNiche', {$state: $state}); - })); - - describe('add / remove niche', () => { - it('should add one empty niche into controller niches collection and call _setIconAdd()', () => { - controller.niches = []; - spyOn(controller, '_setIconAdd').and.callThrough(); - controller.addNiche(); - - expect(controller._setIconAdd).toHaveBeenCalledWith(); - expect(controller.niches.length).toEqual(1); - expect(controller.niches[0].id).toBe(undefined); - expect(controller.niches[0].showAddIcon).toBeTruthy(); - }); - - it('should remove a niche that occupies the position in the index given and call _setIconAdd()', () => { - let index = 2; - controller.niches = [ - {id: 1, warehouseFk: 1, code: '1111', showAddIcon: false}, - {id: 2, warehouseFk: 2, code: '2222', showAddIcon: false}, - {id: 3, warehouseFk: 3, code: '3333', showAddIcon: true} - ]; - - spyOn(controller, '_setIconAdd').and.callThrough(); - - controller.removeNiche(index); - - expect(controller._setIconAdd).toHaveBeenCalledWith(); - expect(controller.niches.length).toEqual(2); - expect(controller.niches[0].showAddIcon).toBeFalsy(); - expect(controller.niches[1].showAddIcon).toBeTruthy(); - expect(controller.niches[index]).toBe(undefined); - }); - }); - - describe('_equalNiches()', () => { - it('should return true if two niches are equals independent of control attributes', () => { - let niche1 = {id: 1, warehouseFk: 1, code: '1111', showAddIcon: true}; - let niche2 = {id: 1, warehouseFk: 1, code: '1111', showAddIcon: false}; - let equals = controller._equalNiches(niche2, niche1); - - expect(equals).toBeTruthy(); - }); - - it('should return false if two niches aint equals independent of control attributes', () => { - let niche1 = {id: 1, warehouseFk: 1, code: '1111', showAddIcon: true}; - let niche2 = {id: 1, warehouseFk: 1, code: '2222', showAddIcon: true}; - let equals = controller._equalNiches(niche2, niche1); - - expect(equals).toBeFalsy(); - }); - }); - - describe('get Niches / Warehouses', () => { - it('should perform a GET query to receive the item niches', () => { - let res = [{id: 1, warehouseFk: 1, code: '1111'}]; - - $httpBackend.whenGET(`/item/api/ItemNiches?filter={"where":{},"include":{"relation":"warehouse"}}`).respond(res); - $httpBackend.expectGET(`/item/api/ItemNiches?filter={"where":{},"include":{"relation":"warehouse"}}`); - controller.getNiches(); - $httpBackend.flush(); - }); - - it('should perform a GET query to receive the all warehouses', () => { - let res = [ - {id: 1, warehouseFk: 1, name: 'warehouse one'}, - {id: 2, warehouseFk: 2, name: 'warehouse two'} - ]; - - $httpBackend.whenGET(`/item/api/Warehouses`).respond(res); - $httpBackend.expectGET(`/item/api/Warehouses`); - controller.getWarehouses(); - $httpBackend.flush(); - }); - }); - - describe('submit()', () => { - it("should return an error message 'The niche must be unique' when the niche code isnt unique", () => { - controller.$scope.form = {}; - spyOn(controller.vnApp, 'showMessage').and.callThrough(); - controller.niches = [ - {warehouseFk: 1, code: 123454, itemFk: 1, id: 1}, - {warehouseFk: 1, code: 123454, itemFk: 1} - ]; - controller.oldNiches = {1: {warehouseFk: 1, id: 1, code: 123454, itemFk: 1}}; - controller.submit(); - - expect(controller.vnApp.showMessage).toHaveBeenCalledWith('The niche must be unique'); - }); - - it("should perfom a query to delete niches", () => { - controller.$scope.form = {$setPristine: () => {}}; - controller.oldNiches = {1: {id: 1, warehouseFk: 1, code: '1111'}}; - controller.niches = []; - controller.removedNiches = [1]; - - $httpBackend.whenGET(`/item/api/ItemNiches?filter={"where":{},"include":{"relation":"warehouse"}}`).respond([]); - $httpBackend.expectPOST(`/item/api/ItemNiches/crudItemNiches`).respond('ok!'); - controller.submit(); - $httpBackend.flush(); - }); - - it("should perfom a query to update niches", () => { - controller.$scope.form = {$setPristine: () => {}}; - controller.niches = [{id: 1, warehouseFk: 1, code: '2222'}]; - controller.oldNiches = {1: {id: 1, warehouseFk: 1, code: '1111'}}; - - $httpBackend.whenGET(`/item/api/ItemNiches?filter={"where":{},"include":{"relation":"warehouse"}}`).respond([]); - $httpBackend.expectPOST(`/item/api/ItemNiches/crudItemNiches`).respond('ok!'); - controller.submit(); - $httpBackend.flush(); - }); - - it("should perfom a query to create new niche", () => { - controller.$scope.form = {$setPristine: () => {}}; - controller.niches = [{warehouseFk: 1, code: 1111, itemFk: 1}]; - - $httpBackend.whenGET(`/item/api/ItemNiches?filter={"where":{},"include":{"relation":"warehouse"}}`).respond([]); - $httpBackend.expectPOST(`/item/api/ItemNiches/crudItemNiches`).respond('ok!'); - controller.submit(); - $httpBackend.flush(); - }); - - it("should return a message 'No changes to save' when there are no changes to apply", () => { - controller.$scope.form = {$setPristine: () => {}}; - spyOn(controller.vnApp, 'showMessage').and.callThrough(); - controller.oldNiches = [ - {warehouseFk: 1, code: 1, itemFk: 1, id: 1}, - {warehouseFk: 2, code: 2, itemFk: 1, id: 2} - ]; - controller.niches = []; - controller.submit(); - - expect(controller.vnApp.showMessage).toHaveBeenCalledWith('No changes to save'); - }); - }); - }); -}); diff --git a/client/item/src/summary/item-summary.html b/client/item/src/summary/item-summary.html deleted file mode 100644 index 7ad31fd9d..000000000 --- a/client/item/src/summary/item-summary.html +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - - - - - - - -
{{$ctrl.item.id}}
-
-
-
- -
-
- - -
Basic data
-

Name: {{$ctrl.item.name}}

-

Type: {{$ctrl.item.itemType.name}}

-

Intrastat: {{$ctrl.item.intrastat.description}}

-

Relevancy: {{$ctrl.item.relevancy}}

-

Origin: {{$ctrl.item.origin.name}}

-

Expence: {{$ctrl.item.expence.name}}

-
-
- - -
Tax
-

- {{tax.country.country}}: {{tax.taxClass.description}} -

-
-
-
- - -
Tags
-

- {{tag.tag.name}}: {{tag.value}} -

-
- - -
Nicho
-

- {{niche.warehouse.name}}: {{niche.code}} -

-
-
- - -
Botanical
-

Botanical: {{$ctrl.item.botanical.botanical}}

-

Genus: {{$ctrl.item.botanical.genus.latin_genus_name}}

-

Specie: {{$ctrl.item.botanical.specie.latin_species_name}}

-
-
- - -
Barcode
-

- {{barcode.code}} -

-
-
-
-
-
\ No newline at end of file diff --git a/client/item/src/summary/item-summary.js b/client/item/src/summary/item-summary.js deleted file mode 100644 index 401d70f0a..000000000 --- a/client/item/src/summary/item-summary.js +++ /dev/null @@ -1,94 +0,0 @@ -import ngModule from '../module'; - -class ItemSummary { - constructor($http) { - this.$http = $http; - } - - _getTags() { - let filter = { - where: { - itemFk: this.item.id - } - }; - this.tags = []; - this.$http.get(`/item/api/ItemTags?filter=${JSON.stringify(Object.assign({}, filter, {include: {relation: 'tag'}}))}`).then(res => { - this.tags = res.data; - }); - } - - _getTaxes() { - let filter = { - fields: ['id', 'countryFk', 'taxClassFk'], - include: [{ - relation: 'country', - scope: {fields: ['country']} - }, { - relation: 'taxClass', - scope: {fields: ['id', 'description']} - }] - }; - - let urlFilter = encodeURIComponent(JSON.stringify(filter)); - let url = `/item/api/Items/${this.item.id}/taxes?filter=${urlFilter}`; - this.$http.get(url).then(json => { - this.taxes = json.data; - }); - } - - _getBotanical() { - let filter = { - where: {itemFk: this.item.id}, - include: [{relation: 'genus'}, {relation: 'specie'}] - }; - this.item.botanical = {}; - this.$http.get(`/item/api/ItemBotanicals?filter=${JSON.stringify(filter)}`) - .then(res => { - if (res.data.length) { - this.item.botanical = res.data[0]; - } - }); - } - - _getNiches() { - let filter = { - where: {itemFk: this.item.id}, - include: {relation: 'warehouse'} - }; - this.$http.get(`/item/api/ItemNiches?filter=${JSON.stringify(filter)}`).then(response => { - this.niches = response.data; - }); - } - - _getBarcodes() { - let filter = { - where: { - itemFk: this.item.id - } - }; - this.barcodes = []; - this.$http.get(`/item/api/ItemBarcodes?filter=${JSON.stringify(filter)}`).then(response => { - this.barcodes = response.data; - }); - } - - $onChanges() { - if (this.item && this.item.id) { - this._getTags(); - this._getBarcodes(); - this._getNiches(); - this._getTaxes(); - if (!this.item.botanical) - this._getBotanical(); - } - } -} -ItemSummary.$inject = ['$http']; - -ngModule.component('vnItemSummary', { - template: require('./item-summary.html'), - controller: ItemSummary, - bindings: { - item: '<' - } -}); diff --git a/client/item/src/tags/item-tags.html b/client/item/src/tags/item-tags.html deleted file mode 100644 index 318a5dec7..000000000 --- a/client/item/src/tags/item-tags.html +++ /dev/null @@ -1,57 +0,0 @@ - - - -
- - Item tags - - - - - - - - - - - - - - - - - - -
\ No newline at end of file diff --git a/client/item/src/tags/item-tags.js b/client/item/src/tags/item-tags.js deleted file mode 100644 index f2a0b6e5d..000000000 --- a/client/item/src/tags/item-tags.js +++ /dev/null @@ -1,143 +0,0 @@ -import ngModule from '../module'; - -class ItemTags { - constructor($stateParams, $scope, $http, $translate, vnApp) { - this.params = $stateParams; - this.$scope = $scope; - this.$http = $http; - this.$translate = $translate; - this.vnApp = vnApp; - - this.itemTagTypes = []; - this.removedItemTags = []; - this.oldItemTags = {}; - } - - _setIconAdd() { - if (this.instancedItemTags && this.instancedItemTags.length) { - this.instancedItemTags.map(element => { - element.showAddIcon = false; - return true; - }); - this.instancedItemTags[this.instancedItemTags.length - 1].showAddIcon = true; - } else { - this.addItemTag(); - } - } - _setDirtyForm() { - if (this.$scope.form) { - this.$scope.form.$setDirty(); - } - } - _unsetDirtyForm() { - if (this.$scope.form) { - this.$scope.form.$setPristine(); - } - } - - addItemTag() { - if (this.instancedItemTags) { - this.instancedItemTags.push({value: null, itemFk: this.params.id, tagFk: null, priority: null, showAddIcon: true}); - this._setIconAdd(); - } - } - - removeItemTag(index) { - let item = this.instancedItemTags[index]; - if (item) { - this.instancedItemTags.splice(index, 1); - this._setIconAdd(); - if (item.id) { - this.removedItemTags.push(item.id); - this._setDirtyForm(); - } - } - } - - _equalItemTags(oldTag, newTag) { - return oldTag.tagFk === newTag.tagFk && oldTag.value === newTag.value && oldTag.priority === newTag.priority; - } - - _setOlTags(instancedItemTags) { - this._setIconAdd(); - instancedItemTags.forEach(tag => { - this.oldItemTags[tag.id] = Object.assign({}, tag); - }); - } - - _getItemTags() { - let filter = { - where: {itemFk: this.params.id}, - order: "priority ASC", - include: {relation: "tag"} - }; - this.$http.get(`/item/api/ItemTags?filter=${JSON.stringify(filter)}`).then(response => { - this.instancedItemTags = response.data; - this.itemTags = JSON.parse(JSON.stringify(this.instancedItemTags)); - this._setOlTags(response.data); - }); - } - - submit() { - let itemTagsDefined = []; - let repeatedItemTags = false; - let canSubmit; - let tagsObj = { - delete: this.removedItemTags, - create: [], - update: [] - }; - this.instancedItemTags.forEach(tag => { - let isNewTag = !tag.id; - - if (itemTagsDefined.indexOf(tag.tagFk) !== -1) { - repeatedItemTags = true; - return; - } - itemTagsDefined.push(tag.tagFk); - - if (isNewTag) { - tagsObj.create.push(tag); - } - - if (!isNewTag && !this._equalItemTags(this.oldItemTags[tag.id], tag)) { - let tagToUpdate = Object.assign({}, tag); - delete tagToUpdate.tag; - delete tagToUpdate.showAddIcon; - tagsObj.update.push(tagToUpdate); - } - }); - - if (this.$scope.form.$invalid) { - return this.vnApp.showMessage(this.$translate.instant('Some fields are invalid')); - } - - if (repeatedItemTags) { - return this.vnApp.showMessage(this.$translate.instant('The tag must be unique')); - } - - canSubmit = tagsObj.update.length > 0 || tagsObj.create.length > 0 || tagsObj.delete.length > 0; - - if (canSubmit) { - return this.$http.post(`/item/api/ItemTags/crudItemTags`, tagsObj).then(() => { - // this.itemTags = JSON.parse(JSON.stringify(this.instancedItemTags)); - this._getItemTags(); - this._unsetDirtyForm(); - }); - } - this.vnApp.showMessage(this.$translate.instant('No changes to save')); - } - - $onInit() { - this._getItemTags(); - } -} -ItemTags.$inject = ['$stateParams', '$scope', '$http', '$translate', 'vnApp']; - -ngModule.component('vnItemTags', { - template: require('./item-tags.html'), - controller: ItemTags, - bindings: { - itemTags: '=' - } -}); diff --git a/client/item/src/tags/item-tags.spec.js b/client/item/src/tags/item-tags.spec.js deleted file mode 100644 index fd1cd00c4..000000000 --- a/client/item/src/tags/item-tags.spec.js +++ /dev/null @@ -1,143 +0,0 @@ -import './item-tags.js'; - -describe('Item', () => { - describe('Component vnItemTags', () => { - let $componentController; - let $state; - let controller; - let $httpBackend; - - beforeEach(() => { - angular.mock.module('item'); - }); - - beforeEach(angular.mock.inject((_$componentController_, _$state_, _$httpBackend_) => { - $componentController = _$componentController_; - $state = _$state_; - $httpBackend = _$httpBackend_; - controller = $componentController('vnItemTags', {$state: $state}); - })); - - describe('add / remove tags', () => { - it('should add one empty tag into controller tags collection and call _setIconAdd()', () => { - controller.instancedItemTags = []; - spyOn(controller, '_setIconAdd').and.callThrough(); - controller.addItemTag(); - - expect(controller._setIconAdd).toHaveBeenCalledWith(); - expect(controller.instancedItemTags.length).toEqual(1); - expect(controller.instancedItemTags[0].id).toBe(undefined); - expect(controller.instancedItemTags[0].showAddIcon).toBeTruthy(); - }); - - it('should remove a tag that occupies the position in the index given and call _setIconAdd()', () => { - let index = 2; - controller.instancedItemTags = [ - {id: 1, typeFk: 1, value: '1111', showAddIcon: false}, - {id: 2, typeFk: 2, value: '2222', showAddIcon: false}, - {id: 3, typeFk: 3, value: '3333', showAddIcon: true} - ]; - - spyOn(controller, '_setIconAdd').and.callThrough(); - - controller.removeItemTag(index); - - expect(controller._setIconAdd).toHaveBeenCalledWith(); - expect(controller.instancedItemTags.length).toEqual(2); - expect(controller.instancedItemTags[0].showAddIcon).toBeFalsy(); - expect(controller.instancedItemTags[1].showAddIcon).toBeTruthy(); - expect(controller.instancedItemTags[index]).toBe(undefined); - }); - }); - - describe('_equalItemTags()', () => { - it('should return true if two tags are equals independent of control attributes', () => { - let tag1 = {id: 1, typeFk: 1, value: '1111', showAddIcon: true}; - let tag2 = {id: 1, typeFk: 1, value: '1111', showAddIcon: false}; - let equals = controller._equalItemTags(tag2, tag1); - - expect(equals).toBeTruthy(); - }); - - it('should return false if two tags aint equal independent of control attributes', () => { - let tag1 = {id: 1, typeFk: 1, value: '1111', showAddIcon: true}; - let tag2 = {id: 1, typeFk: 1, value: '2222', showAddIcon: true}; - let equals = controller._equalItemTags(tag2, tag1); - - expect(equals).toBeFalsy(); - }); - }); - - describe('get itemTags', () => { - it('should perform a GET query to receive the item tags', () => { - let res = [{id: 1, typeFk: 1, value: '1111'}]; - - $httpBackend.whenGET(`/item/api/ItemTags?filter={"where":{},"order":"priority ASC","include":{"relation":"tag"}}`).respond(res); - $httpBackend.expectGET(`/item/api/ItemTags?filter={"where":{},"order":"priority ASC","include":{"relation":"tag"}}`); - controller._getItemTags(); - $httpBackend.flush(); - }); - }); - - describe('submit()', () => { - it("should return an error message 'The tag must be unique' when the tag value isnt unique", () => { - controller.$scope.form = []; - spyOn(controller.vnApp, 'showMessage').and.callThrough(); - controller.instancedItemTags = [ - {typeFk: 1, value: 123454, itemFk: 1, id: 1}, - {typeFk: 1, value: 123454, itemFk: 1} - ]; - controller.oldItemTags = {1: {typeFk: 1, id: 1, value: 123454, itemFk: 1}}; - controller.submit(); - - expect(controller.vnApp.showMessage).toHaveBeenCalledWith('The tag must be unique'); - }); - - it("should perfom a query to delete tags", () => { - controller.$scope.form = {$setPristine: () => {}}; - controller.oldItemTags = {1: {id: 1, typeFk: 1, value: '1111'}}; - controller.instancedItemTags = []; - controller.removedItemTags = [1]; - - $httpBackend.whenGET(`/item/api/ItemTags?filter={"where":{},"order":"priority ASC","include":{"relation":"tag"}}`).respond([]); - $httpBackend.expectPOST(`/item/api/ItemTags/crudItemTags`).respond('ok!'); - controller.submit(); - $httpBackend.flush(); - }); - - it("should perfom a query to update tags", () => { - controller.$scope.form = {$setPristine: () => {}}; - controller.instancedItemTags = [{id: 1, typeFk: 1, value: '2222'}]; - controller.oldItemTags = {1: {id: 1, typeFk: 1, value: '1111'}}; - - $httpBackend.whenGET(`/item/api/ItemTags?filter={"where":{},"order":"priority ASC","include":{"relation":"tag"}}`).respond([]); - $httpBackend.expectPOST(`/item/api/ItemTags/crudItemTags`).respond('ok!'); - controller.submit(); - $httpBackend.flush(); - }); - - it("should perfom a query to create new tag", () => { - controller.$scope.form = {$setPristine: () => {}}; - controller.instancedItemTags = [{typeFk: 1, value: 1111, itemFk: 1}]; - - $httpBackend.whenGET(`/item/api/ItemTags?filter={"where":{},"order":"priority ASC","include":{"relation":"tag"}}`).respond([]); - $httpBackend.expectPOST(`/item/api/ItemTags/crudItemTags`).respond('ok!'); - controller.submit(); - $httpBackend.flush(); - }); - - it("should return a message 'No changes to save' when there are no changes to apply", () => { - controller.$scope.form = {$setPristine: () => {}}; - spyOn(controller.vnApp, 'showMessage').and.callThrough(); - controller.oldItemTags = [ - {typeFk: 1, value: 1, itemFk: 1, id: 1}, - {typeFk: 2, value: 2, itemFk: 1, id: 2} - ]; - controller.instancedItemTags = []; - controller.submit(); - - expect(controller.vnApp.showMessage).toHaveBeenCalledWith('No changes to save'); - }); - }); - }); -}); diff --git a/client/item/src/tax/item-tax.html b/client/item/src/tax/item-tax.html deleted file mode 100644 index aa111756b..000000000 --- a/client/item/src/tax/item-tax.html +++ /dev/null @@ -1,23 +0,0 @@ -
- - Item tax - - - - - - - - - - -
\ No newline at end of file diff --git a/client/item/src/tax/item-tax.js b/client/item/src/tax/item-tax.js deleted file mode 100644 index 57b84fbab..000000000 --- a/client/item/src/tax/item-tax.js +++ /dev/null @@ -1,46 +0,0 @@ -import ngModule from '../module'; - -export default class Controller { - constructor($stateParams, $http) { - this.$http = $http; - this.$stateParams = $stateParams; - - let filter = { - fields: ['id', 'countryFk', 'taxClassFk'], - include: [{ - relation: 'country', - scope: {fields: ['country']} - }, { - relation: 'taxClass', - scope: {fields: ['id', 'description']} - }] - }; - - let urlFilter = encodeURIComponent(JSON.stringify(filter)); - let url = `/item/api/Items/${$stateParams.id}/taxes?filter=${urlFilter}`; - $http.get(url).then(json => { - this.taxes = json.data; - }); - - $http.get(`/item/api/TaxClasses`).then(json => { - this.classes = json.data; - }); - } - submit() { - let data = []; - for (let tax of this.taxes) - data.push({id: tax.id, taxClassFk: tax.taxClassFk}); - - let url = `/item/api/Items/${this.$stateParams.id}/updateTaxes`; - this.$http.post(url, data); - } -} -Controller.$inject = ['$stateParams', '$http']; - -ngModule.component('vnItemTax', { - template: require('./item-tax.html'), - controller: Controller, - bindings: { - item: '<' - } -}); diff --git a/client/locator/index.js b/client/locator/index.js deleted file mode 100644 index d2b755cd8..000000000 --- a/client/locator/index.js +++ /dev/null @@ -1 +0,0 @@ -export * from './src/locator'; diff --git a/client/locator/routes.json b/client/locator/routes.json deleted file mode 100644 index b508fcc5f..000000000 --- a/client/locator/routes.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "module": "locator", - "name": "Locator", - "icon": "add_location", - "validations" : false, - "routes": [ - { - "url": "/locator", - "state": "locator", - "component": "vn-locator-index", - "acl": ["developer"] - } - ] -} \ No newline at end of file diff --git a/client/locator/src/index/index.html b/client/locator/src/index/index.html deleted file mode 100644 index 4194c9db8..000000000 --- a/client/locator/src/index/index.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - Routes locator -
- - - - -
- - - - - - - -
- - - - - - - -
-
\ No newline at end of file diff --git a/client/locator/src/index/index.js b/client/locator/src/index/index.js deleted file mode 100644 index f691f9ece..000000000 --- a/client/locator/src/index/index.js +++ /dev/null @@ -1,33 +0,0 @@ -import ngModule from '../module'; - -class LocatorIndex { - constructor($state) { - this.$state = $state; - this.routes = []; - - for (let i = 1; i < 100; i++) { - let route = { - id: i, - zoneFk: Math.floor(Math.random() * 6) + 1, - postalcode: 46006, - order: Math.floor(Math.random() * 3) + 1, - preparado: '25/08', - entrada: '26/08', - ticket: 1547890 + i, - routeFk: Math.floor(Math.random() * 9999) + 1000, - alias: `Flores X${Math.floor(Math.random() * 3) + 1}`, - bultos: Math.floor(Math.random() * 20) + 10, - m3: (Math.random()).toFixed(2), - error: (Math.floor(Math.random() * 3) + 1) === 1 - }; - route.success = (!route.error && (Math.floor(Math.random() * 3) + 1) === 1); - this.routes.push(route); - } - } -} -LocatorIndex.$inject = ['$state']; - -ngModule.component('vnLocatorIndex', { - template: require('./index.html'), - controller: LocatorIndex -}); diff --git a/client/locator/src/locale/en.yml b/client/locator/src/locale/en.yml deleted file mode 100644 index 8d3c81c58..000000000 --- a/client/locator/src/locale/en.yml +++ /dev/null @@ -1,4 +0,0 @@ -Routes locator: Routes locator -Filter: Filter -Store: Store -Address: Address \ No newline at end of file diff --git a/client/locator/src/locale/es.yml b/client/locator/src/locale/es.yml deleted file mode 100644 index 462c393bf..000000000 --- a/client/locator/src/locale/es.yml +++ /dev/null @@ -1,4 +0,0 @@ -Routes locator: Localizador de rutas -Filter: Filtro -Store: Almacén -Address: Dirección \ No newline at end of file diff --git a/client/locator/src/locator-actions/locator-actions.html b/client/locator/src/locator-actions/locator-actions.html deleted file mode 100644 index e057bf6fb..000000000 --- a/client/locator/src/locator-actions/locator-actions.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/client/locator/src/locator-actions/locator-actions.js b/client/locator/src/locator-actions/locator-actions.js deleted file mode 100644 index 6f61ac81d..000000000 --- a/client/locator/src/locator-actions/locator-actions.js +++ /dev/null @@ -1,13 +0,0 @@ -import ngModule from '../module'; - -class LocatorActions { - constructor($state) { - this.$state = $state; - } -} -LocatorActions.$inject = ['$state']; - -ngModule.component('vnLocatorActions', { - template: require('./locator-actions.html'), - controller: LocatorActions -}); diff --git a/client/locator/src/locator-table/locator-table.html b/client/locator/src/locator-table/locator-table.html deleted file mode 100644 index 79fbcce45..000000000 --- a/client/locator/src/locator-table/locator-table.html +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - {{::route.zoneFk}} - {{::route.postalcode}} - {{::route.order}} - {{::route.preparado}} - {{::route.entrada}} - {{::route.ticket}} - {{::route.routeFk}} - {{::route.alias}} - {{::route.bultos}} - {{::route.m3}} - - - - - - - - Address: {{::route.address}} - - - - - - - - - - - - - - \ No newline at end of file diff --git a/client/locator/src/locator-table/locator-table.js b/client/locator/src/locator-table/locator-table.js deleted file mode 100644 index 2b8834a65..000000000 --- a/client/locator/src/locator-table/locator-table.js +++ /dev/null @@ -1,46 +0,0 @@ -import ngModule from '../module'; - -class LocatorTable { - constructor($filter) { - this.$filter = $filter; - this.itemsDisplayedInList = 7; - this.pageTable = { - filter: { - page: 1, - size: this.itemsDisplayedInList - }, - model: [] - }; - this._routes = []; - } - - set routes(value) { - this._routes = value; - this.totalFilter = this._routes.length; - this.pageTable.filter.page = 1; - this.paginate(); - } - get routes() { - return this._routes; - } - - onOrder(field, order) { - let reverse = order === 'DESC'; - this.routes = this.$filter('orderBy')(this.routes, field, reverse); - this.paginate(); - } - paginate() { - let init = (this.pageTable.filter.page - 1) * this.itemsDisplayedInList; - let fin = this.pageTable.filter.page * this.itemsDisplayedInList; - this.pageTable.model = this.routes.slice(init, fin); - } -} -LocatorTable.$inject = ['$filter']; - -ngModule.component('vnLocatorTable', { - template: require('./locator-table.html'), - bindings: { - routes: '<' - }, - controller: LocatorTable -}); diff --git a/client/locator/src/locator.js b/client/locator/src/locator.js deleted file mode 100644 index 4f53c473a..000000000 --- a/client/locator/src/locator.js +++ /dev/null @@ -1,5 +0,0 @@ -export * from './module'; - -import './index/index'; -import './locator-actions/locator-actions'; -import './locator-table/locator-table'; diff --git a/client/locator/src/module.js b/client/locator/src/module.js deleted file mode 100644 index 2d50fd2ef..000000000 --- a/client/locator/src/module.js +++ /dev/null @@ -1,5 +0,0 @@ -import {ng} from 'vendor'; -import 'core'; - -const ngModule = ng.module('locator', []); -export default ngModule; diff --git a/client/modules.yml b/client/modules.yml deleted file mode 100644 index f71f90ae6..000000000 --- a/client/modules.yml +++ /dev/null @@ -1,9 +0,0 @@ -auth: [] -client: [] -core: [] -item: [] -locator: [] -production: [] -salix: [] -route: [] -ticket: [] diff --git a/client/production/index.js b/client/production/index.js deleted file mode 100644 index 4cbd2fb45..000000000 --- a/client/production/index.js +++ /dev/null @@ -1 +0,0 @@ -export * from './src/production'; diff --git a/client/production/routes.json b/client/production/routes.json deleted file mode 100644 index 159a80144..000000000 --- a/client/production/routes.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "module": "production", - "name": "Production", - "icon": "local_florist", - "validations" : false, - "routes": [ - { - "url": "/production", - "state": "production", - "component": "vn-production-index", - "acl": ["developer"] - } - ] -} \ No newline at end of file diff --git a/client/production/src/index/index.html b/client/production/src/index/index.html deleted file mode 100644 index be21fd321..000000000 --- a/client/production/src/index/index.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - Finder - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/client/production/src/index/index.js b/client/production/src/index/index.js deleted file mode 100644 index bf111e9f0..000000000 --- a/client/production/src/index/index.js +++ /dev/null @@ -1,103 +0,0 @@ -import ngModule from '../module'; -import './style.scss'; - -export default class ProductionIndex { - constructor($element, $scope, $http, aclConstant) { - this.$element = $element; - this.$ = $scope; - this.$http = $http; - this.filter = {}; - this.tickets = []; - - this.checkAll = 0; - this.footer = { - total: null, - lines: null, - meters: null - }; - this._search = null; - - this.sharedData = { - states: [], - hourItems: [] - }; - - this.child = undefined; - this.userProfile = aclConstant.userProfile; - this.filter.warehouseFk = this.userProfile.warehouseId; - } - - get checkAll() { - return this._checkAll; - } - set checkAll(value) { - this._checkAll = value; - } - - // Actions Callbacks - - _changeState(ids, stateId, stateName, index) { - this.$http.put(`/production/api/TicketStates/${stateId}/changeState`, {tickets: ids}).then(() => { - index.forEach(val => { - this.tickets[val].state = stateName; - this.tickets[val].stateFk = stateId; - }); - }); - } - - _sendMessage(tickets) { - this.$http.post(`/production/api/FakeProductions/messageSend`, {tickets: tickets}).then(() => { - this.vnApp.showMessage(this.$translate.instant('Success: message send!')); - }); - } - - _changeTime(ids, time, index) { - this.$http.put(`/production/api/Tickets/${time}/changeTime`, {tickets: ids}).then(() => { - index.forEach(val => { - this.tickets[val].hour = time; - }); - }); - } - - searchTickets(filter) { - this.$.index.filter.filter = Object.assign({}, this.filter, filter || {}); - this.checkAll = 0; - this.$.index.accept().then(json => { - this.tickets = json.tickets; - this.footer.lines = json.lines; - this.footer.meters = json.m3; - this.footer.total = json.total; - }); - } - - refreshTickets() { - this.filter = {}; - this.filter.warehouseFk = this.$.displayValue = this.userProfile.warehouseId; - } - - onChangeWareHouse(warehouse) { - if (warehouse && warehouse != this.filter.warehouseFk) { - this.filter.warehouseFk = warehouse; - this.searchTickets(this.filter); - } - } - - $onInit() { - for (let i = 1; i <= 24; i++) { - let hour = [i].join(''); - if (hour.length === 1) { - hour = [0, i].join(''); - } - hour += ':00'; - this.sharedData.hourItems.push({id: i, name: hour}); - } - this.filter.warehouseFk = this.$.displayValue = this.userProfile.warehouseId; - } -} - -ProductionIndex.$inject = ['$element', '$scope', '$http', 'aclConstant']; - -ngModule.component('vnProductionIndex', { - template: require('./index.html'), - controller: ProductionIndex -}); diff --git a/client/production/src/index/index.spec.js b/client/production/src/index/index.spec.js deleted file mode 100644 index dc9f0d89b..000000000 --- a/client/production/src/index/index.spec.js +++ /dev/null @@ -1,39 +0,0 @@ -import './index.js'; - -describe('Production', () => { - describe('Component vnProductionIndex', () => { - let $componentController; - let $httpBackend; - let $scope; - let controller; - let $element; - let aclConstant; - - beforeEach(() => { - angular.mock.module('production'); - }); - - beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_) => { - $element = angular.element('
'); - $componentController = _$componentController_; - $httpBackend = _$httpBackend_; - $scope = $rootScope.$new(); - aclConstant = {userProfile: {warehouseId: 1}}; - controller = $componentController('vnProductionIndex', {$scope: $scope, $element: $element, aclConstant: aclConstant}); - })); - - describe('_changeState()', () => { - it('should request to update the ticket state', () => { - let ids = [1, 2, 3, 4]; - let stateId = 1; - let stateName = 'state'; - let index = []; - controller.tickets = ['ticketVal']; - $httpBackend.whenPUT('/production/api/TicketStates/1/changeState', {tickets: ids}).respond({data: 'ticketVal'}); - $httpBackend.expectPUT('/production/api/TicketStates/1/changeState', {tickets: ids}); - controller._changeState(ids, stateId, stateName, index); - $httpBackend.flush(); - }); - }); - }); -}); diff --git a/client/production/src/index/style.scss b/client/production/src/index/style.scss deleted file mode 100644 index eea97e50e..000000000 --- a/client/production/src/index/style.scss +++ /dev/null @@ -1,36 +0,0 @@ -vn-production-index { - flex: 1; - - button { - height: 20px; - padding: 0 6px; - } - vn-searchbar { - vn-icon{ - padding-top: 20px; - } - vn-icon-button{ - padding-top: 10px; - } - } - [pad-ten-top] { - padding-top: 10px; - } - .icon-square{ - height: 36px; - } - .locator-header{ - i{ - cursor: pointer; - } - .moreFilters{ - position: absolute; - z-index: 99; - background-color: white; - padding: 15px; - border: 1px solid #9D9D9D; - margin-top: 60px; - width: 600px; - } - } -} \ No newline at end of file diff --git a/client/production/src/locale/en.yml b/client/production/src/locale/en.yml deleted file mode 100644 index 2577c6f43..000000000 --- a/client/production/src/locale/en.yml +++ /dev/null @@ -1 +0,0 @@ -Production: Production \ No newline at end of file diff --git a/client/production/src/locale/es.yml b/client/production/src/locale/es.yml deleted file mode 100644 index 7846f4b3d..000000000 --- a/client/production/src/locale/es.yml +++ /dev/null @@ -1,27 +0,0 @@ -Finder: Localizador -Production: Producción -'Error: No tickets selected!': 'Error: ¡No hay tickets seleccionados!' -'Error: Action not implemented!': 'Error: ¡Acción no implementada!' -State: Estado -Alarm: Alarma -Agencies: Agencias -Agency: Agencia -Store: Almacén -Printed: Impreso -Commercial: Comercial -Hour: Hora -Lines: Líneas -Boxes: Cajas -Comment: Comentario -Message: Mensaje -Send: Enviar -Date: Fecha -Ticket ID: ID Ticket -Route ID: ID Ruta -Province: Provincia -Filter: Filtrar -Cancel: Cancelar -Worker: Trabajador -Town: Población -Client ID: ID Cliente -Ticket with incidence: Ticket con incidencia \ No newline at end of file diff --git a/client/production/src/module.js b/client/production/src/module.js deleted file mode 100644 index 1427bd898..000000000 --- a/client/production/src/module.js +++ /dev/null @@ -1,5 +0,0 @@ -import {ng} from 'vendor'; -import 'core'; - -const ngModule = ng.module('production', []); -export default ngModule; diff --git a/client/production/src/production-actions/production-actions.html b/client/production/src/production-actions/production-actions.html deleted file mode 100644 index 0e79e3b4a..000000000 --- a/client/production/src/production-actions/production-actions.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/client/production/src/production-actions/production-actions.js b/client/production/src/production-actions/production-actions.js deleted file mode 100644 index fee7b687b..000000000 --- a/client/production/src/production-actions/production-actions.js +++ /dev/null @@ -1,118 +0,0 @@ -import ngModule from '../module'; - -export default class ProductionActions { - constructor($http, $translate, vnApp) { - this.$http = $http; - this.$translate = $translate; - this.vnApp = vnApp; - - this._actionState = null; - this._actionWorker = null; - this._actionHours = null; - } - - set actionState(value) { - this._actionState = value; - this.doAction('changeState'); - } - get actionState() { - return this._actionState; - } - - set actionHours(value) { - this._actionHours = value; - this.doAction('changeTime'); - } - get actionHours() { - return this._actionHours; - } - - set actionWorker(value) { - this._actionWorker = value; - this.doAction('changeWorker'); - } - get actionWorker() { - return this._actionWorker; - } - - _changeState(ids, sateteId) { - this.$http.put(`/production/api/TicketStates/${sateteId}/changeState`, {tickets: ids}) - .then( - () => { - this.parent.searchTickets(); - } - ); - } - _sendMessage(tickets) { - this.$http.post(`/production/api/FakeProductions/messageSend`, {tickets: tickets}) - .then( - () => { - this.vnApp.showMessage(this.$translate.instant('Success: message send!')); - } - ); - } - _changeTime(ids, time, index) { - this.$http.put(`/production/api/Tickets/${time}/changeTime`, {tickets: ids}) - .then( - () => { - this.parent.searchTickets(); - } - ); - } - _changeWorker(ids, workerFk, index) { - this.$http.put(`/production/api/Tickets/${workerFk}/changeWorker`, {tickets: ids}) - .then( - () => { - this.parent.searchTickets(); - } - ); - } - - doAction(actionName) { - let ids = []; - let index = []; - let tickets = []; - this.parent.tickets.forEach( - (val, i) => { - if (val.checked) { - ids.push(val.ticketFk); - index.push(i); - tickets.push({ticketFk: val.ticketFk, salesPerson: val.salesPerson}); - } - } - ); - if (tickets.length) { - switch (actionName) { - case 'changeState' : - this._changeState(ids, this.actionState.id); - break; - case 'addComment': - this._sendMessage(tickets); - break; - case 'markPrinted': - this._changeState(ids, 4); - break; - case 'changeTime': - this._changeTime(ids, this.actionHours.name, index); - break; - case 'changeWorker': - this._changeWorker(ids, this.actionWorker.id, index); - break; - default: - this.vnApp.showMessage(this.$translate.instant('Error: Action not implemented!')); - } - } else { - this.vnApp.showMessage(this.$translate.instant('Error: No tickets selected!')); - } - } -} - -ProductionActions.$inject = ['$http', '$translate', 'vnApp']; - -ngModule.component('vnProductionActions', { - template: require('./production-actions.html'), - controller: ProductionActions, - require: { - parent: '^^vnProductionIndex' - } -}); diff --git a/client/production/src/production-comment/production-comment.html b/client/production/src/production-comment/production-comment.html deleted file mode 100644 index e094d47b8..000000000 --- a/client/production/src/production-comment/production-comment.html +++ /dev/null @@ -1,6 +0,0 @@ -
- - - - -
\ No newline at end of file diff --git a/client/production/src/production-comment/production-comment.js b/client/production/src/production-comment/production-comment.js deleted file mode 100644 index 390de47c2..000000000 --- a/client/production/src/production-comment/production-comment.js +++ /dev/null @@ -1,5 +0,0 @@ -import ngModule from '../module'; - -ngModule.component('vnProductionComment', { - template: require('./production-comment.html') -}); diff --git a/client/production/src/production-filters/production-filters.html b/client/production/src/production-filters/production-filters.html deleted file mode 100644 index 587e03199..000000000 --- a/client/production/src/production-filters/production-filters.html +++ /dev/null @@ -1,32 +0,0 @@ -
- - - - - - - - - - - - - - - - - - - - -
diff --git a/client/production/src/production-filters/production-filters.js b/client/production/src/production-filters/production-filters.js deleted file mode 100644 index 0e6143efc..000000000 --- a/client/production/src/production-filters/production-filters.js +++ /dev/null @@ -1,5 +0,0 @@ -import ngModule from '../module'; - -ngModule.component('vnProductionFilterPanel', { - template: require('./production-filters.html') -}); diff --git a/client/production/src/production-table/production-table.html b/client/production/src/production-table/production-table.html deleted file mode 100644 index e87410722..000000000 --- a/client/production/src/production-table/production-table.html +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - {{::ticket.ticketFk}} - {{::ticket.agency}} - {{::ticket.routeFk}} - {{::ticket.salesPerson | ucwords}} - {{::ticket.worker | ucwords}} - {{::ticket.hour}} - {{::ticket.state}} - {{::ticket.lines}} - {{::ticket.m3}} - {{::ticket.boxes}} - - - - - - - - - - : - {{$ctrl.footer.total}} - - - - - - - - {{$ctrl.footer.lines}} - {{$ctrl.footer.meters}} - - - - - - - \ No newline at end of file diff --git a/client/production/src/production-table/production-table.js b/client/production/src/production-table/production-table.js deleted file mode 100644 index 288118a0d..000000000 --- a/client/production/src/production-table/production-table.js +++ /dev/null @@ -1,56 +0,0 @@ -import ngModule from '../module'; - -export class ProductionTable { - constructor($filter) { - this.$filter = $filter; - this._tickets = []; - this.itemsDisplayedInList = 14; - this._checkAll = 0; - this.pageTable = { - filter: { - page: 1, - size: this.itemsDisplayedInList - }, - model: [] - }; - this.filteredField = null; - this.filteredReverse = null; - } - get checkAll() { - return this._checkAll; - } - set checkAll(value) { - this._checkAll = value; - } - set tickets(value) { - this._tickets = this.filteredField ? this.$filter('orderBy')(value, this.filteredField, this.filteredReverse) : value; - this.totalFilter = this._tickets.length; - this.pageTable.filter.page = 1; - this.pageTickets(); - } - get tickets() { - return this._tickets; - } - onOrder(field, order) { - this.filteredField = field; - this.filteredReverse = order === 'DESC'; - this.tickets = this.tickets; // call tickets setter - } - pageTickets() { - let init = (this.pageTable.filter.page - 1) * this.itemsDisplayedInList; - let fin = this.pageTable.filter.page * this.itemsDisplayedInList; - this.pageTable.model = this.tickets.slice(init, fin); - } -} - -ProductionTable.$inject = ['$filter']; - -ngModule.component('vnProductionTable', { - template: require('./production-table.html'), - bindings: { - tickets: '<', - footer: '<', - checkAll: '<' - }, - controller: ProductionTable -}); diff --git a/client/production/src/production.js b/client/production/src/production.js deleted file mode 100644 index aecd90eaf..000000000 --- a/client/production/src/production.js +++ /dev/null @@ -1,7 +0,0 @@ -export * from './module'; - -// import components -import './index/index'; -import './production-filters/production-filters'; -import './production-actions/production-actions'; -import './production-table/production-table'; diff --git a/client/route/index.js b/client/route/index.js deleted file mode 100644 index eadbde870..000000000 --- a/client/route/index.js +++ /dev/null @@ -1 +0,0 @@ -export * from './src/route'; diff --git a/client/route/routes.json b/client/route/routes.json deleted file mode 100644 index 9e7c48833..000000000 --- a/client/route/routes.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "module": "route", - "name": "Routes", - "icon" : "local_shipping", - "validations" : true, - "routes": [ - { - "url": "/routes", - "state": "routes", - "abstract": true, - "component": "ui-view" - }, - { - "url": "/list", - "state": "routes.index", - "component": "vn-route-index", - "acl": ["developer"] - }, - { - "url": "/create", - "state": "routes.create", - "component": "vn-route-create" - }, - { - "url": "/:id", - "state": "routes.card", - "abstract": true, - "component": "vn-route-card" - }, - { - "url": "/basicData", - "state": "routes.card.basicData", - "component": "vn-route-basic-data", - "params": { - "route": "$ctrl.route" - }, - "menu": { - "description": "Basic data", - "icon": "person" - } - }, - { - "url": "/logisticData", - "state": "routes.card.logisticData", - "component": "vn-route-logistic-data", - "acl": ["employee"], - "params": { - "route": "$ctrl.route" - }, - "menu": { - "description": "Logistic data", - "icon": "local_shipping" - } - }, - { - "url": "/tickets", - "state": "routes.card.tickets", - "component": "vn-route-tickets", - "params": { - "route": "$ctrl.route" - }, - "menu": { - "description": "Assigned tickets", - "icon": "assignment" - } - } - ] -} \ No newline at end of file diff --git a/client/route/src/basic-data/basic-data.html b/client/route/src/basic-data/basic-data.html deleted file mode 100644 index 91a4bd70f..000000000 --- a/client/route/src/basic-data/basic-data.html +++ /dev/null @@ -1,35 +0,0 @@ - - -
- - - Basic data - - - - - - - - - - - - - - -
\ No newline at end of file diff --git a/client/route/src/basic-data/basic-data.js b/client/route/src/basic-data/basic-data.js deleted file mode 100644 index 9f2278dbb..000000000 --- a/client/route/src/basic-data/basic-data.js +++ /dev/null @@ -1,8 +0,0 @@ -import ngModule from '../module'; - -ngModule.component('vnRouteBasicData', { - template: require('./basic-data.html'), - bindings: { - route: '<' - } -}); diff --git a/client/route/src/card/card.html b/client/route/src/card/card.html deleted file mode 100644 index b787b738f..000000000 --- a/client/route/src/card/card.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - local_shipping - - -
Route {{::$ctrl.route.id}}
-
{{$ctrl.route.date | date:'dd/MM/yyyy'}}
-
-
-
-
- -
- - - -
- \ No newline at end of file diff --git a/client/route/src/card/card.js b/client/route/src/card/card.js deleted file mode 100644 index e0655c069..000000000 --- a/client/route/src/card/card.js +++ /dev/null @@ -1,12 +0,0 @@ -import ngModule from '../module'; - -class RouteCard { - constructor() { - this.route = null; - } -} - -ngModule.component('vnRouteCard', { - template: require('./card.html'), - controller: RouteCard -}); diff --git a/client/route/src/create/create.html b/client/route/src/create/create.html deleted file mode 100644 index 8b7b7c6ba..000000000 --- a/client/route/src/create/create.html +++ /dev/null @@ -1,43 +0,0 @@ - - - -
-
- - - Create Route - - - - - - - - - - - - - - - - - -
-
diff --git a/client/route/src/create/create.js b/client/route/src/create/create.js deleted file mode 100644 index a51a32da7..000000000 --- a/client/route/src/create/create.js +++ /dev/null @@ -1,20 +0,0 @@ -import ngModule from '../module'; - -class RouteCreate { - constructor($scope, $state) { - this.$ = $scope; - this.$state = $state; - this.delivery = {}; - } - onSubmit() { - this.$.watcher.submit().then( - json => this.$state.go('routes.card.basicData', {id: json.data.id}) - ); - } -} -RouteCreate.$inject = ['$scope', '$state']; - -ngModule.component('vnRouteCreate', { - template: require('./create.html'), - controller: RouteCreate -}); diff --git a/client/route/src/index/googleMaps.svg b/client/route/src/index/googleMaps.svg deleted file mode 100644 index 9a7fc59d7..000000000 --- a/client/route/src/index/googleMaps.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/client/route/src/index/index.html b/client/route/src/index/index.html deleted file mode 100644 index 7cbf0100f..000000000 --- a/client/route/src/index/index.html +++ /dev/null @@ -1,23 +0,0 @@ - -
-
- - - - - - - - - - -
- - - -
diff --git a/client/route/src/index/index.js b/client/route/src/index/index.js deleted file mode 100644 index c8dc8ffd6..000000000 --- a/client/route/src/index/index.js +++ /dev/null @@ -1,18 +0,0 @@ -import ngModule from '../module'; -import './style.css'; -import './item-route'; - -export default class Controller { - constructor() { - this.model = {}; - } - search(index) { - index.filter.search = this.model.search; - index.accept(); - } -} - -ngModule.component('vnRouteIndex', { - template: require('./index.html'), - controller: Controller -}); diff --git a/client/route/src/index/item-route.html b/client/route/src/index/item-route.html deleted file mode 100644 index 226d75810..000000000 --- a/client/route/src/index/item-route.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - ID_RUTA: - {{$ctrl.route.id}} - - - Fecha: - {{$ctrl.route.date | date:'dd/MM/yyyy'}} - - - m3: - {{$ctrl.route.m3}} - - - - - - - \ No newline at end of file diff --git a/client/route/src/index/item-route.js b/client/route/src/index/item-route.js deleted file mode 100644 index 0eeb9fcd5..000000000 --- a/client/route/src/index/item-route.js +++ /dev/null @@ -1,8 +0,0 @@ -import ngModule from '../module'; - -ngModule.component('vnItemRoute', { - template: require('./item-route.html'), - bindings: { - route: '<' - } -}); diff --git a/client/route/src/index/routeIn.svg b/client/route/src/index/routeIn.svg deleted file mode 100644 index dec26dfbf..000000000 --- a/client/route/src/index/routeIn.svg +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - diff --git a/client/route/src/index/routeOut.svg b/client/route/src/index/routeOut.svg deleted file mode 100644 index 7a69b7786..000000000 --- a/client/route/src/index/routeOut.svg +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - diff --git a/client/route/src/index/style.css b/client/route/src/index/style.css deleted file mode 100644 index 0a369664e..000000000 --- a/client/route/src/index/style.css +++ /dev/null @@ -1,12 +0,0 @@ -vn-item-route { - display: block; -} -vn-item-route a { - display: block; - text-decoration: none; - color: inherit; -} -vn-item-route a:hover { - color: white; - background-color: #424242; -} \ No newline at end of file diff --git a/client/route/src/locale/en.yml b/client/route/src/locale/en.yml deleted file mode 100644 index 6659ba5dc..000000000 --- a/client/route/src/locale/en.yml +++ /dev/null @@ -1 +0,0 @@ -Routes: Routes \ No newline at end of file diff --git a/client/route/src/locale/es.yml b/client/route/src/locale/es.yml deleted file mode 100644 index 4805a41e6..000000000 --- a/client/route/src/locale/es.yml +++ /dev/null @@ -1,15 +0,0 @@ -Basic data: Datos básicos -Logistic data: Datos logísticos -Assigned tickets: Tickets asignados -Routes: Rutas -Route: Ruta -Date: Fecha -Agency: Agencia -Driver: Conductor -Vehicle: Vehículo -Start Hour: Hora Inicio -End Hour: Hora Fin -Start Km: Km Inicio -End Km: Km Fin -Packages: Bultos -Route document: Documento de Ruta diff --git a/client/route/src/logistic-data/logistic-data.html b/client/route/src/logistic-data/logistic-data.html deleted file mode 100644 index 9ea4c802b..000000000 --- a/client/route/src/logistic-data/logistic-data.html +++ /dev/null @@ -1,26 +0,0 @@ - - -
- - - Logistic data - - - - - - - - - - - - - - - - -
\ No newline at end of file diff --git a/client/route/src/logistic-data/logistic-data.js b/client/route/src/logistic-data/logistic-data.js deleted file mode 100644 index 4230a8282..000000000 --- a/client/route/src/logistic-data/logistic-data.js +++ /dev/null @@ -1,8 +0,0 @@ -import ngModule from '../module'; - -ngModule.component('vnRouteLogisticData', { - template: require('./logistic-data.html'), - bindings: { - route: '<' - } -}); diff --git a/client/route/src/module.js b/client/route/src/module.js deleted file mode 100644 index 779683e38..000000000 --- a/client/route/src/module.js +++ /dev/null @@ -1,5 +0,0 @@ -import {ng} from 'vendor'; -import 'core'; - -const ngModule = ng.module('route', []); -export default ngModule; diff --git a/client/route/src/route.js b/client/route/src/route.js deleted file mode 100644 index a9db6db33..000000000 --- a/client/route/src/route.js +++ /dev/null @@ -1,10 +0,0 @@ -export * from './module'; - -// import components -import './index/index'; -import './search-panel/search-panel'; -import './create/create'; -import './card/card'; -import './basic-data/basic-data'; -import './logistic-data/logistic-data'; -import './tickets/tickets'; diff --git a/client/route/src/search-panel/locale/es.yml b/client/route/src/search-panel/locale/es.yml deleted file mode 100644 index 590d0e6d8..000000000 --- a/client/route/src/search-panel/locale/es.yml +++ /dev/null @@ -1,8 +0,0 @@ -Client id: Id cliente -Tax number: NIF/CIF -Name: Nombre -Social name: Razon social -Town/City: Ciudad -Postcode: Código postal -Email: Correo electrónico -Phone: Teléfono \ No newline at end of file diff --git a/client/route/src/search-panel/search-panel.html b/client/route/src/search-panel/search-panel.html deleted file mode 100644 index 3661a2c5f..000000000 --- a/client/route/src/search-panel/search-panel.html +++ /dev/null @@ -1,21 +0,0 @@ -
-
- - - - - - - - - - - - -
-
diff --git a/client/route/src/search-panel/search-panel.js b/client/route/src/search-panel/search-panel.js deleted file mode 100644 index c1b79d5de..000000000 --- a/client/route/src/search-panel/search-panel.js +++ /dev/null @@ -1,27 +0,0 @@ -import ngModule from '../module'; - -export default class Controller { - constructor($window) { - this.$window = $window; - // onSubmit() is defined by @vnSearchbar - this.onSubmit = () => {}; - } - onSearch() { - this.setStorageValue(); - this.onSubmit(this.filter); - } - $onChanges() { - var value = JSON.parse(this.$window.sessionStorage.getItem('filter')); - if (value !== undefined) - this.filter = value; - } - setStorageValue() { - this.$window.sessionStorage.setItem('filter', JSON.stringify(this.filter)); - } -} -Controller.$inject = ['$window']; - -ngModule.component('vnRouteSearchPanel', { - template: require('./search-panel.html'), - controller: Controller -}); diff --git a/client/route/src/tickets/tickets.html b/client/route/src/tickets/tickets.html deleted file mode 100644 index e78e9ab70..000000000 --- a/client/route/src/tickets/tickets.html +++ /dev/null @@ -1,7 +0,0 @@ - - - - Assigned tickets - - - \ No newline at end of file diff --git a/client/route/src/tickets/tickets.js b/client/route/src/tickets/tickets.js deleted file mode 100644 index 2405d5d9e..000000000 --- a/client/route/src/tickets/tickets.js +++ /dev/null @@ -1,8 +0,0 @@ -import ngModule from '../module'; - -ngModule.component('vnRouteTickets', { - template: require('./tickets.html'), - bindings: { - route: '<' - } -}); diff --git a/client/salix/index.js b/client/salix/index.js deleted file mode 100644 index 14e899cd0..000000000 --- a/client/salix/index.js +++ /dev/null @@ -1 +0,0 @@ -export * from './src/salix'; diff --git a/client/salix/src/components/app/app.html b/client/salix/src/components/app/app.html deleted file mode 100644 index adbc23575..000000000 --- a/client/salix/src/components/app/app.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/client/salix/src/components/app/app.js b/client/salix/src/components/app/app.js deleted file mode 100644 index 2368fdef2..000000000 --- a/client/salix/src/components/app/app.js +++ /dev/null @@ -1,18 +0,0 @@ -import ngModule from '../../module'; -import './style.scss'; - -export default class App { - constructor($scope, vnApp) { - this.$ = $scope; - this.vnApp = vnApp; - } - $postLink() { - this.vnApp.snackbar = this.$.snackbar; - } -} -App.$inject = ['$scope', 'vnApp']; - -ngModule.component('vnApp', { - template: require('./app.html'), - controller: App -}); diff --git a/client/salix/src/components/app/style.scss b/client/salix/src/components/app/style.scss deleted file mode 100644 index fabe3dcca..000000000 --- a/client/salix/src/components/app/style.scss +++ /dev/null @@ -1,26 +0,0 @@ -body { - height: 100%; -} - -vn-app { - display: block; - height: 100%; - - vn-topbar { - .logo { - float: left; - height: 1.8em; - padding: 1em; - } - vn-spinner { - float: left; - padding: .4em; - } - } - .main-view { - & > * { - height: 100%; - overflow: auto; - } - } -} diff --git a/client/salix/src/components/home/home.html b/client/salix/src/components/home/home.html deleted file mode 100644 index df6699a79..000000000 --- a/client/salix/src/components/home/home.html +++ /dev/null @@ -1,18 +0,0 @@ - - -
-
- - - - - - - - -

-
-
-
- -
\ No newline at end of file diff --git a/client/salix/src/components/home/home.js b/client/salix/src/components/home/home.js deleted file mode 100644 index d24fc4eaf..000000000 --- a/client/salix/src/components/home/home.js +++ /dev/null @@ -1,15 +0,0 @@ -import ngModule from '../../module'; -import './style.scss'; - -export default class Home { - constructor(modulesFactory, $state) { - this.modules = modulesFactory.getModules(); - this.state = $state; - } -} -Home.$inject = ['modulesFactory', '$state']; - -ngModule.component('vnHome', { - template: require('./home.html'), - controller: Home -}); diff --git a/client/salix/src/components/home/style.scss b/client/salix/src/components/home/style.scss deleted file mode 100644 index b35c1a1c7..000000000 --- a/client/salix/src/components/home/style.scss +++ /dev/null @@ -1,59 +0,0 @@ -vn-home { - padding: 2em; - vn-horizontal{ - margin-bottom: 15px; - } - h6{ - color: #3C393B; - text-align: center; - } - a:link{ - text-decoration: none; - } - vn-module-container{ - display: flex; - flex: 1; - flex-direction: row; - justify-content: center; - - .vn-module{ - display: flex; - flex: none; - margin: 10px; - background-color: #FF9300; - color: white; - - overflow:hidden; - -moz-border-radius: 6px; - -webkit-border-radius: 6px; - border-radius: 6px; - - .home__icon{ - width: 150px; - height: 150px; - img { - max-width: 50%; - margin-top: 20px; - } - } - h4{ - text-transform: capitalize; - font-size: 16pt; - } - vn-one{ - text-align: center; - } - - i{ - font-size: 75px !important; - margin: 0 auto; - padding-top: 15px; - } - &:hover{ - opacity: 0.7; - } - - - } - } -} \ No newline at end of file diff --git a/client/salix/src/components/index.js b/client/salix/src/components/index.js deleted file mode 100644 index a2346bd91..000000000 --- a/client/salix/src/components/index.js +++ /dev/null @@ -1,8 +0,0 @@ -import './app/app'; -import './home/home'; -import './main-menu/main-menu'; -import './left-menu/actions'; -import './left-menu/left-menu'; -import './left-menu/menu-item'; -import './topbar/topbar'; -import './searchbar/searchbar'; diff --git a/client/salix/src/components/left-menu/actions.html b/client/salix/src/components/left-menu/actions.html deleted file mode 100644 index 35fa96d32..000000000 --- a/client/salix/src/components/left-menu/actions.html +++ /dev/null @@ -1,5 +0,0 @@ - -
    - -
-
diff --git a/client/salix/src/components/left-menu/actions.js b/client/salix/src/components/left-menu/actions.js deleted file mode 100644 index 30d379df1..000000000 --- a/client/salix/src/components/left-menu/actions.js +++ /dev/null @@ -1,34 +0,0 @@ -import ngModule from '../../module'; - -export default class MenuActions { - constructor($state, $transitions) { - this.$state = $state; - this.deregisterCallback = $transitions.onSuccess({}, - transition => this.switchItem()); - } - switchItem() { - if (!this.items || !this.items.length) return; - - let stateName = this.$state.current.name.replace('.create', '.list').replace('.edit', '.list'); - - for (let i = 0; i < this.items.length; i++) { - this.items[i].active = (this.items[i].href === stateName); - } - } - $onInit() { - this.switchItem(); - } - $onDestroy() { - this.deregisterCallback(); - } - -} -MenuActions.$inject = ['$state', '$transitions']; - -ngModule.component('vnActions', { - template: require('./actions.html'), - controller: MenuActions, - bindings: { - items: '<' - } -}); diff --git a/client/salix/src/components/left-menu/left-menu.html b/client/salix/src/components/left-menu/left-menu.html deleted file mode 100644 index af7ffa922..000000000 --- a/client/salix/src/components/left-menu/left-menu.html +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/client/salix/src/components/left-menu/left-menu.js b/client/salix/src/components/left-menu/left-menu.js deleted file mode 100644 index 0426b74c9..000000000 --- a/client/salix/src/components/left-menu/left-menu.js +++ /dev/null @@ -1,30 +0,0 @@ -import ngModule from '../../module'; -import './style.scss'; - -export default class LeftMenu { - constructor(aclService, $state) { - this.aclService = aclService; - this.$state = $state; - this.items = []; - this.init(); - } - init() { - let routes = this.$state.current.data.routes || []; - if (routes.length) { - routes.forEach(i => { - if (i.menu && this.aclService.routeHasPermission(i)) - this.items.push({ - description: i.menu.description, - icon: i.menu.icon, - href: i.state - }); - }); - } - } -} -LeftMenu.$inject = ['aclService', '$state']; - -ngModule.component('vnLeftMenu', { - template: require('./left-menu.html'), - controller: LeftMenu -}); diff --git a/client/salix/src/components/left-menu/menu-item.html b/client/salix/src/components/left-menu/menu-item.html deleted file mode 100644 index 43a6f68b0..000000000 --- a/client/salix/src/components/left-menu/menu-item.html +++ /dev/null @@ -1,9 +0,0 @@ -
  • - - - - {{::$ctrl.item.description}} - -
  • \ No newline at end of file diff --git a/client/salix/src/components/left-menu/menu-item.js b/client/salix/src/components/left-menu/menu-item.js deleted file mode 100644 index f6c93c2da..000000000 --- a/client/salix/src/components/left-menu/menu-item.js +++ /dev/null @@ -1,8 +0,0 @@ -import ngModule from '../../module'; - -ngModule.component('vnMenuItem', { - template: require('./menu-item.html'), - bindings: { - item: '<' - } -}); diff --git a/client/salix/src/components/left-menu/style.scss b/client/salix/src/components/left-menu/style.scss deleted file mode 100644 index c14fd797e..000000000 --- a/client/salix/src/components/left-menu/style.scss +++ /dev/null @@ -1,7 +0,0 @@ - -vn-menu-item { - & > li.active { - background-color: #424242; - color: white; - } -} diff --git a/client/salix/src/components/main-menu/main-menu.html b/client/salix/src/components/main-menu/main-menu.html deleted file mode 100644 index 33703f371..000000000 --- a/client/salix/src/components/main-menu/main-menu.html +++ /dev/null @@ -1,48 +0,0 @@ -
    -
    -
    {{currentUserName}}
    -
    - - - -
      -
    • - - {{::mod.name}} -
    • -
    -
    - - - -
      -
    • - {{::lang}} -
    • -
    -
    - - - -
    diff --git a/client/salix/src/components/main-menu/main-menu.js b/client/salix/src/components/main-menu/main-menu.js deleted file mode 100644 index 33992ce1b..000000000 --- a/client/salix/src/components/main-menu/main-menu.js +++ /dev/null @@ -1,35 +0,0 @@ -import ngModule from '../../module'; -import './style.scss'; - -export default class MainMenu { - constructor($translate, $scope, $http, $window, modulesFactory) { - this.$ = $scope; - this.$http = $http; - this.$translate = $translate; - this.$window = $window; - this.modules = modulesFactory.getModules(); - this.langs = $translate.getAvailableLanguageKeys(); - } - getCurrentUserName() { - this.$http.get('/auth/api/Accounts/getCurrentUserName') - .then(json => { - this.$.currentUserName = json.data; - }); - } - - onLogoutClick() { - this.$window.location = '/logout'; - } - onChangeLangClick(lang) { - this.$translate.use(lang); - } - $onInit() { - this.getCurrentUserName(); - } -} -MainMenu.$inject = ['$translate', '$scope', '$http', '$window', 'modulesFactory']; - -ngModule.component('vnMainMenu', { - template: require('./main-menu.html'), - controller: MainMenu -}); diff --git a/client/salix/src/components/main-menu/style.scss b/client/salix/src/components/main-menu/style.scss deleted file mode 100644 index 264d518f2..000000000 --- a/client/salix/src/components/main-menu/style.scss +++ /dev/null @@ -1,43 +0,0 @@ -vn-main-menu { - #user { - display: inline-block; - padding-right: 0.2em; - margin-bottom: 8px; - height: 2.5em; - vertical-align: middle; - } - & > div > vn-icon { - font-size: 2.2em; - cursor: pointer; - - &:hover { - color: #FF9300; - } - } - .vn-popover ul { - list-style-type: none; - margin: 0; - color: white; - - li { - background-color: #FF9300; - margin-bottom: .6em; - cursor: pointer; - padding: .8em; - border-radius: .1em; - min-width: 8em; - - & > vn-icon { - padding-right: .3em; - vertical-align: middle; - } - &:hover { - background-color: #FF9300; - opacity: 0.7 !important; - } - &:last-child { - margin-bottom: 0; - } - } - } -} \ No newline at end of file diff --git a/client/salix/src/components/searchbar/searchbar.html b/client/salix/src/components/searchbar/searchbar.html deleted file mode 100644 index e54a00ccd..000000000 --- a/client/salix/src/components/searchbar/searchbar.html +++ /dev/null @@ -1,14 +0,0 @@ -
    - - - - - - - -
    \ No newline at end of file diff --git a/client/salix/src/components/searchbar/searchbar.js b/client/salix/src/components/searchbar/searchbar.js deleted file mode 100644 index 324ddf5a4..000000000 --- a/client/salix/src/components/searchbar/searchbar.js +++ /dev/null @@ -1,161 +0,0 @@ -import ngModule from '../../module'; - -export default class Controller { - constructor($element, $scope, $document, $compile, vnPopover, $timeout, $state, $transitions) { - this.element = $element[0]; - this.$scope = $scope; - this.$document = $document; - this.$compile = $compile; - this.vnPopover = vnPopover; - this.$timeout = $timeout; - this.stringSearch = ''; - this.$state = $state; - this.deregisterCallback = $transitions.onStart({}, - transition => this.changeState(transition)); - } - - clearFilter() { - this.index.filter = { - page: 1, - size: 20 - }; - } - - setFilter(filterObject) { - this.clearFilter(); - Object.assign(this.index.filter, filterObject); - } - - getFiltersFromString(stringSearch) { - let result = {}; - if (stringSearch) { - // find pattern key:value or key:(extra value) and returns array - let findPattern = stringSearch.match(/((([\w_]+):([\w_]+))|([\w_]+):\(([\w_ ]+)\))/gi); - let remnantString = (stringSearch.replace(/((([\w_]+):([\w_]+))|([\w_]+):\(([\w_ ]+)\))/gi, '')).trim(); - if (findPattern) { - for (let i = 0; i < findPattern.length; i++) { - let aux = findPattern[i].split(':'); - let property = aux[0]; - let value = aux[1].replace(/\(|\)/g, ''); - result[property] = value.trim(); - } - } - if (remnantString) { - result.search = remnantString; - } - } - return result; - } - - createStringFromObject(filterObject) { - let search = []; - let keys = Object.keys(filterObject); - if (keys.length) { - keys.forEach(k => { - let ignore = (this.ignoreKeys && this.ignoreKeys instanceof Array && this.ignoreKeys.indexOf(k) !== -1); - if (!ignore) { - let value = filterObject[k]; - - if (typeof value === 'string' && value.indexOf(' ') !== -1) { - search.push(`${k}:(${value})`); - } else if (typeof value !== 'object') { - search.push(`${k}:${value}`); - } - } - }); - - if (filterObject.search) - search.unshift(filterObject.search); - } - return (search.length) ? search.join(' ') : ''; - } - - changeState(transition) { - return !(transition._targetState._identifier.name === this.$state.current.name); - } - - pushFiltersToState(filters) { - let history = window.history || {pushState: () => { - console.error('Error in history.pushState(): Browser incompatibility error'); - }}; - let aux = window.location.hash.split('?q='); - if (Object.keys(filters).length) - history.pushState({}, null, `${aux[0]}?q=${encodeURIComponent(JSON.stringify(filters))}`); - else - history.pushState({}, null, aux[0]); - } - - onpenFilters(event) { - let filter = {}; - if (this.stringSearch) { - filter = this.getFiltersFromString(this.stringSearch); - } - - this.child = this.vnPopover.showComponent(this.popover, this.$scope, this.element); - - // XXX: ¿Existe una forma más adecuada de acceder al controlador de un componente? - var childCtrl = angular.element(this.child).isolateScope().$ctrl; - childCtrl.filter = Object.assign({}, filter); - childCtrl.onSubmit = filter => this.onChildSubmit(filter); - if (this.data) - childCtrl.data = Object.assign({}, this.data); - event.preventDefault(); - } - - onChildSubmit(filter) { - this.stringSearch = this.createStringFromObject(filter); - this.clearFilter(); - this.$timeout(() => { - this.onSubmit(); - }); - } - - onSubmit() { - let filter = {}; - if (this.stringSearch) { - filter = this.getFiltersFromString(this.stringSearch); - } - this.setFilter(filter); - - if (this.onSearch) - this.onSearch(); - - if (angular.element(this.child)) { - if (angular.element(this.child).scope()) - angular.element(this.child).scope().$destroy(); - angular.element(this.child).remove(); - } - delete this.child; - this.pushFiltersToState(filter); - } - - $onDestroy() { - this.clearFilter(); - this.deregisterCallback(); - } - - $onInit() { - if (this.$state.params.q) { - let filter = JSON.parse(decodeURIComponent(this.$state.params.q)); - this.stringSearch = this.createStringFromObject(filter); - } - this.$timeout(() => { - this.onSubmit(); - }); - } -} -Controller.$inject = ['$element', '$scope', '$document', '$compile', 'vnPopover', '$timeout', '$state', '$transitions']; - -ngModule.component('vnSearchbar', { - template: require('./searchbar.html'), - bindings: { - index: '<', - onSearch: '&', - advanced: '=', - popover: '@', - label: '@?', - ignoreKeys: ' - \ No newline at end of file diff --git a/client/salix/src/components/topbar/topbar.js b/client/salix/src/components/topbar/topbar.js deleted file mode 100644 index 583354ad1..000000000 --- a/client/salix/src/components/topbar/topbar.js +++ /dev/null @@ -1,7 +0,0 @@ -import ngModule from '../../module'; -import './style.scss'; - -ngModule.component('vnTopbar', { - template: require('./topbar.html'), - transclude: true -}); diff --git a/client/salix/src/config-routes.js b/client/salix/src/config-routes.js deleted file mode 100644 index 4f3652ced..000000000 --- a/client/salix/src/config-routes.js +++ /dev/null @@ -1,75 +0,0 @@ -import ngModule from './module'; -import deps from 'client/modules.yml'; -import modules from 'client/spliting'; -import splitingRegister from 'core/src/lib/spliting-register'; - -function loader(moduleName, validations) { - load.$inject = ['vnModuleLoader']; - function load(moduleLoader) { - return moduleLoader.load(moduleName, validations); - } - return load; -} - -config.$inject = ['$stateProvider', '$urlRouterProvider', 'aclServiceProvider', 'modulesFactoryProvider']; -function config($stateProvider, $urlRouterProvider, aclServiceProvider, modulesFactory) { - splitingRegister.graph = deps; - splitingRegister.modules = modules; - - let aclService = aclServiceProvider.$get(); - - function getParams(route) { - let params = ''; - let temporalParams = []; - - if (!route.params) { - return params; - } - - Object.keys(route.params).forEach(key => { - temporalParams.push(`${key} = "${route.params[key]}"`); - }); - return temporalParams.join(' '); - } - - $urlRouterProvider.otherwise('/'); - - $stateProvider.state('home', { - url: '/', - template: '' - }); - - for (let file in window.routes) { - let fileRoutes = window.routes[file].routes; - let moduleName = window.routes[file].module; - let validations = window.routes[file].validations || false; - let mainModule = modulesFactory.$get().getMainRoute(fileRoutes); - if (mainModule) { - let count = fileRoutes.length; - for (let i = 0; i < count; i++) { - let route = fileRoutes[i]; - if (aclService.routeHasPermission(route)) { - let configRoute = { - url: route.url, - template: `<${route.component} ${getParams(route)}>`, - resolve: { - loader: loader(moduleName, validations) - }, - data: { - routes: fileRoutes - } - }; - if (route.abstract) - configRoute.abstract = true; - if (route.routeParams) - configRoute.params = route.routeParams; - - $stateProvider.state(route.state, configRoute); - } else if (route.state === mainModule.state) { - break; - } - } - } - } -} -ngModule.config(config); diff --git a/client/salix/src/locale/en.yml b/client/salix/src/locale/en.yml deleted file mode 100644 index fbae9a742..000000000 --- a/client/salix/src/locale/en.yml +++ /dev/null @@ -1,11 +0,0 @@ -Applications: Applications -Home: Home -Notifications: Notifications -Logout: Logout -Change language: Change language -Profile: Profile -Data saved!: Data saved! -Can't contact with server: Can't contact with server -Push on applications menu: To open a module push on applications menu -Clients: Clients -Modules access: Modules access \ No newline at end of file diff --git a/client/salix/src/locale/es.yml b/client/salix/src/locale/es.yml deleted file mode 100644 index fe3cdf228..000000000 --- a/client/salix/src/locale/es.yml +++ /dev/null @@ -1,21 +0,0 @@ -Applications: Aplicaciones -Home: Inicio -Notifications: Notificaciones -Logout: Cerrar sesión -Change language: Cambiar idioma -Profile: Perfil -Data saved!: ¡Datos guardados! -Can't contact with server: No se pudo contactar con el servidor -Push on applications menu: Para abrir un módulo pulsa en el menú de aplicaciones -Clients: Clientes -Routes : Rutas -Production : Producción -Modules access : Acceso a módulos -Locator: Localizador -Items: Artículos -name: Nombre -credit: Crédito -phone: Teléfono -creditInsurance: Crédito Asegurado -Return to module index: Volver a la página principal del módulo -Preview: Vista previa \ No newline at end of file diff --git a/client/salix/src/module.js b/client/salix/src/module.js deleted file mode 100644 index c0c539f3b..000000000 --- a/client/salix/src/module.js +++ /dev/null @@ -1,33 +0,0 @@ -import {ng} from 'vendor'; -import 'core'; - -export const appName = 'salix'; - -const ngModule = ng.module('salix', ['vnCore']); -export default ngModule; - -config.$inject = ['$translatePartialLoaderProvider', '$httpProvider', '$qProvider']; -export function config($translatePartialLoaderProvider, $httpProvider, $qProvider) { - $translatePartialLoaderProvider.addPart(appName); - $httpProvider.interceptors.push('vnInterceptor'); - - // TODO: Handle or remove unhandled rejections - // $qProvider.errorOnUnhandledRejections(false); -} -ngModule.config(config); - -const HOOK_ABORTED_TRANSITION = 3; - -run.$inject = ['$window', '$rootScope', 'vnApp', '$state']; -export function run($window, $rootScope, vnApp, $state) { - $window.validations = {}; - vnApp.name = appName; - - $rootScope.$on('$viewContentLoaded', () => {}); - window.myAppErrorLog = []; - $state.defaultErrorHandler(function(error) { - if (error.type === HOOK_ABORTED_TRANSITION) - window.myAppErrorLog.push(error); - }); -} -ngModule.run(run); diff --git a/client/salix/src/modules-factory.js b/client/salix/src/modules-factory.js deleted file mode 100644 index 02c3e845c..000000000 --- a/client/salix/src/modules-factory.js +++ /dev/null @@ -1,37 +0,0 @@ -import ngModule from './module'; - -function modulesFactory(aclService) { - function getMainRoute(routeCollection) { - let cant = routeCollection.length; - for (let i = 0; i < cant; i++) { - if (!routeCollection[i].abstract) { - return routeCollection[i]; - } - } - return null; - } - - function getModules() { - let modules = []; - for (let file in window.routes) { - let card = { - name: routes[file].name || routes[file].module, - icon: routes[file].icon || '' - }; - let mainRoute = getMainRoute(window.routes[file].routes); - if (mainRoute && aclService.routeHasPermission(mainRoute)) { - card.route = mainRoute; - modules.push(card); - } - } - return modules; - } - - return { - getModules: getModules, - getMainRoute: getMainRoute - }; -} -modulesFactory.$inject = ['aclService']; - -ngModule.factory('modulesFactory', modulesFactory); diff --git a/client/salix/src/package.json b/client/salix/src/package.json deleted file mode 100644 index 626726422..000000000 --- a/client/salix/src/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@salix/core", - "version": "0.0.0", - "description": "", - "main": "index.js", - "repository": { - "type": "git", - "url": "http://git.verdnatura.es:/salix" - } -} diff --git a/client/salix/src/salix.js b/client/salix/src/salix.js deleted file mode 100644 index 88ff6e001..000000000 --- a/client/salix/src/salix.js +++ /dev/null @@ -1,5 +0,0 @@ -import './module'; -import './config-routes'; -import './components/index'; -import './styles/index'; -import './modules-factory'; diff --git a/client/salix/src/styles/background.scss b/client/salix/src/styles/background.scss deleted file mode 100644 index b3a7ec7f2..000000000 --- a/client/salix/src/styles/background.scss +++ /dev/null @@ -1,36 +0,0 @@ -@import "colors"; - -$bg-main: $color-green; -$bg-minor: $color-orange; -$bg-content: $color-light-grey; -$bg-panel: $color-white; -$bg-dark-bar: $color-dark; -$bg-dark-menu: $color-dark-grey; - -html [bg-main], .bg-main { - background-color: $bg-main; -} -html [bg-minor], .bg-minor { - background-color: $bg-minor; -} -html [bg-content], .bg-content { - background-color: $bg-content; -} -html [bg-panel], .bg-panel { - background-color: $bg-panel; -} -html [bg-dark-bar], .bg-dark-bar { - background-color: $bg-dark-bar; -} -html [bg-dark-menu], .bg-dark-menu { - background-color: darken($bg-dark-menu, 35%); -} -/* Color para items seleccionados */ -.bg-dark-item { - background-color: $bg-dark-bar; - color: $color-white; -} -/* Color para items inactivos */ -.bg-opacity-item { - opacity: 0.6; -} diff --git a/client/salix/src/styles/border.scss b/client/salix/src/styles/border.scss deleted file mode 100644 index bd046c559..000000000 --- a/client/salix/src/styles/border.scss +++ /dev/null @@ -1,51 +0,0 @@ -@import "colors"; - -$border-color: #AAA; -$border-thin: 1px; -$border-thick: 2px; - -html [border-none], .border-none { - border: 0; -} - -/* Solid border */ - -html [border-solid], .border-solid { - border: $border-thin solid $border-color; -} -html [border-solid-top], .border-solid-top { - border-top: $border-thin solid $border-color; -} -html [border-solid-left], .border-solid-left { - border-left: $border-thin solid $border-color; -} -html [border-solid-right], .border-solid-right { - border-right: $border-thin solid $border-color; -} -html [border-solid-bottom], .border-solid-bottom { - border-bottom: $border-thin solid $border-color; -} - -/* Dashed border */ - -html [border-dashed], .border-dashed { - border: $border-thin dashed $border-color; -} -html [border-dashed-top], .border-dashed-top { - border-top: $border-thin dashed $border-color; -} -html [border-dashed-left], .border-dashed-left { - border-left: $border-thin dashed $border-color; -} -html [border-dashed-right], .border-dashed-right { - border-right: $border-thin dashed $border-color; -} -html [border-dashed-bottom], .border-dashed-bottom { - border-bottom: $border-thin dashed $border-color; -} - -/* Border Radius */ - -html [border-radius], .border-radius { - border-radius: .3em; -} \ No newline at end of file diff --git a/client/salix/src/styles/colors.scss b/client/salix/src/styles/colors.scss deleted file mode 100644 index d2db195f1..000000000 --- a/client/salix/src/styles/colors.scss +++ /dev/null @@ -1,12 +0,0 @@ - -$color-green: rgb(139,195,74); -$color-orange: rgb(255,171,64); -$color-white: white; -$color-dark: #3c393b; -$color-dark-grey: #424242; -$color-light-grey: #e6e6e6; -$color-medium-grey: #9D9D9D; -$color-medium-green: #CCEC9E; -$color-medium-orange: #FFD29C; -$color-light-green: #D7F1BD; -$color-light-orange: #FFDEBB; \ No newline at end of file diff --git a/client/salix/src/styles/display.scss b/client/salix/src/styles/display.scss deleted file mode 100644 index c296eec69..000000000 --- a/client/salix/src/styles/display.scss +++ /dev/null @@ -1,49 +0,0 @@ -.display-block { - display: block; -} - -.well { - min-height: 20px; - padding: 19px; - margin-bottom: 20px; - background-color: #f5f5f5; - border: 1px solid #e3e3e3; - border-radius: 4px; - box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05); -} - -.form-group { - margin-bottom: 15px; -} - -/* Label del popover */ -.popover-button { - padding: 3px 3px 3px 0px; - height: auto; - min-width: auto; -} - -.popover-label { - font-family: vn-font-bold; - color: black; - padding-top:5px; -} - -/* Icon cuadrado */ -.icon-square{ - min-width: 0px; - height: 46px; - line-height: 0px; -} - -input:disabled, button:disabled { - cursor: not-allowed !important; -} - -input[type="submit"]:disabled, button:disabled { - opacity: 0.7; -} - -.descriptor-icon{ - font-size:60px; -} diff --git a/client/salix/src/styles/font-family.scss b/client/salix/src/styles/font-family.scss deleted file mode 100644 index 38a87a3e8..000000000 --- a/client/salix/src/styles/font-family.scss +++ /dev/null @@ -1,12 +0,0 @@ -@font-face { - font-family: vn-font-medium; - src: url(./fonts/Roboto-Medium.ttf); -} -@font-face { - font-family: vn-font; - src: url(./fonts/Roboto-Regular.ttf); -} -@font-face { - font-family: vn-font-bold; - src: url(./fonts/Roboto-Bold.ttf); -} diff --git a/client/salix/src/styles/font-style.scss b/client/salix/src/styles/font-style.scss deleted file mode 100644 index bb26140ee..000000000 --- a/client/salix/src/styles/font-style.scss +++ /dev/null @@ -1,24 +0,0 @@ -@import "colors"; -@import "font-family"; - -$font-color: $color-dark-grey; - -body { - color: $font-color; - font-family: vn-font; -} -html [uppercase], .uppercase { - text-transform: uppercase; -} - -html [green], .green{color: $color-green} -html [orange], .orange{color: $color-orange} -html [white], .white{color: $color-white} -html [dark], .dark{color: $color-dark} -html [dark-grey], .dark-grey{color: $color-dark-grey} -html [light-grey], .light-grey{color: $color-light-grey} -html [medium-grey], .medium-grey{color: $color-medium-grey} -html [medium-green], .medium-green{color: $color-medium-green} -html [medium-orange], .medium-orange{color: $color-medium-orange} -html [light-green], .light-green{color: $color-light-green} -html [light-orange], .light-orange{color: $color-light-orange} \ No newline at end of file diff --git a/client/salix/src/styles/index.js b/client/salix/src/styles/index.js deleted file mode 100644 index a3e9f74a3..000000000 --- a/client/salix/src/styles/index.js +++ /dev/null @@ -1,10 +0,0 @@ -import './title.scss'; -import './layout.scss'; -import './display.scss'; -import './margin.scss'; -import './padding.scss'; -import './background.scss'; -import './border.scss'; -import './font-style.scss'; -import './misc.scss'; -import './summary.scss'; diff --git a/client/salix/src/styles/margin.scss b/client/salix/src/styles/margin.scss deleted file mode 100644 index 800ed5e83..000000000 --- a/client/salix/src/styles/margin.scss +++ /dev/null @@ -1,116 +0,0 @@ - -$margin-none: 0; -$margin-small: 8px; -$margin-medium: 16px; -$margin-large: 32px; - -/* None */ - -html [margin-none], .margin-none { - margin: $margin-none; -} - -/* Small */ - -html [margin-small], .margin-small { - margin: $margin-small; -} -html [margin-small-top], .margin-small-top { - margin-top: $margin-small; -} -html [margin-small-left], .margin-small-left { - margin-left: $margin-small; -} -html [margin-small-right], .margin-small-right { - margin-right: $margin-small; -} -html [margin-small-bottom], .margin-small-bottom { - margin-bottom: $margin-small; -} -html [margin-small-v], .margin-small-v { - margin-top: $margin-small; - margin-bottom: $margin-small; -} -html [margin-small-h], .margin-small-h { - margin-left: $margin-small; - margin-right: $margin-small; -} - -/* Medium */ - -html [margin-medium], .margin-medium { - margin: $margin-medium; -} -html [margin-medium-top], .margin-medium-top { - margin-top: $margin-medium; -} -html [margin-medium-left], .margin-medium-left { - margin-left: $margin-medium; -} -html [margin-medium-right], .margin-medium-right { - margin-right: $margin-medium; -} -html [margin-medium-bottom], .margin-medium-bottom { - margin-bottom: $margin-medium; -} -html [margin-medium-v], .margin-medium-v { - margin-top: $margin-medium; - margin-bottom: $margin-medium; -} -html [margin-medium-h], .margin-medium-h { - margin-left: $margin-medium; - margin-right: $margin-medium; -} - -/* Large */ - -html [margin-large], .margin-large { - margin: $margin-large; -} -html [margin-large-top], .margin-large-top { - margin-top: $margin-large; -} -html [margin-large-left], .margin-large-left { - margin-left: $margin-large; -} -html [margin-large-right], .margin-large-right { - margin-right: $margin-large; -} -html [margin-large-bottom], .margin-large-bottom { - margin-bottom: $margin-large; -} -html [margin-large-v], .margin-large-v { - margin-top: $margin-large; - margin-bottom: $margin-large; -} -html [margin-large-h], .margin-large-h { - margin-left: $margin-large; - margin-right: $margin-large; -} - - -/* Minus Small */ - -html [margin--small], .margin--small { - margin: -$margin-small; -} -html [margin--small-top], .margin--small-top { -margin-top: -$margin-small; -} -html [margin--small-left], .margin--small-left { -margin-left: -$margin-small; -} -html [margin--small-right], .margin--small-right { -margin-right: -$margin-small; -} -html [margin--small-bottom], .margin--small-bottom { -margin-bottom: -$margin-small; -} -html [margin--small-v], .margin--small-v { -margin-top: -$margin-small; -margin-bottom: -$margin-small; -} -html [margin--small-h], .margin--small-h { -margin-left: -$margin-small; -margin-right: -$margin-small; -} \ No newline at end of file diff --git a/client/salix/src/styles/misc.scss b/client/salix/src/styles/misc.scss deleted file mode 100644 index e20bda7ed..000000000 --- a/client/salix/src/styles/misc.scss +++ /dev/null @@ -1,234 +0,0 @@ -@import "padding"; -@import "margin"; -@import "colors"; -@import "border"; - - -a:focus, -input:focus, -button:focus -{ - outline: none; -} -button::-moz-focus-inner, -input[type=submit]::-moz-focus-inner, -input[type=button]::-moz-focus-inner, -input[type=reset]::-moz-focus-inner -{ - border: none; -} - -.form { - height: 100%; - box-sizing: border-box; - padding: $pad-large; - max-width: 1000px; -} -form vn-horizontal > * { - padding: 0 .4em; -} -form vn-horizontal > *:first-child { - padding-left: 0; -} -form vn-horizontal > *:last-child { - padding-right: 0; -} - -html [fixed-bottom-right] { - position: fixed; - bottom: 2em; - right: 2em; -} -html [text-center], .text-center { - text-align: center; -} -html [text-right], .text-right{ - text-align: right; -} -html [text-left], .text-left{ - text-align: left; -} -html [vn-right], .vn-right{ - float: right; -} -html [vn-left], .vn-left{ - float: left; -} -html [vn-center], .vn-center{ - justify-content: center; -} - -.list > vn-none{ - min-width: 60px; -} - -.list-element{ - padding: 8px 0 0 0; - border-bottom: 1px solid $color-medium-grey; - i { - color: $color-orange; - } - &:hover{ - background-color: $color-light-grey; - } -} -.tooltip { - .list-header{ - border-bottom: 3px solid $color-medium-grey; - font-family: vn-font-bold; - text-align: center - } - .list-element{ - white-space: nowrap; - } -} -.list-footer{ - font-family: vn-font-bold; - border-top: 3px solid $color-medium-grey; -} -.list-element.warning{ - background-color: $color-medium-orange; -} -.list-element.success{ - background-color: $color-medium-green; - -} -.list-element.success:hover{ - background-color: $color-light-green; -} -.list-element.warning:hover{ - background-color: $color-light-orange; -} -.flatpickr-month, .flatpickr-weekdays, span.flatpickr-weekday { - background-color: $color-orange; -} - -html [pointer], .pointer{ - cursor: pointer; -} - -html [noDrop], .noDrop{ - cursor: no-drop; -} - -a { - color: inherit; -} - -.vn-clickable { - cursor: pointer; - transition: background-color 250ms ease-out; - - &:hover { - background-color: rgba(0, 0, 0, .1); - } -} - -button { - @extend .vn-clickable; -} - -vn-label { - font-size: .9em; - color: #666; -} - -vn-button-bar { - display: block; - margin-top: $margin-small; -} - -vn-main-block { - display:block; - max-width: 1920px; - width:100%; - margin: 0 auto; - - .left-block { - width: 16em; - min-width: 16em; - padding-left: 1em; - padding-bottom: 1em; - } -} - -.vn-descriptor { - .header { - background: #ffa410; - color: white; - justify-content: space-between; - align-items: stretch; - - & > vn-icon { - padding: .1em; - font-size: 2.5em; - } - & > a { - @extend .vn-clickable; - - display: flex; - align-items: center; - padding: .5em; - color: white; - text-decoration: none; - transition: background-color 250ms ease-out; - - & > vn-icon { - font-size: 1.8em; - } - } - } - .footer { - text-align: center; - & > vn-icon { - color: #666; - opacity: .4; - padding: 0 5% 0 5%; - font-size: 1.5em; - } - & > vn-icon.bright { - color: #ffa410; - opacity: 1; - } - } -} - -.vn-list { - max-width: 36em; - margin: 0 auto; -} - -.vn-list-item { - @extend .pad-medium; - @extend .border-solid-bottom; - @extend .vn-clickable; - - display: block; - text-decoration: none; - color: inherit; - - & > vn-horizontal > .buttons { - align-items: center; - - vn-icon { - opacity: .4; - color: #ffa410; - margin-left: .5em; - transition: opacity 250ms ease-out; - - &:hover { - opacity: 1; - } - } - } -} -/** START - FORM ELEMENTS DISABLED **/ -fieldset[disabled] .mdl-textfield .mdl-textfield__input, .mdl-textfield.is-disabled .mdl-textfield__input, -fieldset[disabled] .mdl-checkbox .mdl-checkbox__label, .mdl-checkbox.is-disabled .mdl-checkbox__label{ - border: none !important; - color: inherit !important; -} -fieldset[disabled] .mdl-textfield .mdl-textfield__label, .mdl-textfield.is-disabled.is-disabled .mdl-textfield__label { - color: rgb(255,171,64) !important; -} -/** END - FORM ELEMENTS DISABLED **/ \ No newline at end of file diff --git a/client/salix/src/styles/padding.scss b/client/salix/src/styles/padding.scss deleted file mode 100644 index cfa9bc170..000000000 --- a/client/salix/src/styles/padding.scss +++ /dev/null @@ -1,89 +0,0 @@ - -$pad-none: 0; -$pad-small: 8px; -$pad-medium: 16px; -$pad-large: 32px; - -/* None */ - -html [pad-none], .pad-none { - padding: $pad-none; -} - -/* Small */ - -html [pad-small], .pad-small { - padding: $pad-small; -} -html [pad-small-left], .pad-small-left { - padding-left: $pad-small; -} -html [pad-small-right], .pad-small-right { - padding-right: $pad-small; -} -html [pad-small-top], .pad-small-top { - padding-top: $pad-small; -} -html [pad-small-bottom], .pad-small-bottom { - padding-bottom: $pad-small; -} -html [pad-small-v], .pad-small-v { - padding-top: $pad-small; - padding-bottom: $pad-small; -} -html [pad-small-h], .pad-small-h { - padding-left: $pad-small; - padding-right: $pad-small; -} - -/* Medium */ - -html [pad-medium], .pad-medium { - padding: $pad-medium; -} -html [pad-medium-left], .pad-medium-left { - padding-left: $pad-medium; -} -html [pad-medium-right], .pad-medium-right { - padding-right: $pad-medium; -} -html [pad-medium-top], .pad-medium-top { - padding-top: $pad-medium; -} -html [pad-medium-bottom], .pad-medium-bottom { - padding-bottom: $pad-medium; -} -html [pad-medium-v], .pad-medium-v { - padding-top: $pad-medium; - padding-bottom: $pad-medium; -} -html [pad-medium-h], .pad-medium-h { - padding-left: $pad-medium; - padding-right: $pad-medium; -} - -/* Large */ - -html [pad-large], .pad-large { - padding: $pad-large; -} -html [pad-large-left], .pad-large-left { - padding-left: $pad-large; -} -html [pad-large-right], .pad-large-right { - padding-right: $pad-large; -} -html [pad-large-top], .pad-large-top { - padding-top: $pad-large; -} -html [pad-large-bottom], .pad-large-bottom { - padding-bottom: $pad-large; -} -html [pad-large-v], .pad-large-v { - padding-top: $pad-large; - padding-bottom: $pad-large; -} -html [pad-large-h], .pad-large-h { - padding-left: $pad-large; - padding-right: $pad-large; -} diff --git a/client/salix/src/styles/summary.scss b/client/salix/src/styles/summary.scss deleted file mode 100644 index 9f1be4662..000000000 --- a/client/salix/src/styles/summary.scss +++ /dev/null @@ -1,65 +0,0 @@ -@import "./colors"; - -.summary{ - h5 { - border-bottom: 2px solid $color-orange; - margin: 0 0 5px 0 - } - h5.tittle { - border: none; - background: $color-orange; - color: $color-white; - } - p { - margin: 0 0 5px 0 - } - p:after { - content: ' '; - overflow: hidden; - display: block; - clear: both - } -} - -.vn-dialog.dialog-summary { - vn-card { - border: none; - box-shadow: none; - } - - vn-vertical { - padding: 0 !important - } - - & > div > button.close > vn-icon { - color: $color-orange; - } - - & > div { - padding: 0 - } - - tpl-body { - width:auto; - background-color: transparent; - padding: 0 2em - } - - .body { - overflow: auto; - margin-top: 2em; - max-height: 700px; - } - - form { - min-width: 680px; - } - - .buttons { - margin: 0 - } - - vn-check label span { - font-size: .9em - } -} \ No newline at end of file diff --git a/client/salix/src/styles/title.scss b/client/salix/src/styles/title.scss deleted file mode 100644 index c32735686..000000000 --- a/client/salix/src/styles/title.scss +++ /dev/null @@ -1,26 +0,0 @@ - -h1 { - font-size: 32pt; -} -h2 { - font-size: 28pt; -} -h3 { - font-size: 24pt; -} -h4 { - font-size: 20pt; -} -h5 { - font-size: 16pt; -} -h6 { - font-size: 12pt; -} - -h1, h2, h3, h4, h5, h6 { - padding: 0; - margin-top: 0; - margin-bottom: .2em; - font-family: vn-font-bold; -} \ No newline at end of file diff --git a/client/spliting.js b/client/spliting.js deleted file mode 100644 index d5f641029..000000000 --- a/client/spliting.js +++ /dev/null @@ -1,14 +0,0 @@ -export default { - client: - cb => require.ensure([], () => cb(require('client'))), - production: - cb => require.ensure([], () => cb(require('production'))), - route: - cb => require.ensure([], () => cb(require('route'))), - locator: - cb => require.ensure([], () => cb(require('locator'))), - item: - cb => require.ensure([], () => cb(require('item'))), - ticket: - cb => require.ensure([], () => cb(require('ticket'))) -}; diff --git a/client/test_index.js b/client/test_index.js deleted file mode 100644 index 34d621356..000000000 --- a/client/test_index.js +++ /dev/null @@ -1,6 +0,0 @@ -// require all modules ending in ".spec" from the -// current directory and all subdirectories -import 'angular'; -import 'angular-mocks'; -var testsContext = require.context('./', true, /\.spec\.js$/); -testsContext.keys().forEach(testsContext); diff --git a/client/ticket/index.js b/client/ticket/index.js deleted file mode 100644 index dc559e2d9..000000000 --- a/client/ticket/index.js +++ /dev/null @@ -1 +0,0 @@ -export * from './src/ticket'; diff --git a/client/ticket/routes.json b/client/ticket/routes.json deleted file mode 100644 index 8fd9b65f5..000000000 --- a/client/ticket/routes.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "module": "ticket", - "name": "Tickets", - "icon": "receipt", - "validations": false, - "routes": [ - { - "url": "/tickets", - "state": "tickets", - "component": "vn-ticket-index", - "acl": ["developer"] - } - ] -} \ No newline at end of file diff --git a/client/ticket/src/index/index.html b/client/ticket/src/index/index.html deleted file mode 100644 index 51a50474c..000000000 --- a/client/ticket/src/index/index.html +++ /dev/null @@ -1,24 +0,0 @@ - -
    -
    - - - - - - - - - - - -
    -
    - - - diff --git a/client/ticket/src/index/index.js b/client/ticket/src/index/index.js deleted file mode 100644 index bc514194c..000000000 --- a/client/ticket/src/index/index.js +++ /dev/null @@ -1,14 +0,0 @@ -import ngModule from '../module'; -import './item'; - -export default class Controller { - search(index) { - index.accept(); - } -} -Controller.$inject = []; - -ngModule.component('vnTicketIndex', { - template: require('./index.html'), - controller: Controller -}); diff --git a/client/ticket/src/index/item.html b/client/ticket/src/index/item.html deleted file mode 100644 index eed354bff..000000000 --- a/client/ticket/src/index/item.html +++ /dev/null @@ -1,17 +0,0 @@ - - - -
    {{::$ctrl.ticket.name}}
    -
    Id {{::$ctrl.ticket.id}}
    -
    - - - - -
    -
    diff --git a/client/ticket/src/index/item.js b/client/ticket/src/index/item.js deleted file mode 100644 index c48d773f1..000000000 --- a/client/ticket/src/index/item.js +++ /dev/null @@ -1,20 +0,0 @@ -import ngModule from '../module'; - -class Controller { - onClick(event) { - if (event.defaultPrevented) - event.stopImmediatePropagation(); - } - - preview(event) { - event.preventDefault(); - } -} - -ngModule.component('vnTicketItem', { - controller: Controller, - template: require('./item.html'), - bindings: { - ticket: '<' - } -}); diff --git a/client/ticket/src/index/style.scss b/client/ticket/src/index/style.scss deleted file mode 100644 index eb363a9a7..000000000 --- a/client/ticket/src/index/style.scss +++ /dev/null @@ -1,3 +0,0 @@ -vn-ticket-item { - display: block; -} \ No newline at end of file diff --git a/client/ticket/src/locale/en.yml b/client/ticket/src/locale/en.yml deleted file mode 100644 index 1f272d420..000000000 --- a/client/ticket/src/locale/en.yml +++ /dev/null @@ -1 +0,0 @@ -Tickets: Tickets \ No newline at end of file diff --git a/client/ticket/src/locale/es.yml b/client/ticket/src/locale/es.yml deleted file mode 100644 index 1f272d420..000000000 --- a/client/ticket/src/locale/es.yml +++ /dev/null @@ -1 +0,0 @@ -Tickets: Tickets \ No newline at end of file diff --git a/client/ticket/src/module.js b/client/ticket/src/module.js deleted file mode 100644 index 9a852e647..000000000 --- a/client/ticket/src/module.js +++ /dev/null @@ -1,5 +0,0 @@ -import {ng} from 'vendor'; -import 'core'; - -const ngModule = ng.module('ticket', ['vnCore']); -export default ngModule; diff --git a/client/ticket/src/ticket.js b/client/ticket/src/ticket.js deleted file mode 100644 index c7b861d2c..000000000 --- a/client/ticket/src/ticket.js +++ /dev/null @@ -1,4 +0,0 @@ -export * from './module'; - -import './index/index'; - diff --git a/client/vendor/index.js b/client/vendor/index.js deleted file mode 100644 index 8d2b31810..000000000 --- a/client/vendor/index.js +++ /dev/null @@ -1 +0,0 @@ -export * from './src/vendor'; diff --git a/client/vendor/src/angular-cookies.js b/client/vendor/src/angular-cookies.js deleted file mode 100644 index 559ea067b..000000000 --- a/client/vendor/src/angular-cookies.js +++ /dev/null @@ -1,5 +0,0 @@ -import 'angular-cookies'; - -export const angularCookies = { - name: 'ngCookies' -}; diff --git a/client/vendor/src/angular-paging.js b/client/vendor/src/angular-paging.js deleted file mode 100644 index 8a2ad3a7b..000000000 --- a/client/vendor/src/angular-paging.js +++ /dev/null @@ -1,5 +0,0 @@ -import 'angular-paging'; - -export const angularPaging = { - name: 'bw.paging' -}; diff --git a/client/vendor/src/angular-translate.js b/client/vendor/src/angular-translate.js deleted file mode 100644 index aedc10067..000000000 --- a/client/vendor/src/angular-translate.js +++ /dev/null @@ -1,6 +0,0 @@ -import 'angular-translate'; -import 'angular-translate-loader-partial'; - -export const angularTranslate = { - name: 'pascalprecht.translate' -}; diff --git a/client/vendor/src/angular-ui-router.js b/client/vendor/src/angular-ui-router.js deleted file mode 100644 index cb0d4a321..000000000 --- a/client/vendor/src/angular-ui-router.js +++ /dev/null @@ -1,5 +0,0 @@ -import '@uirouter/angularjs'; - -export const angularUiRouter = { - name: 'ui.router' -}; diff --git a/client/vendor/src/angular.js b/client/vendor/src/angular.js deleted file mode 100644 index 769e23ede..000000000 --- a/client/vendor/src/angular.js +++ /dev/null @@ -1,8 +0,0 @@ -import * as angular from 'angular'; - -export const ng = { - module: angular.module, - bootstrap: angular.bootstrap, - $$minErr: angular.$$minErr, - angular: angular -}; diff --git a/client/vendor/src/flatpickr.js b/client/vendor/src/flatpickr.js deleted file mode 100644 index 8637b3b6a..000000000 --- a/client/vendor/src/flatpickr.js +++ /dev/null @@ -1,6 +0,0 @@ -import Flatpickr from 'flatpickr'; -import 'flatpickr/dist/flatpickr.min.css'; -import 'flatpickr/dist/themes/material_orange.css'; -import localeEs from 'flatpickr/dist/l10n/es'; -Flatpickr.l10ns.es = localeEs.es; -export default Flatpickr; diff --git a/client/vendor/src/material-design-lite.js b/client/vendor/src/material-design-lite.js deleted file mode 100644 index 3f0d1a719..000000000 --- a/client/vendor/src/material-design-lite.js +++ /dev/null @@ -1,4 +0,0 @@ -import * as mdl from 'material-design-lite'; -import 'material-design-lite/dist/material.orange-deep_orange.min.css'; - -export const materialDesignLite = mdl; diff --git a/client/vendor/src/mg-crud.js b/client/vendor/src/mg-crud.js deleted file mode 100644 index 294751582..000000000 --- a/client/vendor/src/mg-crud.js +++ /dev/null @@ -1,5 +0,0 @@ -import 'mg-crud'; - -export const mgCrud = { - name: 'mgCrud' -}; diff --git a/client/vendor/src/oc-lazy-load.js b/client/vendor/src/oc-lazy-load.js deleted file mode 100644 index fbb7749a8..000000000 --- a/client/vendor/src/oc-lazy-load.js +++ /dev/null @@ -1,5 +0,0 @@ -import 'oclazyload'; - -export const ocLazyLoad = { - name: 'oc.lazyLoad' -}; diff --git a/client/vendor/src/validator.js b/client/vendor/src/validator.js deleted file mode 100644 index 1bed18e46..000000000 --- a/client/vendor/src/validator.js +++ /dev/null @@ -1,3 +0,0 @@ -import * as validatorJs from 'validator'; - -export const validator = validatorJs; diff --git a/client/vendor/src/vendor.js b/client/vendor/src/vendor.js deleted file mode 100644 index a9bda3ee5..000000000 --- a/client/vendor/src/vendor.js +++ /dev/null @@ -1,9 +0,0 @@ -export * from './angular'; -export * from './angular-cookies'; -export * from './angular-translate'; -export * from './angular-paging'; -export * from './angular-ui-router'; -export * from './mg-crud'; -export * from './oc-lazy-load'; -export * from './material-design-lite'; -export * from './validator'; diff --git a/db/.gitignore b/db/.gitignore new file mode 100644 index 000000000..34fb91784 --- /dev/null +++ b/db/.gitignore @@ -0,0 +1 @@ +config.*.ini diff --git a/db/Dockerfile b/db/Dockerfile new file mode 100644 index 000000000..c376e6893 --- /dev/null +++ b/db/Dockerfile @@ -0,0 +1,39 @@ +FROM mysql:8.0.18 + +ENV MYSQL_ROOT_PASSWORD root +ENV TZ Europe/Madrid + +ARG DEBIAN_FRONTEND=noninteractive +RUN apt-get update \ + && apt-get install -y --no-install-recommends curl ca-certificates \ + && curl -sL https://apt.verdnatura.es/conf/verdnatura.gpg | apt-key add - \ + && echo "deb http://apt.verdnatura.es/ stretch main" > /etc/apt/sources.list.d/vn.list \ + && apt-get update \ + && apt-get install -y vn-mysql libmysqlclient21 \ + && apt-get purge -y --auto-remove curl ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +COPY docker/docker.cnf /etc/mysql/conf.d/ +COPY docker/docker-init.sh docker/docker-start.sh /usr/local/bin/ + +RUN mkdir /mysql-data \ + && chown -R mysql:mysql /mysql-data + +WORKDIR /docker-entrypoint-initdb.d + +COPY dump dump +COPY docker/docker-boot.sh /docker-entrypoint-initdb.d/ +COPY changes import/changes +COPY import-changes.sh config.ini import/ + +ARG STAMP=unknown +RUN gosu mysql docker-init.sh mysqld \ + && rm -rf /docker-entrypoint-initdb.d/* + +USER mysql +ENTRYPOINT ["docker-start.sh"] + +CMD ["mysqld"] + +#HEALTHCHECK --interval=5s --timeout=10s --retries=200 \ +# CMD mysqladmin ping -h 127.0.0.1 -u root || exit 1 diff --git a/db/changes/10080-september/00-catalog_calculate.sql b/db/changes/10080-september/00-catalog_calculate.sql new file mode 100644 index 000000000..4ddb79274 --- /dev/null +++ b/db/changes/10080-september/00-catalog_calculate.sql @@ -0,0 +1,117 @@ +DROP procedure IF EXISTS `vn`.`catalog_calculate`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`catalog_calculate`( + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT) +proc: BEGIN +/** + * Calcula los articulos disponibles y sus precios + * + * @table tmp.item(itemFk) Listado de artículos a calcular + * @param vLanded Fecha de recepcion de mercancia + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.ticketCalculateItem(itemFk, available, producer, + * item, size, stems, category, inkFk, image, origin, price) + * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) + * @return tmp.ticketComponent + * @return tmp.ticketComponentPrice + * @return tmp.zoneGetShipped + + **/ + + DECLARE vAvailableCalc INT; + DECLARE vShipped DATE; + DECLARE vClient INT; + DECLARE vWarehouseFk SMALLINT; + DECLARE vZoneFk INT; + DECLARE vDone BOOL; + DECLARE cTravelTree CURSOR FOR + SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + -- Establece los almacenes y las fechas que van a entrar al disponible + + SELECT clientFk INTO vClient + FROM address WHERE id = vAddressFk; + + CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot( + `warehouseFk` smallint(5) unsigned NOT NULL, + `itemFk` int(11) NOT NULL, + `available` double DEFAULT NULL, + `buyFk` int(11) DEFAULT NULL, + `fix` tinyint(3) unsigned DEFAULT '0', + KEY `itemFk` (`itemFk`), + KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH + ) ENGINE=MEMORY DEFAULT CHARSET=utf8; + + OPEN cTravelTree; + + l: LOOP + SET vDone = FALSE; + FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; + + IF vDone THEN + LEAVE l; + END IF; + + CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); + CALL buyUltimate (vWarehouseFk, vShipped); + + INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk) + SELECT vWarehouseFk, + i.item_id, + IFNULL(i.available, 0), + bu.buyFk + FROM `cache`.available i + JOIN tmp.item br ON br.itemFk = i.item_id + LEFT JOIN item it ON it.id = i.item_id + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id + WHERE i.calc_id = vAvailableCalc + AND it.id != 100 + AND i.available > 0; + + DROP TEMPORARY TABLE tmp.buyUltimate; + END LOOP; + + CLOSE cTravelTree; + + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; + CREATE TEMPORARY TABLE tmp.ticketCalculateItem + ENGINE = MEMORY + SELECT + b.itemFk, + SUM(b.available) available, + p.name producer, + i.name item, + i.size size, + i.stems, + i.category, + i.inkFk, + i.image, + o.code origin, + bl.price, + bl.priceKg + FROM tmp.ticketLot b + JOIN item i ON b.itemFk = i.id + LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible + JOIN origin o ON o.id = i.originFk + JOIN ( + SELECT MIN(price) price, itemFk, priceKg + FROM tmp.ticketComponentPrice + GROUP BY itemFk + ) bl ON bl.itemFk = b.itemFk + GROUP BY b.itemFk; + +END$$ + +DELIMITER ; + diff --git a/db/changes/10081-agency/00-address_getGeo.sql b/db/changes/10081-agency/00-address_getGeo.sql new file mode 100644 index 000000000..fca55dfd2 --- /dev/null +++ b/db/changes/10081-agency/00-address_getGeo.sql @@ -0,0 +1,27 @@ + +DROP FUNCTION IF EXISTS `vn`.`address_getGeo`; +DELIMITER $$ +CREATE DEFINER=`root`@`%` FUNCTION `vn`.`address_getGeo` (vSelf INT) + RETURNS INT + DETERMINISTIC +BEGIN +/** + * Returns the geo for the passed address. + * + * @param vSelf The address id + * @return The geo id + */ + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM address a + JOIN town t ON t.provinceFk = a.provinceFk + JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode + WHERE a.id = vSelf + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + LIMIT 1; + + RETURN vGeoFk; +END$$ +DELIMITER ; + diff --git a/db/changes/10081-agency/00-zone.sql b/db/changes/10081-agency/00-zone.sql new file mode 100644 index 000000000..74e482c4c --- /dev/null +++ b/db/changes/10081-agency/00-zone.sql @@ -0,0 +1,56 @@ +USE `vn`; + +CREATE TABLE `vn`.`zoneWarehouse` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `zoneFk` int(11) NOT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `zoneFk` (`zoneFk`,`warehouseFk`), + KEY `warehouseFk` (`warehouseFk`), + CONSTRAINT `zoneWarehouse_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE/*, +CONSTRAINT `zoneWarehouse_ibfk_2` FOREIGN KEY (`warehouseFk`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE*/ +) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; + +CREATE TABLE `vn`.`zoneEvent` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `zoneFk` int(11) NOT NULL, + `from` date DEFAULT NULL, + `to` date DEFAULT NULL, + `weekDays` set('mon','tue','wed','thu','fri','sat','sun') NOT NULL, + `hour` datetime DEFAULT NULL, + `travelingDays` int(11) DEFAULT NULL, + `price` decimal(10,2) DEFAULT NULL, + `bonus` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `zoneFk` (`zoneFk`), + CONSTRAINT `zoneEvent_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8; + +ALTER TABLE `vn`.`zoneEvent` + ADD COLUMN `type` ENUM('day', 'indefinitely', 'range') NOT NULL AFTER `zoneFk`, + ADD COLUMN `dated` DATE NULL DEFAULT NULL AFTER `type`, + CHANGE COLUMN `from` `started` DATE NULL DEFAULT NULL , + CHANGE COLUMN `to` `ended` DATE NULL DEFAULT NULL ; + +CREATE TABLE `vn`.`zoneExclusion` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `zoneFk` int(11) NOT NULL, + `day` date NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `zoneFk_2` (`zoneFk`,`day`), + KEY `zoneFk` (`zoneFk`), + CONSTRAINT `zoneExclusion_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; +ALTER TABLE `vn`.`zone` +DROP FOREIGN KEY `fk_zone_1`; +ALTER TABLE `vn`.`zone` +CHANGE COLUMN `warehouseFk` `warehouseFk` SMALLINT(6) UNSIGNED NULL DEFAULT NULL ; +ALTER TABLE `vn`.`zone` +ADD CONSTRAINT `fk_zone_1` + FOREIGN KEY (`warehouseFk`) + REFERENCES `vn`.`warehouse` (`id`) + ON DELETE NO ACTION + ON UPDATE CASCADE; + +ALTER TABLE `vn`.`zoneExclusion` + CHANGE COLUMN `day` `dated` DATE NOT NULL ; diff --git a/db/changes/10081-agency/00-zone_getAvailable.sql b/db/changes/10081-agency/00-zone_getAvailable.sql new file mode 100644 index 000000000..d24816e6e --- /dev/null +++ b/db/changes/10081-agency/00-zone_getAvailable.sql @@ -0,0 +1,16 @@ + +DROP PROCEDURE IF EXISTS `vn`.`zone_getAvailable`; +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getAvailable`(vAddress INT, vLanded DATE) +BEGIN + CALL zone_getFromGeo(address_getGeo(vAddress)); + CALL zone_getOptionsForLanding(vLanded); + + SELECT * FROM tmp.zoneOption; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; +END$$ +DELIMITER ; + diff --git a/db/changes/10081-agency/00-zone_getEvents.sql b/db/changes/10081-agency/00-zone_getEvents.sql new file mode 100644 index 000000000..be50f602d --- /dev/null +++ b/db/changes/10081-agency/00-zone_getEvents.sql @@ -0,0 +1,52 @@ +USE `vn`; +DROP procedure IF EXISTS `zone_getEvents`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getEvents`( + vProvinceFk INT, + vPostCode VARCHAR(255), + vAgencyModeFk INT) +BEGIN +/** + * Returns available events for the passed province/postcode and agency. + * + * @param vAgencyModeFk The agency mode id + * @param vProvinceFk The province id + * @param vPostCode The postcode or %NULL to use the province + */ + DECLARE vGeoFk INT; + + IF vPostCode IS NOT NULL THEN + SELECT p.geoFk INTO vGeoFk + FROM postCode p + JOIN town t ON t.id = p.townFk + WHERE p.`code` = vPostCode + AND t.provinceFk = vProvinceFk; + ELSE + SELECT geoFk INTO vGeoFk + FROM province + WHERE id = vProvinceFk; + END IF; + + CALL zone_getFromGeo(vGeoFk); + + IF vAgencyModeFk IS NOT NULL THEN + DELETE t FROM tmp.zone t + JOIN zone z ON z.id = t.id + WHERE z.agencyModeFk != vAgencyModeFk; + END IF; + + SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays + FROM tmp.zone t + JOIN zoneEvent e ON e.zoneFk = t.id; + + SELECT e.zoneFk, e.dated + FROM tmp.zone t + JOIN zoneExclusion e ON e.zoneFk = t.id; + + DROP TEMPORARY TABLE tmp.zone; +END$$ + +DELIMITER ; + diff --git a/db/changes/10081-agency/00-zone_getFromGeo.sql b/db/changes/10081-agency/00-zone_getFromGeo.sql new file mode 100644 index 000000000..244c73556 --- /dev/null +++ b/db/changes/10081-agency/00-zone_getFromGeo.sql @@ -0,0 +1,58 @@ + +DROP PROCEDURE IF EXISTS `vn`.`zone_getFromGeo`; +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getFromGeo`(vGeoFk INT) +BEGIN +/** + * Returns all zones which have the passed geo included. + * + * @param vGeoFk The geo id + * @return tmp.zone(id) The list of zones + */ + DECLARE vChildFk INT DEFAULT vGeoFk; + DECLARE vParentFk INT; + DECLARE vLevel INT DEFAULT 1; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT vGeoFk id, vLevel `level`; + + myLoop: LOOP + SELECT parentFk INTO vParentFk + FROM zoneGeo + WHERE id = vChildFk; + + SET vChildFk = vParentFk; + SET vLevel = vLevel + 1; + + INSERT IGNORE INTO tNodes + SELECT vChildFk, vLevel + FROM DUAL + WHERE vChildFk IS NOT NULL; + + IF ROW_COUNT() = 0 THEN + LEAVE myLoop; + END IF; + END LOOP; + + DROP TEMPORARY TABLE IF EXISTS tmp.zone; + CREATE TEMPORARY TABLE tmp.zone + (INDEX (id)) + ENGINE = MEMORY + SELECT id FROM ( + SELECT zoneFk id, isIncluded + FROM ( + SELECT i.zoneFk, i.isIncluded + FROM tNodes n + JOIN zoneIncluded i ON i.geoFk = n.id + ORDER BY zoneFk, n.`level` + ) t + GROUP BY id HAVING isIncluded + ) t; + + DROP TEMPORARY TABLE tNodes; +END$$ +DELIMITER ; + diff --git a/db/changes/10081-agency/00-zone_getLeaves.sql b/db/changes/10081-agency/00-zone_getLeaves.sql new file mode 100755 index 000000000..ee95b3315 --- /dev/null +++ b/db/changes/10081-agency/00-zone_getLeaves.sql @@ -0,0 +1,88 @@ + +DROP procedure IF EXISTS `vn`.`zone_getLeaves`; +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getLeaves`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255) +) +BEGIN + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id FROM zoneGeo + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + ELSEIF vParentFk IS NULL THEN + INSERT INTO tNodes + SELECT geoFk FROM zoneIncluded + WHERE zoneFk = vSelf; + END IF; + + IF vParentFk IS NULL THEN + DROP TEMPORARY TABLE IF EXISTS tChilds; + CREATE TEMPORARY TABLE tChilds + ENGINE = MEMORY + SELECT id FROM tNodes; + + DROP TEMPORARY TABLE IF EXISTS tParents; + CREATE TEMPORARY TABLE tParents + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF ROW_COUNT() = 0 THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE + tChilds, + tParents; + END IF; + + IF !vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + SELECT g.id, + g.`name`, + g.parentFk, + g.sons, + isIncluded selected + FROM zoneGeo g + JOIN tNodes n ON n.id = g.id + LEFT JOIN zoneIncluded i + ON i.geoFk = g.id AND i.zoneFk = vSelf + ORDER BY depth, selected DESC, `name`; + + DROP TEMPORARY TABLE tNodes; +END$$ +DELIMITER ; diff --git a/db/changes/10081-agency/01-zone_getAgency.sql b/db/changes/10081-agency/01-zone_getAgency.sql new file mode 100644 index 000000000..3d0c86866 --- /dev/null +++ b/db/changes/10081-agency/01-zone_getAgency.sql @@ -0,0 +1,42 @@ +USE `vn`; +DROP procedure IF EXISTS `zone_getAgency`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAgency`(vAddress INT, vLanded DATE) +BEGIN +/** + * Devuelve el listado de agencias disponibles para la fecha + * y dirección pasadas. + * + * @param vAddress Id de dirección de envío, %NULL si es recogida + * @param vLanded Fecha de recogida + * @select Listado de agencias disponibles + */ + + CALL zone_getFromGeo(address_getGeo(vAddress)); + CALL zone_getOptionsForLanding(vLanded); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency; + CREATE TEMPORARY TABLE tmp.zoneGetAgency + (INDEX (agencyModeFk)) ENGINE = MEMORY + SELECT am.name agencyMode, + am.description, + z.agencyModeFk, + am.deliveryMethodFk, + TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, + TRUE isIncluded, + zo.zoneFk + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + GROUP BY agencyModeFk; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; + +END$$ + +DELIMITER ; + diff --git a/db/changes/10081-agency/01-zone_getFirstShipped.sql b/db/changes/10081-agency/01-zone_getFirstShipped.sql new file mode 100644 index 000000000..64e853a81 --- /dev/null +++ b/db/changes/10081-agency/01-zone_getFirstShipped.sql @@ -0,0 +1,2 @@ +USE `vn`; +DROP procedure IF EXISTS `zone_getFirstShipped`; diff --git a/db/changes/10081-agency/01-zone_getLanded.sql b/db/changes/10081-agency/01-zone_getLanded.sql new file mode 100644 index 000000000..a2bbe46a5 --- /dev/null +++ b/db/changes/10081-agency/01-zone_getLanded.sql @@ -0,0 +1,40 @@ +USE `vn`; +DROP procedure IF EXISTS `zone_getLanded`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) +BEGIN +/** +* Devuelve una tabla temporal con el dia de recepcion para vShipped. +* +* @param vShipped Fecha de preparacion de mercancia +* @param vAddressFk Id de consignatario, %NULL para recogida +* @param vAgencyModeFk Id agencia +* @param vWarehouseFk vWarehouseFk +* @table tmp.zoneGetLanded Datos de recepción +*/ + + CALL zone_getFromGeo(address_getGeo(vAddressFk)); + CALL zone_getOptionsForLanding(vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; + CREATE TEMPORARY TABLE tmp.zoneGetLanded + ENGINE = MEMORY + SELECT vWarehouseFk warehouseFk, + TIMESTAMPADD(DAY,zo.travelingDays, vShipped) landed, + zo.zoneFk + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN zoneWarehouse zw ON zw.zoneFk = z.id + WHERE agencyModeFk = vAgencyModeFk + AND zw.warehouseFk = vWarehouseFk; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; + +END$$ + +DELIMITER ; + diff --git a/db/changes/10081-agency/01-zone_getShippedWarehouse.sql b/db/changes/10081-agency/01-zone_getShippedWarehouse.sql new file mode 100644 index 000000000..017b7d17c --- /dev/null +++ b/db/changes/10081-agency/01-zone_getShippedWarehouse.sql @@ -0,0 +1,41 @@ +USE `vn`; +DROP procedure IF EXISTS `zone_getShippedWarehouse`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) +BEGIN +/** + * Devuelve la mínima fecha de envío para cada warehouse + * + * @param vLanded La fecha de recepcion + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.zoneGetShipped + */ + + CALL zone_getFromGeo(address_getGeo(vAddressFk)); + CALL zone_getOptionsForLanding(vLanded); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; + CREATE TEMPORARY TABLE tmp.zoneGetShipped + ENGINE = MEMORY + SELECT * FROM ( + SELECT zo.zoneFk, + TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, + zw.warehouseFk, + z.agencyModeFk + FROM tmp.zoneOption zo + JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk + JOIN zone z ON z.id = zo.zoneFk + WHERE z.agencyModeFk = vAgencyModeFk + ORDER BY shipped) t + GROUP BY warehouseFk; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; +END$$ + +DELIMITER ; + diff --git a/db/changes/10081-agency/01-zone_getWarehouse.sql b/db/changes/10081-agency/01-zone_getWarehouse.sql new file mode 100644 index 000000000..28478e2cc --- /dev/null +++ b/db/changes/10081-agency/01-zone_getWarehouse.sql @@ -0,0 +1,42 @@ +USE `vn`; +DROP procedure IF EXISTS `zone_getWarehouse`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT) +BEGIN +/** + * Devuelve el listado de agencias disponibles para la fecha, + * dirección y almacén pasados. + * + * @param vAddress + * @param vWarehouse warehouse + * @param vLanded Fecha de recogida + * @select Listado de agencias disponibles + */ + + CALL zone_getFromGeo(address_getGeo(vAddress)); + CALL zone_getOptionsForLanding(vLanded); + + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, + am.deliveryMethodFk, + TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, + zw.warehouseFk, + z.id zoneFk + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk + WHERE zw.warehouseFk + GROUP BY z.agencyModeFk + ORDER BY agencyMode; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; +END$$ + +DELIMITER ; + diff --git a/db/changes/10081-agency/02-zoneGetAgency.sql b/db/changes/10081-agency/02-zoneGetAgency.sql new file mode 100644 index 000000000..3a627ba5b --- /dev/null +++ b/db/changes/10081-agency/02-zoneGetAgency.sql @@ -0,0 +1,22 @@ + +USE `vn`; +DROP procedure IF EXISTS `vn`.`zoneGetAgency`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetAgency`(vAddress INT, vLanded DATE) +BEGIN +/** + * Devuelve el listado de agencias disponibles para la fecha + * y dirección pasadas. + * + * @param vAddress Id de dirección de envío, %NULL si es recogida + * @param vDate Fecha de recogida + * @select Listado de agencias disponibles + */ + + CALL zone_getAgency(vAddress,vLanded); +END$$ + +DELIMITER ; +; diff --git a/db/changes/10081-agency/02-zoneGetFirstShipped__.sql b/db/changes/10081-agency/02-zoneGetFirstShipped__.sql new file mode 100644 index 000000000..9483f309c --- /dev/null +++ b/db/changes/10081-agency/02-zoneGetFirstShipped__.sql @@ -0,0 +1,3 @@ + +USE `vn`; +DROP procedure IF EXISTS `vn`.`zoneGetFirstShipped`; diff --git a/db/changes/10081-agency/02-zoneGetLanded.sql b/db/changes/10081-agency/02-zoneGetLanded.sql new file mode 100644 index 000000000..da8d8a9dd --- /dev/null +++ b/db/changes/10081-agency/02-zoneGetLanded.sql @@ -0,0 +1,20 @@ +USE `vn`; +DROP procedure IF EXISTS `zoneGetLanded`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded`(vShipped DATE, vAddress INT, vAgencyMode INT, vWarehouse INT) +BEGIN +/** +* Devuelve una tabla temporal con el dia de recepcion para vShipped. +* +* @param vShipped Fecha de preparacion de mercancia +* @param vAddress Id de consignatario, %NULL para recogida +* @param vAgencyMode Id agencia +* @table tmp.zoneGetLanded Datos de recepción +*/ + CALL zone_getLanded(vShipped,vAddress,vAgencyMode,vWarehouse); +END$$ + +DELIMITER ; + diff --git a/db/changes/10081-agency/02-zoneGetShipped.sql b/db/changes/10081-agency/02-zoneGetShipped.sql new file mode 100644 index 000000000..212eb94df --- /dev/null +++ b/db/changes/10081-agency/02-zoneGetShipped.sql @@ -0,0 +1,24 @@ +USE `vn`; +DROP procedure IF EXISTS `zoneGetShipped`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShipped`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) +BEGIN +/** + * OBSOLETO usar zone_getShippedWarehouse + * Devuelve la mínima fecha de envía para cada warehouse + * + * @param vLanded La fecha de recepcion + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.zoneGetShipped + */ + CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + + SELECT * FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouseFk; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; +END$$ + +DELIMITER ; + diff --git a/db/changes/10081-agency/02-zoneGetShippedWarehouse.sql b/db/changes/10081-agency/02-zoneGetShippedWarehouse.sql new file mode 100644 index 000000000..55f443054 --- /dev/null +++ b/db/changes/10081-agency/02-zoneGetShippedWarehouse.sql @@ -0,0 +1,20 @@ +USE `vn`; +DROP procedure IF EXISTS `zoneGetShippedWarehouse`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) +BEGIN +/** + * Devuelve la mínima fecha de envío para cada warehouse + * + * @param vLanded La fecha de recepcion + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.zoneGetShipped + */ + CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); +END$$ + +DELIMITER ; + diff --git a/db/changes/10081-agency/04-zone_getOptionsForLanding.sql b/db/changes/10081-agency/04-zone_getOptionsForLanding.sql new file mode 100644 index 000000000..ae081f14b --- /dev/null +++ b/db/changes/10081-agency/04-zone_getOptionsForLanding.sql @@ -0,0 +1,67 @@ +USE `vn`; +DROP procedure IF EXISTS `zone_getOptionsForLanding`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForLanding`(vLanded DATE) +BEGIN +/** + * Gets computed options for the passed zones and delivery date. + * + * @table tmp.zones(id) The zones ids + * @param vLanded The delivery date + * @return tmp.zoneOption The computed options + */ + DECLARE vHour TIME DEFAULT TIME(NOW()); + + DROP TEMPORARY TABLE IF EXISTS tTemp; + CREATE TEMPORARY TABLE tTemp + ENGINE = MEMORY + SELECT t.id zoneFk, + IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, + IFNULL(e.travelingDays, z.travelingDays) travelingDays, + IFNULL(e.price, z.price) price, + IFNULL(e.bonus, z.bonus) bonus, + CASE + WHEN e.`type` = 'day' + THEN 1 + WHEN e.`type` = 'range' + THEN 2 + ELSE 3 + END specificity + FROM tmp.zone t + JOIN zone z ON z.id = t.id + JOIN zoneEvent e ON e.zoneFk = t.id + WHERE ( + e.`type` = 'day' + AND e.dated = vLanded + ) OR ( + e.`type` != 'day' + AND e.weekDays & (1 << WEEKDAY(vLanded)) + AND (e.`started` IS NULL OR vLanded >= e.`started`) + AND (e.`ended` IS NULL OR vLanded <= e.`ended`) + ); + + DELETE t FROM tTemp t + JOIN zoneExclusion e + ON e.zoneFk = t.zoneFk AND e.`dated` = vLanded; + + DELETE FROM tTemp + WHERE (@shipped := TIMESTAMPADD(DAY, -travelingDays, vLanded)) < CURDATE() + OR @shipped = CURDATE() AND vHour > `hour`; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; + CREATE TEMPORARY TABLE tmp.zoneOption + ENGINE = MEMORY + SELECT * + FROM ( + SELECT * FROM tTemp + ORDER BY zoneFk, specificity + ) t + GROUP BY zoneFk; + + DROP TEMPORARY TABLE tTemp; +END$$ + +DELIMITER ; + diff --git a/db/changes/10081-agency/04-zone_getOptionsForShipment.sql b/db/changes/10081-agency/04-zone_getOptionsForShipment.sql new file mode 100644 index 000000000..c631f8809 --- /dev/null +++ b/db/changes/10081-agency/04-zone_getOptionsForShipment.sql @@ -0,0 +1,76 @@ +USE `vn`; +DROP procedure IF EXISTS `zone_getOptionsForShipment`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForShipment`(vShipped DATE) +BEGIN +/** + * Gets computed options for the passed zones and shipping date. + * + * @table tmp.zones(id) The zones ids + * @param vShipped The shipping date + * @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options + */ + DROP TEMPORARY TABLE IF EXISTS tLandings; + CREATE TEMPORARY TABLE tLandings + (INDEX (eventFk)) + ENGINE = MEMORY + SELECT e.id eventFk, + @travelingDays := IFNULL(e.travelingDays, z.travelingDays) travelingDays, + TIMESTAMPADD(DAY, @travelingDays, vShipped) landed + FROM tmp.zone t + JOIN zone z ON z.id = t.id + JOIN zoneEvent e ON e.zoneFk = t.id; + + DROP TEMPORARY TABLE IF EXISTS tTemp; + CREATE TEMPORARY TABLE tTemp + ENGINE = MEMORY + SELECT t.id zoneFk, + IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, + IFNULL(e.price, z.price) price, + IFNULL(e.bonus, z.bonus) bonus, + CASE + WHEN e.`type` = 'day' + THEN 1 + WHEN e.`type` = 'range' + THEN 2 + ELSE 3 + END specificity, + l.travelingDays, + l.landed + FROM tmp.zone t + JOIN zone z ON z.id = t.id + JOIN zoneEvent e ON e.zoneFk = t.id + JOIN tLandings l ON l.eventFk = e.id + WHERE ( + e.`type` = 'day' + AND e.`dated` = l.landed + ) OR ( + e.`type` != 'day' + AND e.weekDays & (1 << WEEKDAY(l.landed)) + AND (e.`started` IS NULL OR l.landed >= e.`started`) + AND (e.`ended` IS NULL OR l.landed <= e.`ended`) + ); + + DELETE t FROM tTemp t + JOIN zoneExclusion e + ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; + CREATE TEMPORARY TABLE tmp.zoneOption + ENGINE = MEMORY + SELECT * + FROM ( + SELECT * FROM tTemp + ORDER BY zoneFk, specificity + ) t + GROUP BY zoneFk; + + DROP TEMPORARY TABLE + tTemp, + tLandings; +END$$ + +DELIMITER ; + diff --git a/db/changes/10090-iberflora/00-ACL.sql b/db/changes/10090-iberflora/00-ACL.sql new file mode 100644 index 000000000..3a20e3ecb --- /dev/null +++ b/db/changes/10090-iberflora/00-ACL.sql @@ -0,0 +1 @@ +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Claim', 'updateClaimAction', 'WRITE', 'ALLOW', 'ROLE', 'salesAssistant'); diff --git a/db/changes/10090-iberflora/00-claimState.sql b/db/changes/10090-iberflora/00-claimState.sql new file mode 100644 index 000000000..7a964979b --- /dev/null +++ b/db/changes/10090-iberflora/00-claimState.sql @@ -0,0 +1,2 @@ +UPDATE `vn`.`claimState` SET `roleFk` = '21' WHERE (`id` = '3'); +UPDATE `vn`.`claimState` SET `roleFk` = '21' WHERE (`id` = '5'); diff --git a/db/changes/10090-iberflora/00-component.sql b/db/changes/10090-iberflora/00-component.sql new file mode 100644 index 000000000..fe5de47fc --- /dev/null +++ b/db/changes/10090-iberflora/00-component.sql @@ -0,0 +1,15 @@ +CREATE + OR REPLACE ALGORITHM = UNDEFINED + DEFINER = `root`@`%` + SQL SECURITY DEFINER +VIEW `vn`.`component` AS + SELECT + `t`.`Id_Componente` AS `id`, + `t`.`Componente` AS `name`, + `t`.`tarifa_componentes_series_id` AS `typeFk`, + `t`.`tarifa_class` AS `classRate`, + `t`.`tax` AS `tax`, + `t`.`is_renewable` AS `isRenewable`, + `t`.`code` AS `code` + FROM + `bi`.`tarifa_componentes` `t`; diff --git a/db/changes/10091-iberflora/00-department.sql b/db/changes/10091-iberflora/00-department.sql new file mode 100644 index 000000000..415879485 --- /dev/null +++ b/db/changes/10091-iberflora/00-department.sql @@ -0,0 +1,2 @@ + +UPDATE vn.department SET lft = NULL, rgt = NULL; diff --git a/db/changes/10091-iberflora/00-department_calcTree.sql b/db/changes/10091-iberflora/00-department_calcTree.sql new file mode 100644 index 000000000..5f518d2e2 --- /dev/null +++ b/db/changes/10091-iberflora/00-department_calcTree.sql @@ -0,0 +1,37 @@ +USE `vn`; +DROP procedure IF EXISTS `department_calcTree`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTree`() +BEGIN +/** + * Calculates the #path, #lft, #rgt, #sons and #depth columns of + * the #department table. To build the tree, it uses the #parentFk + * column. + */ + DECLARE vIndex INT DEFAULT 0; + DECLARE vSons INT; + + DROP TEMPORARY TABLE IF EXISTS tNestedTree; + CREATE TEMPORARY TABLE tNestedTree + SELECT id, path, lft, rgt, depth, sons + FROM department LIMIT 0; + + SET max_sp_recursion_depth = 5; + CALL department_calcTreeRec(NULL, '/', 0, vIndex, vSons); + SET max_sp_recursion_depth = 0; + + UPDATE department z + JOIN tNestedTree t ON t.id = z.id + SET z.path = t.path, + z.lft = t.lft, + z.rgt = t.rgt, + z.depth = t.depth, + z.sons = t.sons; + + DROP TEMPORARY TABLE tNestedTree; +END$$ + +DELIMITER ; + diff --git a/db/changes/10091-iberflora/00-department_calcTreeRec.sql b/db/changes/10091-iberflora/00-department_calcTreeRec.sql new file mode 100644 index 000000000..1f24270e2 --- /dev/null +++ b/db/changes/10091-iberflora/00-department_calcTreeRec.sql @@ -0,0 +1,75 @@ +USE `vn`; +DROP procedure IF EXISTS `department_calcTreeRec`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTreeRec`( + vSelf INT, + vPath VARCHAR(255), + vDepth INT, + INOUT vIndex INT, + OUT vSons INT +) +BEGIN +/** + * Calculates and sets the #path, #lft, #rgt, #sons and #depth + * columns for all children of the passed node. Once calculated + * the last node rgt index and the number of sons are returned. + * To update it's children, this procedure calls itself recursively + * for each one. + * + * @vSelf The node identifier + * @vPath The initial path + * @vDepth The initial depth + * @vIndex The initial lft index + * @vSons The number of direct sons + */ + DECLARE vChildFk INT; + DECLARE vLft INT; + DECLARE vMySons INT; + DECLARE vDone BOOL; + DECLARE vChildren CURSOR FOR + SELECT id FROM department + WHERE (vSelf IS NULL AND parentFk IS NULL) + OR (vSelf IS NOT NULL AND parentFk = vSelf); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + SET vSons = 0; + + OPEN vChildren; + myLoop: LOOP + SET vDone = FALSE; + FETCH vChildren INTO vChildFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + SET vIndex = vIndex + 1; + SET vLft = vIndex; + SET vSons = vSons + 1; + + CALL department_calcTreeRec( + vChildFk, + CONCAT(vPath, vChildFk, '/'), + vDepth + 1, + vIndex, + vMySons + ); + + SET vIndex = vIndex + 1; + + INSERT INTO tNestedTree + SET id = vChildFk, + path = vPath, + lft = vLft, + rgt = vIndex, + depth = vDepth, + sons = vMySons; + END LOOP; + CLOSE vChildren; +END$$ + +DELIMITER ; + diff --git a/db/changes/10091-iberflora/00-department_doCalc.sql b/db/changes/10091-iberflora/00-department_doCalc.sql new file mode 100644 index 000000000..ba5c16c48 --- /dev/null +++ b/db/changes/10091-iberflora/00-department_doCalc.sql @@ -0,0 +1,35 @@ +USE `vn`; +DROP procedure IF EXISTS `department_doCalc`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `department_doCalc`() +proc: BEGIN +/** + * Recalculates the department tree. + */ + DECLARE vIsChanged BOOL; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.department_doCalc'); + RESIGNAL; + END; + + IF !GET_LOCK('vn.department_doCalc', 0) THEN + LEAVE proc; + END IF; + + SELECT isChanged INTO vIsChanged + FROM department_recalc; + + IF vIsChanged THEN + UPDATE department_recalc SET isChanged = FALSE; + CALL vn.department_calcTree; + END IF; + + DO RELEASE_LOCK('vn.department_doCalc'); +END$$ + +DELIMITER ; + diff --git a/db/changes/10091-iberflora/00-department_getLeaves.sql b/db/changes/10091-iberflora/00-department_getLeaves.sql new file mode 100644 index 000000000..436f67dbf --- /dev/null +++ b/db/changes/10091-iberflora/00-department_getLeaves.sql @@ -0,0 +1,84 @@ +USE `vn`; +DROP procedure IF EXISTS `department_getLeaves`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `department_getLeaves`( + vParentFk INT, + vSearch VARCHAR(255) +) +BEGIN + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id FROM department LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id FROM department + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + END IF; + + IF vParentFk IS NULL THEN + DROP TEMPORARY TABLE IF EXISTS tChilds; + CREATE TEMPORARY TABLE tChilds + ENGINE = MEMORY + SELECT id FROM tNodes; + + DROP TEMPORARY TABLE IF EXISTS tParents; + CREATE TEMPORARY TABLE tParents + ENGINE = MEMORY + SELECT id FROM department LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM department g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF ROW_COUNT() = 0 THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE + tChilds, + tParents; + END IF; + + IF !vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id FROM department + WHERE parentFk <=> vParentFk; + END IF; + + SELECT d.id, + d.`name`, + d.parentFk, + d.sons + FROM department d + JOIN tNodes n ON n.id = d.id + ORDER BY depth, `name`; + + DROP TEMPORARY TABLE tNodes; +END$$ + +DELIMITER ; + diff --git a/db/changes/10091-iberflora/00-route.sql b/db/changes/10091-iberflora/00-route.sql new file mode 100644 index 000000000..5d8b8de62 --- /dev/null +++ b/db/changes/10091-iberflora/00-route.sql @@ -0,0 +1,10 @@ +ALTER TABLE `vn`.`route` +ADD COLUMN `zoneFk` INT NULL AFTER `description`, +ADD INDEX `fk_route_1_idx` (`zoneFk` ASC); +; +ALTER TABLE `vn`.`route` +ADD CONSTRAINT `fk_route_1` + FOREIGN KEY (`zoneFk`) + REFERENCES `vn`.`zone` (`id`) + ON DELETE RESTRICT + ON UPDATE CASCADE; diff --git a/db/changes/10100-allSaints/00-ACL.sql b/db/changes/10100-allSaints/00-ACL.sql new file mode 100644 index 000000000..ea1ba706b --- /dev/null +++ b/db/changes/10100-allSaints/00-ACL.sql @@ -0,0 +1 @@ +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('UserPhone', '*', 'WRITE', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/10100-allSaints/00-travelLog.sql b/db/changes/10100-allSaints/00-travelLog.sql new file mode 100644 index 000000000..fe9d03274 --- /dev/null +++ b/db/changes/10100-allSaints/00-travelLog.sql @@ -0,0 +1,18 @@ +CREATE TABLE `vn`.`travelLog` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `originFk` int(10) unsigned NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `originFk` (`originFk`), + KEY `userFk` (`userFk`), + CONSTRAINT `travelLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `vn`.`travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `travelLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; \ No newline at end of file diff --git a/db/changes/10100-allSaints/00-upperGap.sql b/db/changes/10100-allSaints/00-upperGap.sql new file mode 100644 index 000000000..6554c47b4 --- /dev/null +++ b/db/changes/10100-allSaints/00-upperGap.sql @@ -0,0 +1,6 @@ +CREATE TABLE `vn`.`packagingConfig` ( + `id` INT NOT NULL AUTO_INCREMENT, + `upperGap` INT NOT NULL, + PRIMARY KEY (`id`)); + +INSERT INTO `vn`.`packagingConfig` (`upperGap`) VALUES ('10'); diff --git a/db/changes/10100-allSaints/00-userLog.sql b/db/changes/10100-allSaints/00-userLog.sql new file mode 100644 index 000000000..f6972796d --- /dev/null +++ b/db/changes/10100-allSaints/00-userLog.sql @@ -0,0 +1,18 @@ +CREATE TABLE `vn`.`userLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(10) unsigned NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `originFk` (`originFk`), + KEY `userFk` (`userFk`), + CONSTRAINT `userLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; \ No newline at end of file diff --git a/db/changes/10100-allSaints/00-userPhoneType.sql b/db/changes/10100-allSaints/00-userPhoneType.sql new file mode 100644 index 000000000..6bfedcc71 --- /dev/null +++ b/db/changes/10100-allSaints/00-userPhoneType.sql @@ -0,0 +1,9 @@ +CREATE TABLE `vn`.`userPhoneType` ( + `code` VARCHAR(45) NOT NULL, + `description` VARCHAR(255) NULL, + PRIMARY KEY (`code`)); + + + +INSERT INTO `vn`.`userPhoneType` (`code`, `description`) VALUES ('businessPhone', 'Telefono de empresa del usuario'); +INSERT INTO `vn`.`userPhoneType` (`code`, `description`) VALUES ('personalPhone', 'Telefono personal del usuario'); diff --git a/db/changes/10100-allSaints/01-userPhone.sql b/db/changes/10100-allSaints/01-userPhone.sql new file mode 100644 index 000000000..54dfbeb26 --- /dev/null +++ b/db/changes/10100-allSaints/01-userPhone.sql @@ -0,0 +1,23 @@ +CREATE TABLE `vn`.`userPhone` ( + `id` INT NOT NULL AUTO_INCREMENT, + `userFk` INT(10) UNSIGNED NOT NULL, + `typeFk` VARCHAR(45) NOT NULL, + `phone` VARCHAR(25) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE INDEX `UserFk_Phone` (`userFk` ASC, `typeFk` ASC, `phone` ASC)); + + +ALTER TABLE `vn`.`userPhone` +ADD CONSTRAINT `fgnTypeFk` + FOREIGN KEY (typeFk) + REFERENCES `vn`.`userPhoneType` (code) + ON DELETE RESTRICT + ON UPDATE CASCADE; + +ALTER TABLE `vn`.`userPhone` +ADD CONSTRAINT `fgnUserFk` + FOREIGN KEY (userFk) + REFERENCES `account`.`user` (id) + ON DELETE CASCADE + ON UPDATE CASCADE; + diff --git a/db/changes/10100-allSaints/02-catalog_componentCalculate.sql b/db/changes/10100-allSaints/02-catalog_componentCalculate.sql new file mode 100644 index 000000000..9d4df64c9 --- /dev/null +++ b/db/changes/10100-allSaints/02-catalog_componentCalculate.sql @@ -0,0 +1,259 @@ +USE `vn`; +DROP procedure IF EXISTS `catalog_componentCalculate`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate`( + vZoneFk INT, + vAddressFk INT, + vShipped DATE) +proc: BEGIN +/** + * Calcula los componentes de los articulos de tmp.ticketLot + * + * @param vZoneFk para calcular el transporte + * @param vAgencyModeFk Id del modo de agencia + * @param tmp.ticketLot (warehouseFk,available,itemFk,buyFk) + * + * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, + * packing, grouping, groupingMode, buyFk, typeFk) + * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) + */ + + DECLARE vClientFk INT; + DECLARE vGeneralInflationCoefficient INT DEFAULT 1; + DECLARE vMinimumDensityWeight INT DEFAULT 167; + DECLARE vBoxFreightItem INT DEFAULT 71; + DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; + DECLARE vSpecialPriceComponent INT DEFAULT 10; + DECLARE vDeliveryComponent INT DEFAULT 15; + DECLARE vRecoveryComponent INT DEFAULT 17; + DECLARE vSellByPacketComponent INT DEFAULT 22; + DECLARE vBuyValueComponent INT DEFAULT 28; + DECLARE vMarginComponent INT DEFAULT 29; + DECLARE vDiscountLastItemComponent INT DEFAULT 32; + DECLARE vExtraBaggedComponent INT DEFAULT 38; + DECLARE vManaAutoComponent INT DEFAULT 39; + + SELECT volume INTO vBoxVolume + FROM vn.packaging + WHERE id = '94'; + + SELECT clientFk INTO vClientFK + FROM address + WHERE id = vAddressFk; + + SET @rate2 := 0; + SET @rate3 := 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; + CREATE TEMPORARY TABLE tmp.ticketComponentCalculate + (PRIMARY KEY (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT + tl.itemFk, tl.warehouseFk, tl.available, + IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, + IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, + IFNULL(pf.rate3, 0) AS minPrice, + IFNULL(pf.packing, b.packing) packing, + IFNULL(pf.`grouping`, b.`grouping`) `grouping`, + ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, + tl.buyFk, + i.typeFk, + IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping + FROM tmp.ticketLot tl + JOIN buy b ON b.id = tl.buyFk + JOIN item i ON i.id = tl.itemFk + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk + LEFT JOIN ( + SELECT * FROM ( + SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, zw.warehouseFk + FROM priceFixed pf + JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk AND (zw.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0) + WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC + ) tpf + GROUP BY tpf.itemFk, tpf.warehouseFk + ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk + WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; + CREATE TEMPORARY TABLE tmp.ticketComponent ( + `warehouseFk` INT UNSIGNED NOT NULL, + `itemFk` INT NOT NULL, + `componentFk` INT UNSIGNED NOT NULL, + `cost` DECIMAL(10,4) NOT NULL, + INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), + UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)); + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vBuyValueComponent, + b.buyingValue + b.freightValue + b.packageValue + b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vMarginComponent, + tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; + CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY + SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk + FROM tmp.ticketComponent tc + GROUP BY tc.itemFk, warehouseFk; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3) + FROM tmp.ticketComponentBase tcb + JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk + WHERE cr.recobro > 0.009; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto + FROM tmp.ticketComponentBase tcb + JOIN `client` c on c.id = vClientFk + JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador + WHERE ms.prices_modifier_activated + HAVING manaAuto <> 0; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, + tcb.itemFk, + cr.id, + GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3) + FROM tmp.ticketComponentBase tcb + JOIN componentRate cr + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFK, + tcc.itemFk, + vDeliveryComponent, + vGeneralInflationCoefficient + * ROUND(( + i.compression + * r.cm3 + * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) + * IFNULL((z.price - z.bonus) + * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 + ) cost + FROM tmp.ticketComponentCalculate tcc + JOIN item i ON i.id = tcc.itemFk + JOIN zone z ON z.id = vZoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk + AND r.Id_Article = tcc.itemFk + HAVING cost <> 0; + + IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost + FROM tmp.ticketComponentCalculate tcc + JOIN vn.addressForPackaging ap + WHERE ap.addressFk = vAddressFk; + END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; + CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY + SELECT * FROM tmp.ticketComponent; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, + tcc.itemFk, + vSpecialPriceComponent, + sp.value - SUM(tcc.cost) sumCost + FROM tmp.ticketComponentCopy tcc + JOIN componentRate cr ON cr.id = tcc.componentFk + JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk + WHERE cr.classRate IS NULL + GROUP BY tcc.itemFk, tcc.warehouseFk + HAVING ABS(sumCost) > 0.001; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; + CREATE TEMPORARY TABLE tmp.ticketComponentSum + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate + FROM tmp.ticketComponent tc + JOIN componentRate cr ON cr.id = tc.componentFk + GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; + CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY + SELECT tcc.warehouseFk, + tcc.itemFk, + 1 rate, + IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 1) = 1 + AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 2 rate, + tcc.packing `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 + AND tcc.packing > 0 AND tcc.available >= tcc.packing) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 3 rate, + tcc.available `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 3) = 3 + GROUP BY tcs.warehouseFk, tcs.itemFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; + CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY + SELECT * FROM ( + SELECT * FROM tmp.ticketComponentRate ORDER BY price + ) t + GROUP BY itemFk, warehouseFk, `grouping`; + + DROP TEMPORARY TABLE + tmp.ticketComponentCalculate, + tmp.ticketComponentSum, + tmp.ticketComponentBase, + tmp.ticketComponentRate, + tmp.ticketComponentCopy; +END$$ + +DELIMITER ; + diff --git a/db/changes/10100-allSaints/02-ticketCalculate__.sql b/db/changes/10100-allSaints/02-ticketCalculate__.sql new file mode 100644 index 000000000..37903f7c3 --- /dev/null +++ b/db/changes/10100-allSaints/02-ticketCalculate__.sql @@ -0,0 +1,17 @@ + +USE `vn`; +DROP procedure IF EXISTS `vn`.`ticketCalculate`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculate__`( + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT) +proc: BEGIN +-- OBSOLETO utilizar catalog_calculate + CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); +END$$ + +DELIMITER ; +; diff --git a/db/changes/10100-allSaints/03-available_calc.sql b/db/changes/10100-allSaints/03-available_calc.sql new file mode 100644 index 000000000..70416f5df --- /dev/null +++ b/db/changes/10100-allSaints/03-available_calc.sql @@ -0,0 +1,63 @@ +USE `vn`; +DROP procedure IF EXISTS `available_calc`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `available_calc`( + vDate DATE, + vAddress INT, + vAgencyMode INT) +BEGIN +/** + * Calculates the available for all available stores + * according to the given parameters. + * + * @param vDate The delivery date + * @param vAddress The delivery address id + * @param vAgencyMode The shipping agency + * @return tmp.availableCalc(calcFk) The available cache ids + */ + DECLARE vCalcFk INT; + DECLARE vShipment DATE; + DECLARE vWarehouse INT; + DECLARE vDone BOOL; + + DECLARE cWarehouses CURSOR FOR + SELECT warehouseFk, shipped FROM tmp.zoneGetShipped; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + -- Establecemos los almacenes y las fechas que van a entrar al disponible + + CALL vn.zone_getShippedWarehouse(vDate, vAddress, vAgencyMode); + + DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; + CREATE TEMPORARY TABLE tmp.availableCalc( + calcFk INT UNSIGNED, + PRIMARY KEY (calcFk) + ) + ENGINE = MEMORY; + + OPEN cWarehouses; + + l: LOOP + SET vDone = FALSE; + FETCH cWarehouses INTO vWarehouse, vShipment; + + IF vDone THEN + LEAVE l; + END IF; + + CALL `cache`.available_refresh(vCalcFk, FALSE, vWarehouse, vShipment); + + INSERT IGNORE INTO tmp.availableCalc + SET calcFk = vCalcFk; + END LOOP; + + CLOSE cWarehouses; + DROP TEMPORARY TABLE tmp.zoneGetShipped; +END$$ + +DELIMITER ; + diff --git a/db/changes/10100-allSaints/03-catalog_calculate.sql b/db/changes/10100-allSaints/03-catalog_calculate.sql new file mode 100644 index 000000000..e6f4f7375 --- /dev/null +++ b/db/changes/10100-allSaints/03-catalog_calculate.sql @@ -0,0 +1,119 @@ +USE `vn`; +DROP procedure IF EXISTS `catalog_calculate`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calculate`( + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT) +proc: BEGIN +/** + * Calcula los articulos disponibles y sus precios + * + * @table tmp.item(itemFk) Listado de artículos a calcular + * @param vLanded Fecha de recepcion de mercancia + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.ticketCalculateItem(itemFk, available, producer, + * item, size, stems, category, inkFk, image, origin, price) + * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) + * @return tmp.ticketComponent + * @return tmp.ticketComponentPrice + * @return tmp.zoneGetShipped + + **/ + + DECLARE vAvailableCalc INT; + DECLARE vShipped DATE; + DECLARE vClient INT; + DECLARE vWarehouseFk SMALLINT; + DECLARE vZoneFk INT; + DECLARE vDone BOOL; + DECLARE cTravelTree CURSOR FOR + SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + -- Establece los almacenes y las fechas que van a entrar al disponible + + SELECT clientFk INTO vClient + FROM address WHERE id = vAddressFk; + + CALL vn.zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot( + `warehouseFk` smallint(5) unsigned NOT NULL, + `itemFk` int(11) NOT NULL, + `available` double DEFAULT NULL, + `buyFk` int(11) DEFAULT NULL, + `fix` tinyint(3) unsigned DEFAULT '0', + KEY `itemFk` (`itemFk`), + KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH + ) ENGINE=MEMORY DEFAULT CHARSET=utf8; + + OPEN cTravelTree; + + l: LOOP + SET vDone = FALSE; + FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; + + IF vDone THEN + LEAVE l; + END IF; + + CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); + CALL buyUltimate (vWarehouseFk, vShipped); + + INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk) + SELECT vWarehouseFk, + i.item_id, + IFNULL(i.available, 0), + bu.buyFk + FROM `cache`.available i + JOIN tmp.item br ON br.itemFk = i.item_id + LEFT JOIN item it ON it.id = i.item_id + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id + WHERE i.calc_id = vAvailableCalc + AND it.id != 100 + AND i.available > 0; + + DROP TEMPORARY TABLE tmp.buyUltimate; + END LOOP; + + CLOSE cTravelTree; + + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; + CREATE TEMPORARY TABLE tmp.ticketCalculateItem + ENGINE = MEMORY + SELECT + b.itemFk, + SUM(b.available) available, + p.name producer, + i.name item, + i.size size, + i.stems, + i.category, + i.inkFk, + i.image, + o.code origin, + bl.price, + bl.priceKg + FROM tmp.ticketLot b + JOIN item i ON b.itemFk = i.id + LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible + JOIN origin o ON o.id = i.originFk + JOIN ( + SELECT MIN(price) price, itemFk, priceKg + FROM tmp.ticketComponentPrice + GROUP BY itemFk + ) bl ON bl.itemFk = b.itemFk + GROUP BY b.itemFk; + +END$$ + +DELIMITER ; + diff --git a/db/changes/10100-allSaints/03-order_confirmWithUser.sql b/db/changes/10100-allSaints/03-order_confirmWithUser.sql new file mode 100644 index 000000000..e7b4b2edb --- /dev/null +++ b/db/changes/10100-allSaints/03-order_confirmWithUser.sql @@ -0,0 +1,244 @@ +USE `hedera`; +DROP procedure IF EXISTS `order_confirmWithUser`; + +DELIMITER $$ +USE `hedera`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `order_confirmWithUser`(IN `vOrder` INT, IN `vUserId` INT) +BEGIN +/** + * Confirms an order, creating each of its tickets on the corresponding + * date, store and user. + * + * @param vOrder The order identifier + * @param vUser The user identifier + */ + DECLARE vOk BOOL; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vWarehouse INT; + DECLARE vShipment DATETIME; + DECLARE vTicket INT; + DECLARE vNotes VARCHAR(255); + DECLARE vItem INT; + DECLARE vConcept VARCHAR(30); + DECLARE vAmount INT; + DECLARE vPrice DECIMAL(10,2); + DECLARE vSale INT; + DECLARE vRate INT; + DECLARE vRowId INT; + DECLARE vDelivery DATE; + DECLARE vAddress INT; + DECLARE vIsConfirmed BOOL; + DECLARE vClientId INT; + DECLARE vCompanyId INT; + DECLARE vAgencyModeId INT; + + DECLARE TICKET_FREE INT DEFAULT 2; + + DECLARE cDates CURSOR FOR + SELECT zgs.shipped, r.warehouse_id + FROM `order` o + JOIN order_row r ON r.order_id = o.id + LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouse_id + WHERE o.id = vOrder AND r.amount != 0 + GROUP BY r.warehouse_id; + + DECLARE cRows CURSOR FOR + SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate + FROM order_row r + JOIN vn.item i ON i.id = r.item_id + WHERE r.amount != 0 + AND r.warehouse_id = vWarehouse + AND r.order_id = vOrder + ORDER BY r.rate DESC; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + -- Carga los datos del pedido + + SELECT o.date_send, o.address_id, o.note, + o.confirmed, a.clientFk, o.company_id, o.agency_id + INTO vDelivery, vAddress, vNotes, + vIsConfirmed, vClientId, vCompanyId, vAgencyModeId + FROM hedera.`order` o + JOIN vn.address a ON a.id = o.address_id + WHERE o.id = vOrder; + + -- Comprueba que el pedido no está confirmado + + IF vIsConfirmed THEN + CALL util.throw ('ORDER_ALREADY_CONFIRMED'); + END IF; + + -- Comprueba que el pedido no está vacío + + SELECT COUNT(*) > 0 INTO vOk + FROM order_row WHERE order_id = vOrder AND amount > 0; + + IF !vOk THEN + CALL util.throw ('ORDER_EMPTY'); + END IF; + + -- Carga las fechas de salida de cada almacén + + CALL vn.zone_getShippedWarehouse (vDelivery, vAddress, vAgencyModeId); + + -- Trabajador que realiza la acción + + IF vUserId IS NULL THEN + SELECT employeeFk INTO vUserId FROM orderConfig; + END IF; + + -- Crea los tickets del pedido + + START TRANSACTION; + + OPEN cDates; + + lDates: + LOOP + SET vTicket = NULL; + SET vDone = FALSE; + FETCH cDates INTO vShipment, vWarehouse; + + IF vDone THEN + LEAVE lDates; + END IF; + + -- Busca un ticket existente que coincida con los parametros + + SELECT t.id INTO vTicket + FROM vn.ticket t + LEFT JOIN vn.ticketState tls on tls.ticket = t.id + JOIN `order` o + ON o.address_id = t.addressFk + AND vWarehouse = t.warehouseFk + AND o.agency_id = t.agencyModeFk + AND o.date_send = t.landed + AND vShipment = DATE(t.shipped) + WHERE o.id = vOrder + AND t.invoiceOutFk IS NULL + AND IFNULL(tls.alertLevel,0) = 0 + LIMIT 1; + + -- Crea el ticket en el caso de no existir uno adecuado + + IF vTicket IS NULL + THEN + CALL vn.ticketCreateWithUser( + vClientId, + IFNULL(vShipment, CURDATE()), + vWarehouse, + vCompanyId, + vAddress, + vAgencyModeId, + NULL, + vDelivery, + vUserId, + vTicket + ); + ELSE + INSERT INTO vncontrol.inter + SET Id_Ticket = vTicket, + Id_Trabajador = vUserId, + state_id = TICKET_FREE; + END IF; + + INSERT IGNORE INTO vn.orderTicket + SET orderFk = vOrder, + ticketFk = vTicket; + + -- Añade las notas + + IF vNotes IS NOT NULL AND vNotes != '' + THEN + INSERT INTO vn.ticketObservation SET + ticketFk = vTicket, + observationTypeFk = 4 /* salesperson */ , + `description` = vNotes + ON DUPLICATE KEY UPDATE + `description` = CONCAT(VALUES(`description`),'. ', `description`); + END IF; + + -- Añade los movimientos y sus componentes + + OPEN cRows; + + lRows: + LOOP + SET vDone = FALSE; + FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate; + + IF vDone THEN + LEAVE lRows; + END IF; + + INSERT INTO vn.sale + SET + itemFk = vItem, + ticketFk = vTicket, + concept = vConcept, + quantity = vAmount, + price = vPrice, + priceFixed = 0, + isPriceFixed = TRUE; + + SET vSale = LAST_INSERT_ID(); + + INSERT INTO vn.saleComponent + (saleFk, componentFk, `value`) + SELECT vSale, cm.component_id, cm.price + FROM order_component cm + JOIN bi.tarifa_componentes tc + ON tc.Id_Componente = cm.component_id + WHERE cm.order_row_id = vRowId + GROUP BY vSale, cm.component_id; + + UPDATE order_row SET Id_Movimiento = vSale + WHERE id = vRowId; + + END LOOP; + + CLOSE cRows; + + -- Fija el coste + + DROP TEMPORARY TABLE IF EXISTS tComponents; + CREATE TEMPORARY TABLE tComponents + (INDEX (saleFk)) + ENGINE = MEMORY + SELECT SUM(sc.`value`) valueSum, sc.saleFk + FROM vn.saleComponent sc + JOIN bi.tarifa_componentes tc ON tc.Id_Componente = sc.componentFk + JOIN bi.tarifa_componentes_series tcs + ON tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id + AND tcs.base + JOIN vn.sale s + ON s.id = sc.saleFk + WHERE s.ticketFk = vTicket + GROUP BY sc.saleFk; + + UPDATE vn.sale s + JOIN tComponents mc ON mc.saleFk = s.id + SET s.priceFixed = valueSum; + + DROP TEMPORARY TABLE tComponents; + END LOOP; + + CLOSE cDates; + + DELETE FROM basketOrder WHERE orderFk = vOrder; + UPDATE `order` SET confirmed = TRUE, confirm_date = NOW() + WHERE id = vOrder; + + COMMIT; +END$$ + +DELIMITER ; + diff --git a/db/changes/10100-allSaints/03-ticketCalculateClon.sql b/db/changes/10100-allSaints/03-ticketCalculateClon.sql new file mode 100644 index 000000000..86d1c6033 --- /dev/null +++ b/db/changes/10100-allSaints/03-ticketCalculateClon.sql @@ -0,0 +1,88 @@ +USE `vn`; +DROP procedure IF EXISTS `ticketCalculateClon`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT) +BEGIN + /* + * @vTicketNew id del nuevo ticket clonado + * @vTicketOld id ticket original, a partir del qual se clonara el nuevo + * Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo + */ + DECLARE vShipped DATE; + DECLARE vClient INT; + DECLARE vWarehouse SMALLINT; + DECLARE vAgencyMode INT; + DECLARE vAddress INT; + DECLARE vLanded DATE; + DECLARE vAgency INT; + DECLARE vZoneFk INT; + + REPLACE INTO orderTicket(orderFk,ticketFk) + SELECT orderFk, vTicketNew + FROM orderTicket + WHERE ticketFk = vTicketOld; + + SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk, t.zoneFk + INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency, vZoneFk + FROM vn.agencyMode a + JOIN vn.ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicketNew; + + IF vLanded IS NULL THEN + CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse); + UPDATE ticket t + JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk + SET t.landed = zgl.landed, + t.zone = zgl.zoneFk + WHERE t.id = vTicketNew; + + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; + END IF; + + -- rellena la tabla tmp.buyUltimate con la ultima compra + CALL buyUltimate(vWarehouse, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; + + CALL catalog_componentCalculate(vZoneFk, vAddress, vAgencyMode); + + -- Bionizamos lineas con Preu = 0 + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT s.id saleFk, vWarehouse warehouseFk + FROM sale s + JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew AND s.price = 0; + + CALL ticketComponentUpdateSale(1); + + -- Bionizamos lineas con Preu > 0 + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT s.id saleFk, vWarehouse warehouseFk + FROM sale s + JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew + AND s.price > 0; + + CALL ticketComponentUpdateSale(6); + + -- Log + CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket'); + + -- Limpieza + DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate; + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; +END$$ + +DELIMITER ; diff --git a/db/changes/10100-allSaints/03-ticketComponentCalculate.sql b/db/changes/10100-allSaints/03-ticketComponentCalculate.sql new file mode 100644 index 000000000..4547c4c64 --- /dev/null +++ b/db/changes/10100-allSaints/03-ticketComponentCalculate.sql @@ -0,0 +1,262 @@ + +USE `vn`; +DROP procedure IF EXISTS `vn`.`ticketComponentCalculate`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate__`( + vAddressFk INT, + vAgencyModeFk INT) +proc: BEGIN +-- OBSOLETO usar catalog_componentCalculate +/** + * Calcula los componentes de un ticket + * + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id del modo de agencia + * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, + * packing, grouping, groupingMode, buyFk, typeFk) + * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) + */ + + DECLARE vClientFk INT; + DECLARE vGeneralInflationCoefficient INT DEFAULT 1; + DECLARE vMinimumDensityWeight INT DEFAULT 167; + DECLARE vBoxFreightItem INT DEFAULT 71; + DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; + DECLARE vSpecialPriceComponent INT DEFAULT 10; + DECLARE vDeliveryComponent INT DEFAULT 15; + DECLARE vRecoveryComponent INT DEFAULT 17; + DECLARE vSellByPacketComponent INT DEFAULT 22; + DECLARE vBuyValueComponent INT DEFAULT 28; + DECLARE vMarginComponent INT DEFAULT 29; + DECLARE vDiscountLastItemComponent INT DEFAULT 32; + DECLARE vExtraBaggedComponent INT DEFAULT 38; + DECLARE vManaAutoComponent INT DEFAULT 39; + + + + SELECT volume INTO vBoxVolume + FROM vn.packaging + WHERE id = '94'; + + SELECT clientFk INTO vClientFK + FROM address + WHERE id = vAddressFk; + + SET @rate2 := 0; + SET @rate3 := 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; + CREATE TEMPORARY TABLE tmp.ticketComponentCalculate + (PRIMARY KEY (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT + tl.itemFk, tl.warehouseFk, tl.available, + IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, + IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, + IFNULL(pf.rate3, 0) AS minPrice, + IFNULL(pf.packing, b.packing) packing, + IFNULL(pf.`grouping`, b.`grouping`) `grouping`, + ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, + tl.buyFk, + i.typeFk, + IF(i.hasKgPrice,b.weight / b.packing, NULL) weightGrouping + FROM tmp.ticketLot tl + JOIN buy b ON b.id = tl.buyFk + JOIN item i ON i.id = tl.itemFk + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk + LEFT JOIN ( + SELECT * FROM ( + SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, aho.warehouseFk + FROM priceFixed pf + JOIN tmp.zoneGetShipped aho ON pf.warehouseFk = aho.warehouseFk OR pf.warehouseFk = 0 + WHERE aho.shipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC + ) tpf + GROUP BY tpf.itemFk, tpf.warehouseFk + ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk + WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; + CREATE TEMPORARY TABLE tmp.ticketComponent ( + `warehouseFk` INT UNSIGNED NOT NULL, + `itemFk` INT NOT NULL, + `componentFk` INT UNSIGNED NOT NULL, + `cost` DECIMAL(10,4) NOT NULL, + INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), + UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)); + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vBuyValueComponent, + b.buyingValue + b.freightValue + b.packageValue + b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vMarginComponent, + tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; + CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY + SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk + FROM tmp.ticketComponent tc + GROUP BY tc.itemFk, warehouseFk; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3) + FROM tmp.ticketComponentBase tcb + JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk + WHERE cr.recobro > 0.009; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto + FROM tmp.ticketComponentBase tcb + JOIN `client` c on c.id = vClientFk + JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador + WHERE ms.prices_modifier_activated + HAVING manaAuto <> 0; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, + tcb.itemFk, + cr.id, + GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3) + FROM tmp.ticketComponentBase tcb + JOIN componentRate cr + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFK, + tcc.itemFk, + vDeliveryComponent, + vGeneralInflationCoefficient + * ROUND(( + i.compression + * r.cm3 + * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) + * IFNULL((z.price - z.bonus) + * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 + ) cost + FROM tmp.ticketComponentCalculate tcc + JOIN item i ON i.id = tcc.itemFk + JOIN agencyMode am ON am.id = vAgencyModeFk + JOIN `address` a ON a.id = vAddressFk + JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = tcc.warehouseFk + JOIN zone z ON z.id = zgs.id + LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk + AND r.Id_Article = tcc.itemFk + HAVING cost <> 0; + + IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost + FROM tmp.ticketComponentCalculate tcc + JOIN vn.addressForPackaging ap + WHERE ap.addressFk = vAddressFk; + END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; + CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY + SELECT * FROM tmp.ticketComponent; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, + tcc.itemFk, + vSpecialPriceComponent, + sp.value - SUM(tcc.cost) sumCost + FROM tmp.ticketComponentCopy tcc + JOIN componentRate cr ON cr.id = tcc.componentFk + JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk + WHERE cr.classRate IS NULL + GROUP BY tcc.itemFk, tcc.warehouseFk + HAVING ABS(sumCost) > 0.001; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; + CREATE TEMPORARY TABLE tmp.ticketComponentSum + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate + FROM tmp.ticketComponent tc + JOIN componentRate cr ON cr.id = tc.componentFk + GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; + CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY + SELECT tcc.warehouseFk, + tcc.itemFk, + 1 rate, + IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, + CAST(SUM(tcs.sumCost) / weightGrouping AS DECIMAL(10,2)) priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 1) = 1 + AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 2 rate, + tcc.packing `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 + AND tcc.packing > 0 AND tcc.available >= tcc.packing) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 3 rate, + tcc.available `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 3) = 3 + GROUP BY tcs.warehouseFk, tcs.itemFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; + CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY + SELECT * FROM ( + SELECT * FROM tmp.ticketComponentRate ORDER BY price + ) t + GROUP BY itemFk, warehouseFk, `grouping`; + + DROP TEMPORARY TABLE + tmp.ticketComponentCalculate, + tmp.ticketComponentSum, + tmp.ticketComponentBase, + tmp.ticketComponentRate, + tmp.ticketComponentCopy; +END$$ + +DELIMITER ; +; diff --git a/db/changes/10100-allSaints/03-ticketCreateWithUser.sql b/db/changes/10100-allSaints/03-ticketCreateWithUser.sql new file mode 100644 index 000000000..8135c72bf --- /dev/null +++ b/db/changes/10100-allSaints/03-ticketCreateWithUser.sql @@ -0,0 +1,88 @@ +USE `vn`; +DROP procedure IF EXISTS `ticketCreateWithUser`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`( + vClientId INT + ,vShipped DATE + ,vWarehouseFk INT + ,vCompanyFk INT + ,vAddressFk INT + ,vAgencyModeFk INT + ,vRouteFk INT + ,vlanded DATE + ,vUserId INT + ,OUT vNewTicket INT) +BEGIN + + DECLARE vZoneFk INT; + + IF vClientId IS NULL THEN + CALL util.throw ('CLIENT_NOT_ESPECIFIED'); + END IF; + + IF NOT vAddressFk OR vAddressFk IS NULL THEN + SELECT id INTO vAddressFk + FROM address + WHERE clientFk = vClientId AND isDefaultAddress; + END IF; + + IF vAgencyModeFk IS NOT NULL THEN + + CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); + + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped + WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; + + IF vZoneFk IS NULL OR vZoneFk = 0 THEN + CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); + END IF; + END IF; + INSERT INTO ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + routeFk, + companyFk, + landed, + zoneFk + ) + SELECT + vClientId, + vShipped, + a.id, + vAgencyModeFk, + a.nickname, + vWarehouseFk, + IF(vRouteFk,vRouteFk,NULL), + vCompanyFk, + vlanded, + vZoneFk + FROM address a + JOIN agencyMode am ON am.id = a.agencyModeFk + WHERE a.id = vAddressFk; + + SET vNewTicket = LAST_INSERT_ID(); + + INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) + SELECT vNewTicket, ao.observationTypeFk, ao.description + FROM addressObservation ao + JOIN address a ON a.id = ao.addressFk + WHERE a.id = vAddressFk; + + INSERT INTO vn.ticketLog + SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); + + IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT id, vNewTicket, getWorker() + FROM state + WHERE `code` = 'DELIVERED'; + END IF; +END$$ + +DELIMITER ; diff --git a/db/changes/10100-allSaints/03-ticketCreateWithoutZone.sql b/db/changes/10100-allSaints/03-ticketCreateWithoutZone.sql new file mode 100644 index 000000000..b4840e31d --- /dev/null +++ b/db/changes/10100-allSaints/03-ticketCreateWithoutZone.sql @@ -0,0 +1,90 @@ +USE `vn`; +DROP procedure IF EXISTS `ticketCreateWithoutZone`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`( + vClientId INT + ,vShipped DATE + ,vWarehouseFk INT + ,vCompanyFk INT + ,vAddressFk INT + ,vAgencyModeFk INT + ,vRouteFk INT + ,vlanded DATE + ,vUserId INT + ,OUT vNewTicket INT) +BEGIN + + DECLARE vZoneFk INT; + + IF vClientId IS NULL THEN + CALL util.throw ('CLIENT_NOT_ESPECIFIED'); + END IF; + + IF NOT vAddressFk OR vAddressFk IS NULL THEN + SELECT id INTO vAddressFk + FROM address + WHERE clientFk = vClientId AND isDefaultAddress; + END IF; + + IF NOT vAgencyModeFk OR vAgencyModeFk IS NULL THEN + SELECT agencyModeFk INTO vAgencyModeFk + FROM address + WHERE clientFk = vClientId AND isDefaultAddress; + END IF; + + CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); + + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped + WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; + + INSERT INTO vn2008.Tickets ( + Id_Cliente, + Fecha, + Id_Consigna, + Id_Agencia, + Alias, + warehouse_id, + Id_Ruta, + empresa_id, + landing, + zoneFk + ) + SELECT + vClientId, + vShipped, + a.id, + IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk), + a.nickname, + vWarehouseFk, + IF(vRouteFk,vRouteFk,NULL), + vCompanyFk, + vlanded, + vZoneFk + FROM address a + JOIN agencyMode am ON am.id = a.agencyModeFk + WHERE a.id = vAddressFk; + + SET vNewTicket = LAST_INSERT_ID(); + + INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) + SELECT vNewTicket, ao.observationTypeFk, ao.description + FROM addressObservation ao + JOIN address a ON a.id = ao.addressFk + WHERE a.id = vAddressFk; + + -- CALL logAddWithUser(vNewTicket, vUserId, 'insert', 'ticket', CONCAT('Ha creado el ticket', ' ', vNewTicket)); + INSERT INTO vn.ticketLog + SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); + + IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT id, vNewTicket, getWorker() + FROM state + WHERE `code` = 'DELIVERED'; + END IF; +END$$ + +DELIMITER ; + diff --git a/db/changes/10100-allSaints/05-catalog_calcFromItem.sql b/db/changes/10100-allSaints/05-catalog_calcFromItem.sql new file mode 100644 index 000000000..40b2c2eb8 --- /dev/null +++ b/db/changes/10100-allSaints/05-catalog_calcFromItem.sql @@ -0,0 +1,31 @@ +USE `vn`; +DROP procedure IF EXISTS `catalog_calcFromItem`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calcFromItem`( + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT, + vItemFk INT) +BEGIN +/** + * Calculates available and price for a single item. + * + * @param vItemFk The item id + * @return tmp.ticketCalculateItem + * @return tmp.ticketComponentPrice + * @return tmp.ticketComponent + * @return tmp.ticketLot + * @return tmp.zoneGetShipped + */ + DROP TEMPORARY TABLE IF EXISTS tmp.item; + CREATE TEMPORARY TABLE tmp.item + ENGINE = MEMORY + SELECT vItemFk itemFk; + + CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); + DROP TEMPORARY TABLE tmp.item; +END$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/00-chatConfig.sql b/db/changes/10110-postCampaign/00-chatConfig.sql new file mode 100644 index 000000000..e0423bb86 --- /dev/null +++ b/db/changes/10110-postCampaign/00-chatConfig.sql @@ -0,0 +1,11 @@ +USE `vn`; + +CREATE TABLE `vn`.`chatConfig` ( + `id` INT NOT NULL AUTO_INCREMENT, + `uri` VARCHAR(255) NOT NULL, + `user` VARCHAR(50) NOT NULL, + `password` VARCHAR(50) NOT NULL, + PRIMARY KEY (`id`)); + + +INSERT INTO `vn`.`chatConfig` (`uri`, `user`, `password`) VALUES ('https://chat.verdnatura.es/api/v1', 'VnBot', 'Ub606cux7op.'); diff --git a/db/changes/10110-postCampaign/00-clientBeforeUpdate.sql b/db/changes/10110-postCampaign/00-clientBeforeUpdate.sql new file mode 100644 index 000000000..5e69e28ad --- /dev/null +++ b/db/changes/10110-postCampaign/00-clientBeforeUpdate.sql @@ -0,0 +1,51 @@ +DROP TRIGGER IF EXISTS `vn`.`client_beforeUpdate`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` TRIGGER `vn`.`client_beforeUpdate` + BEFORE UPDATE ON `client` + FOR EACH ROW +BEGIN + DECLARE vText VARCHAR(255) DEFAULT NULL; + -- Comprueba que el formato de los teléfonos es válido + + IF !(NEW.phone <=> OLD.phone) THEN + CALL pbx.phone_isValid(NEW.phone); + END IF; + + IF !(NEW.mobile <=> OLD.mobile) THEN + CALL pbx.phone_isValid(NEW.mobile); + END IF; + + IF !(NEW.fax <=> OLD.fax) THEN + CALL pbx.phone_isValid(NEW.fax); + END IF; + + IF NEW.payMethodFk = 4 AND NEW.dueDay = 0 THEN + SET NEW.dueDay = 5; + END IF; + + -- Avisar al comercial si ha llegado la documentación sepa/core + + IF NEW.hasSepaVnl AND !OLD.hasSepaVnl THEN + SET vText = 'Sepa de VNL'; + END IF; + + IF NEW.hasCoreVnl AND !OLD.hasCoreVnl THEN + SET vText = 'Core de VNL'; + END IF; + + IF vText IS NOT NULL + THEN + INSERT INTO mail(sender, replyTo, `subject`, body) + SELECT + CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'), + 'administracion@verdnatura.es', + CONCAT('Cliente ', NEW.id), + CONCAT('Recibida la documentación: ', vText) + FROM worker w + LEFT JOIN account.user u ON w.userFk = u.id AND u.active + LEFT JOIN account.account ac ON ac.id = u.id + WHERE w.id = NEW.salesPersonFk; + END IF; +END$$ +DELIMITER ; diff --git a/db/changes/10110-postCampaign/00-clientGetMana.sql b/db/changes/10110-postCampaign/00-clientGetMana.sql new file mode 100644 index 000000000..dcf9171b2 --- /dev/null +++ b/db/changes/10110-postCampaign/00-clientGetMana.sql @@ -0,0 +1,75 @@ +DROP function IF EXISTS `vn`.`clientGetMana`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` FUNCTION `vn`.`clientGetMana`(vClient INT) RETURNS decimal(10,2) + DETERMINISTIC +BEGIN +/** + * Devuelve el mana del cliente. + * + * @param vClient Id del cliente + * @return Mana del cliente + */ + DECLARE vMana DECIMAL(10,2); + DECLARE vFromDated DATE; + DECLARE vHasMana BOOLEAN; + DECLARE vManaComponent INT; + DECLARE vAutoManaComponent INT; + DECLARE vManaBank INT; + DECLARE vManaGreugeType INT; + + SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana'; + SELECT id INTO vManaBank FROM bank WHERE code = 'mana'; + SELECT id INTO vManaComponent FROM component WHERE code = 'mana'; + SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana'; + + SELECT COUNT(*) INTO vHasMana + FROM `client` c + WHERE c.id = vClient AND c.typeFk = 'normal'; + + IF NOT vHasMana THEN + RETURN 0; + END IF; + + SELECT max(dated) INTO vFromDated + FROM clientManaCache; + + SELECT sum(mana) INTO vMana + FROM + ( + SELECT mana + FROM clientManaCache + WHERE clientFk = vClient + AND dated = vFromDated + UNION ALL + SELECT s.quantity * value + FROM ticket t + JOIN address a ON a.id = t.addressFk + JOIN sale s on s.ticketFk = t.id + JOIN saleComponent sc on sc.saleFk = s.id + WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent) + AND t.shipped > vFromDated + AND t.shipped < TIMESTAMPADD(DAY,1,CURDATE()) + AND a.clientFk = vClient + UNION ALL + SELECT - amountPaid + FROM receipt r + JOIN `client` c ON c.id = r.clientFk + WHERE r.bankFk = vManaBank + AND r.payed > vFromDated + AND r.payed <= CURDATE() + AND c.id = vClient + UNION ALL + SELECT g.amount + FROM greuge g + JOIN `client` c ON c.id = g.clientFk + WHERE g.greugeTypeFk = vManaGreugeType + AND g.shipped > vFromDated + AND g.shipped <= CURDATE() + AND c.id = vClient + ) sub; + RETURN IFNULL(vMana,0); +END$$ + +DELIMITER ; + diff --git a/db/changes/10110-postCampaign/00-clientPackagingOverstock.sql b/db/changes/10110-postCampaign/00-clientPackagingOverstock.sql new file mode 100644 index 000000000..a981fd5cb --- /dev/null +++ b/db/changes/10110-postCampaign/00-clientPackagingOverstock.sql @@ -0,0 +1,97 @@ + +DROP procedure IF EXISTS `vn`.`clientPackagingOverstock`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`clientPackagingOverstock`(vClientFk INT, vGraceDays INT ) +BEGIN + DROP TEMPORARY TABLE IF EXISTS tmp.clientPackagingOverstock; + CREATE TEMPORARY TABLE tmp.clientPackagingOverstock + ENGINE = MEMORY + SELECT itemFk, + sum(GotfromClient) - sum(SenttoClient) as devueltos, + sum(InvoicedtoClient) - sum(InvoicedfromClient) as facturados, + LEAST( + sum(GotfromClient) - sum(SenttoClient), + sum(InvoicedtoClient) - sum(InvoicedfromClient) + ) as abonables + FROM + ( + SELECT t.*, + IF(@month = month, 0, 1) monthEnd, + @month := month + FROM + ( + SELECT x.id as ticketFk, + date(x.shipped) as shipped, + x.itemFk, + IFNULL(cast(sum(x.InvoicedtoClient) as DECIMAL(10,0)),0) InvoicedtoClient, + IFNULL(cast(sum(x.InvoicedfromClient) as DECIMAL(10,0)),0) InvoicedfromClient, + IFNULL(cast(sum(x.SenttoClient) as DECIMAL(10,0)),0) SenttoClient, + IFNULL(cast(sum(x.GotfromClient) as DECIMAL(10,0)),0) GotfromClient, + i.name as concept, + x.refFk as invoice, + month(shipped) month, + x.companyFk + FROM + ( + SELECT t.id, + t.shipped, + IFNULL(pe.equivalentFk, s.itemFk) itemFk, + IF(s.quantity > 0, s.quantity, NULL) InvoicedtoClient, + IF(s.quantity < 0, -s.quantity, NULL) InvoicedfromClient, + NULL SenttoClient, + NULL GotfromClient, + t.refFk, + @month := 0 month, + t.companyFk + FROM sale s + JOIN ticket t on t.id = s.ticketFk + JOIN packaging p ON p.itemFk = s.itemFk + LEFT JOIN packageEquivalentItem pe ON pe.itemFk = s.itemFk + WHERE t.clientFk = vClientFk + AND t.shipped > '2017-11-30' + AND p.isPackageReturnable + UNION ALL + SELECT NULL, + '2017-11-30', + IFNULL(pe.equivalentFk, tps.itemFk) itemFk, + tps.sent InvoicedtoClient, + tps.returned InvoicedfromClient, + NULL SenttoClient, + NULL GotfromClient, + 'Histórico', + NULL, + NULL + + FROM ticketPackagingStartingStock tps + LEFT JOIN packageEquivalentItem pe ON pe.itemFk = tps.itemFk + WHERE tps.clientFk = vClientFk + AND tps.isForgetable = FALSE + UNION ALL + SELECT t.id, + t.shipped, + IFNULL(pe.equivalentFk, p.itemFk) itemFk, + NULL, + NULL, + IF(tp.quantity > 0 AND t.shipped <= TIMESTAMPADD(DAY, - vGraceDays, CURDATE()), tp.quantity, NULL) SenttoClient, + IF(tp.quantity < 0, -tp.quantity, NULL) GotfromClient, + NULL AS refFk, + NULL, + t.companyFk + FROM ticketPackaging tp + JOIN ticket t on t.id = tp.ticketFk + JOIN packaging p ON p.id = tp.packagingFk + LEFT JOIN packageEquivalentItem pe ON pe.itemFk = p.itemFk + WHERE t.clientFk = vClientFk + AND t.shipped > '2017-11-21' ) x + + JOIN item i ON x.itemFk = i.id + GROUP BY x.id, x.itemFk + ) t + ORDER BY itemFk, shipped DESC + ) t2 + GROUP BY itemFk; +END$$ + +DELIMITER ; + diff --git a/db/changes/10110-postCampaign/00-clonTravelComplete.sql b/db/changes/10110-postCampaign/00-clonTravelComplete.sql new file mode 100644 index 000000000..9817613f4 --- /dev/null +++ b/db/changes/10110-postCampaign/00-clonTravelComplete.sql @@ -0,0 +1,132 @@ +DROP procedure IF EXISTS `vn`.`clonTravelComplete`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`clonTravelComplete`(IN `vTravelFk` INT, IN `vDateStart` DATE, IN `vDateEnd` DATE, IN `vRef` VARCHAR(255)) +BEGIN + + DECLARE vTravelNew INT; + DECLARE vEntryNew INT; + DECLARE vDone BIT DEFAULT 0; + DECLARE vAuxEntryFk INT; + DECLARE vRsEntry CURSOR FOR + SELECT e.id + FROM entry e + JOIN travel t + ON t.id = e.travelFk + WHERE e.travelFk = vTravelFk; + + DECLARE vRsBuy CURSOR FOR + SELECT b.* + FROM buy b + JOIN entry e + ON b.entryFk = e.id + WHERE e.travelFk = vTravelNew and b.entryFk=entryNew + ORDER BY e.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + INSERT INTO travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg) + SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg + FROM travel + WHERE id = vTravelFk; + + SET vTravelNew = LAST_INSERT_ID(); + SET vDone = 0; + OPEN vRsEntry ; + FETCH vRsEntry INTO vAuxEntryFk; + + WHILE NOT vDone DO + INSERT INTO entry (supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + travelFk, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk) + SELECT supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + vTravelNew, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk + FROM entry + WHERE id = vAuxEntryFk; + + SET vEntryNew = LAST_INSERT_ID(); + + + INSERT INTO buy (entryFk, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isChecked) + SELECT vEntryNew, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isChecked + FROM buy + WHERE entryFk = vAuxEntryFk; + + + FETCH vRsEntry INTO vAuxEntryFk; + END WHILE; + CLOSE vRsEntry; + COMMIT; + END$$ + +DELIMITER ; + diff --git a/db/changes/10110-postCampaign/00-country.sql b/db/changes/10110-postCampaign/00-country.sql new file mode 100644 index 000000000..dcc883ab8 --- /dev/null +++ b/db/changes/10110-postCampaign/00-country.sql @@ -0,0 +1,10 @@ +USE `vn`; + +UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 1); +UPDATE `vn`.`country` SET `ibanLength` = '27' WHERE (`id` = 2); +UPDATE `vn`.`country` SET `ibanLength` = '22' WHERE (`id` = 3); +UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 4); +UPDATE `vn`.`country` SET `ibanLength` = '18' WHERE (`id` = 5); +UPDATE `vn`.`country` SET `ibanLength` = '25' WHERE (`id` = 8); +UPDATE `vn`.`country` SET `ibanLength` = '27' WHERE (`id` = 19); +UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 30); diff --git a/db/changes/10110-postCampaign/00-creditClassificationBeforeUpdate.sql b/db/changes/10110-postCampaign/00-creditClassificationBeforeUpdate.sql new file mode 100644 index 000000000..5ca0fd131 --- /dev/null +++ b/db/changes/10110-postCampaign/00-creditClassificationBeforeUpdate.sql @@ -0,0 +1,16 @@ + +DELIMITER $$ +DROP TRIGGER IF EXISTS `vn`.`creditClassification_BEFORE_UPDATE` $$ + + +CREATE DEFINER=`root`@`%` TRIGGER `vn`.`creditClassification_beforeUpdate` BEFORE UPDATE ON `creditClassification` FOR EACH ROW +BEGIN + IF NEW.client <> OLD.client THEN + CALL util.throw('NOT_ALLOWED_CHANGE_CLIENT'); + END IF; + IF NEW.dateEnd IS NOT NULL AND OLD.dateEnd IS NULL THEN + UPDATE `client` c + SET creditInsurance = 0 WHERE c.id = NEW.client; + END IF; +END$$ +DELIMITER ; diff --git a/db/changes/10110-postCampaign/00-creditInsuranceAfterInsert.sql b/db/changes/10110-postCampaign/00-creditInsuranceAfterInsert.sql new file mode 100644 index 000000000..4429b1e97 --- /dev/null +++ b/db/changes/10110-postCampaign/00-creditInsuranceAfterInsert.sql @@ -0,0 +1,13 @@ + +DELIMITER $$ + +DROP TRIGGER IF EXISTS `vn`.`creditInsurance_AFTER_INSERT` $$ + +CREATE DEFINER=`root`@`%` TRIGGER `vn`.`creditInsurance_afterInsert` AFTER INSERT ON `creditInsurance` FOR EACH ROW +BEGIN + UPDATE `client` c + JOIN vn.creditClassification cc ON cc.client = c.id + SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; + +END$$ +DELIMITER ; diff --git a/db/changes/10110-postCampaign/00-department_doCalc.sql b/db/changes/10110-postCampaign/00-department_doCalc.sql new file mode 100644 index 000000000..7adeb30f0 --- /dev/null +++ b/db/changes/10110-postCampaign/00-department_doCalc.sql @@ -0,0 +1,3 @@ +USE `vn`; + +CREATE DEFINER=`root`@`%` EVENT `department_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-11-15 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.department_doCalc \ No newline at end of file diff --git a/db/changes/10110-postCampaign/00-duaInvoicingBooking.sql b/db/changes/10110-postCampaign/00-duaInvoicingBooking.sql new file mode 100644 index 000000000..091acef43 --- /dev/null +++ b/db/changes/10110-postCampaign/00-duaInvoicingBooking.sql @@ -0,0 +1,74 @@ + +DROP procedure IF EXISTS `vn`.`duaInvoiceInBooking`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`duaInvoiceInBooking`(vDuaFk INT) +BEGIN + DECLARE done BOOL DEFAULT FALSE; + DECLARE vInvoiceFk INT; + DECLARE vASIEN BIGINT DEFAULT 0; + DECLARE vCounter INT DEFAULT 0; + + DECLARE rs CURSOR FOR + SELECT e.invoiceInFk + FROM entry e + JOIN duaEntry de ON de.entryFk = e.id + JOIN invoiceIn ii ON ii.id = e.invoiceInFk + WHERE de.duaFk = vDuaFk + AND de.customsValue + AND ii.isBooked = FALSE; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + OPEN rs; + + UPDATE invoiceIn ii + JOIN entry e ON e.invoiceInFk = ii.id + JOIN duaEntry de ON de.entryFk = e.id + JOIN dua d ON d.id = de.duaFk + SET ii.isBooked = TRUE, + ii.booked = IFNULL(ii.booked,d.booked), + ii.operated = IFNULL(ii.operated,d.operated), + ii.issued = IFNULL(ii.issued,d.issued), + ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried), + e.isConfirmed = TRUE + WHERE d.id = vDuaFk; + + SELECT IFNULL(ASIEN,0) INTO vASIEN + FROM dua + WHERE id = vDuaFk; + + FETCH rs INTO vInvoiceFk; + + WHILE NOT done DO + + CALL invoiceInBookingMain(vInvoiceFk); + + IF vCounter > 0 OR vASIEN > 0 THEN + + UPDATE XDiario x + JOIN config c ON c.ASIEN = x.ASIEN + SET x.ASIEN = vASIEN; + + ELSE + + SELECT ASIEN INTO vASIEN FROM config; + + END IF; + + SET vCounter = vCounter + 1; + + FETCH rs INTO vInvoiceFk; + + END WHILE; + + CLOSE rs; + + UPDATE dua + SET ASIEN = vASIEN + WHERE id = vDuaFk; + +END$$ + +DELIMITER ; + diff --git a/db/changes/10110-postCampaign/00-getItemVisibleAvailable.sql b/db/changes/10110-postCampaign/00-getItemVisibleAvailable.sql new file mode 100644 index 000000000..21b827a75 --- /dev/null +++ b/db/changes/10110-postCampaign/00-getItemVisibleAvailable.sql @@ -0,0 +1,17 @@ +USE `vn`; +DROP procedure IF EXISTS `getItemVisibleAvailable`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `getItemVisibleAvailable`( + vItem INT, + vDate DATE, + vWarehouse TINYINT, + vRefresh BOOL) +BEGIN + -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 + CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); +END$$ + +DELIMITER ; + diff --git a/db/changes/10110-postCampaign/00-itemGetVisibleAvailable.sql b/db/changes/10110-postCampaign/00-itemGetVisibleAvailable.sql new file mode 100644 index 000000000..4701e7124 --- /dev/null +++ b/db/changes/10110-postCampaign/00-itemGetVisibleAvailable.sql @@ -0,0 +1,17 @@ +USE `vn`; +DROP procedure IF EXISTS `itemGetVisibleAvailable`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `itemGetVisibleAvailable`( + vItem INT, + vDate DATE, + vWarehouse TINYINT, + vRefresh BOOL) +BEGIN + -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 + CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); +END$$ + +DELIMITER ; + diff --git a/db/changes/10110-postCampaign/00-item_getVisibleAvailable.sql b/db/changes/10110-postCampaign/00-item_getVisibleAvailable.sql new file mode 100644 index 000000000..e6b6df2f9 --- /dev/null +++ b/db/changes/10110-postCampaign/00-item_getVisibleAvailable.sql @@ -0,0 +1,71 @@ + +USE `vn`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `item_getVisibleAvailable`( + vItem INT, + vDate DATE, + vWarehouse TINYINT, + vRefresh BOOL) +BEGIN + DECLARE vVisibleCalc INT; + DECLARE vAvailableCalc INT; + DECLARE vVisibleAltillo INT; + + CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/ , vWarehouse, vDate); + CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse); + + SELECT visible INTO vVisibleAltillo + FROM vn.itemShelvingStock + WHERE itemFk = vItem + AND warehouseFk = vWarehouse; + + IF vRefresh THEN + + DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; + CREATE TEMPORARY TABLE vn2008.tmp_item + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT vItem item_id, 0 stock, 0 visible; + + SELECT i.id, i.longName, i.box, i.typeFk, + i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, + ip.code, ip.reserve, + vi.visible - IFNULL(vVisibleAltillo,0) AS visible, + av.available + FROM vn.item i + LEFT JOIN vn.itemPlacement ip + ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse + LEFT JOIN vn2008.tmp_item v + ON v.item_id = i.id + LEFT JOIN cache.available av + ON av.calc_id = vAvailableCalc AND av.item_id = i.id + LEFT JOIN cache.visible vi + ON vi.calc_id = vVisibleCalc AND vi.item_id = i.id + LEFT JOIN cache.stock st + ON st.warehouse_id = vWarehouse AND st.item_id = i.id + WHERE (vItem IS NULL OR i.id = vItem); + + ELSE + + SELECT i.id, i.longName, i.box, i.typeFk, + i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, + ip.code, ip.reserve, + v.visible - IFNULL(vVisibleAltillo,0) AS visible, + av.available + FROM vn.item i + LEFT JOIN vn.itemPlacement ip + ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse + LEFT JOIN cache.visible v + ON v.item_id = i.id AND v.calc_id = vVisibleCalc + LEFT JOIN cache.available av + ON av.item_id = i.id AND av.calc_id = vAvailableCalc + WHERE (vItem IS NULL OR i.id = vItem); + + END IF; + +END$$ + +DELIMITER ; +; diff --git a/db/changes/10110-postCampaign/00-payMethod.sql b/db/changes/10110-postCampaign/00-payMethod.sql new file mode 100644 index 000000000..e2421ee53 --- /dev/null +++ b/db/changes/10110-postCampaign/00-payMethod.sql @@ -0,0 +1,7 @@ +USE `vn`; + +ALTER TABLE `vn`.`payMethod` +ADD COLUMN `code` VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL AFTER `id`; + +UPDATE `vn`.`payMethod` SET `code` = 'bankDraft' WHERE (`id` = '4'); +UPDATE `vn`.`payMethod` SET `code` = 'card' WHERE (`id` = '5'); diff --git a/db/changes/10110-postCampaign/00-rangeDateInfo.sql b/db/changes/10110-postCampaign/00-rangeDateInfo.sql new file mode 100644 index 000000000..816269ef9 --- /dev/null +++ b/db/changes/10110-postCampaign/00-rangeDateInfo.sql @@ -0,0 +1,41 @@ +DROP procedure IF EXISTS `vn`.`rangeDateInfo`; + +DELIMITER $$ +CREATE PROCEDURE `vn`.`rangeDateInfo` (vStarted DATE, vEnded DATE) +BEGIN +/** + * Crea una tabla temporal con las fechas + * desde una fecha inicial a una final + * @param vStarted fecha inicial + * @param vEnded fecha final + */ + DECLARE vDated DATE DEFAULT vStarted; + + DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; + CREATE TEMPORARY TABLE tmp.rangeDate( + `dated` DATE, + `period` INT, + `month` INT, + `year` INT, + `day` INT, + `week` INT, + `yearMonth` INT + ) + ENGINE = MEMORY; + + WHILE vDated <= vEnded DO + INSERT INTO tmp.rangeDate + SET `dated` = vDated, + `period` = YEAR(vDated) * 100 + WEEK(vDated, 1), + `month` = MONTH(vDated), + `year` = YEAR(vDated), + `day` = DAY(vDated), + `week` = WEEK(vDated, 1), + `yearMonth` = YEAR(vDated) * 100 + MONTH(vDated); + + SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY); + END WHILE; +END$$ + +DELIMITER ; + diff --git a/db/changes/10110-postCampaign/00-sample.sql b/db/changes/10110-postCampaign/00-sample.sql new file mode 100644 index 000000000..68e9d1a0f --- /dev/null +++ b/db/changes/10110-postCampaign/00-sample.sql @@ -0,0 +1,8 @@ +USE `vn`; + +UPDATE `vn`.`sample` SET `description` = 'Bienvenida como nuevo cliente' WHERE (`id` = '12'); +UPDATE `vn`.`sample` SET `description` = 'Instalación y configuración de impresora de coronas' WHERE (`id` = '13'); +UPDATE `vn`.`sample` SET `description` = 'Solicitud de domiciliación bancaria' WHERE (`id` = '14'); +UPDATE `vn`.`sample` SET `description` = 'Aviso inicial por saldo deudor' WHERE (`id` = '15'); +UPDATE `vn`.`sample` SET `description` = 'Aviso reiterado por saldo deudor' WHERE (`id` = '16'); +UPDATE `vn`.`sample` SET `isVisible` = '0' WHERE (`id` = '17'); diff --git a/db/changes/10110-postCampaign/00-ticketClosure.sql b/db/changes/10110-postCampaign/00-ticketClosure.sql new file mode 100644 index 000000000..07c7ef812 --- /dev/null +++ b/db/changes/10110-postCampaign/00-ticketClosure.sql @@ -0,0 +1,116 @@ +USE `vn`; +DROP procedure IF EXISTS `ticketClosure`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosure`() +BEGIN +/** + * Realiza el cierre de todos los + * tickets de la table ticketClosure. + */ + DECLARE vDone BOOL; + DECLARE vClientFk INT; + DECLARE vTicketFk INT; + DECLARE vIsTaxDataChecked BOOL; + DECLARE vCompanyFk INT; + DECLARE vShipped DATE; + DECLARE vPriority INT DEFAULT 1; + DECLARE vReportDeliveryNote INT DEFAULT 1; + DECLARE vNewInvoiceId INT; + DECLARE vHasDailyInvoice BOOL; + DECLARE vWithPackage BOOL; + + DECLARE cur CURSOR FOR + SELECT ticketFk FROM tmp.ticketClosure; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + RESIGNAL; + END; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2; + CREATE TEMPORARY TABLE tmp.ticketClosure2 + SELECT ticketFk FROM tmp.ticketClosure; + INSERT INTO tmp.ticketClosure + SELECT id FROM stowaway s + JOIN tmp.ticketClosure2 tc ON s.shipFk = tc.ticketFk; + OPEN cur; + + proc: LOOP + SET vDone = FALSE; + + FETCH cur INTO vTicketFk; + + IF vDone THEN + LEAVE proc; + END IF; + + -- ticketClosure start + SELECT + c.id, + c.isTaxDataChecked, + t.companyFk, + t.shipped, + co.hasDailyInvoice, + w.isManaged + INTO vClientFk, + vIsTaxDataChecked, + vCompanyFk, + vShipped, + vHasDailyInvoice, + vWithPackage + FROM ticket t + JOIN `client` c ON c.id = t.clientFk + JOIN province p ON p.id = c.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.id = vTicketFk; + + INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) + (SELECT vTicketFk, p.id, COUNT(*) + FROM expedition e + JOIN packaging p ON p.itemFk = e.itemFk + WHERE e.ticketFk = vTicketFk AND p.isPackageReturnable + AND vWithPackage + GROUP BY p.itemFk); + + -- No retornables o no catalogados + INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) + (SELECT e.itemFk, vTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.itemFk, vClientFk), 1 + FROM expedition e + JOIN item i ON i.id = e.itemFk + LEFT JOIN packaging p ON p.itemFk = i.id + WHERE e.ticketFk = vTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 + AND getSpecialPrice(e.itemFk, vClientFk) > 0 + GROUP BY e.itemFk); + + IF(vHasDailyInvoice) THEN + + -- Facturacion rapida + CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', NULL); + -- Facturar si está contabilizado + IF vIsTaxDataChecked THEN + CALL invoiceOut_newFromClient( + vClientFk, + (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), + vShipped, + vCompanyFk, + NULL, + vNewInvoiceId); + END IF; + ELSE + -- Albaran_print + CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL); + END IF; + + -- ticketClosure end + END LOOP; + + CLOSE cur; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2; +END$$ + +DELIMITER ; + diff --git a/db/changes/10110-postCampaign/00-ticketRequest.sql b/db/changes/10110-postCampaign/00-ticketRequest.sql new file mode 100644 index 000000000..cae9e09ce --- /dev/null +++ b/db/changes/10110-postCampaign/00-ticketRequest.sql @@ -0,0 +1,54 @@ + +ALTER TABLE `vn`.`ticketRequest` +DROP FOREIGN KEY `fgnAtender`; +ALTER TABLE `vn`.`ticketRequest` +CHANGE COLUMN `atenderFk` `attenderFk` INT(11) NULL DEFAULT NULL ; +ALTER TABLE `vn`.`ticketRequest` +ADD CONSTRAINT `fgnAtender` + FOREIGN KEY (`attenderFk`) + REFERENCES `vn`.`worker` (`id`) + ON UPDATE CASCADE; + + + + +DROP TRIGGER IF EXISTS `vn`.`ticketRequest_beforeInsert`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` TRIGGER `vn`.`ticketRequest_beforeInsert` BEFORE INSERT ON `ticketRequest` FOR EACH ROW +BEGIN + IF NEW.ticketFk IS NULL THEN + SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); + END IF; + + IF NEW.requesterFk IS NULL THEN + SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); + END IF; + + IF NEW.attenderFk IS NULL THEN + SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); + END IF; +END$$ +DELIMITER ; + + +DROP TRIGGER IF EXISTS `vn`.`ticketRequest_beforeUpdate`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` TRIGGER `vn`.`ticketRequest_beforeUpdate` BEFORE UPDATE ON `ticketRequest` FOR EACH ROW +BEGIN + IF NEW.saleFk <> OLD.saleFk THEN + SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); + END IF; + + IF NEW.salesPersonCode <> OLD.salesPersonCode THEN + SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); + END IF; + + IF NEW.buyerCode <> OLD.buyerCode THEN + SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); + END IF; +END$$ +DELIMITER ; + + diff --git a/db/changes/10110-postCampaign/00-ticket_recalcComponents.sql b/db/changes/10110-postCampaign/00-ticket_recalcComponents.sql new file mode 100644 index 000000000..885e2998a --- /dev/null +++ b/db/changes/10110-postCampaign/00-ticket_recalcComponents.sql @@ -0,0 +1,77 @@ +USE `vn`; +DROP procedure IF EXISTS `ticket_recalcComponents`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT ) +proc: BEGIN + +/** + * Este procedimiento trata de "rebionizar" un ticket, + * eliminando los componentes existentes e insertandolos de nuevo + * + * @param vTicketFk Id del ticket + * @return tmp.buyUltimate + */ + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vLanded DATE; + DECLARE vIsTicketEditable BOOLEAN; + DECLARE vZoneFk INTEGER; + + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk + INTO vIsTicketEditable, vZoneFk + FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket + WHERE id = vTicketFk; + + SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded + FROM ticket + WHERE id = vTicketFk; + + CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); + + CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, + s.itemFk, bu.buyFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + GROUP BY s.itemFk; + + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT id saleFk, vWarehouseFk warehouseFk + FROM sale s + WHERE s.ticketFk = vTicketFk; + + CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios + + IF vLanded IS NULL THEN + + CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); + + UPDATE vn2008.Tickets t + SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) + WHERE Id_Ticket = vTicketFk; + + DROP TEMPORARY TABLE tmp.zoneGetLanded; + + END IF; + + DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE tmp.ticketComponentPrice; + DROP TEMPORARY TABLE tmp.ticketComponent; + DROP TEMPORARY TABLE tmp.sale; +END$$ + +DELIMITER ; + diff --git a/db/changes/10110-postCampaign/00-ticket_recalcComponentsForcePrice.sql b/db/changes/10110-postCampaign/00-ticket_recalcComponentsForcePrice.sql new file mode 100644 index 000000000..90d65fcc1 --- /dev/null +++ b/db/changes/10110-postCampaign/00-ticket_recalcComponentsForcePrice.sql @@ -0,0 +1,77 @@ +USE `vn`; +DROP procedure IF EXISTS `ticket_recalcComponentsForcePrice`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponentsForcePrice`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN ) +proc: BEGIN + +/** + * Este procedimiento trata de "rebionizar" un ticket, + * eliminando los componentes existentes e insertandolos de nuevo + * + * @param vTicketFk Id del ticket + * @return tmp.buyUltimate + */ + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vLanded DATE; + DECLARE vZoneFk INTEGER; + + IF vIsTicketEditable IS NULL THEN + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk + INTO vIsTicketEditable, vZoneFk + FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket + WHERE id = vTicketFk; + END IF; + SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded + FROM ticket + WHERE id = vTicketFk; + + CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); + + CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, + s.itemFk, bu.buyFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + GROUP BY s.itemFk; + + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT id saleFk, vWarehouseFk warehouseFk + FROM sale s + WHERE s.ticketFk = vTicketFk; + + CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios + + IF vLanded IS NULL THEN + + CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); + + UPDATE vn2008.Tickets t + SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) + WHERE Id_Ticket = vTicketFk; + + DROP TEMPORARY TABLE tmp.zoneGetLanded; + + END IF; + + DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE tmp.ticketComponentPrice; + DROP TEMPORARY TABLE tmp.ticketComponent; + DROP TEMPORARY TABLE tmp.sale; +END$$ + +DELIMITER ; + diff --git a/db/changes/10110-postCampaign/00-workerTimeControlAdd.sql b/db/changes/10110-postCampaign/00-workerTimeControlAdd.sql new file mode 100644 index 000000000..c2091ff83 --- /dev/null +++ b/db/changes/10110-postCampaign/00-workerTimeControlAdd.sql @@ -0,0 +1,73 @@ +DROP function IF EXISTS `vn`.`workerTimeControl_add`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` FUNCTION `vn`.`workerTimeControl_add`( vUserFk INT, vWarehouseFk INT, vTimed DATETIME, vIsManual BOOL) RETURNS int(11) + DETERMINISTIC +BEGIN + DECLARE vDirection VARCHAR(6); + DECLARE vLastIn DATETIME; + DECLARE vDayStayMax INT; + DECLARE vHasDirectionOut INT; + DECLARE vLastInsertedId INT; + + SELECT dayStayMax INTO vDayStayMax + FROM workerTimeControlParams; + + SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; + + IF vDirection = 'out' THEN + + SELECT MAX(timed) INTO vLastIn + FROM workerTimeControl + WHERE userFk = vUserFk + AND direction = 'in' + AND timed < vTimed; + + UPDATE workerTimeControl wtc + SET wtc.direction = 'middle' + WHERE userFk = vUserFk + AND direction = 'out' + AND timed BETWEEN vLastIn AND vTimed; + + ELSE IF vDirection = 'in' THEN + + SELECT COUNT(*) INTO vHasDirectionOut + FROM workerTimeControl wtc + WHERE userFk = vUserFk + AND direction = 'out' + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + + UPDATE workerTimeControl wtc + SET wtc.direction = IF (vHasDirectionOut,'middle','out') + WHERE userFk = vUserFk + AND direction = 'in' + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + + END IF; + END IF; + + INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) + VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); + + SET vLastInsertedId = LAST_INSERT_ID(); + + CALL workerTimeControlSOWP(vUserFk, vTimed); + + RETURN vLastInsertedId; +END$$ + +DELIMITER ; + + + +DROP procedure IF EXISTS `vn`.`workerTimeControl_add`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL) +BEGIN + + + SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); +END$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/00-workerTimeControlCalculate.sql b/db/changes/10110-postCampaign/00-workerTimeControlCalculate.sql new file mode 100644 index 000000000..8e8c7471b --- /dev/null +++ b/db/changes/10110-postCampaign/00-workerTimeControlCalculate.sql @@ -0,0 +1,41 @@ +DROP procedure IF EXISTS `vn`.`timeControl_calculate`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`timeControl_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN + SET @vIsOdd := TRUE; + SET @vUser := NULL; + SET @vDated := NULL; + + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; + + CREATE TEMPORARY TABLE tmp.timeControlCalculate + SELECT userFk, + dated, + IF( timeWork >= 18000, @timeWork:=timeWork + 1200, @timeWork:=timeWork) timeWorkSeconds, + SEC_TO_TIME(@timeWork ) timeWorkSexagesimal, + @timeWork / 3600 timeWorkDecimal + FROM (SELECT SUM(timeWork) timeWork, + userFk, + dated + FROM (SELECT IF(@vUser = wtc.userFk, @vUser :=@vUser, @vUser := wtc.userFk ), + IF(@vIsOdd, @vIsOdd := FALSE, @vIsOdd := TRUE ), + IF(direction='in', @vIsOdd := TRUE, @vIsOdd := @vIsOdd ), + IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed:=@vLastTimed), + IF(@vIsOdd, 0, UNIX_TIMESTAMP(timed)-@vLastTimed) timeWork, + IF(direction='in', @vDated := DATE(wtc.timed), @vDated :=@vDated) dated, + wtc.userFk, + wtc.timed timed, + direction + FROM workerTimeControl wtc + JOIN tmp.`user` w ON w.userFk = wtc.userFk + WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo + ORDER BY userFk, timed + ) sub + GROUP BY userFk, dated + ORDER BY userFk, dated + )sub2; + +END$$ + +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/01-Ordenes.sql b/db/changes/10110-postCampaign/01-Ordenes.sql new file mode 100644 index 000000000..b2b2f7d35 --- /dev/null +++ b/db/changes/10110-postCampaign/01-Ordenes.sql @@ -0,0 +1,53 @@ + +CREATE + OR REPLACE ALGORITHM = UNDEFINED + DEFINER = `root`@`%` + SQL SECURITY DEFINER +VIEW `vn2008`.`Ordenes` AS + SELECT + `tr`.`id` AS `Id_ORDEN`, + `tr`.`description` AS `ORDEN`, + `tr`.`requesterFk` AS `requesterFk`, + `tr`.`attenderFk` AS `attenderFk`, + `tr`.`quantity` AS `CANTIDAD`, + `tr`.`itemFk` AS `Id_ARTICLE`, + `tr`.`price` AS `PRECIOMAX`, + `tr`.`isOk` AS `isOk`, + `tr`.`saleFk` AS `Id_Movimiento`, + `tr`.`ticketFk` AS `ticketFk`, + `tr`.`response` AS `COMENTARIO`, + `tr`.`created` AS `odbc_date`, + `tr`.`ordered` AS `datORDEN`, + `tr`.`shipped` AS `datTICKET`, + `tr`.`salesPersonCode` AS `CodVENDEDOR`, + `tr`.`buyerCode` AS `CodCOMPRADOR`, + `tr`.`price__` AS `PREU`, + `tr`.`clientFk` AS `Id_CLIENTE`, + `tr`.`ok__` AS `OK`, + `tr`.`total` AS `TOTAL`, + `tr`.`buyed` AS `datCOMPRA`, + `tr`.`ko__` AS `KO` + FROM + `vn`.`ticketRequest` `tr`; + + +CREATE + OR REPLACE ALGORITHM = UNDEFINED + DEFINER = `root`@`%` + SQL SECURITY DEFINER +VIEW `vn`.`ticketRequest__` AS + SELECT + `t`.`Id_ORDEN` AS `id`, + `t`.`ORDEN` AS `description`, + `t`.`requesterFk` AS `requesterFk`, + `t`.`attenderFk` AS `attenderFk`, + `t`.`CANTIDAD` AS `quantity`, + `t`.`Id_ARTICLE` AS `itemFk`, + `t`.`PRECIOMAX` AS `price`, + `t`.`isOk` AS `isOk`, + `t`.`Id_Movimiento` AS `saleFk`, + `t`.`ticketFk` AS `ticketFk`, + `t`.`COMENTARIO` AS `response`, + `t`.`odbc_date` AS `created` + FROM + `vn2008`.`Ordenes` `t`; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/01-bionicCalcReverse.sql b/db/changes/10110-postCampaign/01-bionicCalcReverse.sql new file mode 100644 index 000000000..e3f6b1387 --- /dev/null +++ b/db/changes/10110-postCampaign/01-bionicCalcReverse.sql @@ -0,0 +1,92 @@ +DROP function IF EXISTS `vn`.`bionicCalcReverse`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` FUNCTION `vn`.`bionicCalcReverse`(vWarehouse INT, + vMargin DECIMAL(10,3), + vRetailedPrice DECIMAL(10,3), + vM3 DECIMAL(10,3), + vAddress INT, + vAgencyMode INT) RETURNS decimal(10,3) + DETERMINISTIC +BEGIN + DECLARE vGeneralInflationCoeficient INT; + DECLARE vVerdnaturaVolumeBox BIGINT; + DECLARE vClientFk INT; + DECLARE vComponentRecovery VARCHAR(50) DEFAULT 'debtCollection'; + DECLARE vComponentMana VARCHAR(50) DEFAULT 'autoMana'; + DECLARE vComponentPort VARCHAR(50) DEFAULT 'delivery'; + DECLARE vComponentMargin VARCHAR(50) DEFAULT 'margin'; + DECLARE vComponentCost VARCHAR(50) DEFAULT 'purchaseValue'; + DECLARE vComponentCostValue DECIMAL(10,2); + DECLARE vItem INT DEFAULT 98; + DECLARE vItemCarryBox INT; + + SELECT generalInflationCoeFicient, verdnaturaVolumeBox, itemCarryBox + INTO vGeneralInflationCoeficient, vVerdnaturaVolumeBox, vItemCarryBox + FROM bionicConfig; + + SELECT clientFk INTO vClientFk FROM address WHERE id = vAddress; + + -- Creamos la tabla tmp.bionicComponent + DROP TEMPORARY TABLE IF EXISTS tmp.bionicComponent; + CREATE TEMPORARY TABLE tmp.bionicComponent( + `warehouseFk` smallint(5) unsigned NOT NULL, + `itemFk` int(11) NOT NULL, + `componentFk` int(10) unsigned NOT NULL, + `value` decimal(10,4) NOT NULL, + UNIQUE KEY `itemWarehouseComponent` (`itemFk`,`warehouseFk`,`componentFk`) USING HASH, + KEY `itemWarehouse` (`itemFk`,`warehouseFk`) USING BTREE + ) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + + -- Margin + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, id, vMargin + FROM component + WHERE code = vComponentMargin; + + -- Recobro + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, c.id, ROUND(LEAST(cr.recobro,0.25), 3) + FROM bi.claims_ratio cr + JOIN component c ON c.code = vComponentRecovery + WHERE cr.Id_Cliente = vClientFk AND cr.recobro > 0.009; + + -- Componente de maná automático, en función del maná acumulado por el comercial. + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, co.id, ROUND(ms.prices_modifier_rate, 3) + FROM client c + JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador + JOIN component co ON co.code = vComponentMana + WHERE ms.prices_modifier_activated AND c.id = vClientFk LIMIT 1; + + -- Reparto + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, co.id, vGeneralInflationCoeficient + * ROUND( + vM3 + * az.price + * az.inflation + / vVerdnaturaVolumeBox, 4 + ) + FROM agencyMode ag + JOIN address a ON a.id = vAddress AND ag.id = vAgencyMode + JOIN agencyProvince ap ON ap.agencyFk = ag.agencyFk + AND ap.warehouseFk = vWarehouse AND ap.provinceFk = a.provinceFk + JOIN agencyModeZone az ON az.agencyModeFk = vAgencyMode + AND az.zone = ap.zone AND az.itemFk = 71 AND az.warehouseFk = vWarehouse + JOIN component co ON co.code = vComponentPort; + + -- Coste + SELECT vRetailedPrice - SUM(`value`) INTO vComponentCostValue + FROM tmp.bionicComponent; + + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, id,vComponentCostValue + FROM component + WHERE code = vComponentCost; + + RETURN vComponentCostValue; +END$$ + +DELIMITER ; + diff --git a/db/changes/10110-postCampaign/01-ticketBusinessCalculate.sql b/db/changes/10110-postCampaign/01-ticketBusinessCalculate.sql new file mode 100644 index 000000000..97249bd8a --- /dev/null +++ b/db/changes/10110-postCampaign/01-ticketBusinessCalculate.sql @@ -0,0 +1,96 @@ + +DROP procedure IF EXISTS `vn`.`timeBusiness_calculate`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN + +/** + * Horas que debe trabajar un empleado según contrato y día. + * @param vDatedFrom workerTimeControl + * @param vDatedTo workerTimeControl + * @table tmp.user(userFk) + * @return tmp.timeBusinessCalculate + */ + DECLARE vHoursFullTime INT DEFAULT 40; + + DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate; + DROP TEMPORARY TABLE IF EXISTS tmp.businessFullTime; + + CALL rangeDateInfo(vDatedFrom, vDatedTo); + + CREATE TEMPORARY TABLE tmp.timeBusinessCalculate + SELECT dated, + businessFk, + userFk, + departmentFk, + hourStart, + hourEnd, + timeWorkSeconds, + SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal, + timeWorkSeconds / 3600 timeWorkDecimal, + timeWorkSeconds timeBusinessSeconds, + SEC_TO_TIME(timeWorkSeconds) timeBusinessSexagesimal, + timeWorkSeconds / 3600 timeBusinessDecimal, + type, + permissionrate, + hoursWeek + FROM(SELECT rd.dated, + b.business_id businessFk, + w.userFk, + bl.department_id departmentFk, + IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,2) ORDER BY j.start ASC SEPARATOR '-')) hourStart , + IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.end,2) ORDER BY j.end ASC SEPARATOR '-')) hourEnd, + IF(cl.hours_week = vHoursFullTime, 0, IFNULL(SUM(TIME_TO_SEC(j.end)) - SUM(TIME_TO_SEC(j.start)),0)) timeWorkSeconds, + cs.type, + cs.permissionRate, + cl.hours_week hoursWeek + FROM tmp.rangeDate rd + LEFT JOIN postgresql.business b ON rd.dated BETWEEN b.date_start AND ifnull(b.date_end, vDatedTo ) + LEFT JOIN postgresql.profile AS pr ON b.client_id = pr.profile_id + LEFT JOIN postgresql.person AS p ON pr.person_id = p.person_id + LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id + JOIN tmp.`user` u ON u.userFK = w.userFK + JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id + LEFT JOIN postgresql.business_labour_payroll AS bp ON bl.business_id = bp.business_id + LEFT JOIN postgresql.professional_category AS pc ON bl.professional_category_id = pc.professional_category_id + LEFT JOIN postgresql.workcenter AS wc ON bl.workcenter_id = wc.workcenter_id + LEFT JOIN postgresql.calendar_labour_type AS cl ON bl.calendar_labour_type_id = cl.calendar_labour_type_id + LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(rd.dated)+1 + LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and ce.date = rd.dated + LEFT JOIN postgresql.calendar_state cs ON cs.calendar_state_id = ce.calendar_state_id + WHERE rd.dated BETWEEN vDatedFrom AND vDatedTo + GROUP BY w.userFk,dated + )sub; + + + UPDATE tmp.timeBusinessCalculate t + SET t.timeWorkSeconds = vHoursFullTime / 5 * 3600, + t.timeWorkSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600), + t.timeWorkDecimal = vHoursFullTime / 5, + t.timeBusinessSeconds = vHoursFullTime / 5 * 3600, + t.timeBusinessSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600), + t.timeBusinessDecimal = vHoursFullTime / 5 + WHERE DAYOFWEEK(t.dated) IN(2,3,4,5,6) AND hoursWeek = vHoursFullTime ; + + UPDATE tmp.timeBusinessCalculate t + SET t.timeWorkSeconds = t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate) , + t.timeWorkSexagesimal = SEC_TO_TIME(t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate)), + t.timeWorkDecimal = t.timeWorkDecimal - (t.timeWorkDecimal * permissionrate) + WHERE permissionrate <> 0; + + UPDATE tmp.timeBusinessCalculate t + JOIN postgresql.calendar_labour cl ON cl.day = t.dated + JOIN postgresql.business_labour bl ON bl.business_id = t.businessFk AND bl.workcenter_id = cl.workcenter_id + SET t.timeWorkSeconds = 0, + t.timeWorkSexagesimal = 0, + t.timeWorkDecimal = 0, + t.permissionrate = 1, + t.type = 'Festivo' + WHERE t.type IS NULL; + +DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; +END$$ + +DELIMITER ; + diff --git a/db/changes/10120-december/00-entryBeforeUpdate.sql b/db/changes/10120-december/00-entryBeforeUpdate.sql new file mode 100644 index 000000000..088ea9328 --- /dev/null +++ b/db/changes/10120-december/00-entryBeforeUpdate.sql @@ -0,0 +1,58 @@ +DROP TRIGGER IF EXISTS `vn`.`entry_beforeUpdate`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` TRIGGER `vn`.`entry_beforeUpdate` + BEFORE UPDATE ON `entry` + FOR EACH ROW +BEGIN + DECLARE vIsVirtual BOOL; + DECLARE vPrintedCount INT; + DECLARE vHasDistinctWarehouses BOOL; + + IF !(NEW.travelFk <=> OLD.travelFk) THEN + SELECT COUNT(*) > 0 INTO vIsVirtual + FROM entryVirtual WHERE entryFk = NEW.id; + + SELECT !(o.warehouseInFk <=> n.warehouseInFk) + OR !(o.warehouseOutFk <=> n.warehouseOutFk) + INTO vHasDistinctWarehouses + FROM travel o, travel n + WHERE o.id = OLD.travelFk + AND n.id = NEW.travelFk; + + IF vIsVirtual AND vHasDistinctWarehouses THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses'; + END IF; + + IF NEW.travelFk IS NULL THEN + SELECT COUNT(*) INTO vPrintedCount + FROM buy + WHERE entryFk = OLD.id + AND printedStickers > 0; + + IF vPrintedCount > 0 THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'An entry that contains lines with printed labels cannot be deleted'; + END IF; + END IF; + END IF; + + IF !(NEW.supplierFk <=> OLD.supplierFk) THEN + SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk); + END IF; + + IF !(NEW.travelFk <=> OLD.travelFk) + OR !(NEW.currencyFk <=> OLD.currencyFk) THEN + SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); + END IF; + + IF !(ABS(NEW.isBooked) <=> ABS(OLD.isBooked)) THEN + INSERT INTO entryLog SET + action = 'update', + description = 'Cambia a Contabilizada', + userFk = myWorker_getId(), + originFk = NEW.id; + END IF; +END$$ +DELIMITER ; diff --git a/db/changes/10120-december/00-expedition_beforeInsert.sql b/db/changes/10120-december/00-expedition_beforeInsert.sql new file mode 100644 index 000000000..819cd7a7f --- /dev/null +++ b/db/changes/10120-december/00-expedition_beforeInsert.sql @@ -0,0 +1,33 @@ +DROP TRIGGER IF EXISTS `vn`.`expedition_beforeInsert`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` TRIGGER `vn`.`expedition_beforeInsert` + BEFORE INSERT ON `expedition` FOR EACH ROW +BEGIN + DECLARE intcounter INT; + DECLARE vShipFk INT; + + IF NEW.isBox > 0 THEN + + UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk; + + SELECT IFNULL(MAX(counter),0) +1 INTO intcounter + FROM expedition e + INNER JOIN ticket t1 ON e.ticketFk = t1.id + LEFT JOIN ticketState ts ON ts.ticket = t1.id + INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + AND t1.warehouseFk = t2.warehouseFk + WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk + AND t1.agencyModeFk = t2.agencyModeFk; + + SET NEW.`counter` = intcounter; + END IF; + + SELECT shipFk INTO vShipFk FROM stowaway WHERE id = NEW.ticketFk; + + IF vShipFk THEN + CALL stowaway_unboarding(vShipFk, NEW.ticketFk); + END IF; +END$$ +DELIMITER ; diff --git a/db/changes/10120-december/00-stowaway_unboarding.sql b/db/changes/10120-december/00-stowaway_unboarding.sql new file mode 100644 index 000000000..271baba6c --- /dev/null +++ b/db/changes/10120-december/00-stowaway_unboarding.sql @@ -0,0 +1,31 @@ + +USE `vn`; +DROP procedure IF EXISTS `vn`.`stowawayUnBoarding`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `stowaway_unboarding`(vShipFk INT, vStowawayFk INT) +BEGIN + DECLARE vWorker VARCHAR(255); + + DELETE FROM stowaway + WHERE shipFk = vShipFk AND id = vStowawayFk; + + DELETE tt FROM ticketTracking tt + JOIN state s ON s.id = tt.stateFk + WHERE code = 'BOARDING' AND ticketFk = vShipFk; + + DELETE FROM sale + WHERE ticketFk = vShipFk + AND itemFk = 98 + AND concept = CONCAT('POLIZÓN! ',vStowawayFk); + + SELECT u.`name` INTO vWorker + FROM account.user u JOIN worker w ON w.userFk = u.id + WHERE w.id = client_getSalesPersonByTicket(vStowawayFk); + + SELECT messageSend(vWorker,CONCAT('El ticket: ', vStowawayFk, ' ha dejado de ser un polizón')) INTO @a; +END$$ + +DELIMITER ; +; diff --git a/db/changes/10120-december/00-tpvTransaction.sql b/db/changes/10120-december/00-tpvTransaction.sql new file mode 100644 index 000000000..10ec8082c --- /dev/null +++ b/db/changes/10120-december/00-tpvTransaction.sql @@ -0,0 +1,120 @@ + +DROP procedure IF EXISTS `hedera`.`tpvTransaction_confirm`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `hedera`.`tpvTransaction_confirm`( + vAmount INT + ,vOrder INT + ,vMerchant INT + ,vCurrency INT + ,vResponse INT + ,vErrorCode VARCHAR(10) +) +BEGIN +/** + * Confirma una transacción previamente iniciada, reescribiendo + * sus datos por los confirmados por el banco (solo si estos difieren). + * Genera el recibo y su correspondiente entrada en caja. + * + * @param vAmount Cantidad confirmada + * @param vOrder Identificador de transacción + * @param vMerchant Identificador de comercio + * @param vCurrency Identificador de moneda + * @param vResponse Identificador de respuesta del banco + * @param vErrorCode Código de error del banco, si lo hubiera + */ + DECLARE vReceipt INT; + DECLARE vStatus VARCHAR(10); + DECLARE vCustomer INT; + DECLARE vBank INT; + DECLARE vCompany INT; + DECLARE vEmployee INT; + DECLARE vIsDuplicated BOOLEAN; + DECLARE vDate DATE; + DECLARE vConcept VARCHAR(25) DEFAULT 'Cobro Web'; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT COUNT(*) > 0 INTO vIsDuplicated + FROM tpvTransaction + WHERE id = vOrder AND response IS NOT NULL + FOR UPDATE; + + IF vIsDuplicated + THEN + CALL util.throw ('TRANSACTION_DUPLICATED'); + END IF; + + IF vResponse BETWEEN 0 AND 99 + THEN + SELECT + t.clientFk + ,m.bankFk + ,m.companyFk + ,c.employeeFk + ,DATE(t.created) + INTO + vCustomer + ,vBank + ,vCompany + ,vEmployee + ,vDate + FROM tpvMerchant m + JOIN tpvConfig c + LEFT JOIN tpvTransaction t ON t.id = vOrder + WHERE m.id = vMerchant; + + INSERT INTO vn.receipt + SET + amountPaid = vAmount / 100 + ,payed = vDate + ,workerFk = vEmployee + ,bankFk = vBank + ,clientFk = vCustomer + ,companyFk = vCompany + ,invoiceFk = vConcept + ,isConciliate = TRUE; + + SET vReceipt = LAST_INSERT_ID(); + SET vStatus = 'ok'; + + -- Código redundante + + DO vn.till_new + ( + vCustomer + ,vBank + ,vAmount / 100 + ,vConcept + ,vDate + ,'A' + ,TRUE + ,vCustomer + ,vCompany + ,vEmployee + ); + ELSE + SET vReceipt = NULL; + SET vStatus = 'ko'; + END IF; + + UPDATE tpvTransaction + SET + merchantFk = vMerchant + ,receiptFk = vReceipt + ,amount = vAmount + ,response = vResponse + ,errorCode = vErrorCode + ,status = vStatus + WHERE id = vOrder; + COMMIT; +END$$ + +DELIMITER ; + diff --git a/db/changes/10120-december/00-tpvTransaction_undo.sql b/db/changes/10120-december/00-tpvTransaction_undo.sql new file mode 100644 index 000000000..ee7bcc5d1 --- /dev/null +++ b/db/changes/10120-december/00-tpvTransaction_undo.sql @@ -0,0 +1,86 @@ + +DROP procedure IF EXISTS `hedera`.`tpvTransaction_undo`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `hedera`.`tpvTransaction_undo`(vSelf INT) +BEGIN + DECLARE vCustomer INT; + DECLARE vAmount DOUBLE; + DECLARE vReceipt INT; + DECLARE vDate DATE; + DECLARE vBank INT; + DECLARE vAccount VARCHAR(12); + DECLARE vSubaccount VARCHAR(12); + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT + t.clientFk + ,t.amount / 100 + ,t.receiptFk + ,DATE(t.created) + ,m.bankFk + INTO + vCustomer + ,vAmount + ,vReceipt + ,vDate + ,vBank + FROM tpvTransaction t + JOIN tpvMerchant m ON m.id = t.merchantFk + JOIN tpvConfig c + WHERE t.id = vSelf + FOR UPDATE; + + -- Elimina el recibo + + DELETE FROM vn.receipt + WHERE id = vReceipt LIMIT 1; + + -- Elimina la entrada de cajas + + DELETE FROM vn.till + WHERE bankFk = vBank + AND DATE(dated) = vDate + AND `in` = vAmount + LIMIT 1; + + -- Elimina los asientos contables + + SELECT accountingAccount INTO vSubaccount + FROM vn.`client` WHERE id = vCustomer; + + SELECT account INTO vAccount + FROM vn.bank WHERE id = vBank; + + DELETE FROM vn.XDiario + WHERE SUBCTA = vSubaccount + AND CONTRA = vAccount + AND DATE(FECHA) = vDate + AND EUROHABER = vAmount + LIMIT 1; + + DELETE FROM vn.XDiario + WHERE CONTRA = vSubaccount + AND SUBCTA = vAccount + AND DATE(FECHA) = vDate + AND EURODEBE = vAmount + LIMIT 1; + + -- Actualiza la transaccion + + UPDATE tpvTransaction + SET response = NULL, status = 'started' + WHERE id = vSelf; + + COMMIT; +END$$ + +DELIMITER ; + diff --git a/db/config.ini b/db/config.ini new file mode 100644 index 000000000..7800cadfd --- /dev/null +++ b/db/config.ini @@ -0,0 +1,5 @@ +[client] +host = localhost +port = 3306 +user = root +password = root diff --git a/db/docker/docker-boot.sh b/db/docker/docker-boot.sh new file mode 100755 index 000000000..6a0d17c69 --- /dev/null +++ b/db/docker/docker-boot.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +export MYSQL_PWD=root + +mysql_import() { + FILE=$1 + echo "[INFO] -> Importing $FILE" + mysql -u root --default-character-set=utf8 --comments -f < "$FILE" +} + +mysql_import dump/structure.sql +mysql_import dump/mysqlPlugins.sql +mysql_import dump/dumpedFixtures.sql +import/import-changes.sh +mysql_import dump/fixtures.sql + +echo "[INFO] -> Import finished" diff --git a/db/docker/docker-init.sh b/db/docker/docker-init.sh new file mode 100755 index 000000000..19d13a15d --- /dev/null +++ b/db/docker/docker-init.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +. /usr/local/bin/docker-entrypoint.sh + +mysql_check_config "$@" +docker_setup_env "$@" +docker_create_db_directories + +docker_verify_minimum_env +docker_init_database_dir "$@" +docker_temp_server_start "$@" +docker_setup_db + +docker_process_init_files /docker-entrypoint-initdb.d/* + +mysql_expire_root_user +docker_temp_server_stop diff --git a/db/docker/docker-start.sh b/db/docker/docker-start.sh new file mode 100755 index 000000000..1db1933d1 --- /dev/null +++ b/db/docker/docker-start.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +# XXX: Workaround to avoid OverlayFS bug on MacOs +# https://docs.docker.com/storage/storagedriver/overlayfs-driver/#limitations-on-overlayfs-compatibility + +if [ "$RUN_CHOWN" = "true" ]; then + chown -R mysql:mysql /mysql-data +fi + +exec "$@" diff --git a/db/docker/docker.cnf b/db/docker/docker.cnf new file mode 100644 index 000000000..1a0241487 --- /dev/null +++ b/db/docker/docker.cnf @@ -0,0 +1,10 @@ +[mysqld] +innodb_log_file_size = 4M +innodb_autoextend_increment = 4 +innodb_page_size = 8K +innodb_default_row_format = COMPACT +log_bin_trust_function_creators = ON +datadir = /mysql-data +sql_mode = NO_ENGINE_SUBSTITUTION +innodb_temp_data_file_path = /tmp/ibtmp1:12M:autoextend +skip-log-bin diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql new file mode 100644 index 000000000..203c76f2f --- /dev/null +++ b/db/dump/dumpedFixtures.sql @@ -0,0 +1,555 @@ + +USE `util`; +-- MySQL dump 10.13 Distrib 5.7.28, for Linux (x86_64) +-- +-- Host: db.verdnatura.es Database: util +-- ------------------------------------------------------ +-- Server version 5.6.25-4-log + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Dumping data for table `config` +-- + +LOCK TABLES `config` WRITE; +/*!40000 ALTER TABLE `config` DISABLE KEYS */; +INSERT INTO `config` VALUES (1,'10080',0,'production',NULL); +/*!40000 ALTER TABLE `config` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2019-11-26 14:02:56 +USE `account`; +-- MySQL dump 10.13 Distrib 5.7.28, for Linux (x86_64) +-- +-- Host: db.verdnatura.es Database: account +-- ------------------------------------------------------ +-- Server version 5.6.25-4-log + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Dumping data for table `role` +-- + +LOCK TABLES `role` WRITE; +/*!40000 ALTER TABLE `role` DISABLE KEYS */; +INSERT INTO `role` VALUES (0,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2018-04-23 14:33:59'),(1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31'),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35'),(13,'teamBoss','Jefe de departamento',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10'),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27'),(20,'manager','Departamento de gerencia',1,'2017-06-01 14:57:02','2017-06-01 14:57:51'),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52'),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12'),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36'),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27'),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20'),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34'),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53'),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42'),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08'),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53'),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09'),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41'),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12'),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26'),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59'),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16'),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12'),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23'),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18'),(48,'coolerBoss','Jefe del departamento de cámara',1,'2018-02-23 13:12:01','2018-02-23 13:12:01'),(49,'production','Empleado de producción',0,'2018-02-26 15:28:23','2019-01-21 12:57:21'),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12'),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39'),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57'),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57'),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17'),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31'),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02'),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19'),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45'),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10'),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01'),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07'),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05'),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08'),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26'),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56'); +/*!40000 ALTER TABLE `role` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `roleInherit` +-- + +LOCK TABLES `roleInherit` WRITE; +/*!40000 ALTER TABLE `roleInherit` DISABLE KEYS */; +INSERT INTO `roleInherit` VALUES (9,0),(66,0),(5,1),(13,1),(18,1),(31,1),(32,1),(34,1),(35,1),(37,1),(40,1),(42,1),(44,1),(47,1),(51,1),(53,1),(54,1),(56,1),(58,1),(1,2),(1,3),(30,5),(39,5),(60,5),(11,6),(1,11),(2,11),(3,11),(16,13),(20,13),(21,13),(22,13),(34,13),(41,13),(43,13),(45,13),(48,13),(50,13),(52,13),(55,13),(57,13),(59,13),(61,13),(16,15),(20,16),(21,18),(52,19),(65,19),(17,20),(30,20),(5,21),(19,21),(22,21),(39,21),(30,22),(5,33),(34,33),(15,35),(41,35),(52,35),(65,35),(49,36),(61,36),(17,37),(38,37),(17,39),(41,40),(43,42),(36,44),(45,44),(36,47),(48,47),(50,49),(60,50),(65,50),(52,51),(21,53),(30,53),(55,54),(57,56),(15,57),(39,57),(50,57),(60,57),(49,58),(59,58),(50,59),(17,64),(30,64),(38,64),(20,65); +/*!40000 ALTER TABLE `roleInherit` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `roleRole` +-- + +LOCK TABLES `roleRole` WRITE; +/*!40000 ALTER TABLE `roleRole` DISABLE KEYS */; +INSERT INTO `roleRole` VALUES (0,0),(0,1),(0,2),(0,3),(0,5),(0,6),(0,9),(0,11),(0,13),(0,15),(0,16),(0,17),(0,18),(0,19),(0,20),(0,21),(0,22),(0,30),(0,31),(0,32),(0,33),(0,34),(0,35),(0,36),(0,37),(0,38),(0,39),(0,40),(0,41),(0,42),(0,43),(0,44),(0,45),(0,47),(0,48),(0,49),(0,50),(0,51),(0,52),(0,53),(0,54),(0,55),(0,56),(0,57),(0,58),(0,59),(0,60),(0,61),(0,62),(0,64),(0,65),(0,66),(1,1),(1,2),(1,3),(1,6),(1,11),(2,2),(2,6),(2,11),(3,3),(3,6),(3,11),(5,1),(5,2),(5,3),(5,5),(5,6),(5,11),(5,13),(5,18),(5,21),(5,33),(5,53),(6,6),(9,0),(9,1),(9,2),(9,3),(9,5),(9,6),(9,9),(9,11),(9,13),(9,15),(9,16),(9,17),(9,18),(9,19),(9,20),(9,21),(9,22),(9,30),(9,31),(9,32),(9,33),(9,34),(9,35),(9,36),(9,37),(9,38),(9,39),(9,40),(9,41),(9,42),(9,43),(9,44),(9,45),(9,47),(9,48),(9,49),(9,50),(9,51),(9,52),(9,53),(9,54),(9,55),(9,56),(9,57),(9,58),(9,59),(9,60),(9,61),(9,62),(9,64),(9,65),(9,66),(11,6),(11,11),(13,1),(13,2),(13,3),(13,6),(13,11),(13,13),(15,1),(15,2),(15,3),(15,6),(15,11),(15,13),(15,15),(15,35),(15,56),(15,57),(16,1),(16,2),(16,3),(16,6),(16,11),(16,13),(16,15),(16,16),(16,35),(16,56),(16,57),(17,1),(17,2),(17,3),(17,5),(17,6),(17,11),(17,13),(17,15),(17,16),(17,17),(17,18),(17,19),(17,20),(17,21),(17,33),(17,35),(17,36),(17,37),(17,39),(17,44),(17,47),(17,49),(17,50),(17,53),(17,56),(17,57),(17,58),(17,59),(17,64),(17,65),(18,1),(18,2),(18,3),(18,6),(18,11),(18,18),(19,1),(19,2),(19,3),(19,6),(19,11),(19,13),(19,18),(19,19),(19,21),(19,53),(20,1),(20,2),(20,3),(20,6),(20,11),(20,13),(20,15),(20,16),(20,18),(20,19),(20,20),(20,21),(20,35),(20,36),(20,44),(20,47),(20,49),(20,50),(20,53),(20,56),(20,57),(20,58),(20,59),(20,65),(21,1),(21,2),(21,3),(21,6),(21,11),(21,13),(21,18),(21,21),(21,53),(22,1),(22,2),(22,3),(22,6),(22,11),(22,13),(22,18),(22,21),(22,22),(22,53),(30,1),(30,2),(30,3),(30,5),(30,6),(30,11),(30,13),(30,15),(30,16),(30,18),(30,19),(30,20),(30,21),(30,22),(30,30),(30,33),(30,35),(30,36),(30,44),(30,47),(30,49),(30,50),(30,53),(30,56),(30,57),(30,58),(30,59),(30,64),(30,65),(31,1),(31,2),(31,3),(31,6),(31,11),(31,31),(32,1),(32,2),(32,3),(32,6),(32,11),(32,32),(33,33),(34,1),(34,2),(34,3),(34,6),(34,11),(34,13),(34,33),(34,34),(35,1),(35,2),(35,3),(35,6),(35,11),(35,35),(36,1),(36,2),(36,3),(36,6),(36,11),(36,36),(36,44),(36,47),(37,1),(37,2),(37,3),(37,6),(37,11),(37,37),(38,1),(38,2),(38,3),(38,6),(38,11),(38,37),(38,38),(38,64),(39,1),(39,2),(39,3),(39,5),(39,6),(39,11),(39,13),(39,18),(39,21),(39,33),(39,39),(39,53),(39,56),(39,57),(40,1),(40,2),(40,3),(40,6),(40,11),(40,40),(41,1),(41,2),(41,3),(41,6),(41,11),(41,13),(41,35),(41,40),(41,41),(42,1),(42,2),(42,3),(42,6),(42,11),(42,42),(43,1),(43,2),(43,3),(43,6),(43,11),(43,13),(43,42),(43,43),(44,1),(44,2),(44,3),(44,6),(44,11),(44,44),(45,1),(45,2),(45,3),(45,6),(45,11),(45,13),(45,44),(45,45),(47,1),(47,2),(47,3),(47,6),(47,11),(47,47),(48,1),(48,2),(48,3),(48,6),(48,11),(48,13),(48,47),(48,48),(49,1),(49,2),(49,3),(49,6),(49,11),(49,36),(49,44),(49,47),(49,49),(49,58),(50,1),(50,2),(50,3),(50,6),(50,11),(50,13),(50,36),(50,44),(50,47),(50,49),(50,50),(50,56),(50,57),(50,58),(50,59),(51,1),(51,2),(51,3),(51,6),(51,11),(51,51),(52,1),(52,2),(52,3),(52,6),(52,11),(52,13),(52,18),(52,19),(52,21),(52,35),(52,51),(52,52),(52,53),(53,1),(53,2),(53,3),(53,6),(53,11),(53,53),(54,1),(54,2),(54,3),(54,6),(54,11),(54,54),(55,1),(55,2),(55,3),(55,6),(55,11),(55,13),(55,54),(55,55),(56,1),(56,2),(56,3),(56,6),(56,11),(56,56),(57,1),(57,2),(57,3),(57,6),(57,11),(57,13),(57,56),(57,57),(58,1),(58,2),(58,3),(58,6),(58,11),(58,58),(59,1),(59,2),(59,3),(59,6),(59,11),(59,13),(59,58),(59,59),(60,1),(60,2),(60,3),(60,5),(60,6),(60,11),(60,13),(60,18),(60,21),(60,33),(60,36),(60,44),(60,47),(60,49),(60,50),(60,53),(60,56),(60,57),(60,58),(60,59),(60,60),(61,1),(61,2),(61,3),(61,6),(61,11),(61,13),(61,36),(61,44),(61,47),(61,61),(62,62),(64,64),(65,1),(65,2),(65,3),(65,6),(65,11),(65,13),(65,18),(65,19),(65,21),(65,35),(65,36),(65,44),(65,47),(65,49),(65,50),(65,53),(65,56),(65,57),(65,58),(65,59),(65,65),(66,0),(66,1),(66,2),(66,3),(66,5),(66,6),(66,9),(66,11),(66,13),(66,15),(66,16),(66,17),(66,18),(66,19),(66,20),(66,21),(66,22),(66,30),(66,31),(66,32),(66,33),(66,34),(66,35),(66,36),(66,37),(66,38),(66,39),(66,40),(66,41),(66,42),(66,43),(66,44),(66,45),(66,47),(66,48),(66,49),(66,50),(66,51),(66,52),(66,53),(66,54),(66,55),(66,56),(66,57),(66,58),(66,59),(66,60),(66,61),(66,62),(66,64),(66,65),(66,66); +/*!40000 ALTER TABLE `roleRole` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2019-11-26 14:02:57 +USE `salix`; +-- MySQL dump 10.13 Distrib 5.7.28, for Linux (x86_64) +-- +-- Host: db.verdnatura.es Database: salix +-- ------------------------------------------------------ +-- Server version 5.6.25-4-log + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Dumping data for table `ACL` +-- + +LOCK TABLES `ACL` WRITE; +/*!40000 ALTER TABLE `ACL` DISABLE KEYS */; +INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','employee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','employee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','employee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','employee'),(30,'GreugeType','*','READ','ALLOW','ROLE','employee'),(31,'Mandate','*','READ','ALLOW','ROLE','employee'),(32,'MandateType','*','READ','ALLOW','ROLE','employee'),(33,'Company','*','READ','ALLOW','ROLE','employee'),(34,'Greuge','*','READ','ALLOW','ROLE','employee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','employee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(71,'SaleChecked','*','READ','ALLOW','ROLE','employee'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','removes','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','*','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','salesAssistant'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','salesAssistant'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','salesAssistant'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','employee'),(111,'ClientLog','*','READ','ALLOW','ROLE','employee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','employee'),(114,'Receipt','*','READ','ALLOW','ROLE','employee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','employee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','employee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','WRITE','ALLOW','ROLE','deliveryBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'WorkerCalendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'WorkerCalendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','employee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(193,'Zone','editPrices','WRITE','ALLOW','ROLE','deliveryBoss'),(194,'Postcode','*','WRITE','ALLOW','ROLE','employee'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','employee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'); +/*!40000 ALTER TABLE `ACL` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `fieldAcl` +-- + +LOCK TABLES `fieldAcl` WRITE; +/*!40000 ALTER TABLE `fieldAcl` DISABLE KEYS */; +INSERT INTO `fieldAcl` VALUES (1,'Client','name','update','employee'),(2,'Client','contact','update','employee'),(3,'Client','email','update','employee'),(4,'Client','phone','update','employee'),(5,'Client','mobile','update','employee'),(6,'Client','contactChannelFk','update','employee'),(7,'Client','socialName','update','salesPerson'),(8,'Client','fi','update','salesPerson'),(9,'Client','street','update','salesPerson'),(10,'Client','postcode','update','salesPerson'),(11,'Client','city','update','salesPerson'),(12,'Client','countryFk','update','salesPerson'),(13,'Client','provinceFk','update','salesPerson'),(14,'Client','isActive','update','salesPerson'),(15,'Client','salesPersonFk','update','salesAssistant'),(16,'Client','hasToInvoice','update','salesPerson'),(17,'Client','isToBeMailed','update','salesPerson'),(18,'Client','isEqualizated','update','salesPerson'),(19,'Client','isFreezed','update','salesPerson'),(20,'Client','isVies','update','salesPerson'),(21,'Client','hasToInvoiceByAddress','update','salesPerson'),(22,'Client','isTaxDataChecked','update','salesAssistant'),(23,'Client','payMethodFk','update','salesAssistant'),(24,'Client','dueDay','update','salesAssistant'),(25,'Client','iban','update','salesAssistant'),(26,'Client','bankEntityFk','update','salesAssistant'),(27,'Client','hasLcr','update','salesAssistant'),(28,'Client','hasCoreVnl','update','salesAssistant'),(29,'Client','hasSepaVnl','update','salesAssistant'),(30,'Client','credit','update','teamBoss'),(31,'BankEntity','*','insert','salesAssistant'),(32,'Address','isDefaultAddress','*','employee'),(33,'Address','nickname','*','employee'),(34,'Address','postalCode','*','employee'),(35,'Address','provinceFk','*','employee'),(36,'Address','agencyModeFk','*','employee'),(37,'Address','phone','*','employee'),(38,'Address','mobile','*','employee'),(39,'Address','street','*','employee'),(40,'Address','city','*','employee'),(41,'Address','isActive','*','employee'),(42,'Address','isEqualizated','*','salesAssistant'),(43,'Address','clientFk','insert','employee'),(44,'ClientObservation','*','insert','employee'),(45,'Recovery','*','insert','administrative'),(46,'Recovery','finished','update','administrative'),(47,'CreditClassification','finished','update','creditInsurance'),(48,'Account','*','update','employee'),(49,'Greuge','*','insert','salesAssistant'),(50,'ClientSample','*','insert','employee'),(51,'Item','*','*','buyer'),(52,'Item','*','*','marketingBoss'),(53,'ItemBotanical','*','*','buyer'),(54,'ClaimEnd','*','*','salesAssistant'),(55,'Receipt','*','*','administrative'),(56,'ClaimBeginning','*','*','salesAssistant'),(57,'TicketRequest','*','*','salesPerson'),(58,'ClaimBeginning','*','*','salesAssistant'),(59,'TicketRequest','*','*','salesPerson'),(60,'ClaimBeginning','*','*','salesAssistant'),(61,'TicketRequest','*','*','salesPerson'),(62,'ClaimBeginning','*','*','salesAssistant'),(63,'TicketRequest','*','*','salesPerson'),(64,'ClaimBeginning','*','*','salesAssistant'); +/*!40000 ALTER TABLE `fieldAcl` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2019-11-26 14:02:57 +USE `vn`; +-- MySQL dump 10.13 Distrib 5.7.28, for Linux (x86_64) +-- +-- Host: db.verdnatura.es Database: vn +-- ------------------------------------------------------ +-- Server version 5.6.25-4-log + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Dumping data for table `alertLevel` +-- + +LOCK TABLES `alertLevel` WRITE; +/*!40000 ALTER TABLE `alertLevel` DISABLE KEYS */; +INSERT INTO `alertLevel` VALUES ('DELIVERED',3),('FREE',0),('ON_PREPARATION',1),('PACKED',2); +/*!40000 ALTER TABLE `alertLevel` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `bookingPlanner` +-- + +LOCK TABLES `bookingPlanner` WRITE; +/*!40000 ALTER TABLE `bookingPlanner` DISABLE KEYS */; +INSERT INTO `bookingPlanner` VALUES (5,'2017-06-30 22:00:00','4770000002','WORLD',1,4,1),(6,'2017-06-30 22:00:00','4770000010','NATIONAL',2,1,1),(8,'2017-06-30 22:00:00','4770000021','NATIONAL',3,2,1),(9,'2017-06-30 22:00:00','4770000101','EQU',3,1,1),(11,'2017-06-30 22:00:00','4770000110','EQU',2,1,1),(12,'2017-06-30 22:00:00','4770000215','EQU',4,2,1),(13,'2017-06-30 22:00:00','4770000521','EQU',5,2,1),(15,'2017-06-30 22:00:00','4771000000','CEE',2,1,1),(16,'2017-06-30 22:00:00','4771000001','CEE',5,3,1),(19,'2017-07-05 11:54:58','4770000020','NATIONAL',1,4,1),(20,'2017-07-05 12:09:24','4771000000','CEE',3,2,1),(21,'2017-07-05 12:09:24','4771000000','CEE',1,4,1),(22,'2017-07-05 12:12:14','4770000002','WORLD',2,1,1),(23,'2017-07-05 12:12:14','4770000002','WORLD',3,2,1),(24,'2017-07-06 08:07:21','4770000002','WORLD',1,4,5),(25,'2017-07-06 08:07:21','HolandaRED','NATIONAL',2,1,5),(27,'2017-07-06 08:07:21','HolandaGEN','NATIONAL',3,2,5),(32,'2017-07-06 08:07:21','4771000000','CEE',2,1,5),(33,'2017-07-06 08:07:21','4771000001','CEE',5,3,5),(34,'2017-07-06 08:07:21','4770000020','NATIONAL',1,4,5),(35,'2017-07-06 08:07:21','4771000000','CEE',3,2,5),(36,'2017-07-06 08:07:21','4771000000','CEE',1,4,5),(37,'2017-07-06 08:07:21','4770000002','WORLD',2,1,5),(38,'2017-07-06 08:07:21','4770000002','WORLD',3,2,5),(70,'2017-07-06 08:08:48','4770000002','WORLD',1,4,30),(71,'2017-07-06 08:08:48','IGIC reduc','NATIONAL',2,1,30),(72,'2017-07-06 08:08:48','4770000020','NATIONAL',1,4,30),(73,'2017-07-06 08:08:48','IGIC gener','NATIONAL',3,2,30),(78,'2017-07-06 08:08:48','4770000020','NATIONAL',1,4,30),(79,'2017-07-06 08:08:48','4770000002','WORLD',2,1,30),(80,'2017-07-06 08:08:48','4770000002','WORLD',3,2,30),(81,'2017-07-05 22:00:00','IGIC cero','NATIONAL',1,5,30),(82,'2019-01-01 11:51:56','4770000504','EQU',10,5,1),(83,'2019-09-11 10:54:03','4770000405','EQU',11,5,1),(84,'2019-09-11 10:58:17','4770000004','NATIONAL',9,5,1),(85,'2019-09-18 22:00:00','4771000000','CEE',6,5,1); +/*!40000 ALTER TABLE `bookingPlanner` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `cplusInvoiceType477` +-- + +LOCK TABLES `cplusInvoiceType477` WRITE; +/*!40000 ALTER TABLE `cplusInvoiceType477` DISABLE KEYS */; +INSERT INTO `cplusInvoiceType477` VALUES (1,'F1 - Factura'),(2,'F2 - Factura simplificada (ticket)'),(3,'F3 - Factura emitida en sustitución de facturas simplificadas facturadas y declaradas'),(4,'F4 - Asiento resumen de facturas'),(5,'R1 - Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)'),(6,'R2 - Factura rectificativa (Art. 80.3)'),(7,'R3 - Factura rectificativa (Art. 80.4)'),(8,'R4 - Factura rectificativa (Resto)'),(9,'R5 - Factura rectificativa en facturas simplificadas'); +/*!40000 ALTER TABLE `cplusInvoiceType477` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `cplusSubjectOp` +-- + +LOCK TABLES `cplusSubjectOp` WRITE; +/*!40000 ALTER TABLE `cplusSubjectOp` DISABLE KEYS */; +INSERT INTO `cplusSubjectOp` VALUES (1,'Campo vacio'),(2,'S1 – Sujeta – No exenta'),(3,'S2 – Sujeta – No exenta – Inv. Suj. Pasivo'); +/*!40000 ALTER TABLE `cplusSubjectOp` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `cplusTaxBreak` +-- + +LOCK TABLES `cplusTaxBreak` WRITE; +/*!40000 ALTER TABLE `cplusTaxBreak` DISABLE KEYS */; +INSERT INTO `cplusTaxBreak` VALUES (1,'Campo vacio'),(2,'E1 - Exenta por el artículo 20'),(3,'E2 - Exenta por el artículo 21'),(4,'E3 - Exenta por el artículo 22'),(5,'E4 - Exenta por el artículo 24'),(6,'E5 - Exenta por el artículo 25'),(7,'E6 - Exenta por otros'); +/*!40000 ALTER TABLE `cplusTaxBreak` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `pgc` +-- + +LOCK TABLES `pgc` WRITE; +/*!40000 ALTER TABLE `pgc` DISABLE KEYS */; +INSERT INTO `pgc` VALUES ('4722000000',0.00,'Importación Exento ',1,0,0,1),('4722000010',10.00,'Importación Reducido ',1,0,0,1),('4722000021',21.00,'Importación General ',1,0,0,1),('4770000001',8.00,'Reducido',1,1,1,1),('4770000002',0.00,'Extra-Community supply',3,1,0,2),('4770000004',4.00,'Super reducido',1,1,1,1),('4770000010',10.00,'Reducido',1,1,1,1),('4770000020',0.00,'Exento',7,1,1,1),('4770000021',21.00,'General',1,1,1,1),('4770000101',10.00,'Reducido ',1,1,1,1),('4770000108',8.00,'Reducido',1,1,1,1),('4770000110',1.40,'Rec. Eq. Reducido',1,0,0,1),('4770000215',21.00,'General',1,1,1,1),('4770000405',0.50,'Rec. Eq. Super Reducido',1,0,0,1),('4770000504',4.00,'Super reducido',1,1,1,1),('4770000521',5.20,'Rec. Eq. General',1,0,0,1),('4770000701',1.00,'Rec. Eq. Reducido',1,0,0,1),('4771000000',0.00,'Intra-Community supply',6,1,1,1),('4771000001',0.00,'Intra-Community services',7,1,1,1),('HolandaGEN',21.00,'General',1,0,0,1),('HolandaRED',9.00,'Reducido',1,0,0,1),('IGIC cero',0.00,'Cero',1,0,0,1),('IGIC gener',6.50,'General',1,0,0,1),('IGIC reduc',3.00,'Reducido',1,0,0,1); +/*!40000 ALTER TABLE `pgc` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `tag` +-- + +LOCK TABLES `tag` WRITE; +/*!40000 ALTER TABLE `tag` DISABLE KEYS */; +INSERT INTO `tag` VALUES (1,'color','Color',0,0,'ink',NULL,NULL),(2,'','Forma',1,0,NULL,NULL,NULL),(3,'','Material',1,0,NULL,NULL,NULL),(4,'','Longitud',1,1,NULL,'mm',NULL),(5,'','Diámetro',1,1,NULL,'mm',NULL),(6,'','Perímetro',1,1,NULL,'mm',NULL),(7,'','Ancho de la base',1,1,NULL,'mm',NULL),(8,'','Altura',1,1,NULL,'mm',NULL),(9,'','Volumen',1,1,NULL,'ml',NULL),(10,'','Densidad',1,1,NULL,NULL,NULL),(11,'','Calidad',1,0,NULL,NULL,NULL),(12,'','Textura',1,0,NULL,NULL,NULL),(13,'','Material del mango',1,0,NULL,NULL,NULL),(14,'','Compra mínima',1,0,NULL,NULL,NULL),(15,'','Nº pétalos',1,1,NULL,NULL,NULL),(16,'','Ancho',1,1,NULL,'mm',NULL),(18,'','Profundidad',1,1,NULL,'mm',NULL),(19,'','Largo',1,1,NULL,'mm',NULL),(20,'','Ancho superior',1,1,NULL,'mm',NULL),(21,'','Ancho inferior',1,1,NULL,'mm',NULL),(22,'','Gramaje',1,1,NULL,'g',NULL),(23,'stems','Tallos',1,1,NULL,NULL,NULL),(24,'','Estado',1,0,NULL,NULL,NULL),(25,'','Color principal',0,0,'ink',NULL,NULL),(26,'','Color secundario',0,0,'ink',NULL,NULL),(27,'','Longitud(cm)',1,1,NULL,'cm',NULL),(28,'','Diámetro base',1,1,'','mm',NULL),(29,'','Colección',1,0,NULL,NULL,NULL),(30,'','Uds / caja',1,1,NULL,NULL,NULL),(31,'','Contenido',1,0,NULL,NULL,NULL),(32,'','Peso',1,1,NULL,'g',NULL),(33,'','Grosor',1,1,NULL,'mm',NULL),(34,'','Marca',1,0,NULL,NULL,NULL),(35,'origin','Origen',0,0,'origin',NULL,NULL),(36,'','Proveedor',1,0,NULL,NULL,NULL),(37,'producer','Productor',0,0,'producer',NULL,NULL),(38,'','Duración',1,1,NULL,'s',NULL),(39,'','Flor',1,0,NULL,NULL,NULL),(40,'','Soporte',1,0,NULL,NULL,NULL),(41,'','Tamaño flor',1,0,NULL,NULL,NULL),(42,'','Apertura',1,0,NULL,NULL,NULL),(43,'','Tallo',1,0,NULL,NULL,NULL),(44,'','Nº hojas',1,1,NULL,NULL,NULL),(45,'','Dimensiones',1,0,NULL,NULL,NULL),(46,'','Diámetro boca',1,1,NULL,'mm',NULL),(47,'','Nº flores',1,1,NULL,NULL,NULL),(48,'','Uds / paquete',1,1,NULL,NULL,NULL),(49,'','Maceta',1,1,NULL,'cm',NULL),(50,'','Textura flor',1,0,NULL,NULL,NULL),(51,'','Textura hoja',1,0,NULL,NULL,NULL),(52,'','Tipo de IVA',1,0,NULL,NULL,NULL),(53,'','Tronco',1,0,NULL,NULL,NULL),(54,'','Hoja',1,0,NULL,NULL,NULL),(55,'','Formato',1,0,NULL,NULL,NULL),(56,'','Genero',1,0,NULL,NULL,NULL),(57,'','Especie',1,0,NULL,NULL,NULL),(58,'','Variedad',1,0,NULL,NULL,NULL),(59,'','Medida grande',1,0,NULL,NULL,NULL),(60,'','Medida mediano',1,0,NULL,NULL,NULL),(61,'','Medida pequeño',1,0,NULL,NULL,NULL),(62,'','Medida pequeño',1,0,NULL,NULL,NULL),(63,'','Recipiente interior',1,0,NULL,NULL,NULL),(64,'','Material secundario',1,0,NULL,NULL,NULL),(65,'','Colores',1,0,NULL,NULL,NULL),(66,'','Referencia',1,0,NULL,NULL,NULL),(67,'','Categoria',1,0,NULL,NULL,NULL),(68,'','Amb',1,0,NULL,NULL,NULL),(69,'','Anchura',1,1,NULL,'cm',NULL),(70,'','Hueco interior',1,0,NULL,NULL,NULL),(71,'','Tamaño',1,0,NULL,NULL,NULL),(72,'','Color botón',1,0,NULL,NULL,NULL),(73,'','Tamaño minimo del botón',1,0,NULL,NULL,NULL),(74,'','Obtentor',1,0,NULL,NULL,NULL),(75,'','Longitud del brote',1,0,NULL,NULL,NULL),(76,'','Tallos / u.v.',1,0,NULL,NULL,NULL),(77,'','Madera de',1,0,NULL,NULL,NULL),(78,'','Unidad de venta',1,0,NULL,NULL,NULL),(79,'','Temporal',1,0,NULL,NULL,NULL),(80,'','Gramaje/tallo',1,1,NULL,'g',NULL),(81,'','Peso/paquete',1,1,NULL,'g',NULL),(82,'','Flexibilidad del tallo',1,0,NULL,NULL,NULL),(83,'','Nº planchas',1,1,NULL,NULL,NULL),(84,'','Nº páginas',1,1,NULL,NULL,NULL),(85,'','Editorial',1,0,NULL,NULL,NULL),(86,'','Idioma',1,0,NULL,NULL,NULL),(87,'','Fecha publicación',1,0,NULL,NULL,NULL),(88,'','Cubierta',1,0,NULL,NULL,NULL),(89,'','Encuadernación',1,0,NULL,NULL,NULL),(90,'','Autor',1,0,NULL,NULL,NULL),(91,'','Envoltorio',1,0,NULL,NULL,NULL),(92,'','Nombre temporal',1,0,NULL,NULL,NULL),(93,'','Modelo',1,0,NULL,NULL,NULL),(94,'','Producto',1,0,NULL,NULL,NULL),(95,'','Título',1,0,NULL,NULL,NULL),(96,'','Tomo',1,0,NULL,NULL,NULL),(97,'','Articulo',1,0,NULL,NULL,NULL),(98,'','Metodo de cultivo',1,0,NULL,NULL,NULL),(99,'','Edad',1,0,NULL,NULL,NULL),(100,'','Agotado',1,0,NULL,NULL,NULL),(101,'','Altura con asa',1,1,NULL,'cm',NULL),(102,'','Nº tallos',1,1,NULL,NULL,NULL),(103,'','Cultivo',1,0,NULL,NULL,NULL),(104,'','Sabor',1,0,NULL,NULL,NULL),(105,'','Talla',1,0,NULL,NULL,NULL),(106,'','Calibre',1,1,NULL,NULL,NULL),(107,'','Dulzura',1,1,NULL,'bx',NULL),(108,'','Piezas',1,0,NULL,NULL,NULL),(109,'','Altura con patas',1,0,NULL,NULL,NULL); +/*!40000 ALTER TABLE `tag` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `claimResponsible` +-- + +LOCK TABLES `claimResponsible` WRITE; +/*!40000 ALTER TABLE `claimResponsible` DISABLE KEYS */; +INSERT INTO `claimResponsible` VALUES (1,'Compradores',0),(2,'Proveedor',0),(3,'Entradores',0),(4,'Camareros',0),(6,'Sacadores',0),(7,'Revisadores',0),(8,'Calidad general',0),(9,'Encajadores',0),(11,'Comerciales',1),(12,'Clientes',1),(13,'Administración',0),(14,'Agencia',0),(15,'Repartidores',0),(16,'Informatica',0),(17,'Transp.origen',0),(18,'Confeccion',0),(19,'OTROS',0),(21,'Gerencia',0),(22,'Paletizadores',0); +/*!40000 ALTER TABLE `claimResponsible` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `claimReason` +-- + +LOCK TABLES `claimReason` WRITE; +/*!40000 ALTER TABLE `claimReason` DISABLE KEYS */; +INSERT INTO `claimReason` VALUES (1,'Prisas'),(2,'Novato'),(3,'Exceso de confianza'),(4,'Exceso de celo'),(5,'Indiferencia'),(6,'Extraviado o Hurto'),(7,'Incompetencia'),(8,'Ubicación erronea'),(9,'Dat.Inctos/Pak.conf'),(10,'Datos duplicados'),(11,'Fallo stock'),(12,'Innovación'),(13,'Distracción'),(15,'Portes indebidos'),(16,'Baja calidad'),(17,'Defectuoso'),(19,'Endiñado'),(20,'Calor'),(21,'Frio'),(22,'Cambiado'),(24,'Cansancio'),(25,'Mal etiquetado'),(26,'Cantidad malentendido'),(30,'No revisado'),(34,'Error fotografia'),(40,'Fallo Personal VN'),(41,'Fallo Personal Cliente'),(42,'Otros'),(43,'Precio alto'),(44,'Abuso de confianza'),(45,'Retraso Agencia'),(46,'Delicado'); +/*!40000 ALTER TABLE `claimReason` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `claimRedelivery` +-- + +LOCK TABLES `claimRedelivery` WRITE; +/*!40000 ALTER TABLE `claimRedelivery` DISABLE KEYS */; +INSERT INTO `claimRedelivery` VALUES (1,'Cliente'),(2,'No dev./No especif.'),(3,'Reparto'),(4,'Agencia'); +/*!40000 ALTER TABLE `claimRedelivery` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `claimResult` +-- + +LOCK TABLES `claimResult` WRITE; +/*!40000 ALTER TABLE `claimResult` DISABLE KEYS */; +INSERT INTO `claimResult` VALUES (1,'Otros daños'),(2,'Roces'),(3,'Humedad'),(4,'Deshidratacion'),(5,'Error identidad'),(6,'Incompleto (Faltas)'),(7,'Error packing'),(8,'Error color'),(9,'Error medida'),(10,'Error origen'),(11,'Envejecido'),(12,'Venta Perdida'),(13,'Duplicacion'),(14,'Rechazado'),(15,'Rotura'),(16,'Deterioro/Estropeado'),(17,'Podrido'),(18,'Baboso'),(19,'Cocido'),(20,'Congelado'),(21,'Machacado'),(22,'Error precio'),(23,'Manchado'),(24,'No entregado'),(25,'Cobro indebido'),(26,'Decepcion/Esperaba mas'),(27,'Otros'); +/*!40000 ALTER TABLE `claimResult` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `ticketUpdateAction` +-- + +LOCK TABLES `ticketUpdateAction` WRITE; +/*!40000 ALTER TABLE `ticketUpdateAction` DISABLE KEYS */; +INSERT INTO `ticketUpdateAction` VALUES (1,'Cambiar los precios en el ticket'),(3,'Convertir en maná'); +/*!40000 ALTER TABLE `ticketUpdateAction` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `state` +-- + +LOCK TABLES `state` WRITE; +/*!40000 ALTER TABLE `state` DISABLE KEYS */; +INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0),(2,'Libre',1,0,'FREE',NULL,2,0,0),(3,'OK',3,0,'OK',3,28,1,0),(4,'Impreso',4,1,'PRINTED',2,29,1,0),(5,'Preparación',5,1,'ON_PREPARATION',7,5,0,0),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1),(7,'Sin Acabar',2,0,'NOT_READY',NULL,7,0,0),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1),(9,'Encajando',9,1,'PACKING',NULL,9,0,1),(10,'Encajado',10,2,'PACKED',NULL,10,0,1),(11,'Facturado',0,0,'INVOICED',NULL,11,0,1),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1),(17,'Eliminado',14,3,'ERASED',NULL,17,0,0),(20,'Asignado',4,1,'PICKER_DESIGNED',NULL,20,1,0),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0),(22,'¿Fecha?',2,0,'WRONG_DATE',NULL,22,0,0),(23,'URGENTE',2,0,'LAST_CALL',NULL,23,1,0),(24,'Encadenado',3,0,'CHAINED',4,24,0,0),(25,'Embarcando',3,0,'BOARDING',5,25,0,0),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,26,0,0),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0),(28,'Previa OK',3,1,'OK PREVIOUS',3,28,1,0),(29,'Previa Impreso',4,1,'PRINTED PREVIOUS',2,29,1,0); +/*!40000 ALTER TABLE `state` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `sample` +-- + +LOCK TABLES `sample` WRITE; +/*!40000 ALTER TABLE `sample` DISABLE KEYS */; +INSERT INTO `sample` VALUES (1,'Carta_1','Aviso inicial por saldo deudor',0,'0'),(2,'Carta_2','Reiteracion de aviso por saldo deudor',0,'0'),(3,'Cred_Up','Notificación de aumento de crédito',0,'0'),(4,'Cred_down','Notificación de reducción de crédito',0,'0'),(5,'Pet_CC','Petición de datos bancarios B2B',0,'0'),(6,'SolCredito','Solicitud de crédito',0,'0'),(7,'LeyPago','Ley de pagos',0,'0'),(8,'Pet_CC_Core','Petición de datos bancarios CORE',0,'0'),(9,'nueva_alta','Documento de nueva alta de cliente',0,'0'),(10,'client_welcome','Email de bienvenida para nuevo cliente',0,'0'),(11,'setup_printer','Email de instalación de impresora',0,'0'),(12,'client-welcome','Email de bienvenida como nuevo cliente',1,'0'),(13,'printer-setup','Email de instalación y configuración de impresora de coronas',1,'0'),(14,'sepa-core','Email de solicitud de datos bancarios core',1,'1'),(15,'letter-debtor-st','Email de aviso inicial por saldo deudor',1,'1'),(16,'letter-debtor-nd','Email de aviso reiterado por saldo deudor',1,'1'),(17,'client-lcr','Email de solicitud de datos bancarios LCR',1,'1'); +/*!40000 ALTER TABLE `sample` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `department` +-- + +LOCK TABLES `department` WRITE; +/*!40000 ALTER TABLE `department` DISABLE KEYS */; +INSERT INTO `department` VALUES (1,'VERDNATURA',1,78,763,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(22,'COMPRAS',65,66,NULL,72,596,2,5,0,0,1,0,NULL,NULL),(23,'CAMARA',41,42,NULL,72,604,2,6,1,0,0,0,NULL,NULL),(31,'INFORMATICA',11,12,NULL,72,127,3,9,0,0,0,0,NULL,NULL),(34,'CONTABILIDAD',4,5,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(35,'FINANZAS',6,7,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(36,'LABORAL',8,9,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(37,'PRODUCCION',15,24,NULL,72,230,3,11,0,0,0,0,NULL,NULL),(38,'SACADO',20,21,NULL,72,230,4,14,1,0,0,0,NULL,NULL),(39,'ENCAJADO',22,23,NULL,72,230,4,12,1,0,0,0,NULL,NULL),(41,'ADMINISTRACION',3,10,NULL,72,599,3,8,0,0,0,0,NULL,NULL),(43,'VENTAS',51,64,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(44,'GERENCIA',2,25,NULL,72,300,2,7,0,0,0,0,NULL,NULL),(45,'LOGISTICA',26,37,NULL,72,596,3,19,0,0,0,0,NULL,NULL),(46,'REPARTO',38,39,NULL,72,659,3,10,0,0,0,0,NULL,NULL),(48,'ALMACENAJE',40,47,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(49,'PROPIEDAD',48,75,NULL,72,1008,1,1,0,0,0,0,NULL,NULL),(52,'CARGA AEREA',27,28,NULL,72,163,4,28,0,0,0,0,NULL,NULL),(53,'MARKETING Y COMUNICACIÓN',60,61,NULL,72,1238,0,0,0,0,0,0,NULL,NULL),(54,'ORNAMENTALES',76,77,NULL,72,433,3,21,0,0,0,0,NULL,NULL),(55,'TALLER NATURAL',68,69,NULL,72,695,2,23,0,0,0,0,NULL,NULL),(56,'TALLER ARTIFICIAL',70,71,NULL,72,1780,2,24,0,0,0,0,NULL,NULL),(58,'CAMPOS',73,74,NULL,72,225,2,2,0,0,0,0,NULL,NULL),(59,'MANTENIMIENTO',49,50,NULL,72,1907,4,16,0,0,0,0,NULL,NULL),(60,'RECLAMACIONES',58,59,NULL,72,563,3,20,0,0,0,0,NULL,NULL),(61,'VNH',35,36,NULL,73,1297,3,17,0,0,0,0,NULL,NULL),(63,'VENTAS FRANCIA',62,63,NULL,72,277,2,27,0,0,0,0,NULL,NULL),(66,'VERDNAMADRID',31,32,NULL,72,163,3,18,0,0,0,0,NULL,NULL),(68,'COMPLEMENTOS',43,44,NULL,72,617,3,26,1,0,0,0,NULL,NULL),(69,'VERDNABARNA',33,34,NULL,74,432,3,22,0,0,0,0,NULL,NULL),(77,'PALETIZADO',18,19,NULL,72,230,4,15,1,0,0,0,NULL,NULL),(80,'EQUIPO J VALLES',56,57,NULL,72,693,3,4,0,0,0,0,NULL,NULL),(86,'LIMPIEZA',13,14,NULL,72,599,0,0,0,0,0,0,NULL,NULL),(89,'COORDINACION',16,17,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,NULL),(90,'TRAILER',29,30,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(91,'ARTIFICIAL',45,46,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,NULL),(92,'EQUIPO SILVERIO',54,55,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(93,'CONFECCION',67,72,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(94,'EQUIPO J BROCAL',52,53,NULL,0,NULL,NULL,NULL,0,0,1,0,NULL,NULL); +/*!40000 ALTER TABLE `department` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2019-11-26 14:02:57 +USE `bi`; +-- MySQL dump 10.13 Distrib 5.7.28, for Linux (x86_64) +-- +-- Host: db.verdnatura.es Database: bi +-- ------------------------------------------------------ +-- Server version 5.6.25-4-log + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Dumping data for table `tarifa_componentes` +-- + +LOCK TABLES `tarifa_componentes` WRITE; +/*!40000 ALTER TABLE `tarifa_componentes` DISABLE KEYS */; +INSERT INTO `tarifa_componentes` VALUES (10,'Precios Especiales',4,NULL,NULL,1,'specialPrices'),(14,'porte extra por dia semana',6,NULL,NULL,1,'extraCostPerWeekDay'),(15,'reparto',6,NULL,NULL,1,'delivery'),(17,'recobro',5,NULL,NULL,1,'debtCollection'),(21,'ajuste',12,NULL,NULL,1,'adjustment'),(22,'venta por paquete',9,1,NULL,0,'salePerPackage'),(23,'venta por caja',9,2,NULL,0,'salePerBox'),(28,'valor de compra',1,NULL,NULL,1,'purchaseValue'),(29,'margen',4,NULL,NULL,1,'margin'),(32,'descuento ultimas unidades',9,3,-0.05,0,'lastUnitsDiscount'),(33,'venta por caja',9,1,NULL,0,'salePerBox'),(34,'descuento comprador',4,NULL,NULL,1,'buyerDiscount'),(35,'cartera comprador',10,NULL,NULL,1,NULL),(36,'descuadre',11,NULL,NULL,1,'mismatch'),(37,'maná',7,4,NULL,0,'mana'),(38,'embolsado',9,NULL,NULL,1,'bagged'),(39,'maná auto',7,NULL,NULL,1,'autoMana'),(40,'cambios Santos 2016',4,NULL,NULL,1,NULL),(41,'bonificacion porte',4,NULL,NULL,1,'freightCharge'); +/*!40000 ALTER TABLE `tarifa_componentes` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `tarifa_componentes_series` +-- + +LOCK TABLES `tarifa_componentes_series` WRITE; +/*!40000 ALTER TABLE `tarifa_componentes_series` DISABLE KEYS */; +INSERT INTO `tarifa_componentes_series` VALUES (1,'coste',1,0),(2,'com ventas',1,1),(3,'com compras',1,1),(4,'empresa',1,1),(5,'cliente',0,0),(6,'agencia',0,0),(7,'cartera_comercial',0,1),(8,'cartera_producto',0,1),(9,'maniobra',1,1),(10,'cartera_comprador',0,1),(11,'errores',0,1),(12,'otros',0,1); +/*!40000 ALTER TABLE `tarifa_componentes_series` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2019-11-26 14:02:57 +USE `cache`; +-- MySQL dump 10.13 Distrib 5.7.28, for Linux (x86_64) +-- +-- Host: db.verdnatura.es Database: cache +-- ------------------------------------------------------ +-- Server version 5.6.25-4-log + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Dumping data for table `cache` +-- + +LOCK TABLES `cache` WRITE; +/*!40000 ALTER TABLE `cache` DISABLE KEYS */; +INSERT INTO `cache` VALUES (1,'equalizator','00:15:00'),(2,'available','00:06:00'),(3,'stock','00:30:00'),(4,'last_buy','00:30:00'),(5,'weekly_sales','12:00:00'),(6,'bionic','00:05:00'),(7,'sales','00:03:00'),(8,'visible','00:04:00'),(9,'item_range','00:03:00'),(10,'barcodes','01:00:00'),(11,'prod_graphic','00:15:00'),(12,'ticketShipping','00:01:00'); +/*!40000 ALTER TABLE `cache` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2019-11-26 14:02:57 +USE `hedera`; +-- MySQL dump 10.13 Distrib 5.7.28, for Linux (x86_64) +-- +-- Host: db.verdnatura.es Database: hedera +-- ------------------------------------------------------ +-- Server version 5.6.25-4-log + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Dumping data for table `imageCollection` +-- + +LOCK TABLES `imageCollection` WRITE; +/*!40000 ALTER TABLE `imageCollection` DISABLE KEYS */; +INSERT INTO `imageCollection` VALUES (1,'catalog','Artículo',3840,2160,'Item','image','vn','item','image'),(4,'link','Enlace',200,200,'Link','image','hedera','link','image'),(5,'news','Noticias',800,1200,'New','image','hedera','news','image'); +/*!40000 ALTER TABLE `imageCollection` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `tpvError` +-- + +LOCK TABLES `tpvError` WRITE; +/*!40000 ALTER TABLE `tpvError` DISABLE KEYS */; +INSERT INTO `tpvError` VALUES ('SIS0007','Error al desmontar el XML de entrada'),('SIS0008','Error falta Ds_Merchant_MerchantCode'),('SIS0009','Error de formato en Ds_Merchant_MerchantCode'),('SIS0010','Error falta Ds_Merchant_Terminal'),('SIS0011','Error de formato en Ds_Merchant_Terminal'),('SIS0014','Error de formato en Ds_Merchant_Order'),('SIS0015','Error falta Ds_Merchant_Currency'),('SIS0016','Error de formato en Ds_Merchant_Currency'),('SIS0017','Error no se admite operaciones en pesetas'),('SIS0018','Error falta Ds_Merchant_Amount'),('SIS0019','Error de formato en Ds_Merchant_Amount'),('SIS0020','Error falta Ds_Merchant_MerchantSignature'),('SIS0021','Error la Ds_Merchant_MerchantSignature viene vacía'),('SIS0022','Error de formato en Ds_Merchant_TransactionType'),('SIS0023','Error Ds_Merchant_TransactionType desconocido'),('SIS0024','Error Ds_Merchant_ConsumerLanguage tiene más de 3 posiciones'),('SIS0026','Error No existe el comercio / terminal enviado'),('SIS0027','Error Moneda enviada por el comercio es diferente a la que tiene asignada para ese terminal'),('SIS0028','Error Comercio / terminal está dado de baja'),('SIS0030','Error en un pago con tarjeta ha llegado un tipo de operación no valido'),('SIS0031','Método de pago no definido'),('SIS0034','Error de acceso a la Base de Datos'),('SIS0038','Error en java'),('SIS0040','Error el comercio / terminal no tiene ningún método de pago asignado'),('SIS0041','Error en el cálculo de la firma de datos del comercio'),('SIS0042','La firma enviada no es correcta'),('SIS0046','El BIN de la tarjeta no está dado de alta'),('SIS0051','Error número de pedido repetido'),('SIS0054','Error no existe operación sobre la que realizar la devolución'),('SIS0055','Error no existe más de un pago con el mismo número de pedido'),('SIS0056','La operación sobre la que se desea devolver no está autorizada'),('SIS0057','El importe a devolver supera el permitido'),('SIS0058','Inconsistencia de datos, en la validación de una confirmación'),('SIS0059','Error no existe operación sobre la que realizar la devolución'),('SIS0060','Ya existe una confirmación asociada a la preautorización'),('SIS0061','La preautorización sobre la que se desea confirmar no está autorizada'),('SIS0062','El importe a confirmar supera el permitido'),('SIS0063','Error. Número de tarjeta no disponible'),('SIS0064','Error. El número de tarjeta no puede tener más de 19 posiciones'),('SIS0065','Error. El número de tarjeta no es numérico'),('SIS0066','Error. Mes de caducidad no disponible'),('SIS0067','Error. El mes de la caducidad no es numérico'),('SIS0068','Error. El mes de la caducidad no es válido'),('SIS0069','Error. Año de caducidad no disponible'),('SIS0070','Error. El Año de la caducidad no es numérico'),('SIS0071','Tarjeta caducada'),('SIS0072','Operación no anulable'),('SIS0074','Error falta Ds_Merchant_Order'),('SIS0075','Error el Ds_Merchant_Order tiene menos de 4 posiciones o más de 12'),('SIS0076','Error el Ds_Merchant_Order no tiene las cuatro primeras posiciones numéricas'),('SIS0078','Método de pago no disponible'),('SIS0079','Error al realizar el pago con tarjeta'),('SIS0081','La sesión es nueva, se han perdido los datos almacenados'),('SIS0089','El valor de Ds_Merchant_ExpiryDate no ocupa 4 posiciones'),('SIS0092','El valor de Ds_Merchant_ExpiryDate es nulo'),('SIS0093','Tarjeta no encontrada en la tabla de rangos'),('SIS0112','Error. El tipo de transacción especificado en Ds_Merchant_Transaction_Type no esta permitido'),('SIS0115','Error no existe operación sobre la que realizar el pago de la cuota'),('SIS0116','La operación sobre la que se desea pagar una cuota no es una operación válida'),('SIS0117','La operación sobre la que se desea pagar una cuota no está autorizada'),('SIS0118','Se ha excedido el importe total de las cuotas'),('SIS0119','Valor del campo Ds_Merchant_DateFrecuency no válido'),('SIS0120','Valor del campo Ds_Merchant_CargeExpiryDate no válido'),('SIS0121','Valor del campo Ds_Merchant_SumTotal no válido'),('SIS0122','Valor del campo Ds_merchant_DateFrecuency o Ds_Merchant_SumTotal tiene formato incorrecto'),('SIS0123','Se ha excedido la fecha tope para realizar transacciones'),('SIS0124','No ha transcurrido la frecuencia mínima en un pago recurrente sucesivo'),('SIS0132','La fecha de Confirmación de Autorización no puede superar en más de 7 días a la de Preautorización'),('SIS0139','Error el pago recurrente inicial está duplicado SIS0142 Tiempo excedido para el pago'),('SIS0216','Error Ds_Merchant_CVV2 tiene mas de 3/4 posiciones'),('SIS0217','Error de formato en Ds_Merchant_CVV2'),('SIS0221','Error el CVV2 es obligatorio'),('SIS0222','Ya existe una anulación asociada a la preautorización'),('SIS0223','La preautorización que se desea anular no está autorizada'),('SIS0225','Error no existe operación sobre la que realizar la anulación'),('SIS0226','Inconsistencia de datos, en la validación de una anulación'),('SIS0227','Valor del campo Ds_Merchan_TransactionDate no válido'),('SIS0252','El comercio no permite el envío de tarjeta'),('SIS0253','La tarjeta no cumple el check-digit'),('SIS0261','Operación detenida por superar el control de restricciones en la entrada al SIS'),('SIS0274','Tipo de operación desconocida o no permitida por esta entrada al SIS'),('SIS9915','A petición del usuario se ha cancelado el pago'); +/*!40000 ALTER TABLE `tpvError` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `tpvResponse` +-- + +LOCK TABLES `tpvResponse` WRITE; +/*!40000 ALTER TABLE `tpvResponse` DISABLE KEYS */; +INSERT INTO `tpvResponse` VALUES (101,'Tarjeta Caducada'),(102,'Tarjeta en excepción transitoria o bajo sospecha de fraude'),(104,'Operación no permitida para esa tarjeta o terminal'),(106,'Intentos de PIN excedidos'),(116,'Disponible Insuficiente'),(118,'Tarjeta no Registrada'),(125,'Tarjeta no efectiva'),(129,'Código de seguridad (CVV2/CVC2) incorrecto'),(180,'Tarjeta ajena al servicio'),(184,'Error en la autenticación del titular'),(190,'Denegación sin especificar motivo'),(191,'Fecha de caducidad errónea'),(202,'Tarjeta en excepción transitoria o bajo sospecha de fraude con retirada de tarjeta'),(904,'Comercio no registrado en FUC'),(909,'Error de sistema'),(912,'Emisor no Disponible'),(913,'Pedido repetido'),(944,'Sesión Incorrecta'),(950,'Operación de devolución no permitida'),(9064,'Número de posiciones de la tarjeta incorrecto'),(9078,'No existe método de pago válido para esa tarjeta'),(9093,'Tarjeta no existente'),(9094,'Rechazo servidores internacionales'),(9104,'A petición del usuario se ha cancelado el pago'),(9218,'El comercio no permite op. seguras por entrada /operaciones'),(9253,'Tarjeta no cumple el check-digit'),(9256,'El comercio no puede realizar preautorizaciones'),(9257,'Esta tarjeta no permite operativa de preautorizaciones'),(9261,'Operación detenida por superar el control de restricciones en la entrada al SIS'),(9912,'Emisor no Disponible'),(9913,'Error en la confirmación que el comercio envía al TPV Virtual (solo aplicable en la opción de sincronización SOAP)'),(9914,'Confirmación “KO” del comercio (solo aplicable en la opción de sincronización SOAP)'),(9915,'A petición del usuario se ha cancelado el pago'),(9928,'Anulación de autorización en diferido realizada por el SIS (proceso batch)'),(9929,'Anulación de autorización en diferido realizada por el comercio'),(9998,'Operación en proceso de solicitud de datos de tarjeta'),(9999,'Operación que ha sido redirigida al emisora autenticar'); +/*!40000 ALTER TABLE `tpvResponse` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2019-11-26 14:02:57 +USE `postgresql`; +-- MySQL dump 10.13 Distrib 5.7.28, for Linux (x86_64) +-- +-- Host: db.verdnatura.es Database: postgresql +-- ------------------------------------------------------ +-- Server version 5.6.25-4-log + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Dumping data for table `calendar_labour_type` +-- + +LOCK TABLES `calendar_labour_type` WRITE; +/*!40000 ALTER TABLE `calendar_labour_type` DISABLE KEYS */; +INSERT INTO `calendar_labour_type` VALUES (1,'Horario general','00:20:00',40,0),(2,'Horario 35h/semana','00:20:00',35,1),(3,'Horario 20h/semana','00:00:00',20,1),(4,'Festivo y Fin de semana','00:00:00',0,1),(5,'Horario 30h/semana','00:20:00',30,1),(6,'Horario 25h/semana','00:20:00',25,1),(7,'Vacaciones trabajadas','00:00:00',0,1),(8,'Vacaciones','00:00:00',0,1),(9,'Horario 26h/semana','00:20:00',26,1),(10,'Horario 28h/semana','00:20:00',28,1),(11,'Horario 8h/semana','00:00:00',8,1),(12,'Horario 16h/semana','00:00:00',16,1),(13,'Horario 32h/semana','00:20:00',32,1),(14,'Horario 24h/semana','00:20:00',24,1),(15,'Horario 10h/semana','00:00:00',10,1),(16,'Horario 27,5h/semana','00:20:00',28,1),(17,'Horario 13,5h/semana','00:20:00',14,1),(18,'Horario 31h/semana',NULL,31,1),(19,'Horario 21,5h/semana',NULL,22,1),(20,'Horario 34h/semana',NULL,34,1),(21,'Horario 17h/semana',NULL,17,1),(22,'Horario 18h/semana',NULL,18,1),(23,'Horario 37,5 h/semana',NULL,38,1),(24,'Horario 29 h/semana',NULL,29,1),(25,'Horario 12h/semana',NULL,12,1),(26,'Horario 10h/semana',NULL,10,1),(27,'Horario 15h/semana',NULL,15,1),(28,'Horario 9h/semana',NULL,9,1),(29,'Horario 23h/semana',NULL,23,1),(30,'Horario 21h/semana',NULL,21,1),(31,'Horario 39h/semana',NULL,39,1),(32,'Horario 22/semana',NULL,22,1); +/*!40000 ALTER TABLE `calendar_labour_type` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `labour_agreement` +-- + +LOCK TABLES `labour_agreement` WRITE; +/*!40000 ALTER TABLE `labour_agreement` DISABLE KEYS */; +INSERT INTO `labour_agreement` VALUES (1,2.5,1830,'Flores y Plantas','2012-01-01',NULL); +/*!40000 ALTER TABLE `labour_agreement` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `media_type` +-- + +LOCK TABLES `media_type` WRITE; +/*!40000 ALTER TABLE `media_type` DISABLE KEYS */; +INSERT INTO `media_type` VALUES (3,'email'),(12,'extension movil'),(6,'facebook'),(2,'fijo'),(11,'material'),(10,'movil empresa'),(1,'movil personal'),(5,'msn'),(9,'seg social'),(4,'skype'),(7,'web'); +/*!40000 ALTER TABLE `media_type` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `professional_category` +-- + +LOCK TABLES `professional_category` WRITE; +/*!40000 ALTER TABLE `professional_category` DISABLE KEYS */; +INSERT INTO `professional_category` VALUES (1,'Mozos',5,1,27.5),(2,'Encargados',3,1,27.5),(4,'Comprador',3,1,27.5),(5,'Aux Administracion',NULL,1,27.5),(6,'Of Administracion',3,1,27.5),(7,'Jefe Administracion',2,1,27.5),(8,'Informatico',3,1,27.5),(9,'Directivo',1,0,27.5),(10,'Aux Ventas',4,1,27.5),(11,'Vendedor',4,1,27.5),(12,'Jefe de Ventas',4,0,27.5),(13,'Repartidor',5,1,27.5),(14,'Aprendices',NULL,1,27.5),(15,'Técnicos',2,1,27.5),(16,'Aux Florista',5,1,27.5),(17,'Florista',4,1,27.5),(18,'Jefe Floristas',2,1,27.5),(19,'Técnico marketing',3,1,27.5),(20,'Auxiliar marketing',4,1,27.5),(21,'Aux Informática',4,1,27.5),(22,'Peón agrícola',5,1,27.5),(23,'Oficial mantenimiento',4,1,27.5),(24,'Aux mantenimiento',5,1,27.5),(25,'Mozo Aeropuerto',5,1,27.5),(26,'Coordinador',2,1,27.5),(28,'Aux Logistica',4,1,27.5),(29,'Oficial Logistica',3,1,27.5),(30,'Subencargado',4,1,27.5); +/*!40000 ALTER TABLE `professional_category` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `profile_type` +-- + +LOCK TABLES `profile_type` WRITE; +/*!40000 ALTER TABLE `profile_type` DISABLE KEYS */; +INSERT INTO `profile_type` VALUES (1,'Laboral'),(2,'Personal'),(3,'Cliente'),(4,'Proveedor'),(5,'Banco'),(6,'Patronal'); +/*!40000 ALTER TABLE `profile_type` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `workcenter` +-- + +LOCK TABLES `workcenter` WRITE; +/*!40000 ALTER TABLE `workcenter` DISABLE KEYS */; +INSERT INTO `workcenter` VALUES (1,'Silla',20,1026,1),(2,'Mercaflor',19,NULL,NULL),(3,'Marjales',26,20007,NULL),(4,'VNH',NULL,NULL,3),(5,'Madrid',28,2851,5),(6,'Vilassar',88,88031,2),(7,'Tenerife',NULL,NULL,10),(8,'Silla-Agrario',26,2,NULL); +/*!40000 ALTER TABLE `workcenter` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2019-11-26 14:02:57 diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql new file mode 100644 index 000000000..c27d8a445 --- /dev/null +++ b/db/dump/fixtures.sql @@ -0,0 +1,1992 @@ +-- FIXME: cuando se eliminen los procedimientos de la cache, se podra eliminar esta linea +CREATE SCHEMA IF NOT EXISTS `vn2008`; +CREATE SCHEMA IF NOT EXISTS `tmp`; + +ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'root'; + +ALTER TABLE `vn`.`itemTaxCountry` AUTO_INCREMENT = 1; +ALTER TABLE `vn`.`address` AUTO_INCREMENT = 1; +ALTER TABLE `vn`.`zoneGeo` AUTO_INCREMENT = 1; +ALTER TABLE `vn`.`ticket` AUTO_INCREMENT = 1; + +INSERT INTO `vn`.`ticketConfig` (`id`, `scopeDays`) + VALUES + ('1', '6'); + +INSERT INTO `account`.`mailConfig` (`id`, `domain`) + VALUES + ('1', 'verdnatura.es'); + +INSERT INTO `vn`.`bionicConfig` (`generalInflationCoeficient`, `minimumDensityVolumetricWeight`, `verdnaturaVolumeBox`, `itemCarryBox`) + VALUES + (1.30, 167.00, 138000, 71); + +INSERT INTO `account`.`user`(`id`,`name`, `nickname`, `password`,`role`,`active`,`email`, `lang`) + SELECT id, name, CONCAT(name, 'Nick'),MD5('nightmare'), id, 1, CONCAT(name, '@mydomain.com'), 'es' + FROM `account`.`role` WHERE id <> 20; + +INSERT INTO `vn`.`worker`(`id`,`code`, `firstName`, `lastName`, `userFk`, `bossFk`) + SELECT id,UPPER(LPAD(role, 3, '0')), name, name, id, 9 + FROM `vn`.`user`; + +UPDATE `vn`.`worker` SET bossFk = NULL WHERE id = 20; +UPDATE `vn`.`worker` SET bossFk = 20 + WHERE id = 1 OR id = 9; + +DELETE FROM `vn`.`worker` WHERE firstName ='customer'; + +INSERT INTO `hedera`.`tpvConfig`(`id`, `currency`, `terminal`, `transactionType`, `maxAmount`, `employeeFk`, `testUrl`) + VALUES + (1, 978, 1, 0, 2000, 9, 0); + +INSERT INTO `account`.`user`(`id`,`name`,`password`,`role`,`active`,`email`,`lang`) + VALUES + (101, 'BruceWayne', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'BruceWayne@mydomain.com', 'es'), + (102, 'PetterParker', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'PetterParker@mydomain.com', 'en'), + (103, 'ClarkKent', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'ClarkKent@mydomain.com', 'fr'), + (104, 'TonyStark', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'TonyStark@mydomain.com', 'es'), + (105, 'MaxEisenhardt', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'MaxEisenhardt@mydomain.com', 'pt'), + (106, 'DavidCharlesHaller', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'DavidCharlesHaller@mydomain.com', 'es'), + (107, 'HankPym', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'HankPym@mydomain.com', 'es'), + (108, 'CharlesXavier', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'CharlesXavier@mydomain.com', 'es'), + (109, 'BruceBanner', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'BruceBanner@mydomain.com', 'es'), + (110, 'JessicaJones', 'ac754a330530832ba1bf7687f577da91', 1, 1, 'JessicaJones@mydomain.com', 'es'), + (111, 'Missing', 'ac754a330530832ba1bf7687f577da91', 2, 0, NULL, 'es'), + (112, 'Trash', 'ac754a330530832ba1bf7687f577da91', 2, 0, NULL, 'es'); + +INSERT INTO `vn`.`worker`(`id`, `code`, `firstName`, `lastName`, `userFk`,`bossFk`) + VALUES + (106, 'LGN', 'David Charles', 'Haller', 106, 19), + (107, 'ANT', 'Hank' , 'Pym' , 107, 19), + (108, 'DCX', 'Charles' , 'Xavier', 108, 19), + (109, 'HLK', 'Bruce' , 'Banner', 109, 19), + (110, 'JJJ', 'Jessica' , 'Jones' , 110, 19); + +INSERT INTO `vn`.`country`(`id`, `country`, `isUeeMember`, `code`, `currencyFk`, `ibanLength`) + VALUES + (1, 'España', 0, 'ES', 1, 24), + (2, 'Italia', 1, 'IT', 1, 27), + (3, 'Alemania', 1, 'DE', 1, 22), + (4, 'Rumania', 1, 'RO', 1, 24), + (5, 'Holanda', 1, 'NL', 1, 18), + (8, 'Portugal', 1, 'PT', 1, 27), + (19,'Francia', 1, 'FR', 1, 27), + (30,'Canarias', 1, 'IC', 1, 24); + +INSERT INTO `vn`.`warehouse`(`id`, `name`, `isComparative`, `isInventory`, `hasAvailable`, `isManaged`, `hasStowaway`, `hasDms`, `hasComission`) + VALUES + (1, 'Warehouse One', 1, 1, 1, 1, 1, 1, 1), + (2, 'Warehouse Two', 1, 1, 1, 1, 0, 0, 1), + (3, 'Warehouse Three', 1, 1, 1, 1, 0, 0, 0), + (4, 'Warehouse Four', 1, 1, 1, 1, 0, 0, 0), + (5, 'Warehouse Five', 1, 1, 1, 1, 0, 0, 0); + +INSERT INTO `vn`.`sector`(`id`, `description`, `warehouseFk`, `isPreviousPreparedByPacking`, `code`, `pickingPlacement`, `path`) + VALUES + (1, 'First sector', 1, 1, 'FIRST', 999, 999), + (2, 'Second sector', 2, 0, 'SECOND', 100, 150); + +INSERT INTO `vn`.`warehouseAlias`(`id`, `name`) + VALUES + (1, 'Main Warehouse'); + +INSERT INTO `vn`.`accountingType`(`id`, `description`) + VALUES + (1, 'Digital money'), + (2, 'Cash'), + (3, 'Card'), + (4, 'Stolen Money'), + (5, 'Miscellaneous'); + +INSERT INTO `vn`.`currency`(`id`, `code`, `name`, `ratio`) + VALUES + (1, 'EUR', 'Euro', 1), + (2, 'USD', 'Dollar USA', 1.4), + (3, 'GBP', 'Libra', 1), + (4, 'JPY', 'Yen Japones', 1); + +INSERT INTO `vn`.`bank`(`id`, `bank`, `account`, `cash`, `entityFk`, `isActive`, `currencyFk`) + VALUES + (1, 'Pay on receipt', '0000000000', 4, 0, 1, 1), + (2, 'Cash', '1111111111', 1, 0, 1, 1); + +INSERT INTO `vn`.`agency`(`id`, `name`, `warehouseFk`, `isVolumetric`, `bankFk`, `warehouseAliasFk`) + VALUES + (1, 'inhouse pickup' , 1, 0, 1, 1), + (2, 'Super-Man delivery' , 1, 0, 1, 1), + (3, 'Teleportation device' , 1, 0, 1, 1), + (4, 'Entanglement' , 1, 0, 1, 1), + (5, 'Quantum break device' , 1, 0, 1, 1), + (6, 'Walking' , 1, 0, 1, 1), + (7, 'Silla247' , 1, 0, 1, 1), + (8, 'Silla247Expensive' , 1, 0, 1, 1), + (9, 'Refund' , 1, 0, 1, 1), + (10, 'Other agency' , 1, 0, 1, 1); + +UPDATE `vn`.`agencyMode` SET `id` = 1 WHERE `name` = 'inhouse pickup'; +UPDATE `vn`.`agencyMode` SET `id` = 2 WHERE `name` = 'Super-Man delivery'; +UPDATE `vn`.`agencyMode` SET `id` = 3 WHERE `name` = 'Teleportation device'; +UPDATE `vn`.`agencyMode` SET `id` = 4 WHERE `name` = 'Entanglement'; +UPDATE `vn`.`agencyMode` SET `id` = 5 WHERE `name` = 'Quantum break device'; +UPDATE `vn`.`agencyMode` SET `id` = 6 WHERE `name` = 'Walking'; +UPDATE `vn`.`agencyMode` SET `id` = 7 WHERE `name` = 'Silla247'; +UPDATE `vn`.`agencyMode` SET `id` = 8 WHERE `name` = 'Silla247Expensive'; +UPDATE `vn`.`agencyMode` SET `id` = 23 WHERE `name` = 'Refund'; +UPDATE `vn`.`agencyMode` SET `id` = 10 WHERE `name` = 'Other agency'; + +UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 1 WHERE `id` = 1; +UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 1 WHERE `id` = 2; +UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 2 WHERE `id` = 3; +UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 1 WHERE `id` = 4; +UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 1 WHERE `id` = 5; +UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 2 WHERE `id` = 6; +UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 1 WHERE `id` = 7; +UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 1 WHERE `id` = 8; +UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 4 WHERE `id` = 23; +UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 1 WHERE `id` = 10; + +UPDATE `vn`.`agencyMode` SET `web` = 1; + +UPDATE `vn`.`agencyMode` SET `code` = 'refund' WHERE `id` = 23; + +INSERT INTO `vn`.`payMethod`(`id`, `name`, `graceDays`, `outstandingDebt`, `ibanRequired`) + VALUES + (1, 'PayMethod one', 0, 001, 0), + (2, 'PayMethod two', 10, 001, 0), + (3, 'PayMethod three', 0, 001, 0), + (4, 'PayMethod with IBAN', 0, 001, 1), + (5, 'PayMethod five', 10, 001, 0); + +INSERT INTO `vn`.`payDem`(`id`, `payDem`) + VALUES + (1, 10), + (2, 20); + +INSERT INTO `vn`.`province`(`id`, `name`, `countryFk`, `warehouseFk`) + VALUES + (1, 'Province one', 1, NULL), + (2, 'Province two', 1, NULL), + (3, 'Province three', 1, NULL), + (4, 'Province four', 1, NULL), + (5, 'Province five', 1, NULL); + +INSERT INTO `vn`.`town`(`id`, `name`, `provinceFk`) + VALUES + (1, 'Valencia', 1), + (2, 'Silla', 1), + (3, 'Algemesi', 1), + (4, 'Alzira', 1); + +INSERT INTO `vn`.`postCode`(`code`, `townFk`, `geoFk`) + VALUES + ('46000', 1, 6), + ('46460', 2, 6), + ('46680', 3, 6), + ('46600', 4, 7); + +INSERT INTO `vn`.`clientType`(`id`, `code`, `type`) + VALUES + (1, 'normal', 'Normal'), + (2, 'internalUse', 'Autoconsumo'), + (3, 'handMaking', 'Confección'), + (4, 'loses', 'Mermas'); + +INSERT INTO `vn`.`cplusTerIdNif`(`id`, `description`) + VALUES + (1, 'NIF'); + +INSERT INTO `vn`.`contactChannel`(`id`, `name`) + VALUES + (1, 'Rumors on the streets'), + (2, 'Metropolis newspaper'), + (3, 'Daily Bugle'), + (4, 'GCN Channel'), + (5, 'The Newspaper'); + +INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`fax`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`,`clientTypeFk`,`mailAddress`,`cplusTerIdNifFk`,`hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`eypbc`) + VALUES + (101, 'Bruce Wayne', '84612325V', 'Batman', 'Alfred', '1007 Mountain Drive, Gotham', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), + (102, 'Petter Parker', '87945234L', 'Spider man', 'Aunt May', '20 Ingram Street', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), + (103, 'Clark Kent', '06815934E', 'Super man', 'lois lane', '344 Clinton Street', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 0, 19, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), + (104, 'Tony Stark', '06089160W', 'Iron man', 'Pepper Potts', '10880 Malibu Point', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), + (105, 'Max Eisenhardt', '251628698', 'Magneto', 'Rogue', 'Unknown Whereabouts', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 8, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1), + (106, 'DavidCharlesHaller', '53136686Q', 'Legion', 'Charles Xavier', 'Evil hideout', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 19, 0, 1), + (107, 'Hank Pym', '09854837G', 'Ant man', 'Hawk', 'Anthill', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1), + (108, 'Charles Xavier', '22641921P', 'Professor X', 'Beast', '3800 Victory Pkwy, Cincinnati, OH 45207, USA', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1), + (109, 'Bruce Banner', '16104829E', 'Hulk', 'Black widow', 'Somewhere in New York', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1), + (110, 'Jessica Jones', '58282869H', 'Jessica Jones', 'Luke Cage', 'NYCC 2015 Poster', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, NULL, 0, 1), + (111, 'Missing', NULL, 'Missing man', 'Anton', 'The space', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, NULL, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1), + (112, 'Trash', NULL, 'Garbage man', 'Unknown name', 'New York city', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, NULL, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1); + +INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `phone`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) + SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), CONCAT(name, 'Social'), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'SILLA', 46460, 623111111, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, CURDATE(), 1 + FROM `account`.`role` `r` + WHERE `r`.`hasLogin` = 1; + +INSERT INTO `vn`.`clientManaCache`(`clientFk`, `mana`, `dated`) + VALUES + (101, 50, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (102, 100, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (103, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (104, -30, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)); + +INSERT INTO `vn`.`address`(`id`, `nickname`, `street`, `city`, `postalCode`, `provinceFk`, `phone`, `mobile`, `isActive`, `clientFk`, `agencyModeFk`, `longitude`, `latitude`, `isEqualizated`, `isDefaultAddress`) + VALUES + (1, 'Bruce Wayne', '1007 Mountain Drive, Gotham', 'Silla', 46460, 1, 1111111111, 222222222, 1, 101, 2, NULL, NULL, 0, 1), + (2, 'Petter Parker', '20 Ingram Street', 'Silla', 46460, 1, 1111111111, 222222222, 1, 102, 2, NULL, NULL, 0, 1), + (3, 'Clark Kent', '344 Clinton Street', 'Silla', 46460, 1, 1111111111, 222222222, 1, 103, 2, NULL, NULL, 0, 1), + (4, 'Tony Stark', '10880 Malibu Point', 'Silla', 46460, 1, 1111111111, 222222222, 1, 104, 2, NULL, NULL, 0, 1), + (5, 'Max Eisenhardt', 'Unknown Whereabouts', 'Silla', 46460, 1, 1111111111, 222222222, 1, 105, 2, NULL, NULL, 0, 1), + (6, 'DavidCharlesHaller', 'Evil hideout', 'Silla', 46460, 1, 1111111111, 222222222, 1, 106, 2, NULL, NULL, 0, 1), + (7, 'Hank Pym', 'Anthill', 'Silla', 46460, 1, 1111111111, 222222222, 1, 107, 2, NULL, NULL, 0, 1), + (8, 'Charles Xavier', '3800 Victory Pkwy, Cincinnati, OH 45207, USA', 'Silla', 46460, 1, 1111111111, 222222222, 1, 108, 2, NULL, NULL, 0, 1), + (9, 'Bruce Banner', 'Somewhere in New York', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 1), + (10, 'Jessica Jones', 'NYCC 2015 Poster', 'Silla', 46460, 1, 1111111111, 222222222, 1, 110, 2, NULL, NULL, 0, 1), + (11, 'Missing', 'The space', 'Silla', 46460, 1, 1111111111, 222222222, 1, 111, 10, NULL, NULL, 0, 1), + (12, 'Trash', 'New York city', 'Silla', 46460, 1, 1111111111, 222222222, 1, 112, 10, NULL, NULL, 0, 1), + (101, 'address 01', 'Somewhere in Thailand', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), + (102, 'address 02', 'Somewhere in Poland', 'Silla', 46460, 1, 3333333333, 444444444, 1, 109, 2, NULL, NULL, 0, 0), + (103, 'address 03', 'Somewhere in Japan', 'Silla', 46460, 1, 3333333333, 444444444, 1, 109, 2, NULL, NULL, 0, 0), + (104, 'address 04', 'Somewhere in Spain', 'Silla', 46460, 1, 3333333333, 444444444, 1, 109, 2, NULL, NULL, 0, 0), + (105, 'address 05', 'Somewhere in Potugal', 'Silla', 46460, 1, 5555555555, 666666666, 1, 109, 2, NULL, NULL, 0, 0), + (106, 'address 06', 'Somewhere in UK', 'Silla', 46460, 1, 5555555555, 666666666, 1, 109, 2, NULL, NULL, 0, 0), + (107, 'address 07', 'Somewhere in Valencia', 'Silla', 46460, 1, 5555555555, 666666666, 1, 109, 2, NULL, NULL, 0, 0), + (108, 'address 08', 'Somewhere in Silla', 'Silla', 46460, 1, 5555555555, 666666666, 1, 109, 2, NULL, NULL, 0, 0), + (109, 'address 09', 'Somewhere in London', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), + (110, 'address 10', 'Somewhere in Algemesi', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), + (111, 'address 11', 'Somewhere in Carlet', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), + (112, 'address 12', 'Somewhere in Campanar', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), + (113, 'address 13', 'Somewhere in Malilla', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), + (114, 'address 14', 'Somewhere in France', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), + (115, 'address 15', 'Somewhere in Birmingham', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), + (116, 'address 16', 'Somewhere in Scotland', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), + (117, 'address 17', 'Somewhere in nowhere', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), + (118, 'address 18', 'Somewhere over the rainbow', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), + (119, 'address 19', 'Somewhere in Alberic', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), + (120, 'address 20', 'Somewhere in Montortal', 'Silla', 46460, 1, 1111111111, 222222222, 1, 109, 2, NULL, NULL, 0, 0), + (121, 'address 21', 'the bat cave', 'Silla', 46460, 1, 1111111111, 222222222, 1, 101, 2, NULL, NULL, 0, 0), + (122, 'address 22', 'NY roofs', 'Silla', 46460, 1, 1111111111, 222222222, 1, 102, 2, NULL, NULL, 0, 0), + (123, 'address 23', 'The phone box', 'Silla', 46460, 1, 1111111111, 222222222, 1, 103, 2, NULL, NULL, 0, 0), + (124, 'address 24', 'Stark tower Silla', 'Silla', 46460, 1, 1111111111, 222222222, 1, 104, 2, NULL, NULL, 0, 0), + (125, 'address 25', 'The plastic cell', 'Silla', 46460, 1, 1111111111, 222222222, 1, 105, 2, NULL, NULL, 0, 0), + (126, 'address 26', 'Many places', 'Silla', 46460, 1, 1111111111, 222222222, 1, 106, 2, NULL, NULL, 0, 0), + (127, 'address 27', 'Your pocket', 'Silla', 46460, 1, 1111111111, 222222222, 1, 107, 2, NULL, NULL, 0, 0), + (128, 'address 28', 'Cerebro', 'Silla', 46460, 1, 1111111111, 222222222, 1, 108, 2, NULL, NULL, 0, 0), + (129, 'address 29', 'Luke Cages Bar', 'Silla', 46460, 1, 1111111111, 222222222, 1, 110, 2, NULL, NULL, 0, 0), + (130, 'address 30', 'Non valid address', 'Silla', 46460, 1, 1111111111, 222222222, 0, 101, 2, NULL, NULL, 0, 0); + +INSERT INTO `vn`.`address`( `nickname`, `street`, `city`, `postalCode`, `provinceFk`, `isActive`, `clientFk`, `agencyModeFk`, `isDefaultAddress`) + SELECT name, CONCAT(name, 'Street'), 'SILLA', 46460, 1, 1, id, 2, 1 + FROM `account`.`role` `r` + WHERE `r`.`hasLogin` = 1; + +UPDATE `vn`.`client` SET defaultAddressFk = 1 WHERE id = 101; +UPDATE `vn`.`client` SET defaultAddressFk = 2 WHERE id = 102; +UPDATE `vn`.`client` SET defaultAddressFk = 3 WHERE id = 103; +UPDATE `vn`.`client` SET defaultAddressFk = 4 WHERE id = 104; +UPDATE `vn`.`client` SET defaultAddressFk = 5 WHERE id = 105; +UPDATE `vn`.`client` SET defaultAddressFk = 6 WHERE id = 106; +UPDATE `vn`.`client` SET defaultAddressFk = 7 WHERE id = 107; +UPDATE `vn`.`client` SET defaultAddressFk = 8 WHERE id = 108; +UPDATE `vn`.`client` SET defaultAddressFk = 9 WHERE id = 109; +UPDATE `vn`.`client` SET defaultAddressFk = 10 WHERE id = 110; +UPDATE `vn`.`client` SET defaultAddressFk = 11 WHERE id = 200; +UPDATE `vn`.`client` SET defaultAddressFk = 12 WHERE id = 400; + +DROP TEMPORARY TABLE IF EXISTS tmp.address; + +CREATE TEMPORARY TABLE tmp.address + SELECT * FROM `vn`.`address`; + + UPDATE `vn`.`client` `c` + JOIN `tmp`.`address` `a` ON `a`.`clientFk` = `c`.`id` + SET `c`.`defaultAddressFk` = `a`.`id` + WHERE `defaultAddressFk` IS NULL; +DROP TEMPORARY TABLE tmp.address; + +INSERT INTO `vn`.`clientCredit`(`id`, `clientFk`, `workerFk`, `amount`, `created`) + VALUES + (1 , 101, 5, 300, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (2 , 101, 5, 900, DATE_ADD(CURDATE(), INTERVAL -2 MONTH)), + (3 , 101, 5, 800, DATE_ADD(CURDATE(), INTERVAL -3 MONTH)), + (4 , 101, 5, 700, DATE_ADD(CURDATE(), INTERVAL -4 MONTH)), + (5 , 101, 5, 600, DATE_ADD(CURDATE(), INTERVAL -5 MONTH)), + (6 , 101, 5, 500, DATE_ADD(CURDATE(), INTERVAL -6 MONTH)), + (7 , 101, 5, 400, DATE_ADD(CURDATE(), INTERVAL -7 MONTH)), + (8 , 101, 9, 300, DATE_ADD(CURDATE(), INTERVAL -8 MONTH)), + (9 , 101, 9, 200, DATE_ADD(CURDATE(), INTERVAL -9 MONTH)), + (10, 101, 9, 100, DATE_ADD(CURDATE(), INTERVAL -10 MONTH)), + (11, 101, 9, 50 , DATE_ADD(CURDATE(), INTERVAL -11 MONTH)), + (12, 102, 9, 800, CURDATE()), + (14, 104, 9, 90 , CURDATE()), + (15, 105, 9, 90 , CURDATE()); + +INSERT INTO `vn`.`clientCreditLimit`(`id`, `maxAmount`, `roleFk`) + VALUES + (1, 9999999, 20), + (2, 10000, 21), + (3, 600, 13); + +INSERT INTO `vn`.`clientObservation`(`id`, `clientFk`, `workerFk`, `text`, `created`) + VALUES + (1, 101, 1, 'Madness, as you know, is like gravity, all it takes is a little push', CURDATE()), + (2, 102, 1, 'With great power, comes great responsibility', CURDATE()), + (3, 103, 3, 'this is a job for Super-Man!', CURDATE()), + (4, 104, 3, 'yes... I am Iron-Man', CURDATE()), + (5, 105, 5, 'They do understand. Our mutant powers make us superior', CURDATE()), + (6, 106, 5, 'My name is Legion, for we are many!', CURDATE()), + (7, 107, 9, 'I think our first move should be calling the Avengers..', CURDATE()), + (8, 108, 9, 'Just because someone stumbles and loses their path, does not mean they are lost forever.', CURDATE()), + (9, 109, 18, 'HULK SMASH! ...', CURDATE()), + (10, 110, 18, 'They say everyone is born a hero. But if you let it, life will push you over the line until you are the villain.', CURDATE()); + +INSERT INTO `vn`.`observationType`(`id`,`description`) + VALUES + (1,'observation one'), + (2,'observation two'), + (3,'observation three'), + (4,'comercial'); + +INSERT INTO `vn`.`addressObservation`(`id`,`addressFk`,`observationTypeFk`,`description`) + VALUES + (1, 121, 1, 'under the floor'), + (2, 121, 2, 'wears leather and goes out at night'), + (3, 121, 3, 'care with the dog'); + +INSERT INTO `vn`.`creditClassification`(`id`, `client`, `dateStart`, `dateEnd`) + VALUES + (1, 101, CURDATE(), CURDATE()), + (2, 102, CURDATE(), CURDATE()), + (3, 103, CURDATE(), CURDATE()), + (4, 104, CURDATE(), CURDATE()), + (5, 105, CURDATE(), CURDATE()); + +INSERT INTO `vn`.`creditInsurance`(`id`, `creditClassification`, `credit`, `creationDate`, `grade`) + VALUES + (1, 1, 3000, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), NULL), + (2, 2, 6000, DATE_ADD(CURDATE(), INTERVAL -2 MONTH), NULL), + (3, 3, 10000, DATE_ADD(CURDATE(), INTERVAL -3 MONTH), NULL); + +INSERT INTO `vn`.`companyGroup`(`id`, `code`) + VALUES + (1, 'Wayne Industries'); + +INSERT INTO `vn`.`bankEntity`(`id`, `countryFk`, `name`, `bic`) + VALUES + (128, 1, 'The Best Bank', 'BBKKESMMMMMM'), + (2100, 1, 'Caixa Bank', 'CAIXESBB'); + +INSERT INTO `vn`.`supplierAccount`(`id`, `supplierFk`, `iban`, `bankEntityFk`) + VALUES + (241, 442, 'ES111122333344111122221111', 128); + +INSERT INTO `vn`.`company`(`id`, `code`, `supplierAccountFk`, `workerManagerFk`, `companyCode`, `sage200Company`, `expired`) + VALUES + (69 , 'CCs', NULL, 30, NULL, 0, NULL), + (442 , 'VNL', 241, 30, 2 , 1, NULL), + (567 , 'VNH', NULL, 30, NULL, 4, NULL), + (791 , 'FTH', NULL, 30, NULL, 3, '2015-11-30'), + (1381, 'ORN', NULL, 30, NULL, 7, NULL); + +INSERT INTO `vn`.`invoiceOut`(`id`, `serial`, `amount`, `issued`,`clientFk`, `created`, `companyFk`, `dued`, `booked`, `bankFk`, `hasPdf`) + VALUES + (1, 'T', 1014.24, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 101, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 442, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1, 1), + (2, 'T', 121.36, CURDATE(), 102, CURDATE(), 442, CURDATE(), CURDATE(), 1, 1), + (3, 'T', 8.88, CURDATE(), 103, CURDATE(), 442, CURDATE(), CURDATE(), 1, 1), + (4, 'T', 8.88, CURDATE(), 103, CURDATE(), 442, CURDATE(), CURDATE(), 1, 1), + (5, 'A', 8.88, CURDATE(), 103, CURDATE(), 442, CURDATE(), CURDATE(), 1, 1); + +UPDATE `vn`.`invoiceOut` SET ref = 'T1111111' WHERE id = 1; +UPDATE `vn`.`invoiceOut` SET ref = 'T2222222' WHERE id = 2; +UPDATE `vn`.`invoiceOut` SET ref = 'T3333333' WHERE id = 3; +UPDATE `vn`.`invoiceOut` SET ref = 'T4444444' WHERE id = 4; +UPDATE `vn`.`invoiceOut` SET ref = 'A1111111' WHERE id = 5; + +INSERT INTO `vn`.`invoiceOutTax` (`invoiceOutFk`, `taxableBase`, `vat`, `pgcFk`) + VALUES + (1, 895.76, 89.58, 4722000010), + (1, 33.80, 7.10, 4722000021), + (2, 110.33, 11.03, 4770000010), + (3, 8.07, 0.81, 4770000010), + (4, 8.07, 0.81, 4770000010), + (5, 8.07, 0.81, 4770000010); + +INSERT INTO `vn`.`expence`(`id`, `taxTypeFk`, `name`, `isWithheld`) + VALUES + (2000000000, 1, 'Inmovilizado pendiente', 0), + (2000000000, 3, 'Compra de bienes de inmovilizado', 0), + (4751000000, 0, 'Retenciones', 1), + (4751000000, 1, 'Retenciones', 1), + (4751000000, 6, 'Retencion', 0), + (6210000567, 0, 'Alquiler VNH', 0), + (7001000000, 1, 'Mercaderia', 0); + + + +INSERT INTO `vn`.`invoiceOutExpence`(`id`, `invoiceOutFk`, `amount`, `expenceFk`, `created`) + VALUES + (1, 1, 813.06, 2000000000, CURDATE()), + (2, 1, 33.80, 4751000000, CURDATE()), + (3, 1, 70.70, 6210000567, CURDATE()), + (4, 2, 110.33, 2000000000, CURDATE()), + (5, 3, 8.07, 2000000000, CURDATE()), + (6, 4, 8.07, 2000000000, CURDATE()), + (7, 5, 8.07, 2000000000, CURDATE()); + +INSERT INTO `vn`.`taxArea` (`code`, `claveOperacionFactura`, `CodigoTransaccion`) + VALUES + ('CEE', 1, 10), + ('EQU', 0, 1), + ('NATIONAL', 0, 1), + ('WORLD', 2, 15); + +INSERT INTO `vn`.`invoiceOutSerial` (`code`, `description`, `isTaxed`, `taxAreaFk`, `isCEE`) + VALUES + ('A', 'Global nacional', 1, 'NATIONAL', 0), + ('T', 'Española rapida', 1, 'NATIONAL', 0), + ('V', 'Intracomunitaria global', 0, 'CEE', 1); + +INSERT INTO `vn`.`zone` (`id`, `name`, `hour`, `agencyModeFk`, `travelingDays`, `price`, `bonus`) + VALUES + (1, 'Zone pickup A', CONCAT(CURRENT_DATE(), ' ', TIME('22:00')), 1, 0, 0, 0), + (2, 'Zone pickup B', CONCAT(CURRENT_DATE(), ' ', TIME('22:00')), 1, 0, 0, 0), + (3, 'Zone 247 A', CONCAT(CURRENT_DATE(), ' ', TIME('22:00')), 7, 1, 2, 0), + (4, 'Zone 247 B', CONCAT(CURRENT_DATE(), ' ', TIME('22:00')), 7, 1, 2, 0), + (5, 'Zone expensive A', CONCAT(CURRENT_DATE(), ' ', TIME('22:00')), 8, 1, 1000, 0), + (6, 'Zone expensive B', CONCAT(CURRENT_DATE(), ' ', TIME('22:00')), 8, 1, 1000, 0), + (7, 'Zone refund', CONCAT(CURRENT_DATE(), ' ', TIME('22:00')), 23, 0, 0, 0), + (8, 'Zone others', CONCAT(CURRENT_DATE(), ' ', TIME('22:00')), 10, 0, 0, 0), + (9, 'Zone superMan', CONCAT(CURRENT_DATE(), ' ', TIME('22:00')), 2, 0, 0, 0), + (10, 'Zone teleportation', CONCAT(CURRENT_DATE(), ' ', TIME('22:00')), 3, 0, 0, 0), + (11, 'Zone pickup C', CONCAT(CURRENT_DATE(), ' ', TIME('22:00')), 1, 0, 0, 0), + (12, 'Zone entanglement', CONCAT(CURRENT_DATE(), ' ', TIME('22:00')), 4, 0, 0, 0), + (13, 'Zone quantum break', CONCAT(CURRENT_DATE(), ' ', TIME('22:00')), 5, 0, 0, 0); + +INSERT INTO `vn`.`zoneWarehouse` (`id`, `zoneFk`, `warehouseFk`) + VALUES + (1, 1, 1), + (2, 2, 2), + (3, 3, 1), + (4, 4, 2), + (5, 5, 1), + (6, 6, 2), + (7, 7, 1), + (8, 8, 1), + (9, 9, 1), + (10, 10, 3), + (11, 11, 5), + (12, 12, 4), + (13, 13, 5); + +INSERT INTO `vn`.`route`(`id`, `time`, `workerFk`, `created`, `vehicleFk`, `agencyModeFk`, `description`, `m3`, `cost`, `started`, `finished`, `zoneFk`) + VALUES + (1, '1899-12-30 12:15:00', 56, CURDATE(), 1, 1, 'first route', 1.8, 10, CURDATE(), CURDATE(), 1), + (2, '1899-12-30 13:20:00', 56, CURDATE(), 1, 2, 'second route', 0.2, 20, CURDATE(), CURDATE(), 9), + (3, '1899-12-30 14:30:00', 56, CURDATE(), 2, 3, 'third route', 0.5, 30, CURDATE(), CURDATE(), 10), + (4, '1899-12-30 15:45:00', 56, CURDATE(), 3, 4, 'fourth route', 0, 40, CURDATE(), CURDATE(), 12), + (5, '1899-12-30 16:00:00', 56, CURDATE(), 4, 5, 'fifth route', 0.1, 50, CURDATE(), CURDATE(), 13), + (6, NULL, 57, CURDATE(), 5, 7, 'sixth route', 1.7, 60, CURDATE(), CURDATE(), 3), + (7, NULL, 57, CURDATE(), 6, 8, 'seventh route', 0, 70, CURDATE(), CURDATE(), 5); + +INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeFk`, `shipped`, `landed`, `clientFk`,`nickname`, `addressFk`, `refFk`, `isDeleted`, `zoneFk`, `created`) + VALUES + (1 , 3, 1, 1, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 101, 'Bat cave', 121, 'T1111111', 0, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (2 , 1, 1, 1, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 104, 'Stark tower', 124, 'T1111111', 0, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (3 , 1, 7, 1, 6, DATE_ADD(CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 104, 'Stark tower', 124, 'T2222222', 0, 3, DATE_ADD(CURDATE(), INTERVAL -2 MONTH)), + (4 , 3, 2, 1, 2, DATE_ADD(CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 104, 'Stark tower', 124, 'T3333333', 0, 9, DATE_ADD(CURDATE(), INTERVAL -3 MONTH)), + (5 , 3, 3, 3, 3, DATE_ADD(CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 104, 'Stark tower', 124, 'T4444444', 0, 10, DATE_ADD(CURDATE(), INTERVAL -4 MONTH)), + (6 , 1, 3, 3, 3, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 101, 'Mountain Drive Gotham', 1, 'A1111111', 0, 10, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (7 , NULL, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 101, 'Mountain Drive Gotham', 1, NULL, 0, 3, CURDATE()), + (8 , NULL, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 101, 'Bat cave', 121, NULL, 0, 3, CURDATE()), + (9 , NULL, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 104, 'Stark tower', 124, NULL, 0, 3, CURDATE()), + (10, 1, 1, 5, 1, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 102, 'Ingram Street', 2, NULL, 0, 1, CURDATE()), + (11, 1, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 102, 'NY roofs', 122, NULL, 0, 3, CURDATE()), + (12, 1, 1, 1, 1, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 103, 'Phone Box', 123, NULL, 0, 1, CURDATE()), + (13, 1, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 103, 'Phone Box', 123, NULL, 0, 3, CURDATE()), + (14, 1, 2, 1, NULL, CURDATE(), CURDATE(), 104, 'Malibu Point', 4, NULL, 0, 9, CURDATE()), + (15, 1, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 105, 'Plastic Cell', 125, NULL, 0, 3, CURDATE()), + (16, 1, 7, 1, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 106, 'Many Places', 126, NULL, 0, 3, CURDATE()), + (17, 1, 7, 2, 6, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 106, 'Many Places', 126, NULL, 0, 3, CURDATE()), + (18, 1, 4, 4, 4, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 108, 'Cerebro', 128, NULL, 0, 12, CURDATE()), + (19, 1, 5, 5, 3, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 109, 'Somewhere in Thailand', 129, NULL, 1, 13, CURDATE()), + (20, 1, 5, 5, 3, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 109, 'Somewhere in Thailand', 129, NULL, 0, 13, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (21, NULL, 5, 5, 5, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 109, 'Somewhere in Holland', 102, NULL, 0, 13, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (22, NULL, 5, 5, 5, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 109, 'Somewhere in Japan', 103, NULL, 0, 13, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (23, NULL, 8, 1, 7, CURDATE(), DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 101, 'address 21', 121, NULL, 0, 5, CURDATE()), + (24 ,NULL, 8, 1, 7, CURDATE(), CURDATE(), 101, 'Bruce Wayne', 1, NULL, 0, 5, CURDATE()); + +INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`) + VALUES + (1, 11, 1, 'ready'), + (2, 2, 2, 'do it fast please'), + (3, 3, 3, 'Faster faster fasteeeeeer!!!'), + (4, 4, 3, 'Deliver before 8am'), + (5, 13, 3, 'You can run from the disappointments you are trying to forget. But its only when you embrace your past that you truly move forward. Maybe I never get to go home again, but I found my way there. And I am glad I did.'), + (6, 14, 3, 'Careful, armed warhead'), + (7, 23, 1, 'under the floor'), + (8, 23, 2, 'wears leather and goes out at night'), + (9, 23, 3, 'care with the dog'), + (10, 23, 4, 'Reclama ticket: 8'), + (11, 24, 4, 'Reclama ticket: 7'); + +INSERT INTO `vn`.`ticketTracking`(`id`, `ticketFk`, `stateFk`, `workerFk`, `created`) + VALUES + (1, 1, 16, 5 , DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (2, 2, 16, 5 , DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (3, 3, 16, 5 , DATE_ADD(CURDATE(), INTERVAL -2 MONTH)), + (4, 4, 16, 5 , DATE_ADD(CURDATE(), INTERVAL -3 MONTH)), + (5, 5, 16, 18, DATE_ADD(CURDATE(), INTERVAL -4 MONTH)), + (6, 6, 16, 18, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (7, 7, 10, 18, CURDATE()), + (8, 8, 5, 19, CURDATE()), + (9, 9, 5, 19, CURDATE()), + (10, 10, 5, 19, CURDATE()), + (11, 11, 3, 19, CURDATE()), + (12, 12, 3, 19, CURDATE()), + (13, 13, 3, 19, CURDATE()), + (14, 14, 3, 19, CURDATE()), + (15, 15, 3, 19, CURDATE()), + (16, 16, 3, 19, CURDATE()), + (17, 17, 3, 19, CURDATE()), + (18, 18, 3, 19, CURDATE()), + (19, 19, 17, 19, CURDATE()), + (20, 20, 1, 19, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (21, 21, 1, 19, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (22, 22, 1, 19, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (23, 23, 16, 21, CURDATE()), + (24, 24, 16, 21, CURDATE()); + +INSERT INTO `vn`.`stowaway`(`id`, `shipFk`, `created`) + VALUES + (12, 13, CURDATE()); + +INSERT INTO `vn`.`deliveryPoint` (`id`, `name`, `ubication`) + VALUES + (1, 'Silla','46460 Av Espioca 100-Silla'); + +INSERT INTO `vn`.`vehicle`(`id`, `numberPlate`, `tradeMark`, `model`, `companyFk`, `warehouseFk`, `description`, `m3`, `isActive`, `deliveryPointFk`) + VALUES + (1, '3333-BAT', 'WAYNE INDUSTRIES', 'BATMOBILE', 442, 1, 'The ultimate war machine', 50, 1, 1), + (2, '1111-IMK', 'STARK INDUSTRIES', 'MARK-III', 442, 1, 'Iron-Man Heavy Armor MARK-III', 18, 1, 1), + (3, '2222-IMK', 'STARK INDUSTRIES', 'MARK-VI', 442, 1, 'Iron-Man Heavy Armor MARK-VI', 16, 1, 1), + (4, '3333-IMK', 'STARK INDUSTRIES', 'MARK-VII', 442, 1, 'Iron-Man Heavy Armor MARK-VII', 14, 1, 1), + (5, '4444-IMK', 'STARK INDUSTRIES', 'MARK-XLII', 442, 1, 'Iron-Man Heavy Armor MARK-XLII', 13, 1, 1), + (6, '5555-IMK', 'STARK INDUSTRIES', 'MARK-XLV', 442, 1, 'Iron-Man Heavy Armor MARK-XLV', 12, 0, 1); + +INSERT INTO `vn`.`config`(`id`, `mdbServer`, `fakeEmail`, `defaultersMaxAmount`, `inventoried`) + VALUES + (1, 'beta-server', 'nightmare@mydomain.com', '200', DATE_ADD(CURDATE(),INTERVAL -1 MONTH)); + +INSERT INTO `vn`.`greugeType`(`id`, `name`, `code`) + VALUES + (1, 'Diff', 'diff'), + (2, 'Recover', 'recover'), + (3, 'Mana', 'mana'), + (4, 'Reclaim', 'reclaim'), + (5, 'Heritage', 'heritage'), + (6, 'Miscellaneous', 'miscellaneous'); + +INSERT INTO `vn`.`greuge`(`id`, `clientFk`, `description`, `amount`, `shipped`, `created`, `greugeTypeFk`, `ticketFk`) + VALUES + (1, 101, 'some diff charges', -19.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 1, 1), + (2, 101, 'more diff charges', 60, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 2, 1), + (3, 101, 'even more! diff charges', -9.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 3, 1), + (4, 101, 'insane diff charges', 60, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 4, 1), + (5, 101, 'gargantuous diff charges', -9.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 5, 1), + (6, 101, 'diff charges', 88.30, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 6, 1), + (7, 101, 'unaffordable diff charges', -39.12, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 1, 1), + (8, 101, 'some recovery charges', 29.35, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 2, 1), + (9, 101, 'some manna charges', -9.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 3, 1), + (10, 101, 'some claim charges', 13.13, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 4, 1), + (11, 101, 'some heritage charges', -15.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 5, 1), + (12, 101, 'some miscellaneous charges', 58.00, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 6, 1); + +INSERT INTO `vn`.`mandateType`(`id`, `name`) + VALUES + (1, 'B2B'), + (2, 'CORE'), + (3, 'LCR'); + +INSERT INTO `vn`.`mandate`(`id`, `clientFk`, `companyFk`, `code`, `created`, `mandateTypeFk`) + VALUES + (1, 102, 442, '1-1', CURDATE(), 2); + +INSERT INTO `vn`.`itemCategory`(`id`, `name`, `display`, `color`, `icon`, `code`) + VALUES + (1, 'Plant', 1, 'B92A26', 'icon-plant', 'plant'), + (2, 'Flower', 2, 'dcf711', 'icon-flower', 'flower'), + (3, 'Logistic', 0, 'b9f711', NULL, 'logistical'), + (4, 'Handmade', 1, NULL, 'icon-handmade', 'handmade'), + (5, 'Artificial', 1, NULL, 'icon-artificial', 'artificial'), + (6, 'Green', 1, NULL, 'icon-greenery', 'greenery'), + (7, 'Accessories', 1, NULL, 'icon-accessory', 'accessory'), + (8, 'Fruit', 1, NULL, 'icon-fruit', 'fruit'); + +INSERT INTO `vn`.`itemType`(`id`, `code`, `name`, `categoryFk`, `life`,`workerFk`, `isPackaging`) + VALUES + (1, 'CRI', 'Crisantemo', 2, 31, 5, 0), + (2, 'ITG', 'Anthurium', 1, 31, 5, 0), + (3, 'WPN', 'Paniculata', 2, 31, 5, 0), + (4, 'PRT', 'Delivery ports', 3, NULL, 5, 1), + (5, 'CON', 'Container', 3, NULL, 5, 1); + +INSERT INTO `vn`.`ink`(`id`, `name`, `picture`, `showOrder`) + VALUES + ('YEL', 'Yellow', 1, 1), + ('BLU', 'Blue', 1, 2), + ('RED', 'Red', 1, 3); + +INSERT INTO `vn`.`origin`(`id`,`code`, `name`) + VALUES + (1, 'SPA', 'Spain'), + (2, 'HOL', 'Holand'), + (3, 'VLC', 'Valencia'); + +INSERT INTO `vn`.`producer`(`id`, `name`) + VALUES + (1, 'Marvel Studios'), + (2, 'Nordic Mythology'); + +INSERT INTO `vn`.`taxType`(`id`, `nickname`, `isAccrued`, `serial`, `TIPOOPE`, `description`, `countryFk`) + VALUES + (1, 'National', 1, 'R', 'I', 'national VAT', 1), + (2, 'European', 0, 'E', 'I', 'europe VAT', 1); + +INSERT INTO `vn`.`taxCode`(`id`, `dated`, `code`, `taxTypeFk`, `rate`, `equalizationTax`, `type`, `link`, `isActive`, `updated`, `transactionCode`) + VALUES + (1 , CURDATE(), '1111111111', 1, 7.0 , 0.0, 'R', 1, 1, CURDATE(), 1), + (2 , CURDATE(), '2222222222', 2, 16.0, 0.0, 'G', 2, 1, CURDATE(), 1), + (21 , CURDATE(), '3333333333', 1, 7.0, 0.0, 'R', 3, 1, CURDATE(), 1), + (108, CURDATE(), '4444444444', 2, 8.0 , 0.0, 'R', 4, 1, CURDATE(), 1); + +INSERT INTO `vn`.`taxClass`(`id`, `description`, `code`) + VALUES + (1, 'Reduced VAT','R'), + (2, 'General VAT', 'G'); + +INSERT INTO `vn`.`intrastat`(`id`, `description`, `taxClassFk`, `taxCodeFk`) + VALUES + (05080000, 'Coral y materiales similares', 2, 2), + (06021010, 'Plantas vivas: Esqueje/injerto, Vid', 1, 1); + +INSERT INTO `vn`.`item`(`id`, `typeFk`, `size`, `inkFk`, `stems`, `originFk`, `description`, `producerFk`, `intrastatFk`, `isOnOffer`, `expenceFk`, `isBargain`, `comment`, `relevancy`, `image`, `taxClassFk`, `subName`) + VALUES + (1, 2, 70, 'AMA', 1, 1, NULL, 1, 06021010, 0, 2000000000, 0, NULL, 0, 66540, 1, NULL), + (2, 2, 70, 'AZL', 1, 2, NULL, 1, 06021010, 0, 2000000000, 0, NULL, 0, 65540, 1, NULL), + (3, 1, 60, 'AMR', 1, 3, NULL, 1, 05080000, 0, 4751000000, 0, NULL, 0, 61692, 1, NULL), + (4, 1, 60, 'AMR', 1, 1, NULL, 1, 05080000, 1, 4751000000, 0, NULL, 0, 66090, 2, NULL), + (5, 3, 30, 'GRE', 1, 2, NULL, 2, 06021010, 1, 4751000000, 0, NULL, 0, 67350, 2, NULL), + (6, 5, 30, 'GRE', 1, 2, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, 67350, 2, NULL), + (7, 5, 90, 'AZL', 1, 2, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, 67350, 2, NULL), + (8, 2, 70, 'AMA', 1, 1, NULL, 1, 06021010, 0, 2000000000, 0, NULL, 0, 66540, 1, NULL), + (9, 2, 70, 'AZL', 1, 2, NULL, 1, 06021010, 0, 2000000000, 0, NULL, 0, 65540, 1, NULL), + (10, 1, 60, 'AMR', 1, 3, NULL, 1, 05080000, 0, 4751000000, 0, NULL, 0, 61692, 1, NULL), + (11, 1, 60, 'AMR', 1, 1, NULL, 1, 05080000, 1, 4751000000, 0, NULL, 0, 66090, 2, NULL), + (12, 3, 30, 'GRE', 1, 2, NULL, 2, 06021010, 1, 4751000000, 0, NULL, 0, 67350, 2, NULL), + (13, 5, 30, 'GRE', 1, 2, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, 67350, 2, NULL), + (14, 5, 90, 'AZL', 1, 2, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, 67350, 2, NULL), + (15, 4, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, 67350, 2, NULL), + (16, 4, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 0, 4751000000, 0, NULL, 0, 67350, 2, NULL), + (71, 4, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 1, 4751000000, 0, NULL, 0, 67350, 2, NULL); + +INSERT INTO `vn`.`expedition`(`id`, `agencyModeFk`, `ticketFk`, `isBox`, `created`, `itemFk`, `counter`, `checked`, `workerFk`) + VALUES + (1, 1, 1, 71, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1, 1, 1, 18), + (2, 1, 1, 71, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1, 2, 1, 18), + (3, 1, 1, 71, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 2, 3, 1, 18), + (4, 1, 1, 71, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 4, 4, 1, 18), + (5, 1, 2, 71, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1, 1, 1, 18), + (6, 7, 3, 71, DATE_ADD(CURDATE(), INTERVAL -2 MONTH), 1, 1, 1, 18), + (7, 2, 4, 71, DATE_ADD(CURDATE(), INTERVAL -3 MONTH), 1, 1, 1, 18), + (8, 3, 5, 71, DATE_ADD(CURDATE(), INTERVAL -4 MONTH), 1, 1, 1, 18), + (9, 3, 6, 71, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1, 1, 1, 18), + (10, 7, 7, 71, CURDATE(), 1, 1, 1, 18); + +INSERT INTO `vn`.`packaging`(`id`, `volume`, `width`, `height`, `depth`, `isPackageReturnable`, `created`, `itemFk`, `price`) + VALUES + (1, 0.00, 10, 10, 0, 1, CURDATE(), 6, 1.50), + (2, 100.00, 20, 20, 0, 1, CURDATE(), 7, 1.00), + (3, 14000.00, 0, 0, 0, 1, CURDATE(), NULL, 0), + (4, 218000.00, 0, 0, 0, 0, CURDATE(), NULL, 0), + (5, 292000.00, 0, 0, 0, 0, CURDATE(), NULL, 0), + (94, 140875.00, 49.00, 115.00, 25.00, 0, CURDATE(), 71, 0.00), + ('cc', 1640038.00, 56.00, 220.00, 128.00, 1, CURDATE(), 15, 90.00), + ('pallet 100', 2745600.00, 100.00, 220.00, 120.00, 1, CURDATE(), 16, 0.00); + +INSERT INTO `vn`.`ticketPackaging`(`id`, `ticketFk`, `packagingFk`, `quantity`, `created`, `pvp`) + VALUES + (1, 1, 2, 2, CURDATE(), NULL), + (2, 2, 2, 1, CURDATE(), NULL), + (3, 3, 2, 4, CURDATE(), NULL); + +INSERT INTO `vn`.`sale`(`id`, `itemFk`, `ticketFk`, `concept`, `quantity`, `price`, `discount`, `reserved`, `isPicked`, `created`) + VALUES + (1, 1, 1, 'Ranged weapon longbow 2m', 5, 100.39, 0, 0, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (2, 2, 1, 'Melee weapon combat fist 15cm', 10, 7.07, 0, 0, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (3, 1, 1, 'Ranged weapon longbow 2m', 2, 100.39, 0, 0, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (4, 4, 1, 'Melee weapon heavy shield 1x0.5m', 20, 1.69, 0, 0, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (5, 1, 2, 'Ranged weapon longbow 2m', 1, 110.33, 0, 0, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (6, 1, 3, 'Ranged weapon longbow 2m', 1, 110.33, 0, 0, 0, DATE_ADD(CURDATE(), INTERVAL -2 MONTH)), + (7, 2, 11, 'Melee weapon combat fist 15cm', 15, 7.44, 0, 0, 0, CURDATE()), + (8, 4, 11, 'Melee weapon heavy shield 1x0.5m', 10, 1.79, 0, 0, 0, CURDATE()), + (9, 1, 16, 'Ranged weapon longbow 2m', 1, 103.49, 0, 0, 0, CURDATE()), + (10, 2, 16, 'Melee weapon combat fist 15cm', 10, 7.08, 0, 0, 0, CURDATE()), + (11, 1, 16, 'Ranged weapon longbow 2m', 1, 103.49, 0, 0, 0, CURDATE()), + (12, 4, 16, 'Melee weapon heavy shield 1x0.5m', 20, 1.71, 0, 0, 0, CURDATE()), + (13, 2, 8, 'Melee weapon combat fist 15cm', 10, 7.08, 0, 0, 0, CURDATE()), + (14, 1, 8, 'Ranged weapon longbow 2m', 2, 103.49, 0, 0, 0, CURDATE()), + (15, 1, 19, 'Ranged weapon longbow 2m', 1, 103.49, 0, 0, 0, CURDATE()), + (16, 2, 20, 'Melee weapon combat fist 15cm', 20, 7.07, 0, 0, 0, CURDATE()), + (17, 2, 22, 'Melee weapon combat fist 15cm', 30, 7.07, 0, 0, 0, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (18, 4, 22, 'Melee weapon heavy shield 1x0.5m', 20, 1.69, 0, 0, 0, DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (19, 1, 4, 'Ranged weapon longbow 2m', 1, 8.07, 0, 0, 0, DATE_ADD(CURDATE(), INTERVAL -3 MONTH)), + (20, 1, 5, 'Ranged weapon longbow 2m', 1, 8.07, 0, 0, 0, DATE_ADD(CURDATE(), INTERVAL -4 MONTH)), + (21, 1, 6, 'Ranged weapon longbow 2m', 1, 8.07, 0, 0, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (22, 1, 7, 'Ranged weapon longbow 2m', 1, 8.07, 0, 0, 0, CURDATE()), + (23, 1, 9, 'Ranged weapon longbow 2m', 1, 8.07, 0, 0, 0, CURDATE()), + (24, 1, 10, 'Ranged weapon longbow 2m', 1, 8.07, 0, 0, 0, CURDATE()), + (25, 4, 12, 'Melee weapon heavy shield 1x0.5m', 20, 1.72, 0, 0, 0, CURDATE()), + (26, 4, 13, 'Melee weapon heavy shield 1x0.5m', 20, 1.72, 0, 0, 0, CURDATE()), + (27, 4, 14, 'Melee weapon heavy shield 1x0.5m', 20, 1.72, 0, 0, 0, CURDATE()), + (28, 4, 15, 'Melee weapon heavy shield 1x0.5m', 20, 1.72, 0, 0, 0, CURDATE()), + (29, 4, 17, 'Melee weapon heavy shield 1x0.5m', 20, 1.72, 0, 0, 0, CURDATE()), + (30, 4, 18, 'Melee weapon heavy shield 1x0.5m', 20, 1.72, 0, 0, 0, CURDATE()), + (31, 2, 23, 'Melee weapon combat fist 15cm', -5, 7.08, 0, 0, 0, CURDATE()), + (32, 1, 24, 'Ranged weapon longbow 2m', -1, 8.07, 0, 0, 0, CURDATE()); + +INSERT INTO `vn`.`saleChecked`(`saleFk`, `isChecked`) + VALUES + (1, 0), + (2, 1); + +INSERT INTO `vn`.`saleComponent`(`saleFk`, `componentFk`, `value`) + VALUES + (1, 28, 50), + (1, 29, 49.4), + (1, 39, 0.994), + (2, 28, 5), + (2, 29, 2), + (2, 39, 0.07), + (3, 28, 50), + (3, 29, 49.4), + (3, 39, 0.994), + (4, 28, 1.25), + (4, 29, 0.42), + (4, 39, 0.017), + (5, 17, 9.94), + (5, 28, 50), + (5, 29, 49.4), + (5, 39, 0.994), + (6, 17, 9.94), + (6, 28, 50), + (6, 29, 49.4), + (6, 39, 0.994), + (7, 15, 0.0199), + (7, 17, 0.35), + (7, 28, 5), + (7, 29, 2), + (7, 39, 0.07), + (8, 15, 0.0199), + (8, 17, 0.084), + (8, 28, 1.25), + (8, 29, 0.42), + (8, 39, 0.017), + (9, 15, 3.0949), + (9, 21, 0.001), + (9, 28, 50), + (9, 29, 49.4), + (9, 39, 0.994), + (10, 15, 0.0111), + (10, 21, -0.001), + (10, 28, 5), + (10, 29, 2), + (10, 39, 0.07), + (11, 15, 3.0949), + (11, 21, 0.001), + (11, 28, 50), + (11, 29, 49.4), + (11, 39, 0.994), + (12, 15, 0.0199), + (12, 21, 0.003), + (12, 28, 1.25), + (12, 29, 0.42), + (12, 39, 0.017), + (13, 15, 0.114), + (13, 28, 5), + (13, 29, 2), + (13, 39, 0.07), + (14, 15, 3.0949), + (14, 28, 50), + (14, 29, 49.4), + (14, 39, 0.994), + (15, 15, 3.0949), + (15, 28, 50), + (15, 29, 49.4), + (15, 39, 0.994), + (16, 28, 5), + (16, 29, 2), + (16, 39, 0.07), + (17, 28, 5), + (17, 29, 2), + (17, 39, 0.07), + (18, 28, 1.25), + (18, 29, 0.42), + (18, 39, 0.017), + (19, 17, 0.7), + (19, 22, 0.3), + (19, 28, 5), + (19, 29, 2), + (19, 39, 0.02), + (20, 17, 0.7), + (20, 22, 0.3), + (20, 28, 5), + (20, 29, 2), + (20, 39, 0.02), + (21, 17, 0.7), + (21, 22, 0.3), + (21, 28, 5), + (21, 29, 2), + (21, 39, 0.02), + (22, 17, 0.7), + (22, 22, 0.3), + (22, 28, 5), + (22, 29, 2), + (22, 39, 0.02), + (23, 17, 0.7), + (23, 22, 0.3), + (23, 28, 5), + (23, 29, 2), + (23, 39, 0.02), + (24, 17, 0.7), + (24, 22, 0.3), + (24, 28, 5), + (24, 29, 2), + (24, 39, 0.02), + (25, 17, 0.033), + (25, 28, 1.25), + (25, 29, 0.42), + (25, 39, 0.017), + (26, 17, 0.033), + (26, 28, 1.25), + (26, 29, 0.42), + (26, 39, 0.017), + (27, 17, 0.033), + (27, 28, 1.25), + (27, 29, 0.42), + (27, 39, 0.017), + (28, 17, 0.033), + (28, 28, 1.25), + (28, 29, 0.42), + (28, 39, 0.017), + (29, 17, 0.033), + (29, 28, 1.25), + (29, 29, 0.42), + (29, 39, 0.017), + (30, 17, 0.033), + (30, 28, 1.25), + (30, 29, 0.42), + (30, 39, 0.017), + (31, 28, 5), + (31, 29, 2), + (31, 36, 0.01), + (31, 39, 0.07), + (32, 28, 50), + (32, 29, 49.4), + (32, 36, -92.324), + (32, 39, 0.994); + +INSERT INTO `vncontrol`.`accion`(`accion_id`, `accion`) + VALUES + (3, 'ACTION ONE'), + (4, 'ACTIOn TWO'); + +INSERT INTO `vn`.`saleTracking`(`saleFk`, `isChecked`, `created`, `originalQuantity`, `workerFk`, `actionFk`, `id`, `stateFk`) + VALUES + (1, 0, CURDATE(), 5, 55, 3, 1, 14), + (1, 1, CURDATE(), 5, 54, 3, 2, 8), + (2, 1, CURDATE(), 10, 40, 4, 3, 8), + (3, 1, CURDATE(), 2, 40, 4, 4, 8); + +INSERT INTO `vn`.`itemBarcode`(`id`, `itemFk`, `code`) + VALUES + (1, 1, 1111111111), + (2, 1, 2222222222), + (3, 1, 3333333333), + (4, 2, 4444444444); + +INSERT INTO `vn`.`itemPlacement`(`id`, `itemFk`, `warehouseFk`, `code`) + VALUES + (1, 1, 1, 'A1'), + (2, 1, 2, 'A2'), + (3, 1, 3, 'A3'), + (4, 2, 1, 'A4'); + +INSERT INTO `edi`.`genus`(`genus_id`, `latin_genus_name`, `entry_date`, `expiry_date`, `change_date_time`) + VALUES + (1, 'Abelia' , CURDATE(), NULL, CURDATE()), + (2, 'Abies', CURDATE(), NULL, CURDATE()), + (3, 'Abutilon', CURDATE(), NULL, CURDATE()); + +INSERT INTO `edi`.`specie`(`specie_id`, `genus_id`, `latin_species_name`, `entry_date`, `expiry_date`, `change_date_time`) + VALUES + (1, 1, 'grandiflora', CURDATE(), NULL, CURDATE()), + (2, 2, 'procera', CURDATE(), NULL, CURDATE()), + (3, 3, 'decurrens', CURDATE(), NULL, CURDATE()), + (4, 3, 'dealbata', CURDATE(), NULL, CURDATE()); + +INSERT INTO `vn`.`itemBotanical`(`itemFk`, `botanical`, `genusFk`, `specieFk`) + VALUES + (1, 'Hedera helix', 1, 1), + (2, NULL, 2, 2), + (3, 'Cycas revoluta', 2, NULL), + (4, 'Polygonum', NULL, NULL); + +INSERT INTO `vn`.`itemTag`(`id`,`itemFk`,`tagFk`,`value`,`priority`) + VALUES + (1 , 1, 56, 'Ranged weapon', 1), + (2 , 1, 58, 'longbow', 2), + (3 , 1, 27, '2m', 3), + (4 , 1, 36, 'Stark Industries', 4), + (5 , 1, 1, 'Brown', 5), + (6 , 1, 67, '+1 precission', 6), + (7 , 1, 23, '1', 7), + (8 , 2, 56, 'Melee weapon', 1), + (9 , 2, 58, 'combat fist', 2), + (10, 2, 27, '15cm', 3), + (11, 2, 36, 'Stark Industries', 4), + (12, 2, 1, 'Silver', 5), + (13, 2, 67, 'concussion', 6), + (14, 2, 23, '1', 7), + (15, 3, 56, 'Ranged weapon', 1), + (16, 3, 58, 'sniper rifle', 2), + (17, 3, 4, '300mm', 3), + (18, 3, 36, 'Stark Industries', 4), + (19, 3, 1, 'Green', 5), + (20, 3, 67, 'precission', 6), + (21, 3, 23, '1', 7), + (22, 4, 56, 'Melee weapon', 1), + (23, 4, 58, 'heavy shield', 2), + (24, 4, 4, '1x0.5m', 3), + (25, 4, 36, 'Stark Industries', 4), + (26, 4, 1, 'Black', 5), + (27, 4, 67, 'containtment', 6), + (28, 4, 23, '1', 7), + (29, 5, 56, 'Ranged weapon', 1), + (30, 5, 58, 'pistol', 2), + (31, 5, 27, '9mm', 3), + (32, 5, 36, 'Stark Industries', 4), + (33, 5, 1, 'Silver', 5), + (34, 5, 67, 'rapid fire', 6), + (35, 5, 23, '1', 7), + (36, 6, 56, 'Container', 1), + (37, 6, 58, 'ammo box', 2), + (38, 6, 27, '1m', 3), + (39, 6, 36, 'Stark Industries', 4), + (40, 6, 1, 'Green', 5), + (41, 6, 67, 'supply', 6), + (42, 6, 23, '1', 7), + (43, 7, 56, 'Container', 1), + (44, 7, 58, 'medical box', 2), + (45, 7, 27, '1m', 3), + (46, 7, 36, 'Stark Industries', 4), + (47, 7, 1, 'White', 5), + (48, 7, 67, 'supply', 6), + (49, 7, 23, '1', 7), + (50, 8, 56, 'Ranged Reinforced weapon', 1), + (51, 8, 58, '+1 longbow', 2), + (52, 8, 27, '2m', 3), + (53, 8, 36, 'Stark Industries', 4), + (54, 8, 1, 'Brown', 5), + (55, 8, 67, 'precission', 6), + (56, 8, 23, '1', 7), + (57, 9, 56, 'Melee Reinforced weapon', 1), + (58, 9, 58, 'combat fist', 2), + (59, 9, 27, '15cm', 3), + (60, 9, 36, 'Stark Industries', 4), + (61, 9, 1, 'Silver', 5), + (62, 9, 67, 'concussion', 6), + (63, 9, 23, '1', 7), + (64, 10, 56, 'Ranged Reinforced weapon', 1), + (65, 10, 58, 'sniper rifle', 2), + (66, 10, 4, '300mm', 3), + (67, 10, 36, 'Stark Industries', 4), + (68, 10, 1, 'Green', 5), + (69, 10, 67, 'precission', 6), + (70, 10, 23, '1', 7), + (71, 11, 56, 'Melee Reinforced weapon', 1), + (72, 11, 58, 'heavy shield', 2), + (73, 11, 4, '1x0.5m', 3), + (74, 11, 36, 'Stark Industries', 4), + (75, 11, 1, 'Black', 5), + (76, 11, 67, 'containtment', 6), + (77, 11, 23, '1', 7), + (78, 12, 56, 'Ranged Reinforced weapon', 1), + (79, 12, 58, 'pistol', 2), + (80, 12, 27, '9mm', 3), + (81, 12, 36, 'Stark Industries', 4), + (82, 12, 1, 'Silver', 5), + (83, 12, 67, 'rapid fire', 6), + (84, 12, 23, '1', 7), + (85, 13, 56, 'Chest', 1), + (86, 13, 58, 'ammo box', 2), + (87, 13, 27, '1m', 3), + (88, 13, 36, 'Stark Industries', 4), + (89, 13, 1, 'Green', 5), + (90, 13, 67, 'supply', 6), + (91, 13, 23, '1', 7), + (92, 14, 56, 'Chest', 1), + (93, 14, 58, 'medical box', 2), + (94, 14, 27, '1m', 3), + (95, 14, 36, 'Stark Industries', 4), + (96, 14, 1, 'White', 5), + (97, 14, 67, 'supply', 6), + (98, 14, 23, '1', 7), + (99, 71, 92, 'Shipping cost', 2); + +INSERT INTO `vn`.`itemTypeTag`(`id`, `itemTypeFk`, `tagFk`, `priority`) + VALUES + (1, 1, 1, 0), + (2, 2, 2, 0), + (3, 3, 3, 1), + (4, 1, 4, 1), + (5, 1, 5, 1); + +CALL `vn`.`itemRefreshTags`(NULL); + +INSERT INTO `vn`.`itemLog` (`id`, `originFk`, `userFk`, `action`, `description`) + VALUES + ('1', '1', '1', 'insert', 'We made a change!'); + +INSERT INTO `vn`.`recovery`(`id`, `clientFk`, `started`, `finished`, `amount`, `period`) + VALUES + (1, 101, DATE_ADD(CURDATE(),INTERVAL -7 MONTH), DATE_ADD(CURDATE(),INTERVAL -3 MONTH), 50, 7), + (2, 102, DATE_ADD(CURDATE(),INTERVAL -5 MONTH), CURDATE(), 100, 1), + (3, 102, CURDATE(), DATE_ADD(CURDATE(),INTERVAL 1 MONTH), 50, 7), + (4, 103, CURDATE(), NULL, 50, 7); + +INSERT INTO `vn`.`annualAverageInvoiced`(`clientFk`, `invoiced`) + VALUES + (101, 1500), + (102, 100), + (103, 1000), + (104, 500), + (105, 5000); + +INSERT INTO `vn`.`supplier`(`id`, `name`,`account`,`countryFk`,`nif`,`isFarmer`,`retAccount`,`commission`, `created`, `postcodeFk`, `isActive`, `street`, `city`, `provinceFk`, `postCode`, `payMethodFk`, `payDemFk`) + VALUES + (1, 'Plants SL', 4000000001, 1, 'A11111111', 0, NULL, 0, CURDATE(), 1111, 1, 'supplier address 1', 'PONTEVEDRA', 1, 15214, 1, 1), + (2, 'Flower King', 4000000002, 1, 'B22222222', 0, NULL, 0, CURDATE(), 2222, 1, 'supplier address 2', 'LONDON', 2, 45671, 1, 2), + (442, 'Verdnatura Levante SL', 4000000442, 1, 'C33333333', 0, NULL, 0, CURDATE(), 3333, 1, 'supplier address 3', 'SILLA', 1, 43022, 1, 2); + +INSERT INTO `cache`.`cache_calc`(`id`, `cache_id`, `cacheName`, `params`, `last_refresh`, `expires`, `created`, `connection_id`) + VALUES + (1, 2, 'available', CONCAT_WS('/',1,CURDATE()), CURRENT_TIMESTAMP(), DATE_ADD(CURRENT_TIMESTAMP(),INTERVAL 15 MINUTE), CURDATE(), NULL), + (2, 4, 'last_buy', CONCAT_WS('/',1,CURDATE()), CURRENT_TIMESTAMP(), DATE_ADD(CURRENT_TIMESTAMP(),INTERVAL 15 MINUTE), CURDATE(), NULL), + (3, 8, 'visible', CONCAT_WS('/',1,CURDATE()), CURRENT_TIMESTAMP(), DATE_ADD(CURRENT_TIMESTAMP(),INTERVAL 15 MINUTE), CURDATE(), NULL); + +INSERT INTO `vn`.`ticketWeekly`(`ticketFk`, `weekDay`) + VALUES + (1, 0), + (2, 1), + (3, 2), + (4, 4), + (5, 6); + +INSERT INTO `vn`.`travel`(`id`,`shipped`, `landed`, `warehouseInFk`, `warehouseOutFk`, `agencyFk`, `m3`, `kg`,`ref`, `totalEntries`) + VALUES + (1, DATE_ADD(CURDATE(), INTERVAL -2 MONTH), DATE_ADD(CURDATE(), INTERVAL -2 MONTH), 1, 2, 1, 100.00, 1000, 'first travel', 1), + (2, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1, 2, 1, 150, 2000, 'second travel', 2), + (3, CURDATE(), CURDATE(), 1, 2, 1, 0.00, 0.00, 'third travel', 1), + (4, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1, 2, 1, 50.00, 500, 'fourth travel', 0), + (5, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 3, 2, 1, 50.00, 500, 'fifth travel', 1), + (6, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 4, 2, 1, 50.00, 500, 'sixth travel', 1), + (7, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 5, 2, 1, 50.00, 500, 'seventh travel', 1); + +INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `companyFk`, `ref`, `notes`, `evaNotes`) + VALUES + (1, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1, 442, 'Movement 1', 'this is the note one', 'observation one'), + (2, 2, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 2, 442, 'Movement 2', 'this is the note two', 'observation two'), + (3, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 3, 442, 'Movement 3', 'this is the note three', 'observation three'), + (4, 2, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 2, 69, 'Movement 4', 'this is the note four', 'observation four'), + (5, 2, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 5, 442, 'Movement 5', 'this is the note five', 'observation five'), + (6, 2, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 6, 442, 'Movement 6', 'this is the note six', 'observation six'), + (7, 2, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 7, 442, 'Movement 7', 'this is the note seven', 'observation seven'); + +INSERT INTO `bi`.`claims_ratio`(`id_Cliente`, `Consumo`, `Reclamaciones`, `Ratio`, `recobro`, `inflacion`) + VALUES + (101, 500, NULL, 0.00, 0.00, 1.00), + (102, 1000, 2.00, 0.01, 0.05, 1.00), + (103, 2000, 0.00, 0.00, 0.02, 1.00), + (104, 2500, 150.00, 0.02, 0.10, 1.00); + +INSERT INTO `bs`.`waste`(`buyer`, `year`, `week`, `family`, `saleTotal`, `saleWaste`, `rate`) + VALUES + ('CharlesXavier', YEAR(CURDATE()), WEEK(CURDATE(), 1), 'Clavel', '1062', '51', '4.8'), + ('CharlesXavier', YEAR(CURDATE()), WEEK(CURDATE(), 1), 'Clavel Colombia', '35074', '687', '2.0'), + ('CharlesXavier', YEAR(CURDATE()), WEEK(CURDATE(), 1), 'Clavel Mini', '1777', '13', '0.7'), + ('CharlesXavier', YEAR(CURDATE()), WEEK(CURDATE(), 1), 'Clavel Short', '9182', '59', '0.6'), + ('DavidCharlesHaller', YEAR(CURDATE()), WEEK(CURDATE(), 1), 'Contenedores', '-74', '0', '0.0'), + ('DavidCharlesHaller', YEAR(CURDATE()), WEEK(CURDATE(), 1), 'Embalajes', '-7', '0', '0.0'), + ('DavidCharlesHaller', YEAR(CURDATE()), WEEK(CURDATE(), 1), 'Portes', '1100', '0', '0.0'), + ('HankPym', YEAR(CURDATE()), WEEK(CURDATE(), 1), 'Accesorios Funerarios', '848', '-187', '-22.1'), + ('HankPym', YEAR(CURDATE()), WEEK(CURDATE(), 1), 'Accesorios Varios', '186', '0', '0.0'), + ('HankPym', YEAR(CURDATE()), WEEK(CURDATE(), 1), 'Adhesivos', '277', '0', '0.0'); + +INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packageFk`,`stickers`,`freightValue`,`packageValue`,`comissionValue`,`packing`,`grouping`,`groupingMode`,`location`,`price1`,`price2`,`price3`,`minPrice`,`producer`,`printedStickers`,`isChecked`,`isIgnored`, `created`) + VALUES + (1, 1, 1, 50, 5000, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0.00, NULL, 0, 1, 0, DATE_ADD(CURDATE(), INTERVAL -2 MONTH)), + (2, 2, 1, 50, 100, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0.00, NULL, 0, 1, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (3, 3, 1, 50, 100, 4, 1, 1.500, 1.500, 0.000, 1, 1, 0, NULL, 0.00, 99.6, 99.4, 0.00, NULL, 0, 1, 0, CURDATE()), + (4, 2, 2, 5, 450, 3, 1, 1.000, 1.000, 0.000, 10, 10, 0, NULL, 0.00, 7.30, 7.00, 0.00, NULL, 0, 1, 0, CURDATE()), + (5, 3, 3, 55, 500, 5, 1, 1.000, 1.000, 0.000, 1, 1, 0, NULL, 0.00, 78.3, 75.6, 0.00, NULL, 0, 1, 0, CURDATE()), + (6, 4, 8, 50, 1000, 4, 1, 1.000, 1.000, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0.00, NULL, 0, 1, 0, CURDATE()), + (7, 4, 9, 20, 1000, 3, 1, 0.500, 0.500, 0.000, 10, 10, 1, NULL, 0.00, 30.50, 29.00, 0.00, NULL, 0, 1, 0, CURDATE()), + (8, 4, 4, 1.25, 1000, 3, 1, 0.500, 0.500, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, 0.00, NULL, 0, 1, 0, CURDATE()), + (9, 4, 4, 1.25, 1000, 3, 1, 0.500, 0.500, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, 0.00, NULL, 0, 1, 0, CURDATE()), + (10, 5, 1, 50, 10, 4, 1, 2.500, 2.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0.00, NULL, 0, 1, 0, CURDATE()), + (11, 5, 4, 1.25, 10, 3, 1, 2.500, 2.500, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, 0.00, NULL, 0, 1, 0, CURDATE()), + (12, 6, 4, 1.25, 0, 3, 1, 2.500, 2.500, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, 0.00, NULL, 0, 1, 0, CURDATE()), + (13, 7, 1, 50, 0, 3, 1, 2.000, 2.000, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0.00, NULL, 0, 1, 0, CURDATE()), + (14, 7, 2, 5, 0, 3, 1, 2.000, 2.000, 0.000, 10, 10, 1, NULL, 0.00, 7.30, 7.00, 0.00, NULL, 0, 1, 0, CURDATE()), + (15, 7, 4, 1.25, 0, 3, 1, 2.000, 2.000, 0.000, 10, 10, 1, NULL, 0.00, 1.75, 1.67, 0.00, NULL, 0, 1, 0, CURDATE()); + +INSERT INTO `vn`.`deliveryMethod`(`id`, `code`, `description`) + VALUES + (1, 'AGENCY', 'Agencia'), + (2, 'DELIVERY', 'Reparto'), + (3, 'PICKUP', 'Recogida'), + (4, 'OTHER', 'Otros'); + +INSERT INTO `hedera`.`order`(`id`, `date_send`, `customer_id`, `delivery_method_id`, `agency_id`, `address_id`, `company_id`, `note`, `source_app`, `confirmed`, `date_make`, `first_row_stamp`, `confirm_date`) + VALUES + (1, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 101, 3, 1, 121, 442, NULL, 'TPV', 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (2, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 104, 3, 1, 124, 442, NULL, 'WEB', 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (3, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 104, 1, 2, 124, 442, NULL, 'ANDROID', 1, DATE_ADD(CURDATE(), INTERVAL -2 MONTH), DATE_ADD(CURDATE(), INTERVAL -2 MONTH), DATE_ADD(CURDATE(), INTERVAL -2 MONTH)), + (4, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 104, 1, 2, 124, 442, NULL, 'SALIX', 1, DATE_ADD(CURDATE(), INTERVAL -3 MONTH), DATE_ADD(CURDATE(), INTERVAL -3 MONTH), DATE_ADD(CURDATE(), INTERVAL -3 MONTH)), + (5, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 104, 1, 3, 124, 442, NULL, 'SALIX', 1, DATE_ADD(CURDATE(), INTERVAL -4 MONTH), DATE_ADD(CURDATE(), INTERVAL -4 MONTH), DATE_ADD(CURDATE(), INTERVAL -4 MONTH)), + (6, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 101, 1, 3, 1, 442, NULL, 'SALIX', 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH), DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), + (7, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 101, 2, 7, 1, 442, NULL, 'SALIX', 0, CURDATE(), CURDATE(), CURDATE()), + (8, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 101, 2, 7, 121, 442, NULL, 'SALIX', 0, CURDATE(), CURDATE(), CURDATE()), + (9, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 104, 2, 7, 124, 442, NULL, 'SALIX', 0, CURDATE(), CURDATE(), CURDATE()), + (10, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 102, 3, 1, 2, 442, NULL, 'SALIX', 0, CURDATE(), CURDATE(), CURDATE()), + (11, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 102, 2, 7, 122, 442, NULL, 'SALIX', 0, CURDATE(), CURDATE(), CURDATE()), + (12, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 103, 3, 1, 3, 442, NULL, 'SALIX', 0, CURDATE(), CURDATE(), CURDATE()), + (13, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 103, 1, 2, 123, 442, NULL, 'SALIX', 0, CURDATE(), CURDATE(), CURDATE()), + (14, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 104, 1, 2, 4, 442, NULL, 'SALIX', 0, CURDATE(), CURDATE(), CURDATE()), + (15, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 105, 1, 3, 125, 442, NULL, 'SALIX', 0, CURDATE(), CURDATE(), CURDATE()), + (16, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 106, 2, 7, 126, 442, NULL, 'SALIX', 0, CURDATE(), CURDATE(), CURDATE()), + (17, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 107, 1, 4, 127, 442, NULL, 'SALIX', 0, CURDATE(), CURDATE(), CURDATE()), + (18, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 108, 1, 4, 128, 442, NULL, 'SALIX', 0, CURDATE(), CURDATE(), CURDATE()), + (19, DATE_ADD(CURDATE(), INTERVAL + 1 DAY), 109, 1, 5, 129, 442, NULL, 'SALIX', 0, CURDATE(), CURDATE(), CURDATE()), + (20, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 109, 1, 5, 101, 442, NULL, 'SALIX', 0, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (21, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 109, 1, 5, 102, 442, NULL, 'SALIX', 0, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH)), + (22, DATE_ADD(DATE_ADD(CURDATE(),INTERVAL +1 MONTH), INTERVAL +1 DAY), 109, 1, 5, 103, 442, NULL, 'SALIX', 0, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH), DATE_ADD(CURDATE(), INTERVAL +1 MONTH)); + +INSERT INTO `hedera`.`orderRow`(`id`, `orderFk`, `itemFk`, `warehouseFk`, `shipment`, `amount`, `price`, `rate`, `created`, `saleFk`) + VALUES + (1, 1, 1, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 5, 9.10, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1), + (2, 1, 2, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 10, 1.07, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 2), + (3, 1, 1, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 2, 9.10, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 3), + (4, 1, 4, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 20, 3.06, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 4), + (5, 2, 1, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 10, 9.10, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 5), + (6, 3, 1, 2, DATE_ADD(CURDATE(), INTERVAL -2 MONTH), 15, 6.50, 0, DATE_ADD(CURDATE(), INTERVAL -2 MONTH), 6), + (7, 11, 2, 1, CURDATE(), 15, 1.30, 0, CURDATE(), 7), + (8, 11, 4, 1, CURDATE(), 10, 3.26, 0, CURDATE(), 8), + (9, 16, 1, 1, CURDATE(), 5, 9.10, 0, CURDATE(), 9), + (10, 16, 2, 1, CURDATE(), 10, 1.07, 0, CURDATE(), 10), + (11, 16, 1, 1, CURDATE(), 2, 9.10, 0, CURDATE(), 11), + (12, 16, 4, 1, CURDATE(), 20, 3.06, 0, CURDATE(), 12), + (13, 8, 2, 1, CURDATE(), 15, 1.30, 0, CURDATE(), 13), + (14, 8, 1, 1, CURDATE(), 10, 9.28, 0, CURDATE(), 14), + (15, 19, 1, 1, CURDATE(), 10, 1.50, 0, CURDATE(), 15), + (16, 20, 2, 1, CURDATE(), 15, 1.30, 0, CURDATE(), 16), + (17, 22, 2, 1, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), 30, 2.30, 0, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), 17), + (18, 22, 4, 1, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), 20, 3.00, 0, DATE_ADD(CURDATE(), INTERVAL +1 MONTH), 18), + (19, 4, 1, 1, DATE_ADD(CURDATE(), INTERVAL -3 MONTH), 1, 9.10, 0, DATE_ADD(CURDATE(), INTERVAL -3 MONTH), 19), + (20, 5, 1, 1, DATE_ADD(CURDATE(), INTERVAL -4 MONTH), 1, 9.10, 0, DATE_ADD(CURDATE(), INTERVAL -4 MONTH), 20), + (21, 6, 1, 1, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1, 9.10, 0, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 21), + (22, 7, 1, 1, CURDATE(), 1, 9.10, 0, CURDATE(), 22), + (23, 9, 1, 1, CURDATE(), 1, 9.10, 0, CURDATE(), 23), + (24, 10, 1, 1, CURDATE(), 1, 9.10, 0, CURDATE(), 24), + (25, 12, 4, 1, CURDATE(), 20, 3.00, 0, CURDATE(), 25), + (26, 13, 4, 1, CURDATE(), 20, 3.00, 0, CURDATE(), 26), + (27, 14, 4, 1, CURDATE(), 20, 3.00, 0, CURDATE(), 27), + (28, 15, 4, 1, CURDATE(), 20, 3.00, 0, CURDATE(), 28), + (29, 17, 4, 1, CURDATE(), 20, 3.00, 0, CURDATE(), 29), + (30, 18, 4, 1, CURDATE(), 20, 3.00, 0, CURDATE(), 30); + +INSERT INTO `hedera`.`orderRowComponent`(`rowFk`, `componentFk`, `price`) + VALUES + (1, 15, 0.58), + (1, 23, 6.5), + (1, 28, 20.72), + (1, 29, -18.72), + (1, 39, 0.02), + (2, 15, 0.058), + (2, 21, 0.002), + (2, 28, 5.6), + (2, 29, -4.6), + (2, 39, 0.01), + (3, 15, 0.58), + (3, 23, 6.5), + (3, 28, 20.72), + (3, 29, -18.72), + (3, 39, 0.02), + (4, 15, 0.051), + (4, 21, -0.001), + (4, 28, 20.72), + (4, 29, -19.72), + (4, 37, 2), + (4, 39, 0.01), + (5, 15, 0.58), + (5, 23, 6.5), + (5, 28, 20.72), + (5, 29, -18.72), + (5, 39, 0.02), + (6, 23, 6.5), + (7, 15, 0.0114), + (7, 28, 5.6), + (7, 29, -4.6), + (7, 39, 0.01), + (8, 15, 0.0016), + (8, 28, 20.72), + (8, 29, -19.72), + (8, 37, 2), + (8, 39, 0.01), + (9, 15, 0.58), + (9, 23, 6.5), + (9, 28, 20.72), + (9, 29, -18.72), + (9, 39, 0.02), + (10, 15, 0.058), + (10, 21, 0.002), + (10, 28, 5.6), + (10, 29, -4.6), + (10, 39, 0.01), + (11, 15, 0.58), + (11, 23, 6.5), + (11, 28, 20.72), + (11, 29, -18.72), + (11, 39, 0.02), + (12, 15, 0.051), + (12, 22, -0.001), + (12, 28, 20.72), + (12, 29, -19.72), + (12, 37, 2), + (12, 39, 0.01), + (13, 15, 0.2899), + (13, 28, 5.6), + (13, 29, -4.6), + (13, 39, 0.01), + (14, 15, 0.58), + (14, 23, 6.5), + (14, 28, 20.72), + (14, 29, -18.72), + (14, 39, 0.02), + (15, 15, 0.58), + (15, 23, 6.5), + (15, 28, 20.72), + (15, 29, -18.72), + (15, 39, 0.02), + (16, 15, 0.058), + (16, 21, 0.002), + (16, 28, 5.6), + (16, 29, -4.6), + (16, 39, 0.01), + (17, 15, 0.058), + (17, 21, 0.002), + (17, 28, 5.6), + (17, 29, -4.6), + (17, 39, 0.01), + (18, 15, 0.051), + (18, 22, -0.001), + (18, 28, 20.72), + (18, 29, -19.72), + (18, 37, 2), + (18, 39, 0.01), + (19, 15, 0.58), + (19, 23, 6.5), + (19, 28, 20.72), + (19, 29, -18.72), + (19, 39, 0.02), + (20, 15, 0.58), + (20, 23, 6.5), + (20, 28, 20.72), + (20, 29, -18.72), + (20, 39, 0.02), + (21, 15, 0.58), + (21, 23, 6.5), + (21, 28, 20.72), + (21, 29, -18.72), + (21, 39, 0.02), + (22, 15, 0.58), + (22, 23, 6.5), + (22, 28, 20.72), + (22, 29, -18.72), + (22, 39, 0.02), + (23, 15, 0.58), + (23, 23, 6.5), + (23, 28, 20.72), + (23, 29, -18.72), + (23, 39, 0.02), + (24, 15, 0.58), + (24, 23, 6.5), + (24, 28, 20.72), + (24, 29, -18.72), + (24, 39, 0.02), + (25, 15, 0.051), + (25, 22, -0.001), + (25, 28, 20.72), + (25, 29, -19.72), + (25, 37, 2), + (25, 39, 0.01), + (26, 15, 0.051), + (26, 22, -0.001), + (26, 28, 20.72), + (26, 29, -19.72), + (26, 37, 2), + (26, 39, 0.01), + (27, 15, 0.051), + (27, 22, -0.001), + (27, 28, 20.72), + (27, 29, -19.72), + (27, 37, 2), + (27, 39, 0.01), + (28, 15, 0.051), + (28, 22, -0.001), + (28, 28, 20.72), + (28, 29, -19.72), + (28, 37, 2), + (28, 39, 0.01), + (29, 15, 0.051), + (29, 22, -0.001), + (29, 28, 20.72), + (29, 29, -19.72), + (29, 37, 2), + (29, 39, 0.01), + (30, 15, 0.051), + (30, 22, -0.001), + (30, 28, 20.72), + (30, 29, -19.72), + (30, 37, 2), + (30, 39, 0.01); + +INSERT INTO `vn`.`clientContact`(`id`, `clientFk`, `name`, `phone`) + VALUES + (1, 101, 'contact 1', 666777888), + (2, 101, 'contact 2', 111222333), + (3, 101, 'contact 3', 222333444), + (4, 102, 'contact 1', 876543219); + +/* + el mana de los trabajadores lo podemos poner a mano en la tabla si lo calculamos antes, + pero si hazemos alguna modificacion en alguna tabla que utiliza para calcularlo ya no seria correcto + + La otra manera es poner el calculo con los 2 trabajadores que utilizamos ahora mismo para los tickets +*/ + +call vn.manaSpellersRequery(19); +call vn.manaSpellersRequery(18); + +INSERT INTO `vn`.`clientSample`(`id`, `clientFk`, `typeFk`, `created`, `workerFk`, `userFk`, `companyFk`) + VALUES + (1, 101, 1, CURDATE(), 18, 18, 442), + (2, 101, 1, CURDATE(), 18, 18, 442), + (3, 101, 2, CURDATE(), 18, 18, 442), + (4, 102, 2, CURDATE(), 18, 18, 567), + (5, 102, 3, CURDATE(), 19, 19, 567); + +INSERT INTO `vn`.`claimState`(`id`, `description`, `roleFk`) + VALUES + ( 1, 'Pendiente', 1), + ( 2, 'Gestionado', 1), + ( 3, 'Resuelto', 21), + ( 4, 'Anulado', 1), + ( 5, 'Cuestionado', 21), + ( 6, 'Mana', 1); + +INSERT INTO `vn`.`claim`(`id`, `ticketCreated`, `claimStateFk`, `observation`, `clientFk`, `workerFk`, `responsibility`, `isChargedToMana`, `created` ) + VALUES + (1, CURDATE(), 1, 'observation one', 101, 18, 3, 0, CURDATE()), + (2, CURDATE(), 2, 'observation two', 101, 18, 3, 0, CURDATE()), + (3, CURDATE(), 3, 'observation three', 101, 18, 1, 1, CURDATE()), + (4, CURDATE(), 3, 'observation four', 104, 18, 5, 0, CURDATE()); + +INSERT INTO `vn`.`claimBeginning`(`id`, `claimFk`, `saleFk`, `quantity`) + VALUES + (1, 1, 7, 5), + (2, 2, 10, 10), + (3, 3, 22, 1), + (4, 4, 13, 5); + +INSERT INTO `vn`.`claimDestination`(`id`, `description`, `addressFk`) + VALUES + (1, 'Bueno', NULL), + (2, 'Basura/Perd.', 12), + (3, 'Confeccion', NULL), + (4, 'Reclam.PRAG', 12), + (5, 'Corregido', 11); + +INSERT INTO `vn`.`claimDevelopment`(`id`, `claimFk`, `claimResponsibleFk`, `workerFk`, `claimReasonFk`, `claimResultFk`, `claimRedeliveryFk`, `claimDestinationFk`) + VALUES + (1, 1, 1, 21, 1, 1, 2, 5), + (2, 1, 1, 21, 7, 2, 2, 5), + (3, 2, 7, 21, 9, 3, 2, 5), + (4, 3, 7, 21, 15, 8, 2, 5), + (5, 4, 7, 21, 7, 8, 2, 5); + +INSERT INTO `vn`.`claimEnd`(`id`, `saleFk`, `claimFk`, `workerFk`, `claimDestinationFk`) + VALUES + (1, 31, 4, 21, 2), + (2, 32, 3, 21, 3); + +INSERT INTO `hedera`.`tpvMerchant`(`id`, `description`, `companyFk`, `bankFk`, `secretKey`) + VALUES + (1, 'Arkham Bank', 442, 1, 'h12387193H10238'), + (2, 'NewYork Bank', 442, 1, '7981ugsgd1hsdad'); + +INSERT INTO `hedera`.`tpvTransaction`(`id`,`merchantFk`, `clientFk`,`receiptFk`, `amount`, `response`, `errorCode`, `status`, `created`) + VALUES + (1, 1, 101, NULL, 2000, NULL, 'SIS0042', 'ok', CURDATE()), + (2, 1, 101, NULL, 1000, NULL, 'SIS0051', 'started', CURDATE()), + (3, 2, 101, NULL, 7268, NULL, NULL, 'ok', CURDATE()), + (4, 2, 101, NULL, 4698, NULL, NULL, 'started', CURDATE()), + (5, 1, 104, NULL, 2000, NULL, 'SIS0043', 'ok', CURDATE()), + (6, 2, 104, NULL, 4000, NULL, 'SIS0044', 'started', CURDATE()); + +INSERT INTO `vn`.`orderTicket`(`orderFk`, `ticketFk`) + VALUES + (1, 1), + (2, 2), + (3, 3), + (4, 4), + (5, 5), + (6, 6), + (7, 7), + (8, 8), + (9, 9), + (10, 10), + (11, 11), + (12, 12), + (13, 13), + (14, 14), + (15, 15), + (16, 16), + (17, 17), + (18, 18), + (19, 19), + (20, 20), + (21, 21), + (22, 22); + +INSERT INTO `vn`.`userConfig` (`userFk`, `warehouseFk`, `companyFk`) + VALUES + (1, 2, 69), + (5, 1, 442), + (9, 1, 442), + (18, 3, 567); + +INSERT INTO `vn`.`receipt`(`id`, `invoiceFk`, `amountPaid`, `amountUnpaid`, `payed`, `workerFk`, `bankFk`, `clientFk`, `created`, `companyFk`, `isConciliate`) + VALUES + (1, 'Cobro web', 100.50, 0.00, CURDATE(), 9, 1, 101, CURDATE(), 442, 1), + (2, 'Cobro web', 200.50, 0.00, DATE_ADD(CURDATE(), INTERVAL -5 DAY), 9, 1, 101, DATE_ADD(CURDATE(), INTERVAL -5 DAY), 442, 1), + (3, 'Cobro en efectivo', 300.00, 100.00, DATE_ADD(CURDATE(), INTERVAL -10 DAY), 9, 1, 102, DATE_ADD(CURDATE(), INTERVAL -10 DAY), 442, 0), + (4, 'Cobro en efectivo', 400.00, -50.00, DATE_ADD(CURDATE(), INTERVAL -15 DAY), 9, 1, 103, DATE_ADD(CURDATE(), INTERVAL -15 DAY), 442, 0); + +INSERT INTO `vn`.`workerTeam`(`id`, `team`, `workerFk`) + VALUES + (1, 1, 9), + (2, 1, 18), + (3, 2, 101), + (4, 2, 102), + (5, 3, 103), + (6, 3, 104); + +INSERT INTO `vn`.`ticketRequest`(`id`, `description`, `requesterFk`, `attenderFk`, `quantity`, `itemFk`, `price`, `isOk`, `saleFk`, `ticketFk`, `created`) + VALUES + (1, 'Ranged weapon longbow 2m', 18, 35, 5, 1, 9.10, 1, 1, 1, DATE_ADD(CURDATE(), INTERVAL -15 DAY)), + (2, 'Melee weapon combat first 15cm', 18, 35, 10, 2, 1.07, 0, NULL, 1, DATE_ADD(CURDATE(), INTERVAL -15 DAY)), + (3, 'Melee weapon heavy shield 1x0.5m', 18, 35, 20, 4, 3.06, 0, NULL, 1, DATE_ADD(CURDATE(), INTERVAL -15 DAY)), + (4, 'Melee weapon combat first 15cm', 18, 35, 15, NULL, 1.30, NULL, NULL, 11, CURDATE()), + (5, 'Melee weapon combat first 15cm', 18, 35, 15, 4, 1.30, 0, NULL, 18, CURDATE()); + +INSERT INTO `vn`.`ticketServiceType`(`id`, `name`) + VALUES + (1, 'Porte Agencia'), + (2, 'Portes Retorno'), + (3, 'Porte Carry'), + (4, 'Cargo FITOSANITARIO'), + (5, 'Documentos'); + +INSERT INTO `vn`.`ticketService`(`id`, `description`, `quantity`, `price`, `taxClassFk`, `ticketFk`, `ticketServiceTypeFk`) + VALUES + (1, 'Documentos', 1, 2.00, 1, 1, 1), + (2, 'Porte Agencia', 1, 10.00, 1, 2, 1), + (3, 'Documentos', 1, 5.50, 1, 11, 1), + (4, 'Documentos', 1, 2.00, 1, 9, 1), + (5, 'Documentos', 1, 2.00, 1, 8, 1); + +INSERT INTO `pbx`.`sip`(`user_id`, `extension`) + VALUES + (1, 1010), + (3, 1101), + (5, 1102), + (9, 1201); + +INSERT INTO `postgresql`.`person`(`person_id`, `name`, `nickname`, `nif`, `firstname`, `id_trabajador`) + SELECT w.id, w.lastName, u.nickname,CONCAT(RPAD(CONCAT(w.id,9),8,w.id),'A'),w.firstName,w.id + FROM `vn`.`worker` `w` + JOIN `account`.`user` `u` ON `u`.`id` = `w`.`userFk`; + +INSERT INTO `postgresql`.`person`(`person_id`, `name`, `nickname`, `nif`, `firstname`, `id_trabajador`) + VALUES + (1000, 'VERDNATURA LEVANTE SL', 'VNL', 'B78945612', NULL, NULL); + +INSERT INTO `postgresql`.`profile`(`profile_id`, `person_id`, `profile_type_id`) + SELECT p.person_id, p.person_id, 1 + FROM `postgresql`.`person` `p`; + +INSERT INTO `postgresql`.`business`(`business_id`, `client_id`, `provider_id`, `date_start`, `date_end`, `workerBusiness`, `reasonEndFk`) + SELECT p.profile_id, p.profile_id, 1000, CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -1 YEAR)), '-12-31'), CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL +1 YEAR)), '-01-01'), CONCAT('E-46-',RPAD(CONCAT(p.profile_id,9),8,p.profile_id)), NULL + FROM `postgresql`.`profile` `p`; + +INSERT INTO `postgresql`.`business_labour`(`business_id`, `notes`, `department_id`, `professional_category_id`, `incentivo`, `calendar_labour_type_id`, `porhoras`, `labour_agreement_id`, `workcenter_id`) + SELECT b.business_id, NULL, 23, 1, 0, 1, 1, 1, 1 + FROM `postgresql`.`business` `b`; + +INSERT INTO `postgresql`.`media`(`media_id`, `media_type_id`, `value`, `sort`) + VALUES + (1, 10, 600123321, 0), + (2, 10, 700987987, 0); + +INSERT INTO `postgresql`.`profile_media`(`profile_media_id`, `profile_id`, `media_id`) + VALUES + (1, 106, 1), + (2, 107, 2); + +INSERT INTO `vn`.`workCenter` (`id`, `name`, `warehouseFk`) + VALUES + ('1', 'Silla', '1'), + ('5', 'Madrid', '5'); + +INSERT INTO `vn`.`workCenterHoliday` (`workCenterFk`, `days`, `year`) + VALUES + ('1', '27.5', YEAR(CURDATE())), + ('5', '22', YEAR(CURDATE())), + ('1', '24.5', YEAR(DATE_ADD(CURDATE(), INTERVAL -1 YEAR))), + ('5', '23', YEAR(DATE_ADD(CURDATE(), INTERVAL -1 YEAR))); + +INSERT INTO `postgresql`.`calendar_state` (`calendar_state_id`, `type`, `rgb`, `code`) + VALUES + (1, 'Holidays', '#FF4444', 'holiday'), + (2, 'Leave of absence', '#C71585', 'absence'), + (6, 'Half holiday', '#E65F00', 'halfHoliday'); + +INSERT INTO `postgresql`.`calendar_employee` (`business_id`, `calendar_state_id`, `date`) + VALUES + (106, 1, DATE_ADD(CURDATE(), INTERVAL 10 DAY)), + (106, 1, DATE_ADD(CURDATE(), INTERVAL 11 DAY)), + (106, 1, DATE_ADD(CURDATE(), INTERVAL 12 DAY)), + (106, 1, DATE_ADD(CURDATE(), INTERVAL 20 DAY)), + (106, 2, DATE_ADD(CURDATE(), INTERVAL -10 DAY)), + (106, 1, DATE_ADD(CURDATE(), INTERVAL -12 DAY)), + (106, 2, DATE_ADD(CURDATE(), INTERVAL -20 DAY)), + (107, 1, DATE_ADD(CURDATE(), INTERVAL 15 DAY)), + (107, 1, DATE_ADD(CURDATE(), INTERVAL 16 DAY)), + (107, 1, DATE_ADD(CURDATE(), INTERVAL 20 DAY)), + (107, 1, DATE_ADD(CURDATE(), INTERVAL 30 DAY)), + (107, 2, DATE_ADD(CURDATE(), INTERVAL -10 DAY)), + (107, 1, DATE_ADD(CURDATE(), INTERVAL -12 DAY)), + (107, 2, DATE_ADD(CURDATE(), INTERVAL -20 DAY)); + +INSERT INTO `vn`.`smsConfig` (`id`, `uri`, `title`) + VALUES + ('1', 'https://websms.xtratelecom.es/api_php/server.wsdl', 'Verdnatura'); + +INSERT INTO `vn`.`sharingClient`(`id`, `workerFk`, `started`, `ended`, `clientFk`) + VALUES + (1, 19, DATE_ADD(CURDATE(), INTERVAL -5 DAY), DATE_ADD(CURDATE(), INTERVAL +15 DAY), 101), + (2, 18, DATE_ADD(CURDATE(), INTERVAL -5 DAY), DATE_ADD(CURDATE(), INTERVAL +15 DAY), 106); + +INSERT INTO `vn`.`sharingCart`(`id`, `workerFk`, `started`, `ended`, `workerSubstitute`, `created`) + VALUES + (1, 18, DATE_ADD(CURDATE(), INTERVAL -5 DAY), DATE_ADD(CURDATE(), INTERVAL +15 DAY), 19, DATE_ADD(CURDATE(), INTERVAL -5 DAY)); + +CALL `vn`.zoneGeo_calcTree(); -- this is an auto calculate for table vn.zoneGeo, columns: path,lft,rgt,depth,sons + +INSERT INTO `vn`.`zoneIncluded` (`zoneFk`, `geoFk`, `isIncluded`) + VALUES + (1, 3, 0), + (1, 4, 0), + (1, 5, 0), + (1, 1, 1), + (2, 3, 0), + (2, 4, 0), + (2, 5, 0), + (2, 1, 1), + (3, 3, 0), + (3, 4, 0), + (3, 5, 0), + (3, 1, 1), + (4, 3, 0), + (4, 4, 0), + (4, 5, 0), + (4, 1, 1), + (5, 3, 1), + (5, 4, 0), + (5, 5, 1), + (5, 1, 1), + (6, 3, 1), + (6, 4, 0), + (6, 5, 1), + (6, 1, 1), + (7, 3, 0), + (7, 4, 0), + (7, 5, 0), + (7, 1, 1), + (8, 3, 0), + (8, 4, 0), + (8, 5, 0), + (8, 1, 1); + +INSERT INTO `vn`.`zoneEvent`(`zoneFk`, `type`, `dated`) + VALUES + (1, 'day', DATE_ADD(CURDATE(), INTERVAL (IF(DAYOFWEEK(CURDATE())<=2, 2, 9 ) - DAYOFWEEK(CURDATE())) DAY)), + (1, 'day', DATE_ADD(CURDATE(), INTERVAL (IF(DAYOFWEEK(CURDATE())<=3, 3, 10) - DAYOFWEEK(CURDATE())) DAY)), + (1, 'day', DATE_ADD(CURDATE(), INTERVAL (IF(DAYOFWEEK(CURDATE())<=4, 4, 11) - DAYOFWEEK(CURDATE())) DAY)), + (1, 'day', DATE_ADD(CURDATE(), INTERVAL (IF(DAYOFWEEK(CURDATE())<=5, 5, 12) - DAYOFWEEK(CURDATE())) DAY)), + (1, 'day', DATE_ADD(CURDATE(), INTERVAL (IF(DAYOFWEEK(CURDATE())<=6, 6, 13) - DAYOFWEEK(CURDATE())) DAY)), + (2, 'day', DATE_ADD(CURDATE(), INTERVAL (IF(DAYOFWEEK(CURDATE())<=2, 2, 9 ) - DAYOFWEEK(CURDATE())) DAY)), + (2, 'day', DATE_ADD(CURDATE(), INTERVAL (IF(DAYOFWEEK(CURDATE())<=3, 3, 10) - DAYOFWEEK(CURDATE())) DAY)), + (2, 'day', DATE_ADD(CURDATE(), INTERVAL (IF(DAYOFWEEK(CURDATE())<=4, 4, 11) - DAYOFWEEK(CURDATE())) DAY)), + (2, 'day', DATE_ADD(CURDATE(), INTERVAL (IF(DAYOFWEEK(CURDATE())<=5, 5, 12) - DAYOFWEEK(CURDATE())) DAY)), + (2, 'day', DATE_ADD(CURDATE(), INTERVAL (IF(DAYOFWEEK(CURDATE())<=6, 6, 13) - DAYOFWEEK(CURDATE())) DAY)), + (3, 'day', CURDATE()), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +1 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +2 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +3 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +4 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +5 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +6 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +7 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +8 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +9 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +10 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +11 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +12 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +13 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +14 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +15 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +16 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +17 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +18 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +19 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +20 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +21 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +22 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +23 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +24 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +25 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +26 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +27 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +28 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +29 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +30 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +31 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +32 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +33 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +34 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +35 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +36 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +37 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +38 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +39 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +40 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +41 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +42 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +43 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +44 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +45 DAY)), + (3, 'day', DATE_ADD(CURDATE(), INTERVAL +46 DAY)), + (4, 'day', CURDATE()), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +1 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +2 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +3 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +4 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +5 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +6 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +7 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +8 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +9 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +10 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +11 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +12 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +13 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +14 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +15 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +16 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +17 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +18 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +19 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +20 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +21 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +22 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +23 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +24 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +25 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +26 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +27 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +28 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +29 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +30 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +31 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +32 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +33 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +34 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +35 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +36 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +37 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +38 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +39 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +40 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +41 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +42 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +43 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +44 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +45 DAY)), + (4, 'day', DATE_ADD(CURDATE(), INTERVAL +46 DAY)), + (5, 'day', CURDATE()), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +1 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +2 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +3 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +4 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +5 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +6 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +7 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +8 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +9 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +10 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +11 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +12 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +13 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +14 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +15 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +16 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +17 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +18 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +19 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +20 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +21 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +22 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +23 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +24 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +25 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +26 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +27 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +28 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +29 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +30 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +31 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +32 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +33 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +34 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +35 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +36 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +37 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +38 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +39 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +40 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +41 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +42 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +43 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +44 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +45 DAY)), + (5, 'day', DATE_ADD(CURDATE(), INTERVAL +46 DAY)), + (6, 'day', CURDATE()), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +1 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +2 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +3 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +4 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +5 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +6 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +7 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +8 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +9 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +10 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +11 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +12 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +13 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +14 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +15 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +16 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +17 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +18 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +19 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +20 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +21 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +22 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +23 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +24 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +25 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +26 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +27 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +28 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +29 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +30 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +31 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +32 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +33 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +34 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +35 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +36 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +37 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +38 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +39 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +40 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +41 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +42 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +43 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +44 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +45 DAY)), + (6, 'day', DATE_ADD(CURDATE(), INTERVAL +46 DAY)), + (7, 'day', CURDATE()), + (7, 'day', DATE_ADD(CURDATE(), INTERVAL +1 DAY)), + (7, 'day', DATE_ADD(CURDATE(), INTERVAL +2 DAY)), + (7, 'day', DATE_ADD(CURDATE(), INTERVAL +3 DAY)), + (7, 'day', DATE_ADD(CURDATE(), INTERVAL +4 DAY)), + (7, 'day', DATE_ADD(CURDATE(), INTERVAL +5 DAY)), + (7, 'day', DATE_ADD(CURDATE(), INTERVAL +6 DAY)), + (8, 'day', CURDATE()), + (8, 'day', DATE_ADD(CURDATE(), INTERVAL +1 DAY)), + (8, 'day', DATE_ADD(CURDATE(), INTERVAL +2 DAY)), + (8, 'day', DATE_ADD(CURDATE(), INTERVAL +3 DAY)), + (8, 'day', DATE_ADD(CURDATE(), INTERVAL +4 DAY)), + (8, 'day', DATE_ADD(CURDATE(), INTERVAL +5 DAY)), + (8, 'day', DATE_ADD(CURDATE(), INTERVAL +6 DAY)); + +INSERT INTO `vn`.`workerTimeControl`(`userFk`, `timed`, `order`, `manual`, `direction`) + VALUES + (106, CONCAT(CURDATE(), ' 07:00'), 1, TRUE, 'in'), + (106, CONCAT(CURDATE(), ' 10:00'), 2, TRUE, 'middle'), + (106, CONCAT(CURDATE(), ' 10:10'), 3, TRUE, 'middle'), + (106, CONCAT(CURDATE(), ' 15:00'), 4, TRUE, 'out'); + +INSERT INTO `vn`.`dmsType`(`id`, `name`, `path`, `readRoleFk`, `writeRoleFk`, `code`) + VALUES + (1, 'Facturas Recibidas', 'recibidas', NULL, NULL, 'invoiceIn'), + (2, 'Doc oficial', 'oficial', NULL, NULL, 'officialDoc'), + (3, 'Laboral', 'laboral', NULL, NULL, 'hhrrData'), + (4, 'Albaranes recibidos', 'entradas', NULL, NULL, 'deliveryNote'), + (5, 'Otros', 'otros', 1, 1, 'miscellaneous'), + (6, 'Pruebas', 'pruebas', NULL, NULL, 'tests'), + (7, 'IAE Clientes', 'IAE_Clientes', NULL, NULL, 'economicActivitiesTax'), + (8, 'Fiscal', 'fiscal', NULL, NULL, 'fiscal'), + (9, 'Vehiculos', 'vehiculos', NULL, NULL, 'vehicles'), + (10, 'Plantillas', 'plantillas', NULL, NULL, 'templates'), + (11, 'Contratos', 'contratos', NULL, NULL, 'contracts'), + (12, 'ley de pagos', 'ley pagos', 1, 1, 'paymentsLaw'), + (13, 'Basura', 'basura', 1, 1, 'trash'), + (14, 'Ticket', 'tickets', 1, 1, 'ticket'), + (15, 'Presupuestos', 'Presupuestos', NULL, NULL, 'budgets'), + (16, 'Logistica', 'logistica', NULL, NULL, 'logistics'), + (17, 'cmr', 'cmr', NULL, NULL, 'cmr'), + (18, 'dua', 'dua', NULL, NULL, 'dua'), + (19, 'inmovilizado', 'inmovilizado', NULL, NULL, 'fixedAssets'), + (20, 'Reclamación', 'reclamacion', 1, 1, 'claim'); + +INSERT INTO `vn`.`dms`(`id`, `dmsTypeFk`, `file`, `contentType`, `workerFk`, `warehouseFk`, `companyFk`, `hardCopyNumber`, `hasFile`, `reference`, `description`, `created`) + VALUES + (1, 14, '1.txt', 'text/plain', 5, 1, 442, NULL, FALSE, 'Ticket:11', 'Ticket:11 dms for the ticket', CURDATE()), + (2, 5, '2.txt', 'text/plain', 5, 1, 442, 1, TRUE, 'Client:104', 'Client:104 dms for the client', CURDATE()), + (3, 5, '3.txt', 'text/plain', 5, 1, 442, NULL, TRUE, 'Client: 104', 'Client:104 readme', CURDATE()), + (4, 3, '3.txt', 'text/plain', 5, 1, 442, NULL, TRUE, 'Worker: 106', 'Worker:106 readme', CURDATE()); + +INSERT INTO `vn`.`ticketDms`(`ticketFk`, `dmsFk`) + VALUES + (11, 1); + +INSERT INTO `vn`.`clientDms`(`clientFk`, `dmsFk`) + VALUES + (104, 2), + (104, 3); + +INSERT INTO `vn`.`workerDocument`(`id`, `worker`, `document`) + VALUES + (1, 106, 4); + +INSERT INTO `vn`.`device` (`sn`, `model`, `userFk`) + VALUES + ('aaa', 'android', '9'); + +INSERT INTO `vn`.`queuePriority`(`id`, `priority`) + VALUES + (1, 'Alta'), + (2, 'Normal'), + (3, 'Baja'); + +INSERT INTO `vn`.`userPhone`(`id`, `userFk`, `typeFk`, `phone`) + VALUES + (1, 101, 'personalPhone', 1111111111), + (2, 102, 'personalPhone', 1111111111), + (3, 103, 'personalPhone', 1111111111), + (4, 104, 'personalPhone', 1111111111), + (5, 105, 'personalPhone', 1111111111), + (6, 106, 'personalPhone', 1111111111), + (7, 107, 'personalPhone', 1111111111), + (8, 108, 'personalPhone', 1111111111), + (9, 109, 'personalPhone', 1111111111), + (10, 110, 'personalPhone', 1111111111), + (11, 111, 'personalPhone', 1111111111), + (12, 112, 'personalPhone', 1111111111), + (13, 1, 'personalPhone', 623111111), + (14, 2, 'personalPhone', 623111111), + (15, 3, 'personalPhone', 623111111), + (16, 5, 'personalPhone', 623111111), + (17, 6, 'personalPhone', 623111111), + (18, 9, 'personalPhone', 623111111), + (19, 13, 'personalPhone', 623111111), + (20, 15, 'personalPhone', 623111111), + (21, 16, 'personalPhone', 623111111), + (22, 17, 'personalPhone', 623111111), + (23, 18, 'personalPhone', 623111111), + (24, 19, 'personalPhone', 623111111), + (26, 21, 'personalPhone', 623111111), + (27, 22, 'personalPhone', 623111111), + (28, 30, 'personalPhone', 623111111), + (29, 31, 'personalPhone', 623111111), + (30, 32, 'personalPhone', 623111111), + (31, 34, 'personalPhone', 623111111), + (32, 35, 'personalPhone', 623111111), + (33, 36, 'personalPhone', 623111111), + (34, 37, 'personalPhone', 623111111), + (35, 38, 'personalPhone', 623111111), + (36, 39, 'personalPhone', 623111111), + (37, 40, 'personalPhone', 623111111), + (38, 41, 'personalPhone', 623111111), + (39, 42, 'personalPhone', 623111111), + (40, 43, 'personalPhone', 623111111), + (41, 44, 'personalPhone', 623111111), + (42, 45, 'personalPhone', 623111111), + (43, 47, 'personalPhone', 623111111), + (44, 48, 'personalPhone', 623111111), + (45, 50, 'personalPhone', 623111111), + (46, 51, 'personalPhone', 623111111), + (47, 52, 'personalPhone', 623111111), + (48, 54, 'personalPhone', 623111111), + (49, 55, 'personalPhone', 623111111), + (50, 56, 'personalPhone', 623111111), + (51, 57, 'personalPhone', 623111111), + (52, 58, 'personalPhone', 623111111), + (53, 59, 'personalPhone', 623111111), + (54, 60, 'personalPhone', 623111111), + (55, 61, 'personalPhone', 623111111), + (56, 65, 'personalPhone', 623111111), + (57, 66, 'personalPhone', 623111111), + (65, 107, 'businessPhone', 700987987), + (67, 106, 'businessPhone', 1111111112), + (68, 106, 'personalPhone', 1111111113); + +INSERT INTO `vn`.`workerTimeControlParams` (`id`, `dayBreak`, `weekBreak`, `weekScope`, `dayWorkMax`, `dayStayMax`) + VALUES + (1, 43200, 129600, 734400, 43200, 50400); + diff --git a/db/dump/mysqlPlugins.sql b/db/dump/mysqlPlugins.sql new file mode 100644 index 000000000..c3b6f6ee4 --- /dev/null +++ b/db/dump/mysqlPlugins.sql @@ -0,0 +1,4 @@ + +-- Import compiled functions +CREATE AGGREGATE FUNCTION minacum RETURNS INT SONAME 'minacum.so'; +CREATE AGGREGATE FUNCTION multimax RETURNS INT SONAME 'multimax.so'; diff --git a/db/dump/structure.sql b/db/dump/structure.sql new file mode 100644 index 000000000..c33b63dcd --- /dev/null +++ b/db/dump/structure.sql @@ -0,0 +1,56283 @@ +-- MySQL dump 10.13 Distrib 8.0.18, for osx10.15 (x86_64) +-- +-- Host: db.verdnatura.es Database: account +-- ------------------------------------------------------ +-- Server version 5.6.25-4-log + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!50503 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Current Database: `account` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `account` /*!40100 DEFAULT CHARACTER SET utf8 */; + +USE `account`; + +-- +-- Table structure for table `account` +-- + +DROP TABLE IF EXISTS `account`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `account` ( + `id` int(10) unsigned NOT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `account_ibfk_3` FOREIGN KEY (`id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Users allowed to have an account'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `account`.`account_afterInsert` + AFTER INSERT ON `account` + FOR EACH ROW +BEGIN + UPDATE user SET sync = FALSE + WHERE id = NEW.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_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `account`.`account_afterDelete` + AFTER DELETE ON `account` + FOR EACH ROW +BEGIN + UPDATE user SET sync = FALSE + WHERE id = OLD.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 */ ; + +-- +-- Table structure for table `accountConfig` +-- + +DROP TABLE IF EXISTS `accountConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `accountConfig` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `homedir` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The base folder for users home directories', + `shell` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The default shell', + `idBase` int(11) NOT NULL, + `min` smallint(6) NOT NULL, + `max` smallint(6) NOT NULL, + `warn` smallint(6) NOT NULL, + `inact` smallint(6) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration parameters for accounts'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `accountDovecot` +-- + +DROP TABLE IF EXISTS `accountDovecot`; +/*!50001 DROP VIEW IF EXISTS `accountDovecot`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `accountDovecot` AS SELECT + 1 AS `name`, + 1 AS `password`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `accountLog` +-- + +DROP TABLE IF EXISTS `accountLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `accountLog` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `msg` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `pid` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `user` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `host` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `rhost` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `time` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `emailUser` +-- + +DROP TABLE IF EXISTS `emailUser`; +/*!50001 DROP VIEW IF EXISTS `emailUser`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `emailUser` AS SELECT + 1 AS `userFk`, + 1 AS `email`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `ldapConfig` +-- + +DROP TABLE IF EXISTS `ldapConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ldapConfig` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `host` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The hostname of LDAP server', + `rdn` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The LDAP user', + `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Base64 encoded password', + `baseDn` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The base DN to do the query', + `filter` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Filter to apply to the query', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='LDAP server configuration parameters'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `mailAlias` +-- + +DROP TABLE IF EXISTS `mailAlias`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mailAlias` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `alias` varchar(50) CHARACTER SET utf8 NOT NULL, + `isPublic` tinyint(4) NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `alias` (`alias`) +) ENGINE=InnoDB AUTO_INCREMENT=83 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Mail aliases'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `mailAliasAccount` +-- + +DROP TABLE IF EXISTS `mailAliasAccount`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mailAliasAccount` ( + `mailAlias` int(10) unsigned NOT NULL, + `account` int(10) unsigned NOT NULL, + PRIMARY KEY (`mailAlias`,`account`), + KEY `account` (`account`), + CONSTRAINT `account` FOREIGN KEY (`account`) REFERENCES `account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `mailAlias` FOREIGN KEY (`mailAlias`) REFERENCES `mailAlias` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Mail alias that is assigned to each account'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `mailConfig` +-- + +DROP TABLE IF EXISTS `mailConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mailConfig` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `domain` varchar(255) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `mailForward` +-- + +DROP TABLE IF EXISTS `mailForward`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mailForward` ( + `account` int(10) unsigned NOT NULL, + `forwardTo` varchar(250) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`account`), + CONSTRAINT `mailForward_ibfk_1` FOREIGN KEY (`account`) REFERENCES `account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Mail forwarding'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `myRole` +-- + +DROP TABLE IF EXISTS `myRole`; +/*!50001 DROP VIEW IF EXISTS `myRole`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myRole` AS SELECT + 1 AS `id`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myUser` +-- + +DROP TABLE IF EXISTS `myUser`; +/*!50001 DROP VIEW IF EXISTS `myUser`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myUser` AS SELECT + 1 AS `id`, + 1 AS `name`, + 1 AS `active`, + 1 AS `email`, + 1 AS `nickname`, + 1 AS `lang`, + 1 AS `role`, + 1 AS `recoverPass`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `role` +-- + +DROP TABLE IF EXISTS `role`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `role` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(14) COLLATE utf8_unicode_ci NOT NULL COMMENT 'MySQL doesn''t support more than 14 chars for proxied user names', + `description` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `hasLogin` tinyint(3) unsigned NOT NULL DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `name` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Roles'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `roleConfig` +-- + +DROP TABLE IF EXISTS `roleConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `roleConfig` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Identifier', + `mysqlPassword` varchar(255) NOT NULL COMMENT 'The password used for MySQL user roles, base64 encoded', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='Role configuration parameters'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `roleInherit` +-- + +DROP TABLE IF EXISTS `roleInherit`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `roleInherit` ( + `role` int(10) unsigned NOT NULL, + `inheritsFrom` int(10) unsigned NOT NULL, + PRIMARY KEY (`role`,`inheritsFrom`), + KEY `owner_id` (`inheritsFrom`), + CONSTRAINT `roleInherit_ibfk_1` FOREIGN KEY (`role`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `roleInherit_ibfk_2` FOREIGN KEY (`inheritsFrom`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Role inheritance'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `roleRole` +-- + +DROP TABLE IF EXISTS `roleRole`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `roleRole` ( + `role` int(10) unsigned NOT NULL, + `inheritsFrom` int(10) unsigned NOT NULL, + UNIQUE KEY `role` (`role`,`inheritsFrom`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Calculated role inheritance'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `sambaConfig` +-- + +DROP TABLE IF EXISTS `sambaConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sambaConfig` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `host` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The hosname of Samba server', + `sshUser` varchar(30) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The SSH user to connect to servers', + `sshPass` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The SSH password base64 encoded', + `uidBase` int(10) unsigned NOT NULL DEFAULT '10000' COMMENT 'The base for Unix uids', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration parameters for accounts'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `user` +-- + +DROP TABLE IF EXISTS `user`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `user` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(30) CHARACTER SET utf8 NOT NULL, + `nickname` varchar(127) COLLATE utf8_unicode_ci NOT NULL, + `bcryptPassword` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `role` int(10) unsigned NOT NULL DEFAULT '2', + `active` tinyint(1) NOT NULL DEFAULT '1', + `email` varchar(255) CHARACTER SET utf8 DEFAULT NULL, + `lang` char(2) CHARACTER SET utf8 DEFAULT NULL, + `sync` tinyint(4) NOT NULL DEFAULT '0', + `recoverPass` tinyint(3) unsigned NOT NULL DEFAULT '1', + `lastPassChange` datetime DEFAULT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `password` char(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Deprecated', + PRIMARY KEY (`id`), + UNIQUE KEY `name` (`name`), + KEY `role` (`role`), + KEY `email` (`email`), + KEY `nickname` (`nickname`), + KEY `lang` (`lang`), + CONSTRAINT `user_ibfk_2` FOREIGN KEY (`role`) REFERENCES `role` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=17017 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global users'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `user_beforeInsert` + BEFORE INSERT ON `user` + FOR EACH ROW +BEGIN + CALL user_checkName(NEW.`name`); + + IF NEW.nickname = '' THEN + SET NEW.nickname = NEW.`name`; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `user_beforeUpdate` + BEFORE UPDATE ON `user` + FOR EACH ROW +BEGIN + IF !(NEW.`name` <=> OLD.`name`) THEN + CALL user_checkName (NEW.`name`); + END IF; + + IF NEW.`sync` <=> OLD.`sync` THEN + SET NEW.`sync` = FALSE; + END IF; + + IF !(NEW.`password` <=> OLD.`password`) THEN + SET NEW.bcryptPassword = NULL; + SET NEW.lastPassChange = NOW(); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `user_afterUpdate` + AFTER UPDATE ON `user` + FOR EACH ROW +BEGIN + IF !(NEW.`role` <=> OLD.`role`) + THEN + INSERT INTO vn.mail SET + `sender` = 'jgallego@verdnatura.es', + `replyTo` = 'jgallego@verdnatura.es', + `subject` = 'Rol modificado', + `body` = CONCAT(myUserGetName(), ' ha modificado el rol del usuario ', + NEW.`name`, ' de ', OLD.role, ' a ', NEW.role); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `userConfig` +-- + +DROP TABLE IF EXISTS `userConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `userConfig` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `loginKey` varchar(255) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `userPassword` +-- + +DROP TABLE IF EXISTS `userPassword`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `userPassword` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `length` tinyint(3) unsigned NOT NULL, + `nAlpha` tinyint(3) unsigned NOT NULL, + `nUpper` tinyint(3) unsigned NOT NULL, + `nDigits` tinyint(3) unsigned NOT NULL, + `nPunct` tinyint(3) unsigned NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Restrictions on user passwords'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'account' +-- + +-- +-- Dumping routines for database 'account' +-- +/*!50003 DROP FUNCTION IF EXISTS `myUserCheckLogin` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `myUserCheckLogin`() RETURNS tinyint(1) + READS SQL DATA + DETERMINISTIC +BEGIN +/** + * Checks that variables @userId and @userName haven't been altered. + * + * @return %TRUE if they are unaltered or unset, otherwise %FALSE + */ + DECLARE vSignature VARCHAR(128); + DECLARE vKey VARCHAR(255); + + IF @userId IS NOT NULL + AND @userName IS NOT NULL + AND @userSignature IS NOT NULL + THEN + SELECT loginKey INTO vKey FROM userConfig; + SET vSignature = util.hmacSha2(256, CONCAT_WS('/', @userId, @userName), vKey); + RETURN vSignature = @userSignature; + END IF; + + RETURN FALSE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `myUserGetId` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `MYUSERGETID`() RETURNS int(11) + READS SQL DATA + DETERMINISTIC +BEGIN +/** + * Returns the current user id. + * + * @return The user id + */ + DECLARE vUser INT DEFAULT NULL; + + IF myUserCheckLogin() + THEN + SET vUser = @userId; + ELSE + SELECT id INTO vUser FROM user + WHERE name = LEFT(USER(), INSTR(USER(), '@') - 1); + END IF; + + RETURN vUser; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `myUserGetName` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `myUserGetName`() RETURNS varchar(30) CHARSET utf8 + NO SQL + DETERMINISTIC +BEGIN +/** + * Returns the current user name. + * + * @return The user name + */ + DECLARE vUser VARCHAR(30) DEFAULT NULL; + + IF myUserCheckLogin() + THEN + SET vUser = @userName; + ELSE + SET vUser = LEFT(USER(), INSTR(USER(), '@') - 1); + END IF; + + RETURN vUser; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `myUserHasRole` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `myUserHasRole`(vRoleName VARCHAR(255)) RETURNS tinyint(1) + DETERMINISTIC +BEGIN +/** + * Comprueba si el usuario actual tiene asociado un rol. + * + * @param vRoleName Nombre del rol a comprobar + * @return %TRUE si tiene el rol, %FALSE en caso contrario + */ + RETURN userHasRole(myUserGetName(), vRoleName); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `myUserHasRoleId` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `myUserHasRoleId`(vRoleId INT) RETURNS tinyint(1) + DETERMINISTIC +BEGIN +/** + * Comprueba si el usuario actual tiene asociado un rol. + * + * @param vRoleId Identificador del rol a comprobar + * @return %TRUE si tiene el rol, %FALSE en caso contrario + */ + RETURN userHasRoleId(myUserGetName(), vRoleId); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `passwordGenerate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `passwordGenerate`() RETURNS text CHARSET utf8 +BEGIN +/** + * Genera una contraseña aleatoria + * cumpliendo los requisitos mínimos. + * + * @return Generated password + */ + DECLARE vMinLength TINYINT(3); + DECLARE vMinAlpha TINYINT(3); + DECLARE vMinUpper TINYINT(3); + DECLARE vMinDigits TINYINT(3); + DECLARE vMinPunct TINYINT(3); + DECLARE vAlpha TINYINT(3) DEFAULT 0; + DECLARE vUpper TINYINT(3) DEFAULT 0; + DECLARE vDigits TINYINT(3) DEFAULT 0; + DECLARE vPunct TINYINT(3) DEFAULT 0; + DECLARE vRandIndex INT; + DECLARE vPwd TEXT DEFAULT ''; + + DECLARE vAlphaChars TEXT DEFAULT 'abcdefghijklmnopqrstuvwxyz'; + DECLARE vUpperChars TEXT DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + DECLARE vDigitChars TEXT DEFAULT '1234567890'; + DECLARE vPunctChars TEXT DEFAULT '!$%&()=.'; + + SELECT length, nAlpha, nUpper, nDigits, nPunct + INTO vMinLength, vMinAlpha, vMinUpper, vMinDigits, vMinPunct FROM userPassword; + + WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha + OR vUpper < vMinUpper OR vDigits < vMinDigits OR vPunct < vMinPunct DO + SET vRandIndex = FLOOR((RAND() * 4) + 1); + + CASE + WHEN vRandIndex = 1 THEN + SET vPwd = CONCAT(vPwd, SUBSTRING(vAlphaChars, FLOOR((RAND() * 26) + 1), 1)); + SET vAlpha = vAlpha + 1; + WHEN vRandIndex = 2 THEN + SET vPwd = CONCAT(vPwd, SUBSTRING(vUpperChars, FLOOR((RAND() * 26) + 1), 1)); + SET vUpper = vUpper + 1; + WHEN vRandIndex = 3 THEN + SET vPwd = CONCAT(vPwd, SUBSTRING(vDigitChars, FLOOR((RAND() * 10) + 1), 1)); + SET vDigits = vDigits + 1; + WHEN vRandIndex = 4 THEN + SET vPwd = CONCAT(vPwd, SUBSTRING(vPunctChars, FLOOR((RAND() * LENGTH(vPunctChars)) + 1), 1)); + SET vPunct = vPunct + 1; + END CASE; + END WHILE; +RETURN vPwd; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `toUnixDays` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `toUnixDays`(vDate DATE) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Devuelve el timestamp unix en días de una fecha. + * + * @param vData La fecha + * @return Unix timestamp en días + */ + RETURN UNIX_TIMESTAMP(vDate) DIV 86400; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `userGetId` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `userGetId`() RETURNS int(11) + READS SQL DATA + DETERMINISTIC +BEGIN +/** + * @deprecated Use myUserGetId() + */ + RETURN myUserGetId(); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `userGetMysqlRole` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `userGetMysqlRole`(vUserName VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 +BEGIN +/** + * A partir de un nombre de usuario devuelve el rol + * de MySQL asociado y con el que deberia autenticarse + * cuando se utilice sistemas de autenticación externos. + * + * @param vUserName El nombre de usuario + * @return El rol de MySQL asociado + */ + DECLARE vRole VARCHAR(255); + + SELECT CONCAT(IF(r.hasLogin, 'z-', ''), r.name) INTO vRole + FROM role r + JOIN user u ON u.role = r.id + WHERE u.name = vUserName; + + RETURN vRole; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `userGetName` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `userGetName`() RETURNS varchar(30) CHARSET utf8 + NO SQL + DETERMINISTIC +BEGIN +/** + * @deprecated Use myUserGetName() + */ + RETURN myUserGetName(); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `userGetNameFromId` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `userGetNameFromId`(vId INT) RETURNS varchar(30) CHARSET utf8 +BEGIN +/** + * Obtener nombre de usuari a partir de su id + * + * @param vId Id del usuario + * @return Nombre de usuario + */ + DECLARE vName VARCHAR(30); + + SELECT `name` INTO vName + FROM user + WHERE id = vId; + + RETURN vName; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `userHasRole` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `userHasRole`(vUser VARCHAR(255), vRoleName VARCHAR(255)) RETURNS tinyint(1) + DETERMINISTIC +BEGIN +/** + * Comprueba si un usuario implementa un rol. + * + * @param vUser The user name + * @param vRoleName Nombre del rol a comprobar + * @return %TRUE si tiene el rol, %FALSE en caso contrario + */ + DECLARE vHasRole BOOL DEFAULT FALSE; + + SELECT COUNT(*) > 0 INTO vHasRole + FROM user u + JOIN roleRole rr ON rr.role = u.role + JOIN role r ON r.id = rr.inheritsFrom + WHERE u.`name` = vUser + AND r.`name` = vRoleName COLLATE 'utf8_unicode_ci'; + + RETURN vHasRole; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `userHasRoleId` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `userHasRoleId`(vUser VARCHAR(255), vRoleId INT) RETURNS tinyint(1) + DETERMINISTIC +BEGIN +/** + * Comprueba si un usuario implementa un rol. + * + * @param vUser The user name + * @param vRoleId Identificador del rol a comprobar + * @return %TRUE si tiene el rol, %FALSE en caso contrario + */ + DECLARE vHasRole BOOL DEFAULT FALSE; + + SELECT COUNT(*) > 0 INTO vHasRole + FROM user u + JOIN roleRole rr ON rr.role = u.role + JOIN role r ON r.id = rr.inheritsFrom + WHERE u.`name` = vUser + AND r.id = vRoleId; + + RETURN vHasRole; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myUserChangePassword` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myUserChangePassword`(vOldPassword VARCHAR(255), vPassword VARCHAR(255)) +BEGIN +/** + * Changes the current user password, if user is in recovery + * mode ignores the current password. + * + * @param vOldPassword The current password + * @param vPassword The new password + */ + DECLARE vPasswordOk BOOL; + + SELECT `password` = MD5(vOldPassword) OR recoverPass + INTO vPasswordOk + FROM user WHERE id = myUserGetId(); + + IF NOT vPasswordOk THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Invalid password'; + END IF; + + CALL userSetPassword(myUserGetName(), vPassword); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myUserLogout` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myUserLogout`() +BEGIN +/** + * Logouts the user. + */ + SET @userId = NULL; + SET @userName = NULL; + SET @userSignature = NULL; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `role_getDescendents` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `role_getDescendents`(vSelf INT) +BEGIN +/** + * Obtiene los identificadores de todos los subroles + * implementados por un rol (Incluido el mismo). + * + * @param vSelf Identificador del rol + * @table tmp.role Subroles implementados por el rol + */ + DECLARE vIsRoot BOOL; + + DROP TEMPORARY TABLE IF EXISTS + tmp.role, parents, childs; + + CREATE TEMPORARY TABLE tmp.role + (UNIQUE (id)) + ENGINE = MEMORY + SELECT vSelf AS id; + + CREATE TEMPORARY TABLE parents + ENGINE = MEMORY + SELECT vSelf AS id; + + CREATE TEMPORARY TABLE childs + LIKE parents; + + REPEAT + DELETE FROM childs; + INSERT INTO childs + SELECT DISTINCT r.inheritsFrom id + FROM parents p + JOIN roleInherit r ON r.role = p.id + LEFT JOIN tmp.role t ON t.id = r.inheritsFrom + WHERE t.id IS NULL; + + DELETE FROM parents; + INSERT INTO parents + SELECT * FROM childs; + + INSERT INTO tmp.role + SELECT * FROM childs; + + UNTIL ROW_COUNT() <= 0 + END REPEAT; + + -- If it is root all the roles are added + + SELECT COUNT(*) > 0 INTO vIsRoot + FROM tmp.role + WHERE id = 0; + + IF vIsRoot THEN + INSERT IGNORE INTO tmp.role (id) + SELECT id FROM role; + END IF; + + -- Cleaning + + DROP TEMPORARY TABLE + parents, childs; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `role_sync` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `role_sync`() +BEGIN +/** + * Sincroniza la tabla @roleRole con la jerarquía de roles + * actual. Este procedimiento debe ser llamado cada vez que + * se modifique la tabla @roleInherit para que los cambios + * realizados sobre esta sean efectivos. + */ + DECLARE vRoleId INT; + DECLARE vDone BOOL; + + DECLARE cur CURSOR FOR + SELECT id FROM role; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + TRUNCATE TABLE roleRole; + + OPEN cur; + + l: LOOP + SET vDone = FALSE; + FETCH cur INTO vRoleId; + + IF vDone THEN + LEAVE l; + END IF; + + CALL role_getDescendents(vRoleId); + + INSERT INTO roleRole (role, inheritsFrom) + SELECT vRoleId, id FROM tmp.role; + + DROP TEMPORARY TABLE tmp.role; + END LOOP; + + CLOSE cur; + + CALL role_syncPrivileges; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `role_syncPrivileges` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `role_syncPrivileges`() +BEGIN +/** + * Sincroniza los permisos de los usuarios 'rol' de MySQL + * en base a la jerarquía de roles. Los usuarios rol resultantes + * de la mezcla de permisos serán nombrados singuiendo el patrón + * z-[nombre_rol]. + * + * Si existe el usuario any@localhost que se tomará como plantilla + * para los atributos básicos. + * + * ¡Atención! Este procedimiento solo debe ser llamado cuando se + * modifiquen los privilegios de MySQL. Si se modifica la jerarquía + * de roles, se debe llamar al procedimiento roleSync() que llama a + * este internamente. + */ + DECLARE vTplUser VARCHAR(255) DEFAULT 'any'; + DECLARE vTplHost VARCHAR(255) DEFAULT '%'; + DECLARE vRoleHost VARCHAR(255) DEFAULT 'localhost'; + DECLARE vAllHost VARCHAR(255) DEFAULT '%'; + DECLARE vPrefix VARCHAR(2) DEFAULT 'z-'; + DECLARE vPrefixedLike VARCHAR(255); + + -- Borra todos los privilegios calculados + + SET vPrefixedLike = CONCAT(vPrefix, '%'); + + DELETE FROM mysql.user + WHERE `User` LIKE vPrefixedLike; + + DELETE FROM mysql.db + WHERE `User` LIKE vPrefixedLike; + + DELETE FROM mysql.tables_priv + WHERE `User` LIKE vPrefixedLike; + + DELETE FROM mysql.columns_priv + WHERE `User` LIKE vPrefixedLike; + + DELETE FROM mysql.procs_priv + WHERE `User` LIKE vPrefixedLike; + + DELETE FROM mysql.proxies_priv + WHERE `Proxied_user` LIKE vPrefixedLike; + + -- Tablas temporales + + DROP TEMPORARY TABLE IF EXISTS tRole; + CREATE TEMPORARY TABLE tRole + (INDEX (id)) + ENGINE = MEMORY + SELECT + id, + `name` role, + CONCAT(vPrefix, `name`) prefixedRole + FROM role + WHERE hasLogin; + + DROP TEMPORARY TABLE IF EXISTS tRoleInherit; + CREATE TEMPORARY TABLE tRoleInherit + (INDEX (inheritsFrom)) + ENGINE = MEMORY + SELECT + r.prefixedRole, + ri.`name` inheritsFrom + FROM tRole r + JOIN roleRole rr ON rr.role = r.id + JOIN role ri ON ri.id = rr.inheritsFrom; + + -- Vueve a crear el usuario + + INSERT INTO mysql.user ( + `User`, + `Host`, + `Password`, + `ssl_type`, + `ssl_cipher`, + `x509_issuer`, + `x509_subject`, + `max_questions`, + `max_updates`, + `max_connections`, + `max_user_connections` + ) + SELECT + r.prefixedRole, + vTplHost, + IFNULL(t.`Password`, ''), + IFNULL(IF('' != u.`ssl_type`, + u.`ssl_type`, t.`ssl_type`), + ''), + IFNULL(IF('' != u.`ssl_cipher`, + u.`ssl_cipher`, t.`ssl_cipher`), + ''), + IFNULL(IF('' != u.`x509_issuer`, + u.`x509_issuer`, t.`x509_issuer`), + ''), + IFNULL(IF('' != u.`x509_subject`, + u.`x509_subject`, t.`x509_subject`), + ''), + IFNULL(IF(0 != u.`max_questions`, + u.`max_questions`, t.`max_questions`), + 0), + IFNULL(IF(0 != u.`max_updates`, + u.`max_updates`, t.`max_updates`), + 0), + IFNULL(IF(0 != u.`max_connections`, + u.`max_connections`, t.`max_connections`), + 0), + IFNULL(IF(0 != u.`max_user_connections`, + u.`max_user_connections`, t.`max_user_connections`), + 0) + FROM tRole r + LEFT JOIN mysql.user t + ON t.`User` = vTplUser + AND t.`Host` = vRoleHost + LEFT JOIN mysql.user u + ON u.`User` = r.role + AND u.`Host` = vRoleHost; + + INSERT INTO mysql.proxies_priv ( + `User`, + `Host`, + `Proxied_user`, + `Proxied_host`, + `Grantor` + ) + SELECT + '', + vAllHost, + prefixedRole, + vTplHost, + CONCAT(prefixedRole, '@', vTplHost) + FROM tRole; + + -- Copia los privilegios globales del usuario + + DROP TEMPORARY TABLE IF EXISTS tUserPriv; + CREATE TEMPORARY TABLE tUserPriv + (INDEX (prefixedRole)) + ENGINE = MEMORY + SELECT + r.prefixedRole, + MAX(u.`Select_priv`) `Select_priv`, + MAX(u.`Insert_priv`) `Insert_priv`, + MAX(u.`Update_priv`) `Update_priv`, + MAX(u.`Delete_priv`) `Delete_priv`, + MAX(u.`Create_priv`) `Create_priv`, + MAX(u.`Drop_priv`) `Drop_priv`, + MAX(u.`Reload_priv`) `Reload_priv`, + MAX(u.`Shutdown_priv`) `Shutdown_priv`, + MAX(u.`Process_priv`) `Process_priv`, + MAX(u.`File_priv`) `File_priv`, + MAX(u.`Grant_priv`) `Grant_priv`, + MAX(u.`References_priv`) `References_priv`, + MAX(u.`Index_priv`) `Index_priv`, + MAX(u.`Alter_priv`) `Alter_priv`, + MAX(u.`Show_db_priv`) `Show_db_priv`, + MAX(u.`Super_priv`) `Super_priv`, + MAX(u.`Create_tmp_table_priv`) `Create_tmp_table_priv`, + MAX(u.`Lock_tables_priv`) `Lock_tables_priv`, + MAX(u.`Execute_priv`) `Execute_priv`, + MAX(u.`Repl_slave_priv`) `Repl_slave_priv`, + MAX(u.`Repl_client_priv`) `Repl_client_priv`, + MAX(u.`Create_view_priv`) `Create_view_priv`, + MAX(u.`Show_view_priv`) `Show_view_priv`, + MAX(u.`Create_routine_priv`) `Create_routine_priv`, + MAX(u.`Alter_routine_priv`) `Alter_routine_priv`, + MAX(u.`Create_user_priv`) `Create_user_priv`, + MAX(u.`Event_priv`) `Event_priv`, + MAX(u.`Trigger_priv`) `Trigger_priv`, + MAX(u.`Create_tablespace_priv`) `Create_tablespace_priv` + FROM tRoleInherit r + JOIN mysql.user u + ON u.`User` = r.inheritsFrom + AND u.`Host`= vRoleHost + GROUP BY r.prefixedRole; + + UPDATE mysql.user u + JOIN tUserPriv t + ON u.`User` = t.prefixedRole + AND u.`Host` = vTplHost + SET + u.`Select_priv` + = t.`Select_priv`, + u.`Insert_priv` + = t.`Insert_priv`, + u.`Update_priv` + = t.`Update_priv`, + u.`Delete_priv` + = t.`Delete_priv`, + u.`Create_priv` + = t.`Create_priv`, + u.`Drop_priv` + = t.`Drop_priv`, + u.`Reload_priv` + = t.`Reload_priv`, + u.`Shutdown_priv` + = t.`Shutdown_priv`, + u.`Process_priv` + = t.`Process_priv`, + u.`File_priv` + = t.`File_priv`, + u.`Grant_priv` + = t.`Grant_priv`, + u.`References_priv` + = t.`References_priv`, + u.`Index_priv` + = t.`Index_priv`, + u.`Alter_priv` + = t.`Alter_priv`, + u.`Show_db_priv` + = t.`Show_db_priv`, + u.`Super_priv` + = t.`Super_priv`, + u.`Create_tmp_table_priv` + = t.`Create_tmp_table_priv`, + u.`Lock_tables_priv` + = t.`Lock_tables_priv`, + u.`Execute_priv` + = t.`Execute_priv`, + u.`Repl_slave_priv` + = t.`Repl_slave_priv`, + u.`Repl_client_priv` + = t.`Repl_client_priv`, + u.`Create_view_priv` + = t.`Create_view_priv`, + u.`Show_view_priv` + = t.`Show_view_priv`, + u.`Create_routine_priv` + = t.`Create_routine_priv`, + u.`Alter_routine_priv` + = t.`Alter_routine_priv`, + u.`Create_user_priv` + = t.`Create_user_priv`, + u.`Event_priv` + = t.`Event_priv`, + u.`Trigger_priv` + = t.`Trigger_priv`, + u.`Create_tablespace_priv` + = t.`Create_tablespace_priv`; + + DROP TEMPORARY TABLE tUserPriv; + + -- Copia los privilegios a nivel de esquema + + INSERT INTO mysql.db ( + `User`, + `Host`, + `Db`, + `Select_priv`, + `Insert_priv`, + `Update_priv`, + `Delete_priv`, + `Create_priv`, + `Drop_priv`, + `Grant_priv`, + `References_priv`, + `Index_priv`, + `Alter_priv`, + `Create_tmp_table_priv`, + `Lock_tables_priv`, + `Create_view_priv`, + `Show_view_priv`, + `Create_routine_priv`, + `Alter_routine_priv`, + `Execute_priv`, + `Event_priv`, + `Trigger_priv` + ) + SELECT + r.prefixedRole, + vTplHost, + t.`Db`, + MAX(t.`Select_priv`), + MAX(t.`Insert_priv`), + MAX(t.`Update_priv`), + MAX(t.`Delete_priv`), + MAX(t.`Create_priv`), + MAX(t.`Drop_priv`), + MAX(t.`Grant_priv`), + MAX(t.`References_priv`), + MAX(t.`Index_priv`), + MAX(t.`Alter_priv`), + MAX(t.`Create_tmp_table_priv`), + MAX(t.`Lock_tables_priv`), + MAX(t.`Create_view_priv`), + MAX(t.`Show_view_priv`), + MAX(t.`Create_routine_priv`), + MAX(t.`Alter_routine_priv`), + MAX(t.`Execute_priv`), + MAX(t.`Event_priv`), + MAX(t.`Trigger_priv`) + FROM tRoleInherit r + JOIN mysql.db t + ON t.`User` = r.inheritsFrom + AND t.`Host`= vRoleHost + GROUP BY r.prefixedRole, t.`Db`; + + -- Copia los privilegios a nivel de tabla + + INSERT INTO mysql.tables_priv ( + `User`, + `Host`, + `Db`, + `Table_name`, + `Grantor`, + `Timestamp`, + `Table_priv`, + `Column_priv` + ) + SELECT + r.prefixedRole, + vTplHost, + t.`Db`, + t.`Table_name`, + t.`Grantor`, + MAX(t.`Timestamp`), + IFNULL(GROUP_CONCAT(NULLIF(t.`Table_priv`, '')), ''), + IFNULL(GROUP_CONCAT(NULLIF(t.`Column_priv`, '')), '') + FROM tRoleInherit r + JOIN mysql.tables_priv t + ON t.`User` = r.inheritsFrom + AND t.`Host`= vRoleHost + GROUP BY r.prefixedRole, t.`Db`, t.`Table_name`; + + -- Copia los privilegios a nivel de columna + + INSERT INTO mysql.columns_priv ( + `User`, + `Host`, + `Db`, + `Table_name`, + `Column_name`, + `Timestamp`, + `Column_priv` + ) + SELECT + r.prefixedRole, + vTplHost, + t.`Db`, + t.`Table_name`, + t.`Column_name`, + MAX(t.`Timestamp`), + IFNULL(GROUP_CONCAT(NULLIF(t.`Column_priv`, '')), '') + FROM tRoleInherit r + JOIN mysql.columns_priv t + ON t.`User` = r.inheritsFrom + AND t.`Host`= vRoleHost + GROUP BY r.prefixedRole, t.`Db`, t.`Table_name`, t.`Column_name`; + + -- Copia los privilegios de los procedimientos + + INSERT IGNORE INTO mysql.procs_priv ( + `User`, + `Host`, + `Db`, + `Routine_name`, + `Routine_type`, + `Grantor`, + `Timestamp`, + `Proc_priv` + ) + SELECT + r.prefixedRole, + vTplHost, + t.`Db`, + t.`Routine_name`, + t.`Routine_type`, + t.`Grantor`, + t.`Timestamp`, + t.`Proc_priv` + FROM tRoleInherit r + JOIN mysql.procs_priv t + ON t.`User` = r.inheritsFrom + AND t.`Host`= vRoleHost; + + -- Libera memoria + + DROP TEMPORARY TABLE + tRole, + tRoleInherit; + + FLUSH PRIVILEGES; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `userLogin` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `userLogin`(vUserName VARCHAR(255), vPassword VARCHAR(255)) + READS SQL DATA +BEGIN +/** + * Logs in using the user credentials. + * + * @param vUserName The user name + * @param vPassword The user password + */ + DECLARE vAuthIsOk BOOLEAN DEFAULT FALSE; + + SELECT COUNT(*) = 1 INTO vAuthIsOk FROM user + WHERE name = vUserName + AND password = MD5(vPassword) + AND active; + + IF vAuthIsOk + THEN + CALL userLoginWithName (vUserName); + ELSE + CALL util.throw ('INVALID_CREDENTIALS'); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `userLoginWithKey` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `userLoginWithKey`(vUserName VARCHAR(255), vKey VARCHAR(255)) + READS SQL DATA +BEGIN +/** + * Logs in using the user name and MySQL master key. + * + * @param vUserName The user name + * @param vKey The MySQL master key + */ + DECLARE vLoginKey VARCHAR(255); + + SELECT loginKey INTO vLoginKey FROM userConfig; + + IF vLoginKey = vKey THEN + CALL userLoginWithName(vUserName); + ELSE + CALL util.throw('INVALID_KEY'); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `userLoginWithName` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `userLoginWithName`(vUserName VARCHAR(255)) + READS SQL DATA +BEGIN +/** + * Logs in using only the user name. This procedure is + * intended to be executed by users with a high level + * of privileges so that normal users should not have + * execute permissions on it + * + * @param vUserName The user name + */ + DECLARE vUserId INT DEFAULT NULL; + DECLARE vKey VARCHAR(255); + + SELECT id INTO vUserId FROM user + WHERE name = vUserName; + + SELECT loginKey INTO vKey FROM userConfig; + + SET @userId = vUserId; + SET @userName = vUserName; + SET @userSignature = util.hmacSha2(256, CONCAT_WS('/', vUserId, vUserName), vKey); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `userSetPassword` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `userSetPassword`(vUserName VARCHAR(255), vPassword VARCHAR(255)) +BEGIN +/** + * Cambia la contraseña del usuario pasado como parámetro. + * Solo los administradores deberian de tener privilegios de + * ejecución sobre el procedimiento ya que no solicita la + * contraseña actual del usuario. + * + * @param vUserName Nombre de usuario + * @param vPassword Nueva contraseña + */ + DECLARE vSelf INT; + + CALL user_checkPassword(vPassword); + + SELECT id INTO vSelf + FROM user WHERE `name` = vUserName; + + UPDATE user SET + `password` = MD5(vPassword), + `recoverPass` = FALSE + WHERE id = vSelf; + + CALL user_syncPassword(vSelf, vPassword); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `user_checkName` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `user_checkName`(vUserName VARCHAR(255)) +BEGIN +/** + * Comprueba que el nombre de usuario reune los requisitos + * de sintaxis necesarios, en caso contrario lanza una + * excepción. + * El nombre de usuario solo debe contener letras minúsculas + * o, a partir del segundo carácter, números o subguiones. + */ + IF vUserName NOT REGEXP '^[a-z0-9_-]*$' THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'INVALID_USER_NAME'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `user_checkPassword` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `user_checkPassword`(vPassword VARCHAR(255)) +BEGIN +/** + * Comprueba si la contraseña cumple los requisitos de seguridad + * establecidos. Lanza una excepción si no se cumplen. + * + * @param vPassword Contraseña a comprobar + */ + DECLARE vChr CHAR(1); + DECLARE vPasswordOk TINYINT; + DECLARE vI TINYINT DEFAULT 1; + DECLARE vNAlpha TINYINT DEFAULT 0; + DECLARE vNUpper TINYINT DEFAULT 0; + DECLARE vNDigits TINYINT DEFAULT 0; + DECLARE vNPunct TINYINT DEFAULT 0; + + WHILE vI <= CHAR_LENGTH(vPassword) + DO + SET vChr = SUBSTRING(vPassword, vI, 1); + + IF vChr REGEXP '[[:alpha:]]' + THEN + SET vNAlpha = vNAlpha+1; + + IF vChr REGEXP '[A-Z]' + THEN + SET vNUpper = vNUpper+1; + END IF; + ELSEIF vChr REGEXP '[[:digit:]]' + THEN + SET vNDigits = vNDigits+1; + ELSEIF vChr REGEXP '[[:punct:]]' + THEN + SET vNPunct = vNPunct+1; + END IF; + + SET vI = vI+1; + END WHILE; + + SELECT + CHAR_LENGTH(vPassword) >= length + AND vNAlpha >= nAlpha + AND vNUpper >= nUpper + AND vNDigits >= nDigits + AND vNPunct >= nPunct + INTO vPasswordOk + FROM userPassword LIMIT 1; + + IF NOT vPasswordOk THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Password does not meet requirements'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `user_syncPassword` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `user_syncPassword`( + vSelf VARCHAR(255), + vPassword VARCHAR(255) +) +BEGIN +/** + * Synchronizes the user password in other schemes. + * + * @param vSelf The user id + * @param vPassword The user password + */ + CALL pbx.sip_setPassword(vSelf, vPassword); + + DELETE FROM salix.user WHERE id = vSelf; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Current Database: `bi` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bi` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; + +USE `bi`; + +-- +-- Table structure for table `Equalizator` +-- + +DROP TABLE IF EXISTS `Equalizator`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `Equalizator` ( + `Vista` int(11) NOT NULL, + `Pedido` int(11) DEFAULT NULL, + `Impreso` int(11) DEFAULT NULL, + `Encajado` int(11) DEFAULT NULL, + PRIMARY KEY (`Vista`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Greuge_Evolution` +-- + +DROP TABLE IF EXISTS `Greuge_Evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `Greuge_Evolution` ( + `Id_Cliente` int(11) NOT NULL, + `Fecha` date NOT NULL, + `Greuge` decimal(10,2) NOT NULL DEFAULT '0.00', + `Ventas` decimal(10,2) NOT NULL DEFAULT '0.00', + `Fosil` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT 'greuge fósil, correspondiente a los clientes muertos', + `Recobro` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`Id_Cliente`,`Fecha`), + KEY `greuge_evolution_idx1` (`Fecha`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacenamos la evolucion del greuge de los ultimos dias '; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Greuge_comercial_recobro` +-- + +DROP TABLE IF EXISTS `Greuge_comercial_recobro`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `Greuge_comercial_recobro` ( + `Id_Trabajador` int(11) NOT NULL, + `recobro` decimal(10,2) NOT NULL DEFAULT '0.00', + `peso_cartera` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`Id_Trabajador`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Greuges_comercial_detail` +-- + +DROP TABLE IF EXISTS `Greuges_comercial_detail`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `Greuges_comercial_detail` ( + `Id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `Id_Trabajador` int(10) unsigned NOT NULL, + `Comentario` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `Importe` decimal(10,2) NOT NULL, + `Fecha` datetime DEFAULT NULL, + PRIMARY KEY (`Id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=COMPACT; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Last_buy_id` +-- + +DROP TABLE IF EXISTS `Last_buy_id`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `Last_buy_id` ( + `Id_Article` int(11) NOT NULL DEFAULT '90', + `Id_Compra` int(11) NOT NULL DEFAULT '0', + `warehouse_id` smallint(6) unsigned NOT NULL, + PRIMARY KEY (`warehouse_id`,`Id_Article`), + UNIQUE KEY `Id_Compra_UNIQUE` (`Id_Compra`), + CONSTRAINT `Id_CompraFK` FOREIGN KEY (`Id_Compra`) REFERENCES `vn`.`buy` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Ticket_Portes` +-- + +DROP TABLE IF EXISTS `Ticket_Portes`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `Ticket_Portes` ( + `Id_Ticket` int(11) NOT NULL, + `rate` tinyint(4) NOT NULL COMMENT 'Tarifa', + `real_amount` double NOT NULL COMMENT 'Cantidad pactada con la agencia', + `payed_amount` double NOT NULL COMMENT 'Cantidad reflejada en el Ticket', + PRIMARY KEY (`Id_Ticket`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `XDiario_ALL` +-- + +DROP TABLE IF EXISTS `XDiario_ALL`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `XDiario_ALL` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `empresa_id` int(5) NOT NULL, + `SUBCTA` varchar(11) COLLATE utf8_unicode_ci NOT NULL, + `Eurodebe` double DEFAULT NULL, + `Eurohaber` double DEFAULT NULL, + `Fecha` date DEFAULT NULL, + `FECHA_EX` date DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `Cuenta` (`SUBCTA`), + KEY `empresa` (`empresa_id`), + KEY `Fecha` (`Fecha`) +) ENGINE=InnoDB AUTO_INCREMENT=16385456 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `analisis_grafico_simple` +-- + +DROP TABLE IF EXISTS `analisis_grafico_simple`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `analisis_grafico_simple` ( + `Año` smallint(5) unsigned NOT NULL, + `Semana` tinyint(3) unsigned NOT NULL, + `Importe` double DEFAULT NULL, + UNIQUE KEY `Año` (`Año`,`Semana`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `analisis_grafico_ventas` +-- + +DROP TABLE IF EXISTS `analisis_grafico_ventas`; +/*!50001 DROP VIEW IF EXISTS `analisis_grafico_ventas`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `analisis_grafico_ventas` AS SELECT + 1 AS `Año`, + 1 AS `Semana`, + 1 AS `Importe`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `analisis_ventas` +-- + +DROP TABLE IF EXISTS `analisis_ventas`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `analisis_ventas` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `Familia` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `Reino` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `Comercial` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `Comprador` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `Provincia` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `almacen` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + `Año` smallint(5) unsigned NOT NULL, + `Mes` tinyint(3) unsigned NOT NULL, + `Semana` tinyint(3) unsigned NOT NULL, + `Vista` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `Importe` double NOT NULL, + PRIMARY KEY (`id`), + KEY `Año` (`Año`,`Semana`) +) ENGINE=InnoDB AUTO_INCREMENT=122757475 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `analisis_ventas_almacen_evolution` +-- + +DROP TABLE IF EXISTS `analisis_ventas_almacen_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `analisis_ventas_almacen_evolution` ( + `Semana` int(11) NOT NULL, + `Almacen` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + `Ventas` int(11) NOT NULL, + `Año` int(11) NOT NULL, + `Periodo` int(11) NOT NULL, + UNIQUE KEY `Almacen` (`Almacen`,`Periodo`), + KEY `Periodo` (`Periodo`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `analisis_ventas_comprador_evolution` +-- + +DROP TABLE IF EXISTS `analisis_ventas_comprador_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `analisis_ventas_comprador_evolution` ( + `semana` int(11) NOT NULL, + `comprador` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `ventas` int(11) NOT NULL, + `año` int(11) NOT NULL, + `periodo` int(11) NOT NULL, + UNIQUE KEY `comprador` (`comprador`,`periodo`), + KEY `periodo` (`periodo`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `analisis_ventas_familia_evolution` +-- + +DROP TABLE IF EXISTS `analisis_ventas_familia_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `analisis_ventas_familia_evolution` ( + `semana` int(11) NOT NULL, + `familia` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `ventas` int(11) NOT NULL, + `año` int(11) NOT NULL, + `periodo` int(11) NOT NULL, + UNIQUE KEY `familia` (`familia`,`periodo`), + KEY `periodo` (`periodo`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `analisis_ventas_provincia_evolution` +-- + +DROP TABLE IF EXISTS `analisis_ventas_provincia_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `analisis_ventas_provincia_evolution` ( + `semana` int(11) NOT NULL, + `provincia` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `ventas` int(11) NOT NULL, + `año` int(11) NOT NULL, + `periodo` int(11) NOT NULL, + UNIQUE KEY `provincia` (`provincia`,`periodo`), + KEY `periodo` (`periodo`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `analisis_ventas_reino_evolution` +-- + +DROP TABLE IF EXISTS `analisis_ventas_reino_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `analisis_ventas_reino_evolution` ( + `semana` int(11) NOT NULL, + `reino` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + `ventas` int(11) NOT NULL, + `año` int(11) NOT NULL, + `periodo` int(11) NOT NULL, + UNIQUE KEY `reino` (`reino`,`periodo`), + KEY `periodo` (`periodo`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `analisis_ventas_simple` +-- + +DROP TABLE IF EXISTS `analisis_ventas_simple`; +/*!50001 DROP VIEW IF EXISTS `analisis_ventas_simple`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `analisis_ventas_simple` AS SELECT + 1 AS `Año`, + 1 AS `Semana`, + 1 AS `Importe`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `analisis_ventas_vendedor_evolution` +-- + +DROP TABLE IF EXISTS `analisis_ventas_vendedor_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `analisis_ventas_vendedor_evolution` ( + `semana` int(11) NOT NULL, + `vendedor` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `ventas` int(11) NOT NULL, + `año` int(11) NOT NULL, + `periodo` int(11) NOT NULL, + UNIQUE KEY `vendedor` (`vendedor`,`periodo`), + KEY `periodo` (`periodo`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `analisis_ventas_vista_evolution` +-- + +DROP TABLE IF EXISTS `analisis_ventas_vista_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `analisis_ventas_vista_evolution` ( + `semana` int(11) NOT NULL, + `vista` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `ventas` int(11) NOT NULL, + `año` int(11) NOT NULL, + `periodo` int(11) NOT NULL, + UNIQUE KEY `vista` (`vista`,`periodo`), + KEY `periodo` (`periodo`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `calidad_detalle` +-- + +DROP TABLE IF EXISTS `calidad_detalle`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `calidad_detalle` ( + `Id_Cliente` int(11) NOT NULL, + `calidad_parametros_id` int(2) NOT NULL, + `valor` int(3) DEFAULT NULL, + PRIMARY KEY (`Id_Cliente`,`calidad_parametros_id`), + KEY `calidad_parametros_detalle_idx` (`calidad_parametros_id`), + CONSTRAINT `calidad_parametros_detalle` FOREIGN KEY (`calidad_parametros_id`) REFERENCES `calidad_parametros` (`calidad_parametros_id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `calidad_parametros` +-- + +DROP TABLE IF EXISTS `calidad_parametros`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `calidad_parametros` ( + `calidad_parametros_id` int(2) NOT NULL, + `descripcion` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`calidad_parametros_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `claims_ratio` +-- + +DROP TABLE IF EXISTS `claims_ratio`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `claims_ratio` ( + `Id_Cliente` int(11) NOT NULL DEFAULT '0', + `Consumo` decimal(10,2) DEFAULT NULL, + `Reclamaciones` decimal(10,2) DEFAULT NULL, + `Ratio` decimal(5,2) DEFAULT NULL, + `recobro` decimal(5,2) DEFAULT NULL, + `inflacion` decimal(5,2) NOT NULL DEFAULT '1.00', + PRIMARY KEY (`Id_Cliente`), + CONSTRAINT `claims_ratio_ibfk_1` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `customerDebtInventory` +-- + +DROP TABLE IF EXISTS `customerDebtInventory`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `customerDebtInventory` ( + `Id_Cliente` int(11) NOT NULL, + `Debt` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT 'CREATE TABLE bi.customerDebtInventory\n\nSELECT Id_Cliente, sum(Euros) as Debt\n\nFROM \n(\nSELECT Id_Cliente, Entregado as Euros\n\nFROM Recibos \n\nWHERE Fechacobro < ''2017-01-01\n''\nUNION ALL\n\nSELECT Id_Cliente, - Importe \nFROM Facturas\nWHERE Fecha < ''2017-01-01''\n) sub \nGROUP BY Id_Cliente', + PRIMARY KEY (`Id_Cliente`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `customerRiskOverdue` +-- + +DROP TABLE IF EXISTS `customerRiskOverdue`; +/*!50001 DROP VIEW IF EXISTS `customerRiskOverdue`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `customerRiskOverdue` AS SELECT + 1 AS `customer_id`, + 1 AS `amount`, + 1 AS `company_id`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `customer_risk` +-- + +DROP TABLE IF EXISTS `customer_risk`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `customer_risk` ( + `customer_id` int(11) NOT NULL DEFAULT '0', + `company_id` smallint(6) unsigned NOT NULL DEFAULT '0', + `amount` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`customer_id`,`company_id`), + KEY `company_id` (`company_id`), + CONSTRAINT `customer_risk_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `customer_risk_ibfk_2` FOREIGN KEY (`company_id`) REFERENCES `vn`.`company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Saldo de apertura < 2015-01-01'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `defaulters` +-- + +DROP TABLE IF EXISTS `defaulters`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `defaulters` ( + `client` int(11) NOT NULL, + `date` date NOT NULL, + `amount` double NOT NULL DEFAULT '0', + `defaulterSince` date DEFAULT NULL, + `hasChanged` tinyint(1) DEFAULT NULL, + `frozened` date DEFAULT NULL, + PRIMARY KEY (`client`,`date`), + KEY `client` (`client`), + KEY `date` (`date`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `defaulting` +-- + +DROP TABLE IF EXISTS `defaulting`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `defaulting` ( + `date` date NOT NULL, + `amount` double NOT NULL, + PRIMARY KEY (`date`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `f_tvc` +-- + +DROP TABLE IF EXISTS `f_tvc`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `f_tvc` ( + `Id_Ticket` int(11) NOT NULL, + PRIMARY KEY (`Id_Ticket`), + CONSTRAINT `id_ticket_to_comisionantes` FOREIGN KEY (`Id_Ticket`) REFERENCES `vn`.`ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacenamos la lista de tickets para agilizar la consulta. Corresponde a los clientes REAL y en los almacenes COMISIONANTES'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `facturacion_media_anual` +-- + +DROP TABLE IF EXISTS `facturacion_media_anual`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `facturacion_media_anual` ( + `Id_Cliente` int(11) NOT NULL, + `Consumo` double(17,0) DEFAULT NULL, + PRIMARY KEY (`Id_Cliente`), + CONSTRAINT `fmaId_Cliente` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `lastaction` +-- + +DROP TABLE IF EXISTS `lastaction`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `lastaction` ( + `Id_Cliente` int(11) unsigned NOT NULL, + `Cliente` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `Ultima_accion` date DEFAULT NULL, + `Comercial` varchar(3) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`Id_Cliente`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `live_counter` +-- + +DROP TABLE IF EXISTS `live_counter`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `live_counter` ( + `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `amount` double NOT NULL, + PRIMARY KEY (`odbc_date`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `partitioning_information` +-- + +DROP TABLE IF EXISTS `partitioning_information`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `partitioning_information` ( + `schema_name` varchar(10) CHARACTER SET utf8 NOT NULL, + `table_name` varchar(20) CHARACTER SET utf8 NOT NULL, + `date_field` varchar(20) CHARACTER SET utf8 DEFAULT NULL, + `table_depending` varchar(15) CHARACTER SET utf8 DEFAULT NULL, + `execution_order` tinyint(3) unsigned NOT NULL, + PRIMARY KEY (`schema_name`,`table_name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `primer_pedido` +-- + +DROP TABLE IF EXISTS `primer_pedido`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `primer_pedido` ( + `Id_Cliente` int(11) NOT NULL, + `Id_Ticket` int(11) NOT NULL, + `month` tinyint(1) NOT NULL, + `year` smallint(2) NOT NULL, + `total` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`Id_Cliente`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `rotacion` +-- + +DROP TABLE IF EXISTS `rotacion`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `rotacion` ( + `Id_Article` int(11) NOT NULL, + `warehouse_id` smallint(6) unsigned NOT NULL, + `total` int(10) NOT NULL DEFAULT '0', + `rotacion` decimal(10,4) NOT NULL DEFAULT '0.0000', + `cm3` int(11) NOT NULL DEFAULT '0', + `almacenaje` decimal(10,4) NOT NULL DEFAULT '0.0000', + `manipulacion` decimal(10,4) NOT NULL DEFAULT '0.0000', + `auxiliar` decimal(10,4) NOT NULL DEFAULT '0.0000', + `mermas` decimal(10,4) NOT NULL DEFAULT '0.0000', + `cm3reparto` int(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`Id_Article`,`warehouse_id`), + KEY `warehouse_id_rotacion_idx` (`warehouse_id`), + CONSTRAINT `id_article_rotaci` FOREIGN KEY (`Id_Article`) REFERENCES `vn`.`item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `warehouse_id_rotaci` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los valores de rotacion en los ultimos 365 dias'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bi`.`rotacion_beforeInsert` + BEFORE INSERT ON `rotacion` + FOR EACH ROW +BEGIN + IF NEW.Id_Article IN (95, 98) THEN + SET NEW.cm3 = 0; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bi`.`rotacion_beforeUpdate` + BEFORE UPDATE ON `rotacion` + FOR EACH ROW +BEGIN + IF NEW.Id_Article IN (95, 98) THEN + SET NEW.cm3 = 0; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `rutasBoard` +-- + +DROP TABLE IF EXISTS `rutasBoard`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `rutasBoard` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `Id_Ruta` int(10) unsigned NOT NULL DEFAULT '0', + `Id_Agencia` int(11) NOT NULL DEFAULT '0', + `km` bigint(10) NOT NULL DEFAULT '0', + `Dia` varchar(9) CHARACTER SET utf8 DEFAULT NULL, + `Fecha` date NOT NULL, + `Terceros` int(11) NOT NULL DEFAULT '0', + `Bultos` int(11) NOT NULL DEFAULT '0', + `Matricula` varchar(10) COLLATE utf8_unicode_ci, + `Tipo` varchar(1) CHARACTER SET utf8 NOT NULL DEFAULT '', + `year` int(4) NOT NULL, + `month` int(2) NOT NULL, + `warehouse_id` smallint(5) unsigned NOT NULL COMMENT 'A nulo si se puede enrutar desde todos los almacenes', + `coste_bulto` decimal(10,2) unsigned NOT NULL DEFAULT '0.00', + `teorico` decimal(10,2) NOT NULL DEFAULT '0.00', + `practico` decimal(10,2) NOT NULL DEFAULT '0.00', + `greuge` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`id`), + UNIQUE KEY `rutasBoard_Ruta` (`Id_Ruta`), + KEY `rutasBoard_ix1` (`year`), + KEY `rutasBoard_ix2` (`month`), + KEY `rutasBoard_ix3` (`warehouse_id`) +) ENGINE=InnoDB AUTO_INCREMENT=204333 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `saleVolume` +-- + +DROP TABLE IF EXISTS `saleVolume`; +/*!50001 DROP VIEW IF EXISTS `saleVolume`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `saleVolume` AS SELECT + 1 AS `saleFk`, + 1 AS `m3`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `tarifa_componentes` +-- + +DROP TABLE IF EXISTS `tarifa_componentes`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tarifa_componentes` ( + `Id_Componente` int(11) NOT NULL AUTO_INCREMENT, + `Componente` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `tarifa_componentes_series_id` int(11) NOT NULL, + `tarifa_class` smallint(6) DEFAULT NULL, + `tax` double DEFAULT NULL, + `is_renewable` tinyint(2) NOT NULL DEFAULT '1', + `code` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`Id_Componente`), + KEY `series_componentes_idx` (`tarifa_componentes_series_id`), + KEY `comp` (`tarifa_class`), + CONSTRAINT `serie_componente` FOREIGN KEY (`tarifa_componentes_series_id`) REFERENCES `tarifa_componentes_series` (`tarifa_componentes_series_id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tarifa_componentes_series` +-- + +DROP TABLE IF EXISTS `tarifa_componentes_series`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tarifa_componentes_series` ( + `tarifa_componentes_series_id` int(11) NOT NULL AUTO_INCREMENT, + `Serie` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `base` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Marca aquellas series que se utilizan para calcular el precio base de las ventas, a efectos estadisticos', + `margen` tinyint(4) NOT NULL DEFAULT '0', + PRIMARY KEY (`tarifa_componentes_series_id`), + UNIQUE KEY `Serie_UNIQUE` (`Serie`) +) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Permite organizar de forma ordenada los distintos componentes'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tarifa_premisas` +-- + +DROP TABLE IF EXISTS `tarifa_premisas`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tarifa_premisas` ( + `Id_Premisa` int(11) NOT NULL AUTO_INCREMENT, + `premisa` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`Id_Premisa`) +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tarifa_warehouse` +-- + +DROP TABLE IF EXISTS `tarifa_warehouse`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tarifa_warehouse` ( + `Id_Tarifa_Warehouse` int(11) NOT NULL AUTO_INCREMENT, + `warehouse_id` int(11) NOT NULL, + `Id_Premisa` int(11) NOT NULL, + `Valor` double NOT NULL, + PRIMARY KEY (`Id_Tarifa_Warehouse`) +) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los valores de gasto por almacen'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'bi' +-- + +-- +-- Dumping routines for database 'bi' +-- +/*!50003 DROP FUNCTION IF EXISTS `nz` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = '' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `nz`(dblCANTIDAD DOUBLE) RETURNS double +BEGIN + +DECLARE dblRESULT DOUBLE; + +SET dblRESULT = IFNULL(dblCANTIDAD,0); + +RETURN dblRESULT; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `analisis_ventas_evolution_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `analisis_ventas_evolution_add`() +BEGIN + DECLARE vPreviousPeriod INT; + DECLARE vCurrentPeriod INT; + DECLARE vLastPeriod INT; + DECLARE vMinPeriod INT DEFAULT 201400; + DECLARE vMaxPeriod INT DEFAULT vn2008.vnperiod(CURDATE()); + + DECLARE vYear INT; + DECLARE vWeek INT; + + -- Almacen + + SET vCurrentPeriod = IFNULL(vLastPeriod, vMinPeriod); + + WHILE vCurrentPeriod < vMaxPeriod + DO + SELECT MAX(Periodo) INTO vPreviousPeriod + FROM bi.analisis_ventas_almacen_evolution + WHERE Periodo < vMaxPeriod; + + SELECT MIN(period) INTO vCurrentPeriod + FROM vn2008.time + WHERE period > vPreviousPeriod; + + SET vYear = FLOOR(vCurrentPeriod / 100); + SET vWeek = vCurrentPeriod - (vYear * 100); + + DELETE FROM bi.analisis_ventas_almacen_evolution + WHERE Periodo = vCurrentPeriod; + + REPLACE bi.analisis_ventas_almacen_evolution(Almacen, Ventas, Semana,Año, Periodo) + SELECT Almacen, sum(Ventas) AS Ventas, vWeek, vYear, vCurrentPeriod + FROM ( + SELECT almacen, sum(Importe) AS Ventas + FROM bi.analisis_ventas + WHERE vYear = Año + AND vWeek = Semana + GROUP BY almacen + UNION ALL + SELECT almacen, - sum(Importe) AS Ventas + FROM bi.analisis_ventas + WHERE vYear - 1 = Año + AND vWeek = Semana + GROUP BY almacen + UNION ALL + SELECT Almacen, Ventas + FROM bi.analisis_ventas_almacen_evolution + WHERE Periodo = vPreviousPeriod + ) sub + GROUP BY Almacen; + END WHILE; + + -- Reino + + SET vCurrentPeriod = vMinPeriod; + + WHILE vCurrentPeriod < vMaxPeriod + DO + SELECT MAX(periodo) INTO vPreviousPeriod + FROM bi.analisis_ventas_reino_evolution + WHERE periodo < vMaxPeriod; + + SELECT MIN(period) INTO vCurrentPeriod + FROM vn2008.time + WHERE period > vPreviousPeriod; + + SET vYear = FLOOR(vCurrentPeriod / 100); + SET vWeek = vCurrentPeriod - (vYear * 100); + + DELETE FROM bi.analisis_ventas_reino_evolution + WHERE Periodo = vCurrentPeriod; + + REPLACE bi.analisis_ventas_reino_evolution(reino, ventas, semana,año, periodo) + SELECT reino, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod + FROM ( + SELECT Reino, sum(Importe) AS ventas + FROM bi.analisis_ventas + WHERE vYear = Año + AND vWeek = Semana + GROUP BY Reino + UNION ALL + SELECT Reino, - sum(Importe) AS ventas + FROM bi.analisis_ventas + WHERE vYear - 1 = Año + AND vWeek = Semana + GROUP BY Reino + UNION ALL + SELECT reino, ventas + FROM bi.analisis_ventas_reino_evolution + WHERE Periodo = vPreviousPeriod + ) sub + GROUP BY reino; + END WHILE; + + -- Familia + + SET vCurrentPeriod = vMinPeriod; + + WHILE vCurrentPeriod < vMaxPeriod + DO + SELECT MAX(periodo) INTO vPreviousPeriod + FROM bi.analisis_ventas_familia_evolution + WHERE periodo < vMaxPeriod; + + SELECT MIN(period) INTO vCurrentPeriod + FROM vn2008.time + WHERE period > vPreviousPeriod; + + SET vYear = FLOOR(vCurrentPeriod / 100); + SET vWeek = vCurrentPeriod - (vYear * 100); + + DELETE FROM bi.analisis_ventas_familia_evolution + WHERE Periodo = vCurrentPeriod; + + REPLACE bi.analisis_ventas_familia_evolution(familia, ventas, semana,año, periodo) + SELECT Familia, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod + FROM ( + SELECT Familia, sum(Importe) AS ventas + FROM bi.analisis_ventas + WHERE vYear = Año + AND vWeek = Semana + GROUP BY familia + UNION ALL + SELECT Familia, - sum(Importe) AS ventas + FROM bi.analisis_ventas + WHERE vYear - 1 = Año + AND vWeek = Semana + GROUP BY familia + UNION ALL + SELECT familia, ventas + FROM bi.analisis_ventas_familia_evolution + WHERE Periodo = vPreviousPeriod + ) sub + GROUP BY Familia; + END WHILE; + + -- Comprador + -- FIXME: Bucle infinito porque la tabla está vacía +/* + SET vCurrentPeriod = vMinPeriod; + + WHILE vCurrentPeriod < vMaxPeriod + DO + SELECT IFNULL(MAX(periodo),vMinPeriod) INTO vPreviousPeriod + FROM bi.analisis_ventas_comprador_evolution + WHERE periodo < vMaxPeriod; + + SELECT MIN(period) INTO vCurrentPeriod + FROM vn2008.time + WHERE period > vPreviousPeriod; + + SET vYear = FLOOR(vCurrentPeriod / 100); + SET vWeek = vCurrentPeriod - (vYear * 100); + + DELETE FROM bi.analisis_ventas_comprador_evolution + WHERE Periodo = vCurrentPeriod; + + REPLACE bi.analisis_ventas_comprador_evolution(comprador, ventas, semana,año, periodo) + SELECT Comprador, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod + FROM ( + SELECT Comprador, sum(Importe) AS ventas + FROM bi.analisis_ventas + WHERE vYear = Año + AND vWeek = Semana + GROUP BY Comprador + UNION ALL + SELECT Comprador, - sum(Importe) AS ventas + FROM bi.analisis_ventas + WHERE vYear - 1 = Año + AND vWeek = Semana + GROUP BY Comprador + UNION ALL + SELECT comprador, IFNULL(ventas,0) + FROM bi.analisis_ventas_comprador_evolution + WHERE Periodo = vPreviousPeriod + ) sub + GROUP BY Comprador; + END WHILE; +*/ + -- Provincia + + SET vCurrentPeriod = vMinPeriod; + + WHILE vCurrentPeriod < vMaxPeriod + DO + SELECT MAX(periodo) INTO vPreviousPeriod + FROM bi.analisis_ventas_provincia_evolution + WHERE periodo < vMaxPeriod; + + SELECT MIN(period) INTO vCurrentPeriod + FROM vn2008.time + WHERE period > vPreviousPeriod; + + SET vYear = FLOOR(vCurrentPeriod / 100); + SET vWeek = vCurrentPeriod - (vYear * 100); + + DELETE FROM bi.analisis_ventas_provincia_evolution + WHERE Periodo = vCurrentPeriod; + + REPLACE bi.analisis_ventas_provincia_evolution(provincia, ventas, semana,año, periodo) + SELECT Provincia, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod + FROM ( + SELECT Provincia, sum(Importe) AS ventas + FROM bi.analisis_ventas + WHERE vYear = Año + AND vWeek = Semana + GROUP BY Provincia + UNION ALL + SELECT Provincia, - sum(Importe) AS ventas + FROM bi.analisis_ventas + WHERE vYear - 1 = Año + AND vWeek = Semana + GROUP BY Provincia + UNION ALL + SELECT provincia, ventas + FROM bi.analisis_ventas_provincia_evolution + WHERE Periodo = vPreviousPeriod + ) sub + GROUP BY Provincia; + END WHILE; + + -- Vista + + SET vCurrentPeriod = vMinPeriod; + + WHILE vCurrentPeriod < vMaxPeriod + DO + SELECT MAX(periodo) INTO vPreviousPeriod + FROM bi.analisis_ventas_vista_evolution + WHERE periodo < vMaxPeriod; + + SELECT MIN(period) INTO vCurrentPeriod + FROM vn2008.time + WHERE period > vPreviousPeriod; + + SET vYear = FLOOR(vCurrentPeriod / 100); + SET vWeek = vCurrentPeriod - (vYear * 100); + + DELETE FROM bi.analisis_ventas_vista_evolution + WHERE Periodo = vCurrentPeriod; + + REPLACE bi.analisis_ventas_vista_evolution(vista, ventas, semana,año, periodo) + SELECT vista, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod + FROM ( + SELECT Vista, sum(Importe) AS ventas + FROM bi.analisis_ventas + WHERE vYear = Año + AND vWeek = Semana + GROUP BY Vista + UNION ALL + SELECT Vista, - sum(Importe) AS ventas + FROM bi.analisis_ventas + WHERE vYear - 1 = Año + AND vWeek = Semana + GROUP BY Vista + UNION ALL + SELECT vista, ventas + FROM bi.analisis_ventas_vista_evolution + WHERE Periodo = vPreviousPeriod + ) sub + GROUP BY Vista; + END WHILE; + + -- Vendedor + + SET vCurrentPeriod = vMinPeriod; + + WHILE vCurrentPeriod < vMaxPeriod + DO + SELECT MAX(periodo) INTO vPreviousPeriod + FROM bi.analisis_ventas_vendedor_evolution + WHERE periodo < vMaxPeriod; + + SELECT MIN(period) INTO vCurrentPeriod + FROM vn2008.time + WHERE period > vPreviousPeriod; + + SET vYear = FLOOR(vCurrentPeriod / 100); + SET vWeek = vCurrentPeriod - (vYear * 100); + + DELETE FROM bi.analisis_ventas_vendedor_evolution + WHERE Periodo = vCurrentPeriod; + + REPLACE bi.analisis_ventas_vendedor_evolution(vendedor, ventas, semana,año, periodo) + SELECT Comercial AS vendedor, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod + FROM ( + SELECT Comercial, sum(Importe) AS ventas + from bi.analisis_ventas + WHERE vYear = Año + AND vWeek = Semana + GROUP BY Comercial + UNION ALL + SELECT Comercial, - sum(Importe) AS ventas + from bi.analisis_ventas + WHERE vYear - 1 = Año + AND vWeek = Semana + GROUP BY Comercial + UNION ALL + SELECT vendedor, ventas + FROM bi.analisis_ventas_vendedor_evolution + WHERE Periodo = vPreviousPeriod + ) sub + GROUP BY vendedor; + END WHILE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `analisis_ventas_simple` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `analisis_ventas_simple`() +BEGIN + +TRUNCATE bi.analisis_grafico_simple; + +INSERT INTO bi.analisis_grafico_simple SELECT * FROM bi.analisis_grafico_ventas; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `analisis_ventas_update` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `analisis_ventas_update`() +BEGIN + DECLARE vLastMonth DATE; + + SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, CURDATE())); + + DELETE FROM analisis_ventas + WHERE Año > YEAR(vLastMonth) + OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); + + INSERT INTO analisis_ventas ( + Familia, + Reino, + Comercial, + Comprador, + Provincia, + almacen, + Año, + Mes, + Semana, + Vista, + Importe + ) + SELECT + tp.Tipo AS Familia, + r.reino AS Reino, + tr.CodigoTrabajador AS Comercial, + tr2.CodigoTrabajador AS Comprador, + p.name AS Provincia, + w.name AS almacen, + tm.year AS Año, + tm.month AS Mes, + tm.week AS Semana, + v.vista AS Vista, + bt.importe AS Importe + FROM bs.ventas bt + LEFT JOIN vn2008.Tipos tp ON tp.tipo_id = bt.tipo_id + LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id + LEFT JOIN vn2008.Clientes c on c.Id_Cliente = bt.Id_Cliente + LEFT JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = c.Id_Trabajador + LEFT JOIN vn2008.Trabajadores tr2 ON tr2.Id_Trabajador = tp.Id_Trabajador + JOIN vn2008.time tm ON tm.date = bt.fecha + JOIN vn2008.Movimientos m ON m.Id_Movimiento = bt.Id_Movimiento + LEFT JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia + LEFT JOIN vn2008.Vistas v ON v.vista_id = a.Vista + LEFT JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna + LEFT JOIN vn2008.province p ON p.province_id = cs.province_id + LEFT JOIN vn2008.warehouse w ON w.id = t.warehouse_id + WHERE bt.fecha >= vLastMonth AND r.mercancia; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `call_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `call_add`() +BEGIN + DECLARE datSTART DATETIME DEFAULT '2012-03-01'/*CURDATE()*/ ; + + -- Seleccionamos la ultima fecha introducida + SELECT MAX(Fecha) INTO datSTART FROM `call`; + + -- Borramos todas las entradas del dia datSTART por si hubiese registros nuevos + DELETE FROM `call` WHERE Fecha = datSTART; + + INSERT INTO bi.`call`(CodTrabajadorCartera,CodTrabajadorTelefono,dur_in,dur_out,Fecha,`year`,`month`,`week`,`hour`,phone) + SELECT vn2008.Averiguar_ComercialCliente(pb.Id_Cliente,Fecha) CodTrabajadorCartera,ll.CodigoTrabajador, dur_in, + dur_out, ll.Fecha,YEAR(ll.Fecha) `year`, MONTH(ll.Fecha) `month`,WEEK(ll.Fecha,7) `week`, Hora,phone + FROM ( + SELECT Id_Trabajador,CodigoTrabajador, IFNULL(billsec,0) dur_in, 0 dur_out, 1 as Recibidas, NULL as Emitidas, calldate as Fecha, + hour(calldate) as Hora,src as phone + FROM vn2008.Trabajadores T + JOIN vn2008.cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%') + WHERE calldate >= datSTART AND LENGTH(C.src) >=9 AND disposition = 'ANSWERED' AND duration + UNION ALL + SELECT Id_Trabajador,CodigoTrabajador,0 dur_in, IFNULL(billsec,0) dur_out, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate),dst + FROM vn2008.Trabajadores T + JOIN vn2008.cdr C ON C.src = T.extension + WHERE calldate >= datSTART AND LENGTH(C.dst) >=9 AND disposition = 'ANSWERED' AND duration + ) ll + JOIN vn2008.Permisos USING(Id_Trabajador) + LEFT JOIN vn2008.v_phonebook pb ON pb.Telefono = ll.phone + WHERE Id_Grupo = 6; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `claim_ratio_routine` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `claim_ratio_routine`() +BEGIN + DECLARE vMonthToRefund INT DEFAULT 4; + + /* + * PAK 2015-11-20 + * Se trata de añadir a la tabla Greuges todos los + * cargos que luego vamos a utilizar para calcular el recobro + */ + + -- descuentos comerciales COD 11 + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, Importe, Id_Ticket) + SELECT Fecha, Id_Cliente, Concat('COD11 : ',Concepte), - round(Cantidad * + Preu * (100 - Descuento) / 100 ,2) AS Importe, t.Id_Ticket + FROM vn2008.Tickets t + JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket + WHERE Id_Article = 11 + AND Concepte NOT LIKE '$%' + AND Fecha > '2014-01-01' + HAVING nz(Importe) <> 0; + + DELETE mc.* + FROM vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + WHERE m.Id_Article = 11 + AND m.Concepte NOT LIKE '$%' + AND t.Fecha > '2017-01-01'; + + INSERT INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) + SELECT m.Id_Movimiento, 34, round(m.Preu * (100 - m.Descuento)/100,4) + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + WHERE m.Id_Article = 11 + AND m.Concepte NOT LIKE '$%' + AND t.Fecha > '2017-01-01'; + + UPDATE vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + SET Concepte = CONCAT('$ ',Concepte) + WHERE Id_Article = 11 + AND Concepte NOT LIKE '$%' + AND Fecha > '2014-01-01'; + + -- Reclamaciones demasiado sensibles + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, + Importe, Greuges_type_id,Id_Ticket) + SELECT cm.Fecha + , cm.Id_Cliente + , concat('Claim ',cm.id,' : ', m.Concepte) + ,round( -1 * ((sensib -1)/4) * Cantidad * + Preu * (100 - Descuento) / 100, 2) AS Reclamaciones + , 4 + , m.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca USING(Id_Movimiento) + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3; + + -- Reclamaciones que pasan a Maná + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, + Importe , Greuges_type_id,Id_Ticket) + SELECT cm.Fecha + , cm.Id_Cliente + , concat('Claim_mana ',cm.id,' : ', m.Concepte) + ,round( ((sensib -1)/4) * Cantidad * Preu * (100 - Descuento) / 100, 2) + AS Reclamaciones + ,3 + ,m.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca USING(Id_Movimiento) + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3 + AND cm.mana; + + -- Marcamos para no repetir + UPDATE vn2008.cl_act ca + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + SET greuge = 1 + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3; + + -- Recobros + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (Id_Ticket)) + SELECT DISTINCT t.Id_Ticket + FROM vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Tickets_state ts ON ts.Id_Ticket = t.Id_Ticket + JOIN vncontrol.inter i ON i.inter_id = ts.inter_id + JOIN vn2008.state s ON s.id = i.state_id + WHERE mc.Id_Componente = 17 + AND mc.greuge = 0 + AND t.Fecha >= '2016-10-01' + AND t.Fecha < CURDATE() + AND s.alert_level >= 3; + + DELETE g.* + FROM vn2008.Greuges g + JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket + WHERE Greuges_type_id = 2; + + INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, + Greuges_type_id, Id_Ticket) + SELECT Id_Cliente + ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2) + AS dif + ,date(t.Fecha) + , 2 + ,tt.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket + JOIN vn2008.Movimientos_componentes mc + ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = 17 + GROUP BY t.Id_Ticket + HAVING ABS(dif) > 1; + + UPDATE vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento + JOIN tmp.ticket_list tt ON tt.Id_Ticket = m.Id_Ticket + SET greuge = 1 + WHERE Id_Componente = 17; + + /* + * Recalculamos la ratio de las reclamaciones, que luego + * se va a utilizar en el recobro + */ + + REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) + SELECT Id_Cliente, 0,0,0,0 + FROM vn2008.Clientes; + + REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) + SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, + round(Reclamaciones / (12*fm.Consumo),4) AS Ratio, 0 + FROM bi.facturacion_media_anual fm + LEFT JOIN( + SELECT cm.Id_Cliente, round(sum(-1 * ((sensib -1)/4) * + Cantidad * Preu * (100 - Descuento) / 100)) + AS Reclamaciones + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca + ON ca.Id_Movimiento = m.Id_Movimiento + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND cm.cl_est_id = 3 + AND cm.Fecha >= TIMESTAMPADD(YEAR, -1, CURDATE()) + GROUP BY cm.Id_Cliente + ) claims ON claims.Id_Cliente = fm.Id_Cliente; + + + -- Calculamos el porcentaje del recobro para añadirlo al precio de venta + UPDATE bi.claims_ratio cr + JOIN ( + SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge + FROM vn2008.Greuges + WHERE Fecha <= CURDATE() + GROUP BY Id_Cliente + ) g ON g.Id_Cliente = cr.Id_Cliente + SET recobro = GREATEST(0,round(nz(Greuge) / + (nz(Consumo) * vMonthToRefund / 12 ) ,3)); + + -- Protección neonatos + UPDATE bi.claims_ratio cr + JOIN vn.firstTicketShipped fts ON fts.clientFk = cr.Id_Cliente + SET recobro = 0, Ratio = 0 + WHERE fts.shipped > TIMESTAMPADD(MONTH,-1,CURDATE()); + + -- CLIENTE 7983, JULIAN SUAU + UPDATE bi.claims_ratio SET recobro = LEAST(0.05, recobro) WHERE Id_Cliente = 7983; + + -- CLIENTE 4358 + UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 4358; + + -- CLIENTE 5523, VERDECORA + UPDATE bi.claims_ratio SET recobro = GREATEST(0.12, recobro) WHERE Id_Cliente = 5523; + + -- CLIENTE 15979, SERVEIS VETERINARIS + UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 15979; + + -- CLIENTE 5189 i 8942, son de CSR i son el mateix client + UPDATE bi.claims_ratio cr + JOIN (SELECT sum(Consumo * recobro)/sum(Consumo) as recobro + FROM bi.claims_ratio + WHERE Id_Cliente IN ( 5189,8942) + ) sub + SET cr.recobro = sub.recobro + WHERE Id_Cliente IN ( 5189,8942); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clean` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clean`() +BEGIN + DECLARE vDateShort DATETIME; + DECLARE vDateLong DATETIME; + DECLARE vOneYearAgo DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET vDateLong = TIMESTAMPADD(MONTH, -18,CURDATE()); + SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,CURDATE()); + + -- DELETE FROM bi.comparativa_clientes WHERE Fecha < vDateLong; + + DELETE FROM bi.Greuge_Evolution + WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) + OR Fecha < vOneYearAgo; + + DELETE FROM bi.defaulters WHERE `date` < vDateLong; + DELETE FROM bi.defaulting WHERE `date` < vDateLong; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clean_launcher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clean_launcher`() +BEGIN + + call vn2008.clean(0); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `comparativa_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `comparativa_add`() +BEGIN + DECLARE lastCOMP INT; # Se trata de una variable para almacenar el ultimo valor del Periodo + + SELECT MAX(Periodo) INTO lastCOMP FROM vn2008.Comparativa; + -- Fijaremos las ventas con más de un mes de antiguedad en la tabla Comparativa + + IF lastCOMP < vn2008.vnperiod(CURDATE())- 3 AND vn2008.vnweek(CURDATE()) > 3 THEN + + REPLACE vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price) + SELECT tm.period as Periodo, m.Id_Article, t.warehouse_id, sum(m.Cantidad), sum(v.importe) + FROM bs.ventas v + JOIN vn2008.time tm ON tm.date = v.fecha + JOIN vn2008.Movimientos m ON m.Id_Movimiento = v.Id_Movimiento + JOIN vn2008.Tipos tp ON tp.tipo_id = v.tipo_id + JOIN vn2008.reinos r ON r.id = tp.reino_id + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + WHERE tm.period BETWEEN lastCOMP AND vn2008.vnperiod(CURDATE())- 3 + AND t.Id_Cliente NOT IN(400,200) + AND r.display <> 0 + AND t.warehouse_id NOT IN (0,13) + GROUP BY m.Id_Article, Periodo, t.warehouse_id; + + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `comparativa_add_manual` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `comparativa_add_manual`(IN dat_START DATE, IN dat_END DATE) +BEGIN + + DECLARE datINI DATETIME; + DECLARE datFIN DATETIME; + + -- Seleccionamos la fecha minima/maxima del periodo que vamos a consultar + SELECT MIN(`date`) INTO datINI FROM vn2008.`time` WHERE period = vn2008.vnperiod(dat_START); + SELECT TIMESTAMP(MAX(`date`),'23:59:59') INTO datFIN FROM vn2008.`time` WHERE period = vn2008.vnperiod(dat_END); + + DELETE FROM vn2008.Comparativa WHERE Periodo BETWEEN vn2008.vnperiod(dat_START) and vn2008.vnperiod(dat_END); + + REPLACE vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price) + SELECT tm.period AS Periodo + , M.Id_Article + , t.warehouse_id + , SUM(Cantidad) AS Total + , sum(v.importe) AS precio + FROM vn2008.Movimientos M + JOIN vn2008.Tickets t on t.Id_Ticket = M.Id_Ticket + JOIN bs.ventas v on v.Id_Movimiento = M.Id_Movimiento + JOIN vn2008.`time` tm on tm.`date` = v.fecha + WHERE v.fecha BETWEEN datINI and datFIN + AND t.warehouse_id NOT IN (0,13) + GROUP BY Id_Article, Periodo, t.warehouse_id; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `comparativa_add_manual__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `comparativa_add_manual__`(IN dat_START DATE, IN dat_END DATE) +BEGIN + + DECLARE datINI DATETIME; + DECLARE datFIN DATETIME; + + -- Seleccionamos la fecha minima/maxima del periodo que vamos a consultar + SELECT MIN(`date`) INTO datINI FROM vn2008.`time` WHERE period = vn2008.vnperiod(dat_START); + SELECT TIMESTAMP(MAX(`date`),'23:59:59') INTO datFIN FROM vn2008.`time` WHERE period = vn2008.vnperiod(dat_END); + + DELETE FROM vn2008.Comparativa WHERE Periodo BETWEEN vn2008.vnperiod(dat_START) and vn2008.vnperiod(dat_END); + + REPLACE vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price) + SELECT tm.period AS Periodo + , M.Id_Article + , t.warehouse_id + , SUM(Cantidad) AS Total + , sum(v.importe) AS precio + FROM vn2008.Movimientos M + JOIN vn2008.Tickets t on t.Id_Ticket = M.Id_Ticket + JOIN bs.ventas v on v.Id_Movimiento = M.Id_Movimiento + JOIN vn2008.time tm on tm.date = v.fecha + JOIN vn2008.Tipos tp on v.tipo_id = tp.tipo_id + LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id + WHERE v.fecha BETWEEN datINI and datFIN + AND r.display <> 0 AND t.warehouse_id NOT IN (0,13) + GROUP BY Id_Article, Periodo, t.warehouse_id; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `comparativa_add__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `comparativa_add__`() +BEGIN + DECLARE lastCOMP INT; # Se trata de una variable para almacenar el ultimo valor del Periodo + + SELECT MAX(Periodo) INTO lastCOMP FROM vn2008.Comparativa; + -- Fijaremos las ventas con más de un mes de antiguedad en la tabla Comparativa + + IF lastCOMP < vn2008.vnperiod(CURDATE())- 3 AND vn2008.vnweek(CURDATE()) > 3 THEN + + REPLACE vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price) + SELECT tm.period as Periodo, m.Id_Article, t.warehouse_id, sum(m.Cantidad), sum(v.importe) + FROM bs.ventas v + JOIN vn2008.time tm ON tm.date = v.fecha + JOIN vn2008.Movimientos m ON m.Id_Movimiento = v.Id_Movimiento + JOIN vn2008.Articles a ON a.Id_Article = m.Id_Article + JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id + JOIN vn2008.reinos r ON r.id = tp.reino_id + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + WHERE tm.period BETWEEN lastCOMP AND vn2008.vnperiod(CURDATE())- 3 + AND t.Id_Cliente NOT IN(400,200) + AND r.display <> 0 + AND t.warehouse_id NOT IN (0,13) + GROUP BY Id_Article, Periodo, warehouse_id; + + +/* + REPLACE vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price) + SELECT vn2008.vnperiod(T.Fecha) AS Periodo + , Id_Article + , warehouse_id + , SUM(Cantidad) AS Total + , SUM(Cantidad * Preu * (100 - Descuento) / 100) precio + FROM vn2008.Movimientos M + JOIN vn2008.Tickets T USING (Id_Ticket) + JOIN vn2008.Articles A USING (Id_Article) + LEFT JOIN vn2008.Tipos ti ON ti.tipo_id = A.tipo_id + LEFT JOIN vn2008.reinos r ON r.id = ti.reino_id + WHERE T.Fecha BETWEEN TIMESTAMPADD(DAY,-60,CURDATE()) AND TIMESTAMPADD(DAY,-30,CURDATE()) + AND T.Id_Cliente NOT IN(400,200) + AND display <> 0 AND warehouse_id NOT IN (0,13) + GROUP BY Id_Article, Periodo, warehouse_id; +*/ + + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `customer_risk_update` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `customer_risk_update`(v_customer INT, v_company INT, v_amount DECIMAL(10,2)) +BEGIN + IF v_amount IS NOT NULL + THEN + INSERT INTO bi.customer_risk + SET + customer_id = v_customer, + company_id = v_company, + amount = v_amount + ON DUPLICATE KEY UPDATE + amount = amount + VALUES(amount); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `defaultersFromDate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `defaultersFromDate`(IN vDate DATE) +BEGIN + + SELECT t1.*, c.Cliente, w.code AS workerCode, c.pay_met_id,c.Vencimiento + FROM ( + -- Filtramos aquellos clientes cuyo saldo se ha incrementado de ayer a hoy + select * from( + select today.client, today.amount todayAmount, yesterday.amount yesterdayAmount, round(yesterday.amount - today.amount,2) as difference, defaulterSince + from + (select client, amount, defaulterSince + from defaulters + where date = vDate and hasChanged) today + join + (select client, amount + from defaulters + where date = TIMESTAMPADD(DAY,-1,vDate)) yesterday using(client) + + having today.amount > 0 and difference <> 0 + ) newDefaulters + )t1 left join vn2008.Clientes c ON t1.client = c.Id_Cliente + left join vn.worker w ON w.id = c.Id_Trabajador; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `defaulting` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `defaulting`(IN `vDate` DATE) +BEGIN +/*JGF para usar el campo vencimiento de facturas*/ + DECLARE vDone BOOLEAN; + DECLARE vClient INT; + DECLARE vAmount INT; + DECLARE vDued DATE; + DECLARE vAmountInvoice DECIMAL(10,2); + DECLARE vGraceDays INT; + DECLARE defaulters CURSOR FOR + SELECT client, amount, graceDays FROM bi.defaulters d + JOIN vn2008.Clientes c ON c.Id_Cliente = d.client + JOIN vn2008.pay_met pm ON pm.id = c.pay_met_id + WHERE hasChanged AND date = vDate; + + DECLARE invoices CURSOR FOR + SELECT Vencimiento, importe FROM vn2008.Facturas f + WHERE f.Fecha >= '2016-01-01' AND f.Id_Cliente = vClient ORDER BY f.Fecha DESC; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DELETE FROM bi.defaulters WHERE date = vDate; + + INSERT INTO bi.defaulters(client, date, amount) + SELECT customer_id, vDate, FLOOR(SUM(amount)) AS amount + FROM bi.customerRiskOverdue + GROUP BY customer_id; + + -- marcamos si ha cambiado y heredamos la fecha defaulterSince + UPDATE bi.defaulters d + LEFT JOIN ( + SELECT * FROM( + SELECT client, amount , defaulterSince, frozened FROM bi.defaulters + WHERE date <= TIMESTAMPADD(DAY,-1, vDate) + ORDER BY date DESC) t GROUP BY client + ) yesterday using(client) + SET d.hasChanged = IF(d.amount <> IFNULL(yesterday.amount,0), 1, 0), + d.defaulterSince = yesterday.defaulterSince, + d.frozened = yesterday.frozened + WHERE d.date = vDate ; + + OPEN defaulters; + defaulters: LOOP + SET vDone = FALSE; + SET vAmount = 0; + FETCH defaulters INTO vClient,vAmount, vGraceDays; + IF vDone THEN + LEAVE defaulters; + END IF; + OPEN invoices; + invoices:LOOP + + FETCH invoices INTO vDued, vAmountInvoice; + IF vDone THEN + LEAVE invoices; + END IF; + + IF TIMESTAMPADD(DAY, vGraceDays, vDued) <= vDate THEN + SET vAmount = vAmount - vAmountInvoice; + IF vAmount <= 0 THEN + + UPDATE defaulters SET defaulterSince = vDued + WHERE client = vClient and date = vDate; + + SET vAmount = 0; + LEAVE invoices; + END IF; + END IF; + END LOOP; + CLOSE invoices; + END LOOP; + CLOSE defaulters; + + UPDATE defaulters d + JOIN vn.config ON TRUE + SET d.frozened = NULL + WHERE d.`date` = vDate + AND d.amount <= config.defaultersMaxAmount; + + CALL vn.clientFreeze(); + + -- actualizamos defaulting + DELETE FROM bi.defaulting WHERE date = vDate; + + INSERT INTO bi.defaulting(date, amount) + SELECT vDate, SUM(amount) + FROM bi.defaulters + WHERE date = vDate and amount > 0; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `defaulting_launcher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `defaulting_launcher`() +BEGIN + + CALL bi.defaulting(curdate()); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `equaliza` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `equaliza`(IN wh_id INT) +BEGIN + +DECLARE datEQ DATETIME; +/* JGF 2017-03-20 cuelga el sistema + +SELECT `date` INTO datEQ FROM bi.variables WHERE variable = IF(wh_id = 17,'eq_mcf','equalizator'); + + +IF TIMEDIFF(now(), datEQ) > '00:05:00' THEN + + UPDATE bi.Equalizator e + JOIN + ( + SELECT + Vista, + sum(1) as pedido, + sum(PedidoImpreso) as impreso, + sum(t.Factura IS NOT NULL + OR t.Etiquetasemitidas + OR nz(ticket_id) <> 0) as encajado + FROM + vn2008.Movimientos + JOIN + vn2008.Tickets t USING (Id_Ticket) + JOIN + vn2008.Agencias a ON t.Id_Agencia = a.Id_Agencia + JOIN + vn2008.Clientes C USING (Id_Cliente) + LEFT JOIN + (SELECT distinct + ticket_id + FROM + vn2008.expeditions e JOIN vn2008.Tickets t ON t.Id_Ticket = e.ticket_id WHERE Fecha >= curDate()) exp ON ticket_id = Id_Ticket + WHERE + invoice And Fecha >= curDate() + AND t.warehouse_id = wh_id + AND fecha < (TIMESTAMPADD(DAY, 1, CURDATE())) + GROUP BY Vista) sub using(Vista) + SET e.Pedido = sub.pedido, e.Impreso = sub.impreso, e.Encajado = sub.encajado; + + UPDATE bi.variables SET `date`= now() WHERE variable = IF(wh_id = 17,'eq_mcf','equalizator'); + + +END IF; +*/ +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `facturacion_media_anual_update` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `facturacion_media_anual_update`() +BEGIN + TRUNCATE TABLE bi.facturacion_media_anual; + + REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) + SELECT clientFk, avg(Facturacion) + FROM ( + SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion + FROM vn.invoiceOut + WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND TIMESTAMPADD(DAY, - DAY(CURDATE()),CURDATE()) + GROUP BY clientFk, year, month + ) vol + GROUP BY clientFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `greuge_dif_porte_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `greuge_dif_porte_add`() +BEGIN + DECLARE datSTART DATETIME DEFAULT TIMESTAMPADD(DAY,-10,CURDATE()); -- '2019-07-01' + DECLARE datEND DATETIME DEFAULT TIMESTAMPADD(DAY,-1,CURDATE()); + + DROP TEMPORARY TABLE IF EXISTS tmp.dp; + + -- Agencias que no cobran por volumen + CREATE TEMPORARY TABLE tmp.dp + (PRIMARY KEY (Id_Ticket)) + ENGINE = MEMORY + SELECT t.Id_Ticket, + SUM(z.price * ebv.ratio) AS teorico, + 00000.00 as practico, + 00000.00 as greuge + FROM + vn2008.Tickets t + JOIN vn2008.Clientes cli ON cli.Id_cliente = t.Id_Cliente + LEFT JOIN vn2008.expeditions e ON e.ticket_id = t.Id_Ticket + JOIN vn2008.Consignatarios c ON c.Id_Consigna = t.Id_Consigna + JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.EsBulto + JOIN vn.zone z ON t.zoneFk = z.id + WHERE + t.Fecha between datSTART AND datEND + AND cli.`real` + AND t.empresa_id IN (442 , 567) + AND z.isVolumetric = FALSE + GROUP BY t.Id_Ticket; + + -- Agencias que cobran por volumen + INSERT INTO tmp.dp + SELECT sf.ticketFk, + SUM(freight) AS teorico, + 00000.00 as practico, + 00000.00 as greuge + FROM vn.saleFreight sf + JOIN vn.`client` c ON c.id = sf.clientFk + JOIN vn.zone z ON z.id = sf.zoneFk + WHERE c.isRelevant + AND sf.companyFk IN (442 , 567) + AND sf.shipped BETWEEN datSTART AND datEND + AND z.isVolumetric != FALSE + GROUP BY sf.ticketFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.dp_aux; + + CREATE TEMPORARY TABLE tmp.dp_aux + (PRIMARY KEY (Id_Ticket)) + ENGINE = MEMORY + SELECT dp.Id_Ticket, sum(Cantidad * Valor) as valor + FROM tmp.dp + JOIN vn2008.Movimientos m using(Id_Ticket) + JOIN vn2008.Movimientos_componentes mc using(Id_Movimiento) + WHERE mc.Id_Componente = 15 + GROUP BY m.Id_Ticket; + + UPDATE tmp.dp + JOIN tmp.dp_aux using(Id_Ticket) + SET practico = valor; + + DROP TEMPORARY TABLE tmp.dp_aux; + + CREATE TEMPORARY TABLE tmp.dp_aux + (PRIMARY KEY (Id_Ticket)) + ENGINE = MEMORY + SELECT dp.Id_Ticket, sum(Importe) Importe + FROM tmp.dp + JOIN vn2008.Greuges g using(Id_Ticket) + WHERE Greuges_type_id = 1 + GROUP BY Id_Ticket; + + UPDATE tmp.dp + JOIN tmp.dp_aux using(Id_Ticket) + SET greuge = Importe; + + + INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, Greuges_type_id, Id_Ticket) + SELECT t.Id_Cliente + , concat('dif_porte ', dp.Id_Ticket) + , round(IFNULL(teorico,0) - IFNULL(practico,0) - IFNULL(greuge,0),2) as Importe + , date(t.Fecha) + , 1 + ,t.Id_Ticket + FROM tmp.dp + JOIN vn2008.Tickets t on dp.Id_Ticket = t.Id_Ticket + WHERE ABS(IFNULL(teorico,0) - IFNULL(practico,0) - IFNULL(greuge,0)) > 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 DROP PROCEDURE IF EXISTS `Greuge_Evolution_Add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `Greuge_Evolution_Add`() +BEGIN +/* + Inserta en la tabla Greuge_Evolution el saldo acumulado de cada cliente, + así como las ventas acumuladas en los ultimos 365 dias, para poder controlar + su evolucion. +*/ + DECLARE datFEC DATE; + DECLARE datFEC_TOMORROW DATE; + DECLARE datFEC_LASTYEAR DATE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + + GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; + SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')); + INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('jgallego@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); + INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('pako@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); + + END; + + SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; + + DELETE FROM bi.Greuge_Evolution WHERE Fecha >= TIMESTAMPADD(MONTH,-1,CURDATE()); + + SELECT TIMESTAMPADD(DAY,1,MAX(Fecha)), + TIMESTAMPADD(DAY,2,MAX(Fecha)) + INTO datFEC, + datFEC_TOMORROW + FROM bi.Greuge_Evolution; + + SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); + + DELETE FROM bi.Greuge_Evolution WHERE Fecha >= datFEC; + + DROP TEMPORARY TABLE IF EXISTS maxInvoice; + + CREATE TEMPORARY TABLE maxInvoice + (PRIMARY KEY (Id_Cliente)) + ENGINE = MEMORY + SELECT DISTINCT Id_Cliente, max(Fecha) as maxFecha + FROM vn2008.Facturas + GROUP BY Id_Cliente + HAVING maxFecha < timestampadd(month,-2,datFEC); + + WHILE datFEC < CURDATE() DO + + REPLACE bi.Greuge_Evolution(Id_Cliente, Fecha, Greuge, Ventas, Fosil) + + SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0 + FROM ( + SELECT Id_Cliente, sum(Importe) as Greuge + FROM vn2008.Greuges + where Fecha <= datFEC + group by Id_Cliente + ) sub + RIGHT JOIN + + ( + + SELECT Id_Cliente, sum(Ventas) as Ventas + FROM + ( + + SELECT Id_Cliente, IF (fecha != datFEC, -1,1) * (importe + recargo) as Ventas + FROM bs.ventas + WHERE fecha = datFEC or fecha = datFEC_LASTYEAR + + UNION ALL + + SELECT Id_Cliente, Ventas + FROM bi.Greuge_Evolution + WHERE Fecha = TIMESTAMPADD(DAY, -1, datFEC) + + ) sub + group by Id_Cliente + + ) v using(Id_Cliente) + ; + + -- Ahora calcularemos el greuge muerto + + UPDATE bi.Greuge_Evolution ge + JOIN maxInvoice m using(Id_Cliente) + SET FOSIL = GREUGE + WHERE m.maxFecha < TIMESTAMPADD(MONTH,-2,ge.Fecha); + + -- Recobro + + UPDATE bi.Greuge_Evolution ge + JOIN ( + SELECT cs.Id_Cliente, sum(Valor * Cantidad) as Importe + FROM vn2008.Tickets t + JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna + JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket + JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento + WHERE t.Fecha >= datFEC + AND t.Fecha < datFEC_TOMORROW + AND mc.Id_Componente = 17 -- Recobro + GROUP BY cs.Id_Cliente + ) sub using(Id_Cliente) + SET Recobro = Importe + WHERE ge.Fecha = datFEC; + + SET datFEC = datFEC_TOMORROW; + SET datFEC_TOMORROW = TIMESTAMPADD(DAY,1,datFEC_TOMORROW); + SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); + + + END WHILE; + + DROP TEMPORARY TABLE IF EXISTS maxInvoice; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `margenes` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = '' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `margenes`() +BEGIN + +TRUNCATE TABLE bi.margenes; + +INSERT INTO bi.margenes +SELECT Id_Article, Cantidad as Unidades, Cantidad * round(nz(Costefijo) + nz(Embalajefijo) + nz(Comisionfija) + nz(Portefijo),3) as Coste , w.name as almacen, month(landing) as Mes, year(landing) as Year, 0 as Venta +FROM vn2008.Compres C +JOIN vn2008.Entradas E using(Id_Entrada) +JOIN vn2008.travel tr on tr.id = travel_id +JOIN vn2008.warehouse w on w.id = tr.warehouse_id +LEFT JOIN vn2008.Articles A using(Id_Article) +JOIN vn2008.Tipos TP using(tipo_id) +WHERE landing between '2013-01-01' and ' 2013-12-31' +AND E.Id_Proveedor <> 4 +AND not redada +AND not inventario +union all +SELECT Id_Article, Cantidad as Unidades, 0 as Coste , w.name, month(Fecha) as Mes, year(Fecha) as Year, Cantidad * round(Preu * (100 - M.Descuento) / 100,2) as Venta +FROM vn2008.Movimientos M +JOIN vn2008.Articles A using(Id_Article) +JOIN vn2008.Tipos TP using(tipo_id) +JOIN vn2008.Tickets T using(Id_Ticket) +JOIN vn2008.Clientes C using(Id_Cliente) +JOIN vn2008.warehouse w on w.id = warehouse_id +WHERE Fecha between '2013-01-01' and ' 2013-12-31' +AND (Id_Cliente = 31 or invoice) +AND Id_Cliente NOT IN (2066,2067,2068); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nightly_tasks` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nightly_tasks`() +BEGIN + +call bi.analisis_ventas_evolution_add; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nigthlyAnalisisVentas` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nigthlyAnalisisVentas`() +BEGIN + CALL analisis_ventas_update; + CALL analisis_ventas_simple; + CALL analisis_ventas_evolution_add; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `partitioning` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `partitioning`(IN intyear INT) +BEGIN + + DECLARE v_sql TEXT; + DECLARE strSquemaName VARCHAR(10); + DECLARE strTableName VARCHAR(20); + DECLARE strFieldName VARCHAR(20); + DECLARE strDateField VARCHAR(20); + DECLARE strTableDependingOn VARCHAR(20); + DECLARE strFieldDependingOn VARCHAR(20); + DECLARE done BIT DEFAULT 0; + DECLARE strCacheSchema VARCHAR(5); + DECLARE dat_start,dat_end DATE; + DECLARE cur1 CURSOR FOR + SELECT `schema_name`,`table_name` FROM `cache`.partitioning_information ORDER BY execution_order; + DECLARE cur2 CURSOR FOR + SELECT `schema_name`,`table_name`,`date_field` FROM `cache`.partitioning_information WHERE date_field > '' ORDER BY execution_order; + DECLARE cur3 CURSOR FOR + SELECT `schema_name`,`table_name`,`table_depending` FROM `cache`.partitioning_information WHERE table_depending > '' ORDER BY execution_order; + DECLARE cur4 CURSOR FOR + SELECT `schema_name`,`table_name`,`table_depending` FROM `cache`.partitioning_information WHERE table_depending > '' ORDER BY execution_order DESC; + DECLARE cur5 CURSOR FOR + SELECT `schema_name`,`table_name`,`date_field` FROM `cache`.partitioning_information WHERE date_field > '' ORDER BY execution_order DESC; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; + + SET FOREIGN_KEY_CHECKS=0; + IF LENGTH(intyear) <> 4 THEN + CALL el_año_debe_contener_4_caracteres_yyyy(); + END IF; + SET dat_start = STR_TO_DATE(CONCAT('01,01,',intyear),'%d,%m,%Y'); + SET dat_end = STR_TO_DATE(CONCAT('31,12,',intyear),'%d,%m,%Y'); + SET strCacheSchema = CONCAT('vn_',right(intyear,2)); + SET v_sql = sql_printf ('CREATE SCHEMA IF NOT EXISTS %t',strCacheSchema); + CALL util.exec (v_sql); + + -- Insertamos en las tablas del cur1 + OPEN cur1; + FETCH cur1 INTO strSquemaName,strTableName; + WHILE NOT done DO + SET v_sql = sql_printf ('CREATE TABLE IF NOT EXISTS %t.%t LIKE %t.%t', + strCacheSchema, + strTableName, + strSquemaName, + strTableName); + + CALL util.exec (v_sql); + + FETCH cur1 INTO strSquemaName,strTableName; + + END WHILE; + CLOSE cur1; + + -- Insertamos en las tablas del cur2 + OPEN cur2; + FETCH cur2 INTO strSquemaName,strTableName,strDateField; + WHILE NOT done DO + SET v_sql = sql_printf ('REPLACE INTO %t.%t SELECT * FROM %t.%t WHERE %t BETWEEN %v AND %v', + strCacheSchema, + strTableName, + strSquemaName, + strTableName, + strDateField, + dat_start, + dat_end); + + SELECT v_sql; + CALL util.exec (v_sql); + + FETCH cur2 INTO strSquemaName,strTableName,strDateField; + + END WHILE; + CLOSE cur2; + + -- Insertamos en las tablas del cur3 + OPEN cur3; + SET done = 0; + FETCH cur3 INTO strSquemaName,strTableName,strTableDependingOn; + WHILE NOT done DO + + + -- Torna la columna per la qual vincular amb el seu pare + SELECT kcu.column_name INTO strFieldName + FROM information_schema.key_column_usage kcu + WHERE table_schema = CONVERT(strSquemaName USING utf8) COLLATE utf8_general_ci + AND REFERENCED_TABLE_NAME = CONVERT(strTableDependingOn USING utf8) COLLATE utf8_general_ci + AND table_name = CONVERT(strTableName USING utf8) COLLATE utf8_general_ci; + + -- Torna la columna per la qual vincular amb el seu fill + SELECT kcu.column_name INTO strFieldDependingOn + FROM information_schema.key_column_usage kcu + WHERE table_schema = CONVERT(strSquemaName USING utf8) COLLATE utf8_general_ci -- FIX mirar l'esquema del pare + AND constraint_name = 'PRIMARY' + AND table_name = CONVERT(strTableDependingOn USING utf8) COLLATE utf8_general_ci; + + SET v_sql = sql_printf ('REPLACE INTO %t.%t SELECT a.* FROM %t.%t a JOIN %t.%t b ON a.%t = b.%t', + strCacheSchema, + strTableName, + strSquemaName, + strTableName, + strCacheSchema, + strTableDependingOn, + strFieldName, + strFieldDependingOn); + select v_sql; + CALL util.exec (v_sql); + + FETCH cur3 INTO strSquemaName,strTableName,strTableDependingOn; + END WHILE; + + CLOSE cur3; + + -- Borramos en las tablas del cur4 que es igual que el dos pero en sentido descendente + -- para evitar errores con las foreign key + OPEN cur4; + SET done = 0; + FETCH cur4 INTO strSquemaName,strTableName,strTableDependingOn; + WHILE NOT done DO + + + -- Torna la columna per la qual vincular amb el seu pare + SELECT kcu.column_name INTO strFieldName + FROM information_schema.key_column_usage kcu + WHERE table_schema = CONVERT(strSquemaName USING utf8) COLLATE utf8_general_ci + AND REFERENCED_TABLE_NAME = CONVERT(strTableDependingOn USING utf8) COLLATE utf8_general_ci + AND table_name = CONVERT(strTableName USING utf8) COLLATE utf8_general_ci; + + -- Torna la columna per la qual vincular amb el seu fill + SELECT kcu.column_name INTO strFieldDependingOn + FROM information_schema.key_column_usage kcu + WHERE table_schema = CONVERT(strSquemaName USING utf8) COLLATE utf8_general_ci + AND constraint_name = 'PRIMARY' + AND table_name = CONVERT(strTableDependingOn USING utf8) COLLATE utf8_general_ci; + + SELECT v_sql; + SET v_sql = sql_printf ('DELETE a.* FROM %t.%t a JOIN %t.%t b ON a.%t = b.%t', + strSquemaName, + strTableName, + strCacheSchema, + strTableDependingOn, + strFieldName, + strFieldDependingOn); + CALL util.exec (v_sql); + + FETCH cur4 INTO strSquemaName,strTableName,strTableDependingOn; + END WHILE; + + CLOSE cur4; + + -- Borramos en las tablas del cur5 + OPEN cur5; + SET done = 0; + FETCH cur5 INTO strSquemaName,strTableName,strDateField; + WHILE NOT done DO + + SET v_sql = sql_printf ('DELETE FROM %t WHERE %t BETWEEN %v AND %v', + strTableName, + strDateField, + dat_start, + dat_end); + CALL util.exec (v_sql); + + FETCH cur5 INTO strSquemaName,strTableName,strDateField; + + END WHILE; + CLOSE cur5; + SET FOREIGN_KEY_CHECKS=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 DROP PROCEDURE IF EXISTS `primer_pedido_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `primer_pedido_add`() +BEGIN + INSERT IGNORE INTO bi.primer_pedido(Id_Ticket, Id_Cliente, month, year, total) + SELECT * + FROM + (SELECT + `m`.`Id_Ticket` , + `v`.`Id_Cliente` , + `t`.`month`, + `t`.`year`, + v.importe + v.recargo as total + FROM + bs.ventas v + JOIN + vn2008.Movimientos m on m.Id_Movimiento = v.Id_Movimiento + JOIN + vn2008.time t on t.date = v.fecha + WHERE + fecha > CURDATE() + INTERVAL -(1) YEAR + ORDER BY fecha) `s` + GROUP BY `s`.`Id_Cliente`; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `regularidad` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = '' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `regularidad`() +BEGIN + +select Id_Cliente, Meses, IF(Antiguedad = 13,12,Antiguedad) , Meses / IF(Antiguedad = 13,12,Antiguedad) as Regularidad from ( +SELECT Id_Cliente, count(*) as Meses, FLOOR(DATEDIFF('2012-07-31', IF(Created < '2011-08-01','2011-08-01', Created)) / 30) +1 as Antiguedad from +( + +SELECT DISTINCT Id_Cliente, Periodo(Fecha) as periodo from Facturas +where Fecha between '2011-08-01' AND '2012-07-31' + +) sub + +join Clientes using(Id_Cliente) +where Created <= '2012-07-31' + +group by Id_Cliente +having Antiguedad > 0 + +) sub44 +order by Antiguedad ; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `rotacion_update` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `rotacion_update`() +BEGIN + -- Sólo hace la consulta gorda los sábados de madrugada. Necesita casi dos horas. + CALL rotacion_update_manual(1, 999999, TIMESTAMPADD(WEEK, -1, CURDATE()), CURDATE()); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `rotacion_update_manual` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `rotacion_update_manual`( + vItemFrom INT, + vItemTo INT, + vStartDate DATE, + vEndDate DATE +) +BEGIN + + DECLARE vDays INT DEFAULT DATEDIFF(vEndDate, vStartDate); + DECLARE vLastEventFinished DATETIME; + + DROP TEMPORARY TABLE IF EXISTS timing; + CREATE TEMPORARY TABLE timing + SELECT 'Starting Procedure' AS evento, now() as finished, 0 as seconds; + + SELECT now() INTO vLastEventFinished; + + REPLACE bi.rotacion(Id_Article, warehouse_id, total, rotacion) + SELECT Id_Article, warehouse_id, Total, ROUND((SUM(Saldo_Ponderado) / Total), 2) AS rotacion + -- round(AVG(Saldo_Ponderado) / (Total / vDays),1) AS Rotacion + FROM ( + SELECT Id_Article, + warehouse_id, + @intervalo:= IF(warehouse_id = @wh AND Id_Article = @art, + DATEDIFF(Fecha, @fec),1) AS Dias, + IF(warehouse_id = @wh AND Id_Article = @art, + IF(@sd < 0,0,@sd) * @intervalo, + IF(Unidades<0,0,Unidades)) AS Saldo_Ponderado, + IF(warehouse_id = @wh AND Id_Article = @art, + @sd:= @sd + Unidades, @sd:= Unidades) AS Saldo, + @fec:= Fecha, + @art:= Id_Article, + @wh:= warehouse_id + FROM ( + SELECT Id_Article, landing AS Fecha, sum(Cantidad) AS Unidades, + warehouse_id, @fec:= vStartDate, @art := 0, + @d := 0, @sd:= 0, @wh := 0, @intervalo := 0 + FROM ( + SELECT Id_Article, landing, Cantidad, warehouse_id + FROM vn2008.Compres C + JOIN vn2008.Entradas E USING(Id_Entrada) + JOIN vn2008.Articles A USING(Id_Article) + JOIN vn2008.Tipos tp ON tp.tipo_id = A.tipo_id + JOIN vn2008.reinos r ON r.id = tp.reino_id + JOIN vn2008.travel tr ON tr.id = travel_id + JOIN vn2008.warehouse w ON w.id = tr.warehouse_id + WHERE landing BETWEEN vStartDate AND vEndDate + AND r.mercancia = TRUE + AND Id_Article BETWEEN vItemFrom AND vItemTo + AND Id_Proveedor <> 4 + AND r.display <> 0 + AND NOT E.Inventario + AND NOT fuente + AND NOT redada + UNION ALL + SELECT Id_Article, shipment, -Cantidad, warehouse_id_out + FROM vn2008.Compres C + JOIN vn2008.Entradas E USING(Id_Entrada) + JOIN vn2008.Articles A USING(Id_Article) + JOIN vn2008.Tipos tp ON tp.tipo_id = A.tipo_id + JOIN vn2008.reinos r ON r.id = tp.reino_id + JOIN vn2008.travel tr ON tr.id = travel_id + JOIN vn2008.warehouse w ON w.id = tr.warehouse_id_out + WHERE shipment BETWEEN vStartDate AND vEndDate + AND r.mercancia = TRUE + AND Id_Article BETWEEN vItemFrom AND vItemTo + AND Id_Proveedor <> 4 + AND r.display <> 0 + AND NOT fuente + AND NOT E.Inventario + AND NOT redada + UNION ALL + SELECT Id_Article, DATE(Fecha), -Cantidad, warehouse_id + FROM vn2008.Movimientos M + JOIN vn2008.Articles A USING(Id_Article) + JOIN vn2008.Tipos tp ON tp.tipo_id = A.tipo_id + JOIN vn2008.reinos r ON r.id = tp.reino_id + JOIN vn2008.Tickets t USING(Id_Ticket) + JOIN vn2008.warehouse w ON w.id = t.warehouse_id + WHERE Fecha BETWEEN vStartDate AND vEndDate + AND r.mercancia = TRUE + AND r.display <> 0 + AND NOT fuente + AND Id_Article BETWEEN vItemFrom AND vItemTo + AND Id_Cliente NOT IN (2066,2067,2068) + ) sub + GROUP BY Id_Article, warehouse_id, Fecha + ) sub2 + ) sub4 + JOIN ( + SELECT Id_Article, SUM(Cantidad) AS Total, warehouse_id + FROM vn2008.Compres C + JOIN vn2008.Entradas E USING(Id_Entrada) + JOIN vn2008.Articles A USING(Id_Article) + JOIN vn2008.Tipos tp ON tp.tipo_id = A.tipo_id + LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id + JOIN vn2008.travel tr ON tr.id = travel_id + JOIN vn2008.warehouse w ON w.id = tr.warehouse_id + WHERE landing BETWEEN vStartDate AND vEndDate + AND r.mercancia = TRUE + AND Id_Article BETWEEN vItemFrom AND vItemTo + AND Id_Proveedor <> 4 + AND NOT E.Inventario + AND r.display <> 0 + AND NOT redada + AND NOT fuente + GROUP BY Id_Article, warehouse_id + ) sub3 USING(Id_Article, warehouse_id) + GROUP BY Id_Article, warehouse_id; + + INSERT INTO timing + SELECT 'Replace' AS evento, now() as finished, TIMEDIFF(now(),vLastEventFinished) as seconds; + + SELECT MAX(finished) FROM timing INTO vLastEventFinished; + + -- Añadimos el volumen por unidad de venta + -- FIXME: Optimizar la consulta de actualización + + -- CALL vn2008.item_last_buy_(NULL, vStartDate); + CALL cache.last_buy_refresh(FALSE); + + INSERT INTO timing + SELECT 'last_buy_refresh' AS evento, now() as finished, TIMEDIFF(now(),vLastEventFinished) as seconds; + + SELECT MAX(finished) FROM timing INTO vLastEventFinished; + + UPDATE bi.rotacion r + JOIN cache.last_buy b ON r.Id_Article = b.item_id AND r.warehouse_id = b.warehouse_id + JOIN vn2008.Compres c ON c.Id_Compra = b.buy_id + JOIN vn.packaging p ON p.id = c.Id_Cubo + JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article + JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id + JOIN vn2008.reinos re ON re.id = tp.reino_id + SET cm3 = a.compression * IF(p.volume > 0, p.volume, p.width * p.depth * IF(p.height, p.height, a.medida + 10)) / c.packing + WHERE re.mercancia = TRUE + AND r.Id_Article BETWEEN vItemFrom AND vItemTo; + + INSERT INTO timing + SELECT 'update volume' AS evento, now() as finished, TIMEDIFF(now(),vLastEventFinished) as seconds; + + SELECT MAX(finished) FROM timing INTO vLastEventFinished; + + -- DROP TEMPORARY TABLE vn2008.t_item_last_buy; + + -- Añadimos el coste de almacenamiento y manipulacion + + UPDATE bi.rotacion + JOIN ( + SELECT warehouse_id, SUM(total * rotacion * cm3) AS Operacion + FROM bi.rotacion + WHERE Id_Article BETWEEN vItemFrom AND vItemTo + GROUP BY warehouse_id + ) sub USING(warehouse_id) + JOIN ( + SELECT warehouse_id, SUM(Valor) AS Coste_Auxiliar + FROM bi.tarifa_warehouse + WHERE Id_Premisa = 1 + GROUP BY warehouse_id + ) sub2 USING(warehouse_id) + JOIN ( + SELECT warehouse_id, SUM(Valor) AS Coste_Operativo + FROM bi.tarifa_warehouse + WHERE Id_Premisa IN (2,3) + GROUP BY warehouse_id + ) sub3 USING(warehouse_id) + JOIN ( + SELECT warehouse_id, sum(Valor) AS Coste_Manipulacion + FROM bi.tarifa_warehouse + WHERE Id_Premisa = 4 + GROUP BY warehouse_id + ) sub4 USING(warehouse_id) + SET auxiliar = IF(rotacion < 0, 0, ROUND(rotacion * cm3 * Coste_Auxiliar / Operacion, 4)), + almacenaje = IF(rotacion < 0, 0, ROUND(rotacion * cm3 * Coste_Operativo / Operacion, 4)), + manipulacion = IF(rotacion < 0, 0, ROUND(rotacion * cm3 * Coste_Manipulacion / Operacion, 4)) + WHERE Id_Article BETWEEN vItemFrom AND vItemTo; + + INSERT INTO timing + SELECT 'update almacenamiento' AS evento, now() as finished, TIMEDIFF(now(),vLastEventFinished) as seconds; + + SELECT MAX(finished) FROM timing INTO vLastEventFinished; + + -- Añadimos todos los productos de los que no tenemos histórico + -- con la media de su familia como valor por defecto + + INSERT INTO bi.rotacion(Id_Article, warehouse_id, cm3) + SELECT a.Id_Article, warehouse_id,cm3_m + FROM vn2008.Articles a + JOIN ( + SELECT tp.tipo_id, warehouse_id,AVG(cm3) cm3_m + FROM bi.rotacion rt + JOIN vn2008.Articles a ON a.Id_Article = rt.Id_Article + JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id + JOIN vn2008.reinos r ON r.id = tp.reino_id + WHERE r.mercancia = TRUE + GROUP BY tipo_id, warehouse_id + ) sub ON sub.tipo_id = a.tipo_id + WHERE a.Id_Article BETWEEN vItemFrom AND vItemTo + ON DUPLICATE KEY UPDATE rotacion = rotacion; + + INSERT INTO timing + SELECT 'historico' AS evento, now() as finished, TIMEDIFF(now(),vLastEventFinished) as seconds; + + SELECT MAX(finished) FROM timing INTO vLastEventFinished; + + SELECT * FROM timing; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `rotacion_update_manual_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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `rotacion_update_manual_PCA`(IN datSTART DATE, IN datEND DATE) +BEGIN + + +DECLARE intLAPSO INT DEFAULT DATEDIFF(datEND,datSTART ); +DECLARE intART_DESDE BIGINT DEFAULT 1; +DECLARE intART_HASTA BIGINT DEFAULT 100; + +WHILE intART_HASTA < 999999 DO + + IF intART_HASTA MOD 1000 = 0 THEN + + SELECT intART_HASTA; + + END IF; + + REPLACE bi.rotacion(Id_Article,warehouse_id,total,rotacion) + SELECT Id_Article, warehouse_id, Total, round((sum(Saldo_Ponderado)/Total),2) as rotacion -- round(avg(Saldo_Ponderado) / (Total / intLAPSO),1) as Rotacion + FROM + ( + SELECT Id_Article, warehouse_id, + @intervalo:= IF(warehouse_id = @wh AND Id_Article = @art , DATEDIFF(Fecha, @fec),1) as Dias, + IF(warehouse_id = @wh AND Id_Article = @art , IF(@sd < 0,0,@sd) * @intervalo, IF(Unidades<0,0,Unidades)) as Saldo_Ponderado, + IF(warehouse_id = @wh AND Id_Article = @art , @sd:= @sd + Unidades, @sd:= Unidades) as Saldo + + , @fec:= Fecha, @art:= Id_Article, @wh:= warehouse_id + FROM + ( + SELECT Id_Article, landing as Fecha, sum(Cantidad) as Unidades, warehouse_id, @fec:= datSTART, @art := 0, @d := 0, @sd:= 0, @wh := 0, @intervalo := 0 + FROM + ( + SELECT Id_Article, landing, Cantidad, warehouse_id + FROM vn2008.Compres C + JOIN vn2008.Entradas E using(Id_Entrada) + JOIN vn2008.Articles A using(Id_Article) + JOIN vn2008.Tipos using(tipo_id) + JOIN vn2008.reinos re ON re.id = Tipos.reino_id + JOIN vn2008.travel tr on tr.id = travel_id + JOIN vn2008.warehouse w on w.id = tr.warehouse_id + WHERE landing between datSTART and datEND + AND re.mercancia = TRUE + AND warehouse_id = 44 + AND Id_Article between intART_DESDE and intART_HASTA + AND Id_Proveedor <> 4 + AND reino_id IN (3,4) + AND NOT E.Inventario + AND NOT fuente + AND NOT redada + UNION ALL + SELECT Id_Article, shipment, -Cantidad, warehouse_id_out + FROM vn2008.Compres C + JOIN vn2008.Entradas E using(Id_Entrada) + JOIN vn2008.Articles A using(Id_Article) + JOIN vn2008.Tipos using(tipo_id) + JOIN vn2008.reinos re ON re.id = Tipos.reino_id + JOIN vn2008.travel tr on tr.id = travel_id + JOIN vn2008.warehouse w on w.id = tr.warehouse_id_out + WHERE shipment between datSTART and datEND + AND re.mercancia = TRUE + AND warehouse_id_out = 44 + AND Id_Article between intART_DESDE and intART_HASTA + AND Id_Proveedor <> 4 + AND reino_id IN (3,4) + AND NOT fuente + AND NOT E.Inventario + AND NOT redada + UNION ALL + SELECT Id_Article, date(Fecha), -Cantidad, warehouse_id + FROM vn2008.Movimientos M + JOIN vn2008.Articles A using(Id_Article) + JOIN vn2008.Tipos using(tipo_id) + JOIN vn2008.reinos re ON re.id = Tipos.reino_id + JOIN vn2008.Tickets t using(Id_Ticket) + JOIN vn2008.warehouse w on w.id = t.warehouse_id + WHERE Fecha between datSTART and datEND + AND re.mercancia = TRUE + AND t.warehouse_id = 44 + AND reino_id IN (3,4) + AND NOT fuente + AND Id_Article between intART_DESDE and intART_HASTA + AND Id_Cliente NOT IN (2066,2067,2068) + ) sub + GROUP BY Id_Article, warehouse_id, Fecha + ) sub2 + ) sub4 + JOIN + ( + SELECT Id_Article, sum(Cantidad) as Total, warehouse_id + FROM vn2008.Compres C + JOIN vn2008.Entradas E using(Id_Entrada) + JOIN vn2008.Articles A using(Id_Article) + JOIN vn2008.Tipos using(tipo_id) + JOIN vn2008.reinos re ON re.id = Tipos.reino_id + JOIN vn2008.travel tr on tr.id = travel_id + JOIN vn2008.warehouse w on w.id = tr.warehouse_id + WHERE landing between datSTART and datEND + AND warehouse_id = 44 + AND Id_Article between intART_DESDE and intART_HASTA + AND re.mercancia = TRUE + AND Id_Proveedor <> 4 + AND NOT E.Inventario + AND reino_id IN (3,4) + AND NOT redada + AND NOT fuente + GROUP BY Id_Article, warehouse_id + ) sub3 using(Id_Article, warehouse_id) + GROUP BY Id_Article, warehouse_id; + +SET intART_DESDE = intART_DESDE + 100; +SET intART_DESDE = intART_HASTA + 100; + +END WHILE; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `rotacion_volumen_update` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `rotacion_volumen_update`() +BEGIN +/* + CALL vn2008.item_last_buy_(NULL,curdate()); + + -- Añadimos el volumen por unidad de venta + update bi.rotacion r + JOIN vn2008.t_item_last_buy b ON r.Id_Article = b.item_id AND r.warehouse_id = b.warehouse_id + join vn2008.Compres c ON c.Id_Compra = b.buy_id + join vn.item i ON i.id = c.Id_Article + join vn.itemType tp ON tp.id = i.typeFk + join vn.itemCategory ic ON ic.id = tp.categoryFk + set cm3 = vn.item_getVolume(r.Id_Article, Id_Cubo) / Packing + where ic.merchandise = TRUE; +*/ +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `Ultima_Accion` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = '' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `Ultima_Accion`() +BEGIN + +REPLACE INTO bi.lastaction(Id_Cliente, Cliente, Ultima_accion, Comercial) + +SELECT Id_Cliente, Cliente, Ultima_accion, Comercial +FROM vn2008.Clientes +JOIN +( +SELECT Id_Cliente, MAX(calldate) as Ultima_accion, vn2008.Averiguar_ComercialCliente(Id_Cliente, CURDATE()) as Comercial +FROM +( +SELECT Id_Cliente, calldate +FROM vn2008.cdr +JOIN vn2008.Contactos CT on CT.Telefono = dst +JOIN vn2008.Relaciones using(Id_Contacto) +WHERE Id_Cliente IS NOT NULL +AND duration > 30 +UNION ALL +SELECT Id_Cliente, calldate +FROM vn2008.cdr +JOIN vn2008.Contactos CT on CT.Movil = dst +JOIN vn2008.Relaciones using(Id_Contacto) +WHERE Id_Cliente IS NOT NULL +AND duration > 30 +UNION ALL +SELECT Id_Cliente, calldate +FROM vn2008.cdr +JOIN vn2008.Clientes CT on CT.Telefono = dst +WHERE duration > 30 +UNION ALL +SELECT Id_Cliente, calldate +FROM vn2008.cdr +JOIN vn2008.Clientes CT on CT.Movil = dst +WHERE duration > 30 +UNION ALL +SELECT C.Id_Cliente, Fecha +FROM vn2008.Tickets JOIN vn2008.Consignatarios C using(Id_Consigna) +) sub +GROUP BY Id_Cliente ) sub2 USING(Id_Cliente); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `Velocity_Add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `Velocity_Add`() +BEGIN + +DECLARE bol_EXISTS BOOL; +DECLARE datMAX DATETIME; +DECLARE v_buffer VARCHAR(11); +DECLARE v_sql VARCHAR(255); + + + +SELECT MAX(Fecha) INTO datMAX FROM bi.Velocity; + +IF Date(datMAX) = CURDATE() AND hour(datMAX) > hour(now()) THEN + + + SET v_buffer = vn2008.buffer_name(CURDATE(),1); + + SELECT count(*) INTO bol_EXISTS FROM information_schema.`TABLES` + WHERE TABLE_NAME = CONVERT(v_buffer using utf8) collate utf8_general_ci; + + IF bol_EXISTS THEN + + SET v_sql = sql_printf ( + 'INSERT INTO bi.Velocity(tipo_id, Fecha, Disponible, Visible) + SELECT A.tipo_id, NOW(), sum(avalaible), sum(visible) + FROM vn2008.%t b + JOIN Articles A ON b.item_id = A.Id_Article GROUP BY tipo_id; + ', + v_buffer + ); + + + CALL util.exec (v_sql); + + END IF; + +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 */ ; + +-- +-- Current Database: `bs` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; + +USE `bs`; + +-- +-- Temporary view structure for view `bajasLaborales` +-- + +DROP TABLE IF EXISTS `bajasLaborales`; +/*!50001 DROP VIEW IF EXISTS `bajasLaborales`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `bajasLaborales` AS SELECT + 1 AS `firstname`, + 1 AS `name`, + 1 AS `business_id`, + 1 AS `lastDate`, + 1 AS `endContract`, + 1 AS `type`, + 1 AS `dias`, + 1 AS `userFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `bancos_evolution` +-- + +DROP TABLE IF EXISTS `bancos_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `bancos_evolution` ( + `Fecha` date NOT NULL, + `Id_Banco` int(11) NOT NULL, + `saldo` double NOT NULL DEFAULT '0', + `quilla` double NOT NULL DEFAULT '0', + `deuda` double NOT NULL DEFAULT '0', + `liquidez` double NOT NULL DEFAULT '0', + `disponibilidad ajena` double NOT NULL DEFAULT '0', + `saldo_aux` double NOT NULL DEFAULT '0' COMMENT 'Saldo auxiliar para el calculo de lo dispuesto en las polizas', + PRIMARY KEY (`Fecha`,`Id_Banco`), + KEY `fk_banco_evolution_idx` (`Id_Banco`), + CONSTRAINT `fk_banco_evolution` FOREIGN KEY (`Id_Banco`) REFERENCES `vn`.`bank` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los saldos bancarios'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `carteras` +-- + +DROP TABLE IF EXISTS `carteras`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `carteras` ( + `CodigoTrabajador` varchar(3) CHARACTER SET latin1 NOT NULL, + `Año` int(11) NOT NULL, + `Mes` int(11) NOT NULL, + `Peso` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`CodigoTrabajador`,`Año`,`Mes`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `clientDied` +-- + +DROP TABLE IF EXISTS `clientDied`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `clientDied` ( + `id` int(11) NOT NULL DEFAULT '0', + `clientName` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `lastInvoiced` date DEFAULT NULL, + `workerCode` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `Boss` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `Aviso` varchar(13) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `clientNewBorn` +-- + +DROP TABLE IF EXISTS `clientNewBorn`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `clientNewBorn` ( + `clientFk` int(11) NOT NULL, + `shipped` date NOT NULL, + PRIMARY KEY (`clientFk`), + CONSTRAINT `clientNewBorn_fk1` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Listado de clientes que se consideran nuevos a efectos de cobrar la comision adicional del comercial'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `compradores` +-- + +DROP TABLE IF EXISTS `compradores`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `compradores` ( + `Id_Trabajador` int(11) NOT NULL, + `año` int(4) NOT NULL, + `semana` int(2) NOT NULL, + `importe` decimal(10,2) DEFAULT NULL, + `comision` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`Id_Trabajador`,`año`,`semana`), + CONSTRAINT `comprador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `compradores_evolution` +-- + +DROP TABLE IF EXISTS `compradores_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `compradores_evolution` ( + `Id_Trabajador` int(11) NOT NULL, + `fecha` date NOT NULL, + `importe` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`Id_Trabajador`,`fecha`), + CONSTRAINT `evo_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `experienceIberflora2016` +-- + +DROP TABLE IF EXISTS `experienceIberflora2016`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `experienceIberflora2016` ( + `Id_Cliente` int(11) NOT NULL, + `isVisitor` tinyint(4) NOT NULL DEFAULT '0', + PRIMARY KEY (`Id_Cliente`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de clientes que participan en el estudio sobre la mejora del consumo tras la visita a las instalaciones de Silla'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `fondo_maniobra` +-- + +DROP TABLE IF EXISTS `fondo_maniobra`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `fondo_maniobra` ( + `fecha` date NOT NULL, + `fondo` double DEFAULT NULL, + `clientes_facturas` double DEFAULT NULL, + `clientes_cobros` double DEFAULT NULL, + `proveedores_facturas` double DEFAULT NULL, + `proveedores_pagos` double DEFAULT NULL, + `fondo_medio` double DEFAULT NULL, + PRIMARY KEY (`fecha`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `indicators` +-- + +DROP TABLE IF EXISTS `indicators`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `indicators` ( + `updated` date NOT NULL, + `lastYearSales` int(11) DEFAULT NULL, + `totalGreuge` int(11) DEFAULT NULL, + `latePaymentRate` decimal(5,4) DEFAULT NULL, + `countEmployee` decimal(10,2) DEFAULT NULL, + `averageMana` int(11) DEFAULT NULL, + `bankingPool` int(11) DEFAULT NULL, + `lastMonthActiveClients` int(11) DEFAULT NULL, + `lastMonthLostClients` int(11) DEFAULT NULL, + `lastMonthNewClients` int(11) DEFAULT NULL, + `lastMonthWebBuyingRate` decimal(5,4) DEFAULT NULL, + `productionHours` decimal(10,1) DEFAULT NULL, + `dailyWorkersCost` decimal(10,0) DEFAULT NULL, + `volumeM3` decimal(10,0) DEFAULT NULL, + `salesValue` decimal(10,0) DEFAULT NULL, + `valueM3` decimal(10,0) DEFAULT NULL, + `hoursM3` decimal(5,2) DEFAULT NULL, + `workerCostM3` decimal(10,1) DEFAULT NULL, + `salesWorkersCostRate` decimal(10,2) DEFAULT NULL, + `thisWeekSales` decimal(10,2) DEFAULT NULL, + `lastYearWeekSales` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`updated`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los valores actuales para una consulta diaria rápida por los directivos.'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `lastIndicators` +-- + +DROP TABLE IF EXISTS `lastIndicators`; +/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `lastIndicators` AS SELECT + 1 AS `updated`, + 1 AS `lastYearSales`, + 1 AS `incLastYearSales`, + 1 AS `totalGreuge`, + 1 AS `incTotalGreuge`, + 1 AS `latePaymentRate`, + 1 AS `incLatePaymentRate`, + 1 AS `countEmployee`, + 1 AS `incCountEmployee`, + 1 AS `averageMana`, + 1 AS `incAverageMana`, + 1 AS `bankingPool`, + 1 AS `incbankingPool`, + 1 AS `lastMonthActiveClients`, + 1 AS `incLastMonthActiveClients`, + 1 AS `lastMonthLostClients`, + 1 AS `incLastMonthLostClients`, + 1 AS `lastMonthNewClients`, + 1 AS `incLastMonthNewClients`, + 1 AS `lastMonthWebBuyingRate`, + 1 AS `incLastMonthWebBuyingRate`, + 1 AS `productionHours`, + 1 AS `dailyWorkersCost`, + 1 AS `volumeM3`, + 1 AS `salesValue`, + 1 AS `valueM3`, + 1 AS `hoursM3`, + 1 AS `workerCostM3`, + 1 AS `salesWorkersCostRate`, + 1 AS `thisWeekSales`, + 1 AS `lastYearWeekSales`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `m3` +-- + +DROP TABLE IF EXISTS `m3`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `m3` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `fecha` date NOT NULL, + `provinceFk` smallint(5) unsigned DEFAULT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '0', + `m3` decimal(10,2) DEFAULT NULL, + `year` int(11) DEFAULT NULL, + `month` int(11) DEFAULT NULL, + `week` int(11) DEFAULT NULL, + `day` int(11) DEFAULT NULL, + `dayName` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL, + `euros` decimal(10,2) DEFAULT '0.00', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=393137 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `m3Silla` +-- + +DROP TABLE IF EXISTS `m3Silla`; +/*!50001 DROP VIEW IF EXISTS `m3Silla`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `m3Silla` AS SELECT + 1 AS `fecha`, + 1 AS `year`, + 1 AS `month`, + 1 AS `week`, + 1 AS `day`, + 1 AS `dayName`, + 1 AS `Volumen`, + 1 AS `Euros`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `m3analisis` +-- + +DROP TABLE IF EXISTS `m3analisis`; +/*!50001 DROP VIEW IF EXISTS `m3analisis`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `m3analisis` AS SELECT + 1 AS `fecha`, + 1 AS `year`, + 1 AS `month`, + 1 AS `week`, + 1 AS `day`, + 1 AS `dayName`, + 1 AS `Volumen`, + 1 AS `Euros`, + 1 AS `Departamento`, + 1 AS `Horas`, + 1 AS `Salarios`, + 1 AS `tiempoM3`, + 1 AS `valorM3`, + 1 AS `costeLaboralM3`, + 1 AS `costeEuros`, + 1 AS `precioHora`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `manaCustomer` +-- + +DROP TABLE IF EXISTS `manaCustomer`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `manaCustomer` ( + `Id_Cliente` int(11) NOT NULL, + `Mana` decimal(10,0) NOT NULL DEFAULT '0', + `dated` date NOT NULL, + PRIMARY KEY (`Id_Cliente`,`dated`), + KEY `manaCustomerIdx1` (`dated`), + CONSTRAINT `cliente_fk` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `manaSpellersExcluded` +-- + +DROP TABLE IF EXISTS `manaSpellersExcluded`; +/*!50001 DROP VIEW IF EXISTS `manaSpellersExcluded`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `manaSpellersExcluded` AS SELECT + 1 AS `workerFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `mana_spellers` +-- + +DROP TABLE IF EXISTS `mana_spellers`; +/*!50001 DROP VIEW IF EXISTS `mana_spellers`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `mana_spellers` AS SELECT + 1 AS `Id_Trabajador`, + 1 AS `size`, + 1 AS `used`, + 1 AS `prices_modifier_rate`, + 1 AS `prices_modifier_activated`, + 1 AS `minRate`, + 1 AS `maxRate`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `mana_spellers_excluded` +-- + +DROP TABLE IF EXISTS `mana_spellers_excluded`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mana_spellers_excluded` ( + `Id_Trabajador` int(11) NOT NULL, + PRIMARY KEY (`Id_Trabajador`), + CONSTRAINT `mana_spellers_excluded_fk1` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Usuarios que tienen que estar excluidos del cálculo del maná'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `mermas` +-- + +DROP TABLE IF EXISTS `mermas`; +/*!50001 DROP VIEW IF EXISTS `mermas`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `mermas` AS SELECT + 1 AS `Comprador`, + 1 AS `Familia`, + 1 AS `Referencia`, + 1 AS `Item`, + 1 AS `Cantidad`, + 1 AS `Coste_Unitario`, + 1 AS `Importe`, + 1 AS `Cliente`, + 1 AS `ticketFk`, + 1 AS `Fecha`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `mermasCache` +-- + +DROP TABLE IF EXISTS `mermasCache`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mermasCache` ( + `Comprador` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `año` int(4) NOT NULL, + `Valor_Compra` decimal(10,0) DEFAULT NULL, + `Faltas` decimal(10,0) DEFAULT NULL, + `Basura` decimal(10,0) DEFAULT NULL, + PRIMARY KEY (`Comprador`,`año`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `nightTask` +-- + +DROP TABLE IF EXISTS `nightTask`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `nightTask` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `started` datetime DEFAULT NULL, + `finished` datetime DEFAULT NULL, + `lastFinished` datetime DEFAULT NULL, + `order` int(11) DEFAULT NULL, + `schema` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `procedure` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `error` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `errorCode` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=55 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeInsert` BEFORE INSERT ON `nightTask` FOR EACH ROW +BEGIN + + IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN + + CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); + + END IF; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeUpdate` BEFORE UPDATE ON `nightTask` FOR EACH ROW +BEGIN + + IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN + + CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); + + END IF; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `nightTaskConfig` +-- + +DROP TABLE IF EXISTS `nightTaskConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `nightTaskConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `logMail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `payMethodClient` +-- + +DROP TABLE IF EXISTS `payMethodClient`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `payMethodClient` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `payMethodFk` tinyint(3) unsigned NOT NULL DEFAULT '0', + `clientFk` int(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `FkPayMethod_idx` (`payMethodFk`), + KEY `FkClientPayMethod_idx` (`clientFk`), + KEY `FkDateClientPayMethod` (`dated`,`clientFk`), + CONSTRAINT `FkClientPayMethod` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `FkPayMethodClient` FOREIGN KEY (`payMethodFk`) REFERENCES `vn`.`payMethod` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=6215710 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `payMethodClientEvolution` +-- + +DROP TABLE IF EXISTS `payMethodClientEvolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `payMethodClientEvolution` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `payMethodName` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `amountClient` int(11) NOT NULL, + `amount` decimal(10,2) NOT NULL, + `equalizationTax` decimal(10,2) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2048 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `productivity` +-- + +DROP TABLE IF EXISTS `productivity`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `productivity` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `hh` int(10) unsigned NOT NULL, + `mm` int(10) unsigned NOT NULL, + `m3` double NOT NULL DEFAULT '0', + `workers` int(11) NOT NULL DEFAULT '0', + `wCost` double NOT NULL DEFAULT '0', + `numCoordinadores` int(11) NOT NULL DEFAULT '0', + `costCoordinacion` double NOT NULL DEFAULT '0', + `numSacadores` int(11) NOT NULL DEFAULT '0', + `costSacado` double NOT NULL DEFAULT '0', + `numEncajadores` int(11) NOT NULL DEFAULT '0', + `costEncajado` double NOT NULL DEFAULT '0', + `numPaletizadores` int(11) NOT NULL DEFAULT '0', + `costPaletizado` double NOT NULL DEFAULT '0', + `numCamareros` int(11) NOT NULL DEFAULT '0', + `costCamara` double NOT NULL DEFAULT '0', + `numComplementos` int(11) NOT NULL DEFAULT '0', + `costComplementos` double NOT NULL DEFAULT '0', + `numArtificial` int(11) NOT NULL DEFAULT '0', + `costArtificial` double NOT NULL DEFAULT '0', + `m3FV` double NOT NULL DEFAULT '0', + `m3PCA` double NOT NULL DEFAULT '0', + `m3Artificial` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=64091248 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `productivityDepartment` +-- + +DROP TABLE IF EXISTS `productivityDepartment`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `productivityDepartment` ( + `dated` date NOT NULL, + `amountCoordinacion` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountSacado` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountEncajado` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountPaletizado` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountCamara` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountComplementos` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountArtificial` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`dated`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `productivity_evolution` +-- + +DROP TABLE IF EXISTS `productivity_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `productivity_evolution` ( + `dated` date NOT NULL, + `m3productionCost` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`dated`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `salaries2018` +-- + +DROP TABLE IF EXISTS `salaries2018`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `salaries2018` ( + `person_id` int(11) NOT NULL DEFAULT '0', + `sex` enum('M','F') CHARACTER SET utf8 NOT NULL DEFAULT 'F' COMMENT 'M Masculino F Femenino', + `edad` int(6) DEFAULT NULL, + `antiguedad` int(6) DEFAULT NULL, + `Modalidad` varchar(22) CHARACTER SET utf8mb4 NOT NULL DEFAULT '', + `reason` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `worker` varchar(82) CHARACTER SET utf8 DEFAULT NULL, + `totalDays` decimal(32,0) DEFAULT NULL, + `totalAnual` decimal(16,0) DEFAULT NULL, + `virtualMonthlySalary` decimal(16,0) DEFAULT NULL, + `departamento` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `category_name` varchar(50) CHARACTER SET utf8 NOT NULL, + `level_name` varchar(5) CHARACTER SET utf8 DEFAULT NULL, + `thisYearDateStart` varchar(10) CHARACTER SET utf8mb4 DEFAULT NULL, + PRIMARY KEY (`person_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `salePersonEvolution` +-- + +DROP TABLE IF EXISTS `salePersonEvolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `salePersonEvolution` ( + `dated` date NOT NULL DEFAULT '0000-00-00', + `amount` decimal(10,2) NOT NULL DEFAULT '0.00', + `equalizationTax` decimal(10,2) NOT NULL DEFAULT '0.00', + `salesPersonFk` int(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`dated`,`salesPersonFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `salesByWeek` +-- + +DROP TABLE IF EXISTS `salesByWeek`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `salesByWeek` ( + `week` int(11) NOT NULL, + `year` int(11) NOT NULL, + `sales` double DEFAULT NULL, + UNIQUE KEY `week` (`week`,`year`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vendedores` +-- + +DROP TABLE IF EXISTS `vendedores`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `vendedores` ( + `Id_Trabajador` int(11) NOT NULL, + `año` int(4) NOT NULL, + `mes` int(2) NOT NULL, + `importe` decimal(10,2) DEFAULT NULL, + `comision` decimal(10,2) DEFAULT NULL, + `comisionArrendada` decimal(10,2) DEFAULT NULL COMMENT 'comision proveniente de clientes que han sido donados. Ver tabla Clientes_cedidos', + `comisionCedida` decimal(10,2) DEFAULT NULL COMMENT 'comision generada por los clientes que han sido donados. Ver tabla Clientes_cedidos', + `comisionNuevos` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`Id_Trabajador`,`año`,`mes`), + CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vendedores_evolution` +-- + +DROP TABLE IF EXISTS `vendedores_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `vendedores_evolution` ( + `workerFk` int(11) NOT NULL, + `year` int(11) NOT NULL, + `sales` decimal(10,2) DEFAULT NULL, + `month` int(11) NOT NULL, + PRIMARY KEY (`workerFk`,`year`,`month`), + CONSTRAINT `evo_vendedor_trabajador` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ventas` +-- + +DROP TABLE IF EXISTS `ventas`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ventas` ( + `Id_Movimiento` int(11) NOT NULL, + `importe` decimal(10,3) NOT NULL DEFAULT '0.000', + `recargo` decimal(10,3) NOT NULL DEFAULT '0.000', + `fecha` date NOT NULL, + `tipo_id` smallint(5) unsigned NOT NULL, + `Id_Cliente` int(11) NOT NULL DEFAULT '1', + `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', + PRIMARY KEY (`Id_Movimiento`), + KEY `tip_to_tip_idx` (`tipo_id`), + KEY `clientes_bs_ventas_idx` (`Id_Cliente`), + KEY `empresa_bs_ventas_idx` (`empresa_id`), + KEY `fecha_bs` (`fecha`), + CONSTRAINT `clientes_bs_ventas` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `empresa_bs_ventas` FOREIGN KEY (`empresa_id`) REFERENCES `vn`.`company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `mov_to_mov` FOREIGN KEY (`Id_Movimiento`) REFERENCES `vn`.`sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `tip_to_tip` FOREIGN KEY (`tipo_id`) REFERENCES `vn`.`itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ventas_contables` +-- + +DROP TABLE IF EXISTS `ventas_contables`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ventas_contables` ( + `year` int(4) NOT NULL, + `month` int(2) NOT NULL, + `venta` decimal(10,2) DEFAULT NULL, + `grupo` int(1) NOT NULL, + `reino_id` int(10) unsigned NOT NULL, + `tipo_id` smallint(5) unsigned NOT NULL, + `empresa_id` int(4) NOT NULL, + `gasto` varchar(10) CHARACTER SET latin1 NOT NULL, + PRIMARY KEY (`year`,`month`,`grupo`,`reino_id`,`tipo_id`,`empresa_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `warehouseProduction_kk` +-- + +DROP TABLE IF EXISTS `warehouseProduction_kk`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `warehouseProduction_kk` ( + `fecha` date NOT NULL, + `warehouse_id` smallint(6) unsigned NOT NULL, + `m3` decimal(10,0) NOT NULL DEFAULT '0', + `labourCost` decimal(10,0) NOT NULL DEFAULT '0', + `workerHours` decimal(10,0) NOT NULL DEFAULT '0', + PRIMARY KEY (`fecha`,`warehouse_id`), + KEY `warehouseProduction_fk1_idx` (`warehouse_id`), + CONSTRAINT `warehouseProduction_fk1` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `workerMana` +-- + +DROP TABLE IF EXISTS `workerMana`; +/*!50001 DROP VIEW IF EXISTS `workerMana`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `workerMana` AS SELECT + 1 AS `workerFk`, + 1 AS `amount`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `workerSpeed` +-- + +DROP TABLE IF EXISTS `workerSpeed`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerSpeed` ( + `workerCode` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `accion` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1', + `LitrosMinuto` decimal(10,1) DEFAULT NULL, + `LitrosMinutoLastHour` decimal(10,1) DEFAULT NULL, + `lastUpdated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + PRIMARY KEY (`workerCode`,`warehouseFk`,`accion`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'bs' +-- +/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; +/*!50106 DROP EVENT IF EXISTS `nightTask_launchAll` */; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightTask_launchAll` ON SCHEDULE EVERY 1 DAY STARTS '2017-08-27 02:00:00' ON COMPLETION NOT PRESERVE ENABLE DO CALL bs.nightTask_launchAll */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; +DELIMITER ; +/*!50106 SET TIME_ZONE= @save_time_zone */ ; + +-- +-- Dumping routines for database 'bs' +-- +/*!50003 DROP FUNCTION IF EXISTS `tramo` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `tramo`(vDateTime DATETIME) RETURNS varchar(20) CHARSET utf8 COLLATE utf8_unicode_ci +BEGIN + + DECLARE vTramo VARCHAR(20); + DECLARE vHour INT; + + SET vHour = HOUR(vDateTime) ; + + SET vTramo = + CASE + WHEN vHour BETWEEN 0 AND 14 THEN 'Mañana' + WHEN vHour BETWEEN 15 AND 24 THEN 'Tarde' + END ; + +RETURN vTramo; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `analisisComponentes` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `analisisComponentes`() +BEGIN + +DECLARE vDateStart DATE DEFAULT '2016-01-01'; +DECLARE vDateEnd DATE DEFAULT '2016-11-30'; +DECLARE vDate DATE; + +SET vDate = vDateStart; + +DELETE FROM bs.ventasComponentes; + +WHILE vDate <= vDateEnd DO + + INSERT INTO bs.ventasComponentes + SELECT vDate as Fecha, mc.Id_Componente, cast(sum(m.Cantidad * mc.Valor) AS DECIMAL(10,2)) as Importe + FROM vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento + JOIN bs.ventas v ON v.Id_Movimiento = mc.Id_Movimiento + WHERE v.fecha = vDate + AND empresa_id IN (442,567) + GROUP BY mc.Id_Componente; + + SET vDate = TIMESTAMPADD(DAY,1,vDate); + + IF DAY(vDate) MOD 28 = 0 THEN + + SELECT vDate; + + END IF; + +END WHILE; + + SELECT vDate; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `bancos_evolution_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `bancos_evolution_add`() +BEGIN + /* + + Inserta en la tabla bancos_evolution los saldos acumulados + + */ + + + DECLARE vCurrentDate DATE; + DECLARE vStartingDate DATE DEFAULT '2016-01-01'; + DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 7, CURDATE()); + + DELETE FROM bs.bancos_evolution WHERE Fecha > vStartingDate; + + SET vCurrentDate = vStartingDate; + + WHILE vCurrentDate < vMaxDate DO + + REPLACE bs.bancos_evolution( Fecha + ,Id_Banco + ,saldo) + + SELECT vCurrentDate + , Id_Banco + , sum(saldo) + + FROM + ( + + SELECT Id_Banco + ,saldo_aux as saldo + FROM bs.bancos_evolution + + WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate) -- los saldos acumulados del dia anterior + + UNION ALL + + SELECT c.Id_Banco, IFNULL(sum(Entrada),0) - ifnull(sum(Salida),0) as saldo + FROM vn2008.Cajas c + JOIN vn2008.Bancos b using(Id_Banco) -- saldos de las cajas + WHERE cash IN (0,3) + AND Cajafecha = vCurrentDate + AND (Serie = 'MB' OR cash = 3) + GROUP BY Id_Banco + + UNION ALL + + SELECT id_banco, - importe -- pagos futuros + FROM vn2008.pago + WHERE fecha = vCurrentDate + AND fecha >= CURDATE() + AND NOT conciliado + + UNION ALL + + SELECT Id_Banco, Entregado -- cobros futuros + FROM vn2008.Recibos + WHERE Fechacobro = vCurrentDate + AND Fechacobro > CURDATE() + + UNION ALL + + SELECT sp.Id_Banco, Importe -- saldos de la tabla prevision + FROM vn2008.Saldos_Prevision sp + JOIN vn2008.Bancos b using(Id_Banco) + WHERE cash IN (0,3) + AND Fecha = vCurrentDate + + + + )sub + GROUP BY Id_Banco; + + -- Utilizamos el saldo_auxiliar para calcular lo dispuesto en las polizas + + UPDATE bs.bancos_evolution be + SET saldo_aux = saldo; + + -- Ahora actualizamos la quilla + UPDATE bs.bancos_evolution be + LEFT JOIN + ( + SELECT Id_Banco, - sum(importe) as quilla + FROM vn2008.Bancos_poliza + WHERE vCurrentDate between apertura AND IFNULL(cierre, vCurrentDate) + GROUP BY Id_Banco + ) sub using(Id_Banco) + SET be.quilla = sub.quilla + WHERE be.Fecha = vCurrentDate; + + + SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate); + + END WHILE; + + + -- Deuda + UPDATE bs.bancos_evolution be + JOIN vn2008.Bancos using(Id_Banco) + SET be.deuda = IF(cash = 3, be.saldo_aux, 0) + , be.saldo = IF(cash = 3, 0, be.saldo_aux) + WHERE Fecha >= vStartingDate; + + + -- Liquidez + update bs.bancos_evolution set liquidez = saldo - quilla + deuda WHERE Fecha >= vStartingDate; + + -- Disponibilidad + update bs.bancos_evolution set `disponibilidad ajena` = - quilla + deuda WHERE Fecha >= vStartingDate; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `campaignComparative` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `campaignComparative`(vDateFrom DATE, vDateTo DATE) +BEGIN + SELECT + workerName, + id, + name, + CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, + CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount + FROM ( + (SELECT + CONCAT(w.firstname, ' ', w.lastName) AS workerName, + c.id, + c.name, + SUM(v.importe) AS previousAmmount, + 0 currentAmmount + FROM bs.ventas v + INNER JOIN vn.`client` c ON v.Id_Cliente = c.id + INNER JOIN vn.worker w ON c.salesPersonFk = w.id + WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) + AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR) + GROUP BY w.id, v.Id_Cliente) + UNION ALL + (SELECT + CONCAT(w.firstname, ' ', w.lastName) AS workerName, + c.id, + c.name, + 0 AS previousAmmount, + SUM(s.quantity * s.price) AS currentAmmount + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.client c ON c.id = t.clientFk + JOIN vn.worker w ON c.salesPersonFk = w.id + WHERE t.shipped BETWEEN vDateFrom + AND vDateTo + GROUP BY w.id, c.id) + ) comparative + GROUP BY workerName, id + HAVING (previousAmmount <> 0 OR currentAmmount <> 0) + ORDER BY workerName, id; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `carteras_add` */; +ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `carteras_add`() +BEGIN + +DELETE FROM bs.carteras +WHERE Año >= YEAR(CURDATE()) - 1; + +INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) +SELECT year as Año, month as Mes, CodigoTrabajador, sum(importe) as Peso +FROM vn2008.time t +JOIN bs.ventas v on t.date = v.fecha +JOIN vn2008.Clientes c on c.Id_Cliente = v.Id_Cliente +JOIN vn2008.Trabajadores tr on tr.Id_Trabajador = c.Id_Trabajador +WHERE t.year >= YEAR(CURDATE()) - 1 +GROUP BY CodigoTrabajador, Año, Mes; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `clientDied` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientDied`() +BEGIN + + IF DAY(CURDATE()) = 6 THEN + + SET @primerAviso := TIMESTAMPADD(MONTH,-1,CURDATE()); + SET @segundoAviso := TIMESTAMPADD(MONTH,-2,CURDATE()); + SET @tercerAviso := TIMESTAMPADD(MONTH,-3,CURDATE()); + + TRUNCATE TABLE bs.clientDied; + + INSERT INTO bs.clientDied + SELECT c.id, + c.name as clientName, + maxIssued as lastInvoiced, + w.code AS workerCode, + b.code AS Boss, + CASE + WHEN IFNULL(maxIssued,'2000-01-01') < @tercerAviso THEN 'Tercer Aviso' + WHEN maxIssued < @segundoAviso THEN 'Segundo Aviso' + WHEN maxIssued < @primerAviso THEN 'Primer Aviso' + END as Aviso + FROM vn.client c + JOIN vn.worker w ON w.id = c.salesPersonFk + JOIN vn2008.jerarquia j ON j.worker_id = w.id + JOIN vn.worker b ON b.id = j.boss_id + JOIN bs.mana_spellers ms ON ms.Id_Trabajador = c.salesPersonFk + LEFT JOIN (SELECT clientFk, max(issued) as maxIssued FROM vn.invoiceOut GROUP BY clientFk) io ON io.clientFk = c.id + WHERE (maxIssued IS NULL OR maxIssued < @primerAviso) + AND c.created < @tercerAviso; + + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientNewBorn_Update` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientNewBorn_Update`() +BEGIN + + DECLARE fromDated DATE DEFAULT '2019-04-01'; + + -- Eliminamos clientes que ya no son nuevos + DELETE FROM bs.clientNewBorn + WHERE shipped < TIMESTAMPADD(YEAR,-1,CURDATE()); + + -- Clientes nuevos + REPLACE bs.clientNewBorn(clientFk,shipped) + SELECT t.clientFk, MIN(t.shipped) as shipped + FROM vn.ticket t + WHERE shipped > '2001-01-01' + GROUP BY t.clientFk + HAVING shipped >= GREATEST(TIMESTAMPADD(YEAR,-1,CURDATE()), fromDated); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `comercialesCompleto` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `comercialesCompleto`(IN vWorker INT, vDate DATE) +BEGIN + +CALL vn.subordinateGetList(vWorker); + +SELECT + c.Id_Cliente id_cliente, + c.calidad, + c.Cliente cliente, + cr.recobro * 100 tarifa, + c.Telefono telefono, + c.movil, + c.POBLACION poblacion, + p.`name` provincia, + vn2008.red(f.futur) futur, + c.Credito credito, + pm.`name` forma_pago, + vn2008.red(c365 / 12) consumo_medio365, + vn2008.red(c365) consumo365, + vn2008.red(CmLy.peso) peso_mes_año_pasado, + vn2008.red(CmLy.peso * 1.19) objetivo, + tr.CodigoTrabajador, + vn2008.red(mes_actual.consumo) consumoMes, + vn2008.red(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0)) como_lo_llevo, + DATE(LastTicket) ultimo_ticket, + dead.muerto, + g.Greuge, + cr.recobro +FROM + vn2008.Clientes c + LEFT JOIN + (SELECT Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge + FROM vn2008.Greuges + GROUP BY Id_Cliente + ) g ON g.Id_Cliente = c.Id_Cliente + LEFT JOIN + vn2008.province p ON p.province_id = c.province_id + JOIN + vn2008.pay_met pm ON pm.id = c.pay_met_id + LEFT JOIN + vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + LEFT JOIN + bi.claims_ratio cr on cr.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT v.Id_Cliente, SUM(importe) c365 -- optimizat de 6s /5.3s/ 4.7s a 0.3/0.4/0.3 + FROM bs.ventas v + JOIN vn2008.Clientes c USING (Id_Cliente) + + WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, vDate) AND vDate + GROUP BY v.Id_Cliente) c365 ON c365.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT + Id_Cliente, SUM(importe) consumo + FROM + bs.ventas v + INNER JOIN vn2008.Clientes c USING (Id_Cliente) + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + WHERE + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + AND (v.fecha BETWEEN TIMESTAMPADD(DAY, - DAY(vDate) + 1, vDate) AND TIMESTAMPADD(DAY, - 1, vDate)) + GROUP BY Id_Cliente) mes_actual ON mes_actual.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT + t.Id_Cliente, + SUM(m.preu * m.Cantidad * (1 - m.Descuento / 100)) futur + FROM + vn2008.Tickets t + JOIN vn2008.Clientes c ON c.Id_Cliente = t.Id_Cliente + JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + WHERE + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + AND DATE(Fecha) BETWEEN vDate AND LAST_DAY(vDate) + GROUP BY Id_Cliente) f ON c.Id_Cliente = f.Id_Cliente + LEFT JOIN + (SELECT + MAX(t.Fecha) LastTicket, c.Id_Cliente + FROM + vn2008.Tickets t + JOIN vn2008.Clientes c ON c.Id_cliente = t.Id_Cliente + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + + WHERE + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + GROUP BY t.Id_Cliente) LastTicket ON LastTicket.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT + SUM(importe) peso, c.Id_Cliente + FROM + bs.ventas v + JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + WHERE + MONTH(fecha) = MONTH(vDate) + AND YEAR(fecha) = YEAR(vDate) - 1 + AND (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + GROUP BY c.Id_Cliente) CmLy ON CmLy.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT + c.Id_Cliente, + IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto + FROM + vn2008.Facturas f + JOIN vn2008.Clientes c ON c.Id_cliente = f.Id_Cliente + + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + WHERE + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente + JOIN tmp.subordinate s ON s.workerFk = c.Id_Trabajador; + +DROP TEMPORARY TABLE tmp.subordinate; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `compradores_add` */; +ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `compradores_add`(IN intYEAR INT, IN intWEEK_START INT, IN intWEEK_END INT) +BEGIN + +REPLACE bs.compradores + +SELECT tp.Id_Trabajador + , intYEAR as año + , tm.week as semana + , sum(importe) as importe + , 0 as comision + +FROM bs.ventas v +JOIN vn2008.time tm on tm.date = v.fecha +JOIN vn2008.Tipos tp using(tipo_id) +WHERE tm.year = intYEAR and tm.week between intWEEK_START and intWEEK_END +AND reino_id != 6 +GROUP BY tp.Id_Trabajador, tm.week; + + + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `compradores_add_launcher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `compradores_add_launcher`() +BEGIN + + DECLARE vYear INT; + DECLARE vWeek INT; + DECLARE done BOOL DEFAULT FALSE; + + DECLARE rs CURSOR FOR + SELECT year, week + FROM vn.time + WHERE (year = vYear AND week >= vWeek) + OR year > vYear; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + SELECT MAX(año) INTO vYear + FROM compradores; + + SELECT MAX(semana) INTO vWeek + FROM compradores + WHERE año = vYear; + + OPEN rs; + + FETCH rs INTO vYear, vWeek; + + WHILE NOT done DO + + CALL compradores_add(vYear, vWeek, vWeek); + + FETCH rs INTO vYear, vWeek; + + END WHILE; + + CLOSE rs; + + CALL compradores_evolution_add; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `compradores_evolution_add` */; +ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `compradores_evolution_add`() +BEGIN +/* + +Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias + +*/ + +DECLARE datFEC DATE; + + +SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution; + + WHILE datFEC < CURDATE() DO + + SELECT datFEC; + + REPLACE bs.compradores_evolution( Id_Trabajador + , fecha + , importe) + + SELECT Id_Trabajador + , datFEC as fecha + , sum(importe) as importe + + FROM + ( + + SELECT Id_Trabajador + , importe + FROM bs.compradores_evolution + WHERE fecha = TIMESTAMPADD(DAY,-1,datFEC) -- las ventas acumuladas del dia anterior + + UNION ALL + + SELECT Id_Trabajador + , importe * IF(v.fecha < datFEC,-1,1) -- se restan las ventas del año anterior y se suman las del actual + FROM bs.ventas v + JOIN vn2008.Tipos tp using(tipo_id) + WHERE fecha IN (datFEC, TIMESTAMPADD(DAY,-365,datFEC)) + AND reino_id != 6 + + )sub + GROUP BY Id_Trabajador; + + + + + SET datFEC = TIMESTAMPADD(DAY,1,datFEC); + + END WHILE; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `fondo_evolution_add` */; +ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `fondo_evolution_add`() +BEGIN +/* + +Inserta en la tabla fondo_maniobra los saldos acumulados en los ultimos 365 dias + +*/ + +DECLARE datFEC DATE DEFAULT '2015-01-01'; + + +SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.fondo_maniobra; + + WHILE datFEC < CURDATE() DO + + -- esto solo sirve para no aburrirse mientras esperamos... + + IF day(datFEC) mod 28 = 0 then + SELECT datFEC; + end if; + + + REPLACE bs.fondo_maniobra(Fecha, clientes_facturas, clientes_cobros,proveedores_facturas,proveedores_pagos, fondo) + SELECT datFEC as Fecha, Facturas, Cobros,Recibidas,Pagos, Facturas + Cobros + Recibidas + Pagos + FROM + ( + SELECT Sum(Facturas.Importe) AS Facturas + FROM vn2008.Facturas + INNER JOIN vn2008.Clientes ON Facturas.Id_Cliente = Clientes.Id_cliente + WHERE Clientes.`real` + AND empresa_id <>1381 + AND Fecha between '2011-01-01' and datFEC) fac + JOIN + ( + SELECT - Sum(Entregado) AS Cobros + FROM vn2008.Recibos + INNER JOIN vn2008.Clientes ON Recibos.Id_Cliente = Clientes.Id_cliente + WHERE Clientes.`real` + AND empresa_id <> 1381 + AND Fechacobro Between '2011-01-01' and datFEC) cob + JOIN + ( + SELECT - Sum(cantidad) AS Recibidas + FROM vn2008.recibida + INNER JOIN vn2008.recibida_vencimiento ON recibida.id = recibida_vencimiento.recibida_id + WHERE empresa_id <> 1381 + AND recibida.fecha Between '2015-01-01' and datFEC) rec + JOIN + ( + SELECT Sum(importe) AS Pagos + FROM vn2008.pago + WHERE empresa_id <>1381 AND pago.fecha Between '2015-01-01' and datFEC) pag; + + + + UPDATE bs.fondo_maniobra + JOIN + (SELECT avg(fondo) as media + FROM bs.fondo_maniobra + WHERE fecha <= datFEC) sub + SET fondo_medio = media + WHERE fecha = datFEC; + + + SET datFEC = TIMESTAMPADD(DAY,1,datFEC); + + END WHILE; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `indicatorsUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `indicatorsUpdate`(vDated DATE) +BEGIN + + DECLARE oneYearBefore DATE DEFAULT TIMESTAMPADD(YEAR,-1,vDated); + DECLARE twoMonthsBefore DATE DEFAULT TIMESTAMPADD(DAY,-60,vDated); + DECLARE oneMonthBefore DATE DEFAULT TIMESTAMPADD(DAY,-30,vDated); + DECLARE vWeek INT; + + REPLACE indicators(updated) + VALUES(vDated); + + -- Ventas totales del ultimo año + UPDATE indicators + SET lastYearSales = + ( + SELECT SUM(importe + recargo) + FROM bs.ventas v + JOIN vn2008.empresa e ON e.id = v.empresa_id + JOIN vn2008.empresa_grupo eg ON eg.empresa_grupo_id = e.empresa_grupo + WHERE fecha BETWEEN oneYearBefore AND vDated + AND eg.grupo = 'Verdnatura' + ) + WHERE updated = vDated; + + -- Greuge total acumulado + UPDATE indicators + SET totalGreuge = + ( + SELECT SUM(amount) + FROM vn.greuge + WHERE shipped <= vDated + ) + WHERE updated = vDated; + + + -- Tasa de morosidad con respecto a las ventas del último mes + UPDATE indicators + SET latePaymentRate = + (SELECT SUM(amount) FROM bi.defaulters WHERE date = vDated and amount > 0) + / + ( SELECT SUM(importe + recargo) FROM bs.ventas WHERE fecha BETWEEN oneMonthBefore AND vDated) + WHERE updated = vDated; + + -- Número de trabajadores activos + UPDATE indicators + SET countEmployee = + ( SELECT CAST(SUM(hours_week) / 40 AS DECIMAL (10 , 2 )) + FROM + postgresql.business AS b + JOIN postgresql.profile p ON p.profile_id = b.provider_id + JOIN postgresql.person pe ON pe.person_id = p.person_id + LEFT JOIN + postgresql.business_labour AS bl ON bl.business_id = b.business_id + LEFT JOIN + postgresql.calendar_labour_type AS cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id + WHERE + (vDated BETWEEN b.date_start AND b.date_end OR (b.date_end IS NULL AND b.date_start <= vDated)) + AND pe.name = 'VERDNATURA LEVANTE SL' + ) + WHERE updated = vDated; + + -- Maná medio acumulado por comercial + UPDATE indicators + SET averageMana = + (SELECT avg(used) + FROM bs.mana_spellers + ) + WHERE updated = vDated; + + -- Número de clientes que han comprado en los últimos 30 dias + UPDATE indicators + SET lastMonthActiveClients = + (SELECT COUNT(DISTINCT t.clientFk) + FROM vn.ticket t + WHERE t.shipped BETWEEN oneMonthBefore AND vDated + ) + WHERE updated = vDated; + + -- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores + UPDATE indicators + SET lastMonthLostClients = + (SELECT COUNT(lm.clientFk) + FROM + ( + SELECT DISTINCT t.clientFk + FROM vn.ticket t + WHERE t.shipped BETWEEN oneMonthBefore AND vDated + ) cm + RIGHT JOIN + ( + SELECT DISTINCT t.clientFk + FROM vn.ticket t + WHERE t.shipped >= twoMonthsBefore + AND t.shipped < oneMonthBefore + ) lm ON lm.clientFk = cm.clientFk + WHERE cm.clientFk IS NULL + ) + WHERE updated = vDated; + + -- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores + UPDATE indicators + SET lastMonthNewClients = + (SELECT COUNT(cm.clientFk) + FROM + ( + SELECT DISTINCT t.clientFk + FROM vn.ticket t + WHERE t.shipped BETWEEN oneMonthBefore AND vDated + ) cm + LEFT JOIN + ( + SELECT DISTINCT t.clientFk + FROM vn.ticket t + WHERE t.shipped >= twoMonthsBefore + AND t.shipped < oneMonthBefore + ) lm ON lm.clientFk = cm.clientFk + WHERE lm.clientFk IS NULL + ) + WHERE updated = vDated; + + -- Porcentaje de autopedidos sobre los pedidos totales + UPDATE indicators + SET lastMonthWebBuyingRate = + ( SELECT (SUM(source_app != '') - SUM(source_app = 'TPV')) / SUM(source_app != '') + FROM hedera.`order` + WHERE date_send BETWEEN oneMonthBefore AND vDated + ) + WHERE updated = vDated; + + -- Indicadores de producción + UPDATE indicators i + JOIN productionIndicators pi ON pi.dated = i.updated + SET i.productionHours = pi.productionHours, + i.dailyWorkersCost = pi.dailyWorkersCost, + i.volumeM3 = pi.volumeM3, + i.salesValue = pi.salesValue, + i.valueM3 = pi.valueM3, + i.hoursM3 = pi.hoursM3, + i.workerCostM3 = pi.workerCostM3, + i.salesWorkersCostRate = pi.salesWorkersCostRate + WHERE updated BETWEEN oneMonthBefore AND vDated; + + -- CAP Para el calculo de las ventas agrupado por semanas + + SELECT week + FROM vn.time + WHERE dated=vDated INTO vWeek; + + TRUNCATE `bs`.`salesByWeek`; + + INSERT INTO `bs`.`salesByWeek` (week,year,sales) + SELECT `t`.`week` AS `week`,`t`.`year` AS `year`, SUM(`v`.`importe` + `v`.`recargo`) AS `sales` + FROM `bs`.`ventas` `v` + LEFT JOIN `vn`.`time` `t` ON `t`.`dated` = fecha + GROUP BY `t`.`week` , `t`.`year` + ORDER BY `t`.`week` , `t`.`year`; + + -- CAP Indicador Ventas semana actual + UPDATE indicators i + JOIN `bs`.`salesByWeek` s ON s.week= vWeek AND s.year = YEAR(vDated) + SET i.thisWeekSales = s.sales + WHERE updated = vDated; + + -- CAP indicador ventas semana actual en el año pasado + UPDATE indicators i + JOIN `bs`.`salesByWeek` s ON s.week= vWeek AND s.year = YEAR(vDated)-1 + SET i.lastYearWeekSales = s.sales + WHERE updated = vDated; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `indicatorsUpdateLauncher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `indicatorsUpdateLauncher`() +BEGIN + + DECLARE vDated DATE; + + SELECT IFNULL(TIMESTAMPADD(DAY,1,MAX(updated)), '2018-04-01') + INTO vDated + FROM bs.indicators; + + WHILE vDated < CURDATE() DO + + CALL indicatorsUpdate(vDated); + + SELECT TIMESTAMPADD(DAY,1,MAX(updated)) + INTO vDated + FROM bs.indicators; + + END WHILE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `m3Add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `m3Add`() +BEGIN + + DECLARE datSTART DATE; + DECLARE datEND DATE; + + SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART + FROM bs.m3; + + SET datEND = TIMESTAMPADD(DAY,-1,CURDATE()); + + DELETE FROM bs.m3 + WHERE fecha >= datSTART; + + INSERT INTO bs.m3 (fecha, provinceFk, warehouseFk, m3, year, month, week, day, dayName, euros) + SELECT v.fecha, a.provinceFk, t.warehouseFk, sum(i.compression * s.quantity * r.cm3) / 1000000 AS m3, + tm.year, tm.month, tm.week, tm.day, dayname(v.fecha), sum(importe) + FROM vn.ticket t + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN bs.ventas v ON v.Id_Movimiento = s.id -- Filtra solo por ventas "buenas" + JOIN vn.time tm ON tm.dated = v.fecha + JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk + JOIN vn.address a ON a.id = t.addressFk + WHERE v.fecha BETWEEN datSTART AND datEND + AND s.quantity > 0 -- evita abonos + AND t.companyFk = 442 -- Verdnatura + GROUP BY t.warehouseFk, v.fecha, a.provinceFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `manaCustomerUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `manaCustomerUpdate`() +BEGIN +DECLARE vToDated DATE; + DECLARE vFromDated DATE; + DECLARE vForDeleteDated DATE; + DECLARE vManaId INT DEFAULT 37; + DECLARE vManaAutoId INT DEFAULT 39; + DECLARE vManaBankId INT DEFAULT 66; + DECLARE vManaGreugeTypeId INT DEFAULT 3; + + SELECT IFNULL(max(dated), '2016-01-01') + INTO vFromDated + FROM bs.manaCustomer; + + DELETE + FROM bs.manaCustomer + WHERE dated = vFromDated; + + SELECT IFNULL(max(dated), '2016-01-01') + INTO vFromDated + FROM bs.manaCustomer; + + WHILE timestampadd(DAY,30,vFromDated) < CURDATE() DO + + SELECT + timestampadd(DAY,30,vFromDated), + timestampadd(DAY,-90,vFromDated) + INTO + vToDated, + vForDeleteDated; + + DELETE FROM bs.manaCustomer + WHERE dated <= vForDeleteDated; + + + INSERT INTO bs.manaCustomer(Id_Cliente, Mana, dated) + + SELECT + Id_Cliente, + cast(sum(mana) as decimal(10,2)) as mana, + vToDated as dated + FROM + + ( + SELECT cs.Id_Cliente, Cantidad * Valor as mana + FROM vn2008.Tickets t + JOIN vn2008.Consignatarios cs using(Id_Consigna) + JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket + JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento + WHERE Id_Componente IN (vManaAutoId, vManaId) + AND t.Fecha > vFromDated + AND date(t.Fecha) <= vToDated + + + UNION ALL + + SELECT r.Id_Cliente, - Entregado + FROM vn2008.Recibos r + WHERE Id_Banco = vManaBankId + AND Fechacobro > vFromDated + AND Fechacobro <= vToDated + + UNION ALL + + SELECT g.Id_Cliente, g.Importe + FROM vn2008.Greuges g + WHERE Greuges_type_id = vManaGreugeTypeId + AND Fecha > vFromDated + AND Fecha <= vToDated + + UNION ALL + + SELECT Id_Cliente, mana + FROM bs.manaCustomer + WHERE dated = vFromDated + ) sub + + GROUP BY Id_Cliente + HAVING Id_Cliente; + + SET vFromDated = vToDated; + + END WHILE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `manaSpellers_actualize` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `manaSpellers_actualize`() +BEGIN + + /* PAK 2019/08/09 updated + * + * Recalcula el valor del campo con el modificador de precio para el componente de maná automático. + * La tabla mana_spellers es una caché + * + */ + + UPDATE mana_spellers me + JOIN + (SELECT Id_Trabajador, FLOOR(SUM(importe)/12) as pesoCarteraMensual + FROM bs.vendedores + WHERE año * 100 + mes >= (YEAR(CURDATE()) -1) * 100 + MONTH(CURDATE()) + GROUP BY Id_Trabajador + ) lastYearSales USING(Id_Trabajador) + SET me.prices_modifier_rate = GREATEST(me.minRate,LEAST(me.maxRate,ROUND(- me.used/lastYearSales.pesoCarteraMensual,3))) ; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `mermasCacheUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `mermasCacheUpdate`() +BEGIN + + DECLARE vTimeRange INT DEFAULT 30; + DECLARE vCurYearStarted DATE DEFAULT TIMESTAMPADD(DAY, - vTimeRange, CURDATE()); + DECLARE vCurYearFinished DATE DEFAULT CURDATE(); + DECLARE vLastYearStarted DATE DEFAULT TIMESTAMPADD(YEAR, -1 , vCurYearStarted); + DECLARE vLastYearFinished DATE DEFAULT TIMESTAMPADD(YEAR, -1 , vCurYearFinished); + + REPLACE bs.mermasCache + SELECT Comprador, + IF(Fecha < vCurYearStarted, year(CURDATE()) - 1,year(CURDATE())) año, + CAST(sum(Importe) as DECIMAL(10,0)) as Valor_Compra, + CAST(sum(IF(Cliente LIKE 'FALTAS',Importe,0)) as DECIMAL(10,0)) as Faltas, + CAST(sum(IF(Cliente LIKE 'BASURA',Importe,0)) as DECIMAL(10,0)) as Basura + FROM bs.mermas + WHERE Fecha BETWEEN vCurYearStarted AND vCurYearFinished + OR Fecha BETWEEN vLastYearStarted AND vLastYearFinished + GROUP BY año, Comprador; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nightTask_launchAll` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nightTask_launchAll`() +BEGIN +/** + * Runs all nightly tasks. + */ + DECLARE vDone BOOL; + DECLARE vError VARCHAR(255); + DECLARE vErrorCode VARCHAR(255); + DECLARE vNErrors INT DEFAULT 0; + DECLARE vSchema VARCHAR(255); + DECLARE vProcedure VARCHAR(255); + DECLARE vLogMail VARCHAR(255); + DECLARE vId INT; + + DECLARE rs CURSOR FOR + SELECT id, `schema`, `procedure` + FROM nightTask + WHERE finished <= CURDATE() + OR finished IS NULL + ORDER BY `order`; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SET max_sp_recursion_depth = 3; + OPEN rs; + + myLoop: LOOP + SET vDone = FALSE; + FETCH rs INTO vId, vSchema, vProcedure; + + IF vDone THEN + LEAVE myLoop; + END IF; + + UPDATE nightTask + SET `started` = NOW(), + `finished` = NULL, + `error` = NULL, + `errorCode` = NULL + WHERE id = vId; + + SET vError = NULL; + CALL nightTask_launchTask( + vSchema, + vProcedure, + vError, + vErrorCode + ); + + IF vError IS NOT NULL THEN + SET vNErrors = vNErrors + 1; + + UPDATE nightTask + SET `error` = vError, + `errorCode` = vErrorCode + WHERE id = vId; + ELSE + UPDATE nightTask + SET finished = NOW(), + lastFinished = NOW() + WHERE id = vId; + END IF; + END LOOP; + + CLOSE rs; + + SELECT logMail INTO vLogMail + FROM nightTaskConfig LIMIT 1; + + IF vNErrors > 0 AND vLogMail IS NOT NULL THEN + INSERT INTO vn.mail SET + `sender` = vLogMail, + `subject` = 'Nightly task failed', + `body` = CONCAT( + vNErrors, ' procedures of nightly tasks have failed. ', + 'Please, see `', SCHEMA() ,'`.`nightTask` table for more info.' + ); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nightTask_launchTask` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nightTask_launchTask`( + vSchema VARCHAR(255), + vProcedure VARCHAR(255), + OUT vError VARCHAR(255), + OUT vErrorCode VARCHAR(255) +) +BEGIN +/** + * Runs an specific procedure from nightly tasks, if an error + * occurs, instead of throw it, #vError and #vErrorCode variables + * are setted. + * + * @param vSchema The procedure schema + * @param vProcedure The procedure name + * @param vError The error message, if any + * @param vErrorCode The error code, if any + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + GET DIAGNOSTICS CONDITION 1 + vError = MESSAGE_TEXT, + vErrorCode = RETURNED_SQLSTATE; + + CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`')); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `payMethodClientAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `payMethodClientAdd`() +BEGIN + INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk) + SELECT CURDATE(), c.payMethodFk, c.id + FROM vn.client c + JOIN vn.payMethod p ON c.payMethodFk = p.id; + + TRUNCATE `bs`.`payMethodClientEvolution` ; + + INSERT INTO `bs`.`payMethodClientEvolution` (dated, payMethodName, amountClient, amount, equalizationTax) + SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo) + FROM bs.payMethodClient p + JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente + FROM bs.ventas v + WHERE v.fecha>= (SELECT MIN(dated) FROM bs. payMethodClient) + GROUP BY v.Id_cliente, v.fecha) sub ON sub.fecha = p.dated AND sub.Id_cliente = p.ClientFk + JOIN vn.payMethod pm ON p.payMethodFk = pm.id + GROUP BY dated,payMethodFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productivityAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `productivityAdd`(vDate DATE) +BEGIN + + DECLARE vDateStart DATETIME DEFAULT vDate; + DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); + DECLARE myDepLft INT; + DECLARE myDepRgt INT; + + DROP TEMPORARY TABLE IF EXISTS tmp.productivity; + + CREATE TEMPORARY TABLE tmp.productivity + ENGINE = MEMORY + SELECT hh, + mm, + 000.00 as m3, + 000.00 as m3FV, + 000.00 as m3PCA, + 000.00 as m3Artificial, + 0 as workers, + 000.00 as wCost, + 0 as numCoordinadores, + 000.00 as costCoordinacion, + 0 as numSacadores, + 000.00 as costSacado, + 0 as numEncajadores, + 000.00 as costEncajado, + 0 as numPaletizadores, + 000.00 as costPaletizado, + 0 as numCamareros, + 000.00 as costCamara, + 0 as numComplementos, + 000.00 as costComplementos, + 0 as numArtificial, + 000.00 as costArtificial + FROM vn.dayMinute; + +-- Trabajadores + CALL vn.dayMinuteWorker(vDateStart,vDateEnd); -- Genera la tabla tmp.dayMinuteWorker + CALL vn.workerDepartmentByDate(vDate); + + -- General + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + WHERE Almacen IN (1,44) + AND wdd.production + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.workers = sub.workers, p.wCost = sub.Bruto; + + -- Coordinadores + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'COORDINACION'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numCoordinadores = sub.workers, p.costCoordinacion = sub.Bruto; + + -- Sacado + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'SACADO'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numSacadores = sub.workers, p.costSacado = sub.Bruto; + + -- Encajado + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'ENCAJADO'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numEncajadores = sub.workers, p.costEncajado = sub.Bruto; + + -- Paletizado + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'PALETIZADO'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numPaletizadores = sub.workers, p.costPaletizado = sub.Bruto; + + -- Cámara + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'CAMARA'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numCamareros = sub.workers, p.costCamara = sub.Bruto; + + -- Complementos + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'COMPLEMENTOS'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numComplementos = sub.workers, p.costComplementos = sub.Bruto; + + -- Artificial + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'ARTIFICIAL'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numArtificial = sub.workers, p.costArtificial = sub.Bruto; + + -- m3 + CALL vn.ticketBuiltTime(vDate); -- Genera la tabla tmp.ticketBuiltTime(ticketFk,builtTime) + CALL vn.ticketVolumeByDate_ventas(vDate); -- Genera la tabla tmp.ticketVolumeByDate(ticketFk,m3), filtrado por las ventas validas + CALL vn.ticketVolumeByDate_ventas_Artificial(vDate); -- Genera la tabla tmp.ticketVolumeByDate_ventas_Artificial + + UPDATE tmp.productivity p + JOIN + (SELECT HOUR(builtTime) hh, + MINUTE(builtTime) mm, + sum(tvd.m3) as m3, + sum(IF(t.warehouseFk = 1,tvd.m3,0)) as m3FV, + sum(IF(t.warehouseFk = 44,tvd.m3 - IFNULL(tvda.m3,0),0)) as m3PCA, + sum(IFNULL(tvda.m3,0)) as m3Artificial + FROM tmp.ticketBuiltTime tbt + JOIN tmp.ticketVolumeByDate tvd ON tvd.ticketFk = tbt.ticketFk + LEFT JOIN tmp.ticketVolumeByDate_Artificial tvda ON tvda.ticketFk = tbt.ticketFk + JOIN vn.ticket t ON t.id = tbt.ticketFk + WHERE t.warehouseFk IN (1,44) + GROUP BY hh,mm + ) v ON v.hh = p.hh AND v.mm = p.mm + SET p.m3 = v.m3, p.m3FV = v.m3FV, p.m3PCA = v.m3PCA, p.m3Artificial = v.m3Artificial; + + + + DELETE FROM bs.productivity + WHERE dated = vDate; + + INSERT INTO bs.productivity(dated, + hh, + mm, + m3, + m3FV, + m3PCA, + m3Artificial, + workers, + wCost, + numCoordinadores, + costCoordinacion, + numSacadores, + costSacado, + numEncajadores, + costEncajado, + numPaletizadores, + costPaletizado, + numCamareros, + costCamara, + numComplementos, + costComplementos, + numArtificial, + costArtificial) + SELECT vDate, + hh, + mm, + m3, + m3FV, + m3PCA, + m3Artificial, + workers, + wCost, + numCoordinadores, + costCoordinacion, + numSacadores, + costSacado, + numEncajadores, + costEncajado, + numPaletizadores, + costPaletizado, + numCamareros, + costCamara, + numComplementos, + costComplementos, + numArtificial, + costArtificial + FROM tmp.productivity p; + + -- Productivity Evolution + REPLACE bs.productivity_evolution(dated, m3productionCost) + SELECT CURDATE(), sum(wCost) / sum(m3) + FROM bs.productivity + WHERE dated BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND CURDATE(); + + DROP TEMPORARY TABLE tmp.dayMinuteWorker; + DROP TEMPORARY TABLE tmp.productivity; + DROP TEMPORARY TABLE tmp.ticketBuiltTime; + DROP TEMPORARY TABLE tmp.ticketVolumeByDate; + DROP TEMPORARY TABLE tmp.workerDepartmentByDate; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentAdd`(IN vDateStartPeriod DATETIME, IN vDateEndPeriod DATETIME, IN vDateStart DATETIME) +BEGIN + + DECLARE vEndingDate DATETIME; + + SET vEndingDate = vDateStart; + + WHILE vEndingDate <= vDateEndPeriod DO + REPLACE INTO bs.productivityDepartment + SELECT vEndingDate, + CAST(((productivityCoordinacionLastYear - productivityCoordinacion) / 2) * m3 AS DECIMAL (10,2)) AS amountCoordinacion, + CAST(((productivitySacadoLastYear - productivitySacado) / 2) * m3 AS DECIMAL (10,2)) AS amountSacado, + CAST(((productivityEncajadoLastYear - productivityEncajado) / 2) * m3 AS DECIMAL (10,2)) AS amountEncajado, + CAST(((productivityPaletizadoLastYear - productivityPaletizado) / 2) * m3 AS DECIMAL (10,2)) AS amountPaletizado, + CAST(((productivityCamaraLastYear - productivityCamara) / 2) * m3FV AS DECIMAL (10,2)) AS amountCamara, + CAST(((productivityComplementosLastYear - productivityComplementos) / 2) * m3PCA AS DECIMAL (10,2)) AS amountComplementos, + CAST(((productivityArtificialLastYear - productivityArtificial) / 2) * m3Artificial AS DECIMAL (10,2)) AS amountArtificia + FROM + (SELECT + SUM(p.m3) AS m3, SUM(p.m3FV) as m3FV, SUM(p.m3PCA) as m3PCA, SUM(p.m3Artificial) as m3Artificial, + SUM(p.costCoordinacion) / SUM(p.m3) AS productivityCoordinacion, + SUM(p.costSacado) / SUM(p.m3) AS productivitySacado, + SUM(p.costEncajado) / SUM(p.m3) AS productivityEncajado, + SUM(p.costPaletizado) / SUM(p.m3) AS productivityPaletizado, + SUM(p.costCamara) / SUM(p.m3FV) AS productivityCamara, + SUM(p.costComplementos) / SUM(p.m3PCA) AS productivityComplementos, + SUM(p.costArtificial) / SUM(p.m3Artificial) AS productivityArtificial + FROM + bs.productivity p + WHERE + p.dated BETWEEN vDateStartPeriod AND vEndingDate) sub + JOIN + (SELECT + SUM(p.costCoordinacion) / SUM(p.m3) AS productivityCoordinacionLastYear, + SUM(p.costSacado) / SUM(p.m3) AS productivitySacadoLastYear, + SUM(p.costEncajado) / SUM(p.m3) AS productivityEncajadoLastYear, + SUM(p.costPaletizado) / SUM(p.m3) AS productivityPaletizadoLastYear, + SUM(p.costCamara) / SUM(p.m3FV) AS productivityCamaraLastYear, + SUM(p.costComplementos) / SUM(p.m3PCA) AS productivityComplementosLastYear, + SUM(p.costArtificial) / SUM(p.m3Artificial) AS productivityArtificialLastYear + FROM + bs.productivity p + WHERE + p.dated BETWEEN DATE_ADD(vDateStartPeriod, INTERVAL - 1 YEAR) AND DATE_ADD(vEndingDate, INTERVAL - 1 YEAR)) sub1; + + SET vEndingDate = TIMESTAMPADD(DAY,1, vEndingDate); + END WHILE; + END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentLauncher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentLauncher`() +BEGIN + CALL bs.productivityDepartmentAdd('2019-05-06', CURDATE(),DATE_SUB(CURDATE(), INTERVAL 2 WEEK)); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productivityLauncher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher`() +BEGIN + + DECLARE vDateFrom DATE; + + SELECT LEAST(TIMESTAMPADD(MONTH, -1, CURDATE()),MAX(dated)) + INTO vDateFrom + FROM bs.productivity; + + WHILE CURDATE() > vDateFrom DO + CALL bs.productivityAdd(vDateFrom); + SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); + END WHILE; + + SET vDateFrom = TIMESTAMPADD(MONTH, -13, CURDATE()); + + WHILE TIMESTAMPADD(MONTH, -12, CURDATE()) > vDateFrom DO + CALL bs.productivityAdd(vDateFrom); + SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); + END WHILE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productivityLauncher_manual` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher_manual`(vDateFrom DATE, vToDate DATE) +BEGIN + + TRUNCATE tmp.log; + + WHILE vToDate >= vDateFrom DO + + INSERT INTO tmp.log(text) VALUES (vDateFrom); + CALL bs.productivityAdd(vDateFrom); + + CALL bs.productivityAdd(TIMESTAMPADD(YEAR, -1,vDateFrom)); + INSERT INTO tmp.log(text) VALUES (TIMESTAMPADD(YEAR, -1,vDateFrom)); + + SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); + + END WHILE; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `pruebas` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `pruebas`(IN vDateStart DATE, IN vDateEnd DATE) +BEGIN + +WHILE vDateStart <> vDateEnd +DO + UPDATE indicators + SET countEmployee = + ( SELECT CAST(SUM(hours_week) / 40 AS DECIMAL (10 , 2 )) + FROM + postgresql.business AS b + JOIN postgresql.profile p ON p.profile_id = b.provider_id + JOIN postgresql.person pe ON pe.person_id = p.person_id + LEFT JOIN + postgresql.business_labour AS bl ON bl.business_id = b.business_id + LEFT JOIN + postgresql.calendar_labour_type AS cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id + WHERE + (vDateStart BETWEEN b.date_start AND b.date_end OR (b.date_end IS NULL AND b.date_start <= vDateStart)) + AND pe.name = 'VERDNATURA LEVANTE SL' + ) + WHERE updated = vDateStart; + SET vDateStart = DATE_ADD(vDateStart, INTERVAL 1 DAY); + +END WHILE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `salePersonEvolutionAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `salePersonEvolutionAdd`(IN vDateStart DATETIME) +BEGIN + DELETE FROM bs.salePersonEvolution + WHERE dated <= DATE_SUB(CURDATE(), INTERVAL 1 YEAR); + + + INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk) + SELECT fecha dated, + CAST(SUM(importe) AS DECIMAL(10,2) ) amount, + CAST(SUM(recargo) AS DECIMAL(10,2) ) equalizationTax , + IFNULL(salesPersonFk,0) salesPersonFk + FROM bs.ventas v + JOIN vn.client c ON v.Id_Cliente = c.id + JOIN vn.company co ON co.id = v.empresa_id + WHERE co.code = "VNL" AND fecha >= vDateStart + GROUP BY v.fecha,c.salesPersonFk + ORDER BY salesPersonFk,dated ASC; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `userSundayRole` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `userSundayRole`() +BEGIN + -- 4996 Fran Natek Echevarria + DECLARE vDay INT; + SET vDay := (SELECT DAYOFWEEK(CURDATE())); + IF vDay = 1 THEN + UPDATE account.user u + JOIN account.role r + SET u.role = r.id + WHERE u.id = 4996 AND r.name = "salesAssistant"; + ELSE + UPDATE account.user u + JOIN account.role r + SET u.role = r.id + WHERE u.id = 4996 AND r.name = "salesPerson"; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `vendedores_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add`(intYEAR INT, vQuarter INT) +BEGIN + + DECLARE comisionRate DOUBLE DEFAULT 0.029; + + REPLACE vendedores + SELECT c.Id_Trabajador + , intYEAR + , MONTH(v.fecha) intMONTH + , sum(importe) as importe + , sum(importe) * 0.029 as comision + , 0 as comisionCedida + , 0 as comisionArrendada + , 0 as comisionNuevos + + FROM ventas v + JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente + JOIN vn2008.`time` t on t.`date` = v.fecha + WHERE c.Id_Trabajador is not null + AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter + GROUP BY c.Id_Trabajador, t.`month`; + + -- Ventas nuevas + UPDATE vendedores v + JOIN + ( + SELECT c.Id_Trabajador + , sum(importe) * 0.029 as comisionNueva + , t.`month` + , t.`year` + FROM ventas v + JOIN bs.clientNewBorn cnb on v.Id_Cliente = cnb.clientFk + JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente + JOIN vn2008.`time` t on t.`date` = v.fecha + WHERE c.Id_Trabajador is not null + AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter + GROUP BY c.Id_Trabajador, t.`month` + ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año + SET v.comisionNuevos = sub.comisionNueva, v.comision = v.comision - sub.comisionNueva; + + -- Ventas cedidas + UPDATE vendedores v + JOIN ( + SELECT cc.Id_Trabajador_old as Id_Trabajador + , sum(importe) * 0.029 * comision_old as cedido + , sum(importe) * 0.029 * comision_new as arrendada + , t.`month` + , t.`year` + FROM ventas v + JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente + JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente AND v.fecha between datSTART and datEND + JOIN vn2008.`time` t on t.`date` = v.fecha + WHERE c.Id_Trabajador is not null + AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter + GROUP BY cc.Id_Trabajador_old, t.`month` + ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año + SET v.comisionCedida = sub.cedido, v.comision = v.comision - sub.cedido - sub.arrendada; + + -- Ventas arrendadas + UPDATE vendedores v + JOIN ( + SELECT cc.Id_Trabajador_new as Id_Trabajador + , sum(importe) * 0.029 * comision_new as arrendada + , t.`month` + , t.`year` + FROM ventas v + JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente + JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente AND v.fecha between datSTART and datEND + JOIN vn2008.`time` t on t.`date` = v.fecha + WHERE c.Id_Trabajador is not null + AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter + GROUP BY cc.Id_Trabajador_new, t.`month` + ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año + SET v.comisionArrendada = sub.arrendada; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `vendedores_add_launcher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add_launcher`() +BEGIN + + call bs.vendedores_add(YEAR(CURDATE()),QUARTER(CURDATE())); + + call bs.vendedores_evolution_add; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `vendedores_evolution_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_evolution_add`() +BEGIN +/* + +Inserta en la tabla compradores_evolution las ventas acumuladas en el ultimo mes + +*/ + +DECLARE vYear, vMonth INTEGER; +DECLARE vCurYear, vCurMonth INTEGER; +DECLARE vFirstYear INTEGER DEFAULT 2017; +DECLARE vFirstMonth INTEGER DEFAULT 1; + +DECLARE vDateFrom DATE; +DECLARE vDateTo DATE; + +SET vCurYear = year(CURDATE()); +SET vCurMonth = month(CURDATE()); + +SELECT IFNULL(max(year),vFirstYear), IFNULL(max(month),vFirstMonth) + INTO vYear, vMonth + FROM bs.vendedores_evolution; + + WHILE (vYear < vCurYear) OR (vYear = vCurYear AND vMonth < vCurMonth) DO + + SELECT max(dated), TIMESTAMPADD(DAY,-364,max(dated)) INTO vDateTo, vDateFrom + FROM vn.time + WHERE year = vYear + AND month = vMonth; + + SELECT vDateTo, vDateFrom, vYear, vMonth; + + REPLACE bs.vendedores_evolution( workerFk + , year + , month + , sales) + SELECT c.salesPersonFk + , vYear as year + , vMonth as month + , sum(v.importe) as sales + FROM bs.ventas v + JOIN vn.client c on c.id = v.Id_Cliente + WHERE v.fecha BETWEEN vDateFrom AND vDateTo + AND c.salesPersonFk is not null + GROUP BY c.salesPersonFk; + + SET vMonth = vMonth + 1; + + IF vMonth = 13 THEN + + SET vMonth = 1; + SET vYear = vYear + 1; + + END IF; + + END WHILE; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add`(IN datSTART DATETIME, IN datEND DATETIME) +BEGIN + + DECLARE vStartingDate DATETIME; + DECLARE vEndingDate DATETIME; + DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; + + IF datSTART < '2015-10-01' OR datEND < '2015-10-01' THEN + CALL util.throw('fechaDemasiadoAntigua'); + END IF; + + SET datEND = util.dayEnd(datEND); + SET vStartingDate = datSTART; + SET vEndingDate = vn2008.dayend(vStartingDate); + + DELETE + FROM ventas + WHERE fecha between vStartingDate and datEND; + + WHILE vEndingDate <= datEND DO + + REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id) + SELECT Id_Movimiento, + SUM(IF(base, Cantidad * Valor, 0)) as importe, + SUM(IF(base, 0, Cantidad * Valor)) as recargo, + vStartingDate, + a.tipo_id, + cs.Id_Cliente, + t.empresa_id + FROM vn2008.Movimientos_componentes mc + JOIN bi.tarifa_componentes tc using(Id_Componente) + JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) + JOIN vn2008.Movimientos m using(Id_Movimiento) + JOIN vn2008.Articles a using(Id_Article) + JOIN vn2008.Tipos tp using(tipo_id) + JOIN vn2008.reinos r on r.id = tp.reino_id + JOIN vn2008.Tickets t using(Id_Ticket) + JOIN vn2008.Consignatarios cs using(Id_Consigna) + JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente + WHERE t.Fecha between vStartingDate and vEndingDate + AND c.typeFk IN ('Normal','handMaking','internalUse') + AND m.Cantidad <> 0 + AND a.tipo_id != TIPO_PATRIMONIAL + AND m.Descuento <> 100 + AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0) + GROUP BY mc.Id_Movimiento + HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; + + SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); + SET vEndingDate = util.dayEnd(vStartingDate); + + END WHILE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_add_launcher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add_launcher`() +BEGIN + + call bs.ventas_add(timestampadd(week,-1,curdate()),curdate()); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_add__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add__`(IN datSTART DATETIME, IN datEND DATETIME) +BEGIN + + DECLARE vStartingDate DATETIME; + DECLARE vEndingDate DATETIME; + DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; + + SET datEND = util.dayEnd(datEND); + SET vStartingDate = GREATEST('2015-10-01',datSTART); + SET vEndingDate = vn2008.dayend(vStartingDate); + + DELETE + FROM ventas + WHERE fecha between vStartingDate and datEND; + + WHILE vEndingDate <= datEND DO + + REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id) + SELECT Id_Movimiento, + SUM(IF(base, Cantidad * Valor, 0)) as importe, + SUM(IF(base, 0, Cantidad * Valor)) as recargo, + vStartingDate, + a.tipo_id, + cs.Id_Cliente, + t.empresa_id + FROM vn2008.Movimientos_componentes mc + JOIN bi.tarifa_componentes tc using(Id_Componente) + JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) + JOIN vn2008.Movimientos m using(Id_Movimiento) + JOIN vn2008.Articles a using(Id_Article) + JOIN vn2008.Tipos tp using(tipo_id) + JOIN vn2008.reinos r on r.id = tp.reino_id + JOIN vn2008.Tickets t using(Id_Ticket) + JOIN vn2008.Consignatarios cs using(Id_Consigna) + JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente + WHERE t.Fecha between vStartingDate and vEndingDate + AND datEND >= '2015-10-01' + AND c.typeFk IN ('Normal','handMaking','internalUse') + AND m.Cantidad <> 0 + AND a.tipo_id != TIPO_PATRIMONIAL + AND c.Id_Trabajador IS NOT NULL + AND m.Descuento <> 100 + AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0) + GROUP BY mc.Id_Movimiento + HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; + + SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); + SET vEndingDate = util.dayEnd(vStartingDate); + + END WHILE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT) +BEGIN +/** + * Reemplaza las ventas contables. Es el origen de datos para el balance de Entradas + * + * @param vYear Año a reemplazar + * @param vMonth Mes a reemplazar + * + * + **/ +DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; + +DELETE FROM bs.ventas_contables + WHERE year = vYear + AND month = vMonth; + +DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + +CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (Id_Ticket)) + SELECT Id_Ticket + FROM vn2008.Tickets t + JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura + WHERE year(f.Fecha) = vYear + AND month(f.Fecha) = vMonth; + + +INSERT INTO bs.ventas_contables(year + , month + , venta + , grupo + , reino_id + , tipo_id + , empresa_id + , gasto) + + SELECT vYear + , vMonth + , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) + , if( + e.empresa_grupo = e2.empresa_grupo + ,1 + ,if(e2.empresa_grupo,2,0) + ) as grupo + , tp.reino_id + , a.tipo_id + , t.empresa_id + , 7000000000 + + if(e.empresa_grupo = e2.empresa_grupo + ,1 + ,if(e2.empresa_grupo,2,0) + ) * 1000000 + + tp.reino_id * 10000 as Gasto + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna + JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente + JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket + JOIN vn2008.Articles a on m.Id_Article = a.Id_Article + JOIN vn2008.empresa e on e.id = t.empresa_id + LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente + JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id + WHERE Cantidad <> 0 + AND Preu <> 0 + AND m.Descuento <> 100 + AND a.tipo_id != TIPO_PATRIMONIAL + GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto; + + +DROP TEMPORARY TABLE tmp.ticket_list; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add_launcher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add_launcher`() +BEGIN + + call bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,CURDATE()))); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_por_cliente` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_por_cliente`(IN vYear INT, IN vMonth INT) +BEGIN + + +DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + +CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (Id_Ticket)) + SELECT Id_Ticket + FROM vn2008.Tickets t + JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura + WHERE year(f.Fecha) = vYear + AND month(f.Fecha) = vMonth; + + + + SELECT vYear Año + , vMonth Mes + , t.Id_Cliente + , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) Venta + , if( + e.empresa_grupo = e2.empresa_grupo + ,1 + ,if(e2.empresa_grupo,2,0) + ) as grupo + , t.empresa_id empresa + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna + JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente + JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket + JOIN vn2008.Articles a on m.Id_Article = a.Id_Article + JOIN vn2008.empresa e on e.id = t.empresa_id + LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente + JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id + WHERE Cantidad <> 0 + AND Preu <> 0 + AND m.Descuento <> 100 + AND a.tipo_id != 188 + GROUP BY t.Id_Cliente, grupo,t.empresa_id; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `vivosMuertos` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `vivosMuertos`() +BEGIN + +SET @datSTART = TIMESTAMPADD(YEAR,-2,CURDATE()); +SET @datEND = TIMESTAMPADD(DAY,-DAY(CURDATE()),CURDATE()); + +DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos; + +CREATE TEMPORARY TABLE tmp.VivosMuertos +SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto +FROM vn2008.Clientes c +JOIN (SELECT DISTINCT yearMonth FROM vn2008.time WHERE date BETWEEN @datSTART AND @datEND ) tm +LEFT JOIN + (SELECT DISTINCT tm.yearMonth, f.Id_Cliente , 1 as Compra + FROM vn2008.Facturas f + JOIN vn2008.time tm ON tm.date = f.Fecha + WHERE Fecha BETWEEN @datSTART AND @datEND) f ON f.yearMonth = tm.yearMonth AND f.Id_Cliente = c.Id_Cliente; + +UPDATE tmp.VivosMuertos vm +JOIN ( + SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente + FROM vn2008.Facturas f + JOIN vn2008.time tm ON tm.date = f.Fecha + WHERE Fecha BETWEEN @datSTART AND @datEND + GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente +SET Nuevo = 1; + +SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos; + +UPDATE tmp.VivosMuertos vm +JOIN ( + SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente + FROM vn2008.Facturas f + JOIN vn2008.time tm ON tm.date = f.Fecha + WHERE Fecha BETWEEN @datSTART AND @datEND + GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente +SET Muerto = 1 +WHERE yearMonth < @lastYearMonth; + + SELECT * FROM tmp.VivosMuertos; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerSpeed` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerSpeed`() +BEGIN + + /* #UPDATED PAK 2019/09/02 + * #PENDING REVIEW + * + * + * + * + */ + + DECLARE vLastUpdated DATETIME; + DECLARE vSecondsDelay INT DEFAULT 300; + + SELECT IFNULL(MAX(lastUpdated),CURDATE()) INTO vLastUpdated + FROM bs.workerSpeed; + + IF TIMESTAMPDIFF(SECOND, vLastUpdated, NOW()) > vSecondsDelay THEN + + DELETE FROM bs.workerSpeed ; + -- WHERE lastUpdated < CURDATE(); + + -- Sacadores + REPLACE bs.workerSpeed + SELECT workerCode, + accion, + warehouseFk, + CAST(60 * sumaLitros / time_to_sec(timediff(finished, started)) AS DECIMAL(10,1)) as LitrosMinuto, + CAST(sumaLitrosLastHour / 60 AS DECIMAL(10,1)) as LitrosMinutoLastHour, + now() as lastUpdated + FROM + ( + SELECT warehouseFk, + accion, + workerCode, + sum(litros) as sumaLitros, + min(created) as started, + max(created) as finished, + sum(IF(created >= TIMESTAMPADD(HOUR, -1, NOW()),litros, 0)) as sumaLitrosLastHour + FROM + ( + SELECT t.warehouseFk, + st.saleFk, + st.isChecked, + st.originalQuantity, + a.accion, + st.created, + e.code, + w.firstname, + w.lastName, + w.code as workerCode, + r.cm3 * s.quantity / 1000 as litros, + s.concept + FROM vn.saleTracking st + LEFT JOIN + (SELECT saleFk + FROM vn.saleTracking st + JOIN vn.state e ON e.id = st.stateFk + WHERE st.created > CURDATE() + AND e.code LIKE 'PREVIOUS_PREPARATION') prevPrepSales ON prevPrepSales.saleFk = st.saleFk + JOIN vn.sale s ON s.id = st.saleFk + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN bi.rotacion r ON r.warehouse_id = t.warehouseFk AND r.Id_Article = s.itemFk + JOIN vn.worker w ON w.id = st.workerFk + JOIN vn.state e ON e.id = st.stateFk + JOIN vncontrol.accion a ON a.accion_id = st.actionFk + WHERE st.created > TIMESTAMPADD(HOUR,-1,NOW()) + AND prevPrepSales.saleFk IS NULL + ) sub + GROUP BY warehouseFk, accion, workerCode + ) sub2; + + -- Encajadores + REPLACE bs.workerSpeed + SELECT code as workerCode, + 'ENCAJAR' as accion, + warehouseFk, + CAST(60 * sum(Litros) / time_to_sec(timediff(MAX(finished), MIN(started))) AS DECIMAL(10,1)) as LitrosMinuto, + CAST(sum(litrosUltimaHora) / 60 AS DECIMAL(10,1)) as LitrosMinutoLastHour, + now() as lastUpdated + FROM ( + SELECT sv.ticketFk, + sum(sv.litros) as litros, + sum(IF(started > TIMESTAMPADD(HOUR,-1,NOW()),sv.litros,0)) as litrosUltimaHora, + code, + started, + finished, + cajas, + warehouseFk + FROM vn.saleVolume sv + JOIN + ( + SELECT ticketFk, + min(e.created) as started, + max(e.created) as finished, + max(counter) as cajas, + w.code, + t.warehouseFk + FROM vn.expedition e + JOIN vn.worker w ON w.id = e.workerFk + JOIN vn.ticket t ON t.id = e.ticketFk + WHERE e.created > CURDATE() + GROUP BY ticketFk + ) sub ON sub.ticketFk = sv.ticketFk + GROUP BY sv.ticketFk) sub2 + GROUP BY code; + + END IF; + + SELECT * FROM bs.workerSpeed; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerSpeed_detail` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerSpeed_detail`(vWorkerCode VARCHAR(3), vAction VARCHAR(25)) +BEGIN + + SELECT * FROM + ( + SELECT time_format(st.created,'%H:%i') as hora, + t.warehouseFk as Almacen, + t.id as ticketFk, + floor(sum(s.quantity * r.cm3) / 1000) as Litros + + FROM vn.saleTracking st + JOIN vn.sale s ON s.id = st.saleFk + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN bi.rotacion r ON r.warehouse_id = t.warehouseFk AND r.Id_Article = s.itemFk + JOIN vn.worker w ON w.id = st.workerFk + JOIN vn.state e ON e.id = st.stateFk + JOIN vncontrol.accion a ON a.accion_id = st.actionFk + WHERE st.created > CURDATE() + AND a.accion LIKE vAction + AND w.code LIKE vWorkerCode + GROUP BY t.id) sub + ORDER BY hora; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Current Database: `cache` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `cache` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; + +USE `cache`; + +-- +-- Table structure for table `available` +-- + +DROP TABLE IF EXISTS `available`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `available` ( + `calc_id` int(10) unsigned NOT NULL, + `item_id` int(11) NOT NULL, + `available` int(11) NOT NULL, + UNIQUE KEY `calc_id` (`item_id`,`calc_id`) USING HASH, + KEY `calc_id_4` (`calc_id`) USING BTREE +) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cache` +-- + +DROP TABLE IF EXISTS `cache`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cache` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) CHARACTER SET utf8 NOT NULL, + `lifetime` time NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cache_calc` +-- + +DROP TABLE IF EXISTS `cache_calc`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cache_calc` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `cache_id` int(10) unsigned NOT NULL, + `cacheName` varchar(255) CHARACTER SET utf8 DEFAULT NULL, + `params` varchar(100) CHARACTER SET utf8 NOT NULL DEFAULT '', + `last_refresh` datetime DEFAULT NULL, + `expires` datetime DEFAULT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `connection_id` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `cache_name` (`cache_id`,`params`), + KEY `cache_id` (`cache_id`), + KEY `cacheName` (`cacheName`), + KEY `expires` (`expires`) +) ENGINE=InnoDB AUTO_INCREMENT=446148 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cache_valid` +-- + +DROP TABLE IF EXISTS `cache_valid`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cache_valid` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `valid` tinyint(3) unsigned NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=MEMORY AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `departure_limit` +-- + +DROP TABLE IF EXISTS `departure_limit`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `departure_limit` ( + `warehouse_id` smallint(6) unsigned NOT NULL, + `fecha` date NOT NULL, + `hora` int(11) NOT NULL DEFAULT '0', + `minSpeed` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`warehouse_id`,`fecha`), + CONSTRAINT `warehouse_departure` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `last_buy` +-- + +DROP TABLE IF EXISTS `last_buy`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `last_buy` ( + `item_id` int(10) unsigned NOT NULL, + `warehouse_id` smallint(5) unsigned NOT NULL, + `buy_id` int(10) unsigned DEFAULT NULL, + `landing` date DEFAULT NULL, + UNIQUE KEY `item_id` (`item_id`,`warehouse_id`) USING HASH, + KEY `buy_id` (`buy_id`), + KEY `warehouse_id` (`warehouse_id`) USING BTREE +) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `prod_graphic_source` +-- + +DROP TABLE IF EXISTS `prod_graphic_source`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `prod_graphic_source` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `m3` double NOT NULL DEFAULT '0', + `warehouse_id` int(11) NOT NULL, + `hora` int(11) NOT NULL, + `order` int(11) NOT NULL DEFAULT '0', + `alert_level` int(11) NOT NULL DEFAULT '0', + `Agencia` varchar(45) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2833411 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `stock` +-- + +DROP TABLE IF EXISTS `stock`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `stock` ( + `warehouse_id` smallint(5) unsigned NOT NULL, + `item_id` int(10) unsigned NOT NULL, + `amount` int(11) NOT NULL, + UNIQUE KEY `warehouse_id` (`warehouse_id`,`item_id`) USING HASH, + KEY `warehouse_id_2` (`warehouse_id`) USING BTREE +) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `visible` +-- + +DROP TABLE IF EXISTS `visible`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `visible` ( + `calc_id` int(10) unsigned NOT NULL, + `item_id` int(11) NOT NULL, + `visible` int(11) NOT NULL, + UNIQUE KEY `calc_id` (`calc_id`,`item_id`) USING HASH, + KEY `id` (`item_id`) USING BTREE +) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'cache' +-- +/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; +/*!50106 DROP EVENT IF EXISTS `cacheCalc_clean` */; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `cacheCalc_clean` ON SCHEDULE EVERY 30 MINUTE STARTS '2017-01-23 13:15:58' ON COMPLETION NOT PRESERVE ENABLE DO CALL cacheCalc_clean */ ;; +/*!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 `cache_clean` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `cache_clean` ON SCHEDULE EVERY 5 MINUTE STARTS '2019-04-29 13:06:16' ON COMPLETION NOT PRESERVE ENABLE DO CALL cache_clean */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; +DELIMITER ; +/*!50106 SET TIME_ZONE= @save_time_zone */ ; + +-- +-- Dumping routines for database 'cache' +-- +/*!50003 DROP PROCEDURE IF EXISTS `available_clean` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `available_clean`() +BEGIN + DROP TEMPORARY TABLE IF EXISTS tCalc; + CREATE TEMPORARY TABLE tCalc + (INDEX (id)) + ENGINE = MEMORY + SELECT id FROM cache_calc; + + DELETE a + FROM available a + LEFT JOIN tCalc c ON c.id = a.calc_id + WHERE c.id IS NULL; + + DROP TEMPORARY TABLE tCalc; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `available_refresh` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `available_refresh`(OUT `vCalc` INT, IN `vRefresh` INT, IN `vWarehouse` INT, IN `vDate` DATE) +proc: BEGIN + DECLARE vStartDate DATE; + DECLARE vEndDate DATETIME; + DECLARE vReserveDate DATETIME; + DECLARE vParams CHAR(100); + DECLARE vInventoryDate DATE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + CALL cache_calc_unlock (vCalc); + RESIGNAL; + END; + + IF vDate < CURDATE() THEN + LEAVE proc; + END IF; + + CALL vn.itemStock (vWarehouse, vDate, NULL); + + SET vParams = CONCAT_WS('/', vWarehouse, vDate); + CALL cache_calc_start (vCalc, vRefresh, 'available', vParams); + + IF !vRefresh THEN + LEAVE proc; + END IF; + + -- Calcula algunos parámetros necesarios + + SET vStartDate = TIMESTAMP(vDate, '00:00:00'); + SET vEndDate = TIMESTAMP(TIMESTAMPADD(DAY, 4, vDate), '23:59:59'); + + SELECT inventoried INTO vInventoryDate FROM vn.config; + + SELECT SUBTIME(NOW(), reserveTime) INTO vReserveDate + FROM hedera.orderConfig; + + -- Calcula el ultimo dia de vida para cada producto + + DROP TEMPORARY TABLE IF EXISTS item_range; + CREATE TEMPORARY TABLE item_range + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT c.item_id, IF(it.life IS NULL, NULL, + TIMESTAMP(TIMESTAMPADD(DAY, it.life, c.landing), '23:59:59')) AS date_end + FROM ( + SELECT b.itemFk item_id, MAX(t.landed) landing + FROM vn.buy b + JOIN vn.entry e ON b.entryFk = e.id + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vInventoryDate AND vStartDate + AND t.warehouseInFk = vWarehouse + AND NOT e.isInventory + /*AND NOT e.isRaid*/ -- JGF cau-13144 2019-10-14 + GROUP BY b.itemFk + ) c + JOIN vn.item i ON i.id = c.item_id + JOIN vn.itemType it ON it.id = i.typeFk + HAVING date_end >= vStartDate OR date_end IS NULL; + + -- Replica la tabla item_range para poder usarla varias veces en la misma consulta + + DROP TEMPORARY TABLE IF EXISTS item_range_copy1; + CREATE TEMPORARY TABLE item_range_copy1 LIKE item_range; + INSERT INTO item_range_copy1 + SELECT * FROM item_range; + + DROP TEMPORARY TABLE IF EXISTS item_range_copy2; + CREATE TEMPORARY TABLE item_range_copy2 LIKE item_range; + INSERT INTO item_range_copy2 + SELECT * FROM item_range; + + DROP TEMPORARY TABLE IF EXISTS item_range_copy3; + CREATE TEMPORARY TABLE item_range_copy3 LIKE item_range; + INSERT INTO item_range_copy3 + SELECT * FROM item_range; + + DROP TEMPORARY TABLE IF EXISTS item_range_copy4; + CREATE TEMPORARY TABLE item_range_copy4 LIKE item_range; + INSERT INTO item_range_copy4 + SELECT * FROM item_range; + + -- Calcula el ATP + + DELETE FROM available WHERE calc_id = vCalc; + + INSERT INTO available (calc_id, item_id, available) + SELECT vCalc, t.item_id, SUM(stock) amount FROM ( + SELECT il.itemFk AS item_id, stock + FROM tmp.itemList il + JOIN item_range ir ON ir.item_id = il.itemFk + UNION ALL + SELECT t.item_id, minacum(dt, amount, vDate) AS available FROM ( + SELECT itemFk AS item_id, DATE(dat) dt, SUM(quantity) amount FROM ( + SELECT i.itemFk, i.shipped AS dat, i.quantity + FROM vn.itemTicketOut i + JOIN item_range_copy1 ir ON ir.item_id = i.itemFk + WHERE i.shipped >= vStartDate + AND (ir.date_end IS NULL OR i.shipped <= ir.date_end) + AND i.warehouseFk = vWarehouse + UNION ALL + SELECT i.itemFk, i.landed AS dat, i.quantity + FROM vn.itemEntryIn i + JOIN item_range_copy2 ir ON ir.item_id = i.itemFk + WHERE i.landed >= vStartDate + AND (ir.date_end IS NULL OR i.landed <= ir.date_end) + AND i.warehouseInFk = vWarehouse + UNION ALL + SELECT i.itemFk, i.shipped AS dat, i.quantity + FROM vn.itemEntryOut i + JOIN item_range_copy3 ir ON ir.item_id = i.itemFk + WHERE i.shipped >= vStartDate + AND (ir.date_end IS NULL OR i.shipped <= ir.date_end) + AND i.warehouseOutFk = vWarehouse + UNION ALL + SELECT r.item_id, r.shipment, -r.amount + FROM hedera.order_row r + JOIN hedera.`order` o ON o.id = r.order_id + JOIN item_range_copy4 ir ON ir.item_id = r.item_id + WHERE r.shipment >= vStartDate + AND (ir.date_end IS NULL OR r.shipment <= ir.date_end) + AND r.warehouse_id = vWarehouse + AND r.created >= vReserveDate + AND NOT o.confirmed + ) t + GROUP BY item_id, dt + ) t + GROUP BY t.item_id + ) t GROUP BY t.item_id; + + DROP TEMPORARY TABLE IF EXISTS + tmp.itemList + ,item_range + ,item_range_copy1 + ,item_range_copy2 + ,item_range_copy3 + ,item_range_copy4; + + CALL cache_calc_end (vCalc); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `available_refresh__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `available_refresh__`(OUT `vCalc` INT, IN `vRefresh` INT, IN `vWarehouse` INT, IN `vDate` DATE) +proc: BEGIN +-- bernat working in this file + DECLARE vStartDate DATE; + DECLARE vEndDate DATETIME; + DECLARE vReserveDate DATETIME; + DECLARE vParams CHAR(100); + DECLARE vInventoryDate DATE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + CALL cache_calc_unlock (vCalc); + RESIGNAL; + END; + + IF vDate < CURDATE() THEN + LEAVE proc; + END IF; + + CALL vn2008.item_stock (vWarehouse, vDate, NULL); + + SET vParams = CONCAT_WS('/', vWarehouse, vDate); + CALL cache_calc_start (vCalc, vRefresh, 'available', vParams); + + IF !vRefresh THEN + LEAVE proc; + END IF; + + -- Calcula algunos parámetros necesarios + + SET vStartDate = TIMESTAMP(vDate, '00:00:00'); + SET vEndDate = TIMESTAMP(TIMESTAMPADD(DAY, 4, vDate), '23:59:59'); + + SELECT FechaInventario INTO vInventoryDate FROM vn2008.tblContadores; + + SELECT SUBTIME(NOW(), reserveTime) INTO vReserveDate + FROM hedera.orderConfig; + + -- Calcula el ultimo dia de vida para cada producto + + DROP TEMPORARY TABLE IF EXISTS item_range; + CREATE TEMPORARY TABLE item_range + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT c.item_id, IF(t.life IS NULL, NULL, + TIMESTAMP(TIMESTAMPADD(DAY, t.life, c.landing), '23:59:59')) AS date_end + FROM ( + SELECT c.Id_Article item_id, MAX(landing) landing + FROM vn2008.Compres c + JOIN vn2008.Entradas e ON c.Id_Entrada = e.Id_Entrada + JOIN vn2008.travel t ON t.id = e.travel_id + JOIN vn2008.warehouse w ON w.id = t.warehouse_id + WHERE t.landing BETWEEN vInventoryDate AND vStartDate + AND t.warehouse_id = vWarehouse + AND NOT e.Inventario + /*AND NOT e.Redada*/ -- JGF cau-13144 2019-10-14 + GROUP BY Id_Article + ) c + JOIN vn2008.Articles a ON a.Id_Article = c.item_id + JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id + HAVING date_end >= vStartDate OR date_end IS NULL; + + -- Replica la tabla item_range para poder usarla varias veces en la misma consulta + + DROP TEMPORARY TABLE IF EXISTS item_range_copy1; + CREATE TEMPORARY TABLE item_range_copy1 LIKE item_range; + INSERT INTO item_range_copy1 + SELECT * FROM item_range; + + DROP TEMPORARY TABLE IF EXISTS item_range_copy2; + CREATE TEMPORARY TABLE item_range_copy2 LIKE item_range; + INSERT INTO item_range_copy2 + SELECT * FROM item_range; + + DROP TEMPORARY TABLE IF EXISTS item_range_copy3; + CREATE TEMPORARY TABLE item_range_copy3 LIKE item_range; + INSERT INTO item_range_copy3 + SELECT * FROM item_range; + + DROP TEMPORARY TABLE IF EXISTS item_range_copy4; + CREATE TEMPORARY TABLE item_range_copy4 LIKE item_range; + INSERT INTO item_range_copy4 + SELECT * FROM item_range; + + -- Calcula el ATP + + DELETE FROM available WHERE calc_id = vCalc; + + INSERT INTO available (calc_id, item_id, available) + SELECT vCalc, t.item_id, SUM(stock) amount FROM ( + SELECT ti.item_id, stock + FROM vn2008.tmp_item ti + JOIN item_range ir ON ir.item_id = ti.item_id + UNION ALL + SELECT t.item_id, minacum(dt, amount, vDate) AS available FROM ( + SELECT item_id, DATE(dat) dt, SUM(amount) amount FROM ( + SELECT i.item_id, i.dat, i.amount + FROM vn2008.item_out i + JOIN item_range_copy1 ir ON ir.item_id = i.item_id + WHERE i.dat >= vStartDate + AND (ir.date_end IS NULL OR i.dat <= ir.date_end) + AND i.warehouse_id = vWarehouse + UNION ALL + SELECT i.item_id, i.dat, i.amount + FROM vn2008.item_entry_in i + JOIN item_range_copy2 ir ON ir.item_id = i.item_id + WHERE i.dat >= vStartDate + AND (ir.date_end IS NULL OR i.dat <= ir.date_end) + AND i.warehouse_id = vWarehouse + UNION ALL + SELECT i.item_id, i.dat, i.amount + FROM vn2008.item_entry_out i + JOIN item_range_copy3 ir ON ir.item_id = i.item_id + WHERE i.dat >= vStartDate + AND (ir.date_end IS NULL OR i.dat <= ir.date_end) + AND i.warehouse_id = vWarehouse + UNION ALL + SELECT r.item_id, r.shipment, -r.amount + FROM hedera.order_row r + JOIN hedera.`order` o ON o.id = r.order_id + JOIN item_range_copy4 ir ON ir.item_id = r.item_id + WHERE r.shipment >= vStartDate + AND (ir.date_end IS NULL OR r.shipment <= ir.date_end) + AND r.warehouse_id = vWarehouse + AND r.created >= vReserveDate + AND NOT o.confirmed + ) t + GROUP BY item_id, dt + ) t + GROUP BY t.item_id + ) t GROUP BY t.item_id; + + DROP TEMPORARY TABLE + vn2008.tmp_item + ,item_range + ,item_range_copy1 + ,item_range_copy2 + ,item_range_copy3 + ,item_range_copy4; + + CALL cache_calc_end (vCalc); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `cacheCalc_clean` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `cacheCalc_clean`() +BEGIN + DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); + DELETE FROM cache_calc WHERE expires < vCleanTime; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `cache_calc_end` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_end`(IN `v_calc` INT) +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = ADDTIME(NOW(), c.lifetime), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `cache_calc_start` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires + INTO v_cache_id, v_calc, v_expires + FROM cache c + LEFT JOIN cache_calc ca + ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' + WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; + + -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. + + IF !v_refresh AND NOW() < v_expires + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `cache_calc_unlock` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_unlock`(IN `v_calc` INT) +proc: BEGIN + DECLARE v_cache_name VARCHAR(50); + DECLARE v_params VARCHAR(100); + + IF v_calc IS NULL THEN + LEAVE proc; + END IF; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + DELETE FROM cache_calc WHERE id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `cache_clean` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `cache_clean`() + NO SQL +BEGIN + CALL available_clean; + CALL visible_clean; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clean` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clean`() +BEGIN + + DECLARE vDateShort DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); + + DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `departure_timing` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `departure_timing`(vWarehouseId INT) +BEGIN + +DECLARE done BOOL DEFAULT FALSE; +DECLARE rsDeparture INT; +DECLARE rsHoras DECIMAL(5,2); +DECLARE rsInicio DECIMAL(5,2); +DECLARE resto DECIMAL(5,2); +DECLARE horasProd DECIMAL(5,2); +DECLARE inicioProd DECIMAL(5,2) DEFAULT 24.00; +DECLARE myTime DECIMAL(5,2); +DECLARE departureLimit INT; +DECLARE myMinSpeed DECIMAL(10,2); +DECLARE vLoadingDelay DECIMAL(5) DEFAULT 2; + +DECLARE rs CURSOR FOR + SELECT Departure + , Sum(pb.m3)/(GREATEST(v.m3,IFNULL(minSpeed,0))/1.3) AS Horas + , curDate()+(Departure + vLoadingDelay -(Sum(pb.m3)/(GREATEST(v.m3,IFNULL(minSpeed,0))/1.3))/24) AS InicioPreparacion + FROM tmp.production_buffer pb + JOIN vn2008.v_encajado_ultima_hora v ON v.warehouse_id = pb.warehouse_id + LEFT JOIN cache.departure_limit dp ON dp.warehouse_id = pb.warehouse_id AND dp.fecha = CURDATE() + WHERE pb.Fecha = CURDATE() + AND alert_level < 2 + AND IFNULL(Departure,0) > 0 + GROUP BY Departure + ORDER BY Departure DESC; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + SET myTime = HOUR(now()) + MINUTE(now()) / 60; + + OPEN rs; + + FETCH rs INTO rsDeparture, rsHoras , rsInicio; + + WHILE NOT done DO + + SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0); + + SET inicioProd = rsDeparture - rsHoras; + + IF inicioProd - resto < myTime THEN + + SET done = TRUE; + + ELSE + + SET departureLimit = rsDeparture; + + FETCH rs INTO rsDeparture, rsHoras , rsInicio; + + -- SELECT rsDeparture, rsHoras , rsInicio; + + END IF; + + END WHILE; + + SET departureLimit = IFNULL(departureLimit,24); + SET departureLimit = IF(departureLimit = 0, 24, departureLimit); + + SELECT minSpeed INTO myMinSpeed + FROM cache.departure_limit + WHERE warehouse_id = vWarehouseId + AND fecha = CURDATE(); + + REPLACE cache.departure_limit(warehouse_id, fecha, hora, minSpeed) + VALUES (vWarehouseId, CURDATE(), IFNULL(departureLimit,24), IFNULL(myMinSpeed,0)); + + CLOSE rs; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `departure_timing_beta` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `departure_timing_beta`(vWarehouseId INT) +BEGIN + +DECLARE done BOOL DEFAULT FALSE; +DECLARE rsDeparture INT; +DECLARE rsHoras DECIMAL(5,2); +DECLARE rsInicio DECIMAL(5,2); +DECLARE resto DECIMAL(5,2); +DECLARE horasProd DECIMAL(5,2); +DECLARE inicioProd DECIMAL(5,2) DEFAULT 24.00; +DECLARE myTime DECIMAL(5,2); +DECLARE departureLimit INT; + +DECLARE rs CURSOR FOR + SELECT Departure + , Sum(pb.m3)/GREATEST(v.m3,IFNULL(minSpeed,0)) AS Horas + , curDate()+(Departure-(Sum(pb.m3)/GREATEST(v.m3,IFNULL(minSpeed,0)))/24) AS InicioPreparacion + FROM tmp.production_buffer pb + JOIN vn2008.v_encajado_ultima_hora v ON v.warehouse_id = pb.warehouse_id + LEFT JOIN cache.departure_limit dp ON dp.warehouse_id = pb.warehouse_id AND dp.fecha = CURDATE() + WHERE pb.Fecha = CURDATE() + AND alert_level < 2 + AND IFNULL(Departure,0) > 0 + GROUP BY Departure + ORDER BY Departure DESC; + +DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + +SET myTime = HOUR(now()) + MINUTE(now()) / 60; + +OPEN rs; + +FETCH rs INTO rsDeparture, rsHoras , rsInicio; + +SELECT rsDeparture, rsHoras , rsInicio, vWarehouseId, done; + +WHILE NOT done DO + + SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0); + + SET inicioProd = rsDeparture - rsHoras; + + SELECT rsDeparture, rsHoras , rsInicio, resto,inicioProd; + + IF inicioProd - resto < myTime THEN + + SET done = TRUE; + + ELSE + + SET departureLimit = rsDeparture; + + FETCH rs INTO rsDeparture, rsHoras , rsInicio; + + END IF; + +END WHILE; + +SELECT rsDeparture, rsHoras , rsInicio, resto,inicioProd; + + +SET departureLimit = IFNULL(departureLimit,24); + +IF departureLimit > 0 THEN + + REPLACE cache.departure_limit(warehouse_id, fecha, hora, minSpeed) + VALUES (vWarehouseId, CURDATE(), departureLimit, myMinSpeed); + +END IF; + +CLOSE rs; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `last_buy_refresh` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `last_buy_refresh`(vRefresh BOOL) +proc: BEGIN +/** + * Crea o actualiza la cache con la última compra y fecha de cada + * artículo hasta ayer. Para obtener la última compra hasta una fecha + * determinada utilizar el procedimiento vn2008.item_last_buy_(). + * + * @param vRefresh %TRUE para forzar el recálculo de la cache + */ + DECLARE vCalc INT; + DECLARE started DATE; + DECLARE ended DATE; + DECLARE vLastRefresh DATE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + CALL cache_calc_unlock (vCalc); + RESIGNAL; + END; + + CALL cache_calc_start (vCalc, vRefresh, 'last_buy', NULL); + + IF !vRefresh + THEN + LEAVE proc; + END IF; + + -- TODO: ¿Se puede usar la fecha del ultimo inventario? + SELECT inventoried INTO started FROM vn.config LIMIT 1; + SET ended = CURDATE(); -- TIMESTAMPADD(DAY, -1, CURDATE()); + + CALL vn.buyUltimateFromInterval(NULL, started, ended); + + DELETE FROM last_buy; + + INSERT INTO last_buy (item_id, warehouse_id, buy_id, landing) + SELECT itemFk, warehouseFk, buyFk, landed + FROM tmp.buyUltimateFromInterval; + + DROP TEMPORARY TABLE tmp.buyUltimateFromInterval; + + CALL cache_calc_end (vCalc); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `last_buy_refresh__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `last_buy_refresh__`(vRefresh BOOL) +proc: BEGIN +/** + * BERNAT: WORKING IN THIS FILE + * Crea o actualiza la cache con la última compra y fecha de cada + * artículo hasta ayer. Para obtener la última compra hasta una fecha + * determinada utilizar el procedimiento vn2008.item_last_buy_(). + * + * @param vRefresh %TRUE para forzar el recálculo de la cache + **/ + DECLARE vCalc INT; + DECLARE started DATE; + DECLARE ended DATE; + DECLARE vLastRefresh DATE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + CALL cache_calc_unlock (vCalc); + RESIGNAL; + END; + + CALL cache_calc_start (vCalc, vRefresh, 'last_buy', NULL); + + IF !vRefresh + THEN + LEAVE proc; + END IF; + + -- TODO: ¿Se puede usar la fecha del ultimo inventario? + SET started = vn2008.date_inv();-- TIMESTAMPADD(DAY, -90, CURDATE()); + SET ended = CURDATE(); -- TIMESTAMPADD(DAY, -1, CURDATE()); + + CALL vn.buyUltimateFromInterval(NULL, started, ended); + + DELETE FROM last_buy; + + INSERT INTO last_buy (item_id, warehouse_id, buy_id, landing) + SELECT itemFk, warehouseFk, buyFk, landed + FROM tmp.buyUltimateFromInterval; + + DROP TEMPORARY TABLE tmp.buyUltimateFromInterval; + + CALL cache_calc_end (vCalc); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `prod_graphic_refresh` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `prod_graphic_refresh`(v_refresh BOOL, wh_id INT) +proc: BEGIN + DECLARE datEQ DATETIME; + DECLARE timDIF TIME; + DECLARE v_calc INT; + + CALL cache_calc_start (v_calc, v_refresh, 'prod_graphic', wh_id); + + IF !v_refresh + THEN + LEAVE proc; + END IF; + + CALL vn2008.production_control_source(wh_id, 0); + + DELETE FROM prod_graphic_source; + + INSERT INTO prod_graphic_source (warehouse_id, alert_level, m3, hora, `order`, Agencia) + SELECT + wh_id, + pb.alert_level, + m3, + pb.Hora, + pb.state_order, + pb.Agencia + FROM tmp.production_buffer pb + WHERE Fecha = CURDATE() + ; + + + CALL cache_calc_end (v_calc); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `stock_refresh` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `stock_refresh`(v_refresh BOOL) +proc: BEGIN +/** + * Crea o actualiza la cache con el disponible hasta el día de + * ayer. Esta cache es usada como base para otros procedimientos + * como el cáculo del visible o del ATP. + * + * @param v_refresh %TRUE para forzar el recálculo de la cache + **/ + DECLARE v_calc INT; + DECLARE v_date_inv DATE; + DECLARE v_curdate DATE; + DECLARE v_last_refresh DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + CALL cache_calc_unlock (v_calc); + RESIGNAL; + END; + + CALL cache_calc_start (v_calc, v_refresh, 'stock', NULL); + + IF !v_refresh + THEN + LEAVE proc; + END IF; + + SET v_date_inv = (SELECT inventoried FROM vn.config LIMIT 1); + SET v_curdate = CURDATE(); + + DELETE FROM stock; + + INSERT INTO stock (item_id, warehouse_id, amount) + SELECT item_id, warehouse_id, SUM(amount) amount FROM + ( + SELECT itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount + FROM vn.itemTicketOut + WHERE shipped >= v_date_inv AND shipped < v_curdate + UNION ALL + SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount + FROM vn.itemEntryIn + WHERE landed >= v_date_inv AND landed < v_curdate AND isVirtualStock is FALSE + UNION ALL + SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount + FROM vn.itemEntryOut + WHERE shipped >= v_date_inv AND shipped < v_curdate + ) t + GROUP BY item_id, warehouse_id HAVING amount != 0; + + CALL cache_calc_end (v_calc); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `stock_refresh__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `stock_refresh__`(v_refresh BOOL) +proc: BEGIN +/** + * bernat: WORKING IN THIS FILE + * Crea o actualiza la cache con el disponible hasta el día de + * ayer. Esta cache es usada como base para otros procedimientos + * como el cáculo del visible o del ATP. + * + * @param v_refresh %TRUE para forzar el recálculo de la cache + **/ + DECLARE v_calc INT; + DECLARE v_date_inv DATE; + DECLARE v_curdate DATE; + DECLARE v_last_refresh DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + CALL cache_calc_unlock (v_calc); + RESIGNAL; + END; + + CALL cache_calc_start (v_calc, v_refresh, 'stock', NULL); + + IF !v_refresh + THEN + LEAVE proc; + END IF; + + SET v_date_inv = (SELECT FechaInventario FROM vn2008.tblContadores LIMIT 1); + SET v_curdate = CURDATE(); + + DELETE FROM stock; + + INSERT INTO stock (item_id, warehouse_id, amount) + SELECT item_id, warehouse_id, SUM(amount) amount FROM + ( + SELECT item_id, warehouse_id, amount FROM vn2008.item_out + WHERE dat >= v_date_inv AND dat < v_curdate + UNION ALL + SELECT item_id, warehouse_id, amount FROM vn2008.item_entry_in + WHERE dat >= v_date_inv AND dat < v_curdate AND isVirtualStock is FALSE + UNION ALL + SELECT item_id ,warehouse_id, amount FROM vn2008.item_entry_out + WHERE dat >= v_date_inv AND dat < v_curdate + ) t + GROUP BY item_id, warehouse_id HAVING amount != 0; + + CALL cache_calc_end (v_calc); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `visible_clean` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `visible_clean`() +BEGIN + DROP TEMPORARY TABLE IF EXISTS tCalc; + CREATE TEMPORARY TABLE tCalc + (INDEX (id)) + ENGINE = MEMORY + SELECT id FROM cache_calc; + + DELETE v + FROM visible v + LEFT JOIN tCalc c ON c.id = v.calc_id + WHERE c.id IS NULL; + + DROP TEMPORARY TABLE tCalc; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `visible_refresh` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `visible_refresh`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT) +proc: BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + CALL cache_calc_unlock (v_calc); + RESIGNAL; + END; + + CALL cache_calc_start (v_calc, v_refresh, 'visible', v_warehouse); + + IF !v_refresh THEN + LEAVE proc; + END IF; + + -- Calculamos el stock hasta ayer + + CALL `cache`.stock_refresh(false); + + DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; + CREATE TEMPORARY TABLE vn2008.tmp_item + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT item_id, amount stock, amount visible FROM `cache`.stock + WHERE warehouse_id = v_warehouse; + + -- Calculamos los movimientos confirmados de hoy + + CALL vn.item_GetVisible(v_warehouse, NULL); + + DELETE FROM visible WHERE calc_id = v_calc; + + INSERT INTO visible (calc_id, item_id,visible) + SELECT v_calc, item_id, visible FROM vn2008.tmp_item; + + CALL cache_calc_end (v_calc); + + DROP TEMPORARY TABLE vn2008.tmp_item; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `visible_refresh__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `visible_refresh__`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT) +proc: BEGIN + -- bernat working in this file + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + CALL cache_calc_unlock (v_calc); + RESIGNAL; + END; + + CALL cache_calc_start (v_calc, v_refresh, 'visible', v_warehouse); + + IF !v_refresh THEN + LEAVE proc; + END IF; + + -- Calculamos el stock hasta ayer + + CALL `cache`.stock_refresh(false); + + DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; + CREATE TEMPORARY TABLE vn2008.tmp_item + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT item_id, amount stock, amount visible FROM `cache`.stock + WHERE warehouse_id = v_warehouse; + + -- Calculamos los movimientos confirmados de hoy + + CALL vn2008.item_stock_visible(v_warehouse, NULL); + + DELETE FROM visible WHERE calc_id = v_calc; + + INSERT INTO visible (calc_id, item_id,visible) + SELECT v_calc, item_id, visible FROM vn2008.tmp_item; + + CALL cache_calc_end (v_calc); + + DROP TEMPORARY TABLE vn2008.tmp_item; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Current Database: `edi` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `edi` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; + +USE `edi`; + +-- +-- Table structure for table `PriceDetails` +-- + +DROP TABLE IF EXISTS `PriceDetails`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `PriceDetails` ( + `ID` int(11) NOT NULL, + `SuplyResponseID` int(11) NOT NULL, + `PriceType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `Location` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `Price` decimal(10,2) DEFAULT NULL, + `BasisQuantitiy` int(11) DEFAULT NULL, + `BasisQuantityType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `MinimumQuantity` int(11) DEFAULT NULL, + `MinimumQuantityType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `MaximumQuantity Integer` int(11) DEFAULT NULL, + `MaximumQuantityType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `LatestDeliveryDateTime` datetime DEFAULT NULL, + `EarliestDespatchDateTime` datetime DEFAULT NULL, + `FirstOrderDateTime` datetime DEFAULT NULL, + `LatestOrderDateTime` datetime DEFAULT NULL, + PRIMARY KEY (`ID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `VMPSettings` +-- + +DROP TABLE IF EXISTS `VMPSettings`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `VMPSettings` ( + `VMPID` int(11) NOT NULL, + `MessageID` int(11) NOT NULL, + PRIMARY KEY (`VMPID`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `bucket` +-- + +DROP TABLE IF EXISTS `bucket`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `bucket` ( + `bucket_id` int(11) unsigned NOT NULL, + `bucket_type_id` mediumint(8) unsigned NOT NULL, + `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `x_size` mediumint(8) unsigned NOT NULL, + `y_size` mediumint(8) unsigned NOT NULL, + `z_size` mediumint(8) unsigned NOT NULL, + `entry_date` date DEFAULT NULL, + `expiry_date` date DEFAULT NULL, + `change_date_time` datetime DEFAULT NULL, + PRIMARY KEY (`bucket_id`), + KEY `group_id` (`y_size`), + KEY `plant_id` (`x_size`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/VBN020101/CK090916.txt'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `bucket_type` +-- + +DROP TABLE IF EXISTS `bucket_type`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `bucket_type` ( + `bucket_type_id` mediumint(8) unsigned NOT NULL, + `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `entry_date` date DEFAULT NULL, + `expiry_date` date DEFAULT NULL, + `change_date_time` datetime DEFAULT NULL, + PRIMARY KEY (`bucket_type_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/VBN020101/FB090916.txt'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `deliveryInformation` +-- + +DROP TABLE IF EXISTS `deliveryInformation`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `deliveryInformation` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `DeliveryType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `Location` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `DeliveryPrice` decimal(10,2) DEFAULT NULL, + `ChargeAmount` decimal(10,2) DEFAULT NULL, + `BasisQuantitiy` int(11) DEFAULT NULL, + `MinimumQuantity` int(11) DEFAULT NULL, + `MaximumQuantity Integer` int(11) DEFAULT NULL, + `LatestDeliveryDateTime` datetime DEFAULT NULL, + `EarliestDespatchDateTime` datetime DEFAULT NULL, + `FirstOrderDateTime` datetime DEFAULT NULL, + `LatestOrderDateTime` datetime DEFAULT NULL, + `supplyResponseID` int(11) DEFAULT NULL, + PRIMARY KEY (`ID`), + KEY `fgbSupplyResponse_idx` (`supplyResponseID`), + KEY `fgbSupplyResponse_idx2` (`FirstOrderDateTime`), + KEY `fgbSupplyResponse_idx3` (`LatestOrderDateTime`), + CONSTRAINT `fgbSupplyResponse` FOREIGN KEY (`supplyResponseID`) REFERENCES `supplyResponse` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=25319964 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ekt` +-- + +DROP TABLE IF EXISTS `ekt`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ekt` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `barcode` char(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `entryYear` smallint(5) unsigned NOT NULL, + `deliveryNumber` bigint(20) unsigned DEFAULT NULL, + `fec` date DEFAULT NULL, + `hor` time DEFAULT NULL, + `now` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `ptj` mediumint(8) unsigned DEFAULT NULL, + `ref` int(11) NOT NULL, + `item` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `pac` int(11) DEFAULT '0', + `qty` int(10) NOT NULL, + `ori` varchar(3) COLLATE utf8_unicode_ci DEFAULT 'NL', + `cat` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, + `agj` int(11) DEFAULT NULL, + `kop` int(11) DEFAULT NULL, + `ptd` varchar(6) COLLATE utf8_unicode_ci DEFAULT NULL, + `sub` mediumint(8) unsigned DEFAULT NULL, + `pro` mediumint(8) unsigned NOT NULL, + `pri` double NOT NULL, + `package` int(10) unsigned DEFAULT NULL, + `auction` smallint(5) unsigned DEFAULT NULL, + `klo` smallint(5) unsigned DEFAULT NULL, + `k1` smallint(5) unsigned DEFAULT NULL, + `k2` smallint(5) unsigned DEFAULT NULL, + `k3` tinyint(3) unsigned DEFAULT NULL, + `k4` tinyint(3) unsigned DEFAULT NULL, + `s1` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `s2` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `s3` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `s4` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL, + `s5` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `s6` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `ok` tinyint(4) NOT NULL DEFAULT '0', + `trolleyFk` int(11) DEFAULT NULL, + `putOrderFk` int(10) unsigned DEFAULT NULL, + `scanned` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `barcode_year` (`barcode`,`entryYear`), + UNIQUE KEY `entry_year` (`deliveryNumber`,`entryYear`) USING BTREE, + KEY `ref` (`ref`), + KEY `ptj` (`ptj`), + KEY `pro` (`pro`), + KEY `kop` (`kop`), + KEY `barcode` (`barcode`), + KEY `fec` (`fec`), + KEY `putOrderFk` (`putOrderFk`) +) ENGINE=InnoDB AUTO_INCREMENT=1133448 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `exchange` +-- + +DROP TABLE IF EXISTS `exchange`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `exchange` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `mailFk` int(10) unsigned NOT NULL, + `typeFk` smallint(5) unsigned NOT NULL, + `ektFk` int(10) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `type_id` (`typeFk`,`ektFk`), + KEY `message_id` (`mailFk`), + KEY `buy_edi_id` (`ektFk`), + CONSTRAINT `exchange_ibfk_1` FOREIGN KEY (`mailFk`) REFERENCES `mail` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `exchange_ibfk_2` FOREIGN KEY (`ektFk`) REFERENCES `ekt` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=674008 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `exchangeConfig` +-- + +DROP TABLE IF EXISTS `exchangeConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `exchangeConfig` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `logMail` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Mail where the log information is sent', + `restrictToSenders` tinyint(4) NOT NULL COMMENT 'Whether to process mails only from known senders', + `presaleFk` mediumint(8) unsigned DEFAULT NULL, + `defaultKop` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `presale_id` (`presaleFk`), + CONSTRAINT `exchangeConfig_ibfk_1` FOREIGN KEY (`presaleFk`) REFERENCES `exchangeType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Configuration parameters'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `exchangeType` +-- + +DROP TABLE IF EXISTS `exchangeType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `exchangeType` ( + `id` mediumint(8) unsigned NOT NULL, + `description` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `feature` +-- + +DROP TABLE IF EXISTS `feature`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `feature` ( + `item_id` int(11) unsigned NOT NULL, + `feature_type_id` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `feature_value` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `entry_date` date NOT NULL, + `expiry_date` date NOT NULL, + `change_date_time` datetime NOT NULL, + PRIMARY KEY (`item_id`,`feature_type_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FF130916.txt'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `fileConfig` +-- + +DROP TABLE IF EXISTS `fileConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `fileConfig` ( + `fileName` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `toTable` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `file` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `updated` date DEFAULT NULL, + PRIMARY KEY (`fileName`), + UNIQUE KEY `to_table` (`toTable`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ftpConfig` +-- + +DROP TABLE IF EXISTS `ftpConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ftpConfig` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `host` varchar(255) CHARACTER SET utf8 NOT NULL, + `user` varchar(50) CHARACTER SET utf8 NOT NULL, + `password` varchar(50) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Configuration parameters'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `genus` +-- + +DROP TABLE IF EXISTS `genus`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `genus` ( + `genus_id` mediumint(8) unsigned NOT NULL, + `latin_genus_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `entry_date` date DEFAULT NULL, + `expiry_date` date DEFAULT NULL, + `change_date_time` datetime DEFAULT NULL, + PRIMARY KEY (`genus_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FG130916.txt'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `goodCharacteristic` +-- + +DROP TABLE IF EXISTS `goodCharacteristic`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `goodCharacteristic` ( + `supplyResponse` varchar(26) COLLATE utf8_unicode_ci NOT NULL, + `type` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'edi.type', + `value` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'edi.value', + PRIMARY KEY (`supplyResponse`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `imapConfig` +-- + +DROP TABLE IF EXISTS `imapConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `imapConfig` ( + `id` tinyint(3) unsigned NOT NULL, + `host` varchar(150) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'localhost', + `user` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `pass` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `cleanPeriod` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'How long the old mails are preserved', + `successFolder` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `errorFolder` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='IMAP configuration parameters'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `item` +-- + +DROP TABLE IF EXISTS `item`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `item` ( + `id` int(11) unsigned NOT NULL, + `product_name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `plant_id` mediumint(8) unsigned DEFAULT NULL, + `group_id` int(11) unsigned DEFAULT NULL, + `entry_date` date DEFAULT NULL, + `expiry_date` date DEFAULT NULL, + `change_date_time` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `group_id` (`group_id`), + KEY `plant_id` (`plant_id`), + CONSTRAINT `item_fk1` FOREIGN KEY (`group_id`) REFERENCES `item_group` (`group_code`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FP130916.txt'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `item_feature` +-- + +DROP TABLE IF EXISTS `item_feature`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `item_feature` ( + `item_id` int(11) NOT NULL, + `presentation_order` tinyint(11) unsigned NOT NULL, + `feature` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `regulation_type` tinyint(3) unsigned NOT NULL, + `entry_date` date NOT NULL, + `expiry_date` date DEFAULT NULL, + `change_date_time` datetime NOT NULL, + PRIMARY KEY (`item_id`,`presentation_order`,`entry_date`,`change_date_time`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FY130916.txt'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = '' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `item_feature_bi` BEFORE INSERT ON `item_feature` FOR EACH ROW +BEGIN + IF NEW.expiry_date = '0000-00-00' THEN + SET NEW.expiry_date = NULL; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `item_group` +-- + +DROP TABLE IF EXISTS `item_group`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `item_group` ( + `group_code` int(11) unsigned NOT NULL, + `dutch_group_description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `entry_date` date NOT NULL, + `expiry_date` date NOT NULL, + `change_date_time` datetime NOT NULL, + PRIMARY KEY (`group_code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FO130916.txt'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `item_track` +-- + +DROP TABLE IF EXISTS `item_track`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `item_track` ( + `item_id` int(10) unsigned NOT NULL, + `s1` tinyint(3) NOT NULL DEFAULT '0', + `s2` tinyint(3) NOT NULL DEFAULT '0', + `s3` tinyint(3) NOT NULL DEFAULT '0', + `s4` tinyint(3) NOT NULL DEFAULT '0', + `pac` tinyint(3) NOT NULL DEFAULT '0', + `cat` tinyint(3) NOT NULL DEFAULT '0', + `ori` tinyint(3) NOT NULL DEFAULT '0', + `pro` tinyint(3) NOT NULL DEFAULT '0', + `package` tinyint(3) NOT NULL DEFAULT '0', + `s5` tinyint(3) NOT NULL DEFAULT '0', + `s6` tinyint(3) NOT NULL DEFAULT '0', + `kop` tinyint(3) NOT NULL DEFAULT '0', + `sub` tinyint(3) NOT NULL DEFAULT '0', + PRIMARY KEY (`item_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `mail` +-- + +DROP TABLE IF EXISTS `mail`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mail` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `senderFk` int(10) unsigned DEFAULT NULL, + `sender` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `messageId` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `nExchanges` int(10) unsigned NOT NULL, + `error` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `mail_id` (`messageId`), + KEY `sender_id` (`senderFk`), + CONSTRAINT `mail_ibfk_2` FOREIGN KEY (`senderFk`) REFERENCES `mailSender` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=703783 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `mailSender` +-- + +DROP TABLE IF EXISTS `mailSender`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mailSender` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `mail` varchar(150) COLLATE utf8_unicode_ci NOT NULL, + `kop` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `mail` (`mail`) +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='List of allowed mailers'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `marketPlace` +-- + +DROP TABLE IF EXISTS `marketPlace`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `marketPlace` ( + `id` varchar(13) COLLATE utf8_unicode_ci NOT NULL, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `supplierFk` int(11) NOT NULL DEFAULT '1433', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `param` +-- + +DROP TABLE IF EXISTS `param`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `param` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `name` varchar(5) COLLATE utf8_unicode_ci NOT NULL, + `subname` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, + `position` tinyint(3) unsigned NOT NULL DEFAULT '1', + `type` enum('INTEGER','DOUBLE','STRING','DATE','TIME') COLLATE utf8_unicode_ci NOT NULL, + `required` tinyint(3) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `name` (`name`,`subname`) +) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Parameters to capture of every exchange'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `plant` +-- + +DROP TABLE IF EXISTS `plant`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `plant` ( + `plant_id` mediumint(8) unsigned NOT NULL, + `genus_id` mediumint(8) unsigned NOT NULL, + `specie_id` mediumint(8) unsigned DEFAULT NULL, + `entry_date` date DEFAULT NULL, + `expiry_date` date DEFAULT NULL, + `change_date_time` datetime DEFAULT NULL, + PRIMARY KEY (`plant_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FT130916.txt'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `putOrder` +-- + +DROP TABLE IF EXISTS `putOrder`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `putOrder` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `deliveryInformationID` int(11) DEFAULT NULL, + `supplyResponseID` int(11) DEFAULT NULL, + `orderTradelineItemID` int(11) DEFAULT NULL COMMENT 'ticketFk or EntryFk?', + `OrderTradeLineDateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'fecha de creacion en la tabla', + `quantity` int(11) DEFAULT NULL, + `EndUserPartyID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `EndUserPartyGLN` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL, + `OrderStatus` int(11) DEFAULT '0' COMMENT '1 pending\n2 confirmed\n3 canceled', + `isOrderProcessed` tinyint(4) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `orderTradelineItemID_UNIQUE` (`orderTradelineItemID`) +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `edi`.`putOrder_BEFORE_INSERT` BEFORE INSERT ON `putOrder` FOR EACH ROW +BEGIN + + DECLARE nextID INT; + + SELECT 1 + MAX(id) INTO nextID FROM putOrder ; + + SET NEW.orderTradelineItemID = nextID; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `specie` +-- + +DROP TABLE IF EXISTS `specie`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `specie` ( + `specie_id` mediumint(8) unsigned NOT NULL, + `genus_id` mediumint(8) unsigned NOT NULL, + `latin_species_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `entry_date` date DEFAULT NULL, + `expiry_date` date DEFAULT NULL, + `change_date_time` datetime DEFAULT NULL, + PRIMARY KEY (`specie_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FS130916.txt'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `supplier` +-- + +DROP TABLE IF EXISTS `supplier`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `supplier` ( + `supplier_id` int(10) unsigned NOT NULL COMMENT 'FHRegistrationNr', + `glnAddressCode` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL, + `company_name` varchar(70) COLLATE utf8_unicode_ci NOT NULL, + `entry_date` date NOT NULL, + `expiry_date` date NOT NULL, + `change_date_time` datetime NOT NULL, + PRIMARY KEY (`supplier_id`), + KEY `glnaddressCodeidx` (`glnAddressCode`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/FEC010104/CC090916.txt'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `supplyResponse` +-- + +DROP TABLE IF EXISTS `supplyResponse`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `supplyResponse` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `NumberBunchesPerCask` int(11) DEFAULT NULL, + `SupplierGLN` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `NewItem` tinyint(1) DEFAULT NULL, + `SendererID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `ItemSupplierID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `TransactionDate` datetime DEFAULT NULL, + `TransactionNumber` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `AuctionClockNumber` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `SupplierID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `ItemDatesupplyResponsecol` datetime DEFAULT NULL, + `Item_ArticleCode` int(11) DEFAULT NULL, + `VBNOmschrijving` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `ExtraRemark` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `ArtCodeType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `VBNGroupCode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `VBNGroupDescription` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `TransactionTime` time DEFAULT NULL, + `CountryOfOrigin` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `NumberOfItemsPerCask` int(11) DEFAULT NULL, + `NumberOfLayersPerTrolley` int(11) DEFAULT NULL, + `NumberOfUnits` int(11) DEFAULT NULL, + `MinimumNumberToOrder` int(11) DEFAULT NULL, + `MinimumOrderUnitType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `Price` decimal(10,2) DEFAULT NULL, + `Quality` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `s1` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `s2` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `s3` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `s4` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `s5` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `s6` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `ExaminiationCode1` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `ExaminiationCode2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `OrderUnitType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `EmbalageCode` int(11) DEFAULT NULL, + `PictureReference` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `AgentGLN` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `MaximumNumberToOrder` int(11) DEFAULT NULL, + `MaximumOrderType` tinyint(1) DEFAULT NULL COMMENT 'Unit: 1 = piece, 2 = bunch, 3 = box, 4 = layer, 5 = load carrier/trolley', + `IncrementalOrderableQuantity` int(11) DEFAULT NULL, + `IncrementalOrderableQuantityType` tinyint(1) DEFAULT NULL COMMENT 'Unit: 1 = piece, 2 = bunch, 3 = box, 4 = layer, 5 = load carrier/trolley', + `PackingPrice` decimal(10,2) DEFAULT NULL, + `PackingPriceType` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL, + `PackingPriceQuantity` int(11) DEFAULT NULL, + `PackingPriceQuantityType` tinyint(1) DEFAULT NULL COMMENT 'Unit: 1 = piece, 2 = bunch, 3 = box, 4 = layer, 5 = load carrier/trolley', + `MarketPlaceID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `MarketFormCode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '"002" Standard Sales\n"005" Catalogue (optional)\n"001" Committed (optional)\n"003" Buffer (optional, Clock Pre Sales) ', + PRIMARY KEY (`ID`), + UNIQUE KEY `ID_UNIQUE` (`ID`), + KEY `IX_TransNumber` (`TransactionNumber`) COMMENT 'Agregado por Ernesto 11.6.2019\nSe ejecutaba 1 consulta por segundo desde MAIL y consumia un 20% de CPU de todo el servidor !!!!!\nCPU usada es mas estable que Indice en SendererID, cpu vs espacio que ocupa?\n' +) ENGINE=InnoDB AUTO_INCREMENT=9313265 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `type` +-- + +DROP TABLE IF EXISTS `type`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `type` ( + `type_id` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `type_group_id` tinyint(3) unsigned NOT NULL, + `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `entry_date` date NOT NULL, + `expiry_date` date NOT NULL, + `change_date_time` datetime NOT NULL, + PRIMARY KEY (`type_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FE130916.txt'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `value` +-- + +DROP TABLE IF EXISTS `value`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `value` ( + `type_id` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `type_value` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `type_description` varchar(70) COLLATE utf8_unicode_ci NOT NULL, + `entry_date` date NOT NULL, + `expiry_date` date NOT NULL, + `change_date_time` datetime NOT NULL, + PRIMARY KEY (`type_id`,`type_value`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FV130916.txt'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'edi' +-- + +-- +-- Dumping routines for database 'edi' +-- +/*!50003 DROP FUNCTION IF EXISTS `floramondoTodayEntryGet` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `floramondoTodayEntryGet`() RETURNS int(11) + READS SQL DATA +BEGIN + + DECLARE myTravel INT; + DECLARE myEntry INT; + + SET myTravel = FloramondoTodayTravelGet(); + + SELECT IFNULL(MAX(id),0) INTO myEntry + FROM vn.entry + WHERE travelFk = myTravel; + + IF NOT myEntry THEN + + INSERT INTO vn.entry(travelFk, supplierFk, commission, companyFk, currencyFk) + SELECT myTravel, s.id, 4, c.id, cu.id + FROM vn.supplier s + JOIN vn.company c ON c.code = 'VNL' + JOIN vn.currency cu ON cu.code = 'EUR' + WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN'; + + SELECT IFNULL(MAX(id),0) INTO myEntry + FROM vn.entry + WHERE travelFk = myTravel; + + END IF; + + RETURN myEntry; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `floramondoTodayTravelGet` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `floramondoTodayTravelGet`() RETURNS int(11) + READS SQL DATA +BEGIN + + DECLARE myTravel INT; + + SELECT IFNULL(MAX(tr.id),0) INTO myTravel + FROM vn.travel tr + JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk + JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk + WHERE wIn.name = 'VNH' + AND wOut.name = 'Floramondo' + AND landed = CURDATE(); + + IF NOT myTravel THEN + + INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyFk) + SELECT CURDATE(), util.yesterday(), wIn.id, wOut.id, am.id + FROM vn.warehouse wIn + JOIN vn.warehouse wOut ON wOut.name = 'Floramondo' + JOIN vn.agencyMode am ON am.name = 'HOLANDA DIRECTO' + WHERE wIn.name = 'VNH'; + + SELECT MAX(tr.id) INTO myTravel + FROM vn.travel tr + JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk + JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk + WHERE wIn.name = 'VNH' + AND wOut.name = 'Floramondo' + AND landed = CURDATE(); + + END IF; + + RETURN myTravel; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clean` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clean`() +BEGIN + + DELETE di.* + FROM edi.deliveryInformation di + -- LEFT JOIN vn.buy b ON b.deliveryFk = di.ID + WHERE LatestOrderDateTime < CURDATE() + -- AND b.id IS NULL + ; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ekt_load` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ekt_load`(IN `vSelf` INT) +BEGIN + DECLARE vRef INT; + DECLARE vBuy INT; + DECLARE vItem INT; + DECLARE vQty INT; + DECLARE vPackage INT; + DECLARE vIsLot BOOLEAN; + DECLARE vForceToPacking INT DEFAULT 2; + + -- Carga los datos necesarios del EKT + + SELECT ref, qty, package INTO vRef, vQty, vPackage + FROM ekt e + LEFT JOIN item i ON e.ref = i.id + WHERE e.id = vSelf; + + -- Inserta el cubo si no existe + + IF vPackage = 800 + THEN + SET vPackage = 800 + vQty; + + INSERT IGNORE INTO vn2008.Cubos SET + Id_Cubo = vPackage, + x = 7200 / vQty, + y = 1; + ELSE + INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) + SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) + FROM bucket WHERE bucket_id = vPackage; + + IF ROW_COUNT() > 0 + THEN + INSERT INTO vn2008.mail SET + `subject` = 'Cubo añadido', + `text` = CONCAT('Se ha añadido el cubo: ', vPackage), + `to` = 'ekt@verdnatura.es'; + END IF; + END IF; + + -- Intenta obtener el artículo en base a los atributos holandeses + + INSERT IGNORE INTO item_track SET + item_id = vRef; + + SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem + FROM vn2008.buy_edi e + JOIN item_track t ON t.item_id = e.ref + LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref + LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id + JOIN vn2008.config cfg + WHERE e.id = vSelf + AND l.id != vSelf + AND c.Id_Article != cfg.generic_item + AND IF(t.s1, l.s1 = e.s1, TRUE) + AND IF(t.s2, l.s2 = e.s2, TRUE) + AND IF(t.s3, l.s3 = e.s3, TRUE) + AND IF(t.s4, l.s4 = e.s4, TRUE) + AND IF(t.s5, l.s5 = e.s5, TRUE) + AND IF(t.s6, l.s6 = e.s6, TRUE) + AND IF(t.kop, l.kop = e.kop, TRUE) + AND IF(t.pac, l.pac = e.pac, TRUE) + AND IF(t.cat, l.cat = e.cat, TRUE) + AND IF(t.ori, l.ori = e.ori, TRUE) + AND IF(t.pro, l.pro = e.pro, TRUE) + AND IF(t.sub, l.sub = e.sub, TRUE) + AND IF(t.package, l.package = e.package, TRUE) + AND c.Id_Article < 170000 + ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; + + -- Determina si el articulo se vende por lotes + + IF vItem + THEN + SELECT COUNT(*) > 0 INTO vIsLot + FROM vn2008.Articles a + LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id + WHERE a.Id_Article = vItem + AND t.`transaction`; + + -- Si el articulo se vende por lotes se inserta un nuevo artículo + + IF vIsLot + THEN + INSERT INTO vn2008.Articles ( + Article + ,Medida + ,Categoria + ,Id_Origen + ,iva_group_id + ,Foto + ,Color + ,Codintrastat + ,tipo_id + ,Tallos + ) + SELECT + i.`name` + ,IFNULL(e.s1, e.pac) + ,e.cat + ,IFNULL(o.id, 17) + ,IFNULL(a.iva_group_id, 1) + ,a.Foto + ,a.Color + ,a.Codintrastat + ,IFNULL(a.tipo_id, 10) + ,IF(a.tipo_id = 15, 0, 1) + FROM vn2008.buy_edi e + LEFT JOIN item i ON i.id = e.ref + LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori + LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem + WHERE e.id = vSelf; + + SET vItem = LAST_INSERT_ID(); + END IF; + END IF; + + -- Inserta la compra asociada al EKT + + INSERT INTO vn2008.Compres + ( + Id_Entrada + ,buy_edi_id + ,Costefijo + ,Id_Article + ,`grouping` + ,caja + ,Packing + ,Cantidad + ,Productor + ,Etiquetas + ,Id_Cubo + ) + SELECT + cfg.edi_entry + ,vSelf + ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri + ,IFNULL(vItem, cfg.generic_item) + ,IFNULL(c.`grouping`, e.pac) + ,vForceToPacking + ,@pac := e.pac / @t + ,@pac * e.qty + ,s.company_name + ,e.qty + ,IFNULL(c.Id_Cubo, e.package) + FROM vn2008.buy_edi e + LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy + LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article + LEFT JOIN supplier s ON e.pro = s.supplier_id + JOIN vn2008.config cfg + WHERE e.id = vSelf + LIMIT 1; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `exchange_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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `exchange_new`( + IN `vMailFk` INT, + IN `vItem` VARCHAR(255), + IN `vType` MEDIUMINT, + IN `vDeliveryNumber` BIGINT, + IN `vDate` DATE, + IN `vHour` TIME, + IN `vRef` INT, + IN `vAgj` INT, + IN `vCat` VARCHAR(2), + IN `vPac` INT, + IN `vSub` MEDIUMINT, + IN `vKop` INT, + IN `vPtd` VARCHAR(6), + IN `vPro` MEDIUMINT, + IN `vOrigin` VARCHAR(3), + IN `vPtj` MEDIUMINT, + IN `vQuantiy` INT, + IN `vPrice` DOUBLE, + IN `vClock` SMALLINT, + IN `vS1` VARCHAR(3), + IN `vS2` VARCHAR(3), + IN `vS3` VARCHAR(3), + IN `vS4` VARCHAR(4), + IN `vS5` VARCHAR(3), + IN `vS6` VARCHAR(3), + IN `vK1` SMALLINT, + IN `vK2` SMALLINT, + IN `vP1` TINYINT, + IN `vP2` TINYINT, + IN `vAuction` SMALLINT, + IN `vPackage` INT, + IN `vPutOrderFk` INT) +BEGIN +/** + * Adds a new exchange, generates it's barcode and + * inserts/updates the transaction. When the referenced + * transaction exists as provisional, updates it with + * the new values. + */ + DECLARE vEkt INT; + DECLARE vRewriteKop INT DEFAULT NULL; + DECLARE vBarcode CHAR(15) DEFAULT NULL; + DECLARE vIsDuplicated BOOL; + DECLARE vUpdateExistent BOOL DEFAULT FALSE; + DECLARE duplicateKey CONDITION FOR 1062; + + DECLARE CONTINUE HANDLER FOR duplicateKey + SET vIsDuplicated = TRUE; + + -- Generates the barcode + + IF vAgj != 0 AND vAgj IS NOT NULL + THEN + SET vBarcode = CONCAT( + LPAD(vAuction, 2, 0), + LPAD(IFNULL(vClock, 99), 2, 0), + LPAD(DAYOFYEAR(vDate), 3, 0), + IF(vClock IS NULL OR vClock = 99, + LPAD(vAgj, 7, 0), + CONCAT(LPAD(vAgj, 5, 0), '01') + ), + '0' + ); + END IF; + + -- Rewrites the kop parameter + + IF vKop IS NULL THEN + SELECT defaultKop INTO vKop FROM exchangeConfig; + END IF; + + SELECT e.kop INTO vRewriteKop + FROM mailSender e + JOIN mail m ON m.senderFk = e.id + WHERE m.id = vMailFk; + + SET vKop = IFNULL(vRewriteKop, vKop); + + -- Inserts the new transaction + + SET vIsDuplicated = FALSE; + INSERT INTO ekt SET + barcode = IFNULL(vBarcode, barcode) + ,deliveryNumber = vDeliveryNumber + ,entryYear = YEAR(vDate) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk; + + -- If it exists duplicado updates it + + IF NOT vIsDuplicated + THEN + SET vEkt = LAST_INSERT_ID(); + CALL ekt_load (vEkt); + + ELSEIF vDeliveryNumber != 0 + AND vDeliveryNumber IS NOT NULL + THEN + SELECT id INTO vEkt + FROM ekt + WHERE deliveryNumber = vDeliveryNumber; + + SELECT COUNT(*) = 0 INTO vUpdateExistent + FROM ekt t + JOIN `exchange` b ON b.ektFk = t.id + JOIN exchangeConfig c + WHERE t.deliveryNumber = vDeliveryNumber + AND t.entryYear = YEAR(vDate) + AND b.typeFk != c.presaleFk; + END IF; + + IF vUpdateExistent + THEN + UPDATE ekt SET + barcode = IFNULL(vBarcode, barcode) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk + WHERE id = vEkt; + END IF; + + -- Registers the exchange + + INSERT INTO `exchange` SET + mailFk = vMailFk + ,typeFk = vType + ,ektFk = vEkt; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `mail_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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `mail_new`( + vMessageId VARCHAR(100) + ,vSender VARCHAR(150) + ,OUT vSelf INT +) +BEGIN +/** + * Registers a mail message. + * + * @param vMessageId Message-ID of email + * @param vSender Id of mail sender + * @param vSelf The created message id + */ + DECLARE vSenderId INT; + DECLARE vIsDuplicated BOOL; + DECLARE duplicateKey CONDITION FOR 1062; + + DECLARE CONTINUE HANDLER FOR duplicateKey + SET vIsDuplicated = TRUE; + + SELECT id INTO vSenderId + FROM mailSender + WHERE mail = vSender; + + SET vIsDuplicated = FALSE; + INSERT INTO mail SET + sender = vSender, + senderFk = vSenderId, + messageId = vMessageId; + + IF vIsDuplicated THEN + SELECT id INTO vSelf + FROM mail + WHERE messageId = vMessageId; + ELSE + SET vSelf = LAST_INSERT_ID(); + 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 */ ; + +-- +-- Current Database: `hedera` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `hedera` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; + +USE `hedera`; + +-- +-- Table structure for table `androidUser` +-- + +DROP TABLE IF EXISTS `androidUser`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `androidUser` ( + `androidId` varchar(200) CHARACTER SET utf8 NOT NULL, + `userFk` int(10) unsigned NOT NULL, + PRIMARY KEY (`userFk`,`androidId`), + CONSTRAINT `androidUser_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `basketOrder` +-- + +DROP TABLE IF EXISTS `basketOrder`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `basketOrder` ( + `clientFk` int(11) NOT NULL, + `orderFk` int(10) unsigned NOT NULL, + PRIMARY KEY (`orderFk`,`clientFk`), + UNIQUE KEY `customer_id` (`clientFk`), + CONSTRAINT `basketOrder_ibfk_1` FOREIGN KEY (`orderFk`, `clientFk`) REFERENCES `order` (`id`, `customer_id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `basketOrder_ibfk_2` FOREIGN KEY (`orderFk`) REFERENCES `order` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `basketOrder_ibfk_3` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `browser` +-- + +DROP TABLE IF EXISTS `browser`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `browser` ( + `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Browser name in browscap', + `version` float NOT NULL COMMENT 'Minimal version', + UNIQUE KEY `name` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='List of compatible web browsers and its version'; +/*!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 */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `config` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `defaultLang` char(2) CHARACTER SET utf8 NOT NULL COMMENT 'The default language if none is specified', + `https` tinyint(3) unsigned NOT NULL COMMENT 'Wether to force de use of HTTPS', + `cookieLife` smallint(5) unsigned NOT NULL COMMENT 'The cookies life, in days', + `jwtKey` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The key used to encode/decode JWT tokens', + `defaultForm` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Form loaded at web login', + `restUri` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The URI for rest service', + `testRestUri` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The URI for test rest service', + `guestUser` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Guest user name', + `testDomain` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The address for beta website', + `productionDomain` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The address for production website', + `pdfsDir` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Directory where PDFs are allocated', + `dmsDir` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Directory where documents are allocated', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration parameters'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `contact` +-- + +DROP TABLE IF EXISTS `contact`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `contact` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `recipient` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `image` +-- + +DROP TABLE IF EXISTS `image`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `image` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `collectionFk` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `updated` int(11) DEFAULT NULL, + `nRefs` int(10) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `collection` (`collectionFk`,`name`), + CONSTRAINT `image_ibfk_1` FOREIGN KEY (`collectionFk`) REFERENCES `imageCollection` (`name`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=176813 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `imageCollection` +-- + +DROP TABLE IF EXISTS `imageCollection`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `imageCollection` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `desc` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `maxWidth` int(10) unsigned NOT NULL, + `maxHeight` int(10) unsigned NOT NULL, + `model` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `property` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `schema` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Deprecated', + `table` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Deprecated', + `column` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Deprecated', + PRIMARY KEY (`id`), + UNIQUE KEY `name` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `imageCollectionSize` +-- + +DROP TABLE IF EXISTS `imageCollectionSize`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `imageCollectionSize` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `collectionFk` int(10) unsigned NOT NULL, + `width` int(10) unsigned NOT NULL, + `height` int(10) unsigned NOT NULL, + `crop` tinyint(3) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `image_schema_id` (`collectionFk`), + CONSTRAINT `imageCollectionSize_ibfk_1` FOREIGN KEY (`collectionFk`) REFERENCES `imageCollection` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `imageConfig` +-- + +DROP TABLE IF EXISTS `imageConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `imageConfig` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Identifier', + `maxSize` int(10) unsigned NOT NULL COMMENT 'Maximun size for uploaded images in MB', + `useXsendfile` tinyint(4) NOT NULL COMMENT 'Whether to use the apache module XSendfile', + `url` varchar(255) NOT NULL COMMENT 'Public URL where image are hosted', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='Global image parameters'; +/*!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 */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `language` ( + `code` varchar(10) CHARACTER SET utf8 NOT NULL, + `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + `orgName` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `isActive` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!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 */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `link` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `image` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=37 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`link_afterInsert` + AFTER INSERT ON `link` + FOR EACH ROW +BEGIN + CALL image_ref('link', NEW.image); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`link_afterUpdate` + AFTER UPDATE ON `link` + FOR EACH ROW +BEGIN + IF !(NEW.image <=> OLD.image) THEN + CALL image_unref('link', OLD.image); + CALL image_ref('link', NEW.image); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`link_afterDelete` + AFTER DELETE ON `link` + FOR EACH ROW +BEGIN + CALL image_unref('link', OLD.image); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `location` +-- + +DROP TABLE IF EXISTS `location`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `location` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `lat` varchar(12) COLLATE utf8_unicode_ci NOT NULL, + `lng` varchar(12) COLLATE utf8_unicode_ci NOT NULL, + `title` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `address` varchar(75) COLLATE utf8_unicode_ci DEFAULT NULL, + `postcode` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `city` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `province` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `phone` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `language` char(2) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `mailConfig` +-- + +DROP TABLE IF EXISTS `mailConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mailConfig` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Identifier', + `host` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'localhost' COMMENT 'SMTP host', + `port` smallint(6) NOT NULL DEFAULT '465' COMMENT 'SMTP port', + `secure` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Wether to use a secure connection', + `sender` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The sender mail address', + `senderName` varchar(75) CHARACTER SET utf8 NOT NULL COMMENT 'The sender name', + `user` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'SMTP user', + `password` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'SMTP password, base64 encoded', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `mainAccount` +-- + +DROP TABLE IF EXISTS `mainAccount`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mainAccount` ( + `accountFk` mediumint(8) unsigned NOT NULL, + PRIMARY KEY (`accountFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `mainAccountBank` +-- + +DROP TABLE IF EXISTS `mainAccountBank`; +/*!50001 DROP VIEW IF EXISTS `mainAccountBank`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `mainAccountBank` AS SELECT + 1 AS `name`, + 1 AS `iban`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `menu` +-- + +DROP TABLE IF EXISTS `menu`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `menu` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `description` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `path` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `roleFk` int(10) unsigned NOT NULL, + `parentFk` int(10) unsigned DEFAULT NULL, + `displayOrder` tinyint(4) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + KEY `group_id` (`roleFk`), + KEY `parent` (`parentFk`), + CONSTRAINT `menu_ibfk_1` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `message` +-- + +DROP TABLE IF EXISTS `message`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `message` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `code` char(35) COLLATE utf8_unicode_ci NOT NULL, + `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `code` (`code`) +) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `metatag` +-- + +DROP TABLE IF EXISTS `metatag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `metatag` ( + `id` int(11) NOT NULL, + `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `content` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `myAddress` +-- + +DROP TABLE IF EXISTS `myAddress`; +/*!50001 DROP VIEW IF EXISTS `myAddress`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myAddress` AS SELECT + 1 AS `id`, + 1 AS `clientFk`, + 1 AS `street`, + 1 AS `city`, + 1 AS `postalCode`, + 1 AS `provinceFk`, + 1 AS `nickname`, + 1 AS `isDefaultAddress`, + 1 AS `isActive`, + 1 AS `longitude`, + 1 AS `latitude`, + 1 AS `warehouseFk`, + 1 AS `agencyModeFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myBasket` +-- + +DROP TABLE IF EXISTS `myBasket`; +/*!50001 DROP VIEW IF EXISTS `myBasket`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myBasket` AS SELECT + 1 AS `id`, + 1 AS `made`, + 1 AS `sent`, + 1 AS `clientFk`, + 1 AS `deliveryMethodFk`, + 1 AS `agencyModeFk`, + 1 AS `addressFk`, + 1 AS `companyFk`, + 1 AS `notes`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myBasketDefaults` +-- + +DROP TABLE IF EXISTS `myBasketDefaults`; +/*!50001 DROP VIEW IF EXISTS `myBasketDefaults`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myBasketDefaults` AS SELECT + 1 AS `deliveryMethod`, + 1 AS `agencyModeFk`, + 1 AS `addressFk`, + 1 AS `defaultAgencyFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myBasketItem` +-- + +DROP TABLE IF EXISTS `myBasketItem`; +/*!50001 DROP VIEW IF EXISTS `myBasketItem`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myBasketItem` AS SELECT + 1 AS `id`, + 1 AS `orderFk`, + 1 AS `warehouseFk`, + 1 AS `itemFk`, + 1 AS `amount`, + 1 AS `price`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myClient` +-- + +DROP TABLE IF EXISTS `myClient`; +/*!50001 DROP VIEW IF EXISTS `myClient`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myClient` AS SELECT + 1 AS `id`, + 1 AS `isToBeMailed`, + 1 AS `defaultAddressFk`, + 1 AS `credit`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myInvoice` +-- + +DROP TABLE IF EXISTS `myInvoice`; +/*!50001 DROP VIEW IF EXISTS `myInvoice`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myInvoice` AS SELECT + 1 AS `id`, + 1 AS `ref`, + 1 AS `issued`, + 1 AS `amount`, + 1 AS `hasPdf`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myMenu` +-- + +DROP TABLE IF EXISTS `myMenu`; +/*!50001 DROP VIEW IF EXISTS `myMenu`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myMenu` AS SELECT + 1 AS `id`, + 1 AS `path`, + 1 AS `description`, + 1 AS `parentFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myOrder` +-- + +DROP TABLE IF EXISTS `myOrder`; +/*!50001 DROP VIEW IF EXISTS `myOrder`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myOrder` AS SELECT + 1 AS `id`, + 1 AS `landed`, + 1 AS `clientFk`, + 1 AS `deliveryMethodFk`, + 1 AS `agencyModeFk`, + 1 AS `addressFk`, + 1 AS `companyFk`, + 1 AS `note`, + 1 AS `sourceApp`, + 1 AS `isConfirmed`, + 1 AS `created`, + 1 AS `firstRowStamp`, + 1 AS `confirmed`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myOrderRow` +-- + +DROP TABLE IF EXISTS `myOrderRow`; +/*!50001 DROP VIEW IF EXISTS `myOrderRow`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myOrderRow` AS SELECT + 1 AS `id`, + 1 AS `Fk`, + 1 AS `itemFk`, + 1 AS `warehouseFk`, + 1 AS `shipped`, + 1 AS `amount`, + 1 AS `price`, + 1 AS `rate`, + 1 AS `created`, + 1 AS `saleFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myOrderTicket` +-- + +DROP TABLE IF EXISTS `myOrderTicket`; +/*!50001 DROP VIEW IF EXISTS `myOrderTicket`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myOrderTicket` AS SELECT + 1 AS `orderFk`, + 1 AS `ticketFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myTicket` +-- + +DROP TABLE IF EXISTS `myTicket`; +/*!50001 DROP VIEW IF EXISTS `myTicket`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myTicket` AS SELECT + 1 AS `id`, + 1 AS `clientFk`, + 1 AS `warehouseFk`, + 1 AS `shipped`, + 1 AS `landed`, + 1 AS `nickname`, + 1 AS `agencyModeFk`, + 1 AS `refFk`, + 1 AS `addressFk`, + 1 AS `location`, + 1 AS `companyFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myTicketRow` +-- + +DROP TABLE IF EXISTS `myTicketRow`; +/*!50001 DROP VIEW IF EXISTS `myTicketRow`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myTicketRow` AS SELECT + 1 AS `id`, + 1 AS `itemFk`, + 1 AS `ticketFk`, + 1 AS `concept`, + 1 AS `quantity`, + 1 AS `price`, + 1 AS `discount`, + 1 AS `reserved`, + 1 AS `isPicked`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myTicketState` +-- + +DROP TABLE IF EXISTS `myTicketState`; +/*!50001 DROP VIEW IF EXISTS `myTicketState`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myTicketState` AS SELECT + 1 AS `id`, + 1 AS `clientFk`, + 1 AS `warehouseFk`, + 1 AS `shipped`, + 1 AS `landed`, + 1 AS `nickname`, + 1 AS `agencyModeFk`, + 1 AS `refFk`, + 1 AS `addressFk`, + 1 AS `location`, + 1 AS `companyFk`, + 1 AS `alertLevel`, + 1 AS `code`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `myTpvTransaction` +-- + +DROP TABLE IF EXISTS `myTpvTransaction`; +/*!50001 DROP VIEW IF EXISTS `myTpvTransaction`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `myTpvTransaction` AS SELECT + 1 AS `id`, + 1 AS `merchantFk`, + 1 AS `clientFk`, + 1 AS `receiptFk`, + 1 AS `amount`, + 1 AS `response`, + 1 AS `status`, + 1 AS `created`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `news` +-- + +DROP TABLE IF EXISTS `news`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `news` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `title` varchar(150) COLLATE utf8_unicode_ci NOT NULL, + `text` text COLLATE utf8_unicode_ci NOT NULL, + `image` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `userFk` int(10) unsigned NOT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `priority` tinyint(3) unsigned NOT NULL DEFAULT '3', + `tag` varchar(15) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'new', + PRIMARY KEY (`id`), + KEY `user` (`userFk`), + KEY `tag` (`tag`), + CONSTRAINT `news_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`account` (`id`) ON UPDATE CASCADE, + CONSTRAINT `news_ibfk_2` FOREIGN KEY (`tag`) REFERENCES `newsTag` (`name`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=13076 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`news_afterInsert` + AFTER INSERT ON `news` + FOR EACH ROW +BEGIN + CALL image_ref('news', NEW.image); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`news_afterUpdate` + AFTER UPDATE ON `news` + FOR EACH ROW +BEGIN + IF !(NEW.image <=> OLD.image) THEN + CALL image_unref('news', OLD.image); + CALL image_ref('news', NEW.image); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`news_afterDelete` + AFTER DELETE ON `news` + FOR EACH ROW +BEGIN + CALL image_unref('news', OLD.image); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `newsTag` +-- + +DROP TABLE IF EXISTS `newsTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `newsTag` ( + `name` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `description` varchar(25) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `order` +-- + +DROP TABLE IF EXISTS `order`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `order` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `date_send` date NOT NULL DEFAULT '0000-00-00', + `customer_id` int(11) NOT NULL, + `delivery_method_id` int(11) DEFAULT '3', + `agency_id` int(11) DEFAULT '2', + `address_id` int(11) DEFAULT NULL, + `company_id` smallint(5) unsigned NOT NULL DEFAULT '442', + `note` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `source_app` set('WEB','ANDROID','IOS','SALIX','TPV','TABLET_VN','') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'TPV', + `is_bionic` tinyint(1) NOT NULL DEFAULT '1', + `confirmed` tinyint(1) NOT NULL DEFAULT '0', + `date_make` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `first_row_stamp` datetime DEFAULT NULL, + `confirm_date` datetime DEFAULT NULL, + `taxableBase` decimal(10,2) NOT NULL, + `tax` decimal(10,2) NOT NULL, + `total` decimal(10,2) NOT NULL, + PRIMARY KEY (`id`), + KEY `address` (`address_id`), + KEY `delivery_method` (`delivery_method_id`), + KEY `agency` (`agency_id`), + KEY `customer_id` (`customer_id`), + KEY `company_id` (`company_id`), + KEY `id` (`id`,`customer_id`), + KEY `source_app` (`source_app`), + KEY `confirmed` (`confirmed`), + CONSTRAINT `order_ibfk_5` FOREIGN KEY (`address_id`) REFERENCES `vn`.`address` (`id`) ON UPDATE CASCADE, + CONSTRAINT `order_ibfk_8` FOREIGN KEY (`delivery_method_id`) REFERENCES `vn`.`deliveryMethod` (`id`) ON UPDATE CASCADE, + CONSTRAINT `order_ibfk_9` FOREIGN KEY (`agency_id`) REFERENCES `vn`.`agencyMode` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2286868 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate` + AFTER UPDATE ON `order` + FOR EACH ROW +BEGIN + CALL stock.log_add('order', NEW.id, OLD.id); + + IF !(OLD.address_id <=> NEW.address_id) + OR !(OLD.company_id <=> NEW.company_id) + OR !(OLD.customer_id <=> NEW.customer_id) THEN + CALL order_requestRecalc(NEW.id); + END IF; +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`order_beforeDelete` + BEFORE DELETE ON `order` + FOR EACH ROW +BEGIN + DELETE FROM orderRow WHERE orderFk = OLD.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 */ ; + +-- +-- Table structure for table `orderConfig` +-- + +DROP TABLE IF EXISTS `orderConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `orderConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `employeeFk` int(11) NOT NULL, + `defaultAgencyFk` int(11) DEFAULT NULL, + `guestMethod` varchar(45) CHARACTER SET utf8 NOT NULL, + `guestAgencyFk` int(11) NOT NULL, + `guestAddressFk` int(11) NOT NULL, + `reserveTime` time NOT NULL, + `defaultCompanyFk` smallint(6) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `employeeFk` (`employeeFk`), + KEY `guestAgencyFk` (`guestAgencyFk`), + KEY `defaultCompanyFk` (`defaultCompanyFk`), + KEY `guestMethod` (`guestMethod`), + KEY `defaultAgencyFk` (`defaultAgencyFk`), + KEY `guestAddressFk` (`guestAddressFk`), + CONSTRAINT `orderConfig_ibfk_1` FOREIGN KEY (`employeeFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `orderConfig_ibfk_2` FOREIGN KEY (`defaultCompanyFk`) REFERENCES `vn`.`company` (`id`) ON UPDATE CASCADE, + CONSTRAINT `orderConfig_ibfk_3` FOREIGN KEY (`guestAgencyFk`) REFERENCES `vn`.`agencyMode` (`id`) ON UPDATE CASCADE, + CONSTRAINT `orderConfig_ibfk_4` FOREIGN KEY (`defaultAgencyFk`) REFERENCES `vn`.`agencyMode` (`id`), + CONSTRAINT `orderConfig_ibfk_5` FOREIGN KEY (`guestAddressFk`) REFERENCES `vn`.`address` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `orderRecalc` +-- + +DROP TABLE IF EXISTS `orderRecalc`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `orderRecalc` ( + `orderFk` int(10) unsigned NOT NULL, + PRIMARY KEY (`orderFk`), + CONSTRAINT `orderRecalc_ibfk_1` FOREIGN KEY (`orderFk`) REFERENCES `order` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Queue of changed orders to recalc it''s total'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `orderRow` +-- + +DROP TABLE IF EXISTS `orderRow`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `orderRow` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `orderFk` int(10) unsigned NOT NULL DEFAULT '0', + `itemFk` int(11) NOT NULL DEFAULT '0', + `warehouseFk` int(11) DEFAULT NULL, + `shipment` date DEFAULT NULL, + `amount` smallint(6) unsigned NOT NULL DEFAULT '0', + `price` decimal(10,2) DEFAULT NULL, + `rate` smallint(5) unsigned DEFAULT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `saleFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `item` (`itemFk`), + KEY `order_id` (`orderFk`), + KEY `created` (`created`), + KEY `warehouse_shipment` (`warehouseFk`,`shipment`), + CONSTRAINT `orderRow_ibfk_2` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON UPDATE CASCADE, + CONSTRAINT `orderRow_ibfk_3` FOREIGN KEY (`orderFk`) REFERENCES `order` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=13685290 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `orderRow_beforeInsert` + BEFORE INSERT ON `orderRow` + FOR EACH ROW +BEGIN + DECLARE vIsFirst BOOL; + + SELECT (first_row_stamp IS NULL) INTO vIsFirst + FROM `order` + WHERE id = NEW.orderFk; + + IF vIsFirst THEN + UPDATE `order` SET first_row_stamp = NOW() + WHERE id = NEW.orderFk; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`orderRow_afterInsert` + AFTER INSERT ON `orderRow` + FOR EACH ROW +BEGIN + CALL stock.log_add('orderRow', NEW.id, NULL); + CALL order_requestRecalc(NEW.orderFk); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`orderRow_afterUpdate` + AFTER UPDATE ON `orderRow` + FOR EACH ROW +BEGIN + CALL stock.log_add('orderRow', NEW.id, OLD.id); + CALL order_requestRecalc(OLD.orderFk); + CALL order_requestRecalc(NEW.orderFk); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `hedera`.`orderRow_afterDelete` + AFTER DELETE ON `orderRow` + FOR EACH ROW +BEGIN + CALL stock.log_add('orderRow', NULL, OLD.id); + CALL order_requestRecalc(OLD.orderFk); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `orderRowComponent` +-- + +DROP TABLE IF EXISTS `orderRowComponent`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `orderRowComponent` ( + `rowFk` int(10) unsigned NOT NULL, + `componentFk` int(11) NOT NULL, + `price` decimal(12,4) NOT NULL, + PRIMARY KEY (`rowFk`,`componentFk`), + KEY `component_id` (`componentFk`), + CONSTRAINT `orderRowComponent_ibfk_1` FOREIGN KEY (`rowFk`) REFERENCES `orderRow` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `orderTicket` +-- + +DROP TABLE IF EXISTS `orderTicket`; +/*!50001 DROP VIEW IF EXISTS `orderTicket`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `orderTicket` AS SELECT + 1 AS `orderFk`, + 1 AS `ticketFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `order_component` +-- + +DROP TABLE IF EXISTS `order_component`; +/*!50001 DROP VIEW IF EXISTS `order_component`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `order_component` AS SELECT + 1 AS `order_row_id`, + 1 AS `component_id`, + 1 AS `price`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `order_row` +-- + +DROP TABLE IF EXISTS `order_row`; +/*!50001 DROP VIEW IF EXISTS `order_row`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `order_row` AS SELECT + 1 AS `id`, + 1 AS `order_id`, + 1 AS `item_id`, + 1 AS `warehouse_id`, + 1 AS `shipment`, + 1 AS `amount`, + 1 AS `price`, + 1 AS `rate`, + 1 AS `created`, + 1 AS `Id_Movimiento`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `restPriv` +-- + +DROP TABLE IF EXISTS `restPriv`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `restPriv` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `methodPath` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `role` int(10) unsigned NOT NULL, + PRIMARY KEY (`id`), + KEY `role` (`role`), + CONSTRAINT `restPriv_ibfk_1` FOREIGN KEY (`role`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `shelf` +-- + +DROP TABLE IF EXISTS `shelf`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `shelf` ( + `id` int(10) unsigned NOT NULL, + `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `nTrays` tinyint(3) unsigned NOT NULL, + `trayheight` mediumint(8) unsigned NOT NULL, + `topTrayHeight` mediumint(8) unsigned NOT NULL, + `width` mediumint(8) unsigned NOT NULL, + `depth` mediumint(8) unsigned NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Dimensiones de las estanterias'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `shelfConfig` +-- + +DROP TABLE IF EXISTS `shelfConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `shelfConfig` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, + `namePrefix` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `warehouse` smallint(5) unsigned NOT NULL, + `family` smallint(5) unsigned NOT NULL, + `shelf` int(10) unsigned NOT NULL, + `maxAmount` smallint(5) unsigned DEFAULT NULL, + `showPacking` tinyint(4) NOT NULL, + `stack` tinyint(4) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `shelf_id` (`shelf`), + KEY `family_id` (`family`), + KEY `warehouse_id` (`warehouse`), + CONSTRAINT `shelfConfig_ibfk_1` FOREIGN KEY (`family`) REFERENCES `vn`.`itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `shelfConfig_ibfk_2` FOREIGN KEY (`shelf`) REFERENCES `shelf` (`id`) ON UPDATE CASCADE, + CONSTRAINT `shelfConfig_ibfk_3` FOREIGN KEY (`warehouse`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `social` +-- + +DROP TABLE IF EXISTS `social`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `social` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `title` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `icon` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `priority` tinyint(3) unsigned NOT NULL, + PRIMARY KEY (`id`), + KEY `priority` (`priority`) +) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `survey` +-- + +DROP TABLE IF EXISTS `survey`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `survey` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `question` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `surveyAnswer` +-- + +DROP TABLE IF EXISTS `surveyAnswer`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `surveyAnswer` ( + `id` int(10) unsigned NOT NULL, + `surveyFk` int(10) unsigned NOT NULL, + `answer` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `votes` int(10) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `survey` (`surveyFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `surveyVote` +-- + +DROP TABLE IF EXISTS `surveyVote`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `surveyVote` ( + `surveyFk` int(10) unsigned NOT NULL, + `userFk` int(10) unsigned NOT NULL, + PRIMARY KEY (`surveyFk`,`userFk`), + KEY `surveyVote_ibfk_2` (`userFk`), + CONSTRAINT `surveyVote_ibfk_1` FOREIGN KEY (`surveyFk`) REFERENCES `survey` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `surveyVote_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tpvConfig` +-- + +DROP TABLE IF EXISTS `tpvConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tpvConfig` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `currency` smallint(5) unsigned NOT NULL, + `terminal` tinyint(3) unsigned NOT NULL, + `transactionType` tinyint(3) unsigned NOT NULL, + `maxAmount` int(10) unsigned DEFAULT NULL, + `employeeFk` int(10) NOT NULL, + `url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The bank web service URL for production environment', + `testMode` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT 'Whether test mode is enabled', + `testUrl` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The bank web service URL for test environment', + `testKey` varchar(50) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The bank secret key for test environment', + `merchantUrl` varchar(255) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `employee_id` (`employeeFk`), + CONSTRAINT `employee_id` FOREIGN KEY (`employeeFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Virtual TPV parameters'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tpvError` +-- + +DROP TABLE IF EXISTS `tpvError`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tpvError` ( + `code` char(7) COLLATE utf8_unicode_ci NOT NULL, + `message` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT=' List of possible TPV errors'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tpvImapConfig` +-- + +DROP TABLE IF EXISTS `tpvImapConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tpvImapConfig` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `host` varchar(150) COLLATE utf8_unicode_ci NOT NULL, + `user` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `pass` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `cleanPeriod` varchar(15) CHARACTER SET utf8 NOT NULL, + `successFolder` varchar(150) CHARACTER SET utf8 DEFAULT NULL, + `errorFolder` varchar(150) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='IMAP configuration parameters for virtual TPV'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tpvMerchant` +-- + +DROP TABLE IF EXISTS `tpvMerchant`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tpvMerchant` ( + `id` int(10) unsigned NOT NULL COMMENT 'Merchant identifier', + `description` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Small description', + `companyFk` smallint(6) unsigned DEFAULT NULL COMMENT 'Company associated with the merchant', + `bankFk` int(10) NOT NULL COMMENT 'The bank where merchant receipts are created', + `secretKey` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The merchant secret key to sign transactions', + PRIMARY KEY (`id`), + KEY `bank_id` (`bankFk`), + KEY `company_id` (`companyFk`), + KEY `id` (`id`,`companyFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Virtual TPV providers'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tpvMerchantEnable` +-- + +DROP TABLE IF EXISTS `tpvMerchantEnable`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tpvMerchantEnable` ( + `merchantFk` int(10) unsigned NOT NULL DEFAULT '0', + `companyFk` smallint(6) unsigned NOT NULL, + PRIMARY KEY (`merchantFk`,`companyFk`), + UNIQUE KEY `company_id` (`companyFk`), + CONSTRAINT `tpvMerchantEnable_ibfk_1` FOREIGN KEY (`merchantFk`, `companyFk`) REFERENCES `tpvMerchant` (`id`, `companyFk`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Virtual TPV enabled providers'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tpvResponse` +-- + +DROP TABLE IF EXISTS `tpvResponse`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tpvResponse` ( + `id` smallint(5) unsigned NOT NULL, + `message` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='List of possible TPV reponses'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tpvTransaction` +-- + +DROP TABLE IF EXISTS `tpvTransaction`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tpvTransaction` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `merchantFk` int(10) unsigned NOT NULL, + `clientFk` int(11) NOT NULL, + `receiptFk` int(11) DEFAULT NULL, + `amount` int(10) unsigned NOT NULL, + `response` smallint(5) unsigned DEFAULT NULL COMMENT 'Status notified by bank: NULL if no notification, 0 if success, error otherwise', + `errorCode` char(7) COLLATE utf8_unicode_ci DEFAULT NULL, + `status` enum('started','ok','ko') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'started', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `merchant_id` (`merchantFk`), + KEY `receipt_id` (`receiptFk`), + KEY `user_id` (`clientFk`), + KEY `response` (`response`), + KEY `error_code` (`errorCode`), + CONSTRAINT `receipt_id` FOREIGN KEY (`receiptFk`) REFERENCES `vn`.`receipt` (`Id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `tpvTransaction_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `tpvTransaction_ibfk_2` FOREIGN KEY (`merchantFk`) REFERENCES `tpvMerchant` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=379747 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Transactions realized through the virtual TPV'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `userSession` +-- + +DROP TABLE IF EXISTS `userSession`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `userSession` ( + `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `lastUpdate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `ssid` char(64) COLLATE utf8_unicode_ci NOT NULL, + `data` text COLLATE utf8_unicode_ci, + `userVisitFk` int(10) unsigned DEFAULT NULL, + UNIQUE KEY `ssid` (`ssid`), + KEY `userVisit` (`userVisitFk`), + KEY `lastUpdate` (`lastUpdate`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `visit` +-- + +DROP TABLE IF EXISTS `visit`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `visit` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `firstAgentFk` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `firstAgent` (`firstAgentFk`), + CONSTRAINT `visit_ibfk_1` FOREIGN KEY (`firstAgentFk`) REFERENCES `visitAgent` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2035382 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `visitAccess` +-- + +DROP TABLE IF EXISTS `visitAccess`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `visitAccess` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `agentFk` int(10) unsigned NOT NULL, + `stamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `ip` int(10) unsigned DEFAULT NULL, + `referer` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `visit_access_idx_agent` (`agentFk`), + KEY `stamp` (`stamp`), + CONSTRAINT `visitAccess_ibfk_1` FOREIGN KEY (`agentFk`) REFERENCES `visitAgent` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=4558610 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `visitAgent` +-- + +DROP TABLE IF EXISTS `visitAgent`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `visitAgent` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `visitFk` int(10) unsigned NOT NULL, + `firstAccessFk` int(10) unsigned DEFAULT NULL, + `platform` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, + `browser` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, + `version` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `javascript` tinyint(3) unsigned DEFAULT NULL, + `cookies` tinyint(3) unsigned DEFAULT NULL, + `agent` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `visit_id` (`visitFk`), + KEY `firstAccess` (`firstAccessFk`), + CONSTRAINT `visitAgent_ibfk_1` FOREIGN KEY (`visitFk`) REFERENCES `visit` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `visitAgent_ibfk_2` FOREIGN KEY (`firstAccessFk`) REFERENCES `visitAccess` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2687431 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `visitUser` +-- + +DROP TABLE IF EXISTS `visitUser`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `visitUser` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `accessFk` int(10) unsigned NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `access_id` (`accessFk`), + KEY `date_time` (`stamp`), + KEY `user_id` (`userFk`), + CONSTRAINT `visitUser_ibfk_1` FOREIGN KEY (`accessFk`) REFERENCES `visitAccess` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=3988167 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'hedera' +-- +/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; +/*!50106 DROP EVENT IF EXISTS `order_doRecalc` */; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `order_doRecalc` ON SCHEDULE EVERY 10 SECOND STARTS '2019-08-29 14:18:04' ON COMPLETION PRESERVE ENABLE DO CALL order_doRecalc */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; +DELIMITER ; +/*!50106 SET TIME_ZONE= @save_time_zone */ ; + +-- +-- Dumping routines for database 'hedera' +-- +/*!50003 DROP FUNCTION IF EXISTS `myBasket_getId` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `MYBASKET_GETID`() RETURNS int(11) + DETERMINISTIC +BEGIN + DECLARE vOrder INT; + + SELECT orderFk INTO vOrder FROM basketOrder + WHERE clientFk = account.myUserGetId(); + + RETURN vOrder; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `myClient_getDebt` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `myClient_getDebt`(vDate DATE) RETURNS decimal(10,2) + DETERMINISTIC +BEGIN +/** + * Calcula el saldo del cliente actual. + * + * @return Saldo del cliente + */ + RETURN vn.clientGetDebt(account.userGetId(), vDate); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `myUser_checkRestPriv` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `myUser_checkRestPriv`(vMethodPath VARCHAR(255)) RETURNS tinyint(1) + DETERMINISTIC +BEGIN +/** + * Comprueba si el usuario actual tiene permiso para ejecutar + * un servicio REST. + * + * @param vMethodPath Ruta del servicio REST a ejecutar + * @return %TRUE si tiene permisos, %FALSE en caso contrario + **/ + DECLARE vRole INT DEFAULT NULL; + + SELECT role INTO vRole FROM restPriv + WHERE methodPath = vMethodPath; + + RETURN vRole IS NULL + OR account.myUserHasRoleId (vRole); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `order_getTotal` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `order_getTotal`(vSelf INT) RETURNS decimal(10,2) + READS SQL DATA + DETERMINISTIC +BEGIN +/** +* Obtiene el total de un pedido con el IVA y el recargo de +* equivalencia incluidos. +* +* @param vSelf El identificador del pedido +* @return El total del pedido +*/ + DECLARE vTotal DECIMAL(10,2); + + DROP TEMPORARY TABLE IF EXISTS tmp.`order`; + CREATE TEMPORARY TABLE tmp.`order` + ENGINE = MEMORY + SELECT vSelf orderFk; + + CALL order_getTotal; + + SELECT total INTO vTotal FROM tmp.orderTotal; + + DROP TEMPORARY TABLE + tmp.`order`, + tmp.orderTotal; + + RETURN vTotal; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `catalog_calcFromMyAddress` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calcFromMyAddress`(vDelivery DATE, vAddress INT) +BEGIN +/** + * Gets the available items list. + * + * @param vDelivery Delivery date + * @param vAddress Address id + * @return tmp.ticketCalculateItem + * @return tmp.ticketComponentPrice + * @return tmp.ticketComponent + * @return tmp.ticketLot + * @return tmp.zoneGetShipped + */ + DECLARE vAgencyMode INT; + + SELECT a.agencyModeFk + INTO vAgencyMode + FROM myClient c + JOIN vn.address a ON a.clientFk = c.id + WHERE a.id = vAddress; + + CALL vn.available_calc(vDelivery, vAddress, vAgencyMode); + + DROP TEMPORARY TABLE IF EXISTS tmp.item; + CREATE TEMPORARY TABLE tmp.item + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT c.item_id itemFk + FROM `cache`.available c + JOIN tmp.availableCalc a ON a.calcFk = c.calc_id + WHERE c.available > 0 + GROUP BY c.item_id; + + CALL vn.catalog_calculate(vDelivery, vAddress, vAgencyMode); + + DROP TEMPORARY TABLE tmp.item; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `catalog_getTags` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_getTags`(vLimit INT) +BEGIN +/** + * Returns the main tags for a list of items. + * + * @table tItems The list of items + * @select The main tags for the passed items + */ + CALL catalogGetAvailable; + + DROP TEMPORARY TABLE IF EXISTS tTags; + CREATE TEMPORARY TABLE tTags + (INDEX (tagFk)) + ENGINE = MEMORY + SELECT it.tagFk, SUM(it.priority) priority + FROM vn.itemTag it + JOIN tItems i ON i.id = it.itemFk + GROUP BY tagFk + LIMIT vLimit; + + SELECT l.id, l.name + FROM tTags t + JOIN vn.tagL10n l ON l.id = t.tagFk + ORDER BY priority DESC; + + DROP TEMPORARY TABLE tTags; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `catalog_getTagValues` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_getTagValues`(vTag INT) +BEGIN +/** + * Returns the list of available values for a tag and a list of items. + * + * @table tItems The list of items + * @param vTag The tag identifier + * @select The list of available tags + */ + CALL catalogGetAvailable; + + SELECT DISTINCT it.value + FROM vn.itemTag it + JOIN tItems i ON i.id = it.itemFk + WHERE it.tagFk = vTag + ORDER BY value + LIMIT 200; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `image_ref` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `image_ref`( + vCollection VARCHAR(255), + vName VARCHAR(255) +) +proc: BEGIN +/** + * Increases the reference count of an image. + * + * @param vCollection The collection name + * @param vName The image name + */ + IF vName IS NULL THEN + LEAVE proc; + END IF; + + INSERT INTO `image` + SET `collectionFk` = vCollection, + `name` = vName, + `updated` = UNIX_TIMESTAMP(), + `nRefs` = 1 + ON DUPLICATE KEY UPDATE + `nRefs` = nRefs + 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 DROP PROCEDURE IF EXISTS `image_unref` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `image_unref`( + vCollection VARCHAR(255), + vName VARCHAR(255) +) +BEGIN +/** + * Decreases the reference count of an image. + * + * @param vCollection The collection name + * @param vName The image name + */ + UPDATE image SET nRefs = GREATEST(CAST(nRefs AS SIGNED) - 1, 0) + WHERE `name` = vName + AND collectionFk = vCollection; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_calcCatalog` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `item_calcCatalog`( + vSelf INT, + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT) +BEGIN +/** + * Calculates available and price for a single item. + * + * @param vItemFk The item id + * @return List of available lots + */ + DROP TEMPORARY TABLE IF EXISTS tmp.item; + CREATE TEMPORARY TABLE tmp.item + ENGINE = MEMORY + SELECT vSelf itemFk; + + CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); + + SELECT l.warehouseFk, w.name warehouse, + p.`grouping`, p.price, p.rate, l.available + FROM tmp.ticketLot l + JOIN tmp.ticketComponentPrice p ON p.warehouseFk = l.warehouseFk + JOIN vn.warehouse w ON w.id = p.warehouseFk + ORDER BY warehouseFk, `grouping`; + + DROP TEMPORARY TABLE + tmp.ticketCalculateItem, + tmp.ticketComponentPrice, + tmp.ticketComponent, + tmp.ticketLot, + tmp.zoneGetShipped; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_getList` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `item_getList`(IN `vWarehouse` SMALLINT, IN `vShipping` DATE, IN `vCategory` INT, IN `vRate` TINYINT) +BEGIN + DECLARE vCalc INT; + + CALL cache.available_refresh(vCalc, FALSE, vWarehouse, vShipping); + CALL vn.buyUltimate(vWarehouse, vShipping); + + SELECT a.id, a.`name`, a.category, a.size, a.stems, a.inkFk, a.typeFk, a.image, + c.available, o.`name` origin, t.`name` `type`, + CASE b.groupingMode + WHEN 0 THEN 1 + WHEN 2 THEN b.packing + ELSE b.`grouping` + END AS `grouping`, + CASE vRate + WHEN 1 THEN b.price1 + WHEN 2 THEN b.price2 + WHEN 3 THEN b.price3 + ELSE NULL + END AS price + FROM cache.available c + JOIN vn.item a ON a.id = c.item_id + JOIN vn.itemType t ON t.id = a.typeFk + JOIN vn.itemCategory r ON r.id = t.categoryFk + LEFT JOIN vn.origin o ON o.id = a.originFk + JOIN tmp.buyUltimate bu ON bu.itemFk = a.id + JOIN vn.buy b ON b.id = bu.buyFk + WHERE c.calc_id = vCalc + AND c.available > 0 + AND a.id != 90 + AND r.display + AND (vCategory IS NULL OR vCategory = r.id) + ORDER BY a.typeFk, a.`name`, a.size; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_getVisible` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `item_getVisible`( + vWarehouse TINYINT, + vDate DATE, + vType INT, + vPrefix VARCHAR(255)) +BEGIN +/** + * Gets visible items of the specified type at specified date. + * + * @param vWarehouse The warehouse id + * @param vDate The visible date + * @param vType The type id + * @param vPrefix The article prefix to filter or %NULL for all + * @return tmp.itemVisible Visible items + */ + DECLARE vPrefixLen SMALLINT; + DECLARE vFilter VARCHAR(255) DEFAULT NULL; + DECLARE vDateInv DATE DEFAULT vn2008.date_inv(); + + SET vPrefixLen = IFNULL(LENGTH(vPrefix), 0) + 1; + + IF vPrefixLen > 1 THEN + SET vFilter = CONCAT(vPrefix, '%'); + END IF; + + DROP TEMPORARY TABLE IF EXISTS filter; + CREATE TEMPORARY TABLE filter + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT id itemFk FROM vn.item + WHERE typeFk = vType + AND (vFilter IS NULL OR `name` LIKE vFilter); + + DROP TEMPORARY TABLE IF EXISTS currentStock; + CREATE TEMPORARY TABLE currentStock + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(quantity) quantity + FROM ( + SELECT b.itemFk, b.quantity + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vDateInv AND vDate + AND t.warehouseInFk = vWarehouse + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, -b.quantity + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel t ON t.id = e.travelFk + WHERE t.shipped BETWEEN vDateInv AND CURDATE() + AND t.warehouseOutFk = vWarehouse + AND NOT e.isRaid + AND t.isDelivered + UNION ALL + SELECT m.itemFk, -m.quantity + FROM vn.sale m + JOIN vn.ticket t ON t.id = m.ticketFk + JOIN vn.ticketState s ON s.ticket = t.id + WHERE t.shipped BETWEEN vDateInv AND CURDATE() + AND t.warehouseFk = vWarehouse + AND s.alertLevel = 3 + ) t + GROUP BY itemFk + HAVING quantity > 0; + + DROP TEMPORARY TABLE IF EXISTS tmp; + CREATE TEMPORARY TABLE tmp + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT * + FROM ( + SELECT b.itemFk, b.packageFk, b.packing + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vDateInv AND vDate + AND NOT b.isIgnored + AND b.price2 >= 0 + AND b.packageFk IS NOT NULL + ORDER BY t.warehouseInFk = vWarehouse DESC, t.landed DESC + ) t GROUP BY itemFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.itemVisible; + CREATE TEMPORARY TABLE tmp.itemVisible + ENGINE = MEMORY + SELECT i.id Id_Article, + SUBSTRING(i.`name`, vPrefixLen) Article, + t.packing, p.id Id_Cubo, + 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 currentStock s ON s.itemFk = i.id + LEFT JOIN tmp t ON t.itemFk = i.id + LEFT JOIN vn.packaging p ON p.id = t.packageFk + WHERE CEIL(s.quantity / t.packing) > 0 + -- FIXME: Column Cubos.box not included in view vn.packaging + /* AND p.box */; + + DROP TEMPORARY TABLE + filter, + currentStock, + tmp; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_listAllocation` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `item_listAllocation`(IN `vWh` TINYINT, IN `vDate` DATE, IN `vType` INT, IN `vPrefix` VARCHAR(255), IN `vUseIds` BOOLEAN) +BEGIN +/** + * Lists visible items and it's box sizes of the specified + * type at specified date. + * + * @param vWh The warehouse id + * @param vDate The visible date + * @param vType The type id + * @param vPrefix The article prefix to filter or %NULL for all + * @param vUseIds Whether to order the result by item id + * @select List of visible items with it's box sizes + */ + CALL item_getVisible(vWh, vDate, vType, vPrefix); + + IF vUseIds + THEN + SELECT * FROM tmp.itemVisible + ORDER BY Id_Article; + ELSE + SELECT * FROM tmp.itemVisible + ORDER BY Article, packing; + END IF; + + DROP TEMPORARY TABLE tmp.itemVisible; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myBasket_addItem` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_addItem`( + vWarehouse INT, + vItem INT, + vAmount INT) +BEGIN + CALL order_addItem(myBasket_getId(), vWarehouse, vItem, vAmount); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myBasket_calcCatalogFromItem` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_calcCatalogFromItem`(vItem INT) +BEGIN +/** + * Gets the availability and prices for the given item + * using current user basket parameters. + * + * @table tmp.item(itemFk) + * @return tmp.ticketCalculateItem + * @return tmp.ticketComponentPrice + * @return tmp.ticketComponent + * @return tmp.ticketLot + * @return tmp.zoneGetShipped + */ + CALL order_calcCatalogFromItem(myBasket_getId(), vItem); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myBasket_calcCatalogFull` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_calcCatalogFull`() +BEGIN +/** + * Gets the availability and prices for the given items + * using current user basket parameters. + * + * @table tmp.item(itemFk) + * @return tmp.ticketCalculateItem + * @return tmp.ticketComponentPrice + * @return tmp.ticketComponent + * @return tmp.ticketLot + * @return tmp.zoneGetShipped + */ + CALL order_calcCatalogFull(myBasket_getId()); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myBasket_check` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_check`() +BEGIN +/** + * Comprueba que la cesta esta creada y que su configuración es + * correcta. Si la configuración es correcta pero lleva mucho + * tiempo creada actualiza los precios y cantidades de los artículos. + * + * @select El id del pedido y el estado de la cesta + */ + DECLARE vSelf INT; + DECLARE vCreated DATETIME; + DECLARE vStatus VARCHAR(15) DEFAULT 'OK'; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vStatus = 'NOT_EXISTS'; + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET vStatus = 'BAD_CONFIG'; + + SELECT id, made + INTO vSelf, vCreated + FROM myBasket; + + IF vStatus = 'OK' + THEN + CALL order_checkConfig(vSelf); + + IF vStatus = 'OK' AND vCreated < TIMESTAMPADD(DAY, -1, NOW()) + THEN + CALL order_update(vSelf); + SET vStatus = 'UPDATED'; + END IF; + END IF; + + SELECT vStatus stat; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myBasket_configure` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_configure`( + vDelivery DATE, + vDeliveryMethod VARCHAR(45), + vAgency INT, + vAddress INT) +BEGIN +/** + * Configura la cesta de la compra utilizando los parámetros + * pasados. Si los parámetros no son válidos devuelve un error. + * + * @param vDelivery Fecha de recogida + * @param vAgency Id de la agencia + * @param vAddress Id de dirección de envío, @NULL si es recogida + */ + DECLARE vSelf INT; + DECLARE vCompany INT; + DECLARE vDeliveryMethodId INT; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT id INTO vDeliveryMethodId + FROM vn.deliveryMethod + WHERE code = vDeliveryMethod; + + IF vDeliveryMethod = 'PICKUP' AND vAddress IS NULL + THEN + SELECT defaultAddressFk INTO vAddress + FROM myClient; + END IF; + + SET vSelf = myBasket_getId(); + + IF vSelf IS NULL + THEN + SELECT companyFk INTO vCompany + FROM vn.clientDefaultCompany + WHERE clientFk = account.userGetId() + AND CURDATE() BETWEEN started AND finished + LIMIT 1; + + IF vCompany IS NULL + THEN + SELECT defaultCompanyFk INTO vCompany + FROM orderConfig; + END IF; + + INSERT INTO `order` + SET + customer_id = account.userGetId(), + date_send = vDelivery, + delivery_method_id = vDeliveryMethodId, + agency_id = vAgency, + address_id = vAddress, + source_app = 'WEB', + company_id = vCompany; + + SET vSelf = LAST_INSERT_ID(); + + INSERT INTO basketOrder SET + clientFk = account.userGetId(), + orderFk = vSelf; + ELSE + UPDATE `order` + SET + date_send = vDelivery, + delivery_method_id = vDeliveryMethodId, + agency_id = vAgency, + address_id = vAddress + WHERE + id = vSelf; + + CALL order_update(vSelf); + END IF; + + CALL order_checkConfig(vSelf); + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myBasket_configureForGuest` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_configureForGuest`() +BEGIN + DECLARE vMethod VARCHAR(255); + DECLARE vAgency INT; + DECLARE vAddress INT; + DECLARE vDate DATE; + + SELECT guestMethod, guestAgencyFk, guestAddressFk + INTO vMethod, vAgency, vAddress + FROM orderConfig + LIMIT 1; + + SET vDate = TIMESTAMPADD(DAY, 1, CURDATE()); + + IF WEEKDAY(vDate) BETWEEN 5 AND 6 THEN + SET vDate = TIMESTAMPADD(DAY, 7 - WEEKDAY(vDate), vDate); + END IF; + + CALL myBasket_configure(vDate, vMethod, vAgency, vAddress); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myBasket_confirm` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_confirm`() +BEGIN + DECLARE vSelf INT DEFAULT myBasket_getId(); + + IF vSelf IS NOT NULL THEN + CALL order_confirm(vSelf); + + DELETE FROM basketOrder + WHERE orderFk = vSelf; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myBasket_getAvailable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_getAvailable`() +BEGIN +/** + * Gets the available items list. + * + * @table tmp.itemAvailable + */ + CALL order_getAvailable(myBasket_getId()); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myBasket_getTax` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myBasket_getTax`() + READS SQL DATA +BEGIN +/** + * Returns the taxes for the current client basket. + * + * @treturn tmp.orderTax + */ + DROP TEMPORARY TABLE IF EXISTS tmp.`order`; + CREATE TEMPORARY TABLE tmp.`order` + ENGINE = MEMORY + SELECT myBasket_getId() orderFk; + + CALL order_getTax(); + + DROP TEMPORARY TABLE IF EXISTS tmp.`order`; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myOrder_addItem` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myOrder_addItem`( + vSelf INT, + vWarehouse INT, + vItem INT, + vAmount INT) +BEGIN + DECLARE vIsMine BOOL; + + SELECT COUNT(*) INTO vIsMine + FROM myOrder + WHERE id = vSelf; + + IF vIsMine THEN + CALL order_addItem(vSelf, vWarehouse, vItem, vAmount); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myOrder_confirm` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myOrder_confirm`(vSelf INT) +BEGIN + DECLARE vIsMine BOOL; + + SELECT COUNT(*) INTO vIsMine + FROM myOrder + WHERE id = vSelf; + + IF vIsMine THEN + CALL order_confirm(vSelf); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myOrder_getAvailable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myOrder_getAvailable`(vSelf INT) +BEGIN +/** + * Gets the available items list. + * + * @param vSelf The order id + * @table tmp.itemAvailable + */ + DECLARE isMine BOOL; + + SELECT COUNT(*) INTO isMine + FROM myOrder + WHERE id = vSelf; + + IF isMine THEN + CALL order_getAvailable(vSelf); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myOrder_newWithAddress` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myOrder_newWithAddress`( + OUT vSelf INT, + vLandingDate DATE, + vAddressFk INT) +BEGIN +/** + * Crea una nueva orden para el usuario actual especificando + * una fecha de entrega. + * + * @param vSelf Id de la nueva orden + * @param vLandingDate Fecha de entrega + */ + DECLARE vCompany INT; + DECLARE vDeliveryMethodId INT; + DECLARE vAgencyMode INT; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + SET vSelf = NULL; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT a.agencyModeFk, a.id + INTO vAgencyMode, vAddressFk + FROM vn.address a + WHERE a.id = vAddressFk; + + SELECT deliveryMethodFk INTO vDeliveryMethodId + FROM vn.agencyMode am + WHERE am.id = vAgencyMode; + + SELECT companyFk INTO vCompany + FROM vn.clientDefaultCompany + WHERE clientFk = account.userGetId() + AND CURDATE() BETWEEN started AND finished + LIMIT 1; + + IF vCompany IS NULL + THEN + SELECT defaultCompanyFk INTO vCompany + FROM orderConfig; + END IF; + + INSERT INTO `order` + SET + customer_id = account.userGetId(), + date_send = vLandingDate, + delivery_method_id = vDeliveryMethodId, + agency_id = vAgencyMode, + address_id = vAddressFk, + source_app = 'WEB', + company_id = vCompany; + + SET vSelf = LAST_INSERT_ID(); + + CALL order_checkConfig(vSelf); + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myOrder_newWithDate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myOrder_newWithDate`( + OUT vSelf INT, + vLandingDate DATE) +BEGIN +/** + * Crea una nueva orden para el usuario actual especificando + * una fecha de entrega. + * + * @param vSelf Id de la nueva orden + * @param vLandingDate Fecha de entrega + */ + DECLARE vCompany INT; + DECLARE vDeliveryMethodId INT; + DECLARE vAgencyMode INT; + DECLARE vAddress INT; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + SET vSelf = NULL; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT a.agencyModeFk, a.id + INTO vAgencyMode, vAddress + FROM myClient c + JOIN vn.address a ON a.id = c.defaultAddressFk; + + SELECT deliveryMethodFk INTO vDeliveryMethodId + FROM vn.agencyMode am + WHERE am.id = vAgencyMode; + + SELECT companyFk INTO vCompany + FROM vn.clientDefaultCompany + WHERE clientFk = account.userGetId() + AND CURDATE() BETWEEN started AND finished + LIMIT 1; + + IF vCompany IS NULL + THEN + SELECT defaultCompanyFk INTO vCompany + FROM orderConfig; + END IF; + + INSERT INTO `order` + SET + customer_id = account.userGetId(), + date_send = vLandingDate, + delivery_method_id = vDeliveryMethodId, + agency_id = vAgencyMode, + address_id = vAddress, + source_app = 'WEB', + company_id = vCompany; + + SET vSelf = LAST_INSERT_ID(); + + CALL order_checkConfig(vSelf); + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myTicket_get` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myTicket_get`(vSelf INT) +BEGIN +/** + * Returns a current user ticket header. + * + * @param vSelf The ticket identifier + */ + DECLARE vTaxBase DECIMAL(10,2); + DECLARE vTax DECIMAL(10,2); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + ENGINE = MEMORY + SELECT id ticketFk FROM myTicket + WHERE id = vSelf; + + CALL vn.ticketGetTax; + + SELECT IFNULL(SUM(taxableBase), 0.0), IFNULL(SUM(tax), 0.0) + INTO vTaxBase, vTax + FROM tmp.ticketAmount; + + SELECT t.id, t.landed, t.shipped, t.refFk, t.nickname, + ag.description agency, m.code method, + a.street, a.postalCode, a.city, p.name province, + vTaxBase taxBase, vTaxBase + vTax AS total + FROM tmp.ticket v + JOIN vn.ticket t ON t.id = v.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.agencyMode ag ON ag.id = t.agencyModeFk + LEFT JOIN vn.deliveryMethod m ON m.id = ag.deliveryMethodFk + LEFT JOIN vn.province p ON p.id = a.provinceFk + WHERE t.id = vSelf; + + DROP TEMPORARY TABLE + tmp.ticket, + tmp.ticketTax, + tmp.ticketAmount; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myTicket_getPackages` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myTicket_getPackages`(vSelf INT) +BEGIN +/** + * Returns a current user ticket packages. + * + * @param vSelf The ticket identifier + * @select The ticket packages + */ + SELECT i.image, im.updated, i.id, i.name, tp.quantity + FROM myTicket t + JOIN vn.ticketPackaging tp ON tp.ticketFk = t.id + JOIN vn.packaging p ON p.id = tp.packagingFk + JOIN vn.item i ON i.id = p.itemFk + LEFT JOIN image im + ON im.collectionFk = 'catalog' + AND im.name = i.image + WHERE t.id = vSelf; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myTicket_getRows` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myTicket_getRows`(vSelf INT) +BEGIN + SELECT r.itemFk, r.quantity, r.concept, r.price, r.discount, + i.category, i.size, i.stems, i.inkFk, + i.tag5, i.value5, i.tag6, i.value6, i.tag7, i.value7, + i.image, im.updated + FROM myTicketRow r + JOIN vn.item i ON i.id = r.itemFk + LEFT JOIN image im + ON im.collectionFk = 'catalog' + AND im.name = i.image + WHERE r.ticketFk = vSelf + ORDER BY r.concept; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myTicket_list` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myTicket_list`(vFrom DATE, vTo DATE) +BEGIN +/** + * Returns the current user list of tickets between two dates reange. + * Also returns the total price with tax of every ticket. + * + * @param vFrom From date, if %NULL current date minus 25 days + * @param vTo To date, if %NULL current date + * @select The tickets list + */ + SET vFrom = IFNULL(vFrom, DATE_FORMAT(TIMESTAMPADD(MONTH, -3, CURDATE()), '%Y-%m-01')); + SET vTo = IFNULL(vTo, TIMESTAMPADD(YEAR, 1, CURDATE())); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + (KEY (ticketFk)) + ENGINE = MEMORY + SELECT t.id ticketFk + FROM myTicket t + WHERE shipped BETWEEN TIMESTAMP(vFrom) AND TIMESTAMP(vTo, '23:59:59'); + + CALL vn.ticketGetTotal; + + SELECT v.id, IFNULL(v.landed, v.shipped) landed, + v.shipped, v.companyFk, v.nickname, + a.city, ag.description agency, t.total + FROM tmp.ticket i + JOIN vn.ticket v ON v.id = i.ticketFk + JOIN vn.address a ON a.id = v.addressFk + JOIN vn.agencyMode ag ON ag.id = v.agencyModeFk + JOIN tmp.ticketTotal t ON t.ticketFk = i.ticketFk + ORDER BY IFNULL(v.landed, v.shipped) DESC, i.ticketFk DESC; + + DROP TEMPORARY TABLE + tmp.ticket, + tmp.ticketTotal; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myTicket_logAccess` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myTicket_logAccess`(vSelf INT) +BEGIN +/** + * Logs an access to a ticket. + * + * @param vSelf The ticket identifier + */ + INSERT INTO vn.ticketLog + (originFk, userFk, `action`, description) + SELECT vSelf, account.userGetId(), 'select', 'Accede a ticket' + FROM myTicket t + WHERE t.id = vSelf; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myTpvTransaction_end` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myTpvTransaction_end`(vSelf INT, vStatus VARCHAR(12)) +BEGIN +/** + * Finaliza una transaccción estableciendo su estado a 'ok' o + * 'ko' en función de si esta se ha realizado correctamente. + * Este procedimiento debe ser llamado directamente por el cliente + * nada mas finalizar la transacción y solo tiene validez hasta que + * llega la notificacion definitiva desde el banco. + * + * @param vSelf El identificador de la transacción + * @param vStatus El estado, 'ok' o 'ko' + */ + IF vStatus IN ('ok', 'ko') + THEN + UPDATE myTpvTransaction SET status = vStatus + WHERE id = vSelf AND response IS NULL; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `myTpvTransaction_start` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `myTpvTransaction_start`(vAmount INT, vCompany INT) +BEGIN +/** + * Inicia una nueva transacción con el TPV virtual, generando + * un identificador de transacción y devolviendo con un SELECT + * los parámetros que deben enviarse a la URL del servicio web + * del banco. + * + * @param vAmount Cantidad a pagar en céntimos + * @param vCompany El identificador de la empresa + * + * @select Los parámetros que deben pasarse al banco + */ + DECLARE vSelf CHAR(12); + DECLARE vMerchant INT; + DECLARE vUrl VARCHAR(255); + DECLARE vKey VARCHAR(50); + DECLARE vTestMode BOOLEAN; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + IF vCompany IS NULL + THEN + SELECT companyFk INTO vCompany + FROM tpvMerchantEnable LIMIT 1; + END IF; + + SELECT merchantFk INTO vMerchant + FROM tpvMerchantEnable WHERE companyFk = vCompany; + + SELECT testMode INTO vTestMode + FROM tpvConfig; + + IF NOT vTestMode + THEN + SELECT c.url, m.secretKey INTO vUrl, vKey + FROM tpvMerchant m + JOIN tpvConfig c + WHERE m.id = vMerchant; + ELSE + SELECT testUrl, testKey INTO vUrl, vKey + FROM tpvConfig; + END IF; + + INSERT INTO myTpvTransaction + SET + merchantFk = vMerchant + ,clientFk = account.userGetId() + ,amount = vAmount; + + SET vSelf = LAST_INSERT_ID(); + + SELECT + vAmount amount + ,vSelf transactionId + ,vMerchant merchant + ,currency + ,transactionType + ,terminal + ,merchantUrl + ,vUrl url + ,vKey secretKey + FROM tpvConfig; + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_addItem` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_addItem`( + vSelf INT, + vWarehouse INT, + vItem INT, + vAmount INT) +BEGIN +/** + * Adds an item to the order, checking availability and grouping. + * + * @param vSelf The order id + * @param vWarehouse The warehouse id + * @param vItem The item id + * @param vAmount The amount to add + */ + DECLARE vRow INT; + DECLARE vAdd INT; + DECLARE vAvailable INT; + DECLARE vDone BOOL; + DECLARE vGrouping INT; + DECLARE vRate INT; + DECLARE vShipment DATE; + DECLARE vPrice DECIMAL(10,2); + DECLARE cur CURSOR FOR + SELECT `grouping`, price, rate + FROM tmp.ticketComponentPrice + WHERE warehouseFk = vWarehouse + AND itemFk = vItem + ORDER BY `grouping` DESC; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CALL order_calcCatalogFromItem(vSelf, vItem); + START TRANSACTION; + + SELECT shipped INTO vShipment + FROM tmp.zoneGetShipped + WHERE warehouseFk = vWarehouse; + + SELECT available INTO vAvailable + FROM tmp.ticketLot + WHERE warehouseFk = vWarehouse + AND itemFk = vItem; + + IF vAmount > IFNULL(vAvailable, 0) THEN + CALL util.throw ('ORDER_ROW_UNAVAILABLE'); + END IF; + + OPEN cur; + + l: LOOP + SET vDone = FALSE; + FETCH cur INTO vGrouping, vPrice, vRate; + + IF vDone THEN + LEAVE l; + END IF; + + SET vAdd = vAmount - MOD(vAmount, vGrouping); + SET vAmount = vAmount - vAdd; + + IF vAdd = 0 THEN + ITERATE l; + END IF; + + INSERT INTO orderRow SET + orderFk = vSelf, + itemFk = vItem, + warehouseFk = vWarehouse, + shipment = vShipment, + rate = vRate, + amount = vAdd, + price = vPrice; + + SET vRow = LAST_INSERT_ID(); + + INSERT INTO orderRowComponent (rowFk, componentFk, price) + SELECT vRow, c.componentFk, c.cost + FROM tmp.ticketComponent c + JOIN vn.component t + ON t.id = c.componentFk + AND (t.classRate IS NULL OR t.classRate = vRate) + WHERE c.warehouseFk = vWarehouse + AND c.itemFk = vItem; + END LOOP; + + CLOSE cur; + + IF vAmount > 0 THEN + CALL util.throw ('AMOUNT_NOT_MATCH_GROUPING'); + END IF; + + COMMIT; + CALL vn.ticketCalculatePurge; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_calcCatalog` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_calcCatalog`(vSelf INT) +BEGIN +/** + * Gets the availability and prices for order items. + * + * @param vSelf The order id + * @return tmp.ticketCalculateItem + * @return tmp.ticketComponentPrice + * @return tmp.ticketComponent + * @return tmp.ticketLot + */ + DECLARE vDate DATE; + DECLARE vAddress INT; + DECLARE vAgencyMode INT; + + SELECT date_send, address_id, agency_id + INTO vDate, vAddress, vAgencyMode + FROM `order` + WHERE id = vSelf; + + DROP TEMPORARY TABLE IF EXISTS tmp.item; + CREATE TEMPORARY TABLE tmp.item + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk FROM orderRow + WHERE orderFk = vSelf + GROUP BY itemFk; + + CALL vn.catalog_calculate(vDate, vAddress, vAgencyMode); + + DROP TEMPORARY TABLE tmp.item; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_calcCatalogFromItem` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_calcCatalogFromItem`(vSelf INT, vItem INT) +BEGIN +/** + * Gets the availability and prices for the given item + * using the order parameters. + * + * @param vSelf The order id + * @table tmp.item(itemFk) + * @return tmp.ticketCalculateItem + * @return tmp.ticketComponentPrice + * @return tmp.ticketComponent + * @return tmp.ticketLot + * @return tmp.zoneGetShipped + */ + DECLARE vDate DATE; + DECLARE vAddress INT; + DECLARE vAgencyMode INT; + + SELECT date_send, address_id, agency_id + INTO vDate, vAddress, vAgencyMode + FROM `order` + WHERE id = vSelf; + + CALL vn.catalog_calcFromItem(vDate, vAddress, vAgencyMode, vItem); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_calcCatalogFull` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_calcCatalogFull`(vSelf INT) +BEGIN +/** + * Gets the availability and prices for the given items + * using the order parameters. + * + * @param vSelf The order id + * @table tmp.item(itemFk) + * @return tmp.ticketCalculateItem + * @return tmp.ticketComponentPrice + * @return tmp.ticketComponent + * @return tmp.ticketLot + * @return tmp.zoneGetShipped + */ + DECLARE vDate DATE; + DECLARE vAddress INT; + DECLARE vAgencyMode INT; + + SELECT date_send, address_id, agency_id + INTO vDate, vAddress, vAgencyMode + FROM `order` + WHERE id = vSelf; + + CALL vn.catalog_calculate(vDate, vAddress, vAgencyMode); + + IF account.myUserGetName() = 'visitor' + THEN + DROP TEMPORARY TABLE tmp.ticketComponent; + UPDATE tmp.ticketCalculateItem SET price = NULL; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_checkConfig` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_checkConfig`(vSelf INT) +BEGIN +/** + * Comprueba que la configuración del pedido es correcta. + * + * @param vSelf Identificador del pedido + */ + DECLARE vDeliveryMethod VARCHAR(255); + DECLARE vLanded DATE; + DECLARE vAgencyMode INT; + DECLARE vAddress INT; + DECLARE vIsAvailable BOOL; + + -- Obtiene los datos del pedido + + SELECT d.code, o.date_send, o.agency_id, o.address_id + INTO vDeliveryMethod, vLanded, vAgencyMode, vAddress + FROM `order` o + JOIN vn.deliveryMethod d ON d.id = o.delivery_method_id + WHERE o.id = vSelf; + + -- Comprueba que se ha seleccionado una dirección + + IF vDeliveryMethod IN ('AGENCY', 'DELIVERY') + && vAddress IS NULL + THEN + CALL util.throw ('ORDER_EMPTY_ADDRESS'); + END IF; + + -- Comprueba que la agencia es correcta + + CALL vn.zoneGetAgency(vAddress, vLanded); + + SELECT COUNT(*) > 0 INTO vIsAvailable + FROM tmp.zoneGetAgency + WHERE agencyModeFk = vAgencyMode; + + IF !vIsAvailable THEN + CALL util.throw ('ORDER_INVALID_AGENCY'); + END IF; + + DROP TEMPORARY TABLE tmp.zoneGetAgency; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_confirm` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_confirm`(vSelf INT) +BEGIN +/** + * Confirms an order, creating each of its tickets on + * the corresponding date and store. + * + * @param vSelf The order identifier + */ + CALL order_confirmWithUser(vSelf, account.userGetId()); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_confirmWithUser` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_confirmWithUser`(IN `vOrder` INT, IN `vUserId` INT) +BEGIN +/** + * Confirms an order, creating each of its tickets on the corresponding + * date, store and user. + * + * @param vOrder The order identifier + * @param vUser The user identifier + */ + DECLARE vOk BOOL; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vWarehouse INT; + DECLARE vShipment DATETIME; + DECLARE vTicket INT; + DECLARE vNotes VARCHAR(255); + DECLARE vItem INT; + DECLARE vConcept VARCHAR(30); + DECLARE vAmount INT; + DECLARE vPrice DECIMAL(10,2); + DECLARE vSale INT; + DECLARE vRate INT; + DECLARE vRowId INT; + DECLARE vDelivery DATE; + DECLARE vAddress INT; + DECLARE vIsConfirmed BOOL; + DECLARE vClientId INT; + DECLARE vCompanyId INT; + DECLARE vAgencyModeId INT; + + DECLARE TICKET_FREE INT DEFAULT 2; + + DECLARE cDates CURSOR FOR + SELECT zgs.shipped, r.warehouse_id + FROM `order` o + JOIN order_row r ON r.order_id = o.id + LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouse_id + WHERE o.id = vOrder AND r.amount != 0 + GROUP BY r.warehouse_id; + + DECLARE cRows CURSOR FOR + SELECT r.id, r.item_id, a.Article, r.amount, r.price, r.rate + FROM order_row r + JOIN vn2008.Articles a ON a.Id_Article = r.item_id + WHERE r.amount != 0 + AND r.warehouse_id = vWarehouse + AND r.order_id = vOrder + ORDER BY r.rate DESC; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + -- Carga los datos del pedido + + SELECT o.date_send, o.address_id, o.note, + o.confirmed, cs.Id_Cliente, o.company_id, o.agency_id + INTO vDelivery, vAddress, vNotes, + vIsConfirmed, vClientId, vCompanyId, vAgencyModeId + FROM hedera.`order` o + JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = o.address_id + WHERE id = vOrder; + + -- Comprueba que el pedido no está confirmado + + IF vIsConfirmed THEN + CALL util.throw ('ORDER_ALREADY_CONFIRMED'); + END IF; + + -- Comprueba que el pedido no está vacío + + SELECT COUNT(*) > 0 INTO vOk + FROM order_row WHERE order_id = vOrder AND amount > 0; + + IF !vOk THEN + CALL util.throw ('ORDER_EMPTY'); + END IF; + + -- Carga las fechas de salida de cada almacén + + CALL vn.zoneGetShippedWarehouse (vDelivery, vAddress, vAgencyModeId); + + -- Trabajador que realiza la acción + + IF vUserId IS NULL THEN + SELECT employeeFk INTO vUserId FROM orderConfig; + END IF; + + -- Crea los tickets del pedido + + START TRANSACTION; + + OPEN cDates; + + lDates: + LOOP + SET vTicket = NULL; + SET vDone = FALSE; + FETCH cDates INTO vShipment, vWarehouse; + + IF vDone THEN + LEAVE lDates; + END IF; + + -- Busca un ticket existente que coincida con los parametros + + SELECT Id_Ticket INTO vTicket + FROM vn2008.Tickets t + LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket + JOIN `order` o + ON o.address_id = t.Id_Consigna + AND vWarehouse = t.warehouse_id + AND o.agency_id = t.Id_Agencia + AND t.landing = o.date_send + AND vShipment = DATE(t.Fecha) + WHERE o.id = vOrder + AND t.Factura IS NULL + AND IFNULL(tls.alertLevel,0) = 0 + AND t.Id_Cliente <> 1118 + LIMIT 1; + + -- Crea el ticket en el caso de no existir uno adecuado + + IF vTicket IS NULL + THEN + CALL vn.ticketCreateWithUser( + vClientId, + IFNULL(vShipment, CURDATE()), + vWarehouse, + vCompanyId, + vAddress, + vAgencyModeId, + NULL, + vDelivery, + vUserId, + vTicket + ); + ELSE + INSERT INTO vncontrol.inter + SET Id_Ticket = vTicket, + state_id = TICKET_FREE; + END IF; + + INSERT IGNORE INTO vn2008.order_Tickets + SET order_id = vOrder, + Id_Ticket = vTicket; + + -- Añade las notas + + IF vNotes IS NOT NULL AND vNotes != '' + THEN + INSERT INTO vn2008.ticket_observation SET + Id_Ticket = vTicket, + observation_type_id = 4 /* salesperson */ , + `text` = vNotes + ON DUPLICATE KEY UPDATE + `text` = CONCAT(VALUES(`text`),'. ', `text`); + END IF; + + -- Añade los movimientos y sus componentes + + OPEN cRows; + + lRows: + LOOP + SET vDone = FALSE; + FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate; + + IF vDone THEN + LEAVE lRows; + END IF; + + INSERT INTO vn2008.Movimientos + SET + Id_Article = vItem, + Id_Ticket = vTicket, + Concepte = vConcept, + Cantidad = vAmount, + Preu = vPrice, + CostFixat = 0, + PrecioFijado = TRUE; + + SET vSale = LAST_INSERT_ID(); + + INSERT INTO vn2008.Movimientos_componentes + (Id_Movimiento, Id_Componente, Valor) + SELECT vSale, cm.component_id, cm.price + FROM order_component cm + JOIN bi.tarifa_componentes tc + ON tc.Id_Componente = cm.component_id + WHERE cm.order_row_id = vRowId + GROUP BY vSale, cm.component_id; + + UPDATE order_row SET Id_Movimiento = vSale + WHERE id = vRowId; + + END LOOP; + + CLOSE cRows; + + -- Fija el coste + + DROP TEMPORARY TABLE IF EXISTS tComponents; + CREATE TEMPORARY TABLE tComponents + (INDEX (saleFk)) + ENGINE = MEMORY + SELECT SUM(mc.Valor) valueSum, mc.Id_Movimiento saleFk + FROM vn2008.Movimientos_componentes mc + JOIN bi.tarifa_componentes tc USING(Id_Componente) + JOIN bi.tarifa_componentes_series tcs + ON tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id + AND tcs.base + JOIN vn2008.Movimientos m + ON m.Id_Movimiento = mc.Id_Movimiento + WHERE m.Id_Ticket = vTicket + GROUP BY mc.Id_Movimiento; + + UPDATE vn2008.Movimientos m + JOIN tComponents mc ON mc.saleFk = m.Id_Movimiento + SET m.CostFixat = valueSum; + + DROP TEMPORARY TABLE tComponents; + END LOOP; + + CLOSE cDates; + + DELETE FROM basketOrder WHERE orderFk = vOrder; + UPDATE `order` SET confirmed = TRUE, confirm_date = NOW() + WHERE id = vOrder; + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_confirmWithUser__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_confirmWithUser__`(IN `vOrder` INT, IN `vUserId` INT) +BEGIN +/** + * Confirms an order, creating each of its tickets on the corresponding + * date, store and user. + * + * @param vOrder The order identifier + * @param vUser The user identifier + */ + DECLARE vOk BOOL; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vWarehouse INT; + DECLARE vShipment DATETIME; + DECLARE vTicket INT; + DECLARE vNotes VARCHAR(255); + DECLARE vItem INT; + DECLARE vConcept VARCHAR(30); + DECLARE vAmount INT; + DECLARE vPrice DECIMAL(10,2); + DECLARE vSale INT; + DECLARE vRate INT; + DECLARE vRowId INT; + DECLARE vDelivery DATE; + DECLARE vAddress INT; + DECLARE vIsConfirmed BOOL; + DECLARE vClientId INT; + DECLARE vCompanyId INT; + DECLARE vAgencyModeId INT; + + DECLARE TICKET_FREE INT DEFAULT 2; + DECLARE SYSTEM_WORKER INT DEFAULT 20; + + DECLARE cDates CURSOR FOR + SELECT zgs.shipped, r.warehouse_id + FROM `order` o + JOIN order_row r ON r.order_id = o.id + LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouse_id + WHERE o.id = vOrder AND r.amount != 0 + GROUP BY r.warehouse_id; + + DECLARE cRows CURSOR FOR + SELECT r.id, r.item_id, a.Article, r.amount, r.price, r.rate + FROM order_row r + JOIN vn2008.Articles a ON a.Id_Article = r.item_id + WHERE r.amount != 0 + AND r.warehouse_id = vWarehouse + AND r.order_id = vOrder + ORDER BY r.rate DESC; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + -- Carga los datos del pedido + + SELECT o.date_send, o.address_id, o.note, + o.confirmed, cs.Id_Cliente, o.company_id, o.agency_id + INTO vDelivery, vAddress, vNotes, + vIsConfirmed, vClientId, vCompanyId, vAgencyModeId + FROM hedera.`order` o + JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = o.address_id + WHERE id = vOrder; + + -- Comprueba que el pedido no está confirmado + + IF vIsConfirmed THEN + CALL util.throw ('ORDER_ALREADY_CONFIRMED'); + END IF; + + -- Comprueba que el pedido no está vacío + + SELECT COUNT(*) > 0 INTO vOk + FROM order_row WHERE order_id = vOrder AND amount > 0; + + IF !vOk THEN + CALL util.throw ('ORDER_EMPTY'); + END IF; + + -- Carga las fechas de salida de cada almacén + + CALL vn.zoneGetShippedWarehouse (vDelivery, vAddress, vAgencyModeId); + + -- Trabajador que realiza la acción + + IF vUserId IS NULL THEN + SELECT employeeFk INTO vUserId FROM orderConfig; + END IF; + + -- Crea los tickets del pedido + + START TRANSACTION; + + OPEN cDates; + + lDates: + LOOP + SET vTicket = NULL; + SET vDone = FALSE; + FETCH cDates INTO vShipment, vWarehouse; + + IF vDone THEN + LEAVE lDates; + END IF; + + -- Busca un ticket existente que coincida con los parametros + + SELECT Id_Ticket INTO vTicket + FROM vn2008.Tickets t + LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket + JOIN `order` o + ON o.address_id = t.Id_Consigna + AND vWarehouse = t.warehouse_id + AND o.agency_id = t.Id_Agencia + AND t.landing = o.date_send + AND vShipment = DATE(t.Fecha) + WHERE o.id = vOrder + AND t.Factura IS NULL + AND IFNULL(tls.alertLevel,0) = 0 + AND t.Id_Cliente <> 1118 + LIMIT 1; + + -- Crea el ticket en el caso de no existir uno adecuado + + IF vTicket IS NULL + THEN + CALL vn.ticketCreateWithUser( + vClientId, + IFNULL(vShipment, CURDATE()), + vWarehouse, + vCompanyId, + vAddress, + vAgencyModeId, + NULL, + vDelivery, + vUserId, + vTicket + ); + ELSE + INSERT INTO vncontrol.inter + SET Id_Ticket = vTicket, + Id_Trabajador = SYSTEM_WORKER, + state_id = TICKET_FREE; + END IF; + + INSERT IGNORE INTO vn2008.order_Tickets + SET order_id = vOrder, + Id_Ticket = vTicket; + + -- Añade las notas + + IF vNotes IS NOT NULL AND vNotes != '' + THEN + INSERT INTO vn2008.ticket_observation SET + Id_Ticket = vTicket, + observation_type_id = 4 /* salesperson */ , + `text` = vNotes + ON DUPLICATE KEY UPDATE + `text` = CONCAT(VALUES(`text`),'. ', `text`); + END IF; + + -- Añade los movimientos y sus componentes + + OPEN cRows; + + lRows: + LOOP + SET vDone = FALSE; + FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate; + + IF vDone THEN + LEAVE lRows; + END IF; + + INSERT INTO vn2008.Movimientos + SET + Id_Article = vItem, + Id_Ticket = vTicket, + Concepte = vConcept, + Cantidad = vAmount, + Preu = vPrice, + CostFixat = 0, + PrecioFijado = TRUE; + + SET vSale = LAST_INSERT_ID(); + + INSERT INTO vn2008.Movimientos_componentes + (Id_Movimiento, Id_Componente, Valor) + SELECT vSale, cm.component_id, cm.price + FROM order_component cm + JOIN bi.tarifa_componentes tc + ON tc.Id_Componente = cm.component_id + WHERE cm.order_row_id = vRowId + GROUP BY vSale, cm.component_id; + + UPDATE order_row SET Id_Movimiento = vSale + WHERE id = vRowId; + + END LOOP; + + CLOSE cRows; + + -- Fija el coste + + DROP TEMPORARY TABLE IF EXISTS tComponents; + CREATE TEMPORARY TABLE tComponents + (INDEX (saleFk)) + ENGINE = MEMORY + SELECT SUM(mc.Valor) valueSum, mc.Id_Movimiento saleFk + FROM vn2008.Movimientos_componentes mc + JOIN bi.tarifa_componentes tc USING(Id_Componente) + JOIN bi.tarifa_componentes_series tcs + ON tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id + AND tcs.base + JOIN vn2008.Movimientos m + ON m.Id_Movimiento = mc.Id_Movimiento + WHERE m.Id_Ticket = vTicket + GROUP BY mc.Id_Movimiento; + + UPDATE vn2008.Movimientos m + JOIN tComponents mc ON mc.saleFk = m.Id_Movimiento + SET m.CostFixat = valueSum; + + DROP TEMPORARY TABLE tComponents; + END LOOP; + + CLOSE cDates; + + DELETE FROM basketOrder WHERE orderFk = vOrder; + UPDATE `order` SET confirmed = TRUE, confirm_date = NOW() + WHERE id = vOrder; + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_doRecalc` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_doRecalc`() +proc: BEGIN +/** + * Recalculates modified orders. + */ + DECLARE vDone BOOL; + DECLARE vOrderFk INT; + + DECLARE cCur CURSOR FOR + SELECT orderFk FROM orderRecalc; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('hedera.order_doRecalc'); + ROLLBACK; + RESIGNAL; + END; + + IF !GET_LOCK('hedera.order_doRecalc', 0) THEN + LEAVE proc; + END IF; + + OPEN cCur; + + myLoop: LOOP + SET vDone = FALSE; + FETCH cCur INTO vOrderFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + START TRANSACTION; + CALL order_recalc(vOrderFk); + COMMIT; + + DELETE FROM orderRecalc WHERE orderFk = vOrderFk; + END LOOP; + + CLOSE cCur; + DO RELEASE_LOCK('hedera.order_doRecalc'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_getAvailable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_getAvailable`(vSelf INT) +BEGIN +/** + * Gets the available items list. + * + * @param vSelf The order id + * @table tmp.itemAvailable + */ + DECLARE vDelivery DATE; + DECLARE vAddress INT; + DECLARE vAgencyMode INT; + + SELECT date_send, address_id, agency_id + INTO vDelivery, vAddress, vAgencyMode + FROM `order` + WHERE id = vSelf; + + CALL vn.available_calc(vDelivery, vAddress, vAgencyMode); + + DROP TEMPORARY TABLE IF EXISTS tmp.itemAvailable; + CREATE TEMPORARY TABLE tmp.itemAvailable + (INDEX (id)) + ENGINE = MEMORY + SELECT DISTINCT a.item_id id + FROM `cache`.available a + JOIN tmp.availableCalc c ON c.calcFk = a.calc_id + WHERE a.available > 0; + + DROP TEMPORARY TABLE tmp.availableCalc; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_getTax` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_getTax`() + READS SQL DATA +BEGIN +/** + * Calcula el IVA, y el recargo de equivalencia de un pedido + * desglosados por tipos. + * + * @param vOrder El identificador del pedido + * @return tmp.orderTax Bases imponibles, IVA y recargo de equivalencia + */ + DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; + CREATE TEMPORARY TABLE tmp.addressCompany + (INDEX (addressFk, companyFk)) + ENGINE = MEMORY + SELECT DISTINCT o.address_id addressFk, o.company_id companyFk + FROM tmp.`order` tmpOrder + JOIN hedera.`order` o ON o.id = tmpOrder.orderFk; + + CALL vn.addressTaxArea; + + -- Calcula el IVA y el recargo desglosado. + + DROP TEMPORARY TABLE IF EXISTS tmp.orderTax; + CREATE TEMPORARY TABLE tmp.orderTax + (INDEX (orderFk)) + ENGINE = MEMORY + SELECT o.id orderFk, + tc.code, + SUM(m.amount * m.price) taxableBase, + pgc.rate + FROM tmp.`order` tmpOrder + JOIN `order` o ON o.id = tmpOrder.orderFk + JOIN orderRow m ON m.orderFk = o.id + JOIN vn.item i ON i.id = m.itemFk + JOIN vn.`client` c ON c.id = o.customer_id + JOIN vn.supplier s ON s.id = o.company_id + JOIN tmp.addressTaxArea ata + ON ata.addressFk = o.address_id AND ata.companyFk = o.company_id + JOIN vn.itemTaxCountry itc + ON itc.itemFk = i.id AND itc.countryFk = s.countryFk + JOIN vn.bookingPlanner bp + ON bp.countryFk = s.countryFk + AND bp.taxAreaFk = ata.areaFk + AND bp.taxClassFk = itc.taxClassFk + JOIN vn.pgc ON pgc.`code` = bp.pgcFk + JOIN vn.taxClass tc ON tc.id = bp.taxClassFk + GROUP BY tmpOrder.orderFk, pgc.`code`, pgc.rate + HAVING taxableBase != 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.orderAmount; + CREATE TEMPORARY TABLE tmp.orderAmount + (INDEX (orderFk)) + ENGINE = MEMORY + SELECT orderFk, taxableBase, `code`, + SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax + FROM tmp.orderTax + GROUP BY orderFk, `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 DROP PROCEDURE IF EXISTS `order_getTotal` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_getTotal`() +BEGIN +/** + * Calcula el total con IVA para un conjunto de orders. + * + * @table tmp.order(orderFk) Identificadores de las ordenes a calcular + * @return tmp.orderTotal Total para cada orden + */ + CALL order_getTax; + + DROP TEMPORARY TABLE IF EXISTS tmp.orderTotal; + CREATE TEMPORARY TABLE tmp.orderTotal + (INDEX (orderFk)) + ENGINE = MEMORY + SELECT o.orderFk, IFNULL(SUM(ot.taxableBase + ot.tax), 0.0) AS total + FROM tmp.`order` o + LEFT JOIN tmp.orderAmount ot ON o.orderFk = ot.orderFk + GROUP BY orderFk; + + DROP TEMPORARY TABLE + tmp.orderTax, + tmp.orderAmount; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_recalc` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_recalc`(vSelf INT) +BEGIN +/** + * Recalculates the order total. + * + * @param vSelf The order id + */ + DECLARE vTaxableBase DECIMAL(10,2); + DECLARE vTax DECIMAL(10,2); + + DROP TEMPORARY TABLE IF EXISTS tmp.`order`; + CREATE TEMPORARY TABLE tmp.`order` + ENGINE = MEMORY + SELECT vSelf orderFk; + + CALL order_getTax; + + SELECT IFNULL(SUM(taxableBase), 0.0), IFNULL(SUM(tax), 0.0) + INTO vTaxableBase, vTax + FROM tmp.orderAmount; + + UPDATE `order` + SET taxableBase = vTaxableBase, + tax = vTax, + total = vTaxableBase + vTax + WHERE id = vSelf; + + DROP TEMPORARY TABLE + tmp.`order`, + tmp.orderTax; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_requestRecalc` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_requestRecalc`(vSelf INT) +proc: BEGIN +/** + * Adds a request to recalculate the order total. + * + * @param vSelf The order identifier + */ + IF vSelf IS NULL THEN + LEAVE proc; + END IF; + + INSERT IGNORE INTO orderRecalc SET orderFk = vSelf; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `order_update` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `order_update`(vSelf INT) +proc: BEGIN +/** + * Actualiza las líneas de un pedido. + * + * @param vSelf Id del pedido + */ + DECLARE vDate DATE; + DECLARE vAddress INT; + DECLARE vAgencyMode INT; + DECLARE vNRows INT; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT COUNT(*) INTO vNRows + FROM orderRow WHERE orderFk = vSelf; + + IF vNRows > 0 + THEN + CALL order_calcCatalog(vSelf); + + DELETE c + FROM orderRow r + JOIN orderRowComponent c ON c.rowFk = r.id + WHERE r.orderFk = vSelf; + + UPDATE orderRow r + LEFT JOIN tmp.ticketComponentPrice p + ON p.warehouseFk = r.warehouseFk + AND p.itemFk = r.itemFk + AND p.rate = r.rate + LEFT JOIN tmp.zoneGetShipped t + ON t.warehouseFk = r.warehouseFk + SET + r.price = p.price, + r.amount = IF(p.itemFk IS NOT NULL, + r.amount + IF(@m := MOD(r.amount, p.`grouping`), p.`grouping` - @m, 0), 0), + r.shipment = t.shipped + WHERE r.orderFk = vSelf; + + INSERT INTO orderRowComponent(rowFk, componentFk, price) + SELECT r.id, c.componentFk, c.cost + FROM orderRow r + JOIN tmp.ticketComponent c + ON c.warehouseFk = r.warehouseFk + AND c.itemFk = r.itemFk + JOIN vn.component t + ON t.id = c.componentFk + AND (t.classRate IS NULL OR t.classRate = r.rate) + WHERE r.orderFk = vSelf; + + CALL vn.ticketCalculatePurge; + END IF; + + UPDATE `order` SET date_make = NOW() + WHERE id = vSelf; + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `survey_vote` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `survey_vote`(vAnswer INT) +BEGIN + DECLARE vSurvey INT; + DECLARE vCount TINYINT; + DECLARE EXIT HANDLER FOR 1062 + CALL util.throw('You cannot vote twice to the same survey'); + + SELECT durveyFk INTO vSurvey + FROM surveyAnswer WHERE id = vAnswer; + + INSERT INTO surveyVote SET + surveyFk = vSurvey, + userFk = account.userGetId(); + + UPDATE surveyAnswer SET votes = votes + 1 + WHERE id = vAnswer; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `tpvTransaction_confirm` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransaction_confirm`( + vAmount INT + ,vOrder INT + ,vMerchant INT + ,vCurrency INT + ,vResponse INT + ,vErrorCode VARCHAR(10) +) +BEGIN +/** + * Confirma una transacción previamente iniciada, reescribiendo + * sus datos por los confirmados por el banco (solo si estos difieren). + * Genera el recibo y su correspondiente entrada en caja. + * + * @param vAmount Cantidad confirmada + * @param vOrder Identificador de transacción + * @param vMerchant Identificador de comercio + * @param vCurrency Identificador de moneda + * @param vResponse Identificador de respuesta del banco + * @param vErrorCode Código de error del banco, si lo hubiera + */ + DECLARE vReceipt INT; + DECLARE vStatus VARCHAR(10); + DECLARE vCustomer INT; + DECLARE vBank INT; + DECLARE vCompany INT; + DECLARE vEmployee INT; + DECLARE vIsDuplicated BOOLEAN; + DECLARE vDate DATE; + DECLARE vConcept VARCHAR(25) DEFAULT 'Cobro Web'; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT COUNT(*) > 0 INTO vIsDuplicated + FROM tpvTransaction + WHERE id = vOrder AND response IS NOT NULL + FOR UPDATE; + + IF vIsDuplicated + THEN + CALL util.throw ('TRANSACTION_DUPLICATED'); + END IF; + + IF vResponse BETWEEN 0 AND 99 + THEN + SELECT + t.clientFk + ,m.bankFk + ,m.companyFk + ,c.employeeFk + ,DATE(t.created) + INTO + vCustomer + ,vBank + ,vCompany + ,vEmployee + ,vDate + FROM tpvMerchant m + JOIN tpvConfig c ON c.id = 1 + LEFT JOIN tpvTransaction t ON t.id = vOrder + WHERE m.id = vMerchant; + + INSERT INTO vn.receipt + SET + amountPaid = vAmount / 100 + ,payed = vDate + ,workerFk = vEmployee + ,bankFk = vBank + ,clientFk = vCustomer + ,companyFk = vCompany + ,invoiceFk = vConcept + ,isConciliate = TRUE; + + SET vReceipt = LAST_INSERT_ID(); + SET vStatus = 'ok'; + + -- Código redundante + + DO vn2008.till_entry + ( + vCustomer + ,vBank + ,vAmount / 100 + ,vConcept + ,vDate + ,'A' + ,TRUE + ,vCustomer + ,vCompany + ,vEmployee + ); + ELSE + SET vReceipt = NULL; + SET vStatus = 'ko'; + END IF; + + UPDATE tpvTransaction + SET + merchantFk = vMerchant + ,receiptFk = vReceipt + ,amount = vAmount + ,response = vResponse + ,errorCode = vErrorCode + ,status = vStatus + WHERE id = vOrder; + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `tpvTransaction_confirmAll` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransaction_confirmAll`(vDate DATE) +BEGIN +/** + * Confirma todas las transacciones confirmadas por el cliente pero no + * por el banco para una fecha dada. + * + * @param vDate Fecha deseada + */ + DECLARE vOrder INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; + DECLARE vDateIni DATETIME DEFAULT TIMESTAMP(vDate, '00:00:00'); + DECLARE vDateEnd DATETIME DEFAULT TIMESTAMP(vDate, '23:59:59'); + + DECLARE cTransactions CURSOR FOR + SELECT id + FROM tpvTransaction + WHERE created BETWEEN vDateIni AND vDateEnd + AND status = 'ok' + AND response IS NULL; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN cTransactions; + + l: LOOP + FETCH cTransactions INTO vOrder; + + IF vDone THEN + LEAVE l; + END IF; + + CALL tpvTransaction_confirmById (vOrder); + END LOOP l; + + CLOSE cTransactions; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `tpvTransaction_confirmById` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransaction_confirmById`(vOrder INT) +BEGIN +/** + * Confirma manualmente una transacción espedificando su identificador. + * + * @param vOrder Identificador de la transacción + */ + DECLARE vAmount INT; + DECLARE vMerchant INT; + DECLARE vCurrency INT; + + SELECT amount, merchantFk, currency + INTO vAmount, vMerchant, vCurrency + FROM tpvTransaction t + JOIN tpvMerchant m ON m.id = t.merchantFk + JOIN tpvConfig c + WHERE t.id = vOrder; + + CALL tpvTransaction_confirm( + vAmount + ,vOrder + ,vMerchant + ,vCurrency + ,0 + ,NULL + ); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `tpvTransaction_undo` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransaction_undo`(vSelf INT) +BEGIN + DECLARE vCustomer INT; + DECLARE vAmount DOUBLE; + DECLARE vReceipt INT; + DECLARE vDate DATE; + DECLARE vBank INT; + DECLARE vAccount VARCHAR(12); + DECLARE vSubaccount VARCHAR(12); + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT + t.clientFk + ,t.amount / 100 + ,t.receiptFk + ,DATE(t.created) + ,m.bankFk + INTO + vCustomer + ,vAmount + ,vReceipt + ,vDate + ,vBank + FROM tpvTransaction t + JOIN tpvMerchant m ON m.id = t.merchantFk + JOIN tpvConfig c + WHERE t.id = vSelf + FOR UPDATE; + + -- Elimina el recibo + + DELETE FROM vn2008.Recibos + WHERE Id = vReceipt LIMIT 1; + + -- Elimina la entrada de cajas + + DELETE FROM vn2008.Cajas + WHERE Id_Banco = vBank + AND DATE(CajaFecha) = vDate + AND Entrada = vAmount + LIMIT 1; + + -- Elimina los asientos contables + + SELECT Cuenta INTO vSubaccount + FROM vn2008.Clientes WHERE Id_Cliente = vCustomer; + + SELECT Cuenta INTO vAccount + FROM vn2008.Bancos WHERE Id_Banco = vBank; + + DELETE FROM vn2008.XDiario + WHERE SUBCTA = vSubaccount + AND CONTRA = vAccount + AND DATE(FECHA) = vDate + AND EUROHABER = vAmount + LIMIT 1; + + DELETE FROM vn2008.XDiario + WHERE CONTRA = vSubaccount + AND SUBCTA = vAccount + AND DATE(FECHA) = vDate + AND EURODEBE = vAmount + LIMIT 1; + + -- Actualiza la transaccion + + UPDATE tpvTransaction + SET response = NULL, status = 'started' + WHERE id = vSelf; + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `visitUser_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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `visitUser_new`( + vAccess INT + ,vSsid VARCHAR(64) +) +BEGIN + DECLARE vUserVisit INT; + + INSERT INTO visitUser SET + accessFk = vAccess, + userFk = account.userGetId(); + + SET vUserVisit = LAST_INSERT_ID(); + + UPDATE userSession SET userVisitFk = vUserVisit + WHERE ssid = vSsid; + + DELETE FROM userSession + WHERE lastUpdate < TIMESTAMPADD(HOUR, -1, NOW()); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `visit_listByBrowser` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `visit_listByBrowser`(vFrom DATE, vTo DATE) +BEGIN +/** + * Lists visits grouped by browser. + * + * @param vFrom The from date + * @param vTo The to date + * @select The list of visits + */ + SELECT browser, + MIN(CAST(version AS DECIMAL(4, 1))) minVersion, + MAX(CAST(version AS DECIMAL(4, 1))) maxVersion, + MAX(c.stamp) lastVisit, + COUNT(DISTINCT c.id) visits, + SUM(a.firstAccessFk = c.id AND v.firstAgentFk = a.id) newVisits + FROM visitUser e + JOIN visitAccess c ON c.id = e.accessFk + JOIN visitAgent a ON a.id = c.agentFk + JOIN visit v ON v.id = a.visitFk + WHERE c.stamp BETWEEN TIMESTAMP(vFrom,'00:00:00') AND TIMESTAMP(vTo,'23:59:59') + GROUP BY browser ORDER BY visits DESC; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `visit_register` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `visit_register`( + vVisit INT + ,vPlatform VARCHAR(30) + ,vBrowser VARCHAR(30) + ,vVersion VARCHAR(15) + ,vJavascript TINYINT + ,vCookies TINYINT + ,vAgent VARCHAR(255) + ,vIp INT + ,vReferer VARCHAR(255) +) +BEGIN + DECLARE vFirstVisit TINYINT DEFAULT FALSE; + DECLARE vFirstAgent TINYINT DEFAULT FALSE; + DECLARE vAgentId INT DEFAULT NULL; + DECLARE vAccessId INT DEFAULT NULL; + + -- Registers the visit + + IF vVisit IS NULL || (SELECT COUNT(*) FROM visit WHERE id = vVisit) = 0 + THEN + INSERT INTO visit SET id = DEFAULT; + SET vVisit = LAST_INSERT_ID(); + SET vFirstVisit = TRUE; + END IF; + + SELECT id INTO vAgentId FROM visitAgent + WHERE visitFk = vVisit + AND (agent = vAgent OR (vAgent IS NULL AND agent IS NULL)) + LIMIT 1; + + -- Registers the user agent + + IF vAgentId IS NULL + THEN + INSERT INTO visitAgent SET + visitFk = vVisit + ,platform = vPlatform + ,browser = vBrowser + ,version = vVersion + ,javascript = vJavascript + ,cookies = vCookies + ,agent = vAgent; + + SET vAgentId = LAST_INSERT_ID(); + SET vFirstAgent = TRUE; + END IF; + + IF vFirstVisit + THEN + UPDATE visit SET firstAgentFk = vAgentId + WHERE id = vVisit; + END IF; + + -- Registers the user access + + INSERT INTO visitAccess SET + agentFk = vAgentId + ,ip = vIp + ,referer = vReferer; + + SET vAccessId = LAST_INSERT_ID(); + + IF vFirstAgent + THEN + UPDATE visitAgent SET firstAccessFk = vAccessId + WHERE id = vAgentId; + END IF; + + -- Returns the visit info + + SELECT vVisit visit, vAccessId access; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Current Database: `nst` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `nst` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; + +USE `nst`; + +-- +-- Table structure for table `balance` +-- + +DROP TABLE IF EXISTS `balance`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `balance` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `lft` int(11) NOT NULL, + `rgt` int(11) NOT NULL, + `name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `lft_UNIQUE` (`lft`), + UNIQUE KEY `rgt_UNIQUE` (`rgt`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `geo` +-- + +DROP TABLE IF EXISTS `geo`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `geo` ( + `id` int(11) NOT NULL, + `lft` int(11) DEFAULT NULL, + `rgt` int(11) DEFAULT NULL, + `depth` int(11) DEFAULT NULL, + `sons` int(11) DEFAULT NULL, + `item` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `lft_UNIQUE` (`lft`), + UNIQUE KEY `rgt_UNIQUE` (`rgt`), + CONSTRAINT `nst_geo_id` FOREIGN KEY (`id`) REFERENCES `nst` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `labourTree` +-- + +DROP TABLE IF EXISTS `labourTree`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `labourTree` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `lft` int(11) NOT NULL, + `rgt` int(11) NOT NULL, + `depth` int(11) NOT NULL DEFAULT '0', + `sons` int(11) NOT NULL DEFAULT '0', + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=92 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `nst` +-- + +DROP TABLE IF EXISTS `nst`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `nst` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `lft` int(11) NOT NULL, + `rgt` int(11) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `lft_UNIQUE` (`lft`), + UNIQUE KEY `rgt_UNIQUE` (`rgt`) +) ENGINE=InnoDB AUTO_INCREMENT=6681 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'nst' +-- + +-- +-- Dumping routines for database 'nst' +-- +/*!50003 DROP PROCEDURE IF EXISTS `nodeAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nodeAdd`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45), IN `vParentFk` INT, IN `vChild` VARCHAR(100)) +BEGIN + DECLARE vSql TEXT; + DECLARE vTableClone VARCHAR(45); + + SET vTableClone = CONCAT(vTable, 'Clone'); + + CALL util.exec(CONCAT('DROP TEMPORARY TABLE IF EXISTS tmp.', vTableClone)); + CALL util.exec(CONCAT( + 'CREATE TEMPORARY TABLE tmp.', vTableClone, + ' ENGINE = MEMORY', + ' SELECT * FROM ', vScheme, '.', vTable + )); + + CALL util.exec(CONCAT( + 'SELECT COUNT(c.id) INTO @childs', + ' FROM ', vScheme, '.', vTable, ' p', + ' LEFT JOIN tmp.', vTableClone, ' c ON c.depth = p.depth + 1', + ' AND c.lft BETWEEN p.lft AND p.rgt AND c.id != ', vParentFk, + ' WHERE p.id = ', vParentFk + )); + + IF @childs = 0 THEN + CALL util.exec(CONCAT( + 'SELECT lft, depth INTO @vLeft, @vDepth', + ' FROM ', vScheme, '.', vTable, + ' WHERE id = ', vParentFk + )); + ELSE + CALL util.exec(CONCAT( + 'SELECT c.rgt, p.depth INTO @vLeft, @vDepth', + ' FROM ', vScheme, '.', vTable, ' p', + ' JOIN tmp.', vTableClone, ' c ON c.depth = p.depth + 1' + ' AND c.lft BETWEEN p.lft AND p.rgt', + ' WHERE p.id = ', vParentFk, + ' ORDER BY c.lft', + ' DESC LIMIT 1' + )); + END IF; + + CALL util.exec(CONCAT( + 'UPDATE ', vScheme, '.', vTable, ' SET rgt = rgt + 2', + ' WHERE rgt > @vLeft', + ' ORDER BY rgt DESC' + )); + CALL util.exec(CONCAT( + 'UPDATE ', vScheme, '.', vTable, ' SET lft = lft + 2', + ' WHERE lft > @vLeft', + ' ORDER BY lft DESC' + )); + + SET vChild = REPLACE(vChild, "'", "\\'"); + + CALL util.exec(CONCAT( + 'INSERT INTO ', vScheme, '.', vTable, ' (name, lft, rgt, depth)', + ' VALUES ("', vChild, '", @vLeft + 1, @vLeft + 2, @vDepth + 1)' + )); + + CALL util.exec(CONCAT('DROP TEMPORARY TABLE tmp.', vTableClone)); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nodeDelete` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nodeDelete`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45), IN `vNodeId` INT) +BEGIN + DECLARE vMyRight INT; + DECLARE vMyLeft INT; + DECLARE vMyWidth INT; + + CALL util.exec(CONCAT( + 'SELECT t.rgt, t.lft, t.rgt - t.lft + 1', + ' INTO @vMyRight, @vMyLeft, @vMyWidth', + ' FROM ', vScheme, '.', vTable, ' t', + ' WHERE t.id = ', vNodeId + )); + + CALL util.exec(CONCAT( + 'DELETE FROM ', vScheme, '.', vTable, + ' WHERE lft BETWEEN @vMyLeft AND @vMyRight' + )); + + CALL util.exec(CONCAT( + 'UPDATE ', vScheme, '.', vTable, ' SET rgt = rgt - @vMyWidth' + ' WHERE rgt > @vMyRight ORDER BY rgt' + )); + + CALL util.exec(CONCAT( + 'UPDATE ', vScheme, '.', vTable, ' SET lft = lft - @vMyWidth' + ' WHERE lft > @vMyRight ORDER BY lft' + )); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nodeMove` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nodeMove`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45), IN `vNodeId` INT, IN `vFatherId` INT) +BEGIN + -- Averiguamos el ancho de la rama + CALL util.exec (sql_printf ( + 'SELECT t.rgt - t.lft +1 INTO @vMyWidth FROM %t.%t t WHERE t.id = %v' + ,vScheme + ,vTable + ,vNodeId + )); + + -- Averiguamos la posicion del nuevo padre + + CALL util.exec (sql_printf ( + 'SELECT t.rgt, t.lft INTO @vFatherRight , @vFatherLeft FROM %t.%t t WHERE t.id = %v' + ,vScheme + ,vTable + ,vFatherId + )); + + -- 1º Incrementamos los valores de todos los nodos a la derecha del punto de inserción (vFatherRight) , para hacer sitio + + CALL util.exec (sql_printf ( + 'UPDATE %t.%t SET rgt = rgt + @vMyWidth WHERE rgt >= @vFatherRight ORDER BY rgt DESC' + ,vScheme + ,vTable + )); + + CALL util.exec (sql_printf ( + 'UPDATE %t.%t SET lft = lft + @vMyWidth WHERE lft >= @vFatherRight ORDER BY lft DESC' + ,vScheme + ,vTable + )); + + -- Es preciso recalcular los valores del nodo en el caso de que estuviera a la derecha del nuevo padre + + CALL util.exec (sql_printf ( + 'SELECT t.rgt, t.lft, @vFatherRight - t.lft INTO @vMyRight, @vMyLeft, @vGap FROM %t.%t t WHERE t.id = %v' + ,vScheme + ,vTable + ,vNodeId + )); + -- 2º Incrementamos el valor de todos los nodos a trasladar hasta alcanzar su nueva posicion + + CALL util.exec (sql_printf ( + 'UPDATE %t.%t SET lft = lft + @vGap WHERE lft BETWEEN @vMyLeft AND @vMyRight ORDER BY lft DESC' + ,vScheme + ,vTable + )); + CALL util.exec (sql_printf ( + 'UPDATE %t.%t SET rgt = rgt + @vGap WHERE rgt BETWEEN @vMyLeft AND @vMyRight ORDER BY rgt DESC' + ,vScheme + ,vTable + )); + + -- 3º Restaremos a todos los nodos resultantes, a la derecha de la posicion arrancada el ancho de la rama escindida + + CALL util.exec (sql_printf ( + 'UPDATE %t.%t SET lft = lft - @vMyWidth WHERE lft > @vMyLeft ORDER BY lft' + ,vScheme + ,vTable + )); + CALL util.exec (sql_printf ( + 'UPDATE %t.%t SET rgt = rgt - @vMyWidth WHERE rgt > @vMyRight ORDER BY rgt' + ,vScheme + ,vTable + )); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nodeRecalc` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nodeRecalc`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45)) +BEGIN + CALL util.exec(CONCAT ( + 'UPDATE ', vScheme, '.', vTable, ' d', + ' JOIN (SELECT', + ' node.id,', + ' COUNT(parent.id) - 1 as depth,', + ' cast((node.rgt - node.lft - 1) / 2 as DECIMAL) as sons', + ' FROM ', + ' ', vScheme, '.', vTable, ' AS node,', + ' ', vScheme, '.', vTable, ' AS parent', + ' WHERE node.lft BETWEEN parent.lft AND parent.rgt', + ' GROUP BY node.id', + ' ORDER BY node.lft) n ON n.id = d.id ', + ' SET d.`depth` = n.depth, d.sons = n.sons' + )); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nodeTree` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nodeTree`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45), IN `vGap` INT, IN `vShouldShow` BOOLEAN) +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.nest; + CALL util.exec (sql_printf ( + 'CREATE TEMPORARY TABLE tmp.nest + SELECT node.id + ,CONCAT( REPEAT(REPEAT(" ",%v), COUNT(parent.id) - 1), node.name) AS name + ,node.lft + ,node.rgt + ,COUNT(parent.id) - 1 as depth + ,cast((node.rgt - node.lft - 1) / 2 as DECIMAL) as sons + FROM %t.%t AS node, + %t.%t AS parent + WHERE node.lft BETWEEN parent.lft AND parent.rgt + GROUP BY node.id + ORDER BY node.lft' + ,vGap + ,vScheme + ,vTable + ,vScheme + ,vTable + )); + + IF vShouldShow THEN + SELECT * FROM tmp.nest; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nodeTree_pako` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nodeTree_pako`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45), IN `vGap` INT, IN `vShouldShow` BOOLEAN) +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.nest; + CALL util.exec (sql_printf ( + 'CREATE TEMPORARY TABLE tmp.nest + SELECT node.id + ,CONCAT( REPEAT(REPEAT(" ",%v), COUNT(parent.id) - 1), node.name) AS name + ,node.lft + ,node.rgt + ,COUNT(parent.id) - 1 as depth + ,cast((node.rgt - node.lft - 1) / 2 as DECIMAL) as sons + ,node.isSelected + FROM %t.%t AS node, + %t.%t AS parent + WHERE node.lft BETWEEN parent.lft AND parent.rgt + GROUP BY node.id + ORDER BY node.lft' + ,vGap + ,vScheme + ,vTable + ,vScheme + ,vTable + )); + + IF vShouldShow THEN + SELECT * FROM tmp.nest; + 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 */ ; + +-- +-- Current Database: `pbx` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `pbx` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; + +USE `pbx`; + +-- +-- Table structure for table `blacklist` +-- + +DROP TABLE IF EXISTS `blacklist`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `blacklist` ( + `phone` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`phone`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Hangup input calls from this list'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`blacklist_beforeInsert` + BEFORE INSERT ON `blacklist` + FOR EACH ROW +BEGIN + CALL phone_isValid(NEW.phone); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`blacklist_berforeUpdate` + BEFORE UPDATE ON `blacklist` + FOR EACH ROW +BEGIN + CALL phone_isValid(NEW.phone); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `cdr` +-- + +DROP TABLE IF EXISTS `cdr`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cdr` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `call_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `clid` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `src` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `dst` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `dcontext` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `channel` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `dst_channel` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `last_app` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `last_data` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `duration` int(11) NOT NULL DEFAULT '0', + `billsec` int(11) NOT NULL DEFAULT '0', + `disposition` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `ama_flags` int(11) NOT NULL DEFAULT '0', + `account_code` varchar(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `unique_id` varchar(32) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `user_field` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + PRIMARY KEY (`id`), + KEY `calldate` (`call_date`), + KEY `dst` (`dst`), + KEY `accountcode` (`account_code`), + KEY `dstchannel` (`dst_channel`), + KEY `disposition` (`disposition`), + KEY `src` (`src`) +) ENGINE=InnoDB AUTO_INCREMENT=321003 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `cdrConf` +-- + +DROP TABLE IF EXISTS `cdrConf`; +/*!50001 DROP VIEW IF EXISTS `cdrConf`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `cdrConf` AS SELECT + 1 AS `calldate`, + 1 AS `clid`, + 1 AS `src`, + 1 AS `dst`, + 1 AS `dcontext`, + 1 AS `channel`, + 1 AS `dstchannel`, + 1 AS `lastapp`, + 1 AS `lastdata`, + 1 AS `duration`, + 1 AS `billsec`, + 1 AS `disposition`, + 1 AS `amaflags`, + 1 AS `accountcode`, + 1 AS `uniqueid`, + 1 AS `userfield`*/; +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 */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `config` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `sundayFestive` tinyint(4) NOT NULL, + `countryPrefix` varchar(20) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `followme` +-- + +DROP TABLE IF EXISTS `followme`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `followme` ( + `extension` varchar(128) CHARACTER SET utf8 NOT NULL, + `phone` varchar(20) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`extension`), + CONSTRAINT `followme_ibfk_1` FOREIGN KEY (`extension`) REFERENCES `sip` (`extension`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`followme_beforeInsert` + BEFORE INSERT ON `followme` + FOR EACH ROW +BEGIN + CALL pbx.phone_isValid(NEW.phone); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`followme_beforeUpdate` + BEFORE UPDATE ON `followme` + FOR EACH ROW +BEGIN + CALL pbx.phone_isValid(NEW.phone); +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 */ ; + +-- +-- Temporary view structure for view `followmeConf` +-- + +DROP TABLE IF EXISTS `followmeConf`; +/*!50001 DROP VIEW IF EXISTS `followmeConf`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `followmeConf` AS SELECT + 1 AS `name`, + 1 AS `music`, + 1 AS `context`, + 1 AS `takecall`, + 1 AS `declinecall`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `followmeConfig` +-- + +DROP TABLE IF EXISTS `followmeConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `followmeConfig` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `music` varchar(50) CHARACTER SET utf8 DEFAULT NULL, + `context` varchar(50) CHARACTER SET utf8 NOT NULL, + `takeCall` char(1) CHARACTER SET utf8 NOT NULL, + `declineCall` char(1) CHARACTER SET utf8 NOT NULL, + `timeout` int(11) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `followmeNumberConf` +-- + +DROP TABLE IF EXISTS `followmeNumberConf`; +/*!50001 DROP VIEW IF EXISTS `followmeNumberConf`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `followmeNumberConf` AS SELECT + 1 AS `name`, + 1 AS `ordinal`, + 1 AS `phonenumber`, + 1 AS `timeout`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `queue` +-- + +DROP TABLE IF EXISTS `queue`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `queue` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `description` varchar(128) CHARACTER SET utf8 NOT NULL, + `name` varchar(128) CHARACTER SET utf8 NOT NULL, + `config` int(10) unsigned NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name` (`name`), + UNIQUE KEY `description` (`description`), + KEY `config` (`config`), + CONSTRAINT `queue_ibfk_1` FOREIGN KEY (`config`) REFERENCES `queueConfig` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Queues'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`queue_beforeInsert` + BEFORE INSERT ON `queue` + FOR EACH ROW +BEGIN + CALL queue_isValid(NEW.`name`); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`queue_beforeUpdate` + BEFORE UPDATE ON `queue` + FOR EACH ROW +BEGIN + CALL queue_isValid(NEW.`name`); +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 */ ; + +-- +-- Temporary view structure for view `queueConf` +-- + +DROP TABLE IF EXISTS `queueConf`; +/*!50001 DROP VIEW IF EXISTS `queueConf`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `queueConf` AS SELECT + 1 AS `name`, + 1 AS `strategy`, + 1 AS `timeout`, + 1 AS `retry`, + 1 AS `weight`, + 1 AS `maxlen`, + 1 AS `ringinuse`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `queueConfig` +-- + +DROP TABLE IF EXISTS `queueConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `queueConfig` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `strategy` varchar(128) CHARACTER SET utf8 NOT NULL, + `timeout` int(10) unsigned NOT NULL, + `retry` int(10) unsigned NOT NULL, + `weight` int(10) unsigned NOT NULL, + `maxLen` int(10) unsigned NOT NULL, + `ringInUse` tinyint(4) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Default values for queues configuration'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `queueMember` +-- + +DROP TABLE IF EXISTS `queueMember`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `queueMember` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `queue` varchar(128) CHARACTER SET utf8 NOT NULL, + `extension` varchar(128) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `queue` (`queue`,`extension`), + KEY `extension` (`extension`), + CONSTRAINT `queueMember_ibfk_1` FOREIGN KEY (`queue`) REFERENCES `queue` (`name`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `queueMember_ibfk_2` FOREIGN KEY (`extension`) REFERENCES `sip` (`extension`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=792 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Queue members'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `queueMemberConf` +-- + +DROP TABLE IF EXISTS `queueMemberConf`; +/*!50001 DROP VIEW IF EXISTS `queueMemberConf`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `queueMemberConf` AS SELECT + 1 AS `uniqueid`, + 1 AS `queue_name`, + 1 AS `interface`, + 1 AS `paused`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `queuePhone` +-- + +DROP TABLE IF EXISTS `queuePhone`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `queuePhone` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `queue` varchar(128) CHARACTER SET utf8 NOT NULL, + `phone` varchar(128) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `queue` (`queue`,`phone`), + CONSTRAINT `queuePhone_ibfk_1` FOREIGN KEY (`queue`) REFERENCES `queue` (`name`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=1003 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`queuePhone_beforeInsert` + BEFORE INSERT ON `queuePhone` + FOR EACH ROW +BEGIN + CALL phone_isValid(NEW.phone); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`queuePhone_beforeUpdate` + BEFORE UPDATE ON `queuePhone` + FOR EACH ROW +BEGIN + CALL phone_isValid(NEW.phone); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `schedule` +-- + +DROP TABLE IF EXISTS `schedule`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `schedule` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `weekDay` tinyint(3) unsigned NOT NULL COMMENT '0 = Monday, 6 = Sunday', + `timeStart` time NOT NULL, + `timeEnd` time NOT NULL, + `queue` varchar(128) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`), + KEY `queue` (`queue`), + CONSTRAINT `schedule_ibfk_1` FOREIGN KEY (`queue`) REFERENCES `queue` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `sip` +-- + +DROP TABLE IF EXISTS `sip`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sip` ( + `user_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'The user id', + `extension` varchar(128) CHARACTER SET utf8 NOT NULL COMMENT 'The softphone extension', + `md5Secret` varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'MD5 hash of extension and password', + `secret` varchar(80) CHARACTER SET utf8 DEFAULT NULL COMMENT 'Deprecated', + `caller_id` varchar(80) CHARACTER SET utf8 DEFAULT NULL COMMENT 'Deprecated', + PRIMARY KEY (`user_id`), + UNIQUE KEY `extension` (`extension`), + CONSTRAINT `sip_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='SIP accounts'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`sip_beforeInsert` + BEFORE INSERT ON `sip` + FOR EACH ROW +BEGIN + CALL sip_isValid(NEW.extension); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sip_afterInsert` + AFTER INSERT ON `sip` + FOR EACH ROW +BEGIN + INSERT INTO sipReg + SET userId = NEW.user_id; + + UPDATE account.user + SET sync = FALSE + WHERE id = NEW.user_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_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`sip_beforeUpdate` + BEFORE UPDATE ON `sip` + FOR EACH ROW +BEGIN + CALL sip_isValid(NEW.extension); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`sip_afterUpdate` + AFTER UPDATE ON `sip` + FOR EACH ROW +BEGIN + IF !(OLD.extension <=> NEW.extension) THEN + UPDATE account.user + SET sync = FALSE + WHERE id = NEW.user_id; + 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 */ ; + +-- +-- Temporary view structure for view `sipConf` +-- + +DROP TABLE IF EXISTS `sipConf`; +/*!50001 DROP VIEW IF EXISTS `sipConf`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `sipConf` AS SELECT + 1 AS `id`, + 1 AS `name`, + 1 AS `callbackextension`, + 1 AS `md5secret`, + 1 AS `callerid`, + 1 AS `host`, + 1 AS `deny`, + 1 AS `permit`, + 1 AS `type`, + 1 AS `context`, + 1 AS `incominglimit`, + 1 AS `pickupgroup`, + 1 AS `careinvite`, + 1 AS `insecure`, + 1 AS `transport`, + 1 AS `ipaddr`, + 1 AS `regseconds`, + 1 AS `port`, + 1 AS `defaultuser`, + 1 AS `useragent`, + 1 AS `lastms`, + 1 AS `fullcontact`, + 1 AS `regserver`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `sipConfig` +-- + +DROP TABLE IF EXISTS `sipConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sipConfig` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `host` varchar(40) CHARACTER SET utf8 DEFAULT NULL, + `deny` varchar(95) CHARACTER SET utf8 NOT NULL, + `permit` varchar(95) CHARACTER SET utf8 NOT NULL, + `type` enum('user','peer','friend') CHARACTER SET utf8 NOT NULL, + `context` varchar(80) CHARACTER SET utf8 NOT NULL, + `incomingLimit` varchar(10) CHARACTER SET utf8 NOT NULL, + `pickupGroup` varchar(10) CHARACTER SET utf8 NOT NULL, + `careInvite` varchar(10) CHARACTER SET utf8 NOT NULL, + `insecure` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `transport` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `avpf` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `icesupport` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `encryption` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `dtlsenable` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `dtlverify` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `dtlscertfile` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `dtlsprivatekey` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `dtlssetup` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Default values for SIP accounts'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `sipReg` +-- + +DROP TABLE IF EXISTS `sipReg`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sipReg` ( + `userId` int(10) unsigned NOT NULL, + `ipAddr` varchar(45) CHARACTER SET utf8 DEFAULT NULL, + `regSeconds` bigint(20) unsigned DEFAULT NULL, + `port` varchar(50) CHARACTER SET utf8 DEFAULT NULL, + `defaultUser` varchar(50) CHARACTER SET utf8 DEFAULT NULL, + `userAgent` varchar(80) CHARACTER SET utf8 DEFAULT NULL, + `lastMs` varchar(50) CHARACTER SET utf8 DEFAULT NULL, + `fullContact` varchar(50) CHARACTER SET utf8 DEFAULT NULL, + `regServer` varchar(20) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`userId`), + CONSTRAINT `sipReg_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `sip` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='SIP registrations'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'pbx' +-- + +-- +-- Dumping routines for database 'pbx' +-- +/*!50003 DROP FUNCTION IF EXISTS `clientFromPhone` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `clientFromPhone`(vPhone VARCHAR(255)) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * @deprecated Use vn.client_getFromPhone() + */ + RETURN vn.client_getFromPhone(vPhone); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `phone_format` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `phone_format`(vPhone VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 + DETERMINISTIC +BEGIN + DECLARE vI INT DEFAULT 0; + DECLARE vChr VARCHAR(1); + DECLARE vLen INT DEFAULT LENGTH(vPhone); + DECLARE vNewPhone VARCHAR(255) DEFAULT ''; + + WHILE vI < vLen + DO + SET vChr = SUBSTR(vPhone, vI + 1, 1); + + IF vChr REGEXP '^[0-9]$' + THEN + SET vNewPhone = CONCAT(vNewPhone, vChr); + ELSEIF vChr = '+' AND vI = 0 + THEN + SET vNewPhone = CONCAT(vNewPhone, '00'); + END IF; + + SET vI = vI + 1; + END WHILE; + + IF vNewPhone REGEXP '^0+$' OR vNewPhone = '' THEN + RETURN NULL; + END IF; + + IF vNewPhone REGEXP '^0034' THEN + SET vNewPhone = SUBSTR(vNewPhone, 5); + END IF; + + RETURN vNewPhone; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `phone_isValid` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `phone_isValid`(vPhone VARCHAR(255)) +BEGIN +/** + * Check if an phone has the correct format and + * throws an exception if it hasn't. + * + * @param vPhone The phone number + */ + DECLARE vIsValid BOOL; + + SET vIsValid = vPhone IS NULL + OR (vPhone REGEXP '^[0-9]+$' + AND vPhone NOT REGEXP '^0+$' + AND vPhone NOT REGEXP '^0034'); + + IF NOT vIsValid THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Phone format is invalid'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `queue_isValid` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `queue_isValid`(vQueue VARCHAR(255)) + DETERMINISTIC +BEGIN +/** + * Check if an queue has the correct format and + * throws an exception if it hasn't. + * + * @param vQueue The queue number + */ + DECLARE vIsValid BOOL; + + SET vIsValid = vQueue IS NULL + OR vQueue REGEXP '^[1-9][0-9]00$'; + + IF NOT vIsValid THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Queue format is invalid'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sip_isValid` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `sip_isValid`(vExtension VARCHAR(255)) + DETERMINISTIC +BEGIN +/** + * Check if an extension has the correct format and + * throws an exception if it hasn't. + * + * @param vExtension The extension + */ + DECLARE vIsValid BOOL; + + SET vIsValid = vExtension IS NULL + OR (vExtension REGEXP '^[0-9]{4}$' + AND MOD(vExtension, 100) != 0); + + IF NOT vIsValid THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Extension format is invalid'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sip_setPassword` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `sip_setPassword`( + vUser VARCHAR(255), + vPassword VARCHAR(255) +) +BEGIN + UPDATE sip SET + md5Secret = MD5(CONCAT(extension, ':asterisk:', vPassword)) + WHERE user_id = vUser; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Current Database: `postgresql` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `postgresql` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; + +USE `postgresql`; + +-- +-- Table structure for table `address` +-- + +DROP TABLE IF EXISTS `address`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `address` ( + `address_id` int(11) NOT NULL AUTO_INCREMENT, + `town_id` int(11) NOT NULL, + `address_type_id` int(11) NOT NULL, + `name` varchar(40) DEFAULT NULL, + `address1` varchar(255) DEFAULT NULL, + `number` int(11) DEFAULT NULL, + `address2` varchar(30) DEFAULT NULL, + PRIMARY KEY (`address_id`), + KEY `address_address_type_id_idx` (`address_type_id`), + KEY `address_town_id_idx` (`town_id`), + CONSTRAINT `address_ibfk_1` FOREIGN KEY (`address_type_id`) REFERENCES `address_type` (`address_type_id`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `address_ibfk_2` FOREIGN KEY (`town_id`) REFERENCES `townKk` (`town_id`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=846 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `address_type` +-- + +DROP TABLE IF EXISTS `address_type`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `address_type` ( + `address_type_id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(20) NOT NULL, + PRIMARY KEY (`address_type_id`) +) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `bank_account` +-- + +DROP TABLE IF EXISTS `bank_account`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `bank_account` ( + `bank_account_id` int(11) NOT NULL AUTO_INCREMENT, + `client_id` int(11) DEFAULT NULL, + `account` char(50) DEFAULT NULL, + `bic` char(20) DEFAULT NULL, + `bank_account_type_id` int(11) DEFAULT NULL, + `nation_id` int(11) DEFAULT NULL, + `sortcode` char(50) DEFAULT NULL, + `bank_name` char(30) DEFAULT NULL, + `bank_adress` char(125) DEFAULT NULL, + `bank_city` char(50) DEFAULT NULL, + `bank_account_link_id` int(11) DEFAULT NULL, + PRIMARY KEY (`bank_account_id`), + KEY `fki_bank_account_client_pk` (`client_id`), + KEY `fki_bank_profile` (`client_id`), + KEY `fki_business_account_fk` (`client_id`), + KEY `fki_person_account_fk` (`client_id`), + KEY `bank_account_bank_account_type_id_fkey` (`bank_account_type_id`), + KEY `bank_account_nation_id_fkey` (`nation_id`), + CONSTRAINT `bank_account_bank_account_type_id_fkey` FOREIGN KEY (`bank_account_type_id`) REFERENCES `bank_account_type` (`bank_account_type_id`) ON UPDATE CASCADE, + CONSTRAINT `bank_account_nation_id_fkey` FOREIGN KEY (`nation_id`) REFERENCES `nation` (`nation_id`) ON UPDATE CASCADE, + CONSTRAINT `bank_profile` FOREIGN KEY (`client_id`) REFERENCES `profile` (`profile_id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=937 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `bank_account_type` +-- + +DROP TABLE IF EXISTS `bank_account_type`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `bank_account_type` ( + `bank_account_type_id` int(11) NOT NULL AUTO_INCREMENT, + `name` char(15) DEFAULT NULL, + PRIMARY KEY (`bank_account_type_id`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `bank_bic` +-- + +DROP TABLE IF EXISTS `bank_bic`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `bank_bic` ( + `nrbe` int(11) NOT NULL, + `denominacion` varchar(255) DEFAULT NULL, + `bic` char(11) DEFAULT NULL, + `referenciaFTH` varchar(35) DEFAULT NULL, + `referenciaVNL` varchar(35) DEFAULT NULL, + PRIMARY KEY (`nrbe`), + KEY `bankbic_ikey1` (`bic`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `business` +-- + +DROP TABLE IF EXISTS `business`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `business` ( + `business_id` int(11) NOT NULL AUTO_INCREMENT, + `client_id` int(11) DEFAULT NULL, + `provider_id` int(11) DEFAULT NULL, + `date_start` date DEFAULT NULL, + `date_end` date DEFAULT NULL, + `workerBusiness` longtext, + `reasonEndFk` int(11) DEFAULT NULL, + PRIMARY KEY (`business_id`), + KEY `business_client` (`client_id`), + KEY `bussiness_provider` (`provider_id`), + CONSTRAINT `business_client` FOREIGN KEY (`client_id`) REFERENCES `profile` (`profile_id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `bussiness_provider` FOREIGN KEY (`provider_id`) REFERENCES `profile` (`profile_id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=3059 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `business_labour` +-- + +DROP TABLE IF EXISTS `business_labour`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `business_labour` ( + `business_id` int(11) NOT NULL, + `notes` longtext, + `department_id` int(11) DEFAULT '2', + `professional_category_id` int(11) DEFAULT '0', + `incentivo` double DEFAULT '0', + `calendar_labour_type_id` int(11) DEFAULT '1', + `porhoras` smallint(6) NOT NULL DEFAULT '0', + `labour_agreement_id` int(11) DEFAULT NULL, + `workcenter_id` int(11) DEFAULT NULL, + PRIMARY KEY (`business_id`), + KEY `fki_business_labour_agreement` (`labour_agreement_id`), + KEY `fki_workcenter_labour` (`workcenter_id`), + KEY `horario_tipo` (`calendar_labour_type_id`), + KEY `business_labour_department_idx` (`department_id`), + CONSTRAINT `bus_restriction` FOREIGN KEY (`business_id`) REFERENCES `business` (`business_id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `business_labour_agreement` FOREIGN KEY (`labour_agreement_id`) REFERENCES `labour_agreement` (`labour_agreement_id`) ON UPDATE CASCADE, + CONSTRAINT `business_labour_department` FOREIGN KEY (`department_id`) REFERENCES `vn`.`department` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `horario_tipo` FOREIGN KEY (`calendar_labour_type_id`) REFERENCES `calendar_labour_type` (`calendar_labour_type_id`) ON UPDATE CASCADE, + CONSTRAINT `workcenter_labour` FOREIGN KEY (`workcenter_id`) REFERENCES `workcenter` (`workcenter_id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `business_labour_payroll` +-- + +DROP TABLE IF EXISTS `business_labour_payroll`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `business_labour_payroll` ( + `business_id` int(11) NOT NULL, + `cod_tarifa` int(11) DEFAULT NULL, + `cod_categoria` int(11) DEFAULT NULL, + `cod_contrato` int(11) DEFAULT NULL, + `importepactado` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`business_id`), + CONSTRAINT `business_labour_payroll_fk1` FOREIGN KEY (`business_id`) REFERENCES `business` (`business_id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `calendar_employee` +-- + +DROP TABLE IF EXISTS `calendar_employee`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `calendar_employee` ( + `business_id` int(11) NOT NULL, + `calendar_state_id` int(11) NOT NULL, + `date` date NOT NULL, + PRIMARY KEY (`business_id`,`date`), + KEY `calendar_employee_business_labour_id_idx` (`business_id`), + KEY `calendar_employee_calendar_state_calendar_state_id_idx` (`calendar_state_id`), + CONSTRAINT `calendar_employee_state_id` FOREIGN KEY (`calendar_state_id`) REFERENCES `calendar_state` (`calendar_state_id`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `calendar_free` +-- + +DROP TABLE IF EXISTS `calendar_free`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `calendar_free` ( + `calendar_free_id` int(11) NOT NULL AUTO_INCREMENT, + `type` varchar(20) NOT NULL, + `rgb` varchar(7) DEFAULT NULL, + PRIMARY KEY (`calendar_free_id`) +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `calendar_labour` +-- + +DROP TABLE IF EXISTS `calendar_labour`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `calendar_labour` ( + `calendar_free_id` int(11) NOT NULL, + `person_id` int(11) NOT NULL, + `day` date NOT NULL, + `calendar_labour_legend_id` int(11) DEFAULT NULL, + `workcenter_id` int(11) NOT NULL, + `calendar_id` int(11) NOT NULL AUTO_INCREMENT, + PRIMARY KEY (`calendar_id`), + UNIQUE KEY `person_id_UNIQUE` (`person_id`,`day`,`workcenter_id`), + KEY `calendar_labour_calendar_free_id_idx` (`calendar_free_id`), + KEY `fki_calendar_labour_legend_id` (`calendar_labour_legend_id`), + KEY `fki_calendar_labour_person_day` (`person_id`,`day`), + KEY `fki_workcenter_calendar` (`workcenter_id`), + CONSTRAINT `fk_calendar_labour_calendar_free1` FOREIGN KEY (`calendar_free_id`) REFERENCES `calendar_free` (`calendar_free_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `fk_calendar_labour_legend_id` FOREIGN KEY (`calendar_labour_legend_id`) REFERENCES `calendar_labour_legend` (`calendar_labour_legend_id`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `workcenter_calendar` FOREIGN KEY (`workcenter_id`) REFERENCES `workcenter` (`workcenter_id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=586 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `calendar_labour_legend` +-- + +DROP TABLE IF EXISTS `calendar_labour_legend`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `calendar_labour_legend` ( + `calendar_labour_legend_id` int(11) NOT NULL AUTO_INCREMENT, + `descripcion` longtext, + PRIMARY KEY (`calendar_labour_legend_id`), + UNIQUE KEY `calendar_labour_legend_calendar_labour_legend_id_key` (`calendar_labour_legend_id`) +) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `calendar_labour_type` +-- + +DROP TABLE IF EXISTS `calendar_labour_type`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `calendar_labour_type` ( + `calendar_labour_type_id` int(11) NOT NULL AUTO_INCREMENT, + `descripcion` varchar(50) DEFAULT NULL, + `pausa_remunerada` time DEFAULT NULL, + `hours_week` smallint(6) DEFAULT NULL, + `isPartial` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`calendar_labour_type_id`), + UNIQUE KEY `hours_labour_hours_labour_id_key` (`calendar_labour_type_id`) +) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `calendar_state` +-- + +DROP TABLE IF EXISTS `calendar_state`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `calendar_state` ( + `calendar_state_id` int(11) NOT NULL AUTO_INCREMENT, + `type` varchar(30) NOT NULL, + `rgb` varchar(7) NOT NULL, + `color` bigint(20) DEFAULT '0', + `permissionRate` decimal(3,2) DEFAULT NULL, + `code` varchar(45) DEFAULT NULL, + `isAllowedToWork` tinyint(4) NOT NULL DEFAULT '0', + PRIMARY KEY (`calendar_state_id`) +) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `currency` +-- + +DROP TABLE IF EXISTS `currency`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `currency` ( + `currency_id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(15) NOT NULL, + PRIMARY KEY (`currency_id`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `income_employee` +-- + +DROP TABLE IF EXISTS `income_employee`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `income_employee` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `debe` decimal(10,2) DEFAULT NULL, + `haber` decimal(10,2) DEFAULT '0.00', + `id_incomeType` int(11) DEFAULT NULL, + `odbc_date` date DEFAULT NULL, + `person_id` int(11) DEFAULT NULL, + `concepto` longtext, + PRIMARY KEY (`id`), + KEY `fincometype_id` (`id_incomeType`), + KEY `fperson_id` (`person_id`), + CONSTRAINT `fincometype_id` FOREIGN KEY (`id_incomeType`) REFERENCES `incometype_employee` (`id_incometype`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `fperson_id` FOREIGN KEY (`person_id`) REFERENCES `person` (`person_id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=76272 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `incometype_employee` +-- + +DROP TABLE IF EXISTS `incometype_employee`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `incometype_employee` ( + `id_incometype` int(11) NOT NULL, + `descripcion` varchar(255) DEFAULT NULL, + `nomina` smallint(6) DEFAULT '0', + PRIMARY KEY (`id_incometype`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `journey` +-- + +DROP TABLE IF EXISTS `journey`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `journey` ( + `journey_id` int(11) NOT NULL AUTO_INCREMENT, + `day_id` smallint(6) NOT NULL DEFAULT '1' COMMENT 'Lunes = 1 \nDomingo = 7', + `start` time DEFAULT NULL, + `end` time DEFAULT NULL, + `business_id` int(11) NOT NULL, + PRIMARY KEY (`journey_id`), + KEY `fki_business_journey` (`business_id`), + CONSTRAINT `business_journey` FOREIGN KEY (`business_id`) REFERENCES `business_labour` (`business_id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2716 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `labour_agreement` +-- + +DROP TABLE IF EXISTS `labour_agreement`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `labour_agreement` ( + `labour_agreement_id` int(11) NOT NULL AUTO_INCREMENT, + `month_hollidays` double DEFAULT NULL, + `year_hours` int(11) DEFAULT NULL, + `name` char(50) DEFAULT NULL, + `date_START` date DEFAULT NULL, + `date_END` date DEFAULT NULL, + PRIMARY KEY (`labour_agreement_id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `media` +-- + +DROP TABLE IF EXISTS `media`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `media` ( + `media_id` int(11) NOT NULL AUTO_INCREMENT, + `media_type_id` int(11) NOT NULL, + `value` varchar(55) NOT NULL, + `sort` int(11) DEFAULT NULL, + PRIMARY KEY (`media_id`), + KEY `media_media_type_id_idx` (`media_type_id`), + CONSTRAINT `media_ibfk_1` FOREIGN KEY (`media_type_id`) REFERENCES `media_type` (`media_type_id`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=1171 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `media_type` +-- + +DROP TABLE IF EXISTS `media_type`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `media_type` ( + `media_type_id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(15) NOT NULL, + PRIMARY KEY (`media_type_id`), + UNIQUE KEY `media_type_name_key` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `nation` +-- + +DROP TABLE IF EXISTS `nation`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `nation` ( + `nation_id` int(11) NOT NULL AUTO_INCREMENT, + `currency_id` int(11) NOT NULL DEFAULT '1', + `name` varchar(20) NOT NULL, + `brief` char(3) NOT NULL, + `flag` longblob, + PRIMARY KEY (`nation_id`), + UNIQUE KEY `nation_name_key` (`name`), + KEY `nation_currency_id_idx` (`currency_id`), + CONSTRAINT `nation_ibfk_1` FOREIGN KEY (`currency_id`) REFERENCES `currency` (`currency_id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `periodos` +-- + +DROP TABLE IF EXISTS `periodos`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `periodos` ( + `fecha` date NOT NULL, + `periodo` int(11) DEFAULT NULL, + PRIMARY KEY (`fecha`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `person` +-- + +DROP TABLE IF EXISTS `person`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `person` ( + `person_id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(60) NOT NULL, + `nickname` varchar(15) DEFAULT NULL, + `nif` varchar(15) DEFAULT NULL, + `birth` date DEFAULT NULL, + `firstname` varchar(20) DEFAULT NULL, + `p2` longtext, + `nis` int(11) DEFAULT NULL, + `id_trabajador` int(11) DEFAULT NULL, + `isDisable` smallint(6) NOT NULL DEFAULT '0', + `isFreelance` smallint(6) NOT NULL DEFAULT '0' COMMENT 'M Male\nF Female', + `isSsDiscounted` smallint(6) NOT NULL DEFAULT '0', + `sex` enum('M','F') NOT NULL DEFAULT 'F' COMMENT 'M Masculino F Femenino', + PRIMARY KEY (`person_id`), + UNIQUE KEY `person_nis` (`person_id`), + UNIQUE KEY `Index_unique_nif` (`nif`), + UNIQUE KEY `person_nif_key` (`nif`), + UNIQUE KEY `nis_UNIQUE` (`nis`), + KEY `index1` (`person_id`,`name`,`nickname`,`firstname`), + KEY `person_worker` (`id_trabajador`), + CONSTRAINT `Person_ibfk_1` FOREIGN KEY (`id_trabajador`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=1166 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `professional_category` +-- + +DROP TABLE IF EXISTS `professional_category`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `professional_category` ( + `professional_category_id` int(11) NOT NULL AUTO_INCREMENT, + `category_name` varchar(50) NOT NULL, + `professional_levels_id` int(11) DEFAULT NULL, + `fichajes` tinyint(4) NOT NULL DEFAULT '1', + `holiday_days` decimal(3,1) DEFAULT NULL, + PRIMARY KEY (`professional_category_id`), + UNIQUE KEY `professional_category_name_category_key` (`category_name`) +) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `professional_levels` +-- + +DROP TABLE IF EXISTS `professional_levels`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `professional_levels` ( + `professional_levels_id` int(11) NOT NULL AUTO_INCREMENT, + `level_name` varchar(5) DEFAULT NULL, + `price_overtime` double DEFAULT NULL, + PRIMARY KEY (`professional_levels_id`) +) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `profile` +-- + +DROP TABLE IF EXISTS `profile`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `profile` ( + `profile_id` int(11) NOT NULL AUTO_INCREMENT, + `person_id` int(11) NOT NULL, + `profile_type_id` int(11) NOT NULL DEFAULT '1', + PRIMARY KEY (`profile_id`), + KEY `profile_person_id_idx` (`person_id`), + KEY `profile_profile_type_id_idx` (`profile_type_id`), + CONSTRAINT `person_fk` FOREIGN KEY (`person_id`) REFERENCES `person` (`person_id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=1050 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `profile_address` +-- + +DROP TABLE IF EXISTS `profile_address`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `profile_address` ( + `profile_address_id` int(11) NOT NULL AUTO_INCREMENT, + `profile_id` int(11) NOT NULL, + `address_id` int(11) NOT NULL, + PRIMARY KEY (`profile_address_id`), + KEY `profile_address_address_id_idx` (`address_id`), + KEY `profile_address_profile_id_idx` (`profile_id`) +) ENGINE=InnoDB AUTO_INCREMENT=182 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `profile_media` +-- + +DROP TABLE IF EXISTS `profile_media`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `profile_media` ( + `profile_media_id` int(11) NOT NULL AUTO_INCREMENT, + `profile_id` int(11) NOT NULL, + `media_id` int(11) NOT NULL, + PRIMARY KEY (`profile_media_id`), + KEY `profile_media_media_id_idx` (`media_id`), + KEY `profile_media_profile_id_idx` (`profile_id`), + CONSTRAINT `fk_profile_media_media1` FOREIGN KEY (`media_id`) REFERENCES `media` (`media_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `media_ibfk_20` FOREIGN KEY (`profile_id`) REFERENCES `profile` (`profile_id`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=1332 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `profile_type` +-- + +DROP TABLE IF EXISTS `profile_type`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `profile_type` ( + `profile_type_id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(15) NOT NULL, + PRIMARY KEY (`profile_type_id`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `province` +-- + +DROP TABLE IF EXISTS `province`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `province` ( + `province_id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(15) NOT NULL, + `nation_id` int(11) NOT NULL, + PRIMARY KEY (`province_id`), + UNIQUE KEY `province_name_key` (`name`), + KEY `province_nation_id_idx` (`nation_id`), + CONSTRAINT `fk_province_nation1` FOREIGN KEY (`nation_id`) REFERENCES `nation` (`nation_id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=162 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `townKk` +-- + +DROP TABLE IF EXISTS `townKk`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `townKk` ( + `town_id` int(11) NOT NULL AUTO_INCREMENT, + `province_id` int(11) NOT NULL, + `name` varchar(30) NOT NULL, + `postal_code` varchar(8) NOT NULL, + PRIMARY KEY (`town_id`), + KEY `town_province_id_idx` (`province_id`), + CONSTRAINT `townKk_ibfk_1` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=3673 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workcenter` +-- + +DROP TABLE IF EXISTS `workcenter`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workcenter` ( + `workcenter_id` int(11) NOT NULL AUTO_INCREMENT, + `name` longtext, + `center_id` int(11) DEFAULT NULL, + `counter` bigint(20) DEFAULT NULL, + `warehouseFk` smallint(6) DEFAULT NULL, + PRIMARY KEY (`workcenter_id`) +) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workerTimeControlConfig` +-- + +DROP TABLE IF EXISTS `workerTimeControlConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerTimeControlConfig` ( + `id` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL, + PRIMARY KEY (`id`), + KEY `warehouseFk_1_idx` (`warehouseFk`), + CONSTRAINT `warehouseFk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `vn`.`warehouse` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workers20190711_FichadasAbril` +-- + +DROP TABLE IF EXISTS `workers20190711_FichadasAbril`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workers20190711_FichadasAbril` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `person_id` int(11) NOT NULL DEFAULT '0', + `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL, + `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL, + `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL, + `Fecha` date DEFAULT NULL, + `Hora` int(2) DEFAULT NULL, + `Minuto` int(2) DEFAULT NULL, + `sumable` double DEFAULT NULL, + `jornada` decimal(5,2) NOT NULL DEFAULT '8.00', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'postgresql' +-- + +-- +-- Dumping routines for database 'postgresql' +-- + +-- +-- Current Database: `salix` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `salix` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; + +USE `salix`; + +-- +-- Table structure for table `ACL` +-- + +DROP TABLE IF EXISTS `ACL`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ACL` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `model` varchar(512) CHARACTER SET utf8 DEFAULT NULL, + `property` varchar(512) CHARACTER SET utf8 DEFAULT NULL, + `accessType` set('READ','WRITE','*') COLLATE utf8_unicode_ci DEFAULT 'READ', + `permission` set('DENY','ALLOW') COLLATE utf8_unicode_ci DEFAULT 'ALLOW', + `principalType` set('ROLE','USER') COLLATE utf8_unicode_ci DEFAULT 'ROLE', + `principalId` varchar(512) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=202 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `AccessToken` +-- + +DROP TABLE IF EXISTS `AccessToken`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `AccessToken` ( + `id` varchar(255) CHARACTER SET utf8 NOT NULL, + `ttl` int(11) DEFAULT NULL, + `scopes` varchar(255) CHARACTER SET utf8 DEFAULT NULL, + `created` datetime DEFAULT NULL, + `userId` int(11) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `Account` +-- + +DROP TABLE IF EXISTS `Account`; +/*!50001 DROP VIEW IF EXISTS `Account`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `Account` AS SELECT + 1 AS `id`, + 1 AS `name`, + 1 AS `password`, + 1 AS `roleFk`, + 1 AS `active`, + 1 AS `email`, + 1 AS `created`, + 1 AS `updated`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `Role` +-- + +DROP TABLE IF EXISTS `Role`; +/*!50001 DROP VIEW IF EXISTS `Role`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `Role` AS SELECT + 1 AS `id`, + 1 AS `name`, + 1 AS `description`, + 1 AS `created`, + 1 AS `modified`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `RoleMapping` +-- + +DROP TABLE IF EXISTS `RoleMapping`; +/*!50001 DROP VIEW IF EXISTS `RoleMapping`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `RoleMapping` AS SELECT + 1 AS `id`, + 1 AS `principalType`, + 1 AS `principalId`, + 1 AS `roleId`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `fieldAcl` +-- + +DROP TABLE IF EXISTS `fieldAcl`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `fieldAcl` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `model` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `property` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `actionType` set('insert','update','*') COLLATE utf8_unicode_ci DEFAULT '*', + `role` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `user` +-- + +DROP TABLE IF EXISTS `user`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `user` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `realm` varchar(512) CHARACTER SET utf8 DEFAULT NULL, + `username` varchar(512) CHARACTER SET utf8 DEFAULT NULL, + `password` varchar(512) CHARACTER SET utf8 NOT NULL, + `email` varchar(512) CHARACTER SET utf8 NOT NULL, + `emailVerified` tinyint(1) DEFAULT NULL, + `verificationToken` varchar(512) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=50054 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `userConfigView` +-- + +DROP TABLE IF EXISTS `userConfigView`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `userConfigView` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `userFk` int(10) unsigned NOT NULL, + `tableCode` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `configuration` text COLLATE utf8_unicode_ci, + PRIMARY KEY (`id`), + UNIQUE KEY `uniqueUser_TableCode` (`userFk`,`tableCode`) +) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'salix' +-- + +-- +-- Dumping routines for database 'salix' +-- +/*!50003 DROP PROCEDURE IF EXISTS `production_control_source` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `production_control_source`(idWarehouse INT, scopeDays TINYINT) +BEGIN + CALL vn2008.production_control_source(idWarehouse, scopeDays); + + SET @id = 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.production; + CREATE TEMPORARY TABLE tmp.production + ENGINE = MEMORY + SELECT + @id := @id+1 id, + p.Id_Ticket ticketFk, + p.Id_Cliente clientFk, + p.Alias client, + p.Fecha `date`, + p.Hora hour, + p.POBLACION city, + p.PROVINCIA province, + p.province_id provinceFk, + p.Agencia agency, + p.agency_id agencyFk, + p.lines, + p.m3, + p.problems, + p.problem, + p.state stateFk, + t.Id_Trabajador workerfk, + CONCAT(t.Nombre, ' ', t.Apellidos) worker, + tt.Id_Trabajador salesPersonFk, + CONCAT(tt.Nombre, ' ', tt.Apellidos) salesPerson, + s.name state, + p.Cajas boxes, + p.Id_Ruta routeFk + FROM tmp.production_buffer p + JOIN vn2008.state s ON p.state = s.id + JOIN vn2008.Trabajadores t ON p.CodigoTrabajador = t.CodigoTrabajador COLLATE utf8_unicode_ci + JOIN vn2008.Trabajadores tt ON p.Comercial = tt.CodigoTrabajador COLLATE utf8_unicode_ci; + + DROP TEMPORARY TABLE tmp.production_buffer; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Current Database: `stock` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `stock` /*!40100 DEFAULT CHARACTER SET utf8 */; + +USE `stock`; + +-- +-- Table structure for table `inbound` +-- + +DROP TABLE IF EXISTS `inbound`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `inbound` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `tableName` set('buy','sale') NOT NULL, + `tableId` int(10) unsigned NOT NULL, + `isSync` tinyint(4) NOT NULL, + `isPicked` tinyint(4) NOT NULL DEFAULT '0', + `warehouseFk` int(10) unsigned NOT NULL, + `itemFk` int(10) unsigned NOT NULL, + `dated` datetime NOT NULL, + `expired` datetime DEFAULT NULL, + `quantity` int(10) unsigned NOT NULL, + `available` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `source` (`tableName`,`tableId`), + KEY `warehouseFk` (`warehouseFk`,`itemFk`,`dated`,`expired`,`available`), + KEY `isSync` (`isSync`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; +ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `stock`.`inbound_beforeInsert` + BEFORE INSERT ON `inbound` + FOR EACH ROW +BEGIN + SET NEW.isPicked = NEW.isPicked OR NEW.dated < CURDATE(); + + CALL visible_log( + NEW.isPicked, + NEW.warehouseFk, + NEW.itemFk, + NEW.quantity + ); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `stock`.`inbound_afterDelete` + AFTER DELETE ON `inbound` + FOR EACH ROW +BEGIN + UPDATE outbound o + JOIN inboundPick ou ON ou.outboundFk = o.id + SET o.lack = o.lack + ou.quantity, + o.isSync = FALSE + WHERE ou.inboundFk = OLD.id; + + DELETE FROM inboundPick + WHERE inboundFk = OLD.id; + + CALL visible_log( + OLD.isPicked, + OLD.warehouseFk, + OLD.itemFk, + -OLD.quantity + ); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `inboundPick` +-- + +DROP TABLE IF EXISTS `inboundPick`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `inboundPick` ( + `inboundFk` int(10) unsigned DEFAULT NULL, + `outboundFk` int(10) unsigned DEFAULT NULL, + `quantity` int(11) NOT NULL, + UNIQUE KEY `buyFk` (`inboundFk`,`outboundFk`), + KEY `saleFk` (`outboundFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `log` +-- + +DROP TABLE IF EXISTS `log`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `log` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `operation` set('insert','delete') NOT NULL, + `tableName` varchar(255) NOT NULL, + `tableId` varchar(255) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `tableName` (`tableName`,`tableId`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `outbound` +-- + +DROP TABLE IF EXISTS `outbound`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `outbound` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `tableName` set('sale','buy','orderRow') NOT NULL, + `tableId` int(10) unsigned NOT NULL, + `isSync` tinyint(3) unsigned NOT NULL, + `isPicked` tinyint(4) NOT NULL DEFAULT '0', + `warehouseFk` int(10) unsigned NOT NULL, + `itemFk` int(10) unsigned NOT NULL, + `dated` datetime NOT NULL, + `created` datetime NOT NULL, + `expired` datetime DEFAULT NULL, + `quantity` int(10) unsigned NOT NULL, + `lack` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `source` (`tableName`,`tableId`), + KEY `warehouseFk` (`warehouseFk`,`itemFk`,`dated`), + KEY `expired` (`expired`), + KEY `isSync` (`isSync`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; +ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `stock`.`outbound_beforeInsert` + BEFORE INSERT ON `outbound` + FOR EACH ROW +BEGIN + SET NEW.lack = NEW.quantity; + SET NEW.isPicked = NEW.isPicked OR NEW.dated < CURDATE(); + + CALL visible_log( + NEW.isPicked, + NEW.warehouseFk, + NEW.itemFk, + -NEW.quantity + ); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `stock`.`outbound_afterDelete` + AFTER DELETE ON `outbound` + FOR EACH ROW +BEGIN + UPDATE inbound i + JOIN inboundPick ou ON ou.inboundFk = i.id + SET i.available = i.available + ou.quantity, + i.isSync = FALSE + WHERE ou.outboundFk = OLD.id; + + DELETE FROM inboundPick + WHERE outboundFk = OLD.id; + + CALL visible_log( + OLD.isPicked, + OLD.warehouseFk, + OLD.itemFk, + OLD.quantity + ); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `visible` +-- + +DROP TABLE IF EXISTS `visible`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `visible` ( + `itemFk` int(10) unsigned NOT NULL, + `warehouseFk` int(10) unsigned NOT NULL, + `quantity` int(11) NOT NULL, + PRIMARY KEY (`itemFk`,`warehouseFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'stock' +-- +/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; +/*!50106 DROP EVENT IF EXISTS `log_clean` */; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `log_clean` ON SCHEDULE EVERY 1 DAY STARTS '2019-06-17 05:00:00' ON COMPLETION PRESERVE ENABLE DO CALL log_clean */ ;; +/*!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 `log_syncNoWait` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `log_syncNoWait` ON SCHEDULE EVERY 5 SECOND STARTS '2017-06-27 17:15:02' ON COMPLETION NOT PRESERVE DISABLE DO CALL log_syncNoWait */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; +DELIMITER ; +/*!50106 SET TIME_ZONE= @save_time_zone */ ; + +-- +-- Dumping routines for database 'stock' +-- +/*!50003 DROP PROCEDURE IF EXISTS `inbound_addPick` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `inbound_addPick`( + vSelf INT, + vOutboundFk INT, + vQuantity INT +) +BEGIN + INSERT INTO inboundPick + SET + inboundFk = vSelf, + outboundFk = vOutboundFk, + quantity = vQuantity + ON DUPLICATE KEY UPDATE + quantity = quantity + vQuantity; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `inbound_removePick` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `inbound_removePick`( + vSelf INT, + vOutboundFk INT, + vQuantity INT, + vTotalQuantity INT +) +BEGIN + IF vQuantity < vTotalQuantity THEN + UPDATE inboundPick + SET quantity = quantity - vQuantity + WHERE inboundFk = vSelf + AND outboundFk = vOutboundFk; + ELSE + DELETE FROM inboundPick + WHERE inboundFk = vSelf + AND outboundFk = vOutboundFk; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `inbound_requestQuantity` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `inbound_requestQuantity`( + vSelf INT, + vRequested INT, + vDated DATETIME, + OUT vSupplied INT) +BEGIN +/** + * Disassociates inbound picks after the given date until the + * demanded quantity is satisfied. + * + * @param vSelf The inbound reference + * @param vRequested The requested quantity + * @param vDate The starting date for the associated outbounds + * @param vSupplied The supplied quantity + */ + DECLARE vOutboundFk INT; + DECLARE vPickQuantity INT; + DECLARE vPickGranted INT; + DECLARE vDone BOOL; + + DECLARE vPicks CURSOR FOR + SELECT p.outboundFk, p.quantity + FROM inboundPick p + JOIN outbound o ON o.id = p.outboundFk + WHERE p.inboundFk = vSelf + AND o.dated > vDated + ORDER BY o.dated DESC, o.created DESC; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SET vSupplied = 0; + + OPEN vPicks; + + myLoop: LOOP + SET vDone = FALSE; + FETCH vPicks INTO vOutboundFk, vPickQuantity; + + IF vDone THEN + LEAVE myLoop; + END IF; + + SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity); + SET vSupplied = vSupplied + vPickGranted; + CALL inbound_removePick(vSelf, vOutboundFk, vPickGranted, vPickQuantity); + + UPDATE outbound + SET isSync = FALSE, + lack = lack + vPickGranted + WHERE id = vOutboundFk; + + IF vSupplied >= vRequested THEN + LEAVE myLoop; + END IF; + END LOOP; + + CLOSE vPicks; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `inbound_sync` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `inbound_sync`(vSelf INT) +BEGIN +/** + * Associates a inbound with their possible outbounds, updating it's available. + * + * @param vSelf The inbound identifier + */ + DECLARE vDated DATETIME; + DECLARE vExpired DATETIME; + DECLARE vItem INT; + DECLARE vWarehouse INT; + DECLARE vQuantity INT; + DECLARE vAvailable INT; + DECLARE vSupplied INT; + DECLARE vSuppliedFromRequest INT; + DECLARE vOutboundFk INT; + DECLARE vLack INT; + DECLARE vHasPicks BOOL; + DECLARE vDone BOOL; + + DECLARE vOutbounds CURSOR FOR + SELECT id, lack, lack < quantity + FROM outbound + WHERE warehouseFk = vWarehouse + AND itemFk = vItem + AND dated >= vDated + AND (vExpired IS NULL OR dated < vExpired) + ORDER BY dated, created; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SELECT warehouseFk, itemFk, available, quantity, expired, dated + INTO vWarehouse, vItem, vAvailable, vQuantity, vExpired, vDated + FROM inbound + WHERE id = vSelf; + + IF vAvailable IS NULL THEN + SET vAvailable = vQuantity; + END IF; + + OPEN vOutbounds; + + myLoop: LOOP + SET vDone = FALSE; + FETCH vOutbounds INTO vOutboundFk, vLack, vHasPicks; + + IF vDone THEN + LEAVE myLoop; + END IF; + + SET vSupplied = LEAST(vAvailable, vLack); + + IF vSupplied > 0 THEN + SET vAvailable = vAvailable - vSupplied; + UPDATE outbound + SET lack = lack - vSupplied + WHERE id = vOutboundFk; + END IF; + + IF vHasPicks AND vAvailable > 0 THEN + CALL outbound_requestQuantity(vOutboundFk, vAvailable, vDated, vSuppliedFromRequest); + SET vSupplied = vSupplied + vSuppliedFromRequest; + SET vAvailable = vAvailable - vSuppliedFromRequest; + END IF; + + IF vSupplied > 0 THEN + CALL inbound_addPick(vSelf, vOutboundFk, vSupplied); + END IF; + + IF vAvailable <= 0 THEN + LEAVE myLoop; + END IF; + END LOOP; + + CLOSE vOutbounds; + + UPDATE inbound + SET isSync = TRUE, + available = vAvailable + WHERE id = vSelf; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `log_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `log_add`(IN `vTableName` VARCHAR(255), IN `vNewId` VARCHAR(255), IN `vOldId` VARCHAR(255)) +proc: BEGIN + -- XXX: Disabled while testing + LEAVE proc; + + IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vOldId, + operation = 'delete'; + END IF; + + IF vNewId IS NOT NULL THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vNewId, + operation = 'insert'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `log_clean` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `log_clean`() +BEGIN + DELETE FROM inbound WHERE dated = vn.getInventoryDate(); + DELETE FROM outbound WHERE dated = vn.getInventoryDate(); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `log_delete` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `log_delete`(vTableName VARCHAR(255), vTableId INT) +proc: BEGIN +/** + * Processes orphan transactions. + */ + IF vTableName NOT IN ('buy', 'sale', 'orderRow') THEN + LEAVE proc; + END IF; + + DELETE FROM inbound + WHERE tableName = vTableName COLLATE utf8_general_ci + AND tableId = vTableId; + + DELETE FROM outbound + WHERE tableName = vTableName COLLATE utf8_general_ci + AND tableId = vTableId; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `log_refreshAll` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshAll`() +BEGIN +/** + * Recalculates the entire cache. It takes a considerable time, + * please avoid calls to this procedure from commonly used operations. + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('stock.log_sync'); + RESIGNAL; + END; + + IF !GET_LOCK('stock.log_sync', 30) THEN + CALL util.throw('Lock timeout exceeded'); + END IF; + + TRUNCATE TABLE stock.`log`; + TRUNCATE TABLE stock.`inbound`; + TRUNCATE TABLE stock.`inboundPick`; + TRUNCATE TABLE stock.`outbound`; + TRUNCATE TABLE stock.`visible`; + + CALL log_refreshSale(NULL, NULL); + CALL log_refreshBuy(NULL, NULL); + CALL log_refreshOrder(NULL, NULL); + + UPDATE outbound SET isSync = TRUE; + CALL log_sync(TRUE); + + DO RELEASE_LOCK('stock.log_sync'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `log_refreshBuy` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshBuy`( + `vTableName` VARCHAR(255), + `vTableId` INT) +BEGIN + DROP TEMPORARY TABLE IF EXISTS tValues; + CREATE TEMPORARY TABLE tValues + ENGINE = MEMORY + SELECT + b.id buyFk, + e.id entryFk, + t.id travelFk, + b.itemFk, + e.isRaid, + ADDTIME(t.shipped, + IFNULL(t.shipmentHour, '00:00:00')) shipped, + t.warehouseOutFk, + t.isDelivered, + ADDTIME(t.landed, + IFNULL(t.landingHour, '00:00:00')) landed, + t.warehouseInFk, + t.isReceived, + tp.life, + ABS(b.quantity) quantity, + b.created, + b.quantity > 0 isIn, + t.shipped < vn.getInventoryDate() lessThanInventory + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.item i ON i.id = b.itemFk + JOIN vn.itemType tp ON tp.id = i.typeFk + WHERE ( + vTableId IS NULL + OR (vTableName = 'travel' AND t.id = vTableId) + OR (vTableName = 'entry' AND e.id = vTableId) + OR (vTableName = 'buy' AND b.id = vTableId) + ) + AND t.landed >= vn.getInventoryDate() + AND b.quantity != 0; + + REPLACE INTO inbound ( + tableName, tableId, warehouseFk, dated, + itemFk, expired, quantity, isPicked + ) + SELECT 'buy', + buyFk, + IF(isIn, warehouseInFk, warehouseOutFk), + @dated := IF(isIn, landed, shipped), + itemFk, + TIMESTAMPADD(DAY, life, @dated), + quantity, + IF(isIn, isReceived, isDelivered) AND !isRaid + FROM tValues + WHERE isIn OR !lessThanInventory; + + REPLACE INTO outbound ( + tableName, tableId, warehouseFk, dated, + itemFk, created, quantity, isPicked + ) + SELECT 'buy', + buyFk, + IF(isIn, warehouseOutFk, warehouseInFk), + IF(isIn, shipped, landed), + itemFk, + created, + quantity, + IF(isIn, isDelivered, isReceived) AND !isRaid + FROM tValues + WHERE !isIn OR !lessThanInventory; + + DROP TEMPORARY TABLE tValues; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `log_refreshOrder` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshOrder`( + `vTableName` VARCHAR(255), + `vTableId` INT) +BEGIN + DECLARE vExpireTime INT DEFAULT 20; + DECLARE vExpired DATETIME DEFAULT TIMESTAMPADD(MINUTE, -vExpireTime, NOW()); + + DROP TEMPORARY TABLE IF EXISTS tValues; + CREATE TEMPORARY TABLE tValues + ENGINE = MEMORY + SELECT + r.id rowFk, + r.itemFk, + r.warehouseFk, + r.shipment shipped, + r.amount quantity, + r.created + FROM hedera.orderRow r + JOIN hedera.`order` o ON o.id = r.orderFk + WHERE ( + vTableId IS NULL + OR (vTableName = 'order' AND o.id = vTableId) + OR (vTableName = 'orderRow' AND r.id = vTableId) + ) + AND !o.confirmed + AND r.shipment >= vn.getInventoryDate() + AND r.created >= vExpired + AND r.amount != 0; + + REPLACE INTO outbound ( + tableName, tableId, warehouseFk, dated, + itemFk, created, expired, quantity + ) + SELECT 'orderRow', + rowFk, + warehouseFk, + shipped, + itemFk, + created, + TIMESTAMPADD(MINUTE, vExpireTime, created), + quantity + FROM tValues; + + DROP TEMPORARY TABLE tValues; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `log_refreshSale` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshSale`( + `vTableName` VARCHAR(255), + `vTableId` INT) +BEGIN + DROP TEMPORARY TABLE IF EXISTS tValues; + CREATE TEMPORARY TABLE tValues + ENGINE = MEMORY + SELECT + m.id saleFk, + m.ticketFk, + m.itemFk, + t.warehouseFk, + t.shipped, + ABS(m.quantity) quantity, + m.created, + TIMESTAMPADD(DAY, tp.life, t.shipped) expired, + m.quantity < 0 isIn, + m.isPicked OR s.alertLevel > 1 isPicked + FROM vn.sale m + JOIN vn.ticket t ON t.id = m.ticketFk + 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 + WHERE ( + vTableId IS NULL + OR (vTableName = 'ticket' AND t.id = vTableId) + OR (vTableName = 'sale' AND m.id = vTableId) + ) + AND t.shipped >= vn.getInventoryDate() + AND m.quantity != 0; + + REPLACE INTO inbound ( + tableName, tableId, warehouseFk, dated, + itemFk, expired, quantity, isPicked + ) + SELECT 'sale', + saleFk, + warehouseFk, + shipped, + itemFk, + expired, + quantity, + isPicked + FROM tValues + WHERE isIn; + + REPLACE INTO outbound ( + tableName, tableId, warehouseFk, dated, + itemFk, created, quantity, isPicked + ) + SELECT 'sale', + saleFk, + warehouseFk, + shipped, + itemFk, + created, + quantity, + isPicked + FROM tValues + WHERE !isIn; + + DROP TEMPORARY TABLE tValues; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `log_sync` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `log_sync`(vSync BOOL) +proc: BEGIN + DECLARE vDone BOOL; + DECLARE vLogId INT; + DECLARE vHasPendingSync BOOL; + DECLARE vOperation VARCHAR(255); + DECLARE vTableName VARCHAR(255); + DECLARE vTableId VARCHAR(255); + DECLARE vInboundFk INT; + DECLARE vOutboundFk INT; + + DECLARE cInbound CURSOR FOR + SELECT id FROM inbound + WHERE !isSync + ORDER BY dated; + + DECLARE cOutbound CURSOR FOR + SELECT id FROM outbound + WHERE !isSync + ORDER BY dated; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + -- Applies changes + + opsLoop: LOOP + START TRANSACTION; + + SET vDone = FALSE; + SELECT id, operation, tableName, tableId + INTO vLogId, vOperation, vTableName, vTableId + FROM `log` + ORDER BY id LIMIT 1 + FOR UPDATE; + + IF vDone THEN + COMMIT; + LEAVE opsLoop; + END IF; + + CALL log_delete(vTableName, vTableId); + + IF vOperation = 'insert' THEN + IF vTableName IN ('travel', 'entry', 'buy') THEN + CALL log_refreshBuy(vTableName, vTableId); + ELSEIF vTableName IN ('ticket', 'sale') THEN + CALL log_refreshSale(vTableName, vTableId); + ELSEIF vTableName IN ('order', 'orderRow') THEN + CALL log_refreshOrder(vTableName, vTableId); + END IF; + END IF; + + DELETE FROM `log` WHERE id = vLogId; + SET vSync = TRUE; + + COMMIT; + END LOOP; + + IF !vSync THEN + LEAVE proc; + END IF; + + -- Deletes expired outbounds + + DELETE FROM outbound WHERE expired <= NOW(); + + -- Attaches desync inbounds + + REPEAT + OPEN cInbound; + SET vHasPendingSync = FALSE; + + inboundLoop: LOOP + SET vDone = FALSE; + FETCH cInbound INTO vInboundFk; + + IF vDone THEN + LEAVE inboundLoop; + END IF; + + START TRANSACTION; + CALL inbound_sync(vInboundFk); + COMMIT; + + SET vHasPendingSync = TRUE; + END LOOP; + + CLOSE cInbound; + UNTIL !vHasPendingSync END REPEAT; + + -- Attaches desync outbounds + + REPEAT + OPEN cOutbound; + SET vHasPendingSync = FALSE; + + outboundLoop: LOOP + SET vDone = FALSE; + FETCH cOutbound INTO vOutboundFk; + + IF vDone THEN + LEAVE outboundLoop; + END IF; + + START TRANSACTION; + CALL outbound_sync(vOutboundFk); + COMMIT; + + SET vHasPendingSync = TRUE; + END LOOP; + + CLOSE cOutbound; + UNTIL !vHasPendingSync END REPEAT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `log_syncNoWait` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `log_syncNoWait`() +BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('stock.log_sync'); + RESIGNAL; + END; + + IF GET_LOCK('stock.log_sync', 0) THEN + CALL log_sync(FALSE); + END IF; + + DO RELEASE_LOCK('stock.log_sync'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `outbound_requestQuantity` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `outbound_requestQuantity`( + vSelf INT, + vRequested INT, + vDated DATETIME, + OUT vSupplied INT) +BEGIN +/** + * Disassociates outbound picks after the given date until the + * demanded quantity is satisfied. + * + * @param vSelf The outbound reference + * @param vRequested The requested quantity + * @param vDate The starting date for the associated inbounds + * @param vSupplied The supplied quantity + */ + DECLARE vInboundFk INT; + DECLARE vPickQuantity INT; + DECLARE vPickGranted INT; + DECLARE vDone BOOL; + + DECLARE vPicks CURSOR FOR + SELECT p.inboundFk, p.quantity + FROM inboundPick p + JOIN inbound i ON i.id = p.inboundFk + WHERE p.outboundFk = vSelf + AND i.dated > vDated + ORDER BY i.dated DESC; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SET vSupplied = 0; + + OPEN vPicks; + + myLoop: LOOP + SET vDone = FALSE; + FETCH vPicks INTO vInboundFk, vPickQuantity; + + IF vDone THEN + LEAVE myLoop; + END IF; + + SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity); + SET vSupplied = vSupplied + vPickGranted; + CALL inbound_removePick(vInboundFk, vSelf, vPickGranted, vPickQuantity); + + UPDATE inbound + SET isSync = FALSE, + available = available + vPickGranted + WHERE id = vInboundFk; + + IF vSupplied >= vRequested THEN + LEAVE myLoop; + END IF; + END LOOP; + + CLOSE vPicks; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `outbound_sync` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `outbound_sync`(vSelf INT) +BEGIN +/** + * Attaches a outbound with available inbounds. + * + * @param vSelf The outbound reference + */ + DECLARE vDated DATETIME; + DECLARE vItem INT; + DECLARE vWarehouse INT; + DECLARE vLack INT; + DECLARE vSupplied INT; + DECLARE vSuppliedFromRequest INT; + DECLARE vInboundFk INT; + DECLARE vAvailable INT; + DECLARE vHasPicks BOOL; + DECLARE vDone BOOL; + + DECLARE vInbounds CURSOR FOR + SELECT id, available, available < quantity + FROM inbound + WHERE warehouseFk = vWarehouse + AND itemFk = vItem + AND dated <= vDated + AND (expired IS NULL OR expired > vDated) + ORDER BY dated; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SELECT warehouseFk, itemFk, dated, lack + INTO vWarehouse, vItem, vDated, vLack + FROM outbound + WHERE id = vSelf; + + OPEN vInbounds; + + myLoop: LOOP + SET vDone = FALSE; + FETCH vInbounds INTO vInboundFk, vAvailable, vHasPicks; + + IF vDone THEN + LEAVE myLoop; + END IF; + + SET vSupplied = LEAST(vLack, vAvailable); + + IF vSupplied > 0 THEN + SET vLack = vLack - vSupplied; + UPDATE inbound + SET available = available - vSupplied + WHERE id = vInboundFk; + END IF; + + IF vHasPicks AND vLack > 0 THEN + CALL inbound_requestQuantity(vInboundFk, vLack, vDated, vSuppliedFromRequest); + SET vSupplied = vSupplied + vSuppliedFromRequest; + SET vLack = vLack - vSuppliedFromRequest; + END IF; + + IF vSupplied > 0 THEN + CALL inbound_addPick(vInboundFk, vSelf, vSupplied); + END IF; + + IF vLack = 0 THEN + LEAVE myLoop; + END IF; + END LOOP; + + CLOSE vInbounds; + + UPDATE outbound + SET isSync = TRUE, + lack = vLack + WHERE id = vSelf; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `visible_log` */; +ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `visible_log`( + vIsPicked BOOL, + vWarehouseFk INT, + vItemFk INT, + vQuantity INT +) +proc: BEGIN + IF !vIsPicked THEN + LEAVE proc; + END IF; + + INSERT INTO visible + SET itemFk = vItemFk, + warehouseFk = vWarehouseFk, + quantity = vQuantity + ON DUPLICATE KEY UPDATE + quantity = quantity + VALUES(quantity); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `stock` CHARACTER SET utf8 COLLATE utf8_general_ci ; + +-- +-- Current Database: `util` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `util` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; + +USE `util`; + +-- +-- Table structure for table `config` +-- + +DROP TABLE IF EXISTS `config`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `config` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `dbVersion` char(11) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The current database version', + `hasTriggersDisabled` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Defines if triggers are disabled', + `environment` varchar(45) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The current Database environment', + `lastDump` datetime DEFAULT NULL COMMENT 'Timestamp of the last data dump', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration table'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `debug` +-- + +DROP TABLE IF EXISTS `debug`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `debug` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `connectionId` int(10) unsigned DEFAULT NULL, + `user` varchar(255) CHARACTER SET utf8 DEFAULT NULL, + `host` varchar(255) CHARACTER SET utf8 DEFAULT NULL, + `variable` varchar(255) CHARACTER SET utf8 DEFAULT NULL, + `value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=546 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Log de depuración'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'util' +-- + +-- +-- Dumping routines for database 'util' +-- +/*!50003 DROP FUNCTION IF EXISTS `capitalizeFirst` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `capitalizeFirst`(vString VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 + NO SQL + DETERMINISTIC +BEGIN +/** + * Pass the first letter of every word in a string to uppercase. + * + * @param vString String to tranform + * @return Transformed string + */ + DECLARE vNewString VARCHAR(255) DEFAULT ''; + DECLARE vI INT DEFAULT 1; + DECLARE vSpaceIni, vWordIni INT; + DECLARE vLen INT DEFAULT CHAR_LENGTH(vString); + + WHILE vI < vLen + DO + SET vSpaceIni = vI; + + WHILE MID(vString, vI, 1) REGEXP '[[:space:]]' DO + SET vI = vI + 1; + END WHILE; + + SET vWordIni = vI; + SET vI = vWordIni + 1; + + WHILE vI <= vLen AND MID(vString, vI, 1) NOT REGEXP '[[:space:]]' DO + SET vI = vI + 1; + END WHILE; + + SET vNewString = CONCAT(vNewString + ,MID(vString, vSpaceIni, vWordIni - vSpaceIni) + ,UPPER(MID(vString, vWordIni, 1)) + ,MID(vString, vWordIni + 1, vI - vWordIni - 1) + ); + END WHILE; + + RETURN vNewString; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `crypt` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `crypt`(vText VARCHAR(255), vKey VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 + READS SQL DATA +BEGIN + + DECLARE vResult VARCHAR(255); + + CALL vn.crypt(vText, vKey, vResult); + + RETURN vResult; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `cryptOff` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `cryptOff`(vText VARCHAR(255), vKey VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 + READS SQL DATA +BEGIN + + DECLARE vResult VARCHAR(255); + + CALL vn.cryptOff(vText, vKey, vResult); + + RETURN vResult; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `dayEnd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `dayEnd`(vDated DATE) RETURNS datetime + NO SQL + DETERMINISTIC +BEGIN +/** + * Formats a date to the end of the day. + * + * @param vDated The date to format + * @return The formatted date + */ + RETURN TIMESTAMP(vDated, '23:59:59'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `firstDayOfMonth` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `firstDayOfMonth`(vDate DATE) RETURNS date + NO SQL + DETERMINISTIC +BEGIN +/** + * Returns the date formatted to the first day of month. + * + * @param vDate The date to format + * @return The formatted date + */ + RETURN DATE_FORMAT(vDate, '%Y-%m-01'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `firstDayOfYear` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `firstDayOfYear`(vDate DATE) RETURNS date + NO SQL + DETERMINISTIC +BEGIN +/** + * Returns the date formatted to the first day of year. + * + * @param vDate The date to format + * @return The formatted date + */ + RETURN DATE_FORMAT(vDate, '%Y-01-01'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `hmacSha2` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `hmacSha2`(`vAlg` SMALLINT, `vMsg` MEDIUMBLOB, `vKey` MEDIUMBLOB) RETURNS varchar(128) CHARSET utf8 + NO SQL + DETERMINISTIC +BEGIN +/** + * HMAC function based on SHA2 algorythms. + */ + DECLARE vHashlen INT UNSIGNED; + DECLARE vOpad, vIpad TINYBLOB; + + CASE vAlg + WHEN 224 THEN SET vHashlen = 64; + WHEN 256 THEN SET vHashlen = 64; + WHEN 384 THEN SET vHashlen = 128; + WHEN 512 THEN SET vHashlen = 128; + ELSE CALL throw ('WRONG_ALGORYTHM_IDENTIFICATOR_USED'); + END CASE; + + IF LENGTH(vKey) > vHashlen THEN + SET vKey = UNHEX(SHA2(vKey, vAlg)); + END IF; + + SET vKey = RPAD(vKey, vHashlen, 0x00); + + SET vIpad = stringXor(vKey, 0x36); + SET vOpad = stringXor(vKey, 0x5C); + + RETURN SHA2(CONCAT(vOpad, UNHEX(SHA2(CONCAT(vIpad, vMsg), vAlg))), vAlg); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `lang` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `lang`() RETURNS char(2) CHARSET utf8 + NO SQL + DETERMINISTIC +BEGIN +/** + * Returns the current language code. + * + * @return The language code + */ + RETURN IFNULL(@lang, SUBSTR(@@lc_messages, 1, 2)); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `nextWeek` */; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `nextWeek`(vYearWeek INT) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * A partir de un perido año/semana en formato AAAASS devuelve el siguiente + * periodo. Esta función trabaja de la misma forma que la función WEEK() en + * modo 3. + */ + DECLARE vYear INT DEFAULT FLOOR(vYearWeek / 100); + + IF vYearWeek < YEARWEEK(CONCAT(vYear, '-12-31'), 3) THEN + RETURN vYearWeek + 1; + ELSE + RETURN ((vYear + 1) * 100) + 1; + 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 */ ; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP FUNCTION IF EXISTS `stringXor` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `stringXor`(vString MEDIUMBLOB, vConst TINYINT UNSIGNED) RETURNS mediumblob + NO SQL + DETERMINISTIC +BEGIN +/** + * Returns XOR of binary string and an 8-bit constant. + */ + DECLARE vLen, vPos INT UNSIGNED; + DECLARE vResult MEDIUMBLOB; + + SET vLen = LENGTH(vString); + SET vPos = 1; + SET vResult = ''; + + WHILE vPos <= vLen DO + SET vResult = CONCAT(vResult, LPAD(HEX( ORD(SUBSTR(vString, vPos, 1)) ^ vConst), 2, '0')); + SET vPos = vPos + 1; + END WHILE; + + RETURN UNHEX(vResult); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `today` */; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `today`() RETURNS date + DETERMINISTIC +BEGIN +/** + * Devuelve la fecha actual. Usar en lugar de la función nativa + * CURDATE() en aquellos que se necesite rendimiento ya que la + * la última no es determinista. + * + * @return La fecha actual + */ + RETURN CURDATE(); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP FUNCTION IF EXISTS `tomorrow` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `tomorrow`() RETURNS date + DETERMINISTIC +BEGIN +/** + * Devuelve la fecha de mañana. + * + * @return La fecha de mañana + */ + RETURN TIMESTAMPADD(DAY, 1, CURDATE()); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `twoDaysAgo` */; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `twoDaysAgo`() RETURNS date + DETERMINISTIC +BEGIN +/** + * Devuelve la fecha de antes de ayer. + * + * @return La fecha de antes de ayer + */ + RETURN TIMESTAMPADD(DAY, -2, CURDATE()); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP FUNCTION IF EXISTS `yearRelativePosition` */; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `yearRelativePosition`(vYear INT) RETURNS varchar(20) CHARSET utf8 + DETERMINISTIC +BEGIN +/** + * Devuelve la posicion del año relativa al año actual. + * Se utiliza como cabecera en informes de balances. + * + * @param vYear Año a evaluar + * @return La posicion relativa del año + */ + DECLARE vCurYear INT DEFAULT YEAR(CURDATE()); + + IF vYear = vCurYear THEN + RETURN 'curYear'; + END IF; + + IF vYear = vCurYear - 1 THEN + RETURN 'lastYear'; + END IF; + + IF vYear = vCurYear - 2 THEN + RETURN 'twoYearsAgo'; + END IF; + + RETURN 'other'; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP FUNCTION IF EXISTS `yesterday` */; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `yesterday`() RETURNS date + DETERMINISTIC +BEGIN +/** + * Devuelve la fecha de ayer. + * + * @return La fecha de ayer + */ + RETURN TIMESTAMPADD(DAY, -1, CURDATE()); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `compareObjects` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `compareObjects`(vChain VARCHAR(45),vCompare VARCHAR(45)) + READS SQL DATA +BEGIN +/** + * Devuelve un listado de todos los procedimientos, funciones + * eventos, disparadores y vistas que estan incluidos en las dos cadenadas dadas. + * + * Es util para buscar una columna de una tabla en concreto + * @param vChain Cadena a buscar + * @param vCompare Cadena a buscar y comparar los resultados con la primera cadena + * @select Listado de objetos + */ + SET vChain = CONCAT('%', vChain, '%'); + SET vCompare = CONCAT('%', vCompare, '%'); + SELECT * FROM + ( + SELECT t1.* FROM + ( + SELECT + `db`, + `name`, + `type`, + `body`, + `created`, + `modified` + FROM `mysql`.`proc` + WHERE `body` LIKE vChain COLLATE utf8_general_ci + UNION ALL + SELECT + `db`, + `name`, + 'EVENT', + `body_utf8`, + `created`, + `modified` + FROM `mysql`.`event` + WHERE `body_utf8` LIKE vChain COLLATE utf8_general_ci + UNION ALL + SELECT + `EVENT_OBJECT_SCHEMA`, + `TRIGGER_NAME`, + 'TRIGGER', + `ACTION_STATEMENT`, + NULL, + NULL + FROM `information_schema`.`TRIGGERS` + WHERE `ACTION_STATEMENT` LIKE vChain COLLATE utf8_general_ci + UNION ALL + SELECT + `TABLE_SCHEMA`, + `TABLE_NAME`, + 'VIEW', + `VIEW_DEFINITION`, + NULL, + NULL + FROM `information_schema`.`VIEWS` + WHERE `VIEW_DEFINITION` LIKE vChain COLLATE utf8_general_ci + ) t1 + JOIN ( + SELECT + `db`, + `name`, + `type`, + `body`, + `created`, + `modified` + FROM `mysql`.`proc` + WHERE `body` LIKE vCompare COLLATE utf8_general_ci + UNION ALL + SELECT + `db`, + `name`, + 'EVENT', + `body_utf8`, + `created`, + `modified` + FROM `mysql`.`event` + WHERE `body_utf8` LIKE vCompare COLLATE utf8_general_ci + UNION ALL + SELECT + `EVENT_OBJECT_SCHEMA`, + `TRIGGER_NAME`, + 'TRIGGER', + `ACTION_STATEMENT`, + NULL, + NULL + FROM `information_schema`.`TRIGGERS` + WHERE `ACTION_STATEMENT` LIKE vCompare COLLATE utf8_general_ci + UNION ALL + SELECT + `TABLE_SCHEMA`, + `TABLE_NAME`, + 'VIEW', + `VIEW_DEFINITION`, + NULL, + NULL + FROM `information_schema`.`VIEWS` + WHERE `VIEW_DEFINITION` LIKE vCompare COLLATE utf8_general_ci) t2 ON t2.name = t1.name + ORDER BY t1.`db`, t1.`name` + ) t; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `debugAdd` */; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `debugAdd`(vVariable VARCHAR(255), vValue VARCHAR(255)) + MODIFIES SQL DATA +BEGIN +/** + * Añade una entrada de depuración en la tabla @debug. + * + * @param vVariable Nombre de variable + * @param vValue Valor de la variable + */ + DECLARE vIndex INT DEFAULT INSTR(USER(), '@'); + + INSERT INTO debug SET + `connectionId` = CONNECTION_ID(), + `user` = LEFT(USER(), vIndex - 1), + `host` = RIGHT(USER(), CHAR_LENGTH(USER()) - vIndex), + `variable` = vVariable, + `value` = vValue; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `exec` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `exec`(vSqlQuery TEXT) +BEGIN +/** + * Executes a string with an SQL query. + * + * @param vSqlQuery The SQL string + */ + SET @sqlQuery = vSqlQuery; + + PREPARE stmt FROM @sqlQuery; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + + SET @sqlQuery = NULL; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `findObject` */; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `findObject`(vChain VARCHAR(45)) + READS SQL DATA +BEGIN +/** + * Devuelve un listado de todos los procedimientos, funciones + * eventos, disparadores y vistas que inluyen una cadena dada. + * + * @param vChain Cadena a buscar + * @select Listado de objetos + */ + SET vChain = CONCAT('%', vChain, '%'); + + SELECT * FROM + ( + SELECT + `db`, + `name`, + `type`, + `body`, + `created`, + `modified` + FROM `mysql`.`proc` + WHERE `body` LIKE vChain COLLATE utf8_general_ci + UNION ALL + SELECT + `db`, + `name`, + 'EVENT', + `body_utf8`, + `created`, + `modified` + FROM `mysql`.`event` + WHERE `body_utf8` LIKE vChain COLLATE utf8_general_ci + UNION ALL + SELECT + `EVENT_OBJECT_SCHEMA`, + `TRIGGER_NAME`, + 'TRIGGER', + `ACTION_STATEMENT`, + NULL, + NULL + FROM `information_schema`.`TRIGGERS` + WHERE `ACTION_STATEMENT` LIKE vChain COLLATE utf8_general_ci + UNION ALL + SELECT + `TABLE_SCHEMA`, + `TABLE_NAME`, + 'VIEW', + `VIEW_DEFINITION`, + NULL, + NULL + FROM `information_schema`.`VIEWS` + WHERE `VIEW_DEFINITION` LIKE vChain COLLATE utf8_general_ci + ) t + ORDER BY `db`, `name`; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `proc_changedPrivs` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `proc_changedPrivs`() +BEGIN + SELECT s.* + FROM proc_privs s + LEFT JOIN mysql.procs_priv p + ON p.`Host` = s.`Host` + AND p.`Host` = s.`Host` + AND p.`Db` = s.`Db` + AND p.`User` = s.`User` + AND p.`Routine_name` = s.`Routine_name` + AND p.`Routine_type` = s.`Routine_type` + WHERE p.Proc_priv IS NULL; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `proc_restorePrivs` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `proc_restorePrivs`() +BEGIN +/** + * Restores the privileges saved by proc_savePrivs(). + * This procedure should be called after modifying a procedure, + * for more info see proc_savePrivs(). + */ + INSERT IGNORE INTO mysql.procs_priv + SELECT * FROM proc_privs; + + FLUSH PRIVILEGES; + DROP TEMPORARY TABLE proc_privs; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `proc_savePrivs` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `proc_savePrivs`() +BEGIN +/** + * Saves routine privileges, used to simplify the task of keeping + * routine privileges when they are modified due to the lack of + * CREATE OR REPLACE [PROCEDURE|FUNCTION]. + * This procedure should be called before modifying a routine, to + * restore the saved privileges use proc_restorePrivs(). + */ + CREATE TEMPORARY TABLE proc_privs + ENGINE = MEMORY + SELECT * FROM mysql.procs_priv; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `throw` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `throw`(vMessage CHAR(35)) +BEGIN +/** + * Throws a user-defined exception. + * + * @param vMessage The error message + */ + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = vMessage; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `warn` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `warn`(vCode CHAR(35)) +BEGIN + DECLARE w VARCHAR(1) DEFAULT '__'; + SET @warn = vCode; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Current Database: `vn` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; + +USE `vn`; + +-- +-- Table structure for table `XDiario` +-- + +DROP TABLE IF EXISTS `XDiario`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `XDiario` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `ASIEN` double DEFAULT NULL, + `FECHA` datetime DEFAULT NULL, + `SUBCTA` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL, + `CONTRA` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL, + `CONCEPTO` varchar(50) CHARACTER SET utf8 DEFAULT NULL, + `EURODEBE` decimal(10,2) DEFAULT NULL, + `EUROHABER` decimal(10,2) DEFAULT NULL, + `BASEEURO` decimal(10,2) DEFAULT NULL, + `SERIE` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, + `FACTURA` varchar(8) COLLATE utf8_unicode_ci DEFAULT '0', + `BASEIMPO` decimal(10,2) DEFAULT NULL, + `IVA` decimal(10,2) DEFAULT NULL, + `RECEQUIV` decimal(10,2) DEFAULT '0.00', + `DOCUMENTO` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `DEPARTA` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `CLAVE` int(11) DEFAULT NULL, + `ESTADO` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, + `NCASADO` decimal(10,2) DEFAULT NULL, + `TCASADO` decimal(10,2) DEFAULT NULL, + `TRANS` decimal(10,2) DEFAULT NULL, + `CAMBIO` decimal(10,2) DEFAULT NULL, + `DEBEME` decimal(10,2) DEFAULT NULL, + `HABERME` decimal(10,2) DEFAULT NULL, + `PTAHABER` decimal(10,2) DEFAULT NULL, + `AUXILIAR` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, + `SUCURSAL` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL, + `PTADEBE` decimal(10,2) DEFAULT NULL, + `CODDIVISA` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, + `IMPAUXME` decimal(10,2) DEFAULT NULL, + `MONEDAUSO` varchar(1) COLLATE utf8_unicode_ci DEFAULT '2', + `NOCONV` tinyint(1) NOT NULL DEFAULT '0', + `NUMEROINV` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `TIPOOPE` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, + `NFACTICK` tinyint(1) NOT NULL DEFAULT '1', + `TERIDNIF` tinyint(1) NOT NULL DEFAULT '2', + `TERNIF` varchar(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'I.F.', + `TERNOM` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Nombre Importador', + `OPBIENES` tinyint(1) NOT NULL DEFAULT '1', + `TIPOFAC` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, + `TIPOIVA` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, + `L340` tinyint(2) NOT NULL DEFAULT '0', + `enlazado` tinyint(1) NOT NULL DEFAULT '0', + `FECHA_EX` date DEFAULT NULL COMMENT 'FEcha de expedicion de la factura', + `LRECT349` tinyint(1) NOT NULL DEFAULT '0', + `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', + `LDIFADUAN` tinyint(4) NOT NULL DEFAULT '0', + `METAL` tinyint(1) NOT NULL DEFAULT '0', + `METALIMP` decimal(10,2) NOT NULL DEFAULT '0.00', + `CLIENTE` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL, + `METALEJE` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL, + `FECHA_OP` date DEFAULT NULL COMMENT 'FEcha de operacion', + `FACTURAEX` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Numero de factura del proveedor', + `TIPOCLAVE` int(3) DEFAULT NULL, + `TIPOEXENCI` int(3) DEFAULT NULL, + `TIPONOSUJE` int(3) DEFAULT NULL, + `TIPOFACT` int(3) DEFAULT NULL, + `TIPORECTIF` int(3) DEFAULT NULL, + `SERIE_RT` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, + `FACTU_RT` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `BASEIMP_RT` decimal(10,2) DEFAULT NULL, + `BASEIMP_RF` decimal(10,2) DEFAULT NULL, + `RECTIFICA` int(1) NOT NULL DEFAULT '0', + `FECHA_RT` date DEFAULT NULL, + `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `updated` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `FECREGCON` date DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `empresa_id` (`empresa_id`), + CONSTRAINT `XDiario_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=4095537 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`XDiario_beforeInsert` BEFORE INSERT ON `XDiario` FOR EACH ROW +BEGIN +/* + IF NEW.EURODEBE < 0 THEN + + SET NEW.EUROHABER = - NEW.EURODEBE; + SET NEW.EURODEBE = NULL; + + END IF; + + IF NEW.EUROHABER < 0 THEN + + SET NEW.EURODEBE = - NEW.EUROHABER; + SET NEW.EUROHABER = NULL; + + END IF; + + IF NEW.DEBEME < 0 THEN + + SET NEW.HABERME = - NEW.DEBEME; + SET NEW.DEBEME = NULL; + + END IF; + + IF NEW.HABERME < 0 THEN + + SET NEW.DEBEME = - NEW.HABERME; + SET NEW.HABERME = NULL; + 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 */ ; + +-- +-- Temporary view structure for view `absenceType` +-- + +DROP TABLE IF EXISTS `absenceType`; +/*!50001 DROP VIEW IF EXISTS `absenceType`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `absenceType` AS SELECT + 1 AS `id`, + 1 AS `name`, + 1 AS `rgb`, + 1 AS `code`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `accountingType` +-- + +DROP TABLE IF EXISTS `accountingType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `accountingType` ( + `id` smallint(6) NOT NULL DEFAULT '0', + `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='descripcio dels valors de la columna "cash" de la taula vn2008.Bancios'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `activeContrat` +-- + +DROP TABLE IF EXISTS `activeContrat`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `activeContrat` ( + `date` date NOT NULL, + `business_id` int(11) NOT NULL, + PRIMARY KEY (`date`,`business_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `activityTaxDismissed` +-- + +DROP TABLE IF EXISTS `activityTaxDismissed`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `activityTaxDismissed` ( + `clientFk` int(11) NOT NULL, + `isNotified` tinyint(1) DEFAULT '0', + `isDismissed` tinyint(1) DEFAULT '0', + `notified` int(11) DEFAULT '0', + PRIMARY KEY (`clientFk`), + CONSTRAINT `clientFk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `address` +-- + +DROP TABLE IF EXISTS `address`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `address` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `clientFk` int(11) NOT NULL DEFAULT '0', + `warehouseFk` smallint(6) unsigned DEFAULT '1', + `street` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `city` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `provinceFk` smallint(5) unsigned DEFAULT NULL, + `postalCode` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `phone` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `mobile` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `nickname` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL, + `isDefaultAddress` tinyint(1) NOT NULL DEFAULT '0', + `agencyModeFk` int(11) NOT NULL DEFAULT '2', + `notes` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `hasInsurance` tinyint(1) NOT NULL DEFAULT '0', + `porte` double DEFAULT NULL, + `isActive` tinyint(4) NOT NULL DEFAULT '1', + `postcodeOLD` int(11) unsigned DEFAULT NULL, + `longitude` decimal(11,7) DEFAULT NULL, + `latitude` decimal(11,7) DEFAULT NULL, + `codPosOld` char(5) COLLATE utf8_unicode_ci DEFAULT NULL, + `isEqualizated` tinyint(1) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `Id_Agencia` (`agencyModeFk`), + KEY `Id_cliente` (`clientFk`), + KEY `warehouse_id` (`warehouseFk`), + KEY `province_id` (`provinceFk`), + KEY `telefono` (`phone`), + KEY `movil` (`mobile`), + KEY `CODPOSTAL` (`postalCode`), + CONSTRAINT `address_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE, + CONSTRAINT `address_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `address_ibfk_3` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE, + CONSTRAINT `address_ibfk_4` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=29842 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`address_beforeInsert` + BEFORE INSERT ON `vn`.`address` FOR EACH ROW +BEGIN + DECLARE vIsEqualizated BOOL; + + CALL pbx.phone_isValid(NEW.phone); + CALL pbx.phone_isValid(NEW.mobile); + + IF NEW.isEqualizated IS NULL THEN + SELECT isEqualizated + INTO vIsEqualizated + FROM client + WHERE id = NEW.clientFk; + + SET NEW.isEqualizated = vIsEqualizated; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`address_beforeUpdate` + BEFORE UPDATE ON `vn`.`address` FOR EACH ROW +BEGIN + CALL pbx.phone_isValid(NEW.phone); + CALL pbx.phone_isValid(NEW.mobile); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`address_afterUpdate` + AFTER UPDATE ON `address` FOR EACH ROW +BEGIN + -- Recargos de equivalencia distintos implican facturacion por consignatario + IF NEW.isEqualizated != OLD.isEqualizated THEN + IF + (SELECT COUNT(*) FROM + ( + SELECT DISTINCT (isEqualizated = FALSE) as Equ + FROM address + WHERE clientFk = NEW.clientFk + ) t1 + ) > 1 + THEN + UPDATE client + SET hasToInvoiceByAddress = TRUE + WHERE id = NEW.clientFk; + END IF; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `addressForPackaging` +-- + +DROP TABLE IF EXISTS `addressForPackaging`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `addressForPackaging` ( + `addressFk` int(11) NOT NULL, + `packagingValue` decimal(10,2) NOT NULL DEFAULT '0.04', + PRIMARY KEY (`addressFk`), + CONSTRAINT `addresForPackaging_fk1` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `addressObservation` +-- + +DROP TABLE IF EXISTS `addressObservation`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `addressObservation` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `addressFk` int(11) NOT NULL, + `observationTypeFk` tinyint(3) unsigned NOT NULL, + `description` text COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `Id_Consigna` (`addressFk`,`observationTypeFk`), + KEY `addressObservationFgn_idx` (`observationTypeFk`), + CONSTRAINT `addressFgn` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `addressObservationFgn` FOREIGN KEY (`observationTypeFk`) REFERENCES `observationType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=4245 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Observaciones de los consignatarios'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `agency` +-- + +DROP TABLE IF EXISTS `agency`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `agency` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, + `warehouseFk` smallint(5) unsigned DEFAULT NULL COMMENT 'A nulo si se puede enrutar desde todos los almacenes', + `isVolumetric` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Si el calculo del porte se hacer por volumen', + `bankFk` int(11) NOT NULL DEFAULT '8' COMMENT 'para realizar los reembolsos', + `warehouseAliasFk` smallint(5) unsigned DEFAULT NULL, + `isOwn` tinyint(1) NOT NULL DEFAULT '0', + `labelZone` tinyint(4) NOT NULL DEFAULT '0', + `workCenterFk` int(11) DEFAULT NULL, + `supplierFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `warehouse_id` (`warehouseFk`), + KEY `Id_Banco` (`bankFk`), + KEY `agencias_alias_idx` (`warehouseAliasFk`), + KEY `agency_ibfk_3_idx` (`workCenterFk`), + KEY `agency_ibfk_4_idx` (`supplierFk`), + CONSTRAINT `agency_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `agency_ibfk_2` FOREIGN KEY (`bankFk`) REFERENCES `bank` (`id`) ON UPDATE CASCADE, + CONSTRAINT `agency_ibfk_3` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`) ON UPDATE CASCADE, + CONSTRAINT `agency_ibfk_4` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=287 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`agency_afterInsert` AFTER INSERT ON `vn`.`agency` FOR EACH ROW +BEGIN + INSERT INTO agencyMode(name,agencyFk) VALUES(NEW.name,NEW.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 */ ; + +-- +-- Table structure for table `agencyMode` +-- + +DROP TABLE IF EXISTS `agencyMode`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `agencyMode` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `description` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `deliveryMethodFk` int(11) DEFAULT '0', + `m3` double DEFAULT '0', + `cod71` tinyint(3) unsigned DEFAULT '0', + `web` smallint(1) unsigned zerofill NOT NULL DEFAULT '0', + `agencyFk` smallint(6) NOT NULL, + `agencyServiceFk` tinyint(4) NOT NULL DEFAULT '1', + `inflation` decimal(5,2) NOT NULL DEFAULT '0.00' COMMENT 'Este valor se utiliza para aumentar el valor del componente porte.', + `isVolumetric` tinyint(1) NOT NULL DEFAULT '0', + `reportMail` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `showAgencyName` tinyint(1) DEFAULT '1' COMMENT 'obsoleta', + `isActive` tinyint(1) NOT NULL DEFAULT '1', + `isExternalAgency` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'obsoleta', + `flag` blob COMMENT 'obsoleta', + `code` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `Agencias` (`name`), + KEY `Vista` (`deliveryMethodFk`) +) ENGINE=InnoDB AUTO_INCREMENT=1243 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `alertLevel` +-- + +DROP TABLE IF EXISTS `alertLevel`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `alertLevel` ( + `code` varchar(45) CHARACTER SET utf8 NOT NULL, + `alertLevel` int(11) NOT NULL, + PRIMARY KEY (`code`), + CONSTRAINT `fk_code_1` FOREIGN KEY (`code`) REFERENCES `state` (`code`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `annualAverageInvoiced` +-- + +DROP TABLE IF EXISTS `annualAverageInvoiced`; +/*!50001 DROP VIEW IF EXISTS `annualAverageInvoiced`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `annualAverageInvoiced` AS SELECT + 1 AS `clientFk`, + 1 AS `invoiced`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `assignedTicketToWorker` +-- + +DROP TABLE IF EXISTS `assignedTicketToWorker`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `assignedTicketToWorker` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `idWorker` int(11) DEFAULT NULL, + `idTicket` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `idWorker_UNIQUE` (`idWorker`), + UNIQUE KEY `idTicket_UNIQUE` (`idTicket`) +) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla para relacionar un ticket con el sacador del altillo '; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `autoRadioConfig` +-- + +DROP TABLE IF EXISTS `autoRadioConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `autoRadioConfig` ( + `id` int(11) NOT NULL, + `password` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `user` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `port` int(11) DEFAULT NULL, + `url` varchar(75) COLLATE utf8_unicode_ci DEFAULT NULL, + `login` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `client` int(32) DEFAULT NULL, + `center` int(32) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `autoRadioLogCall` +-- + +DROP TABLE IF EXISTS `autoRadioLogCall`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `autoRadioLogCall` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `ticketFk` int(11) NOT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `response` longtext COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `ticket_idx` (`ticketFk`), + CONSTRAINT `ticket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=1896 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `autonomousRegion` +-- + +DROP TABLE IF EXISTS `autonomousRegion`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `autonomousRegion` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(50) CHARACTER SET utf8 NOT NULL, + `geoFk` int(11) DEFAULT NULL, + `countryFk` mediumint(8) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `countryFk` (`countryFk`), + CONSTRAINT `countryFk` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `bank` +-- + +DROP TABLE IF EXISTS `bank`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `bank` ( + `id` int(11) NOT NULL DEFAULT '0', + `bank` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `account` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `cash` smallint(6) NOT NULL DEFAULT '0', + `warehouseFk` smallint(5) unsigned NOT NULL DEFAULT '1', + `entityFk` int(10) unsigned NOT NULL, + `isActive` tinyint(4) NOT NULL DEFAULT '1', + `currencyFk` tinyint(3) unsigned DEFAULT '1', + `code` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `BancosBanco` (`bank`), + KEY `fk_Bancos_entity1_idx` (`entityFk`), + KEY `foreignkey1_idx` (`cash`), + KEY `Bancoscurrency_idx` (`currencyFk`), + CONSTRAINT `Bancoscurrency` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE, + CONSTRAINT `foreignkey1` FOREIGN KEY (`cash`) REFERENCES `accountingType` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Apunta a la vista vn.Accounting\nLa columna cash es la FK de vn.AccountingType'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `bankEntity` +-- + +DROP TABLE IF EXISTS `bankEntity`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `bankEntity` ( + `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1', + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `bic` varchar(11) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `bic_UNIQUE` (`bic`), + KEY `fg_entity1_idx` (`countryFk`), + CONSTRAINT `fg_entity1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=30055 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Entidades bancarias '; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `bionicConfig` +-- + +DROP TABLE IF EXISTS `bionicConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `bionicConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `generalInflationCoeficient` double(10,2) NOT NULL, + `minimumDensityVolumetricWeight` double(10,2) NOT NULL, + `verdnaturaVolumeBox` int(11) NOT NULL, + `itemCarryBox` int(11) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `bookingPlanner` +-- + +DROP TABLE IF EXISTS `bookingPlanner`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `bookingPlanner` ( + `id` int(10) NOT NULL AUTO_INCREMENT, + `effectived` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `pgcFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `taxAreaFk` varchar(15) CHARACTER SET utf8 NOT NULL DEFAULT 'SPAIN', + `priority` int(2) unsigned DEFAULT NULL, + `taxClassFk` tinyint(3) unsigned NOT NULL DEFAULT '1', + `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + KEY `pgcFk_bookingPlanner_idx` (`pgcFk`), + KEY `taxClassFk` (`taxClassFk`), + KEY `countryFk` (`countryFk`), + KEY `bookingPlannerIdx3` (`taxAreaFk`,`taxClassFk`,`countryFk`), + CONSTRAINT `bookingPlannerTaxArea` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON UPDATE CASCADE, + CONSTRAINT `bookingPlanner_ibfk_1` FOREIGN KEY (`pgcFk`) REFERENCES `pgc` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `bookingPlanner_ibfk_2` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `bookingPlanner_ibfk_3` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=86 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `botanicExport` +-- + +DROP TABLE IF EXISTS `botanicExport`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `botanicExport` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `ediGenusFk` mediumint(8) unsigned NOT NULL, + `ediSpecieFk` mediumint(8) unsigned DEFAULT NULL, + `countryFk` mediumint(8) unsigned DEFAULT NULL, + `restriction` enum('Sin restriccion','Importacion Prohibida','pasaporte fitosanitario','pasaporte individual','declaracion origen') CHARACTER SET utf8 NOT NULL, + `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `isProtectedZone` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `Id_Paises` (`countryFk`), + CONSTRAINT `botanicExport_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=340 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Especifica los generos y especies prohibidos en paises'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`botanicExport_beforeInsert` BEFORE INSERT ON `botanicExport` FOR EACH ROW +BEGIN + IF (SELECT botanicExport_isUpdatable (NEW.ediGenusFk, NEW.ediSpecieFk, NEW.countryFk, NEW.restriction) ) > 0 THEN + CALL util.throw ('Datos duplicados'); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `businessReasonEnd` +-- + +DROP TABLE IF EXISTS `businessReasonEnd`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `businessReasonEnd` ( + `id` tinyint(3) NOT NULL AUTO_INCREMENT, + `reason` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `buy` +-- + +DROP TABLE IF EXISTS `buy`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `buy` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `entryFk` int(11) NOT NULL DEFAULT '0', + `itemFk` int(11) NOT NULL DEFAULT '90', + `quantity` int(11) DEFAULT '0', + `dispatched` int(11) NOT NULL DEFAULT '0', + `buyingValue` decimal(10,3) DEFAULT '0.000', + `freightValue` decimal(10,3) DEFAULT '0.000', + `isIgnored` tinyint(1) NOT NULL DEFAULT '0', + `stickers` int(11) DEFAULT '0', + `packing` int(11) DEFAULT '0', + `grouping` smallint(5) unsigned NOT NULL DEFAULT '1', + `groupingMode` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0=sin obligar 1=groping 2=packing', + `containerFk` smallint(5) unsigned DEFAULT NULL, + `comissionValue` decimal(10,3) DEFAULT '0.000', + `packageValue` decimal(10,3) DEFAULT '0.000', + `location` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, + `packageFk` varchar(10) COLLATE utf8_unicode_ci DEFAULT '--', + `price1` decimal(10,2) DEFAULT '0.00', + `price2` decimal(10,2) DEFAULT '0.00', + `price3` decimal(10,2) DEFAULT '0.00', + `minPrice` decimal(10,2) DEFAULT '0.00', + `producer` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `printedStickers` int(11) DEFAULT '0', + `workerFk` int(11) DEFAULT '0', + `isChecked` tinyint(1) NOT NULL DEFAULT '0', + `isPickedOff` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Esta mercancia no va a la zona de picking.', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `__cm2` int(10) unsigned NOT NULL DEFAULT '0', + `ektFk` int(11) DEFAULT NULL, + `weight` decimal(10,2) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `CompresId_Trabajador` (`workerFk`), + KEY `Id_Cubo` (`packageFk`), + KEY `Id_Entrada` (`entryFk`), + KEY `container_id` (`containerFk`), + KEY `buy_edi_id` (`ektFk`), + KEY `itemFk_entryFk` (`itemFk`,`entryFk`), + CONSTRAINT `buy_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE, + CONSTRAINT `buy_ibfk_2` FOREIGN KEY (`packageFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE, + CONSTRAINT `buy_id` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `buy_itemfk` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=358205565 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_beforeInsert` + BEFORE INSERT ON `buy` + FOR EACH ROW +trig: BEGIN + DECLARE vWarehouse INT; + DECLARE vLanding DATE; + DECLARE vGrouping INT; + DECLARE vGroupingMode TINYINT; + + IF @isModeInventory THEN + LEAVE trig; + END IF; + + CALL buy_checkGrouping(NEW.`grouping`); + + SELECT t.warehouseInFk, t.landed INTO vWarehouse, vLanding + FROM entry e + JOIN travel t ON t.id = e.travelFk + WHERE e.id = NEW.entryFk; + + SELECT b.`grouping`, b.groupingMode INTO vGrouping, vGroupingMode + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed <= vLanding + AND b.itemFk = NEW.itemFk + AND !b.isIgnored + ORDER BY t.warehouseInFk = vWarehouse DESC, t.landed DESC, b.id DESC + LIMIT 1; + + IF NEW.`grouping` IS NULL THEN + SET NEW.`grouping` = vGrouping; + END IF; + + IF NEW.groupingMode IS NULL THEN + SET NEW.groupingMode = vGroupingMode; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_afterInsert` + AFTER INSERT ON `buy` + FOR EACH ROW +trig: BEGIN + CALL stock.log_add('buy', NEW.id, NULL); + + IF @isModeInventory THEN + LEAVE trig; + END IF; + + CALL buy_afterUpsert(NEW.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_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_beforeUpdate` + BEFORE UPDATE ON `buy` + FOR EACH ROW +BEGIN + IF !(NEW.`grouping` <=> OLD.`grouping`) THEN + CALL buy_checkGrouping(NEW.`grouping`); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_afterUpdate` + AFTER UPDATE ON `buy` + FOR EACH ROW +trig: BEGIN + IF !(NEW.id <=> OLD.id) + OR !(NEW.entryFk <=> OLD.entryFk) + OR !(NEW.itemFk <=> OLD.itemFk) + OR !(NEW.quantity <=> OLD.quantity) + OR !(NEW.created <=> OLD.created) THEN + CALL stock.log_add('buy', NEW.id, OLD.id); + END IF; + + IF @isModeInventory THEN + LEAVE trig; + END IF; + + CALL buy_afterUpsert(NEW.id); + + IF (!(NEW.weight <=> OLD.weight) OR !(NEW.packing <=> OLD.packing) OR !(NEW.packageFk <=> OLD.packageFk)) AND NEW.weight THEN + UPDATE item + SET density = NEW.weight / (item_getVolume(NEW.itemFk, NEW.packageFk) / 1000000) + WHERE id = NEW.itemFk; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_beforeDelete` + BEFORE DELETE ON `buy` + FOR EACH ROW +BEGIN + IF OLD.printedStickers > 0 THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'A buy from which labels have been printed cannot be deleted'; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `buy_afterDelete` + AFTER DELETE ON `buy` + FOR EACH ROW +BEGIN + CALL stock.log_add('buy', NULL, OLD.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 */ ; + +-- +-- Table structure for table `buyMark` +-- + +DROP TABLE IF EXISTS `buyMark`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `buyMark` ( + `id` int(11) NOT NULL, + `comment` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `mark` tinyint(1) DEFAULT NULL, + `odbcDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + CONSTRAINT `Compres_mark_ibfk_1` FOREIGN KEY (`id`) REFERENCES `buy` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `calendarHolidays` +-- + +DROP TABLE IF EXISTS `calendarHolidays`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `calendarHolidays` ( + `calendarHolidaysTypeFk` int(11) NOT NULL, + `dated` date NOT NULL, + `calendarHolidaysNameFk` int(11) DEFAULT NULL, + `workCenterFk` int(11) NOT NULL, + PRIMARY KEY (`dated`,`workCenterFk`), + KEY `calendarholidaystypeFk_idx` (`calendarHolidaysTypeFk`), + KEY `calendarHolidaysNameFk_idx` (`calendarHolidaysNameFk`), + KEY `workCenterFk_idx` (`workCenterFk`), + CONSTRAINT `calendarHolidaysNameFk` FOREIGN KEY (`calendarHolidaysNameFk`) REFERENCES `calendarHolidaysName` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `calendarholidaystypeFk` FOREIGN KEY (`calendarHolidaysTypeFk`) REFERENCES `calendarHolidaysType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `workCenterFk` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `calendarHolidaysName` +-- + +DROP TABLE IF EXISTS `calendarHolidaysName`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `calendarHolidaysName` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(100) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `calendarHolidaysType` +-- + +DROP TABLE IF EXISTS `calendarHolidaysType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `calendarHolidaysType` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(50) NOT NULL, + `hexColour` char(7) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `category` +-- + +DROP TABLE IF EXISTS `category`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `category` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `nick` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `chain` +-- + +DROP TABLE IF EXISTS `chain`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `chain` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Grupos de clientes'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `claim` +-- + +DROP TABLE IF EXISTS `claim`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `claim` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `ticketCreated` date NOT NULL, + `claimDepartmentFk` tinyint(3) unsigned DEFAULT NULL, + `claimStateFk` int(10) unsigned NOT NULL DEFAULT '1', + `observation` text COLLATE utf8_unicode_ci, + `clientFk` int(11) NOT NULL, + `workerFk` int(11) NOT NULL, + `responsibility` int(1) unsigned NOT NULL DEFAULT '3', + `isChargedToMana` tinyint(1) NOT NULL DEFAULT '0', + `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `ticketFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `cl_dep_id` (`claimDepartmentFk`), + KEY `cl_est_id` (`claimStateFk`), + KEY `Id_Cliente` (`clientFk`), + KEY `Id_Trabajador` (`workerFk`), + KEY `cl_main_ticketFk_idx` (`ticketFk`), + CONSTRAINT `cl_main_ticketFk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE, + CONSTRAINT `claim_ibfk_3` FOREIGN KEY (`claimStateFk`) REFERENCES `claimState` (`id`) ON UPDATE CASCADE, + CONSTRAINT `claim_ibfk_4` FOREIGN KEY (`claimDepartmentFk`) REFERENCES `vn2008`.`cl_dep` (`id`) ON UPDATE CASCADE, + CONSTRAINT `claim_ibfk_5` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=72699 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Reclamaciones, tabla principal'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `claimBeginning` +-- + +DROP TABLE IF EXISTS `claimBeginning`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `claimBeginning` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `claimFk` int(10) unsigned NOT NULL, + `saleFk` int(11) DEFAULT NULL, + `claimComplaintFk` int(10) unsigned NOT NULL DEFAULT '1', + `claimRequestFk` int(1) unsigned NOT NULL DEFAULT '1', + `quantity` double DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `Id_Movimiento` (`saleFk`), + KEY `cl_main_id` (`claimFk`), + CONSTRAINT `claimBeginning_ibfk_7` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `claimBeginning_ibfk_8` FOREIGN KEY (`claimFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=159141 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalle de las reclamaciones'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`claimBeginning_afterInsert` + AFTER INSERT ON `claimBeginning` + FOR EACH ROW +BEGIN + DECLARE vTicket INT; + + SELECT ticketFk INTO vTicket + FROM sale + WHERE id = NEW.saleFk; + + UPDATE claim + SET ticketFk = vTicket + WHERE id = NEW.claimFk; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `claimDestination` +-- + +DROP TABLE IF EXISTS `claimDestination`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `claimDestination` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `description` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `addressFk` int(10) DEFAULT NULL COMMENT 'Indica el consignatario para el ticket que regulariza el inventario', + PRIMARY KEY (`id`), + KEY `clSolAddressFk_idx` (`addressFk`), + CONSTRAINT `clSolAddressFk` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Solucion ofrecida a la reclamación'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `claimDevelopment` +-- + +DROP TABLE IF EXISTS `claimDevelopment`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `claimDevelopment` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `claimFk` int(10) unsigned NOT NULL, + `claimResponsibleFk` int(10) unsigned NOT NULL DEFAULT '1', + `workerFk` int(11) DEFAULT NULL, + `claimReasonFk` int(10) unsigned NOT NULL DEFAULT '1', + `claimResultFk` int(10) unsigned NOT NULL DEFAULT '1', + `claimRedeliveryFk` tinyint(3) unsigned NOT NULL DEFAULT '1', + `claimDestinationFk` tinyint(3) unsigned NOT NULL DEFAULT '2', + PRIMARY KEY (`id`), + KEY `cl_main_id` (`claimFk`), + KEY `cl_res_id` (`claimResponsibleFk`), + KEY `Id_Trabajador` (`workerFk`), + KEY `cl_mot_id` (`claimReasonFk`), + KEY `cl_con_id` (`claimResultFk`), + KEY `cl_dev` (`claimRedeliveryFk`), + KEY `cl_sol` (`claimDestinationFk`), + CONSTRAINT `claimDevelopment_ibfk_10` FOREIGN KEY (`claimFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `claimDevelopment_ibfk_11` FOREIGN KEY (`claimRedeliveryFk`) REFERENCES `claimRedelivery` (`id`) ON UPDATE CASCADE, + CONSTRAINT `claimDevelopment_ibfk_12` FOREIGN KEY (`claimDestinationFk`) REFERENCES `claimDestination` (`id`) ON UPDATE CASCADE, + CONSTRAINT `claimDevelopment_ibfk_6` FOREIGN KEY (`claimResponsibleFk`) REFERENCES `claimResponsible` (`id`) ON UPDATE CASCADE, + CONSTRAINT `claimDevelopment_ibfk_7` FOREIGN KEY (`claimReasonFk`) REFERENCES `claimReason` (`id`) ON UPDATE CASCADE, + CONSTRAINT `claimDevelopment_ibfk_8` FOREIGN KEY (`claimResultFk`) REFERENCES `claimResult` (`id`) ON UPDATE CASCADE, + CONSTRAINT `claimDevelopment_ibfk_9` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=61996 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Causas de las reclamaciones'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `claimDms` +-- + +DROP TABLE IF EXISTS `claimDms`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `claimDms` ( + `claimFk` int(10) unsigned NOT NULL, + `dmsFk` int(11) NOT NULL, + PRIMARY KEY (`claimFk`,`dmsFk`), + KEY `dmsFk_idx` (`dmsFk`), + CONSTRAINT `claimFk` FOREIGN KEY (`claimFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `dmsFk` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `claimEnd` +-- + +DROP TABLE IF EXISTS `claimEnd`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `claimEnd` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `saleFk` int(11) DEFAULT NULL, + `claimFk` int(10) unsigned NOT NULL, + `workerFk` int(11) NOT NULL DEFAULT '20', + `claimDestinationFk` tinyint(4) DEFAULT NULL, + `isGreuge` tinyint(4) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `cl_main_id` (`claimFk`), + KEY `Id_Trabajador` (`workerFk`), + KEY `Id_Movimiento` (`saleFk`), + KEY `cl_sol_id` (`claimDestinationFk`), + CONSTRAINT `claimEnd_ibfk_1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `claimEnd_ibfk_3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `claimEnd_ibfk_4` FOREIGN KEY (`claimFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=121333 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Acciones en respuesta a las reclamaciones'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `claimLog` +-- + +DROP TABLE IF EXISTS `claimLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `claimLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(10) unsigned NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `originFk` (`originFk`), + KEY `userFk` (`userFk`), + CONSTRAINT `claimOriginFk` FOREIGN KEY (`originFk`) REFERENCES `claim` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `claimUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=8585 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `claimRatio` +-- + +DROP TABLE IF EXISTS `claimRatio`; +/*!50001 DROP VIEW IF EXISTS `claimRatio`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `claimRatio` AS SELECT + 1 AS `clientFk`, + 1 AS `yearSale`, + 1 AS `claimAmount`, + 1 AS `claimingRate`, + 1 AS `priceIncreasing`, + 1 AS `packingRate`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `claimReason` +-- + +DROP TABLE IF EXISTS `claimReason`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `claimReason` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Motivos de las fallos'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `claimRedelivery` +-- + +DROP TABLE IF EXISTS `claimRedelivery`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `claimRedelivery` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Método por el cual el cliente nos devuelve la mercancía'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `claimResponsible` +-- + +DROP TABLE IF EXISTS `claimResponsible`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `claimResponsible` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `responsability` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'if=1 >sensib >culpa', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Responsables de las causas'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `claimResult` +-- + +DROP TABLE IF EXISTS `claimResult`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `claimResult` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Consecuencias de los motivos'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `claimState` +-- + +DROP TABLE IF EXISTS `claimState`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `claimState` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `description` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `roleFk` int(10) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + KEY `roleFgn_idx` (`roleFk`), + CONSTRAINT `roleFgn` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Estados posibles de las reclamaciones'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `client` +-- + +DROP TABLE IF EXISTS `client`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `client` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `discount` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)', + `defaultAddressFk` int(11) DEFAULT NULL, + `street` longtext COLLATE utf8_unicode_ci, + `fi` varchar(14) COLLATE utf8_unicode_ci DEFAULT NULL, + `phone` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `fax` varchar(11) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'obsoleta (comprobar)', + `email` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `cc` varchar(23) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'obsoleta (comprobar)', + `dueDay` smallint(6) NOT NULL DEFAULT '5', + `receipt` int(11) DEFAULT '1' COMMENT 'obsoleta', + `isOfficial` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'obsoleta (comprobar)', + `isTaxDataChecked` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Deprecated', + `mobile` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `accountingAccount` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `isEqualizated` tinyint(1) NOT NULL DEFAULT '0', + `city` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL, + `provinceFk` smallint(5) unsigned DEFAULT NULL, + `postcode` varchar(8) COLLATE utf8_unicode_ci DEFAULT NULL, + `socialName` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL, + `contact` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `wholesaler` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)', + `isReExpedition` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)', + `hasToInvoice` tinyint(1) NOT NULL DEFAULT '1', + `notes` text COLLATE utf8_unicode_ci COMMENT 'obsoleta (comprobar)', + `administrativeNotes` text COLLATE utf8_unicode_ci NOT NULL COMMENT 'obsoleta (comprobar)', + `invoiceCopy` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)', + `hold` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)', + `isFreezed` tinyint(1) NOT NULL DEFAULT '0', + `salesPersonFk` int(11) DEFAULT NULL, + `credit` decimal(10,2) NOT NULL DEFAULT '0.00', + `cyc` double DEFAULT NULL COMMENT 'obsoleta (comprobar)', + `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1', + `isActive` tinyint(1) NOT NULL DEFAULT '1', + `gestdocFk` int(11) DEFAULT NULL, + `quality` int(2) DEFAULT '11', + `payMethodFk` tinyint(3) unsigned NOT NULL DEFAULT '5', + `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `isToBeMailed` tinyint(1) NOT NULL DEFAULT '1', + `contactChannelFk` smallint(6) DEFAULT NULL, + `isVies` tinyint(4) NOT NULL DEFAULT '0', + `splitHolland` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'obsoleta (comprobar)', + `sepaFth` tinyint(1) DEFAULT '0' COMMENT 'campo para recibir los escritos de los clientes para el sepa\n\nobsoleta (comprobar)', + `hasSepaVnl` tinyint(1) DEFAULT '0', + `coreFth` tinyint(1) DEFAULT '0' COMMENT 'obsoleta (comprobar)', + `hasCoreVnl` tinyint(1) DEFAULT '0', + `riskCalculated` date NOT NULL, + `hasCoreVnh` tinyint(1) DEFAULT '0', + `isRelevant` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Define los clientes cuyas ventas hay que tener en cuenta en los calculos estadisticos.', + `clientTypeFk` int(11) NOT NULL DEFAULT '1', + `postcodeOld` int(11) unsigned DEFAULT NULL COMMENT 'obsoleta (comprobar)', + `mailAddress` int(11) DEFAULT NULL, + `codposOLD` char(5) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'obsoleta (comprobar)', + `creditInsurance` int(11) DEFAULT NULL, + `eypbc` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Email\\nYesterday\\nPurchases\\nBy\\nConsigna', + `hasToInvoiceByAddress` tinyint(1) DEFAULT '0', + `cplusTerIdNifFk` int(11) NOT NULL DEFAULT '1' COMMENT 'OBSOLETO', + `isCreatedAsServed` tinyint(1) DEFAULT '0', + `hasInvoiceSimplified` tinyint(1) NOT NULL DEFAULT '0', + `iban` varchar(45) CHARACTER SET utf8 DEFAULT NULL, + `hasLcr` tinyint(1) NOT NULL DEFAULT '0', + `bankEntityFk` int(10) DEFAULT NULL, + `typeFk` varchar(20) CHARACTER SET utf8 NOT NULL DEFAULT 'normal', + PRIMARY KEY (`id`), + UNIQUE KEY `IF` (`fi`), + KEY `Id_Trabajador` (`salesPersonFk`), + KEY `Id_Pais` (`countryFk`), + KEY `pay_met_id` (`payMethodFk`), + KEY `canal_nuevo_cliente` (`contactChannelFk`), + KEY `Cuenta` (`accountingAccount`), + KEY `province_id` (`provinceFk`), + KEY `default_address` (`defaultAddressFk`), + KEY `Telefono` (`phone`), + KEY `movil` (`mobile`), + KEY `tipos_de_cliente_idx` (`clientTypeFk`), + KEY `codpos` (`codposOLD`,`postcode`), + KEY `fk_Clientes_entity_idx` (`bankEntityFk`), + KEY `typeFk` (`typeFk`), + CONSTRAINT `canal_nuevo_cliente` FOREIGN KEY (`contactChannelFk`) REFERENCES `contactChannel` (`id`) ON UPDATE CASCADE, + CONSTRAINT `client_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE, + CONSTRAINT `client_ibfk_2` FOREIGN KEY (`payMethodFk`) REFERENCES `payMethod` (`id`) ON UPDATE CASCADE, + CONSTRAINT `client_ibfk_3` FOREIGN KEY (`salesPersonFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `client_ibfk_4` FOREIGN KEY (`defaultAddressFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `client_ibfk_5` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE, + CONSTRAINT `tipos_de_cliente` FOREIGN KEY (`clientTypeFk`) REFERENCES `clientType` (`id`) ON UPDATE CASCADE, + CONSTRAINT `typeFk` FOREIGN KEY (`typeFk`) REFERENCES `clientType` (`code`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=17017 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`client_beforeInsert` + BEFORE INSERT ON `client` + FOR EACH ROW +BEGIN + + CALL pbx.phone_isValid(NEW.phone); + CALL pbx.phone_isValid(NEW.mobile); + CALL pbx.phone_isValid(NEW.fax); + + SET NEW.accountingAccount = 4300000000 + NEW.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_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`client_beforeUpdate` + BEFORE UPDATE ON `client` + FOR EACH ROW +BEGIN + -- BERNAT: WORKING IN THIS FILE + DECLARE vText VARCHAR(255) DEFAULT NULL; + + -- Comprueba que el formato de los teléfonos es válido + + IF !(NEW.phone <=> OLD.phone) THEN + CALL pbx.phone_isValid(NEW.phone); + END IF; + + IF !(NEW.mobile <=> OLD.mobile) THEN + CALL pbx.phone_isValid(NEW.mobile); + END IF; + + IF !(NEW.fax <=> OLD.fax) THEN + CALL pbx.phone_isValid(NEW.fax); + END IF; + + IF NEW.payMethodFk = 4 AND NEW.dueDay = 0 THEN + SET NEW.dueDay = 5; + END IF; + + -- Avisar al comercial si ha llegado la documentación sepa/core + + IF NEW.hasSepaVnl AND !OLD.hasSepaVnl THEN + SET vText = 'Sepa de VNL'; + END IF; + + IF NEW.hasCoreVnl AND !OLD.hasCoreVnl THEN + SET vText = 'Core de VNL'; + END IF; + + IF vText IS NOT NULL + THEN + INSERT INTO vn2008.mail(`to`, reply_to, subject, text) + SELECT + CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'), + 'administracion@verdnatura.es', + CONCAT('Cliente ', NEW.id), + CONCAT('Recibida la documentación: ', vText) + FROM worker w + LEFT JOIN account.user u ON w.userFk = u.id AND u.active + LEFT JOIN account.account ac ON ac.id = u.id + WHERE w.id = NEW.salesPersonFk; + END IF; +END */;; +DELIMITER ; +/*!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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`client_afterUpdate` +AFTER UPDATE ON `client` +FOR EACH ROW +BEGIN + IF !(NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN + UPDATE `address` SET isDefaultAddress = 0 + WHERE clientFk = NEW.id; + + UPDATE `address` SET isDefaultAddress = 1 + WHERE id = NEW.defaultAddressFk; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `clientChain` +-- + +DROP TABLE IF EXISTS `clientChain`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `clientChain` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `clientFk` int(11) NOT NULL, + `chainFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `clientChain_fk1_idx` (`clientFk`), + KEY `clientChain_fk2_idx` (`chainFk`), + CONSTRAINT `clientChain_fk1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `clientChain_fk2` FOREIGN KEY (`chainFk`) REFERENCES `chain` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `clientContact` +-- + +DROP TABLE IF EXISTS `clientContact`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `clientContact` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `clientFk` int(11) NOT NULL, + `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `phone` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=4162 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `clientCredit` +-- + +DROP TABLE IF EXISTS `clientCredit`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `clientCredit` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `clientFk` int(11) NOT NULL, + `amount` double unsigned NOT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `workerFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `workers_fk_idx` (`workerFk`), + KEY `credit_ClienteFk` (`clientFk`), + CONSTRAINT `credit_ClienteFk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `workers_fk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=86085 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `clientCreditLimit` +-- + +DROP TABLE IF EXISTS `clientCreditLimit`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `clientCreditLimit` ( + `id` int(11) NOT NULL, + `maxAmount` int(10) unsigned NOT NULL, + `roleFk` int(10) unsigned NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `clientDms` +-- + +DROP TABLE IF EXISTS `clientDms`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `clientDms` ( + `clientFk` int(11) NOT NULL, + `dmsFk` int(11) NOT NULL, + PRIMARY KEY (`dmsFk`), + KEY `gest_doc_id` (`dmsFk`), + KEY `fk_clientes_gestdoc_1_idx` (`clientFk`), + CONSTRAINT `clientDms_ibfk_2` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `fk_clientes_gestdoc_3` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `clientLog` +-- + +DROP TABLE IF EXISTS `clientLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `clientLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(11) NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `originFk` (`originFk`), + KEY `userFk` (`userFk`), + CONSTRAINT `clientLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `clientLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=243781 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `clientManaCache` +-- + +DROP TABLE IF EXISTS `clientManaCache`; +/*!50001 DROP VIEW IF EXISTS `clientManaCache`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `clientManaCache` AS SELECT + 1 AS `clientFk`, + 1 AS `mana`, + 1 AS `dated`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `clientObservation` +-- + +DROP TABLE IF EXISTS `clientObservation`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `clientObservation` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `clientFk` int(11) NOT NULL, + `workerFk` int(11) NOT NULL, + `text` text COLLATE utf8_unicode_ci NOT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `Id_Trabajador` (`workerFk`), + KEY `Id_Cliente` (`clientFk`), + CONSTRAINT `clientObservation_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `clientObservation_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=79281 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Todas las observaciones referentes a un ticket'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`clientObservation_AFTER_INSERT` AFTER INSERT ON `clientObservation` FOR EACH ROW +BEGIN +/* DECLARE vMailSender VARCHAR(90); + DECLARE vUserName VARCHAR(30); + DECLARE vUserId INT ; + + SELECT u.name, u.id INTO vUserName, vUserId + FROM account.user u + JOIN vn.worker w ON w.userFk = u.id + WHERE w.id = NEW.workerFk; + + SELECT CONCAT(salesPerson.name, '@verdnatura.es, ',vUserName, '@verdnatura.es') INTO vMailSender + FROM vn.client c + JOIN vn.worker w ON w.id = c.salesPersonFk + JOIN account.user salesPerson ON salesPerson.id = w.userFk + WHERE c.id = NEW.clientFk + AND salesPerson.id <> vUserId; + + IF vMailSender >'' THEN + INSERT INTO vn.mail SET + `sender` = vMailSender, + `replyTo` = CONCAT(vUserName, '@verdnatura.es'), + `subject` = CONCAT ('Nota añadida al cliente ', NEW.clientFk) , + `body` = CONCAT(vUserName, ' ha añadido la siguiente nota: ', NEW.`text`); + END IF; +*/ +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `clientProtected` +-- + +DROP TABLE IF EXISTS `clientProtected`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `clientProtected` ( + `clientFk` int(11) NOT NULL, + `workerFk` int(11) NOT NULL, + `isValidated` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`clientFk`), + KEY `clientProtected_fk2_idx` (`workerFk`), + CONSTRAINT `clientProtected_fk1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `clientProtected_fk2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de clientes y comerciales que no se van a ver afectados por las desagsignaciones mensuales automaticas'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `clientRisk` +-- + +DROP TABLE IF EXISTS `clientRisk`; +/*!50001 DROP VIEW IF EXISTS `clientRisk`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `clientRisk` AS SELECT + 1 AS `clientFk`, + 1 AS `companyFk`, + 1 AS `amount`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `clientSample` +-- + +DROP TABLE IF EXISTS `clientSample`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `clientSample` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `clientFk` int(10) unsigned NOT NULL, + `typeFk` int(10) unsigned NOT NULL, + `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `workerFk` int(10) unsigned NOT NULL, + `balance` float NOT NULL, + `companyFk` smallint(5) unsigned DEFAULT NULL, + `userFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `empresa_id` (`companyFk`), + CONSTRAINT `clientSample_ibfk_1` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=18669 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `clientType` +-- + +DROP TABLE IF EXISTS `clientType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `clientType` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `code` varchar(20) CHARACTER SET utf8 NOT NULL, + `type` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `isCreatedAsServed` tinyint(1) DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `code_UNIQUE` (`code`) +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Establece categorias para poder agrupar las ventas'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cmr` +-- + +DROP TABLE IF EXISTS `cmr`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cmr` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `ticketFk` int(11) NOT NULL, + `truckPlate` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, + `observations` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `senderInstruccions` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'Flowers 4º C. Plants 14º C', + `paymentInstruccions` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'Carriage paid', + `specialAgreements` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `cmr_fk1_idx` (`ticketFk`), + CONSTRAINT `cmr_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=75 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`cmr_BEFORE_INSERT` BEFORE INSERT ON `cmr` FOR EACH ROW +BEGIN + + DECLARE vLastSenderInstructions VARCHAR(255); + DECLARE vLastId INT; + DECLARE vCurrentAgency INT; + + SELECT am.agencyFk INTO vCurrentAgency + FROM vn.agencyMode am + JOIN vn.ticket t ON t.agencyModeFk = am.id + WHERE t.id = NEW.ticketFk; + + SELECT MAX(cmr.id) INTO vLastId + FROM cmr + JOIN vn.ticket t ON t.id = cmr.ticketFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + WHERE am.agencyFk = vCurrentAgency + ; + + SELECT senderInstruccions INTO vLastSenderInstructions + FROM cmr + WHERE id = vLastId; + + SET NEW.senderInstruccions = vLastSenderInstructions; + +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 */ ; + +-- +-- Temporary view structure for view `cmr_list` +-- + +DROP TABLE IF EXISTS `cmr_list`; +/*!50001 DROP VIEW IF EXISTS `cmr_list`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `cmr_list` AS SELECT + 1 AS `cmrFk`, + 1 AS `ticketFk`, + 1 AS `truckPlate`, + 1 AS `observations`, + 1 AS `senderInstruccions`, + 1 AS `paymentInstruccions`, + 1 AS `specialAgreements`, + 1 AS `created`, + 1 AS `addressFk`, + 1 AS `shipped`, + 1 AS `clientName`, + 1 AS `clientPostalCode`, + 1 AS `clientStreet`, + 1 AS `clientCity`, + 1 AS `clientProvince`, + 1 AS `clientCountry`, + 1 AS `companyName`, + 1 AS `companyStreet`, + 1 AS `companyPostCode`, + 1 AS `companyCity`, + 1 AS `companyCountry`, + 1 AS `warehouseAddress`, + 1 AS `clientOficialName`, + 1 AS `carrierName`, + 1 AS `carrierStreet`, + 1 AS `carrierPostCode`, + 1 AS `carrierCity`, + 1 AS `carrierCountry`, + 1 AS `phone`, + 1 AS `mobile`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `collection` +-- + +DROP TABLE IF EXISTS `collection`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `collection` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `workerFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `ticketCollection_idx` (`workerFk`), + CONSTRAINT `ticketCollection` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=133 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `collectionReportSource` +-- + +DROP TABLE IF EXISTS `collectionReportSource`; +/*!50001 DROP VIEW IF EXISTS `collectionReportSource`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `collectionReportSource` AS SELECT + 1 AS `collectionFk`, + 1 AS `ticketFk`, + 1 AS `itemFk`, + 1 AS `concept`, + 1 AS `size`, + 1 AS `quantity`, + 1 AS `nicho`, + 1 AS `level`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `company` +-- + +DROP TABLE IF EXISTS `company`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `company` ( + `id` smallint(5) unsigned NOT NULL, + `code` char(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `register` varchar(120) COLLATE utf8_unicode_ci NOT NULL, + `workerManagerFk` int(11) NOT NULL, + `registered` date NOT NULL, + `expired` date DEFAULT NULL, + `logo` longblob, + `isOfficial` tinyint(1) unsigned NOT NULL DEFAULT '1', + `hasCyc` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0', + `rgb` varchar(6) COLLATE utf8_unicode_ci NOT NULL, + `email` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `stamp` blob, + `created` timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP, + `clientFk` int(11) DEFAULT NULL, + `sage200Company` int(2) DEFAULT NULL, + `supplierAccountFk` mediumint(8) unsigned DEFAULT NULL, + `isDefaulter` tinyint(4) NOT NULL DEFAULT '0', + `companyGroupFk` int(11) NOT NULL DEFAULT '1' COMMENT 'usado para calcular los greuges ', + `companyCode` int(2) DEFAULT NULL COMMENT 'Campo para movConta', + `footnotes` longtext COLLATE utf8_unicode_ci COMMENT 'pie de paginas en las facturas', + `phytosanitary` longtext COLLATE utf8_unicode_ci, + PRIMARY KEY (`id`), + KEY `gerente_id` (`workerManagerFk`), + KEY `empresa_cliente_idx` (`clientFk`), + KEY `Id_Proveedores_account` (`supplierAccountFk`), + KEY `empresa_grupo_fk_idx` (`companyGroupFk`), + CONSTRAINT `company_ibfk_1` FOREIGN KEY (`workerManagerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `empresa_cliente` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `empresa_fk4` FOREIGN KEY (`supplierAccountFk`) REFERENCES `supplierAccount` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `fk_empresa_grupo` FOREIGN KEY (`companyGroupFk`) REFERENCES `companyGroup` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `companyGroup` +-- + +DROP TABLE IF EXISTS `companyGroup`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `companyGroup` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `code` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `component` +-- + +DROP TABLE IF EXISTS `component`; +/*!50001 DROP VIEW IF EXISTS `component`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `component` AS SELECT + 1 AS `id`, + 1 AS `name`, + 1 AS `typeFk`, + 1 AS `classRate`, + 1 AS `tax`, + 1 AS `isRenewable`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `componentRate` +-- + +DROP TABLE IF EXISTS `componentRate`; +/*!50001 DROP VIEW IF EXISTS `componentRate`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `componentRate` AS SELECT + 1 AS `id`, + 1 AS `name`, + 1 AS `componentTypeRate`, + 1 AS `classRate`, + 1 AS `tax`, + 1 AS `isRenewable`, + 1 AS `code`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `componentType` +-- + +DROP TABLE IF EXISTS `componentType`; +/*!50001 DROP VIEW IF EXISTS `componentType`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `componentType` AS SELECT + 1 AS `id`, + 1 AS `type`, + 1 AS `base`, + 1 AS `isMargin`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `componentTypeRate` +-- + +DROP TABLE IF EXISTS `componentTypeRate`; +/*!50001 DROP VIEW IF EXISTS `componentTypeRate`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `componentTypeRate` AS SELECT + 1 AS `id`, + 1 AS `type`, + 1 AS `base`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `confectionType` +-- + +DROP TABLE IF EXISTS `confectionType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `confectionType` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!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 */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `config` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `ochoa` int(10) unsigned NOT NULL, + `invoiceOutFk` int(11) DEFAULT '0', + `bookFk` int(11) DEFAULT '0', + `serialAFk` int(11) DEFAULT '0', + `serialEFk` int(11) DEFAULT '0', + `serialRFk` int(11) DEFAULT '0', + `serialCFk` int(11) DEFAULT '0', + `serialHFk` int(11) NOT NULL, + `serialPFk` int(11) DEFAULT '0', + `serialTFk` int(11) DEFAULT '0', + `inventoried` datetime DEFAULT NULL, + `serialMFk` int(11) DEFAULT '0', + `itemLog` int(11) DEFAULT '0', + `weekGoal` int(11) DEFAULT NULL, + `photosPath` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `cashBoxNumber` int(11) DEFAULT '0', + `redCode` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `TabletTime` datetime DEFAULT NULL, + `t0` int(11) NOT NULL DEFAULT '0', + `t1` int(11) NOT NULL DEFAULT '0', + `t2` int(11) NOT NULL DEFAULT '0', + `t3` int(11) NOT NULL DEFAULT '0', + `cc` double NOT NULL DEFAULT '0', + `palet` double NOT NULL DEFAULT '0', + `campaign` datetime NOT NULL, + `campaignLife` tinyint(3) unsigned NOT NULL, + `truckDays` tinyint(3) unsigned NOT NULL, + `transportCharges` double NOT NULL, + `escanerPath` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `printedTurn` int(4) DEFAULT NULL, + `truckLength` int(11) DEFAULT '24', + `fuelConsumption` int(11) DEFAULT NULL, + `petrol` decimal(10,1) DEFAULT NULL, + `maintenance` decimal(10,1) DEFAULT NULL, + `hourPrice` decimal(10,1) DEFAULT NULL, + `meterPrice` decimal(10,1) DEFAULT NULL, + `kmPrice` decimal(10,1) DEFAULT NULL, + `routeOption` int(11) DEFAULT '1', + `dbproduccion` tinyint(1) NOT NULL DEFAULT '1', + `mdbServer` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `fakeEmail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `defaultersMaxAmount` int(10) DEFAULT '200' COMMENT 'maxima deuda permitida a partir de la cual se bloquea a un usuario', + `ASIEN` bigint(20) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `fechainv_idx` (`inventoried`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!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 */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `config__` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `mdbServer` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `fakeEmail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `defaultersMaxAmount` int(10) DEFAULT '200' COMMENT 'maxima deuda permitida a partir de la cual se bloquea a un usuario', + `ASIEN` bigint(20) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `contactChannel` +-- + +DROP TABLE IF EXISTS `contactChannel`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `contactChannel` ( + `id` smallint(6) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Canal por el que nos ha conocido un cliente y se ha dado de'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `country` +-- + +DROP TABLE IF EXISTS `country`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `country` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `country` varchar(25) COLLATE utf8_unicode_ci NOT NULL, + `CEE` tinyint(1) NOT NULL DEFAULT '1', + `code` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, + `currencyFk` tinyint(3) unsigned NOT NULL DEFAULT '1', + `politicalCountryFk` mediumint(8) unsigned NOT NULL COMMENT 'Pais Real(apaño por culpa del España Exento)', + `nstGeoFk` int(11) DEFAULT NULL, + `nstName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `geoFk` int(11) DEFAULT NULL, + `hasDailyInvoice` tinyint(4) NOT NULL DEFAULT '0', + `isUeeMember` tinyint(4) NOT NULL DEFAULT '0', + `ibanLength` tinyint(4) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `Id_Paisreal` (`politicalCountryFk`) +) ENGINE=InnoDB AUTO_INCREMENT=72 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`country_beforeInsert` + BEFORE INSERT ON `country` FOR EACH ROW +BEGIN + SET NEW.geoFk = zoneGeo_new('country', NEW.country, NULL); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`country_beforeUpdate` + BEFORE UPDATE ON `country` FOR EACH ROW +BEGIN + IF !(OLD.geoFk <=> NEW.geoFk) THEN + CALL zoneGeo_throwNotEditable; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`country_afterUpdate` AFTER UPDATE ON `country` FOR EACH ROW +BEGIN + IF !(OLD.country <=> NEW.country) THEN + UPDATE zoneGeo SET `name` = NEW.country + WHERE id = NEW.geoFk; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`country_afterDelete` AFTER DELETE ON `country` FOR EACH ROW +BEGIN + CALL zoneGeo_delete(OLD.geoFk); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `cplusCorrectingType` +-- + +DROP TABLE IF EXISTS `cplusCorrectingType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cplusCorrectingType` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cplusInvoiceType472` +-- + +DROP TABLE IF EXISTS `cplusInvoiceType472`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cplusInvoiceType472` ( + `id` int(10) unsigned NOT NULL, + `description` varchar(255) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*18) TIPO FACTURA (Asientos)SOPORTADO – DEDUCIBLE (472)'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cplusInvoiceType477` +-- + +DROP TABLE IF EXISTS `cplusInvoiceType477`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cplusInvoiceType477` ( + `id` int(10) unsigned NOT NULL, + `description` varchar(255) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*18) TIPO FACTURA (Asientos)REPERCUTIDO - DEVENGADO (477)'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cplusRectificationType` +-- + +DROP TABLE IF EXISTS `cplusRectificationType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cplusRectificationType` ( + `id` int(10) unsigned NOT NULL, + `description` varchar(255) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*20) TIPO RECTIFICATIVA (Asientos)'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cplusSubjectOp` +-- + +DROP TABLE IF EXISTS `cplusSubjectOp`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cplusSubjectOp` ( + `id` int(10) unsigned NOT NULL, + `description` varchar(255) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*17) TIPO OPERACIÓN SUJETA/NO SUJETA (Asientos)'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cplusTaxBreak` +-- + +DROP TABLE IF EXISTS `cplusTaxBreak`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cplusTaxBreak` ( + `id` int(10) unsigned NOT NULL, + `description` varchar(255) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*16) TIPO EXENCIÓN (Asientos)'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cplusTerIdNif` +-- + +DROP TABLE IF EXISTS `cplusTerIdNif`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cplusTerIdNif` ( + `id` int(11) NOT NULL, + `description` varchar(255) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cplusTrascendency472` +-- + +DROP TABLE IF EXISTS `cplusTrascendency472`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cplusTrascendency472` ( + `id` int(10) unsigned NOT NULL, + `description` varchar(255) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*15) CLAVE DE RÉGIMEN ESPECIAL O TRASCENDENCIA(Asientos)SOPORTADO – DEDUCIBLE (472)'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cplusTrascendency477` +-- + +DROP TABLE IF EXISTS `cplusTrascendency477`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `cplusTrascendency477` ( + `id` int(10) unsigned NOT NULL, + `description` varchar(255) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*15) CLAVE DE RÉGIMEN ESPECIAL O TRASCENDENCIA(Asientos) REPERCUTIDO - DEVENGADO (477)'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `creditClassification` +-- + +DROP TABLE IF EXISTS `creditClassification`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `creditClassification` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `client` int(11) NOT NULL, + `dateStart` date NOT NULL, + `dateEnd` date DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `creditClassifClientFk_idx` (`client`), + KEY `creditClassifdateEnd_idx` (`dateEnd`), + CONSTRAINT `creditClassifClientFk` FOREIGN KEY (`client`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=3277 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditClassification_BEFORE_UPDATE` BEFORE UPDATE ON `creditClassification` FOR EACH ROW +BEGIN + -- BERNAT: WORKING IN THIS FILE + IF NEW.client <> OLD.client THEN + CALL util.throw('NOT_ALLOWED_CHANGE_CLIENT'); + END IF; + IF NEW.dateEnd IS NOT NULL AND OLD.dateEnd IS NULL THEN + UPDATE vn2008.Clientes c + SET creditInsurance = 0 WHERE c.Id_cliente = NEW.client; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `creditInsurance` +-- + +DROP TABLE IF EXISTS `creditInsurance`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `creditInsurance` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `creditClassification` int(11) DEFAULT NULL, + `credit` int(11) DEFAULT NULL, + `creationDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `grade` tinyint(1) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `CreditInsurance_Fk1_idx` (`creditClassification`), + CONSTRAINT `CreditInsurance_Fk1` FOREIGN KEY (`creditClassification`) REFERENCES `creditClassification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=3200 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalla los clientes que tienen seguro de credito'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditInsurance_AFTER_INSERT` AFTER INSERT ON `creditInsurance` FOR EACH ROW +BEGIN + -- BERNAT: WORKING IN THIS FILE + UPDATE vn2008.Clientes c + JOIN vn.creditClassification cc ON cc.client = c.Id_Cliente + SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `currency` +-- + +DROP TABLE IF EXISTS `currency`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `currency` ( + `id` tinyint(3) unsigned NOT NULL, + `code` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `ratio` double NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `Moneda_UNIQUE` (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `dayMinute` +-- + +DROP TABLE IF EXISTS `dayMinute`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `dayMinute` ( + `id` int(10) unsigned NOT NULL, + `hh` int(10) unsigned NOT NULL, + `mm` int(10) unsigned NOT NULL, + PRIMARY KEY (`id`), + KEY `dayMinute_ix1` (`hh`), + KEY `dayMinute_ix2` (`mm`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='sirve de soporte para el calculo presencial de los trabjadores'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `defaulter` +-- + +DROP TABLE IF EXISTS `defaulter`; +/*!50001 DROP VIEW IF EXISTS `defaulter`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `defaulter` AS SELECT + 1 AS `clientFk`, + 1 AS `created`, + 1 AS `amount`, + 1 AS `defaulterSinced`, + 1 AS `hasChanged`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `deliveryMethod` +-- + +DROP TABLE IF EXISTS `deliveryMethod`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `deliveryMethod` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `code` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `code` (`code`) +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `deliveryPoint` +-- + +DROP TABLE IF EXISTS `deliveryPoint`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `deliveryPoint` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `ubication` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `delivery_zip` +-- + +DROP TABLE IF EXISTS `delivery_zip`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `delivery_zip` ( + `postal_code` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `country_code` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `place_name` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `admin_name1` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `code_name1` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `admin_name2` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `code_name2` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `admin_name3` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `code_name3` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `latitude` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `longitude` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `accuracy` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + KEY `country_code_idx` (`country_code`), + KEY `place_name_idx` (`place_name`), + KEY `postal_code_idx` (`postal_code`), + KEY `admin_name3_idx` (`admin_name3`), + KEY `admin_name2_idx` (`admin_name2`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `department` +-- + +DROP TABLE IF EXISTS `department`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `department` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `lft` int(11) DEFAULT NULL, + `rgt` int(11) DEFAULT NULL, + `workerFk` int(11) DEFAULT NULL COMMENT 'Id_Trabajador es el jefe del departamento', + `companyFk` int(11) NOT NULL, + `bossFk` int(11) DEFAULT NULL, + `x` int(11) DEFAULT NULL, + `y` int(11) DEFAULT NULL, + `isProduction` tinyint(4) NOT NULL DEFAULT '0', + `isSelected` tinyint(1) NOT NULL DEFAULT '0', + `depth` int(11) NOT NULL DEFAULT '0', + `sons` decimal(10,0) NOT NULL DEFAULT '0', + `parentFk` int(10) unsigned DEFAULT NULL, + `path` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`), + KEY `fk_department_Trabajadores1_idx` (`workerFk`), + KEY `dep_org_ibfk_3_idx` (`companyFk`), + KEY `lft_rgt_depth_idx` (`lft`,`rgt`,`depth`), + CONSTRAINT `fk_department_Trabajadores1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=95 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`department_beforeInsert` + BEFORE INSERT ON `department` FOR EACH ROW +BEGIN + UPDATE vn.department_recalc SET isChanged = TRUE; +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`department_afterUpdate` + AFTER UPDATE ON `department` FOR EACH ROW +BEGIN + IF !(OLD.parentFk <=> NEW.parentFk) THEN + UPDATE vn.department_recalc SET isChanged = TRUE; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`department_afterDelete` + AFTER DELETE ON `department` FOR EACH ROW +BEGIN + UPDATE vn.department_recalc SET isChanged = TRUE; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `departmentItemType` +-- + +DROP TABLE IF EXISTS `departmentItemType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `departmentItemType` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `departmentFk` int(11) NOT NULL, + `itemTypeFk` smallint(5) unsigned NOT NULL, + `workerFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `departmentItemTypeIdx1_idx` (`departmentFk`,`itemTypeFk`), + KEY `departmentItemTypeIdx2_idx` (`itemTypeFk`), + KEY `departmentItemTypeIdx3_idx` (`workerFk`), + CONSTRAINT `departmentItemTypeIdx1` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON UPDATE CASCADE, + CONSTRAINT `departmentItemTypeIdx2` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`) ON UPDATE CASCADE, + CONSTRAINT `departmentItemTypeIdx3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `departmentTree` +-- + +DROP TABLE IF EXISTS `departmentTree`; +/*!50001 DROP VIEW IF EXISTS `departmentTree`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `departmentTree` AS SELECT + 1 AS `id`, + 1 AS `dep`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `department_recalc` +-- + +DROP TABLE IF EXISTS `department_recalc`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `department_recalc` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `isChanged` tinyint(4) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `device` +-- + +DROP TABLE IF EXISTS `device`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `device` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `sn` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `model` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `userFk` int(10) unsigned NOT NULL, + PRIMARY KEY (`id`), + KEY `device_fk1_idx` (`userFk`), + CONSTRAINT `device_fk1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=375 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `deviceProduction` +-- + +DROP TABLE IF EXISTS `deviceProduction`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `deviceProduction` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `imei` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `modelFk` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `macWifi` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `serialNumber` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `departmentFk` int(11) DEFAULT NULL, + `isOutOfService` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `device_id_UNIQUE` (`id`), + UNIQUE KEY `sn_UNIQUE` (`imei`), + KEY `deviceProductionModelsFgn` (`modelFk`), + KEY `departmentFgn` (`departmentFk`), + CONSTRAINT `departmentFgn` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `deviceProductionModelsFgn` FOREIGN KEY (`modelFk`) REFERENCES `deviceProductionModels` (`code`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=381 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `deviceProductionModels` +-- + +DROP TABLE IF EXISTS `deviceProductionModels`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `deviceProductionModels` ( + `code` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `deviceProductionUser` +-- + +DROP TABLE IF EXISTS `deviceProductionUser`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `deviceProductionUser` ( + `deviceProductionFk` int(11) NOT NULL, + `userFk` int(10) unsigned NOT NULL, + PRIMARY KEY (`deviceProductionFk`,`userFk`), + KEY `userFgn_idx` (`userFk`), + CONSTRAINT `deviceProductionFgn` FOREIGN KEY (`deviceProductionFk`) REFERENCES `deviceProduction` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `userFgn` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `dms` +-- + +DROP TABLE IF EXISTS `dms`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `dms` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dmsTypeFk` int(11) NOT NULL DEFAULT '1', + `reference` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `description` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL, + `companyFk` smallint(5) unsigned NOT NULL DEFAULT '791', + `hardCopyNumber` mediumint(8) unsigned DEFAULT NULL, + `contentType` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `file` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, + `hasFile` tinyint(4) NOT NULL DEFAULT '0', + `workerFk` int(11) NOT NULL, + `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `warehouseFk` smallint(5) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `emp_id` (`companyFk`,`hardCopyNumber`,`warehouseFk`), + KEY `trabajador_id` (`workerFk`), + KEY `warehouse_id` (`warehouseFk`) +) ENGINE=InnoDB AUTO_INCREMENT=1409575 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='document managment system'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`dms_beforeInsert` BEFORE INSERT ON `vn`.`dms` FOR EACH ROW +BEGIN + DECLARE vHardCopyNumber INT; + DECLARE vDmsTypeCode INT; + + IF NEW.warehouseFk = 44 THEN + SET NEW.warehouseFk = 1; + END IF; + + IF NEW.hasFile THEN + SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber + FROM dms + WHERE companyFk = NEW.companyFk + AND warehouseFk = NEW.warehouseFk ; + + SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1) ; + END IF; + + SELECT code INTO vDmsTypeCode + FROM dmsType WHERE NEW.dmsTypeFk = id; + IF (vDmsTypeCode ='ticket') THEN + UPDATE ticket SET isSigned = 1 WHERE id = NEW.reference; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate` BEFORE UPDATE ON `vn`.`dms` FOR EACH ROW +BEGIN + DECLARE vHardCopyNumber INT; + IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) THEN + + SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber + FROM dms + WHERE companyFk = NEW.companyFk + AND warehouseFk = NEW.warehouseFk; + + SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); + END IF; + IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN + + SET NEW.hasFile = 0; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `dmsType` +-- + +DROP TABLE IF EXISTS `dmsType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `dmsType` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `path` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `writeRoleFk` int(10) unsigned DEFAULT NULL, + `readRoleFk` int(10) unsigned DEFAULT NULL, + `code` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `readRoleFk` (`readRoleFk`), + KEY `writeRoleFk` (`writeRoleFk`), + CONSTRAINT `readRoleFk` FOREIGN KEY (`readRoleFk`) REFERENCES `account`.`role` (`id`), + CONSTRAINT `writeRoleFk` FOREIGN KEY (`writeRoleFk`) REFERENCES `account`.`role` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `dua` +-- + +DROP TABLE IF EXISTS `dua`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `dua` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `code` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `awbFk` smallint(11) unsigned NOT NULL, + `issued` date DEFAULT NULL, + `operated` date DEFAULT NULL, + `booked` date DEFAULT NULL, + `bookEntried` date DEFAULT NULL, + `gestdocFk` int(11) DEFAULT NULL, + `customsValue` decimal(10,2) DEFAULT NULL, + `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442', + `ASIEN` double DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `fk_awb_dua_awb_idx` (`awbFk`), + KEY `fk_dua_gestdoc1_idx` (`gestdocFk`), + KEY `dua_fk4_idx` (`companyFk`), + CONSTRAINT `dua_fk1` FOREIGN KEY (`gestdocFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `dua_fk2` FOREIGN KEY (`awbFk`) REFERENCES `vn2008`.`awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `dua_fk4` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=19542 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `duaEntry` +-- + +DROP TABLE IF EXISTS `duaEntry`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `duaEntry` ( + `duaFk` int(11) NOT NULL, + `entryFk` int(11) NOT NULL, + `value` decimal(10,2) DEFAULT NULL, + `customsValue` decimal(10,2) DEFAULT NULL, + `euroValue` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`duaFk`,`entryFk`), + KEY `fk_duaEntry_dua1_idx` (`duaFk`), + KEY `fk_duaEntry_Entradas1_idx` (`entryFk`), + CONSTRAINT `fk_duaEntry_Entradas1` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_duaEntry_dua1` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `duaIntrastat` +-- + +DROP TABLE IF EXISTS `duaIntrastat`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `duaIntrastat` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `duaFk` int(11) NOT NULL, + `intrastatFk` int(8) unsigned NOT NULL, + `amount` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`id`), + KEY `duaIntrastat_fk1_idx` (`intrastatFk`), + KEY `duaIntrastat_fk2_idx` (`duaFk`), + CONSTRAINT `duaIntrastat_fk1` FOREIGN KEY (`intrastatFk`) REFERENCES `intrastat` (`id`) ON UPDATE CASCADE, + CONSTRAINT `duaIntrastat_fk2` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=7324 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `duaInvoiceIn` +-- + +DROP TABLE IF EXISTS `duaInvoiceIn`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `duaInvoiceIn` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `duaFk` int(11) NOT NULL, + `invoiceInFk` mediumint(8) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `duaFk_UNIQUE` (`duaFk`,`invoiceInFk`), + KEY `duaInvoiceIn_fk1_idx` (`duaFk`), + KEY `duaInvoiceIn_fk2_idx` (`invoiceInFk`), + CONSTRAINT `duaInvoiceIn_fk1` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `duaInvoiceIn_fk2` FOREIGN KEY (`invoiceInFk`) REFERENCES `vn2008`.`recibida` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=5333 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Facturas asociadas a la declaración aduanera, básicamente la del agente transitario'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `duaTax` +-- + +DROP TABLE IF EXISTS `duaTax`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `duaTax` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `duaFk` int(11) NOT NULL, + `supplierFk` int(11) NOT NULL, + `taxClassFk` tinyint(3) unsigned NOT NULL, + `base` decimal(10,2) NOT NULL, + `rate` decimal(5,2) NOT NULL, + `tax` decimal(10,2) NOT NULL, + PRIMARY KEY (`id`), + KEY `fk_dua_tax_awb_dua1_idx` (`duaFk`), + KEY `duaTax_fk2_idx` (`supplierFk`), + KEY `duaTax_fk3_idx` (`taxClassFk`), + CONSTRAINT `duaTax_fk1` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `duaTax_fk2` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE, + CONSTRAINT `duaTax_fk3` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=10732 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `ediGenus` +-- + +DROP TABLE IF EXISTS `ediGenus`; +/*!50001 DROP VIEW IF EXISTS `ediGenus`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `ediGenus` AS SELECT + 1 AS `id`, + 1 AS `latinGenusName`, + 1 AS `entried`, + 1 AS `dued`, + 1 AS `modified`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `ediSpecie` +-- + +DROP TABLE IF EXISTS `ediSpecie`; +/*!50001 DROP VIEW IF EXISTS `ediSpecie`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `ediSpecie` AS SELECT + 1 AS `id`, + 1 AS `genusFk`, + 1 AS `latinSpeciesName`, + 1 AS `entried`, + 1 AS `dued`, + 1 AS `modified`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `emergencyMedia` +-- + +DROP TABLE IF EXISTS `emergencyMedia`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `emergencyMedia` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `value` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Table to save all emergency phones', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `energyInput` +-- + +DROP TABLE IF EXISTS `energyInput`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `energyInput` ( + `input` int(11) NOT NULL COMMENT 'The input number', + `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `consumption` int(11) NOT NULL COMMENT 'Consumption in watts', + PRIMARY KEY (`input`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Defines inputs and the power of each one'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `energyMeter` +-- + +DROP TABLE IF EXISTS `energyMeter`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `energyMeter` ( + `input` int(11) NOT NULL COMMENT 'The input number', + `period` datetime NOT NULL COMMENT 'Consumption period in hours interval', + `activeTime` int(11) NOT NULL COMMENT 'Number of seconds active', + `consumption` decimal(10,2) NOT NULL COMMENT 'Comsumption in watts', + PRIMARY KEY (`input`,`period`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='History of consumption of each input with one hour intervals'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `entry` +-- + +DROP TABLE IF EXISTS `entry`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `entry` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `supplierFk` int(11) NOT NULL DEFAULT '644', + `dated` datetime NOT NULL, + `ref` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `isBooked` tinyint(1) NOT NULL DEFAULT '0', + `isInventory` tinyint(1) NOT NULL DEFAULT '0', + `notes` longtext COLLATE utf8_unicode_ci, + `isConfirmed` tinyint(1) NOT NULL DEFAULT '0', + `isOrdered` tinyint(1) NOT NULL DEFAULT '0', + `isRaid` tinyint(1) NOT NULL DEFAULT '0', + `commission` float DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `evaNotes` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `travelFk` int(11) unsigned DEFAULT NULL, + `currencyFk` tinyint(3) unsigned DEFAULT '1', + `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442', + `gestDocFk` int(11) DEFAULT NULL, + `invoiceInFk` mediumint(8) unsigned DEFAULT NULL, + `isBlocked` tinyint(4) NOT NULL DEFAULT '0', + `loadPriority` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `Id_Proveedor` (`supplierFk`), + KEY `Fecha` (`dated`), + KEY `travel_id` (`travelFk`), + KEY `empresa_id` (`companyFk`), + KEY `gestdoc_id` (`gestDocFk`), + KEY `recibida_id` (`invoiceInFk`), + CONSTRAINT `Entradas_fk8` FOREIGN KEY (`invoiceInFk`) REFERENCES `vn2008`.`recibida` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `entry_ibfk_1` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE, + CONSTRAINT `entry_ibfk_6` FOREIGN KEY (`travelFk`) REFERENCES `travel` (`id`) ON UPDATE CASCADE, + CONSTRAINT `entry_ibfk_7` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=183609 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='InnoDB free: 88064 kB; (`Id_Proveedor`) REFER `vn2008/Provee'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `entry_beforeInsert` + BEFORE INSERT ON `entry` + FOR EACH ROW +BEGIN + SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk); + SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `entry_afterInsert` + AFTER INSERT ON `entry` + FOR EACH ROW +BEGIN + CALL travel_requestRecalc(NEW.travelFk); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `entry_beforeUpdate` + BEFORE UPDATE ON `entry` + FOR EACH ROW +BEGIN + -- Bernat: working in this file + DECLARE vIsClone BOOL; + DECLARE vPrintedCount INT; + DECLARE vHasDistinctWarehouses BOOL; + + IF !(NEW.travelFk <=> OLD.travelFk) THEN + SELECT COUNT(*) > 0 INTO vIsClone + FROM vn2008.Entradas_Auto WHERE Id_Entrada = NEW.id; + + SELECT !(o.warehouseInFk <=> n.warehouseInFk) + OR !(o.warehouseOutFk <=> n.warehouseOutFk) + INTO vHasDistinctWarehouses + FROM travel o, travel n + WHERE o.id = OLD.travelFk + AND n.id = NEW.travelFk; + + IF vIsClone AND vHasDistinctWarehouses THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses'; + END IF; + + IF NEW.travelFk IS NULL THEN + SELECT COUNT(*) INTO vPrintedCount + FROM buy + WHERE entryFk = OLD.id + AND printedStickers > 0; + + IF vPrintedCount > 0 THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'An entry that contains lines with printed labels cannot be deleted'; + END IF; + END IF; + END IF; + + IF !(NEW.supplierFk <=> OLD.supplierFk) THEN + SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk); + END IF; + + IF !(NEW.travelFk <=> OLD.travelFk) + OR !(NEW.currencyFk <=> OLD.currencyFk) THEN + SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); + END IF; + + IF !(ABS(NEW.isBooked) <=> ABS(OLD.isBooked)) THEN + INSERT INTO vn2008.Entradas_dits SET + idaccion_dits = 105, + Id_Trabajador = myWorker_getId(), + Id_Ticket = NEW.id, + value_old = OLD.isBooked, + value_new = NEW.isBooked; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `entry_afterUpdate` + AFTER UPDATE ON `entry` + FOR EACH ROW +BEGIN + IF !(NEW.id <=> OLD.id) + OR !(NEW.travelFk <=> OLD.travelFk) + OR !(NEW.isRaid <=> OLD.isRaid) THEN + CALL stock.log_add('entry', NEW.id, OLD.id); + END IF; + + IF !(NEW.travelFk <=> OLD.travelFk) THEN + CALL travel_requestRecalc(OLD.travelFk); + CALL travel_requestRecalc(NEW.travelFk); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `entry_beforeDelete` + BEFORE DELETE ON `entry` + FOR EACH ROW +BEGIN + DELETE FROM buy WHERE entryFk = OLD.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_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `entry_afterDelete` + AFTER DELETE ON `entry` + FOR EACH ROW +BEGIN + CALL travel_requestRecalc(OLD.travelFk); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `entryLog` +-- + +DROP TABLE IF EXISTS `entryLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `entryLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(11) NOT NULL, + `userFk` int(10) unsigned NOT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + PRIMARY KEY (`id`), + KEY `logEntry_ibfk_1` (`originFk`), + KEY `entryLog_ibfk_2` (`userFk`), + CONSTRAINT `entryLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `entryLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=181611 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `entrySplit` +-- + +DROP TABLE IF EXISTS `entrySplit`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `entrySplit` ( + `receivedFk` int(11) NOT NULL, + `delayedFk` int(11) NOT NULL, + PRIMARY KEY (`receivedFk`,`delayedFk`), + KEY `entrySplit_fk2_idx` (`delayedFk`), + CONSTRAINT `entrySplit_fk1` FOREIGN KEY (`receivedFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `entrySplit_fk2` FOREIGN KEY (`delayedFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `entryVirtual` +-- + +DROP TABLE IF EXISTS `entryVirtual`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `entryVirtual` ( + `entryFk` int(11) NOT NULL, + PRIMARY KEY (`entryFk`), + CONSTRAINT `entryVirtual_ibfk_1` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='entradas que se van moviendo automaticamente al futuro'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `envialiaAgency` +-- + +DROP TABLE IF EXISTS `envialiaAgency`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `envialiaAgency` ( + `id` varchar(6) COLLATE utf8_unicode_ci NOT NULL, + `route` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `agencyName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `id_UNIQUE` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `envialiaCity` +-- + +DROP TABLE IF EXISTS `envialiaCity`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `envialiaCity` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `city` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `postalCode` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `agencyFk` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `agencyFk` (`agencyFk`), + KEY `postalCode` (`postalCode`) +) ENGINE=InnoDB AUTO_INCREMENT=1585166 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `envialiaConfig` +-- + +DROP TABLE IF EXISTS `envialiaConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `envialiaConfig` ( + `serviceType` varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '024' COMMENT 'Tipo de servicio en horas. 024 -> servicio las 24h', + `numBox` varchar(3) COLLATE utf8_unicode_ci DEFAULT '001' COMMENT 'cajas por envio', + `startRange` bigint(25) DEFAULT NULL COMMENT 'Principio del rango que nos proporciona enviaría', + `endRange` bigint(25) DEFAULT NULL COMMENT 'limite del rango que nos proporciona enviaría', + `cargoAgency` varchar(25) COLLATE utf8_unicode_ci DEFAULT '004666' COMMENT 'numero de verdnatura dado por enviaría', + `actualNumber` bigint(25) DEFAULT NULL COMMENT 'Numero actual de etiquetas imprimidas , comprimido entre startRange y endRange, ', + `isAlreadyNotified` int(1) NOT NULL DEFAULT '0' COMMENT 'Booleano para que el evento vn.envialiaRangeChecker compruebe si se a enviado una notificación\n', + `notificationThrehold` int(11) DEFAULT NULL COMMENT 'Umbral para avisar a enviaría de reseetar el startRange y endRange\nSe avisara a enviaría si el umbral + el actualNumber es superior a endRange\n', + PRIMARY KEY (`serviceType`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `exchangeInsuranceEntry` +-- + +DROP TABLE IF EXISTS `exchangeInsuranceEntry`; +/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceEntry`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `exchangeInsuranceEntry` AS SELECT + 1 AS `dated`, + 1 AS `Dolares`, + 1 AS `rate`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `exchangeInsuranceIn` +-- + +DROP TABLE IF EXISTS `exchangeInsuranceIn`; +/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceIn`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `exchangeInsuranceIn` AS SELECT + 1 AS `dated`, + 1 AS `amount`, + 1 AS `rate`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `exchangeInsuranceOut` +-- + +DROP TABLE IF EXISTS `exchangeInsuranceOut`; +/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceOut`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `exchangeInsuranceOut` AS SELECT + 1 AS `received`, + 1 AS `divisa`, + 1 AS `rate`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `exchangeReportSourcePrevious` +-- + +DROP TABLE IF EXISTS `exchangeReportSourcePrevious`; +/*!50001 DROP VIEW IF EXISTS `exchangeReportSourcePrevious`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!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` +-- + +DROP TABLE IF EXISTS `excuse`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `excuse` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `txt` varchar(255) CHARACTER SET latin1 NOT NULL, + `date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `expedition` +-- + +DROP TABLE IF EXISTS `expedition`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `expedition` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `agencyModeFk` int(11) NOT NULL, + `ticketFk` int(10) NOT NULL, + `isBox` int(11) DEFAULT '1', + `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `isRefund` bit(1) DEFAULT b'0', + `isPickUp` bit(1) DEFAULT b'0', + `itemFk` int(11) DEFAULT NULL, + `counter` smallint(5) unsigned NOT NULL, + `checked` tinyint(4) NOT NULL DEFAULT '0', + `workerFk` int(11) DEFAULT NULL, + `externalId` bigint(25) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `index1` (`agencyModeFk`), + KEY `index2` (`isBox`), + KEY `index3` (`created`), + KEY `index4` (`ticketFk`), + CONSTRAINT `Id_Agencia` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE, + CONSTRAINT `ticket_id` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=3475031 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`expedition_beforeInsert` + BEFORE INSERT ON `expedition` FOR EACH ROW +-- Edit trigger body code below this line. Do not edit lines above this one +BEGIN + DECLARE intcounter INT; + DECLARE vShipFk INT; + + IF NEW.isBox > 0 THEN + + UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk; + + SELECT IFNULL(MAX(counter),0) +1 INTO intcounter + FROM expedition e + INNER JOIN ticket t1 ON e.ticketFk = t1.id + LEFT JOIN ticketState ts ON ts.ticket = t1.id + INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + AND t1.warehouseFk = t2.warehouseFk + WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk + AND t1.agencyModeFk = t2.agencyModeFk; + + SET NEW.`counter` = intcounter; + END IF; + + -- JGF 14/01/19 si existe un polizon queda anulado + SELECT shipFk INTO vShipFk FROM stowaway WHERE id = NEW.ticketFk; + + IF vShipFk THEN + CALL stowawayUnBoarding(vShipFk, NEW.ticketFk); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`expedition_beforeUpdate` + BEFORE UPDATE ON `expedition` FOR EACH ROW +-- Edit trigger body code below this line. Do not edit lines above this one +BEGIN + IF NEW.counter <> OLD.counter THEN + IF (SELECT COUNT(*) FROM expedition e + INNER JOIN ticket t1 ON e.ticketFk = t1.id + INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + WHERE t1.id = NEW.ticketFk AND counter = NEW.counter) > 0 THEN + SET NEW.id = NULL; + END IF; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`expedition_beforeDelete` + BEFORE DELETE ON `expedition` FOR EACH ROW +BEGIN + UPDATE ticket t + SET packages = (SELECT COUNT(counter)-1 + FROM expedition e WHERE e.ticketFk = OLD.ticketFk and e.isBox) + WHERE t.id = OLD.ticketFk; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `expeditionBoxVol` +-- + +DROP TABLE IF EXISTS `expeditionBoxVol`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `expeditionBoxVol` ( + `boxFk` int(11) NOT NULL, + `m3` double NOT NULL, + `ratio` double NOT NULL, + PRIMARY KEY (`boxFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Establece el volumen de cada servicio para poder comparar el teorico y el real en el control de portes'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `expence` +-- + +DROP TABLE IF EXISTS `expence`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `expence` ( + `id` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `taxTypeFk` tinyint(4) NOT NULL, + `name` varchar(50) DEFAULT NULL, + `isConbase` tinyint(4) NOT NULL DEFAULT '1', + `isWithheld` tinyint(4) NOT NULL DEFAULT '0', + `isForSale` tinyint(4) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`,`taxTypeFk`), + KEY `iva_tipo_id` (`taxTypeFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `firstTicketShipped` +-- + +DROP TABLE IF EXISTS `firstTicketShipped`; +/*!50001 DROP VIEW IF EXISTS `firstTicketShipped`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `firstTicketShipped` AS SELECT + 1 AS `shipped`, + 1 AS `clientFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `floraHollandBuyedItems` +-- + +DROP TABLE IF EXISTS `floraHollandBuyedItems`; +/*!50001 DROP VIEW IF EXISTS `floraHollandBuyedItems`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `floraHollandBuyedItems` AS SELECT + 1 AS `itemFk`, + 1 AS `longName`, + 1 AS `quantity`, + 1 AS `buyingValue`, + 1 AS `landed`, + 1 AS `companyFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `fuelType` +-- + +DROP TABLE IF EXISTS `fuelType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `fuelType` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `code` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `code_UNIQUE` (`code`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `gateArea` +-- + +DROP TABLE IF EXISTS `gateArea`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `gateArea` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `greuge` +-- + +DROP TABLE IF EXISTS `greuge`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `greuge` ( + `Id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `clientFk` int(10) unsigned NOT NULL, + `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `amount` decimal(10,2) NOT NULL, + `shipped` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `greugeTypeFk` int(11) DEFAULT NULL, + `ticketFk` int(11) DEFAULT NULL, + PRIMARY KEY (`Id`), + KEY `greuges_type_fk_idx` (`greugeTypeFk`), + KEY `Id_Ticket_Greuge_Ticket_idx` (`ticketFk`), + KEY `Greuges_cliente_idx` (`clientFk`), + CONSTRAINT `Id_Ticket_Greuge_Ticket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `greuges_type_fk` FOREIGN KEY (`greugeTypeFk`) REFERENCES `greugeType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=3850864 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=COMPACT; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`greuge_beforeUpdate` BEFORE UPDATE ON `greuge` FOR EACH ROW +BEGIN + DECLARE vMaxDate DATETIME DEFAULT TIMESTAMPADD(YEAR,1,CURDATE()); + + IF NEW.shipped > vMaxDate THEN + SET NEW.shipped = vMaxDate; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `greugeType` +-- + +DROP TABLE IF EXISTS `greugeType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `greugeType` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `code` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `holiday` +-- + +DROP TABLE IF EXISTS `holiday`; +/*!50001 DROP VIEW IF EXISTS `holiday`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `holiday` AS SELECT + 1 AS `holidayDetailFk`, + 1 AS `holidayTypeFk`, + 1 AS `workCenterFk`, + 1 AS `dated`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `holidayDetail` +-- + +DROP TABLE IF EXISTS `holidayDetail`; +/*!50001 DROP VIEW IF EXISTS `holidayDetail`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `holidayDetail` AS SELECT + 1 AS `id`, + 1 AS `description`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `holidayLegend` +-- + +DROP TABLE IF EXISTS `holidayLegend`; +/*!50001 DROP VIEW IF EXISTS `holidayLegend`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `holidayLegend` AS SELECT + 1 AS `id`, + 1 AS `description`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `holidayType` +-- + +DROP TABLE IF EXISTS `holidayType`; +/*!50001 DROP VIEW IF EXISTS `holidayType`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `holidayType` AS SELECT + 1 AS `id`, + 1 AS `name`, + 1 AS `rgb`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `ink` +-- + +DROP TABLE IF EXISTS `ink`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ink` ( + `id` char(3) COLLATE utf8_unicode_ci NOT NULL, + `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `picture` blob NOT NULL, + `showOrder` int(11) NOT NULL, + `ball` blob, + `isCargex` tinyint(4) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `inkI18n` +-- + +DROP TABLE IF EXISTS `inkI18n`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `inkI18n` ( + `inkFk` char(3) COLLATE utf8_unicode_ci NOT NULL, + `lang` char(2) CHARACTER SET utf8 NOT NULL, + `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`inkFk`,`lang`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `inkL10n` +-- + +DROP TABLE IF EXISTS `inkL10n`; +/*!50001 DROP VIEW IF EXISTS `inkL10n`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `inkL10n` AS SELECT + 1 AS `id`, + 1 AS `name`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `intrastat` +-- + +DROP TABLE IF EXISTS `intrastat`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `intrastat` ( + `id` int(8) unsigned zerofill NOT NULL, + `description` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `import` tinyint(4) NOT NULL DEFAULT '0', + `taxClassFk` tinyint(3) unsigned NOT NULL DEFAULT '2', + `taxCodeFk` tinyint(2) unsigned NOT NULL DEFAULT '64', + PRIMARY KEY (`id`), + KEY `iva_group_id` (`taxClassFk`), + CONSTRAINT `intrastat_ibfk_1` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `inventoryFailure` +-- + +DROP TABLE IF EXISTS `inventoryFailure`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `inventoryFailure` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `itemFk` int(11) NOT NULL, + `quantity` int(11) NOT NULL, + `value` decimal(10,2) NOT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL, + `throwerFk` int(11) DEFAULT NULL, + `guiltyFk` int(11) DEFAULT NULL, + `causeFk` int(11) DEFAULT NULL, + `explanation` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `inventoryFailure_fk1_idx` (`itemFk`), + KEY `inventoryFailure_fk2_idx` (`throwerFk`), + KEY `inventoryFailure_fk_idx` (`guiltyFk`), + KEY `inventoryFailure_fk4_idx` (`warehouseFk`), + KEY `inventoryFailure_fk5_idx` (`causeFk`), + CONSTRAINT `inventoryFailure_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `inventoryFailure_fk2` FOREIGN KEY (`throwerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `inventoryFailure_fk3` FOREIGN KEY (`guiltyFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `inventoryFailure_fk4` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `inventoryFailure_fk5` FOREIGN KEY (`causeFk`) REFERENCES `inventoryFailureCause` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=29968 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `inventoryFailureCause` +-- + +DROP TABLE IF EXISTS `inventoryFailureCause`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `inventoryFailureCause` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `invoiceCorrection` +-- + +DROP TABLE IF EXISTS `invoiceCorrection`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `invoiceCorrection` ( + `correctingFk` int(10) unsigned NOT NULL COMMENT 'Factura rectificativa', + `correctedFk` int(10) unsigned NOT NULL COMMENT 'Factura rectificada', + `cplusRectificationTypeFk` int(10) unsigned NOT NULL, + `cplusInvoiceType477Fk` int(10) unsigned NOT NULL, + `invoiceCorrectionTypeFk` int(11) NOT NULL DEFAULT '3', + PRIMARY KEY (`correctingFk`), + KEY `correctedFk_idx` (`correctedFk`), + KEY `invoiceCorrection_ibfk_1_idx` (`cplusRectificationTypeFk`), + KEY `cplusInvoiceTyoeFk_idx` (`cplusInvoiceType477Fk`), + KEY `invoiceCorrectionTypeFk_idx` (`invoiceCorrectionTypeFk`), + CONSTRAINT `corrected_fk` FOREIGN KEY (`correctedFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `correcting_fk` FOREIGN KEY (`correctingFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `cplusInvoiceTyoeFk` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `cplusInvoiceType477` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceCorrectionType_Fk33` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceCorrection_ibfk_1` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Relacion entre las facturas rectificativas y las rectificadas.'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `invoiceCorrectionDataSource` +-- + +DROP TABLE IF EXISTS `invoiceCorrectionDataSource`; +/*!50001 DROP VIEW IF EXISTS `invoiceCorrectionDataSource`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `invoiceCorrectionDataSource` AS SELECT + 1 AS `itemFk`, + 1 AS `quantity`, + 1 AS `concept`, + 1 AS `price`, + 1 AS `discount`, + 1 AS `refFk`, + 1 AS `saleFk`, + 1 AS `shipped`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `invoiceCorrectionType` +-- + +DROP TABLE IF EXISTS `invoiceCorrectionType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `invoiceCorrectionType` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `description_UNIQUE` (`description`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `invoiceInSerial` +-- + +DROP TABLE IF EXISTS `invoiceInSerial`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `invoiceInSerial` ( + `code` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `cplusTerIdNifFk` int(11) NOT NULL DEFAULT '1', + `taxAreaFk` varchar(15) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`code`), + KEY `InvoiceInSerial_Fk1_idx` (`cplusTerIdNifFk`), + KEY `InvoiceInSerialTaxArea_idx` (`taxAreaFk`), + CONSTRAINT `InvoiceInSerialTaxArea` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON UPDATE CASCADE, + CONSTRAINT `InvoiceInSerial_Fk1` FOREIGN KEY (`cplusTerIdNifFk`) REFERENCES `cplusTerIdNif` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `invoiceInTaxBookingAccount` +-- + +DROP TABLE IF EXISTS `invoiceInTaxBookingAccount`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `invoiceInTaxBookingAccount` ( + `id` int(10) NOT NULL AUTO_INCREMENT, + `effectived` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `account` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `taxAreaFk` varchar(15) CHARACTER SET utf8 NOT NULL, + `priority` int(2) unsigned DEFAULT NULL, + `taxClassFk` tinyint(3) unsigned NOT NULL DEFAULT '1', + `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1', + `rate` decimal(5,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`id`), + KEY `invoiceInTaxBookingAccount_fk1_idx` (`taxAreaFk`), + KEY `invoiceInTaxBookingAccount_fk2_idx` (`taxClassFk`), + KEY `invoiceInTaxBookingAccount_fk3_idx` (`countryFk`), + CONSTRAINT `invoiceInTaxBookingAccount_fk1` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `invoiceInTaxBookingAccount_fk2` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceInTaxBookingAccount_fk3` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `invoiceOut` +-- + +DROP TABLE IF EXISTS `invoiceOut`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `invoiceOut` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `ref` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `serial` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `issued` date DEFAULT NULL, + `amount` decimal(12,2) DEFAULT '0.00', + `dued` datetime DEFAULT NULL, + `bankFk` int(11) DEFAULT NULL, + `clientFk` int(11) DEFAULT '0', + `Id_Remesa__` int(11) DEFAULT NULL, + `Remesar__` tinyint(1) NOT NULL DEFAULT '0', + `taxableBase7` decimal(12,2) DEFAULT '0.00', + `taxableBase16` decimal(12,2) DEFAULT '0.00', + `equ1` decimal(12,2) DEFAULT '0.00', + `equ4` decimal(12,2) DEFAULT '0.00', + `vat7` decimal(12,2) DEFAULT '0.00', + `vat16` decimal(12,2) DEFAULT '0.00', + `workerFk` int(11) DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442', + `liquidacion__` smallint(6) DEFAULT '0', + `hasPdf` tinyint(3) unsigned NOT NULL DEFAULT '0', + `booked` date DEFAULT NULL, + `cplusInvoiceType477Fk` int(10) unsigned NOT NULL DEFAULT '1', + `cplusTaxBreakFk` int(10) unsigned NOT NULL DEFAULT '1', + `cplusSubjectOpFk` int(10) unsigned NOT NULL DEFAULT '1', + `cplusTrascendency477Fk` int(10) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`,`ref`), + UNIQUE KEY `Id_Factura` (`ref`), + KEY `Id_Banco` (`bankFk`), + KEY `Id_Cliente` (`clientFk`), + KEY `Id_Remesa` (`Id_Remesa__`), + KEY `Id_Trabajador` (`workerFk`), + KEY `empresa_id` (`companyFk`), + KEY `Fecha` (`issued`), + KEY `Facturas_ibfk_2_idx` (`cplusInvoiceType477Fk`), + KEY `Facturas_ibfk_3_idx` (`cplusSubjectOpFk`), + KEY `Facturas_ibfk_4_idx` (`cplusTaxBreakFk`), + KEY `Facturas_ibfk_5_idx` (`cplusTrascendency477Fk`), + KEY `Facturas_idx_Vencimiento` (`dued`), + CONSTRAINT `invoiceOut_ibfk_1` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceOut_ibfk_2` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `cplusInvoiceType477` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceOut_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `cplusSubjectOp` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceOut_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoice_bank_id` FOREIGN KEY (`bankFk`) REFERENCES `bank` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoice_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=525260 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`invoiceOut_beforeInsert` + BEFORE INSERT ON `invoiceOut` FOR EACH ROW +-- Edit trigger body code below this line. Do not edit lines above this one +BEGIN + DECLARE vRef CHAR(9) DEFAULT '0000001'; + DECLARE vMaxId INT; + + SELECT IFNULL(MAX(id),0) INTO vMaxId + FROM invoiceOut + WHERE serial LIKE NEW.serial + AND ((Year(NEW.issued) = Year(issued) + AND companyFk = NEW.companyFk)); + + IF vMaxId THEN + + SELECT RIGHT(MAX(ref), LENGTH(ref)-1) + 1 + INTO vRef + FROM invoiceOut + WHERE serial LIKE NEW.serial + AND ((Year(NEW.issued) = Year(issued) + AND length(ref) > 6 + AND companyFk = NEW.companyFk) /*OR (NEW.serial LIKE 'B' AND length(ref) > 7)*/ ); + ELSE + SELECT CONCAT(sage200Company,RIGHT(YEAR(CURDATE()),1),'00001') INTO vRef + FROM company + WHERE id = NEW.companyFk; +/*Primer digito la empresa, segundo el año, despues la numeracion correlativa con 5 digitos*/ + END IF; + + SELECT CONCAT(NEW.serial, LPAD(vRef,7,'0')) INTO vRef; + SET NEW.ref = vRef; +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`invoiceOut_afterInsert` + AFTER INSERT ON `invoiceOut` FOR EACH ROW +BEGIN + CALL bi.customer_risk_update (NEW.clientFk, NEW.companyFk, NEW.amount); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`invoiceOut_beforeUpdate` + BEFORE UPDATE ON `invoiceOut` FOR EACH ROW +BEGIN + CALL bi.customer_risk_update (OLD.clientFk, OLD.companyFk, -OLD.amount); + CALL bi.customer_risk_update (NEW.clientFk, NEW.companyFk, NEW.amount); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`invoiceOut_beforeDelete` + BEFORE DELETE ON `invoiceOut` FOR EACH ROW +BEGIN + CALL bi.customer_risk_update (OLD.clientFk, OLD.companyFk, -OLD.amount); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `invoiceOutExpence` +-- + +DROP TABLE IF EXISTS `invoiceOutExpence`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `invoiceOutExpence` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `invoiceOutFk` int(10) unsigned NOT NULL, + `amount` decimal(10,2) NOT NULL DEFAULT '0.00', + `expenceFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `invoiceOutExpence_restriccion` (`expenceFk`,`invoiceOutFk`), + KEY `invoiceOutExpence_FK_1_idx` (`invoiceOutFk`), + KEY `invoiceOutExpence_FK_2_idx` (`expenceFk`), + CONSTRAINT `invoiceOutExpence_FK_1` FOREIGN KEY (`invoiceOutFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `invoiceOutExpence_FK_2` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=139712 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Desglosa la base imponible de una factura en funcion del tipo de gasto/venta'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `invoiceOutSerial` +-- + +DROP TABLE IF EXISTS `invoiceOutSerial`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `invoiceOutSerial` ( + `code` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `isTaxed` tinyint(1) NOT NULL DEFAULT '1', + `taxAreaFk` varchar(15) CHARACTER SET utf8 NOT NULL DEFAULT 'NATIONAL', + `isCEE` tinyint(1) NOT NULL DEFAULT '0', + `cplusInvoiceType477Fk` int(10) unsigned DEFAULT '1', + PRIMARY KEY (`code`), + KEY `taxAreaFk_idx` (`taxAreaFk`), + CONSTRAINT `invoiceOutSeriaTaxArea` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `invoiceOutTax` +-- + +DROP TABLE IF EXISTS `invoiceOutTax`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `invoiceOutTax` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `invoiceOutFk` int(10) unsigned NOT NULL, + `taxableBase` decimal(10,2) NOT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `vat` decimal(10,2) NOT NULL DEFAULT '0.00', + `pgcFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0000000000', + PRIMARY KEY (`id`), + UNIQUE KEY `invoiceOutTax_Resctriccion` (`invoiceOutFk`,`pgcFk`), + KEY `invoiceOutFk_idx` (`invoiceOutFk`), + KEY `pgcFk` (`pgcFk`), + CONSTRAINT `invoiceOutFk` FOREIGN KEY (`invoiceOutFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `invoiceOutTax_ibfk_1` FOREIGN KEY (`pgcFk`) REFERENCES `pgc` (`code`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=1193218 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `item` +-- + +DROP TABLE IF EXISTS `item`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `item` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `equivalent` int(11) unsigned DEFAULT NULL, + `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `size` int(10) unsigned DEFAULT NULL, + `stems` int(11) DEFAULT '1', + `minPrice` double DEFAULT '0', + `isToPrint` tinyint(1) NOT NULL DEFAULT '0', + `isDeliveryNote` tinyint(1) NOT NULL DEFAULT '0', + `taxClassFk` tinyint(4) unsigned NOT NULL DEFAULT '1', + `family` varchar(3) COLLATE utf8_unicode_ci DEFAULT 'VT', + `box` tinyint(1) NOT NULL DEFAULT '0', + `category` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `originFk` tinyint(2) unsigned NOT NULL, + `doPhoto` tinyint(4) NOT NULL DEFAULT '0', + `image` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `inkFk` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `niche` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `intrastatFk` int(8) unsigned zerofill DEFAULT NULL, + `hasMinPrice` tinyint(1) NOT NULL DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `isOnOffer` tinyint(4) NOT NULL DEFAULT '0', + `isBargain` tinyint(4) NOT NULL DEFAULT '0', + `comment` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, + `typeFk` smallint(5) unsigned NOT NULL, + `generic` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0', + `producerFk` mediumint(3) unsigned DEFAULT NULL, + `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `density` int(11) NOT NULL DEFAULT '167' COMMENT 'Almacena la densidad en kg/m3 para el calculo de los portes, si no se especifica se pone por defecto la del tipo en un trigger', + `relevancy` tinyint(1) NOT NULL DEFAULT '0', + `expenceFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '7001000000', + `isActive` tinyint(1) NOT NULL DEFAULT '1', + `longName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `subName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `tag5` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `value5` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `tag6` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `value6` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `tag7` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `value7` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `tag8` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `value8` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `tag9` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `value9` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `tag10` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `value10` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `compression` decimal(5,2) NOT NULL DEFAULT '1.00' COMMENT 'Relacion de compresividad entre el volumen de las entradas en Silla y el empaquetado en los envios a clientes.\n\nMenor que 1 significa que se puede comprimir más que el volumen original.', + `minimum` decimal(10,0) unsigned NOT NULL DEFAULT '3' COMMENT 'Cantidad máxima de cajas / cubos que cabe en un nicho', + `upToDown` decimal(10,0) unsigned NOT NULL DEFAULT '0' COMMENT 'Se muestra el precio por kilo ', + `hasKgPrice` tinyint(1) NOT NULL DEFAULT '0', + `sectorFk` int(11) DEFAULT '2', + PRIMARY KEY (`id`), + KEY `Article` (`name`), + KEY `Color` (`inkFk`), + KEY `id_origen` (`originFk`), + KEY `Codintrastat` (`intrastatFk`), + KEY `iva_group_id` (`taxClassFk`), + KEY `tipo_id` (`typeFk`), + KEY `producer_id` (`producerFk`), + KEY `expenceFk_idx` (`expenceFk`), + KEY `ArticlesIsActive_idx` (`isActive`), + KEY `item_ibfk_6_idx` (`sectorFk`), + CONSTRAINT `expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE, + CONSTRAINT `item_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `origin` (`id`) ON UPDATE CASCADE, + CONSTRAINT `item_ibfk_2` FOREIGN KEY (`intrastatFk`) REFERENCES `intrastat` (`id`) ON UPDATE CASCADE, + CONSTRAINT `item_ibfk_4` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE, + CONSTRAINT `item_ibfk_5` FOREIGN KEY (`typeFk`) REFERENCES `itemType` (`id`) ON UPDATE CASCADE, + CONSTRAINT `item_ibfk_6` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `producer_id` FOREIGN KEY (`producerFk`) REFERENCES `producer` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=380013 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`item_beforeInsert` + BEFORE INSERT ON `item` FOR EACH ROW +BEGIN + DECLARE vDensity DOUBLE; + DECLARE vInsertId INT; + DECLARE vProducerFk VARCHAR(50); + DECLARE vInkName VARCHAR(50); + + IF NEW.density IS NULL THEN + SELECT density INTO vDensity + FROM itemType WHERE id = NEW.typeFk; + + SET NEW.density = vDensity; + END IF; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`item_afterInsert` + AFTER INSERT ON `item` FOR EACH ROW +BEGIN + CALL hedera.image_ref('catalog', NEW.image); + + INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk) + SELECT NEW.id, 1, NEW.taxClassFk; + + INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk) + SELECT NEW.id, 5, NEW.taxClassFk; + + INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk) + SELECT NEW.id, 30, NEW.taxClassFk; +/* + IF NEW.typeFk IS NOT NULL THEN + INSERT INTO vn.itemTag (itemFk, tagFk, priority) + SELECT NEW.id, tagFk, priority FROM vn.itemTypeTag + WHERE itemTypeFk = NEW.typeFk; + END IF; +*/ +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`item_afterUpdate` + AFTER UPDATE ON `item` FOR EACH ROW +BEGIN + IF !(NEW.image <=> OLD.image) THEN + CALL hedera.image_unref('catalog', OLD.image); + CALL hedera.image_ref('catalog', NEW.image); + END IF; + IF NEW.density = 0 THEN + CALL util.throw('error densidad = 0'); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`item_afterDelete` + AFTER DELETE ON `item` FOR EACH ROW +BEGIN + CALL hedera.image_unref('catalog', OLD.image); + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `itemBarcode` +-- + +DROP TABLE IF EXISTS `itemBarcode`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemBarcode` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `itemFk` int(11) NOT NULL, + `code` varchar(22) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `code` (`code`), + UNIQUE KEY `Id_Article_2` (`itemFk`,`code`), + KEY `Id_Article` (`itemFk`), + CONSTRAINT `itemBarcode_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=43128 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `itemBotanical` +-- + +DROP TABLE IF EXISTS `itemBotanical`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemBotanical` ( + `itemFk` int(11) NOT NULL, + `botanical` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `genusFk` mediumint(8) unsigned DEFAULT NULL, + `specieFk` mediumint(8) unsigned DEFAULT NULL, + PRIMARY KEY (`itemFk`), + KEY `genusFgn_idx` (`genusFk`), + KEY `specieFgn_idx` (`specieFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Sustituye a antiguo NomBotanic de Articles'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemBotanical_beforeInsert` BEFORE INSERT ON `itemBotanical` FOR EACH ROW +BEGIN + IF NEW.botanical = '' THEN + SET NEW.botanical = NULL; + END IF; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemBotanical_beforeUpdate` BEFORE UPDATE ON `itemBotanical` FOR EACH ROW +BEGIN + IF NEW.botanical = '' THEN + SET NEW.botanical = NULL; + 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 */ ; + +-- +-- Temporary view structure for view `itemBotanicalWithGenus` +-- + +DROP TABLE IF EXISTS `itemBotanicalWithGenus`; +/*!50001 DROP VIEW IF EXISTS `itemBotanicalWithGenus`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemBotanicalWithGenus` AS SELECT + 1 AS `itemFk`, + 1 AS `ediBotanic`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `itemCategory` +-- + +DROP TABLE IF EXISTS `itemCategory`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemCategory` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `order` int(10) unsigned DEFAULT NULL, + `display` tinyint(4) NOT NULL DEFAULT '1', + `color` char(6) COLLATE utf8_unicode_ci DEFAULT NULL, + `shortLife` int(11) NOT NULL DEFAULT '0' COMMENT 'Sirve para filtrar aquellos reinos que tienen precios estables', + `merchandise` tinyint(1) NOT NULL DEFAULT '1', + `icon` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `code` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `reino_UNIQUE` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `itemCategoryI18n` +-- + +DROP TABLE IF EXISTS `itemCategoryI18n`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemCategoryI18n` ( + `categoryFk` int(10) unsigned NOT NULL, + `lang` char(2) CHARACTER SET utf8 NOT NULL, + `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`categoryFk`,`lang`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `itemCategoryL10n` +-- + +DROP TABLE IF EXISTS `itemCategoryL10n`; +/*!50001 DROP VIEW IF EXISTS `itemCategoryL10n`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemCategoryL10n` AS SELECT + 1 AS `id`, + 1 AS `name`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `itemConversor` +-- + +DROP TABLE IF EXISTS `itemConversor`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemConversor` ( + `espItemFk` int(11) NOT NULL, + `genItemFk` int(11) DEFAULT NULL, + PRIMARY KEY (`espItemFk`), + KEY `itemConversor_fk2_idx` (`genItemFk`), + CONSTRAINT `itemConversor_fk1` FOREIGN KEY (`espItemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemConversor_fk2` FOREIGN KEY (`genItemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Relaciona los item específicos con los genéricos'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `itemEntryIn` +-- + +DROP TABLE IF EXISTS `itemEntryIn`; +/*!50001 DROP VIEW IF EXISTS `itemEntryIn`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemEntryIn` AS SELECT + 1 AS `warehouseInFk`, + 1 AS `landed`, + 1 AS `itemFk`, + 1 AS `quantity`, + 1 AS `isReceived`, + 1 AS `isVirtualStock`, + 1 AS `entryFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `itemEntryOut` +-- + +DROP TABLE IF EXISTS `itemEntryOut`; +/*!50001 DROP VIEW IF EXISTS `itemEntryOut`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemEntryOut` AS SELECT + 1 AS `warehouseOutFk`, + 1 AS `shipped`, + 1 AS `itemFk`, + 1 AS `quantity`, + 1 AS `isDelivered`, + 1 AS `entryFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `itemFreeNumber` +-- + +DROP TABLE IF EXISTS `itemFreeNumber`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemFreeNumber` ( + `itemFk` int(11) NOT NULL, + PRIMARY KEY (`itemFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `itemLog` +-- + +DROP TABLE IF EXISTS `itemLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(11) NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `itemLogItemFk_idx` (`originFk`), + KEY `itemLogUserFk_idx` (`userFk`), + CONSTRAINT `itemLogItemFk` FOREIGN KEY (`originFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemLogUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=107546 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `itemPlacement` +-- + +DROP TABLE IF EXISTS `itemPlacement`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemPlacement` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `itemFk` int(11) NOT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1', + `code` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `modificationDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `reserve` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `pickable` int(11) unsigned NOT NULL DEFAULT '0', + `sectorFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `Id_Article_UNIQUE` (`itemFk`,`warehouseFk`), + KEY `Articles_nicho_wh_fk` (`warehouseFk`), + KEY `itemPlacement_fk3_idx` (`id`,`sectorFk`), + KEY `itemPlacement_fk3_idx1` (`sectorFk`), + CONSTRAINT `Articles_nicho_wh_fk` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `Articles_nichos_fk` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemPlacement_fk3` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=1179115 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemPlacement_AFTER_DELETE` AFTER DELETE ON `itemPlacement` FOR EACH ROW +BEGIN + INSERT INTO vn.mail SET + `sender` = 'jgallego@verdnatura.es', + `replyTo` = 'jgallego@verdnatura.es', + `subject` = 'Nicho modificado', + `body` = CONCAT(account.myUserGetName(), ' ha eliminado la linea de ', OLD.`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 */ ; + +-- +-- Table structure for table `itemPlacementSupply` +-- + +DROP TABLE IF EXISTS `itemPlacementSupply`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemPlacementSupply` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `itemFk` int(11) NOT NULL, + `quantity` decimal(10,0) NOT NULL DEFAULT '0', + `priority` int(10) unsigned NOT NULL DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `userFk` int(10) unsigned NOT NULL COMMENT 'Persona que crea la orden', + `repoUserFk` int(10) unsigned DEFAULT NULL COMMENT 'Reponedor que la tiene asignada', + `sectorFk` int(11) NOT NULL DEFAULT '2', + PRIMARY KEY (`id`), + KEY `itemPlacementSupply_fk1_idx` (`itemFk`), + KEY `itemPlacementSupply_fk2_idx` (`userFk`), + KEY `itemPlacementSupply_fk2_idx1` (`repoUserFk`), + KEY `itemPlacementSupply_fk4_idx` (`sectorFk`), + CONSTRAINT `itemPlacementSupply_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemPlacementSupply_fk2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemPlacementSupply_fk3` FOREIGN KEY (`repoUserFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemPlacementSupply_fk4` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=86940 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de nichos de picking que hay que reponer'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `itemPlacementSupplyList` +-- + +DROP TABLE IF EXISTS `itemPlacementSupplyList`; +/*!50001 DROP VIEW IF EXISTS `itemPlacementSupplyList`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemPlacementSupplyList` AS SELECT + 1 AS `id`, + 1 AS `itemFk`, + 1 AS `quantity`, + 1 AS `priority`, + 1 AS `created`, + 1 AS `userFk`, + 1 AS `repoUserFk`, + 1 AS `saldo`, + 1 AS `longName`, + 1 AS `subName`, + 1 AS `size`, + 1 AS `workerCode`, + 1 AS `repoCode`, + 1 AS `parking`, + 1 AS `sectorFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `itemPlacementSupplyList__` +-- + +DROP TABLE IF EXISTS `itemPlacementSupplyList__`; +/*!50001 DROP VIEW IF EXISTS `itemPlacementSupplyList__`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemPlacementSupplyList__` AS SELECT + 1 AS `id`, + 1 AS `itemFk`, + 1 AS `quantity`, + 1 AS `priority`, + 1 AS `created`, + 1 AS `userFk`, + 1 AS `repoUserFk`, + 1 AS `saldo`, + 1 AS `longName`, + 1 AS `subName`, + 1 AS `size`, + 1 AS `workerCode`, + 1 AS `repoCode`, + 1 AS `parking`, + 1 AS `sectorFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `itemRepo` +-- + +DROP TABLE IF EXISTS `itemRepo`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemRepo` ( + `itemFk` int(11) NOT NULL, + `quantity` int(10) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`itemFk`), + CONSTRAINT `itemRepo_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `itemShelving` +-- + +DROP TABLE IF EXISTS `itemShelving`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemShelving` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `itemFk` int(11) NOT NULL, + `shelvingFk` varchar(10) CHARACTER SET utf8 NOT NULL, + `shelve` varchar(2) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'A', + `deep` int(11) unsigned NOT NULL DEFAULT '1', + `quantity` decimal(10,0) NOT NULL DEFAULT '0', + `visible` decimal(10,0) NOT NULL DEFAULT '0', + `available` decimal(10,0) NOT NULL DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `priority` int(11) unsigned DEFAULT NULL COMMENT 'El 0 es la mínima prioridad', + `grouping` smallint(5) unsigned DEFAULT NULL, + `packing` int(11) unsigned DEFAULT NULL, + `packagingFk` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `level` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', + `userFk` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `itemShelving_fk1_idx` (`itemFk`), + KEY `itemShelving_fk2_idx` (`shelvingFk`), + KEY `itemShelving_fk3_idx` (`packagingFk`), + KEY `itemShelving_fk3_idx1` (`userFk`), + CONSTRAINT `itemShelving_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemShelving_fk2` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemShelving_fk3` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=151395 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla utilizada para localizar los artículos dentro de los carros. Usado para la gestión del almacén en el altillo '; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemShelving_BEFORE_INSERT` BEFORE INSERT ON `itemShelving` FOR EACH ROW +BEGIN + + SET NEW.userFk = account.userGetId(); + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`z-developer`@`%`*/ /*!50003 TRIGGER `vn`.`itemShelving_BEFORE_UPDATE` BEFORE UPDATE ON `itemShelving` FOR EACH ROW +BEGIN + + SET NEW.userFk = account.userGetId(); + +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 */ ; + +-- +-- Temporary view structure for view `itemShelvingAvailable` +-- + +DROP TABLE IF EXISTS `itemShelvingAvailable`; +/*!50001 DROP VIEW IF EXISTS `itemShelvingAvailable`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemShelvingAvailable` AS SELECT + 1 AS `saleFk`, + 1 AS `Modificado`, + 1 AS `ticketFk`, + 1 AS `isPicked`, + 1 AS `itemFk`, + 1 AS `quantity`, + 1 AS `concept`, + 1 AS `size`, + 1 AS `Estado`, + 1 AS `sectorProdPriority`, + 1 AS `available`, + 1 AS `sectorFk`, + 1 AS `matricula`, + 1 AS `parking`, + 1 AS `itemShelving`, + 1 AS `Agency`, + 1 AS `shipped`, + 1 AS `grouping`, + 1 AS `packing`, + 1 AS `hour`, + 1 AS `isPreviousPreparable`, + 1 AS `physicalVolume`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `itemShelvingList` +-- + +DROP TABLE IF EXISTS `itemShelvingList`; +/*!50001 DROP VIEW IF EXISTS `itemShelvingList`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemShelvingList` AS SELECT + 1 AS `shelvingFk`, + 1 AS `visible`, + 1 AS `created`, + 1 AS `parking`, + 1 AS `itemFk`, + 1 AS `longName`, + 1 AS `size`, + 1 AS `subName`, + 1 AS `parked`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `itemShelvingPlacementSupply` +-- + +DROP TABLE IF EXISTS `itemShelvingPlacementSupply`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemShelvingPlacementSupply` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `itemShelvingFk` int(10) unsigned NOT NULL, + `itemPlacementSupplyFk` int(10) unsigned NOT NULL, + `quantity` decimal(10,0) NOT NULL DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `userFk` int(10) unsigned NOT NULL, + `isPicked` tinyint(4) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `itemShelvingPlacementSupply_fk1_idx` (`itemShelvingFk`), + KEY `itemShelvingPlacementSupply_fk2_idx` (`itemPlacementSupplyFk`), + KEY `itemShelvingPlacementSupply_fk3_idx` (`userFk`), + CONSTRAINT `itemShelvingPlacementSupply_fk1` FOREIGN KEY (`itemShelvingFk`) REFERENCES `itemShelving` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemShelvingPlacementSupply_fk2` FOREIGN KEY (`itemPlacementSupplyFk`) REFERENCES `itemPlacementSupply` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=81650 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalle de los itemShelving afectados por las ordenes de reposicion de nicho'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `itemShelvingPlacementSupplyStock` +-- + +DROP TABLE IF EXISTS `itemShelvingPlacementSupplyStock`; +/*!50001 DROP VIEW IF EXISTS `itemShelvingPlacementSupplyStock`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemShelvingPlacementSupplyStock` AS SELECT + 1 AS `itemShelvingFk`, + 1 AS `itemFk`, + 1 AS `quantity`, + 1 AS `packing`, + 1 AS `stock`, + 1 AS `longName`, + 1 AS `size`, + 1 AS `subName`, + 1 AS `shelving`, + 1 AS `parking`, + 1 AS `created`, + 1 AS `priority`, + 1 AS `parkingFk`, + 1 AS `sectorFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `itemShelvingPlacementSupplyStock__` +-- + +DROP TABLE IF EXISTS `itemShelvingPlacementSupplyStock__`; +/*!50001 DROP VIEW IF EXISTS `itemShelvingPlacementSupplyStock__`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemShelvingPlacementSupplyStock__` AS SELECT + 1 AS `itemShelvingFk`, + 1 AS `itemFk`, + 1 AS `quantity`, + 1 AS `packing`, + 1 AS `stock`, + 1 AS `longName`, + 1 AS `size`, + 1 AS `subName`, + 1 AS `shelving`, + 1 AS `parking`, + 1 AS `created`, + 1 AS `priority`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `itemShelvingSale` +-- + +DROP TABLE IF EXISTS `itemShelvingSale`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemShelvingSale` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `itemShelvingFk` int(10) unsigned NOT NULL, + `saleFk` int(11) NOT NULL, + `quantity` decimal(10,0) NOT NULL DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `userFk` int(11) unsigned NOT NULL, + PRIMARY KEY (`id`), + KEY `itemShelvingSale_fk1_idx` (`itemShelvingFk`), + KEY `itemShelvingSale_fk2_idx` (`saleFk`), + KEY `itemShelvingSale_fk3_idx` (`userFk`), + CONSTRAINT `itemShelvingSale_fk1` FOREIGN KEY (`itemShelvingFk`) REFERENCES `itemShelving` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemShelvingSale_fk2` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemShelvingSale_fk3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=56499 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalle del producto que se retira de los carros, relacionando la linea de movimiento correspondiente'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemShelvingSale_AFTER_INSERT` AFTER INSERT ON `itemShelvingSale` FOR EACH ROW +BEGIN + + UPDATE vn.sale + SET isPicked = TRUE + WHERE id = NEW.saleFk; + +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 */ ; + +-- +-- Temporary view structure for view `itemShelvingSaleSum` +-- + +DROP TABLE IF EXISTS `itemShelvingSaleSum`; +/*!50001 DROP VIEW IF EXISTS `itemShelvingSaleSum`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemShelvingSaleSum` AS SELECT + 1 AS `id`, + 1 AS `itemShelvingFk`, + 1 AS `saleFk`, + 1 AS `quantity`, + 1 AS `created`, + 1 AS `sectorFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `itemShelvingStock` +-- + +DROP TABLE IF EXISTS `itemShelvingStock`; +/*!50001 DROP VIEW IF EXISTS `itemShelvingStock`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemShelvingStock` AS SELECT + 1 AS `itemFk`, + 1 AS `visible`, + 1 AS `packing`, + 1 AS `grouping`, + 1 AS `sector`, + 1 AS `visibleOriginal`, + 1 AS `removed`, + 1 AS `sectorFk`, + 1 AS `warehouseFk`, + 1 AS `shelvingFk`, + 1 AS `parkingCode`, + 1 AS `parkingFk`, + 1 AS `itemShelvingFk`, + 1 AS `created`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `itemShelvingStockFull` +-- + +DROP TABLE IF EXISTS `itemShelvingStockFull`; +/*!50001 DROP VIEW IF EXISTS `itemShelvingStockFull`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemShelvingStockFull` AS SELECT + 1 AS `itemFk`, + 1 AS `quantity`, + 1 AS `packing`, + 1 AS `grouping`, + 1 AS `sector`, + 1 AS `removed`, + 1 AS `sectorFk`, + 1 AS `warehouseFk`, + 1 AS `shelvingFk`, + 1 AS `parkingCode`, + 1 AS `parkingFk`, + 1 AS `itemShelvingFk`, + 1 AS `created`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `itemShelvingStockRemoved` +-- + +DROP TABLE IF EXISTS `itemShelvingStockRemoved`; +/*!50001 DROP VIEW IF EXISTS `itemShelvingStockRemoved`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemShelvingStockRemoved` AS SELECT + 1 AS `itemShelvingFk`, + 1 AS `itemFk`, + 1 AS `removed`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `itemTag` +-- + +DROP TABLE IF EXISTS `itemTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemTag` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `itemFk` int(11) NOT NULL, + `tagFk` int(11) NOT NULL, + `value` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `intValue` int(11) DEFAULT NULL, + `priority` int(2) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `itemFk` (`itemFk`,`tagFk`,`value`) USING BTREE, + KEY `tagFk` (`tagFk`,`value`), + KEY `priorityItem` (`priority`,`itemFk`), + KEY `value` (`value`), + KEY `itemFk_2` (`itemFk`,`tagFk`,`intValue`), + CONSTRAINT `itemTagItemFk` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemTagTagFk` FOREIGN KEY (`tagFk`) REFERENCES `tag` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=1428016 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemTag_beforeInsert` + BEFORE INSERT ON `itemTag` FOR EACH ROW +BEGIN + SET NEW.intValue = itemTag_getIntValue(NEW.`value`); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemTag_AFTER_INSERT` AFTER INSERT ON `itemTag` FOR EACH ROW +trig: BEGIN + IF @isTriggerDisabled THEN + LEAVE trig; + END IF; + + CALL vn.itemRefreshTags(NEW.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_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemTag_beforeUpdate` + BEFORE UPDATE ON `itemTag` FOR EACH ROW +BEGIN + IF !(OLD.`value` <=> NEW.`value`) + OR !(OLD.intValue <=> NEW.intValue) THEN + SET NEW.intValue = itemTag_getIntValue(NEW.`value`); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemTag_afterUpdate` + AFTER UPDATE ON `itemTag` FOR EACH ROW +trig: BEGIN + IF @isTriggerDisabled THEN + LEAVE trig; + END IF; + + CALL vn.itemRefreshTags(NEW.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_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemTag_afterDelete` + AFTER DELETE ON `itemTag` FOR EACH ROW +trig: BEGIN + IF @isTriggerDisabled THEN + LEAVE trig; + END IF; + + CALL vn.itemRefreshTags(OLD.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 */ ; + +-- +-- Temporary view structure for view `itemTagged` +-- + +DROP TABLE IF EXISTS `itemTagged`; +/*!50001 DROP VIEW IF EXISTS `itemTagged`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemTagged` AS SELECT + 1 AS `itemFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `itemTaxCountry` +-- + +DROP TABLE IF EXISTS `itemTaxCountry`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemTaxCountry` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `itemFk` int(11) DEFAULT NULL, + `countryFk` mediumint(8) unsigned DEFAULT NULL, + `taxClassFk` tinyint(3) unsigned NOT NULL DEFAULT '1', + `effectived` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `itemFk_UNIQUE` (`itemFk`,`countryFk`), + KEY `taxClassFK_idx` (`taxClassFk`), + KEY `countryFK_paises_idx` (`countryFk`), + CONSTRAINT `countryFK_paises` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE, + CONSTRAINT `itemFK_Article` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `taxClassFK_Iva_Group` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=911122 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Define la clase de iva por artículo y pais'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `itemTicketOut` +-- + +DROP TABLE IF EXISTS `itemTicketOut`; +/*!50001 DROP VIEW IF EXISTS `itemTicketOut`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemTicketOut` AS SELECT + 1 AS `warehouseFk`, + 1 AS `shipped`, + 1 AS `itemFk`, + 1 AS `quantity`, + 1 AS `isPicked`, + 1 AS `reserved`, + 1 AS `refFk`, + 1 AS `saleFk`, + 1 AS `ticketFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `itemType` +-- + +DROP TABLE IF EXISTS `itemType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemType` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `order` int(11) DEFAULT '0', + `temperature` tinyint(1) unsigned NOT NULL DEFAULT '0', + `categoryFk` int(10) unsigned NOT NULL, + `workerFk` int(11) NOT NULL, + `isInventory` tinyint(4) NOT NULL DEFAULT '1' COMMENT 'Se utiliza tanto en el cálculo del inventario, como en el del informe del inventario valorado', + `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `f11` tinyint(4) NOT NULL DEFAULT '0', + `father` smallint(5) DEFAULT NULL, + `transaction` tinyint(4) NOT NULL DEFAULT '0', + `making` int(10) unsigned DEFAULT NULL, + `location` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `life` smallint(5) unsigned DEFAULT NULL, + `maneuver` double NOT NULL DEFAULT '0.21', + `target` double NOT NULL DEFAULT '0.15', + `topMargin` double NOT NULL DEFAULT '0.3', + `profit` double NOT NULL DEFAULT '0.02', + `isFV` tinyint(3) DEFAULT '1', + `density` double NOT NULL DEFAULT '167' COMMENT 'Almacena el valor por defecto de la densidad en kg/m3 para el calculo de los portes aereos, en articulos se guarda la correcta', + `promo` double NOT NULL DEFAULT '0', + `isBox` tinyint(4) NOT NULL DEFAULT '0', + `CYM` int(11) NOT NULL DEFAULT '0', + `isPackaging` tinyint(1) NOT NULL DEFAULT '0', + `hasComponents` tinyint(1) NOT NULL DEFAULT '1', + `roleCodeFk` varchar(14) COLLATE utf8_unicode_ci DEFAULT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`code`), + UNIQUE KEY `tipo_id_UNIQUE` (`id`), + UNIQUE KEY `Tipo_UNIQUE` (`name`,`categoryFk`), + KEY `Trabajador` (`workerFk`), + KEY `reino_id` (`categoryFk`), + KEY `Tipos_fk3_idx` (`making`), + KEY `tipos_fk4_idx` (`roleCodeFk`), + KEY `warehouseFk5_idx` (`warehouseFk`), + CONSTRAINT `Tipos_fk3` FOREIGN KEY (`making`) REFERENCES `confectionType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `Trabajador` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `itemType_ibfk_1` FOREIGN KEY (`categoryFk`) REFERENCES `itemCategory` (`id`) ON UPDATE CASCADE, + CONSTRAINT `itemType_ibfk_2` FOREIGN KEY (`roleCodeFk`) REFERENCES `account`.`role` (`name`) ON UPDATE CASCADE, + CONSTRAINT `warehouseFk5` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=286 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Protege la tabla tipos de updates para los 4 parámetros de los compradores, en funcion del valor del campo CodigoRojo de tblContadores.'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`itemType_beforeUpdate` BEFORE UPDATE ON `itemType` FOR EACH ROW +-- Edit trigger body code below this line. Do not edit lines above this one +BEGIN + /* + Jgallego 12-08-2019 + + DECLARE strCOD VARCHAR(40); + + SELECT redCode INTO strCOD FROM config LIMIT 1; + IF strCOD <> 'tipos' + THEN + SET NEW.maneuver = OLD.maneuver ; + SET NEW.target = OLD.target ; + SET NEW.top_margin = OLD.top_margin ; + SET NEW.profit = OLD.profit ; + END IF;*/ +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `itemTypeI18n` +-- + +DROP TABLE IF EXISTS `itemTypeI18n`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemTypeI18n` ( + `typeFk` smallint(5) unsigned NOT NULL, + `lang` char(2) CHARACTER SET utf8 NOT NULL, + `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`typeFk`,`lang`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `itemTypeL10n` +-- + +DROP TABLE IF EXISTS `itemTypeL10n`; +/*!50001 DROP VIEW IF EXISTS `itemTypeL10n`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `itemTypeL10n` AS SELECT + 1 AS `id`, + 1 AS `name`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `itemTypeTag` +-- + +DROP TABLE IF EXISTS `itemTypeTag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemTypeTag` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `itemTypeFk` smallint(5) unsigned NOT NULL, + `tagFk` int(11) NOT NULL, + `priority` int(2) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `itemTypeFk_UNIQUE` (`itemTypeFk`,`tagFk`), + KEY `itemTypeTagTipo_idx` (`itemTypeFk`), + KEY `itemTypeTagTag_idx` (`tagFk`), + CONSTRAINT `itemTypeTagTag` FOREIGN KEY (`tagFk`) REFERENCES `tag` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `itemTypeTagTipos` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=250 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `itemVerdecora` +-- + +DROP TABLE IF EXISTS `itemVerdecora`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `itemVerdecora` ( + `itemFk` int(11) NOT NULL, + `codin` int(11) DEFAULT NULL, + PRIMARY KEY (`itemFk`), + CONSTRAINT `itemVerdecora_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Relaciona nuestros articulos con los de Verdecora'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `labourTree` +-- + +DROP TABLE IF EXISTS `labourTree`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `labourTree` ( + `id` int(11) NOT NULL DEFAULT '0', + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `lft` int(11) NOT NULL, + `rgt` int(11) NOT NULL, + `depth` bigint(22) NOT NULL DEFAULT '0', + `sons` decimal(10,0) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ledgerConfig` +-- + +DROP TABLE IF EXISTS `ledgerConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ledgerConfig` ( + `lastBookEntry` int(11) NOT NULL, + PRIMARY KEY (`lastBookEntry`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `mail` +-- + +DROP TABLE IF EXISTS `mail`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mail` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `sender` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `replyTo` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `subject` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `body` text COLLATE utf8_unicode_ci NOT NULL, + `sent` tinyint(2) NOT NULL DEFAULT '0', + `creationDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `attachment` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `status` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'OK', + `senderFk` int(11) DEFAULT NULL, + `recipientFk` int(11) DEFAULT NULL, + `plainTextBody` text COLLATE utf8_unicode_ci, + PRIMARY KEY (`id`), + KEY `sent_idx` (`sent`), + KEY `creation_idx` (`creationDate`) +) ENGINE=InnoDB AUTO_INCREMENT=1969292 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `mailTemplates` +-- + +DROP TABLE IF EXISTS `mailTemplates`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mailTemplates` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(50) CHARACTER SET utf8 NOT NULL, + `attachmentPath` text CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `mandate` +-- + +DROP TABLE IF EXISTS `mandate`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mandate` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `clientFk` int(11) NOT NULL, + `companyFk` smallint(5) unsigned NOT NULL, + `code` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL, + `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `finished` timestamp NULL DEFAULT NULL, + `mandateTypeFk` smallint(5) NOT NULL, + PRIMARY KEY (`id`), + KEY `mandato_fgkey1_idx` (`clientFk`), + KEY `mandato_fgkey2_idx` (`companyFk`), + KEY `mandato_fgkey3_idx` (`mandateTypeFk`), + CONSTRAINT `mandato_fgkey1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `mandato_fgkey2` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `mandato_fgkey3` FOREIGN KEY (`mandateTypeFk`) REFERENCES `mandateType` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=17348 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`mandate_beforeInsert` + BEFORE INSERT ON `mandate` + FOR EACH ROW +BEGIN + IF (NEW.code IS NULL) THEN + SET NEW.code=CONCAT(NEW.clientFk,'-',(SELECT AUTO_INCREMENT + FROM information_schema.TABLES + WHERE TABLE_SCHEMA='vn' and TABLE_NAME='mandate')); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `mandateType` +-- + +DROP TABLE IF EXISTS `mandateType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mandateType` ( + `id` smallint(5) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `manuscript` +-- + +DROP TABLE IF EXISTS `manuscript`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `manuscript` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `code` varchar(45) CHARACTER SET utf8 NOT NULL, + `description` text COLLATE utf8_unicode_ci, + `enabled` tinyint(1) NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `code_UNIQUE` (`code`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `medicalCenter` +-- + +DROP TABLE IF EXISTS `medicalCenter`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `medicalCenter` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `medicalReview` +-- + +DROP TABLE IF EXISTS `medicalReview`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `medicalReview` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `workerFk` int(11) NOT NULL, + `centerFk` int(11) NOT NULL, + `date` date DEFAULT NULL, + `time` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, + `isFit` tinyint(1) DEFAULT NULL, + `amount` double DEFAULT NULL, + `invoice` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `remark` longtext COLLATE utf8_unicode_ci, + PRIMARY KEY (`id`), + KEY `frgcenter_idx` (`centerFk`), + KEY `frgnkWorker_idx` (`workerFk`), + CONSTRAINT `frgcenter` FOREIGN KEY (`centerFk`) REFERENCES `medicalCenter` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `frgnkWorker` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=369 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `message` +-- + +DROP TABLE IF EXISTS `message`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `message` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `uuid` varchar(50) CHARACTER SET utf8 NOT NULL, + `sender` varchar(50) CHARACTER SET utf8 NOT NULL, + `recipient` varchar(50) CHARACTER SET utf8 NOT NULL, + `message` longtext CHARACTER SET utf8, + `sendDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `sender` (`sender`), + KEY `recipient` (`recipient`), + KEY `uuid` (`uuid`(8)) +) ENGINE=InnoDB AUTO_INCREMENT=2077647 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `messageInbox` +-- + +DROP TABLE IF EXISTS `messageInbox`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `messageInbox` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `uuid` varchar(50) CHARACTER SET utf8 NOT NULL, + `sender` varchar(50) CHARACTER SET utf8 NOT NULL, + `recipient` varchar(45) CHARACTER SET utf8 NOT NULL, + `finalRecipient` varchar(50) CHARACTER SET utf8 NOT NULL, + `message` longtext CHARACTER SET utf8, + `sendDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `read` varchar(45) CHARACTER SET utf8 NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `uuid` (`uuid`(8)), + KEY `finalRecipient` (`finalRecipient`) +) ENGINE=InnoDB AUTO_INCREMENT=2254338 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `mobileAppVersionControl` +-- + +DROP TABLE IF EXISTS `mobileAppVersionControl`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `mobileAppVersionControl` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `appName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `version` int(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla para llevar el control de las Versions de las aplicaciones móvil '; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `noticeCategory` +-- + +DROP TABLE IF EXISTS `noticeCategory`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `noticeCategory` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `keyName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `subject` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `description` text COLLATE utf8_unicode_ci, + `isEnabled` tinyint(1) NOT NULL DEFAULT '1', + `requiredRole` int(11) NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `keyName_UNIQUE` (`keyName`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `noticeSubscription` +-- + +DROP TABLE IF EXISTS `noticeSubscription`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `noticeSubscription` ( + `noticeCategoryFk` int(11) NOT NULL DEFAULT '0', + `userFk` int(10) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`noticeCategoryFk`,`userFk`), + KEY `noticeSubscription_ibfk_2` (`userFk`), + CONSTRAINT `noticeSubscription_ibfk_1` FOREIGN KEY (`noticeCategoryFk`) REFERENCES `noticeCategory` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `noticeSubscription_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `observationType` +-- + +DROP TABLE IF EXISTS `observationType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `observationType` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `description` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `orderTicket` +-- + +DROP TABLE IF EXISTS `orderTicket`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `orderTicket` ( + `orderFk` int(10) unsigned NOT NULL, + `ticketFk` int(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`ticketFk`,`orderFk`), + KEY `order_id` (`orderFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `origin` +-- + +DROP TABLE IF EXISTS `origin`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `origin` ( + `id` tinyint(2) unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + `warehouseFk` smallint(5) unsigned DEFAULT '4', + `flag` blob, + `nl` tinyint(4) NOT NULL DEFAULT '0', + `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `Abreviatura` (`code`), + KEY `warehouse_id` (`warehouseFk`), + KEY `Id_Paises` (`countryFk`), + CONSTRAINT `origin_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=60 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `originI18n` +-- + +DROP TABLE IF EXISTS `originI18n`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `originI18n` ( + `originFk` tinyint(2) unsigned NOT NULL, + `lang` char(2) CHARACTER SET utf8 NOT NULL, + `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`originFk`,`lang`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `originL10n` +-- + +DROP TABLE IF EXISTS `originL10n`; +/*!50001 DROP VIEW IF EXISTS `originL10n`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `originL10n` AS SELECT + 1 AS `id`, + 1 AS `name`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `outgoingInvoiceVat` +-- + +DROP TABLE IF EXISTS `outgoingInvoiceVat`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `outgoingInvoiceVat` ( + `outgoingInvoice` mediumint(8) NOT NULL, + `taxBase` decimal(12,2) DEFAULT NULL, + `equalizationTax` decimal(12,2) DEFAULT NULL, + `Vat` decimal(12,2) DEFAULT NULL, + PRIMARY KEY (`outgoingInvoice`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `packageChecked` +-- + +DROP TABLE IF EXISTS `packageChecked`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `packageChecked` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `itemFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `entryFk_UNIQUE` (`itemFk`), + KEY `fkItem_idx` (`itemFk`) +) ENGINE=InnoDB AUTO_INCREMENT=3438 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `packageEquivalent` +-- + +DROP TABLE IF EXISTS `packageEquivalent`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `packageEquivalent` ( + `packageFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `equivalentFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`packageFk`,`equivalentFk`), + KEY `packageEquivalent_fk2_idx` (`equivalentFk`), + CONSTRAINT `packageEquivalent_fk1` FOREIGN KEY (`packageFk`) REFERENCES `packaging` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `packageEquivalent_fk2` FOREIGN KEY (`equivalentFk`) REFERENCES `packaging` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='recoge los modelos de cubos que se han de sustituir a efectos de presentar informes resumidos'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `packageEquivalentItem` +-- + +DROP TABLE IF EXISTS `packageEquivalentItem`; +/*!50001 DROP VIEW IF EXISTS `packageEquivalentItem`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `packageEquivalentItem` AS SELECT + 1 AS `itemFk`, + 1 AS `equivalentFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `packaging` +-- + +DROP TABLE IF EXISTS `packaging`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `packaging` ( + `id` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `volume` decimal(10,2) DEFAULT '0.00', + `width` decimal(10,2) DEFAULT '0.00', + `depth` decimal(10,2) DEFAULT '0.00', + `height` decimal(10,2) DEFAULT '0.00', + `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, + `packagingReturnFk` int(11) DEFAULT NULL, + `lower` int(11) DEFAULT NULL, + `upload` int(11) DEFAULT NULL, + `base` decimal(10,2) DEFAULT NULL, + `itemFk` int(11) DEFAULT NULL, + `price` decimal(10,2) NOT NULL, + `isBox` tinyint(1) NOT NULL DEFAULT '0', + `cubicPackage` decimal(10,2) DEFAULT NULL, + `returnCost` decimal(10,2) NOT NULL DEFAULT '0.00', + `cmrName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `Article` (`itemFk`), + CONSTRAINT `Article` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `parking` +-- + +DROP TABLE IF EXISTS `parking`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `parking` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `column` varchar(5) CHARACTER SET utf8 NOT NULL DEFAULT '--', + `row` varchar(5) CHARACTER SET utf8 NOT NULL DEFAULT '--', + `sectorFk` int(11) NOT NULL DEFAULT '2', + `code` varchar(8) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `column_UNIQUE` (`column`,`row`), + UNIQUE KEY `code_UNIQUE` (`code`), + KEY `parking_fk1_idx` (`sectorFk`), + CONSTRAINT `parking_fk1` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=27886 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla con los parkings del altillo'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`parking_BEFORE_INSERT` BEFORE INSERT ON `parking` FOR EACH ROW +BEGIN + + -- SET new.`code` = CONCAT(new.`column`,' - ',new.`row`) ; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`parking_BEFORE_UPDATE` BEFORE UPDATE ON `parking` FOR EACH ROW +BEGIN + + -- SET new.`code` = CONCAT(new.`column`,' - ',new.`row`) ; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `payDem` +-- + +DROP TABLE IF EXISTS `payDem`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `payDem` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `payDem` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `payMethod` +-- + +DROP TABLE IF EXISTS `payMethod`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `payMethod` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + `solution` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, + `outstandingDebt` tinyint(3) unsigned zerofill NOT NULL DEFAULT '000', + `graceDays` int(11) unsigned NOT NULL DEFAULT '0', + `ibanRequired` tinyint(3) DEFAULT '0', + `isNotified` tinyint(3) NOT NULL DEFAULT '1', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `pedidosInternos` +-- + +DROP TABLE IF EXISTS `pedidosInternos`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `pedidosInternos` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `idArticle` int(11) DEFAULT NULL, + `quantity` int(11) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=54 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `person` +-- + +DROP TABLE IF EXISTS `person`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `person` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `firstname` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `surnames` varchar(60) COLLATE utf8_unicode_ci NOT NULL, + `fi` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `birth` date DEFAULT NULL, + `readerId` int(11) DEFAULT NULL, + `workerFk` int(11) DEFAULT NULL, + `isDisable` tinyint(1) NOT NULL DEFAULT '0', + `isFreelance` tinyint(1) NOT NULL DEFAULT '0', + `isSsDiscounted` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `nif` (`fi`), + KEY `nifIndex` (`fi`), + KEY `workerFk_idx` (`workerFk`), + CONSTRAINT `Person_ibfk_1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=818 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `personMedia` +-- + +DROP TABLE IF EXISTS `personMedia`; +/*!50001 DROP VIEW IF EXISTS `personMedia`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `personMedia` AS SELECT + 1 AS `workerFk`, + 1 AS `mediaValue`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `pgc` +-- + +DROP TABLE IF EXISTS `pgc`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `pgc` ( + `code` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `rate` decimal(10,2) NOT NULL, + `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `cplusTaxBreakFk` int(10) unsigned DEFAULT '1', + `mod340` tinyint(1) NOT NULL DEFAULT '0', + `mod347` tinyint(1) NOT NULL DEFAULT '0', + `cplusTrascendency477Fk` int(10) unsigned DEFAULT '1', + PRIMARY KEY (`code`), + KEY `pgc_fk1_idx` (`cplusTaxBreakFk`), + KEY `pgc_fk2_idx` (`cplusTrascendency477Fk`), + CONSTRAINT `pgc_fk1` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE, + CONSTRAINT `pgc_fk2` FOREIGN KEY (`cplusTrascendency477Fk`) REFERENCES `cplusTrascendency477` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Plan General Contable'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `pgcEqu` +-- + +DROP TABLE IF EXISTS `pgcEqu`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `pgcEqu` ( + `vatFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Cuenta de IVA', + `equFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Cuenta de recargo de equivalencia', + PRIMARY KEY (`vatFk`,`equFk`), + KEY `pgcEqu_fk2_idx` (`equFk`), + CONSTRAINT `pgcEqu_fk1` FOREIGN KEY (`vatFk`) REFERENCES `pgc` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `pgcEqu_fk2` FOREIGN KEY (`equFk`) REFERENCES `pgc` (`code`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Recoge las cuentas contables con recargo de equivalencia e identifica a la que corresponde al iva y la que corresponde al recargo'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `postCode` +-- + +DROP TABLE IF EXISTS `postCode`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `postCode` ( + `code` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `townFk` int(11) NOT NULL, + `geoFk` int(11) DEFAULT NULL, + PRIMARY KEY (`code`,`townFk`), + KEY `postCodeTownFk_idx` (`townFk`), + CONSTRAINT `postCodeTownFk` FOREIGN KEY (`townFk`) REFERENCES `town` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`postCode_beforeInsert` + BEFORE INSERT ON `postCode` FOR EACH ROW +BEGIN + SET NEW.geoFk = zoneGeo_new('postCode', NEW.`code`, + (SELECT geoFk FROM town WHERE id = NEW.townFk)); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `postCode_beforeUpdate` + BEFORE UPDATE ON `postCode` FOR EACH ROW +BEGIN + IF !(OLD.geoFk <=> NEW.geoFk) THEN + CALL zoneGeo_throwNotEditable; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`postCode_afterUpdate` + AFTER UPDATE ON `postCode` FOR EACH ROW +BEGIN + IF !(OLD.townFk <=> NEW.townFk) THEN + CALL zoneGeo_setParent(NEW.geoFk, + (SELECT geoFk FROM town WHERE id = NEW.townFk)); + END IF; + + IF !(OLD.`code` <=> NEW.`code`) THEN + UPDATE zoneGeo SET `name` = NEW.`code` + WHERE id = NEW.geoFk; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`postCode_afterDelete` + AFTER DELETE ON `postCode` FOR EACH ROW +BEGIN + CALL zoneGeo_delete(OLD.geoFk); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `postCodeBack__` +-- + +DROP TABLE IF EXISTS `postCodeBack__`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `postCodeBack__` ( + `code` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `townFk` int(11) NOT NULL, + `geoFk` int(11) DEFAULT NULL, + PRIMARY KEY (`code`,`townFk`), + KEY `postCodeTownFk_idx2` (`townFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `priceBuilderTag__` +-- + +DROP TABLE IF EXISTS `priceBuilderTag__`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `priceBuilderTag__` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `priceBuilderFk` int(11) NOT NULL, + `tagFk` int(11) NOT NULL, + `value` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `priceBuilderTag_fk1_idx` (`priceBuilderFk`), + KEY `priceBuilderTag_fk2_idx` (`tagFk`), + CONSTRAINT `priceBuilderTag_fk1` FOREIGN KEY (`priceBuilderFk`) REFERENCES `priceBuilder__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `priceBuilderTag_fk2` FOREIGN KEY (`tagFk`) REFERENCES `tag` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `priceBuilderWarehouse__` +-- + +DROP TABLE IF EXISTS `priceBuilderWarehouse__`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `priceBuilderWarehouse__` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `warehouseFk` smallint(6) unsigned NOT NULL, + `priceBuilderFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `priceBuilderWarehouse_fk1_idx` (`warehouseFk`), + KEY `priceBuilderWarehouse_fk2_idx` (`priceBuilderFk`), + CONSTRAINT `priceBuilderWarehouse_fk1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `priceBuilderWarehouse_fk2` FOREIGN KEY (`priceBuilderFk`) REFERENCES `priceBuilder__` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `priceBuilder__` +-- + +DROP TABLE IF EXISTS `priceBuilder__`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `priceBuilder__` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `itemTypeFk` smallint(5) unsigned NOT NULL COMMENT 'Sirve para definir precios en tarifa2 para grupos de items', + `started` date DEFAULT NULL, + `finished` date DEFAULT NULL, + `price` decimal(10,3) NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `priceBuilder_fk1_idx` (`itemTypeFk`), + KEY `priceBuilder_fk2_idx` (`userFk`), + CONSTRAINT `priceBuilder_fk1` FOREIGN KEY (`itemTypeFk`) REFERENCES `itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `priceBuilder_fk2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `priceFixed` +-- + +DROP TABLE IF EXISTS `priceFixed`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `priceFixed` ( + `itemFk` int(10) NOT NULL, + `rate0` double NOT NULL, + `rate1` double NOT NULL, + `rate2` double NOT NULL, + `rate3` double NOT NULL, + `started` date NOT NULL, + `ended` date NOT NULL, + `bonus` double NOT NULL DEFAULT '0', + `warehouseFk` smallint(5) unsigned NOT NULL DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `id` int(11) NOT NULL AUTO_INCREMENT, + `grouping` smallint(5) DEFAULT NULL, + `packing` int(11) DEFAULT NULL, + `box` tinyint(4) DEFAULT NULL, + PRIMARY KEY (`itemFk`,`started`,`ended`,`warehouseFk`), + UNIQUE KEY `price_fixed_id_UNIQUE` (`id`), + KEY `item_id` (`itemFk`), + KEY `date_start` (`started`), + KEY `date_end` (`ended`), + KEY `warehouse_id` (`warehouseFk`), + CONSTRAINT `priceFixed_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=65157 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`priceFixed_beforeInsert` BEFORE INSERT ON `vn`.`priceFixed` + FOR EACH ROW + BEGIN + DECLARE vDated DATE; + IF NEW.started > NEW.ended THEN + SET vDated = NEW.started; + SET NEW.started = NEW.ended; + SET NEW.ended = vDated; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`priceFixed_beforeUpdate` BEFORE UPDATE ON `vn`.`priceFixed` + FOR EACH ROW +BEGIN + DECLARE vDated DATE; + IF NEW.started > NEW.ended THEN + SET vDated = NEW.started; + SET NEW.started = NEW.ended; + SET NEW.ended = vDated; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `printServerQueue` +-- + +DROP TABLE IF EXISTS `printServerQueue`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `printServerQueue` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `printerFk` tinyint(3) unsigned DEFAULT NULL, + `priorityFk` tinyint(3) unsigned DEFAULT NULL, + `reportFk` tinyint(3) unsigned DEFAULT '0', + `statusFk` tinyint(3) unsigned DEFAULT '1', + `started` datetime DEFAULT NULL, + `finished` datetime DEFAULT NULL, + `param1` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `workerFk` int(11) DEFAULT '20', + `param2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `param3` text COLLATE utf8_unicode_ci, + `error` text COLLATE utf8_unicode_ci, + PRIMARY KEY (`id`), + UNIQUE KEY `Id_Impresora_2` (`printerFk`,`priorityFk`,`reportFk`,`statusFk`,`param1`,`workerFk`,`param2`), + KEY `Id_estado` (`statusFk`), + KEY `Id_Impresora` (`printerFk`), + KEY `Id_Informe` (`reportFk`), + KEY `Id_Prioridad` (`priorityFk`), + KEY `Id_Trabajador` (`workerFk`), + CONSTRAINT `printServerQueue_ibfk_3` FOREIGN KEY (`priorityFk`) REFERENCES `queuePriority` (`id`) ON UPDATE CASCADE, + CONSTRAINT `printServerQueue_ibfk_4` FOREIGN KEY (`printerFk`) REFERENCES `vn2008`.`Impresoras` (`Id_Impresora`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=20465 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `printingQueueCheck` +-- + +DROP TABLE IF EXISTS `printingQueueCheck`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `printingQueueCheck` ( + `lastCount` int(11) unsigned NOT NULL DEFAULT '0', + `lastCheckSum` int(11) unsigned NOT NULL DEFAULT '0', + `isAlreadyNotified` tinyint(2) NOT NULL DEFAULT '0', + PRIMARY KEY (`lastCount`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Comprueba que el servidor de impresion no esta parado'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `producer` +-- + +DROP TABLE IF EXISTS `producer`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `producer` ( + `id` mediumint(3) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `isVisible` tinyint(1) NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=41633 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `professionalCategory` +-- + +DROP TABLE IF EXISTS `professionalCategory`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `professionalCategory` ( + `id` int(11) NOT NULL, + `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `salary` decimal(10,2) DEFAULT NULL, + `salaryorSeniority` decimal(10,2) DEFAULT NULL, + `year` int(2) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `profile` +-- + +DROP TABLE IF EXISTS `profile`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `profile` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `personFk` int(11) DEFAULT NULL, + `profileTypeFk` int(11) NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + KEY `personFk` (`personFk`), + KEY `profileTypeFk` (`profileTypeFk`), + CONSTRAINT `profile_ibfk_1` FOREIGN KEY (`personFk`) REFERENCES `person` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `profile_ibfk_2` FOREIGN KEY (`profileTypeFk`) REFERENCES `profileType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=697 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `profileType` +-- + +DROP TABLE IF EXISTS `profileType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `profileType` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `province` +-- + +DROP TABLE IF EXISTS `province`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `province` ( + `id` smallint(6) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(30) COLLATE utf8_unicode_ci 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, + `nstGeoFk` int(11) DEFAULT NULL, + `nstName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `geoFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `Paises_Id` (`countryFk`), + KEY `warehouse_Id` (`warehouseFk`), + KEY `provicne_zone_fk_idx` (`zoneFk`), + 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 `warehouse_Id` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=217 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`province_beforeInsert` + BEFORE INSERT ON `province` FOR EACH ROW +BEGIN + SET NEW.geoFk = zoneGeo_new('province', NEW.`name`, + (SELECT geoFk FROM country WHERE id = NEW.countryFk)); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`province_beforeUpdate` + BEFORE UPDATE ON `province` FOR EACH ROW +BEGIN + IF !(OLD.geoFk <=> NEW.geoFk) THEN + CALL zoneGeo_throwNotEditable; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` + AFTER UPDATE ON `province` FOR EACH ROW +BEGIN + IF !(OLD.countryFk <=> NEW.countryFk) THEN + CALL zoneGeo_setParent(NEW.geoFk, + (SELECT geoFk FROM country WHERE id = NEW.countryFk)); + END IF; + + IF !(OLD.`name` <=> NEW.`name`) THEN + UPDATE zoneGeo SET `name` = NEW.`name` + WHERE id = NEW.geoFk; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`province_afterDelete` + AFTER DELETE ON `province` FOR EACH ROW +BEGIN + CALL zoneGeo_delete(OLD.geoFk); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `punchState` +-- + +DROP TABLE IF EXISTS `punchState`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `punchState` ( + `workerFk` int(11) NOT NULL, + `state` tinyint(4) DEFAULT '0', + PRIMARY KEY (`workerFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Table for storing punches that have cars with errors'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `queuePriority` +-- + +DROP TABLE IF EXISTS `queuePriority`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `queuePriority` ( + `id` tinyint(3) unsigned NOT NULL DEFAULT '0', + `priority` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `rateConfig` +-- + +DROP TABLE IF EXISTS `rateConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `rateConfig` ( + `id` int(11) NOT NULL, + `rate0` int(11) DEFAULT NULL, + `rate1` int(11) DEFAULT NULL, + `rate2` int(11) DEFAULT NULL, + `rate3` int(11) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `receipt` +-- + +DROP TABLE IF EXISTS `receipt`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `receipt` ( + `Id` int(11) NOT NULL AUTO_INCREMENT, + `invoiceFk` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `amountPaid` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountUnpaid` decimal(10,2) NOT NULL DEFAULT '0.00', + `payed` datetime DEFAULT NULL, + `workerFk` int(11) DEFAULT NULL, + `bankFk` int(11) DEFAULT '0', + `clientFk` int(11) DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442', + `isConciliate` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0', + PRIMARY KEY (`Id`), + KEY `Id_Banco` (`bankFk`), + KEY `Id_Trabajador` (`workerFk`), + KEY `empresa_id` (`companyFk`), + KEY `clientDate` (`clientFk`,`payed`), + KEY `id_factura` (`invoiceFk`), + CONSTRAINT `receiptWorkerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `receipt_ibfk_1` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, + CONSTRAINT `receipt_ibfk_2` FOREIGN KEY (`bankFk`) REFERENCES `bank` (`id`) ON UPDATE CASCADE, + CONSTRAINT `recibo_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=616111 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`receipt_afterInsert` AFTER INSERT ON `receipt` FOR EACH ROW + CALL bi.customer_risk_update (NEW.clientFk, NEW.companyFk, -NEW.amountPaid) */;; +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`receipt_beforeUpdate` BEFORE UPDATE ON `receipt` FOR EACH ROW +BEGIN + CALL bi.customer_risk_update (OLD.clientFk, OLD.companyFk, OLD.amountPaid); + CALL bi.customer_risk_update (NEW.clientFk, NEW.companyFk, -NEW.amountPaid); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`receipt_beforeDelete` BEFORE DELETE ON `receipt` FOR EACH ROW + CALL bi.customer_risk_update (OLD.clientFk, OLD.companyFk, OLD.amountPaid) */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `recovery` +-- + +DROP TABLE IF EXISTS `recovery`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `recovery` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `clientFk` int(11) NOT NULL DEFAULT '0', + `started` date NOT NULL COMMENT 'Fecha a partir de la que comienza el recobro', + `finished` date DEFAULT NULL COMMENT 'Fecha en la que acaba', + `amount` double NOT NULL, + `period` tinyint(3) unsigned NOT NULL DEFAULT '7' COMMENT 'numero de dias que indica cada cuanto hare el recobro', + PRIMARY KEY (`id`), + KEY `cliente_idx` (`clientFk`), + CONSTRAINT `cliente333` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE, + CONSTRAINT `cliente_cliente` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=318 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='En esta tabla apuntaremos los acuerdos de recobro semanal a '; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `referenceCurrent` +-- + +DROP TABLE IF EXISTS `referenceCurrent`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `referenceCurrent` ( + `dated` date NOT NULL, + `value` decimal(10,4) NOT NULL, + `currencyFk` tinyint(3) unsigned NOT NULL, + PRIMARY KEY (`dated`,`currencyFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `referenceRate` +-- + +DROP TABLE IF EXISTS `referenceRate`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `referenceRate` ( + `currencyFk` tinyint(3) unsigned NOT NULL, + `dated` date NOT NULL, + `value` float unsigned NOT NULL, + PRIMARY KEY (`currencyFk`,`dated`), + KEY `date` (`dated`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `referenceRateConfig` +-- + +DROP TABLE IF EXISTS `referenceRateConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `referenceRateConfig` ( + `simulatedValue` float unsigned NOT NULL DEFAULT '1.2309', + PRIMARY KEY (`simulatedValue`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `role` +-- + +DROP TABLE IF EXISTS `role`; +/*!50001 DROP VIEW IF EXISTS `role`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `role` AS SELECT + 1 AS `id`, + 1 AS `name`, + 1 AS `description`, + 1 AS `hasLogin`*/; +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 */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `route` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `workerFk` int(11) DEFAULT NULL, + `created` date NOT NULL, + `vehicleFk` int(10) unsigned DEFAULT NULL, + `agencyModeFk` int(11) DEFAULT NULL, + `time` datetime DEFAULT NULL, + `isOk` tinyint(1) unsigned NOT NULL DEFAULT '0', + `kmStart` mediumint(9) NOT NULL, + `kmEnd` mediumint(9) NOT NULL, + `started` datetime NOT NULL, + `finished` datetime NOT NULL, + `gestdocFk` int(11) DEFAULT NULL, + `cost` double unsigned DEFAULT NULL, + `m3` decimal(10,1) unsigned DEFAULT NULL, + `description` text COLLATE utf8_unicode_ci, + PRIMARY KEY (`id`), + KEY `Id_Agencia` (`agencyModeFk`), + KEY `Fecha` (`created`), + KEY `gestdoc_id` (`gestdocFk`), + KEY `route_ibfk_2_idx` (`workerFk`), + CONSTRAINT `route_ibfk_1` FOREIGN KEY (`gestdocFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `route_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=61044 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`route_beforeUpdate` + BEFORE UPDATE ON `route` FOR EACH ROW +BEGIN + IF NEW.isOk <> FALSE AND OLD.isOk = FALSE THEN + SET NEW.m3 = ( SELECT SUM(litros)/1000 + FROM vn.saleVolume s + JOIN vn.ticket t ON s.ticketFk = t.id + WHERE t.routeFk = NEW.id); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`route_afterUpdate` + AFTER UPDATE ON `route` FOR EACH ROW +BEGIN + IF IFNULL(NEW.gestdocFk,0) <> IFNULL(OLD.gestdocFk,0) AND NEW.gestdocFk > 0 THEN + -- JGF 09/09/14 cuando se añade un gestdoc a una ruta, se le asigna automagicamente a todos sus Tickets + + -- Inserta el gestdoc en todos los tickets de la ruta + INSERT INTO ticketDms(ticketFk,dmsFk) + SELECT id, NEW.gestdocFk FROM ticket WHERE routeFk = NEW.id + ON DUPLICATE KEY UPDATE dmsFk = NEW.gestdocFk; + + -- Update del firmado + UPDATE ticket t + JOIN ticketDms tg ON t.id = tg.ticketFk + SET isSigned = 1 WHERE t.routeFk = NEW.id; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `routeAction` +-- + +DROP TABLE IF EXISTS `routeAction`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `routeAction` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `price` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `routeComplement` +-- + +DROP TABLE IF EXISTS `routeComplement`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `routeComplement` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `workerFk` int(11) NOT NULL, + `price` decimal(10,2) NOT NULL, + `routeActionFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `fgn_workerFk_idx` (`workerFk`), + KEY `fgn_routeActionFk_idx` (`routeActionFk`), + CONSTRAINT `fgn_routeActionFk` FOREIGN KEY (`routeActionFk`) REFERENCES `routeAction` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fgn_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=1136 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `routeGate` +-- + +DROP TABLE IF EXISTS `routeGate`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `routeGate` ( + `deviceId` varchar(30) CHARACTER SET utf8 NOT NULL, + `displayText` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `status` set('idle','doing','done','') CHARACTER SET utf8 DEFAULT 'idle', + `gateAreaFk` int(11) NOT NULL DEFAULT '1', + `routeFk` int(11) DEFAULT NULL, + `freeTickets` int(11) DEFAULT NULL, + `expeditions` int(11) DEFAULT NULL, + `scanned` int(11) DEFAULT NULL, + `flag` blob, + `pallets` int(11) DEFAULT NULL, + `lastScanned` datetime DEFAULT NULL, + `ready` tinyint(4) NOT NULL DEFAULT '0', + PRIMARY KEY (`deviceId`), + UNIQUE KEY `routeFk_UNIQUE` (`routeFk`), + KEY `routeGate_fk1_idx` (`gateAreaFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`routeGateBeforeUpdate` + BEFORE UPDATE ON `routeGate` + FOR EACH ROW +BEGIN + IF (NOT (NEW.expeditions <=> OLD.expeditions) + OR NOT (NEW.scanned <=> OLD.scanned)) + AND NEW.status <=> OLD.status + THEN + IF NEW.expeditions = 0 + THEN + SET NEW.status = 'idle'; + ELSEIF NEW.expeditions = NEW.scanned + THEN + SET NEW.status = 'done'; + ELSE + SET NEW.status = 'doing'; + END IF; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `routeLoadWorker` +-- + +DROP TABLE IF EXISTS `routeLoadWorker`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `routeLoadWorker` ( + `routeFk` int(10) unsigned NOT NULL, + `workerFk` int(11) NOT NULL, + PRIMARY KEY (`routeFk`,`workerFk`), + KEY `frmWorker_idx` (`workerFk`), + CONSTRAINT `frmRutas` FOREIGN KEY (`routeFk`) REFERENCES `route` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `frmWorker` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `routeLog` +-- + +DROP TABLE IF EXISTS `routeLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `routeLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(10) unsigned NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `originFk` (`originFk`), + KEY `userFk` (`userFk`), + CONSTRAINT `routeLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `route` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `routeLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=227662 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `routeParams` +-- + +DROP TABLE IF EXISTS `routeParams`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `routeParams` ( + `ID` int(10) unsigned NOT NULL AUTO_INCREMENT, + `kmRate` decimal(10,4) DEFAULT NULL, + `m3Distributed` decimal(10,4) DEFAULT NULL, + `m3Management` decimal(10,2) DEFAULT NULL, + `load1m3` decimal(10,4) DEFAULT NULL, + `load2m3` decimal(10,4) DEFAULT NULL, + `load3m3` decimal(10,4) DEFAULT NULL, + `load4m3` decimal(10,4) DEFAULT NULL, + `load5m3` decimal(10,4) DEFAULT NULL, + `load6m3` decimal(10,4) DEFAULT NULL, + PRIMARY KEY (`ID`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `routeUserPercentage` +-- + +DROP TABLE IF EXISTS `routeUserPercentage`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `routeUserPercentage` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `workerFk` int(11) NOT NULL, + `percentage` decimal(10,2) NOT NULL, + `dated` date NOT NULL, + PRIMARY KEY (`id`), + KEY `routeUserPercentageFk_idx` (`workerFk`), + CONSTRAINT `routeUserPercentageFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `sale` +-- + +DROP TABLE IF EXISTS `sale`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sale` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `itemFk` int(11) NOT NULL, + `ticketFk` int(11) NOT NULL, + `concept` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `quantity` decimal(10,2) NOT NULL DEFAULT '0.00', + `originalQuantity` double(9,1) DEFAULT NULL, + `price` decimal(10,2) DEFAULT '0.00', + `discount` tinyint(2) unsigned NOT NULL DEFAULT '0', + `priceFixed` decimal(10,2) NOT NULL DEFAULT '0.00', + `reserved` tinyint(1) NOT NULL DEFAULT '0', + `isPicked` tinyint(1) NOT NULL DEFAULT '0', + `isPriceFixed` tinyint(1) NOT NULL DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `Id_Ticket` (`ticketFk`), + KEY `itemFk_ticketFk` (`itemFk`,`ticketFk`), + CONSTRAINT `movement_ticket_id` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `sale_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=26615111 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sale_afterInsert` + AFTER INSERT ON `sale` + FOR EACH ROW +BEGIN + CALL stock.log_add('sale', NEW.id, NULL); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sale_beforeUpdate` + BEFORE UPDATE ON `sale` + FOR EACH ROW +BEGIN + + IF NEW.discount > 100 THEN + SET NEW.discount = 0; + END IF; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sale_afterUpdate` + AFTER UPDATE ON `sale` + FOR EACH ROW +BEGIN + IF !(NEW.id <=> OLD.id) + OR !(NEW.ticketFk <=> OLD.ticketFk) + OR !(NEW.itemFk <=> OLD.itemFk) + OR !(NEW.quantity <=> OLD.quantity) + OR !(NEW.created <=> OLD.created) + OR !(NEW.isPicked <=> OLD.isPicked) THEN + CALL stock.log_add('sale', NEW.id, OLD.id); + END IF; + + IF !(OLD.ticketFk <=> NEW.ticketFk) THEN + UPDATE ticketRequest SET ticketFk = NEW.ticketFk + WHERE saleFk = NEW.id; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sale_afterDelete` + AFTER DELETE ON `sale` + FOR EACH ROW +BEGIN + CALL stock.log_add('sale', NULL, OLD.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 */ ; + +-- +-- Table structure for table `saleChecked` +-- + +DROP TABLE IF EXISTS `saleChecked`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `saleChecked` ( + `saleFk` int(11) NOT NULL, + `isChecked` int(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`saleFk`), + CONSTRAINT `fk_Movimientos_checked_1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `saleComponent` +-- + +DROP TABLE IF EXISTS `saleComponent`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `saleComponent` ( + `saleFk` int(11) NOT NULL, + `componentFk` int(11) NOT NULL, + `value` double NOT NULL, + `isGreuge` tinyint(4) NOT NULL DEFAULT '0', + `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`saleFk`,`componentFk`), + KEY `fk_mov_comp_idx` (`componentFk`), + CONSTRAINT `mc_fk1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `mc_fk2` FOREIGN KEY (`componentFk`) REFERENCES `bi`.`tarifa_componentes` (`Id_Componente`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `saleFreight` +-- + +DROP TABLE IF EXISTS `saleFreight`; +/*!50001 DROP VIEW IF EXISTS `saleFreight`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `saleFreight` AS SELECT + 1 AS `ticketFk`, + 1 AS `clientFk`, + 1 AS `routeFk`, + 1 AS `saleFk`, + 1 AS `zoneFk`, + 1 AS `companyFk`, + 1 AS `shipped`, + 1 AS `price`, + 1 AS `freight`, + 1 AS `volume`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `saleItemShelving` +-- + +DROP TABLE IF EXISTS `saleItemShelving`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `saleItemShelving` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `saleFk` int(11) NOT NULL, + `itemShelvingFk` int(10) unsigned NOT NULL, + `quantity` int(11) NOT NULL DEFAULT '0', + `isPicked` tinyint(4) NOT NULL DEFAULT '0', + `ubication` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `saleItemShelving_fk1_idx` (`itemShelvingFk`) +) ENGINE=InnoDB AUTO_INCREMENT=26208 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `saleState` +-- + +DROP TABLE IF EXISTS `saleState`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `saleState` ( + `saleFk` int(11) NOT NULL, + `stateFk` tinyint(3) unsigned NOT NULL, + PRIMARY KEY (`saleFk`), + KEY `saleState_fk2_idx` (`stateFk`), + CONSTRAINT `saleState_fk1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `saleState_fk2` FOREIGN KEY (`stateFk`) REFERENCES `state` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='cahce para el estado de la linea'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `saleTracking` +-- + +DROP TABLE IF EXISTS `saleTracking`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `saleTracking` ( + `saleFk` int(11) NOT NULL, + `isChecked` tinyint(3) unsigned NOT NULL DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `originalQuantity` double DEFAULT NULL, + `workerFk` int(11) NOT NULL, + `actionFk` int(11) DEFAULT NULL, + `id` int(11) NOT NULL AUTO_INCREMENT, + `stateFk` tinyint(3) unsigned NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `stateFk_UNIQUE` (`stateFk`,`saleFk`), + KEY `Id_Movimiento` (`saleFk`), + KEY `fgnStateFk_idx` (`stateFk`), + KEY `saleTracking_idx5` (`created`), + KEY `saleTracking_fk2_idx` (`actionFk`), + CONSTRAINT `fgnStateFk` FOREIGN KEY (`stateFk`) REFERENCES `state` (`id`) ON UPDATE CASCADE, + CONSTRAINT `saleTracking_fk2` FOREIGN KEY (`actionFk`) REFERENCES `vncontrol`.`accion` (`accion_id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=21545889 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`saleTracking_beforeInsert` BEFORE INSERT ON `saleTracking` FOR EACH ROW +BEGIN + IF(NEW.stateFk = 14) THEN + SET NEW.actionFk = 3; + END IF; + + IF(NEW.stateFk = 8) THEN + SET NEW.actionFk = 4; + 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 */ ; + +-- +-- Temporary view structure for view `saleVolume` +-- + +DROP TABLE IF EXISTS `saleVolume`; +/*!50001 DROP VIEW IF EXISTS `saleVolume`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `saleVolume` AS SELECT + 1 AS `ticketFk`, + 1 AS `saleFk`, + 1 AS `litros`, + 1 AS `routeFk`, + 1 AS `shipped`, + 1 AS `volume`, + 1 AS `physicalWeight`, + 1 AS `weight`, + 1 AS `physicalVolume`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `sample` +-- + +DROP TABLE IF EXISTS `sample`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sample` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(20) CHARACTER SET utf8 NOT NULL, + `description` varchar(105) COLLATE utf8_unicode_ci NOT NULL, + `isVisible` tinyint(4) NOT NULL DEFAULT '1', + `hasCompany` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `sector` +-- + +DROP TABLE IF EXISTS `sector`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sector` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1', + `isPreviousPreparedByPacking` tinyint(4) NOT NULL DEFAULT '1', + `code` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `pickingPlacement` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `path` int(11) DEFAULT NULL, + PRIMARY KEY (`id`,`warehouseFk`), + UNIQUE KEY `code_UNIQUE` (`code`), + KEY `sector_fk1_idx` (`warehouseFk`), + CONSTRAINT `sector_fk1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `sharingCart` +-- + +DROP TABLE IF EXISTS `sharingCart`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sharingCart` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `workerFk` int(11) NOT NULL, + `started` date NOT NULL, + `ended` date NOT NULL, + `workerSubstitute` int(11) NOT NULL, + `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `Worker` (`workerFk`), + KEY `Suplent` (`workerSubstitute`), + CONSTRAINT `Suplent_key` FOREIGN KEY (`workerSubstitute`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `Trabajador_key` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2250 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`sharingCart_beforeInsert` BEFORE INSERT ON `sharingCart` FOR EACH ROW + +BEGIN + SET NEW.started = GREATEST(CURDATE(),NEW.started); + SET NEW.ended = GREATEST(CURDATE(),NEW.ended); + + IF NEW.workerFk = NEW.workerSubstitute THEN + SET NEW.workerFk = NULL; +END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`sharingCart_beforeUpdate` BEFORE UPDATE ON `sharingCart` FOR EACH ROW + +BEGIN + SET NEW.started = GREATEST(CURDATE(),NEW.started); + SET NEW.ended = GREATEST(CURDATE(),NEW.ended); + + IF NEW.workerFk = NEW.workerSubstitute THEN + SET NEW.workerFk = NULL; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `sharingClient` +-- + +DROP TABLE IF EXISTS `sharingClient`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sharingClient` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `workerFk` int(11) NOT NULL, + `started` date NOT NULL, + `ended` date NOT NULL, + `clientFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `Worker` (`workerFk`), + KEY `Client` (`clientFk`), + CONSTRAINT `Clients_key` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE, + CONSTRAINT `Trabajadores_key` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`sharingClient_beforeInsert` BEFORE INSERT ON `sharingClient` FOR EACH ROW +BEGIN + SET NEW.ended = GREATEST(CURDATE(),NEW.ended); + SET NEW.started = GREATEST(CURDATE(),NEW.started); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`sharingClient_beforeUpdate` BEFORE UPDATE ON `sharingClient` FOR EACH ROW +BEGIN + SET NEW.ended = GREATEST(CURDATE(),NEW.ended); + SET NEW.started = GREATEST(CURDATE(),NEW.started); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `shelving` +-- + +DROP TABLE IF EXISTS `shelving`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `shelving` ( + `code` varchar(10) CHARACTER SET utf8 NOT NULL, + `parkingFk` int(11) DEFAULT NULL, + `isPrinted` tinyint(4) NOT NULL DEFAULT '0', + `priority` int(11) DEFAULT NULL, + `parked` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`code`), + KEY `shelving_fk1_idx` (`parkingFk`), + CONSTRAINT `shelving_fk1` FOREIGN KEY (`parkingFk`) REFERENCES `parking` (`id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla usada para localizar el carro en el parking del altillo'; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`shelving_BEFORE_UPDATE` BEFORE UPDATE ON `shelving` FOR EACH ROW +BEGIN + + IF OLD.parkingFk != NEW.parkingFk THEN + + UPDATE item i + JOIN itemShelving ish ON ish.itemFk = i.id + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + SET i.sectorFk = p.sectorFk + WHERE sh.`code` = OLD.`code`; + + END IF; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `sms` +-- + +DROP TABLE IF EXISTS `sms`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `sms` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `senderFk` int(11) NOT NULL, + `destinationFk` int(11) DEFAULT NULL, + `sender` varchar(15) CHARACTER SET utf8 NOT NULL DEFAULT '693474205', + `destination` varchar(15) CHARACTER SET utf8 NOT NULL, + `message` varchar(160) COLLATE utf8_unicode_ci NOT NULL, + `statusCode` smallint(9) NOT NULL DEFAULT '0', + `status` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=158472 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `smsConfig` +-- + +DROP TABLE IF EXISTS `smsConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `smsConfig` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `uri` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `user` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `password` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `title` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='SMS configuration parameters'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `solunionCAP` +-- + +DROP TABLE IF EXISTS `solunionCAP`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `solunionCAP` ( + `creditInsurance` int(11) NOT NULL, + `dateStart` date NOT NULL, + `dateEnd` date NOT NULL, + `dateLeaving` date DEFAULT NULL, + PRIMARY KEY (`creditInsurance`,`dateStart`), + KEY `solunionCAPdateLeavingIdx` (`dateLeaving`), + CONSTRAINT `solunionCAP` FOREIGN KEY (`creditInsurance`) REFERENCES `creditInsurance` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`solunionCAP_AFTER_INSERT` AFTER INSERT ON `solunionCAP` FOR EACH ROW +BEGIN + UPDATE vn2008.Clientes c + JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditInsurance ci ON ci.creditClassification = cc.id + SET creditInsurance = ci.credit * 2 WHERE ci.id = NEW.creditInsurance; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`solunionCAP_AFTER_UPDATE` AFTER UPDATE ON `solunionCAP` FOR EACH ROW +BEGIN + IF NEW.dateLeaving IS NOT NULL THEN + UPDATE vn2008.Clientes c + JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditInsurance ci ON ci.creditClassification = cc.id + SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; + ELSE + UPDATE vn2008.Clientes c + JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditInsurance ci ON ci.creditClassification = cc.id + SET creditInsurance = ci.credit * 2 WHERE ci.id = OLD.creditInsurance; + 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 */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`solunionCAP_BEFORE_DELETE` BEFORE DELETE ON `solunionCAP` FOR EACH ROW +BEGIN + UPDATE vn2008.Clientes c + JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditInsurance ci ON ci.creditClassification = cc.id + SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; + +-- +-- Table structure for table `specialPrice` +-- + +DROP TABLE IF EXISTS `specialPrice`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `specialPrice` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `clientFk` int(11) NOT NULL DEFAULT '0', + `itemFk` int(11) NOT NULL DEFAULT '0', + `value` double NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `Id_Cliente_2` (`clientFk`,`itemFk`), + KEY `Id_Article` (`itemFk`), + KEY `Id_Cliente` (`clientFk`), + CONSTRAINT `sp_article_id` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE, + CONSTRAINT `sp_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE, + CONSTRAINT `{01A99AF1-3D3F-4B15-AC0C-C7A834F319A3}` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `{EE4ADEF6-0AC6-401F-B7C4-D797972FC065}` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=713 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `state` +-- + +DROP TABLE IF EXISTS `state`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `state` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `order` tinyint(3) unsigned DEFAULT NULL, + `alertLevel` int(11) NOT NULL DEFAULT '0', + `code` varchar(45) CHARACTER SET utf8 NOT NULL, + `sectorProdPriority` tinyint(3) DEFAULT NULL, + `nextStateFk` tinyint(4) NOT NULL COMMENT 'Estado al que tiene que cambiar el ticket despues de preparacion previa', + `isPreviousPreparable` tinyint(1) NOT NULL DEFAULT '0', + `isPicked` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `code_UNIQUE` (`code`) +) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `stockBuyed` +-- + +DROP TABLE IF EXISTS `stockBuyed`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `stockBuyed` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `user` int(10) unsigned DEFAULT NULL, + `buyed` decimal(10,2) DEFAULT NULL, + `date` date DEFAULT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `reserved` decimal(10,2) DEFAULT NULL, + `requested` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `date_UNIQUE` (`date`,`user`), + KEY `stockBuyed_user_idx` (`user`), + CONSTRAINT `stockBuyedUserFk` FOREIGN KEY (`user`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=864507 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `stowaway` +-- + +DROP TABLE IF EXISTS `stowaway`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `stowaway` ( + `id` int(11) NOT NULL COMMENT 'ticket pequeño', + `shipFk` int(11) NOT NULL COMMENT 'ticket grande', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tickets polizones y sus naves de embarque'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `supplier` +-- + +DROP TABLE IF EXISTS `supplier`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `supplier` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `account` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `street` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `postCode__` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'deprecada', + `city` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `provinceFk` smallint(5) unsigned DEFAULT NULL, + `countryFk` mediumint(8) unsigned DEFAULT NULL, + `nif` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `isOfficial` tinyint(1) NOT NULL DEFAULT '1', + `isFarmer` tinyint(1) NOT NULL DEFAULT '0', + `retAccount` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `phone` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL, + `Fax` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL, + `commission` float NOT NULL DEFAULT '0', + `nickname` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `payMethodFk` tinyint(3) unsigned NOT NULL, + `payDay` tinyint(4) unsigned DEFAULT NULL, + `payDemFk` tinyint(3) unsigned NOT NULL DEFAULT '7', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `isSerious` tinyint(1) unsigned zerofill DEFAULT '1', + `note` text COLLATE utf8_unicode_ci, + `postcodeFk` int(11) unsigned DEFAULT NULL, + `postCode` char(5) COLLATE utf8_unicode_ci DEFAULT NULL, + `isActive` tinyint(4) DEFAULT '1', + PRIMARY KEY (`id`), + UNIQUE KEY `cuenta` (`account`), + UNIQUE KEY `NIF` (`nif`), + KEY `pais_id` (`countryFk`), + KEY `pay_met_id` (`payMethodFk`), + KEY `province_id` (`provinceFk`), + KEY `pay_dem_id` (`payDemFk`), + KEY `codpos` (`postCode`,`postCode__`), + CONSTRAINT `Id_Pais` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE, + CONSTRAINT `pay_dem_id` FOREIGN KEY (`payDemFk`) REFERENCES `payDem` (`id`) ON UPDATE CASCADE, + CONSTRAINT `pay_met_id` FOREIGN KEY (`payMethodFk`) REFERENCES `payMethod` (`id`) ON UPDATE CASCADE, + CONSTRAINT `province_id` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2993 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `supplierAccount` +-- + +DROP TABLE IF EXISTS `supplierAccount`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `supplierAccount` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `supplierFk` int(11) NOT NULL, + `iban` varchar(30) CHARACTER SET utf8 DEFAULT NULL, + `office` varchar(4) CHARACTER SET utf8 DEFAULT NULL, + `DC` varchar(2) CHARACTER SET utf8 DEFAULT NULL, + `number` varchar(10) CHARACTER SET utf8 DEFAULT NULL, + `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'obsoleta(comprobar)', + `bicSufix` varchar(3) CHARACTER SET utf8 NOT NULL DEFAULT '', + `bankEntityFk` int(10) DEFAULT NULL, + `bankFk` int(11) DEFAULT NULL COMMENT 'obsoleta(comprobar)', + PRIMARY KEY (`id`), + KEY `fk_proveedores_proveedores_account_idx` (`supplierFk`), + KEY `fk_Proveedores_account_entity1_idx` (`bankEntityFk`), + KEY `fk_banco_prov_account_idx` (`bankFk`) +) ENGINE=InnoDB AUTO_INCREMENT=894 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `supplierExpense` +-- + +DROP TABLE IF EXISTS `supplierExpense`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `supplierExpense` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `supplierFk` int(11) NOT NULL, + `currencyFk` tinyint(3) unsigned NOT NULL DEFAULT '2', + `amount` decimal(10,2) NOT NULL DEFAULT '0.00', + `description` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442', + `dmsFk` int(11) DEFAULT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `isConciliated` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0', + `dueDated` date NOT NULL, + PRIMARY KEY (`id`), + KEY `empresa_id` (`companyFk`), + KEY `supplierExDated` (`dated`), + KEY `id_moneda` (`currencyFk`), + KEY `proveedor_pago` (`supplierFk`), + KEY `gestdoc_id` (`dmsFk`), + KEY `dueDatedIdx` (`dueDated`), + CONSTRAINT `gestdoc_fk` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON UPDATE CASCADE, + CONSTRAINT `pago_ibfk_1` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, + CONSTRAINT `pago_moneda` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE, + CONSTRAINT `proveedor_pago` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=130 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `supplierPackaging` +-- + +DROP TABLE IF EXISTS `supplierPackaging`; +/*!50001 DROP VIEW IF EXISTS `supplierPackaging`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `supplierPackaging` AS SELECT + 1 AS `supplierFk`, + 1 AS `itemFk`, + 1 AS `longName`, + 1 AS `supplier`, + 1 AS `entryFk`, + 1 AS `landed`, + 1 AS `out`, + 1 AS `in`, + 1 AS `almacen`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `tablet` +-- + +DROP TABLE IF EXISTS `tablet`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tablet` ( + `uuid` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `place` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `macwifi` varchar(45) COLLATE utf8_unicode_ci DEFAULT '0', + PRIMARY KEY (`uuid`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tabletDepartment` +-- + +DROP TABLE IF EXISTS `tabletDepartment`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tabletDepartment` ( + `tabletFk` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `departmentFk` int(11) NOT NULL, + PRIMARY KEY (`tabletFk`,`departmentFk`), + KEY `departmentFk_idx` (`departmentFk`), + CONSTRAINT `departmentFk` FOREIGN KEY (`departmentFk`) REFERENCES `department` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tag` +-- + +DROP TABLE IF EXISTS `tag`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tag` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `code` varchar(45) CHARACTER SET utf8 NOT NULL, + `name` varchar(25) CHARACTER SET utf8 NOT NULL, + `isFree` tinyint(1) NOT NULL DEFAULT '1', + `isQuantitatif` tinyint(4) NOT NULL DEFAULT '0', + `sourceTable` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `unit` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `ediTypeFk` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `tagEdiTypeFkIdx` (`ediTypeFk`), + CONSTRAINT `fgnTag` FOREIGN KEY (`ediTypeFk`) REFERENCES `edi`.`type` (`type_id`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=111 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Categorias para etiquetar los productos'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tagAbbreviation` +-- + +DROP TABLE IF EXISTS `tagAbbreviation`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tagAbbreviation` ( + `value` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + `abbreviation` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`value`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tagI18n` +-- + +DROP TABLE IF EXISTS `tagI18n`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tagI18n` ( + `tagFk` int(10) unsigned NOT NULL, + `lang` char(2) CHARACTER SET utf8 NOT NULL, + `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`tagFk`,`lang`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `tagL10n` +-- + +DROP TABLE IF EXISTS `tagL10n`; +/*!50001 DROP VIEW IF EXISTS `tagL10n`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `tagL10n` AS SELECT + 1 AS `id`, + 1 AS `name`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `taxArea` +-- + +DROP TABLE IF EXISTS `taxArea`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `taxArea` ( + `code` varchar(15) CHARACTER SET utf8 NOT NULL, + `ClaveOperacionFactura` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, + `CodigoTransaccion` int(2) DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `taxClass` +-- + +DROP TABLE IF EXISTS `taxClass`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `taxClass` ( + `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `description` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `code` varchar(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'R', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `taxClassCode` +-- + +DROP TABLE IF EXISTS `taxClassCode`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `taxClassCode` ( + `taxClassFk` tinyint(3) unsigned NOT NULL, + `effectived` date NOT NULL, + `taxCodeFk` tinyint(3) unsigned NOT NULL, + PRIMARY KEY (`taxClassFk`,`effectived`,`taxCodeFk`), + KEY `iva_codigo_id` (`taxCodeFk`), + CONSTRAINT `taxClassCode_ibfk_1` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE, + CONSTRAINT `taxClassCode_ibfk_2` FOREIGN KEY (`taxCodeFk`) REFERENCES `taxCode` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `taxCode` +-- + +DROP TABLE IF EXISTS `taxCode`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `taxCode` ( + `id` tinyint(2) unsigned NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `code` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `taxTypeFk` tinyint(2) NOT NULL, + `rate` decimal(4,1) NOT NULL DEFAULT '0.0', + `equalizationTax` decimal(4,1) NOT NULL DEFAULT '0.0', + `type` char(1) COLLATE utf8_unicode_ci NOT NULL, + `link` tinyint(4) unsigned NOT NULL DEFAULT '0' COMMENT 'las que tienen el mismo valor se contabilizan emparejadas', + `isActive` tinyint(2) NOT NULL DEFAULT '1', + `updated` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `transactionCode` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `iva_tipo_id` (`taxTypeFk`), + KEY `codigo` (`code`), + KEY `tipo_index` (`type`), + CONSTRAINT `taxCode_ibfk_1` FOREIGN KEY (`taxTypeFk`) REFERENCES `taxType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=123 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `taxType` +-- + +DROP TABLE IF EXISTS `taxType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `taxType` ( + `id` tinyint(2) NOT NULL AUTO_INCREMENT, + `nickname` varchar(6) COLLATE utf8_unicode_ci NOT NULL, + `isAccrued` tinyint(4) NOT NULL DEFAULT '0', + `serial` char(1) COLLATE utf8_unicode_ci DEFAULT NULL, + `TIPOOPE` varchar(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT ' ' COMMENT 'respetar el nombre de la columna, se utiliza en contaplus', + `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `countryFk` mediumint(8) unsigned NOT NULL, + PRIMARY KEY (`id`), + KEY `serie_id` (`serial`), + KEY `Id_Pais` (`countryFk`), + CONSTRAINT `taxType_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ticket` +-- + +DROP TABLE IF EXISTS `ticket`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticket` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `clientFk` int(11) NOT NULL DEFAULT '0', + `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1', + `shipped` datetime NOT NULL, + `nickname` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `notes` longtext COLLATE utf8_unicode_ci, + `refFk` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `invoiceOutFk` int(10) unsigned DEFAULT NULL COMMENT 'eliminar', + `isBooked` tinyint(1) NOT NULL DEFAULT '0', + `addressFk` int(11) NOT NULL DEFAULT '0', + `workerFk` int(11) DEFAULT NULL, + `observations` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'eliminar', + `isSigned` tinyint(1) NOT NULL DEFAULT '0', + `isLabeled` tinyint(1) NOT NULL DEFAULT '0', + `isPrinted` tinyint(1) NOT NULL DEFAULT '0', + `packages` smallint(10) unsigned DEFAULT '0', + `location` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `hour` int(11) DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `isBlocked` tinyint(1) NOT NULL DEFAULT '1', + `solution` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, + `routeFk` int(10) unsigned DEFAULT NULL, + `priority` tinyint(3) unsigned DEFAULT NULL, + `hasPriority` tinyint(1) unsigned NOT NULL DEFAULT '1', + `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442', + `agencyModeFk` int(11) DEFAULT NULL, + `landed` date DEFAULT NULL, + `isBoxed` tinyint(2) NOT NULL DEFAULT '0', + `isDeleted` tinyint(2) NOT NULL DEFAULT '0', + `zoneFk` int(11) DEFAULT NULL, + `collectionFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `Id_Cliente` (`clientFk`), + KEY `Id_Consigna` (`addressFk`), + KEY `Id_Trabajador` (`workerFk`), + KEY `warehouse_id` (`warehouseFk`), + KEY `empresa_id` (`companyFk`), + KEY `Id_Agencia` (`agencyModeFk`), + KEY `Factura` (`refFk`), + KEY `Id_Ruta` (`routeFk`), + KEY `warehouse_date` (`warehouseFk`,`shipped`), + KEY `Fecha` (`shipped`,`clientFk`), + KEY `tickets_zone_fk_idx` (`zoneFk`), + KEY `tickets_fk11_idx` (`collectionFk`), + CONSTRAINT `ticket_customer_id` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE, + CONSTRAINT `ticket_ibfk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `ticket_ibfk_5` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, + CONSTRAINT `ticket_ibfk_6` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE, + CONSTRAINT `ticket_ibfk_8` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`), + CONSTRAINT `ticket_ibfk_9` FOREIGN KEY (`routeFk`) REFERENCES `route` (`id`) ON UPDATE CASCADE, + CONSTRAINT `tickets_fk10` FOREIGN KEY (`refFk`) REFERENCES `invoiceOut` (`ref`) ON UPDATE CASCADE, + CONSTRAINT `tickets_fk11` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `tickets_zone_fk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2513929 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `ticket_afterInsert` + AFTER INSERT ON `ticket` + FOR EACH ROW +BEGIN + DECLARE vClientType VARCHAR(255); + DECLARE vStateCode VARCHAR(255); + + -- Borrar cuando se cambie el insert ticket en la APP móvil + + SELECT typeFk INTO vClientType + FROM vn.`client` WHERE id = NEW.clientFk; + + IF vClientType = 'loses' THEN + SET vStateCode = 'DELIVERED'; + ELSE + SET vStateCode = 'FREE'; + END IF; + + INSERT INTO vncontrol.inter(Id_Ticket, state_id, Id_Trabajador) + SELECT NEW.id, id, vn.myWorker_getId() + FROM state + WHERE `code` = vStateCode COLLATE utf8_general_ci; + + -- Borrar al acabar el proceso de cambio de nichos a carros + /* IF NEW.warehouseFk IN (1,44) THEN + + INSERT INTO vn.ticketObservation(ticketFk, description, observationTypeFk) + VALUES(NEW.id,'NO OLVIDES ESCANEAR LAS MATRICULAS',1) + ON DUPLICATE KEY UPDATE description = CONCAT(description,'. Y NO OLVIDES ESCANEAR LAS MATRICULAS'); + + END IF; */ +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `ticket_beforeUpdate` + BEFORE UPDATE ON `ticket` + FOR EACH ROW +BEGIN + IF !(NEW.shipped <=> OLD.shipped) THEN + IF YEAR(NEW.shipped) < 2000 THEN + SIGNAL SQLSTATE '46000' + SET MESSAGE_TEXT = 'Year cannot be lesser than 2000'; + END IF; + + IF YEAR(NEW.shipped) = 2000 THEN + SET NEW.isDeleted = TRUE; + END IF; + END IF; + + IF !(NEW.isDeleted <=> OLD.isDeleted) AND NEW.isDeleted THEN + SET NEW.shipped = DATE_FORMAT(NEW.shipped, '2000-%m-%d %T'); + SET NEW.landed = DATE_FORMAT(NEW.landed, '2000-%m-%d %T'); + SET NEW.routeFk = NULL; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `ticket_afterUpdate` + AFTER UPDATE ON `ticket` + FOR EACH ROW +BEGIN + IF !(NEW.id <=> OLD.id) + OR !(NEW.warehouseFk <=> OLD.warehouseFk) + OR !(NEW.shipped <=> OLD.shipped) THEN + CALL stock.log_add('ticket', NEW.id, OLD.id); + END IF; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `ticket_beforeDelete` + BEFORE DELETE ON `ticket` + FOR EACH ROW +BEGIN + DELETE FROM sale WHERE ticketFk = OLD.id; + + DELETE FROM ticketDms WHERE ticketFk = OLD.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 */ ; + +-- +-- Table structure for table `ticketCollection` +-- + +DROP TABLE IF EXISTS `ticketCollection`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketCollection` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `ticketFk` int(11) NOT NULL, + `collectionFk` int(11) NOT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `level` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `ticketCollection_fk1_idx` (`collectionFk`), + KEY `ticketCollection_fk2_idx` (`ticketFk`), + CONSTRAINT `ticketCollection_fk1` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `ticketCollection_fk2` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=1241 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ticketConfig` +-- + +DROP TABLE IF EXISTS `ticketConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `scopeDays` tinyint(3) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ticketDms` +-- + +DROP TABLE IF EXISTS `ticketDms`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketDms` ( + `ticketFk` int(11) NOT NULL, + `dmsFk` int(11) NOT NULL, + PRIMARY KEY (`ticketFk`,`dmsFk`), + KEY `gestdoc_id` (`dmsFk`), + CONSTRAINT `ticketDms_dmsFk` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `ticketDms_ticketFk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketDms_beforeDelete` BEFORE DELETE ON `ticketDms` FOR EACH ROW +BEGIN + UPDATE dms + SET dmsTypeFk = (SELECT id FROM dmsType WHERE `code` = 'trash') + WHERE id = OLD.dmsFk; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `ticketDown` +-- + +DROP TABLE IF EXISTS `ticketDown`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketDown` ( + `ticketFk` int(11) NOT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `selected` int(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`ticketFk`), + KEY `created_idx` (`created`), + KEY `selected_idx` (`selected`), + CONSTRAINT `ticketDown_fk1` FOREIGN KEY (`selected`) REFERENCES `ticketDown_SelectionType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Cola de impresion para los tickets que se van a solicitar al altillo'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ticketDown_SelectionType` +-- + +DROP TABLE IF EXISTS `ticketDown_SelectionType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketDown_SelectionType` ( + `id` int(11) NOT NULL, + `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `description_UNIQUE` (`description`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `ticketGetVolume__` +-- + +DROP TABLE IF EXISTS `ticketGetVolume__`; +/*!50001 DROP VIEW IF EXISTS `ticketGetVolume__`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `ticketGetVolume__` AS SELECT + 1 AS `ticketFk`, + 1 AS `routeFk`, + 1 AS `saleFk`, + 1 AS `shipped`, + 1 AS `volume`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `ticketLastState` +-- + +DROP TABLE IF EXISTS `ticketLastState`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketLastState` ( + `ticketFk` int(11) NOT NULL DEFAULT '0', + `ticketTrackingFk` int(11) NOT NULL, + `name` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`ticketFk`), + KEY `double_foreign` (`ticketFk`,`ticketTrackingFk`), + CONSTRAINT `Id_Ticket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `double_foreign` FOREIGN KEY (`ticketFk`, `ticketTrackingFk`) REFERENCES `vncontrol`.`inter` (`Id_Ticket`, `inter_id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ticketLog` +-- + +DROP TABLE IF EXISTS `ticketLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(11) NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete','select') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `logTicketoriginFk` (`originFk`), + KEY `logTicketuserFk` (`userFk`), + CONSTRAINT `ticketLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `ticketLog_user` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=8412961 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `ticketNotInvoiced` +-- + +DROP TABLE IF EXISTS `ticketNotInvoiced`; +/*!50001 DROP VIEW IF EXISTS `ticketNotInvoiced`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `ticketNotInvoiced` AS SELECT + 1 AS `companyFk`, + 1 AS `companyCode`, + 1 AS `clientFk`, + 1 AS `clientName`, + 1 AS `shipped`, + 1 AS `value`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `ticketObservation` +-- + +DROP TABLE IF EXISTS `ticketObservation`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketObservation` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `ticketFk` int(11) NOT NULL, + `observationTypeFk` tinyint(3) unsigned NOT NULL, + `description` text COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `Id_Ticket` (`ticketFk`,`observationTypeFk`), + KEY `observation_type_id` (`observationTypeFk`), + CONSTRAINT `ticketObservation_ibfk_1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `ticketObservation_ibfk_2` FOREIGN KEY (`observationTypeFk`) REFERENCES `observationType` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=1530942 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Todas las observaciones referentes a un ticket'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ticketPackage` +-- + +DROP TABLE IF EXISTS `ticketPackage`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketPackage` ( + `ticket` int(11) NOT NULL, + `counter` int(10) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`ticket`), + CONSTRAINT `ticketPackage_ticketFk` FOREIGN KEY (`ticket`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ticketPackaging` +-- + +DROP TABLE IF EXISTS `ticketPackaging`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketPackaging` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `ticketFk` int(11) NOT NULL, + `packagingFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `quantity` int(10) DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `pvp` double DEFAULT NULL, + `workerFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `ticketPackaging_fk1_idx` (`ticketFk`), + KEY `ticketPackaging_fk2_idx` (`packagingFk`), + KEY `ticketPackaging_fk3_idx` (`workerFk`), + CONSTRAINT `ticketPackaging_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `ticketPackaging_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE, + CONSTRAINT `ticketPackaging_fk3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=79234 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketPackaging_BEFORE_INSERT` BEFORE INSERT ON `ticketPackaging` FOR EACH ROW +BEGIN + + SET NEW.workerFk = vn.getWorker(); + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `ticketPackagingStartingStock` +-- + +DROP TABLE IF EXISTS `ticketPackagingStartingStock`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketPackagingStartingStock` ( + `clientFk` int(11) NOT NULL, + `packagingFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `itemFk` int(11) NOT NULL, + `sent` int(11) DEFAULT NULL, + `returned` int(11) DEFAULT NULL, + `isForgetable` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`clientFk`,`packagingFk`), + KEY `ticketPackagingStartingStock_fk2_idx` (`packagingFk`), + KEY `ticketPackagingStartingStock_fk3_idx` (`itemFk`), + CONSTRAINT `ticketPackagingStartingStock_fk1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `ticketPackagingStartingStock_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `ticketPackagingStartingStock_fk3` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ticketParking` +-- + +DROP TABLE IF EXISTS `ticketParking`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketParking` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `ticketFk` int(11) NOT NULL, + `parkingFk` int(11) NOT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `ticketParking_idx1` (`ticketFk`,`parkingFk`), + KEY `ticketParking_fk1_idx` (`parkingFk`), + CONSTRAINT `ticketParking_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `ticketParking_fk2` FOREIGN KEY (`parkingFk`) REFERENCES `parking` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=16798 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los distintos lugares donde puede estar aparcado cada uno de los prepedidos'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `ticketPreviousPreparingList` +-- + +DROP TABLE IF EXISTS `ticketPreviousPreparingList`; +/*!50001 DROP VIEW IF EXISTS `ticketPreviousPreparingList`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `ticketPreviousPreparingList` AS SELECT + 1 AS `ticketFk`, + 1 AS `code`, + 1 AS `saleLines`, + 1 AS `alreadyMadeSaleLines`, + 1 AS `madeRate`, + 1 AS `created`, + 1 AS `sectorFk`, + 1 AS `parking`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `ticketRequest` +-- + +DROP TABLE IF EXISTS `ticketRequest`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketRequest` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `ordered` datetime DEFAULT NULL, + `shipped` datetime DEFAULT NULL, + `salesPersonCode` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `buyerCode` varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'NOE', + `quantity` int(11) DEFAULT NULL, + `price` double DEFAULT NULL, + `price__` double DEFAULT NULL, + `itemFk` double DEFAULT NULL, + `clientFk` int(11) DEFAULT NULL, + `response` longtext COLLATE utf8_unicode_ci, + `ok__` tinyint(1) NOT NULL DEFAULT '0', + `total` int(11) DEFAULT NULL, + `buyed` datetime DEFAULT NULL, + `ko__` tinyint(1) NOT NULL DEFAULT '0', + `saleFk` int(11) DEFAULT NULL, + `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `isOk` tinyint(1) DEFAULT NULL, + `requesterFk` int(11) DEFAULT NULL, + `atenderFk` int(11) DEFAULT NULL, + `ticketFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `Id_Movimiento_UNIQUE` (`saleFk`), + KEY `Id_ARTICLE` (`itemFk`), + KEY `Id_CLIENTE` (`clientFk`), + KEY `Id_Comprador` (`buyerCode`), + KEY `Id_Movimiento` (`saleFk`), + KEY `Id_Vendedor` (`salesPersonCode`), + KEY `fgnRequester_idx` (`requesterFk`), + KEY `fgnAtender_idx` (`atenderFk`), + KEY `fgnTicket_idx` (`ticketFk`), + CONSTRAINT `fgbMovimiento` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `fgnAtender` FOREIGN KEY (`atenderFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `fgnRequester` FOREIGN KEY (`requesterFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `fgnTicket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=52600 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketRequest_beforeInsert` BEFORE INSERT ON `ticketRequest` FOR EACH ROW +BEGIN + IF NEW.ticketFk IS NULL THEN + SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); + END IF; + + IF NEW.requesterFk IS NULL THEN + SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); + END IF; + + IF NEW.atenderFk IS NULL THEN + SET NEW.atenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketRequest_beforeUpdate` BEFORE UPDATE ON `ticketRequest` FOR EACH ROW +BEGIN + IF NEW.saleFk <> OLD.saleFk THEN + SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); + END IF; + + IF NEW.salesPersonCode <> OLD.salesPersonCode THEN + SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); + END IF; + + IF NEW.buyerCode <> OLD.buyerCode THEN + SET NEW.atenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `ticketService` +-- + +DROP TABLE IF EXISTS `ticketService`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketService` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `quantity` int(11) NOT NULL DEFAULT '0', + `price` decimal(10,2) unsigned NOT NULL DEFAULT '0.00', + `taxClassFk` tinyint(3) unsigned DEFAULT NULL, + `ticketFk` int(11) NOT NULL, + `ticketServiceTypeFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `ticketServiceIvaGroup_idx` (`taxClassFk`), + KEY `fgn_ticketFk_idx` (`ticketFk`), + KEY `ticketService_ticketServiceType_idx` (`ticketServiceTypeFk`), + CONSTRAINT `fgn_ticketFk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `ticketServiceIvaGroup` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE, + CONSTRAINT `ticketService_ticketServiceType` FOREIGN KEY (`ticketServiceTypeFk`) REFERENCES `ticketServiceType` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Servicios asociadas a un ticket'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ticketServiceType` +-- + +DROP TABLE IF EXISTS `ticketServiceType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketServiceType` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `expenceFk` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '7001000000', + PRIMARY KEY (`id`), + KEY `ticketServiceType_expence_idx` (`expenceFk`), + CONSTRAINT `ticketServiceType_expence` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='Lista de los posibles servicios a elegir'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `ticketState` +-- + +DROP TABLE IF EXISTS `ticketState`; +/*!50001 DROP VIEW IF EXISTS `ticketState`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `ticketState` AS SELECT + 1 AS `updated`, + 1 AS `stateFk`, + 1 AS `workerFk`, + 1 AS `ticketFk`, + 1 AS `state`, + 1 AS `productionOrder`, + 1 AS `alertLevel`, + 1 AS `code`, + 1 AS `ticket`, + 1 AS `worker`, + 1 AS `isPreviousPreparable`, + 1 AS `isPicked`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `ticketStateToday` +-- + +DROP TABLE IF EXISTS `ticketStateToday`; +/*!50001 DROP VIEW IF EXISTS `ticketStateToday`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `ticketStateToday` AS SELECT + 1 AS `ticket`, + 1 AS `state`, + 1 AS `productionOrder`, + 1 AS `alertLevel`, + 1 AS `worker`, + 1 AS `code`, + 1 AS `updated`, + 1 AS `isPicked`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `ticketTracking` +-- + +DROP TABLE IF EXISTS `ticketTracking`; +/*!50001 DROP VIEW IF EXISTS `ticketTracking`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `ticketTracking` AS SELECT + 1 AS `id`, + 1 AS `stateFk`, + 1 AS `created`, + 1 AS `ticketFk`, + 1 AS `workerFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `ticketTrolley` +-- + +DROP TABLE IF EXISTS `ticketTrolley`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketTrolley` ( + `ticket` int(11) NOT NULL, + `labelCount` int(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`ticket`), + CONSTRAINT `fk_ticketTrolley_vs_ticket` FOREIGN KEY (`ticket`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ticketUpdateAction` +-- + +DROP TABLE IF EXISTS `ticketUpdateAction`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketUpdateAction` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='En esta tabla pondremos las distintas opciones que se ofrecen al comecial o al cliente al cambiar alguno de los parametros básicos de un ticket'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ticketWeekly` +-- + +DROP TABLE IF EXISTS `ticketWeekly`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticketWeekly` ( + `ticketFk` int(11) NOT NULL AUTO_INCREMENT, + `weekDay` tinyint(1) DEFAULT NULL COMMENT 'funcion de mysql Lunes = 0, Domingo = 6', + PRIMARY KEY (`ticketFk`), + CONSTRAINT `Id_Ticket_fk` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2511082 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `till` +-- + +DROP TABLE IF EXISTS `till`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `till` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `isAccountable` tinyint(1) NOT NULL DEFAULT '0', + `serie` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, + `number` int(11) DEFAULT NULL, + `concept` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `in` decimal(10,2) DEFAULT NULL, + `out` decimal(10,2) DEFAULT NULL, + `bankFk` int(11) DEFAULT '1', + `workerFk` int(11) DEFAULT NULL, + `companyFk` smallint(5) unsigned DEFAULT '442' COMMENT 'kakear', + `isLinked` tinyint(4) DEFAULT '0', + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `isOk` tinyint(4) NOT NULL DEFAULT '0', + `warehouseFk` smallint(5) unsigned NOT NULL DEFAULT '1' COMMENT 'to kak\\n', + `isConciliate` tinyint(4) NOT NULL DEFAULT '0', + `supplierAccountFk` mediumint(8) unsigned NOT NULL, + `calculatedCode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `InForeignValue` decimal(10,2) DEFAULT NULL, + `OutForeignValue` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `id_calculated_UNIQUE` (`calculatedCode`), + KEY `CajasCajafecha` (`dated`), + KEY `Id_Banco` (`bankFk`), + KEY `Id_Trabajador` (`workerFk`), + KEY `empresa_id` (`companyFk`), + KEY `warehouse_id` (`warehouseFk`), + KEY `fk_Cajas_Proveedores_account1_idx` (`supplierAccountFk`), + CONSTRAINT `till_ibfk_2` FOREIGN KEY (`bankFk`) REFERENCES `bank` (`id`) ON UPDATE CASCADE, + CONSTRAINT `till_ibfk_3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=750671 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`till_beforeInsert` BEFORE INSERT ON `till` FOR EACH ROW +BEGIN + IF IFNULL(NEW.concept,"") = "" THEN + CALL util.throw ('Error. El concepto esta vacío'); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `tillConfig` +-- + +DROP TABLE IF EXISTS `tillConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `tillConfig` ( + `id` int(11) NOT NULL, + `openingBalance` decimal(10,2) NOT NULL, + `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `town` +-- + +DROP TABLE IF EXISTS `town`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `town` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `provinceFk` smallint(6) unsigned NOT NULL, + `geoFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `name_idx` (`name`), + KEY `townProvinceFk` (`provinceFk`), + CONSTRAINT `townProvinceFk` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=241176 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`town_beforeInsert` + BEFORE INSERT ON `town` FOR EACH ROW +BEGIN + SET NEW.geoFk = zoneGeo_new('town', NEW.`name`, + (SELECT geoFk FROM province WHERE id = NEW.provinceFk)); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `town_beforeUpdate` + BEFORE UPDATE ON `town` FOR EACH ROW +BEGIN + IF !(OLD.geoFk <=> NEW.geoFk) THEN + CALL zoneGeo_throwNotEditable; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`town_afterUpdate` + AFTER UPDATE ON `town` FOR EACH ROW +BEGIN + IF !(OLD.provinceFk <=> NEW.provinceFk) THEN + CALL zoneGeo_setParent(NEW.geoFk, + (SELECT geoFk FROM province WHERE id = NEW.provinceFk)); + END IF; + + IF !(OLD.`name` <=> NEW.`name`) THEN + UPDATE zoneGeo SET `name` = NEW.`name` + WHERE id = NEW.geoFk; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`town_afterDelete` + AFTER DELETE ON `town` FOR EACH ROW +BEGIN + CALL zoneGeo_delete(OLD.geoFk); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `trainingCenter` +-- + +DROP TABLE IF EXISTS `trainingCenter`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `trainingCenter` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `trainingCourse` +-- + +DROP TABLE IF EXISTS `trainingCourse`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `trainingCourse` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `workerFk` int(11) NOT NULL, + `trainingCourseTypeFk` int(11) NOT NULL, + `centerFk` int(11) DEFAULT NULL, + `started` datetime NOT NULL, + `ended` datetime NOT NULL, + `invoice` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `amount` double DEFAULT NULL, + `remark` longtext COLLATE utf8_unicode_ci, + `hasDiscount` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `frgnWorker_idx` (`workerFk`), + KEY `frgnCenter_idx` (`centerFk`), + KEY `frgnTrainingCourseType_idx` (`trainingCourseTypeFk`), + CONSTRAINT `frgnCenter` FOREIGN KEY (`centerFk`) REFERENCES `trainingCenter` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `frgnTrainingCourseType` FOREIGN KEY (`trainingCourseTypeFk`) REFERENCES `trainingCourseType` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `frgnWorker` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=452 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de trabajadores que han realizado una formación'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `trainingCourseType` +-- + +DROP TABLE IF EXISTS `trainingCourseType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `trainingCourseType` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de las formaciones'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `travel` +-- + +DROP TABLE IF EXISTS `travel`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `travel` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `shipped` date DEFAULT NULL, + `shipmentHour` time DEFAULT NULL, + `landed` date NOT NULL, + `landingHour` time DEFAULT NULL, + `warehouseInFk` smallint(6) unsigned DEFAULT NULL, + `warehouseOutFk` smallint(6) unsigned DEFAULT NULL, + `agencyFk` int(11) DEFAULT NULL, + `ref` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, + `isDelivered` tinyint(1) NOT NULL DEFAULT '0', + `isReceived` tinyint(1) NOT NULL DEFAULT '0', + `m3` decimal(10,2) unsigned DEFAULT NULL, + `kg` decimal(10,0) unsigned DEFAULT NULL, + `cargoSupplierFk` int(11) DEFAULT NULL, + `totalEntries` tinyint(4) unsigned DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `shipment_2` (`shipped`,`landed`,`warehouseInFk`,`warehouseOutFk`,`agencyFk`,`ref`), + KEY `agency_id` (`agencyFk`), + KEY `shipment` (`shipped`), + KEY `landing` (`landed`), + KEY `warehouse_landing` (`warehouseInFk`,`landed`), + KEY `warehouse_out_shipment` (`warehouseOutFk`,`shipped`), + KEY `travel_ibfk_4_idx` (`cargoSupplierFk`), + CONSTRAINT `travel_ibfk_1` FOREIGN KEY (`warehouseInFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `travel_ibfk_2` FOREIGN KEY (`warehouseOutFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `travel_ibfk_3` FOREIGN KEY (`agencyFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE, + CONSTRAINT `travel_ibfk_4` FOREIGN KEY (`cargoSupplierFk`) REFERENCES `vn2008`.`Proveedores_cargueras` (`Id_Proveedor`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=143498 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `travel_beforeInsert` + BEFORE INSERT ON `travel` + FOR EACH ROW +BEGIN + CALL travel_checkDates(NEW.shipped, NEW.landed); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `travel_beforeUpdate` + BEFORE UPDATE ON `travel` + FOR EACH ROW +BEGIN + IF !(NEW.landed <=> OLD.landed) + OR !(NEW.shipped <=> OLD.shipped) THEN + CALL travel_checkDates(NEW.shipped, NEW.landed); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `travel_afterUpdate` + AFTER UPDATE ON `travel` + FOR EACH ROW +BEGIN + CALL stock.log_add('travel', NEW.id, OLD.id); + + IF !(NEW.shipped <=> OLD.shipped) THEN + UPDATE entry + SET commission = entry_getCommission(travelFk, currencyFk,supplierFk) + WHERE travelFk = NEW.id; + END IF; + + IF !(ABS(NEW.isDelivered) <=> ABS(OLD.isDelivered)) + THEN + INSERT INTO vn2008.travel_dits SET + idaccion_dits = 89, + Id_Trabajador = myWorker_getId(), + Id_Ticket = NEW.id, + value_old = OLD.isDelivered, + value_new = NEW.isDelivered; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `travelObservation` +-- + +DROP TABLE IF EXISTS `travelObservation`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `travelObservation` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `originFk` int(11) NOT NULL, + `userFk` int(11) NOT NULL, + `description` text COLLATE utf8_unicode_ci NOT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Observaciones de travel'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `travelRecalc` +-- + +DROP TABLE IF EXISTS `travelRecalc`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `travelRecalc` ( + `travelFk` int(10) unsigned NOT NULL, + PRIMARY KEY (`travelFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Travels to recalc it''s entry count'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `travelThermograph` +-- + +DROP TABLE IF EXISTS `travelThermograph`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `travelThermograph` ( + `thermographFk` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `created` date NOT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL, + `travelFk` int(10) unsigned DEFAULT NULL, + `temperature` enum('COOL','WARM') COLLATE utf8_unicode_ci NOT NULL, + `result` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `dmsFk` int(11) DEFAULT NULL, + PRIMARY KEY (`thermographFk`,`created`), + KEY `thermograph_fk_idx` (`thermographFk`), + KEY `gestdoc_fk_idx` (`dmsFk`), + KEY `travel_id` (`travelFk`), + KEY `warehouse_id` (`warehouseFk`), + CONSTRAINT `travelThermographDmsFgn` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON UPDATE CASCADE, + CONSTRAINT `travelThermographThermographFgn` FOREIGN KEY (`thermographFk`) REFERENCES `vn2008`.`thermograph` (`thermograph_id`) ON UPDATE CASCADE, + CONSTRAINT `travelThermographTravelFgn` FOREIGN KEY (`travelFk`) REFERENCES `travel` (`id`), + CONSTRAINT `travelThermographWarehouseFgn` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Registra cada termografo que se ha introducido en cada travel'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `user` +-- + +DROP TABLE IF EXISTS `user`; +/*!50001 DROP VIEW IF EXISTS `user`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `user` AS SELECT + 1 AS `id`, + 1 AS `name`, + 1 AS `password`, + 1 AS `role`, + 1 AS `active`, + 1 AS `recoverPass`, + 1 AS `lastPassChange`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `userConfig` +-- + +DROP TABLE IF EXISTS `userConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `userConfig` ( + `userFk` int(10) unsigned NOT NULL, + `warehouseFk` smallint(6) DEFAULT NULL, + `companyFk` smallint(5) unsigned DEFAULT NULL, + `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `updated` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`userFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Configuración de usuario en Salix'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vehicle` +-- + +DROP TABLE IF EXISTS `vehicle`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `vehicle` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `numberPlate` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `model` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + `tradeMark` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + `companyFk` smallint(5) unsigned NOT NULL DEFAULT '442', + `m3` double DEFAULT NULL, + `isActive` tinyint(4) NOT NULL DEFAULT '1', + `warehouseFk` smallint(6) unsigned DEFAULT NULL, + `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `deliveryPointFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `empresa_id` (`companyFk`), + KEY `provinceFk_idx` (`warehouseFk`), + KEY `vehicle_deliveryPointFk_idx` (`deliveryPointFk`), + CONSTRAINT `provinceFk` FOREIGN KEY (`warehouseFk`) REFERENCES `province` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `vehicle_deliveryPointFk` FOREIGN KEY (`deliveryPointFk`) REFERENCES `deliveryPoint` (`id`) ON UPDATE CASCADE, + CONSTRAINT `vehicle_ibfk_1` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=453 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `warehouse` +-- + +DROP TABLE IF EXISTS `warehouse`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `warehouse` ( + `id` smallint(6) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + `isFeedStock` tinyint(1) unsigned NOT NULL DEFAULT '0', + `addressName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `delay` double NOT NULL DEFAULT '0.004', + `hasAvailable` tinyint(4) NOT NULL DEFAULT '0', + `isForTicket` tinyint(2) unsigned zerofill NOT NULL DEFAULT '00', + `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1', + `labelZone` tinyint(4) NOT NULL DEFAULT '0', + `hasComission` tinyint(4) NOT NULL DEFAULT '0', + `isInventory` tinyint(2) NOT NULL DEFAULT '0', + `isComparative` tinyint(2) NOT NULL DEFAULT '0' COMMENT 'Si esta a true,en la comparativa muestra el stock de este almacen, cuando no se especifica almacen.', + `valuatedInventory` tinyint(2) NOT NULL DEFAULT '0' COMMENT 'Determina si se incluye en el informe de inventario valorado', + `isManaged` tinyint(2) NOT NULL DEFAULT '0' COMMENT 'Se añaden los cubos de expedition a la tabla ticketPackaging', + `hasConfectionTeam` tinyint(1) unsigned NOT NULL DEFAULT '0', + `hasStowaway` tinyint(1) NOT NULL DEFAULT '0', + `hasDms` tinyint(1) NOT NULL DEFAULT '0', + `pickUpAgencyModeFk` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name_UNIQUE` (`name`), + KEY `Id_Paises` (`countryFk`), + KEY `isComparativeIdx` (`isComparative`), + CONSTRAINT `warehouse_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=58 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `warehouse_afterInsert` AFTER INSERT ON `warehouse` FOR EACH ROW +BEGIN + IF NEW.isFeedStock THEN + INSERT INTO warehouseAlias(`name`) VALUES(NEW.`name`); + INSERT INTO warehouseJoined(warehouseFk, warehouseAliasFk) + VALUES(NEW.id,LAST_INSERT_ID()); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `warehouse_afterUpdate` AFTER UPDATE ON `warehouse` FOR EACH ROW +BEGIN + IF NEW.isFeedStock IS TRUE and OLD.isFeedStock IS FALSE then + INSERT INTO warehouseAlias(`name`) VALUES(NEW.`name`); + INSERT INTO warehouseJoined(warehouseFk, warehouseAliasFk) + VALUES(NEW.id,LAST_INSERT_ID()); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `warehouseAlias` +-- + +DROP TABLE IF EXISTS `warehouseAlias`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `warehouseAlias` ( + `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workCenter` +-- + +DROP TABLE IF EXISTS `workCenter`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workCenter` ( + `id` int(11) NOT NULL DEFAULT '0', + `name` varchar(255) DEFAULT NULL, + `payrollCenterFk` int(11) DEFAULT NULL, + `counter` bigint(20) DEFAULT NULL, + `warehouseFk` smallint(6) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workCenterHoliday` +-- + +DROP TABLE IF EXISTS `workCenterHoliday`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workCenterHoliday` ( + `workCenterFk` int(11) NOT NULL, + `days` double NOT NULL, + `year` smallint(6) NOT NULL, + PRIMARY KEY (`workCenterFk`,`year`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `worker` +-- + +DROP TABLE IF EXISTS `worker`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `worker` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `code` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `firstName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `lastName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `password` varchar(50) CHARACTER SET utf8 DEFAULT NULL, + `email` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `extension` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `sub` int(11) unsigned DEFAULT NULL, + `user` varchar(20) CHARACTER SET utf8 DEFAULT NULL, + `typeBussines` varchar(30) CHARACTER SET utf8 DEFAULT 'no dejar vacio' COMMENT 'campo obsoleto, actualmente se rellena en laboral', + `laborCategory` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `started` datetime DEFAULT NULL, + `ended` datetime DEFAULT NULL, + `notes` varchar(254) COLLATE utf8_unicode_ci DEFAULT NULL, + `photo` blob, + `fi` varchar(9) COLLATE utf8_unicode_ci DEFAULT NULL, + `address` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `birthed` date NOT NULL, + `maritalStatus` enum('soltero/a','casado/a') COLLATE utf8_unicode_ci NOT NULL, + `phone` varchar(9) COLLATE utf8_unicode_ci NOT NULL, + `companyFk` smallint(5) unsigned NOT NULL, + `clientFk` int(11) DEFAULT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `bossFk` int(11) NOT NULL DEFAULT '2', + `fiDueDate` datetime DEFAULT NULL, + `hasMachineryAutorized` tinyint(2) DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `CodigoTrabajador_UNIQUE` (`code`), + UNIQUE KEY `user` (`user`), + UNIQUE KEY `user_id_UNIQUE` (`userFk`), + UNIQUE KEY `Id_Cliente_Interno` (`clientFk`), + KEY `sub` (`sub`), + KEY `boss_idx` (`bossFk`), + KEY `empresa_id` (`companyFk`), + CONSTRAINT `Clientes` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE, + CONSTRAINT `worker_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=101330 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`worker_beforeInsert` + BEFORE INSERT ON `worker` FOR EACH ROW +BEGIN + IF NEW.password = '' THEN + SET NEW.password = 'FALLO'; + END IF; + + SET NEW.id = 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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`worker_beforeUpdate` + BEFORE UPDATE ON `worker` FOR EACH ROW +BEGIN + IF NEW.password = '' THEN + SET NEW.password = 'FALLO'; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `workerBosses` +-- + +DROP TABLE IF EXISTS `workerBosses`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerBosses` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `workerFk` int(11) NOT NULL, + `bossFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `workerFk_UNIQUE` (`workerFk`,`bossFk`), + KEY `fg_worker_worker_idx` (`workerFk`), + KEY `fg_bossFk_worker_idx` (`bossFk`), + CONSTRAINT `fg_bossFk_worker` FOREIGN KEY (`bossFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fg_workerFk_worker` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2515 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `workerCalendar` +-- + +DROP TABLE IF EXISTS `workerCalendar`; +/*!50001 DROP VIEW IF EXISTS `workerCalendar`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `workerCalendar` AS SELECT + 1 AS `businessFk`, + 1 AS `workerFk`, + 1 AS `absenceTypeFk`, + 1 AS `dated`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `workerClockLog` +-- + +DROP TABLE IF EXISTS `workerClockLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerClockLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(11) NOT NULL, + `userFk` int(10) unsigned NOT NULL, + `action` set('insert','update','delete','select') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `logWorkerClockoriginFk` (`originFk`), + KEY `logWorkerClockuserFk` (`userFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workerConfig` +-- + +DROP TABLE IF EXISTS `workerConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerConfig` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `defaultWorkerFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `defaultWorkerFk` (`defaultWorkerFk`), + CONSTRAINT `workerConfig_ibfk_1` FOREIGN KEY (`defaultWorkerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `workerDepartment` +-- + +DROP TABLE IF EXISTS `workerDepartment`; +/*!50001 DROP VIEW IF EXISTS `workerDepartment`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `workerDepartment` AS SELECT + 1 AS `workerFk`, + 1 AS `departmentFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `workerDocument` +-- + +DROP TABLE IF EXISTS `workerDocument`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerDocument` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `worker` int(10) unsigned DEFAULT NULL, + `document` int(11) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `workerDocument_ibfk_1` (`worker`), + KEY `workerDocument_ibfk_2` (`document`), + CONSTRAINT `workerDocument_ibfk_1` FOREIGN KEY (`worker`) REFERENCES `worker` (`userFk`) ON UPDATE CASCADE, + CONSTRAINT `workerDocument_ibfk_2` FOREIGN KEY (`document`) REFERENCES `dms` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=12993 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workerEmergencyBoss` +-- + +DROP TABLE IF EXISTS `workerEmergencyBoss`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerEmergencyBoss` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `value` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Table to save all responsible people phones', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workerHourPrice` +-- + +DROP TABLE IF EXISTS `workerHourPrice`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerHourPrice` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `hollidayInc` decimal(4,2) DEFAULT NULL, + `nightInc` decimal(4,2) DEFAULT NULL, + `extraInc` decimal(4,2) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Recoge los acuerdos de los distintos convenios'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workerJourney` +-- + +DROP TABLE IF EXISTS `workerJourney`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerJourney` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `userFk` int(10) unsigned NOT NULL, + `dated` date NOT NULL, + `total` decimal(5,2) NOT NULL DEFAULT '0.00', + `priceOrdinaryHour` decimal(5,2) NOT NULL DEFAULT '0.00', + `nocturn` decimal(5,2) NOT NULL DEFAULT '0.00', + `priceNocturnHour` decimal(5,2) NOT NULL DEFAULT '0.00', + `hollyday` decimal(5,2) NOT NULL DEFAULT '0.00', + `priceHollydayHour` decimal(5,2) NOT NULL DEFAULT '0.00', + `lunch` decimal(5,2) NOT NULL DEFAULT '0.00', + `priceExtraHour` decimal(5,2) NOT NULL DEFAULT '0.00', + `extra` decimal(5,2) NOT NULL DEFAULT '0.00', + `contractJourney` decimal(5,2) NOT NULL DEFAULT '0.00', + `priceExtraHollyday` decimal(5,2) NOT NULL DEFAULT '0.00', + `businessFk` int(11) DEFAULT NULL, + `isPaid` tinyint(1) NOT NULL DEFAULT '0', + `isUpdated` tinyint(1) NOT NULL DEFAULT '0', + `permission` decimal(5,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`id`), + UNIQUE KEY `userFk_UNIQUE` (`userFk`,`dated`), + KEY `fk_workerJourney_user_idx` (`userFk`), + CONSTRAINT `fk_workerJourney_user` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=66128753 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `workerLabour` +-- + +DROP TABLE IF EXISTS `workerLabour`; +/*!50001 DROP VIEW IF EXISTS `workerLabour`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `workerLabour` AS SELECT + 1 AS `businessFk`, + 1 AS `workerFk`, + 1 AS `workCenterFk`, + 1 AS `started`, + 1 AS `ended`, + 1 AS `departmentFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `workerLog` +-- + +DROP TABLE IF EXISTS `workerLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(11) NOT NULL, + `userFk` int(10) unsigned NOT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `workerFk_idx` (`originFk`), + KEY `userFk_idx` (`userFk`), + CONSTRAINT `userFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `workerFk` FOREIGN KEY (`originFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=16400 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workerMana` +-- + +DROP TABLE IF EXISTS `workerMana`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerMana` ( + `workerFk` int(11) NOT NULL, + `size` int(11) NOT NULL DEFAULT '300', + `amount` int(11) NOT NULL DEFAULT '0', + `pricesModifierRate` double NOT NULL DEFAULT '0', + `isPricesModifierActivated` tinyint(1) NOT NULL DEFAULT '1', + `minRate` decimal(3,2) NOT NULL DEFAULT '-0.05', + `maxRate` decimal(3,2) NOT NULL DEFAULT '0.05', + PRIMARY KEY (`workerFk`), + KEY `fk_mana_spellers_Trabajadores_idx` (`workerFk`), + CONSTRAINT `fk_mana_spellers_Trabajadores` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `workerMana__` +-- + +DROP TABLE IF EXISTS `workerMana__`; +/*!50001 DROP VIEW IF EXISTS `workerMana__`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `workerMana__` AS SELECT + 1 AS `workerFk`, + 1 AS `size`, + 1 AS `amount`, + 1 AS `pricesModifierRate`, + 1 AS `isPricesModifierActivated`, + 1 AS `minRate`, + 1 AS `maxRate`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `workerMedia` +-- + +DROP TABLE IF EXISTS `workerMedia`; +/*!50001 DROP VIEW IF EXISTS `workerMedia`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `workerMedia` AS SELECT + 1 AS `workerFk`, + 1 AS `mediaValue`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `workerTeam` +-- + +DROP TABLE IF EXISTS `workerTeam`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerTeam` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `team` int(11) NOT NULL, + `workerFk` int(10) unsigned NOT NULL, + PRIMARY KEY (`id`), + KEY `user_idx` (`workerFk`), + KEY `team_idx` (`team`), + CONSTRAINT `user_team` FOREIGN KEY (`workerFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=261 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `workerTeamCollegues` +-- + +DROP TABLE IF EXISTS `workerTeamCollegues`; +/*!50001 DROP VIEW IF EXISTS `workerTeamCollegues`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `workerTeamCollegues` AS SELECT + 1 AS `workerFk`, + 1 AS `collegueFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `workerTimeControl` +-- + +DROP TABLE IF EXISTS `workerTimeControl`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerTimeControl` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `userFk` int(10) unsigned NOT NULL, + `timed` datetime NOT NULL, + `manual` tinyint(4) NOT NULL DEFAULT '0', + `order` int(11) DEFAULT NULL, + `warehouseFk` smallint(6) unsigned DEFAULT NULL, + `direction` enum('in','out','middle') COLLATE utf8_unicode_ci DEFAULT 'middle', + PRIMARY KEY (`id`), + UNIQUE KEY `userFk_Timed_uniq` (`userFk`,`timed`), + KEY `warehouseFkfk1_idx` (`warehouseFk`), + CONSTRAINT `warehouseFk_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `workerTimeControl_fk1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=8313026 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Fichadas'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workerTimeControlConfig` +-- + +DROP TABLE IF EXISTS `workerTimeControlConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerTimeControlConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `warehouseFk` smallint(6) unsigned NOT NULL, + `host` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `warehouseFk_1_idx` (`warehouseFk`), + CONSTRAINT `warehouseFk_2` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workerTimeControlLog` +-- + +DROP TABLE IF EXISTS `workerTimeControlLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerTimeControlLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `userFk` int(10) NOT NULL, + `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Log de fichadas, se rellena cuando el fichador(tablet) no autoriza el fichaje (PROC:vn.workerTimeControl_check)'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workerTimeControlParams` +-- + +DROP TABLE IF EXISTS `workerTimeControlParams`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerTimeControlParams` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dayBreak` int(11) NOT NULL, + `weekBreak` int(11) NOT NULL, + `weekScope` int(11) NOT NULL, + `dayWorkMax` int(11) NOT NULL, + `dayStayMax` int(11) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='All values in seconds'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workerTimeControlPin` +-- + +DROP TABLE IF EXISTS `workerTimeControlPin`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerTimeControlPin` ( + `workerFk` int(11) NOT NULL, + `pin` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`workerFk`), + CONSTRAINT `workerFk_.1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workerTimeControlSchedule` +-- + +DROP TABLE IF EXISTS `workerTimeControlSchedule`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workerTimeControlSchedule` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `time` time DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `punique_trhf` (`time`) +) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary view structure for view `workerTimeControlUserInfo` +-- + +DROP TABLE IF EXISTS `workerTimeControlUserInfo`; +/*!50001 DROP VIEW IF EXISTS `workerTimeControlUserInfo`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `workerTimeControlUserInfo` AS SELECT + 1 AS `userFk`, + 1 AS `name`, + 1 AS `surname`, + 1 AS `user`, + 1 AS `password`, + 1 AS `bcryptPassword`, + 1 AS `departmentFk`, + 1 AS `dni`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `workerTimeControlWorking` +-- + +DROP TABLE IF EXISTS `workerTimeControlWorking`; +/*!50001 DROP VIEW IF EXISTS `workerTimeControlWorking`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `workerTimeControlWorking` AS SELECT + 1 AS `userFk`, + 1 AS `timed`, + 1 AS `name`, + 1 AS `surname`, + 1 AS `phone`, + 1 AS `workerPhone`, + 1 AS `department`, + 1 AS `workerCenter`, + 1 AS `maxOrder`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `workerTimeControl_Journey` +-- + +DROP TABLE IF EXISTS `workerTimeControl_Journey`; +/*!50001 DROP VIEW IF EXISTS `workerTimeControl_Journey`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `workerTimeControl_Journey` AS SELECT + 1 AS `userFk`, + 1 AS `dated`, + 1 AS `Journey`, + 1 AS `dayName`, + 1 AS `name`, + 1 AS `firstname`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary view structure for view `workerTimeJourneyNG` +-- + +DROP TABLE IF EXISTS `workerTimeJourneyNG`; +/*!50001 DROP VIEW IF EXISTS `workerTimeJourneyNG`*/; +SET @saved_cs_client = @@character_set_client; +/*!50503 SET character_set_client = utf8mb4 */; +/*!50001 CREATE VIEW `workerTimeJourneyNG` AS SELECT + 1 AS `userFk`, + 1 AS `dated`, + 1 AS `Journey`, + 1 AS `dayName`, + 1 AS `name`, + 1 AS `firstname`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `workers20190711` +-- + +DROP TABLE IF EXISTS `workers20190711`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workers20190711` ( + `person_id` int(11) NOT NULL DEFAULT '0', + `business_id` int(11) NOT NULL DEFAULT '0', + `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL, + `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL, + `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL, + `Fecha_Inicio` date DEFAULT NULL, + `Fecha_Fin` date DEFAULT NULL, + `departamento` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `Jornada_Semanal` smallint(6) DEFAULT NULL, + `Codigo_Contrato` int(11) DEFAULT NULL, + `userFk` int(11) NOT NULL, + PRIMARY KEY (`person_id`), + UNIQUE KEY `userFk_UNIQUE` (`userFk`), + UNIQUE KEY `nif_UNIQUE` (`nif`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workers20190711_FichadasAbril` +-- + +DROP TABLE IF EXISTS `workers20190711_FichadasAbril`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workers20190711_FichadasAbril` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `person_id` int(11) NOT NULL DEFAULT '0', + `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL, + `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL, + `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL, + `Fecha` date DEFAULT NULL, + `Hora` int(2) DEFAULT NULL, + `Minuto` int(2) DEFAULT NULL, + `sumable` double DEFAULT NULL, + `jornada` decimal(5,2) NOT NULL DEFAULT '8.00', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=8171 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workers20190711_FichadasJulio11` +-- + +DROP TABLE IF EXISTS `workers20190711_FichadasJulio11`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workers20190711_FichadasJulio11` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `person_id` int(11) NOT NULL DEFAULT '0', + `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL, + `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL, + `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL, + `Fecha` date DEFAULT NULL, + `Hora` int(2) DEFAULT NULL, + `Minuto` int(2) DEFAULT NULL, + `sumable` double DEFAULT NULL, + `jornada` decimal(5,2) NOT NULL DEFAULT '8.00', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=328 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workers20190711_FichadasJunio` +-- + +DROP TABLE IF EXISTS `workers20190711_FichadasJunio`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workers20190711_FichadasJunio` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `person_id` int(11) NOT NULL DEFAULT '0', + `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL, + `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL, + `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL, + `Fecha` date DEFAULT NULL, + `Hora` int(2) DEFAULT NULL, + `Minuto` int(2) DEFAULT NULL, + `sumable` double DEFAULT NULL, + `jornada` decimal(5,2) NOT NULL DEFAULT '8.00', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=6936 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workers20190711_FichadasMayo` +-- + +DROP TABLE IF EXISTS `workers20190711_FichadasMayo`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workers20190711_FichadasMayo` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `person_id` int(11) NOT NULL DEFAULT '0', + `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL, + `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL, + `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL, + `Fecha` date DEFAULT NULL, + `Hora` int(2) DEFAULT NULL, + `Minuto` int(2) DEFAULT NULL, + `sumable` double DEFAULT NULL, + `jornada` decimal(5,2) NOT NULL DEFAULT '8.00', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=7855 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workers20190711_FichadasOctubre` +-- + +DROP TABLE IF EXISTS `workers20190711_FichadasOctubre`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workers20190711_FichadasOctubre` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `person_id` int(11) NOT NULL DEFAULT '0', + `nif` varchar(15) CHARACTER SET utf8 DEFAULT NULL, + `Apellidos` varchar(60) CHARACTER SET utf8 NOT NULL, + `Nombre` varchar(20) CHARACTER SET utf8 DEFAULT NULL, + `Fecha` date DEFAULT NULL, + `Hora` int(2) DEFAULT NULL, + `Minuto` int(2) DEFAULT NULL, + `sumable` double DEFAULT NULL, + `jornada` decimal(5,2) NOT NULL DEFAULT '8.00', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=7419 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `workingHours` +-- + +DROP TABLE IF EXISTS `workingHours`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `workingHours` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `timeIn` datetime NOT NULL, + `timeOut` datetime DEFAULT NULL, + `userId` int(10) unsigned NOT NULL, + PRIMARY KEY (`id`), + KEY `user_working_hour_idx` (`userId`), + CONSTRAINT `user_working_hour` FOREIGN KEY (`userId`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=23782 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena horas de Entrada y de Salida del personal'; +/*!40101 SET character_set_client = @saved_cs_client */; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`workingHoursBeforeInsert` BEFORE INSERT ON `workingHours` FOR EACH ROW +BEGIN + IF (SELECT COUNT(*) FROM workingHours WHERE userId = NEW.userId AND DATE(timeIn) = CURDATE()) > 0 THEN + CALL util.throw ('ALREADY_LOGGED'); + 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 */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; + +-- +-- Table structure for table `zone` +-- + +DROP TABLE IF EXISTS `zone`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `zone` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `hour` datetime NOT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL, + `agencyModeFk` int(11) NOT NULL, + `travelingDays` int(11) NOT NULL DEFAULT '1', + `price` double NOT NULL DEFAULT '0', + `bonus` double NOT NULL DEFAULT '0', + `isVolumetric` tinyint(1) NOT NULL DEFAULT '0', + `inflation` decimal(5,2) NOT NULL DEFAULT '1.00', + PRIMARY KEY (`id`), + KEY `fk_zone_1_idx` (`warehouseFk`), + KEY `fk_zone_2_idx` (`agencyModeFk`), + KEY `zone_name_idx` (`name`), + CONSTRAINT `fk_zone_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `fk_zone_2` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=491 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `zoneCalendar` +-- + +DROP TABLE IF EXISTS `zoneCalendar`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `zoneCalendar` ( + `zoneFk` int(11) NOT NULL, + `delivered` date NOT NULL, + `price` double NOT NULL, + `bonus` double NOT NULL, + PRIMARY KEY (`zoneFk`,`delivered`), + CONSTRAINT `zoneFk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `zoneGeo` +-- + +DROP TABLE IF EXISTS `zoneGeo`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `zoneGeo` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `type` set('country','province','town','postCode') CHARACTER SET utf8 NOT NULL, + `name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `parentFk` int(10) unsigned DEFAULT NULL, + `path` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `lft` int(11) DEFAULT NULL, + `rgt` int(11) DEFAULT NULL, + `depth` bigint(22) NOT NULL DEFAULT '0', + `sons` decimal(10,0) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `lft_rgt_depth_idx` (`lft`,`rgt`,`depth`), + KEY `name_idx` (`name`), + KEY `parentFk` (`parentFk`), + KEY `path` (`path`) +) ENGINE=InnoDB AUTO_INCREMENT=597479 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`zoneGeo_beforeInsert` + BEFORE INSERT ON `zoneGeo` FOR EACH ROW +BEGIN + CALL zoneGeo_checkName(NEW.`name`); +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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`zoneGeo_beforeUpdate` + BEFORE UPDATE ON `zoneGeo` FOR EACH ROW +BEGIN + IF !(OLD.`name` <=> NEW.`name`) THEN + CALL zoneGeo_checkName(NEW.`name`); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `zoneGeoRecalc` +-- + +DROP TABLE IF EXISTS `zoneGeoRecalc`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `zoneGeoRecalc` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `isChanged` tinyint(4) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `zoneIncluded` +-- + +DROP TABLE IF EXISTS `zoneIncluded`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `zoneIncluded` ( + `zoneFk` int(11) NOT NULL, + `geoFk` int(11) NOT NULL, + `isIncluded` tinyint(1) DEFAULT NULL, + PRIMARY KEY (`zoneFk`,`geoFk`), + KEY `geoFk_idx` (`geoFk`), + CONSTRAINT `zoneFk2` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `zoneGeoFk2` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'vn' +-- +/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; +/*!50106 DROP EVENT IF EXISTS `envialiaThreHoldChecker` */; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `envialiaThreHoldChecker` ON SCHEDULE EVERY 1 DAY STARTS '2019-02-07 07:00:00' ON COMPLETION NOT PRESERVE ENABLE COMMENT 'comprueba el rango de numeros para las etiquetas de envialia' DO BEGIN + DECLARE vActualNumber BIGINT; + DECLARE vEndRange BIGINT; + DECLARE vIsAlreadyNotified BOOLEAN; + DECLARE vNotificationThrehold INT; + + SELECT actualNumber, endRange, isAlreadyNotified, notificationThrehold + INTO vActualNumber, vEndRange, vIsAlreadyNotified, vNotificationThrehold + FROM envialiaConfig; + + IF (vActualNumber+vNotificationThrehold) >= vEndRange AND + vIsAlreadyNotified = FALSE + THEN + INSERT INTO vn2008.mail (`to`, subject, text) + VALUES ('cau@verdnatura.es', + 'Hablar con envialia, acercandonos al numero final del rango permitido para las etiquetas', + CONCAT('Numero actual: ', vActualNumber, ' , numero final: ',vEndRange)); + UPDATE envialiaConfig SET isAlreadyNotified = TRUE; + END IF; + + IF (vActualNumber+vNotificationThrehold) < vEndRange AND + vIsAlreadyNotified = TRUE + THEN + UPDATE envialiaConfig SET isAlreadyNotified = FALSE; + END IF; + +END */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!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 `printQueue_check` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN + + DECLARE vCurrentCount INT; + DECLARE vCheckSum INT; + DECLARE vIsAlreadyNotified BOOLEAN; + DECLARE vTableQueue TEXT; + DECLARE vLineQueue TEXT; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vCur CURSOR FOR + SELECT CONCAT(' + ', IFNULL(pq.id, ''), ' + ', IFNULL(p.path, ''),' + ', IFNULL(i.Informe, ''),' + ', IFNULL(e.Estado, ''),' + ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' + ', IFNULL(pq.`error`, ''),' + ') + FROM vn.printingQueue pq + LEFT JOIN vn.worker w ON w.id = pq.worker + LEFT JOIN vn.printer p ON p.id = pq.printer + LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report + JOIN vn2008.Estados e ON e.Id_Estado = pq.state + LIMIT 30; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum + FROM vn.printingQueue WHERE state = 1; + + SELECT isAlreadyNotified INTO vIsAlreadyNotified + FROM printingQueueCheck; + + IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND + (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND + vIsAlreadyNotified = FALSE AND vCurrentCount > 0 + THEN + + SELECT ' + + + + + + + + ' INTO vTableQueue; + + OPEN vCur; + + l: LOOP + + SET vDone = FALSE; + + FETCH vCur INTO vLineQueue; + + IF vDone THEN + LEAVE l; + END IF; + + SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; + + END LOOP; + + CLOSE vCur; + + INSERT INTO vn2008.mail (`to`, subject, text) + VALUES ('cau@verdnatura.es', + 'servidor de impresion parado', + CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
    Id ColaRuta ImpresoraInformeEstadoTrabajadorError
    ')); + + UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; + END IF; + + IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND + vIsAlreadyNotified = TRUE + THEN + UPDATE printingQueueCheck SET isAlreadyNotified = FALSE; + END IF; + + UPDATE printingQueueCheck + SET lastCount = vCurrentCount, + lastCheckSum = vCheckSum; + +END */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!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 `ticketClosure` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `ticketClosure` ON SCHEDULE EVERY 1 DAY STARTS '2017-09-18 00:30:00' ON COMPLETION NOT PRESERVE ENABLE COMMENT 'Realiza el cierre de todos los almacenes del dia actual' DO CALL ticketClosureMultiWarehouse(DATE_ADD(CURDATE(), INTERVAL -1 DAY)) */ ;; +/*!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 `travel_doRecalc` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `travel_doRecalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-05-17 10:52:29' ON COMPLETION PRESERVE ENABLE DO CALL travel_doRecalc */ ;; +/*!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 `zoneGeo_doCalc` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `zoneGeo_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-09-13 15:30:47' ON COMPLETION PRESERVE ENABLE DO CALL vn.zoneGeo_doCalc */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; +DELIMITER ; +/*!50106 SET TIME_ZONE= @save_time_zone */ ; + +-- +-- Dumping routines for database 'vn' +-- +/*!50003 DROP FUNCTION IF EXISTS `addressTaxArea` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `addressTaxArea`(vAddresId INT, vCompanyId INT) RETURNS varchar(25) CHARSET utf8 + DETERMINISTIC +BEGIN +/** + * Devuelve el area de un Consignatario, + * intracomunitario, extracomunitario, nacional o recargo de equivalencia. + * Asumimos que no tenemos ninguna empresa + * + * @param vAddresId Id del Consignatario + * @param vCompanyId Compañia desde la que se factura + * @return Código de area + */ + DECLARE vTaxArea VARCHAR(25); + DECLARE vClientIsUeeMember INT; + DECLARE vSupplierIsUeeMember INT; + DECLARE vSpainCountryCode INT DEFAULT 1; + DECLARE vSupplierCountry INT; + DECLARE vClientCountry INT; + DECLARE vIsEqualizated BOOLEAN; + DECLARE vIsVies BOOLEAN; + + SELECT cClient.isUeeMember, c.countryFk, a.isEqualizated, cSupplier.isUeeMember, s.countryFk, c.isVies + INTO vClientIsUeeMember, vClientCountry, vIsEqualizated, vSupplierIsUeeMember, vSupplierCountry, vIsVies + FROM address a + JOIN `client` c ON c.id = a.clientFk + JOIN country cClient ON cClient.id = c.countryFk + JOIN supplier s ON s.id = vCompanyId + JOIN country cSupplier ON cSupplier.id = s.countryFk + WHERE a.id = vAddresId; + + CASE + WHEN (NOT vClientIsUeeMember OR NOT vSupplierIsUeeMember) AND vSupplierCountry != vClientCountry THEN + SET vTaxArea = 'WORLD'; + WHEN vClientIsUeeMember AND vSupplierIsUeeMember AND vClientCountry != vSupplierCountry AND vIsVies THEN + SET vTaxArea = 'CEE'; + WHEN vIsEqualizated AND vClientCountry = vSpainCountryCode THEN + SET vTaxArea = 'EQU'; + ELSE + SET vTaxArea = 'NATIONAL'; + END CASE; + + RETURN vTaxArea; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `barcodeToItem` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `barcodeToItem`(vBarcode VARCHAR(22)) RETURNS int(11) + DETERMINISTIC +BEGIN + + DECLARE vItemFk INT; + + SELECT id INTO vItemFk + FROM vn.item + WHERE id = vBarcode; + + IF vItemFk THEN + RETURN vItemFk; + END IF; + + SELECT itemFk INTO vItemFk + FROM buy + WHERE id = vBarcode; + + IF vItemFk THEN + RETURN vItemFk; + END IF; + + SELECT itemFk INTO vItemFk + FROM itemBarcode + WHERE code = vBarcode; + + RETURN 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 DROP FUNCTION IF EXISTS `bionicCalcReverse` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `bionicCalcReverse`(vWarehouse INT, + vMargin DECIMAL(10,3), + vRetailedPrice DECIMAL(10,3), + vM3 DECIMAL(10,3), + vConsigna INT, + vAgencia INT) RETURNS decimal(10,3) + DETERMINISTIC +BEGIN + -- BERNAT: WORKING IN THIS FILE + DECLARE COEFICIENTE_DE_INFLACION_GENERAL INT DEFAULT 1.3; + DECLARE DENSIDAD_MINIMA_PESO_VOLUMETRICO INT DEFAULT 167; + DECLARE VOLUMEN_CAJA_VERDNATURA BIGINT DEFAULT 138000; + DECLARE vCustomer INT; + DECLARE vComponentRecovery INT DEFAULT 17; + DECLARE vComponentMana INT DEFAULT 39; + DECLARE vComponentPort INT DEFAULT 15; + DECLARE vComponentMargin INT DEFAULT 29; + DECLARE vComponentCost INT DEFAULT 28; + DECLARE vCost DECIMAL(10,2); + DECLARE vItem INT DEFAULT 98; + + SELECT clientFk INTO vCustomer FROM address WHERE id = vConsigna; + + -- Creamos la tabla tmp.bionic_component + DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component; + CREATE TEMPORARY TABLE tmp.bionic_component LIKE + vn2008.template_bionic_component; + + -- Margen + INSERT INTO tmp.bionic_component (warehouse_id, item_id, component_id, cost) + SELECT vWarehouse, vItem, vComponentMargin, vMargin; + + -- Recobro + INSERT INTO tmp.bionic_component (warehouse_id, item_id, component_id, cost) + SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3) + FROM bi.claims_ratio + WHERE Id_Cliente = vCustomer AND recobro > 0.009; + + -- Componente de maná automático, en función del maná acumulado por el comercial. + INSERT INTO tmp.bionic_component (warehouse_id, item_id, component_id, cost) + SELECT vWarehouse, vItem, vComponentMana, ROUND(prices_modifier_rate, 3) + FROM client c + JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador + WHERE ms.prices_modifier_activated AND c.id = vCustomer LIMIT 1; + + -- Reparto + INSERT INTO tmp.bionic_component (warehouse_id, item_id, component_id, cost) + SELECT vWarehouse, vItem, vComponentPort, COEFICIENTE_DE_INFLACION_GENERAL + * ROUND( + vM3 + * az.price + * az.inflation + / VOLUMEN_CAJA_VERDNATURA, 4 + ) + FROM agencyMode ag + JOIN address a ON a.id = vConsigna AND ag.id = vAgencia + JOIN agencyProvince ap ON ap.agencyFk = ag.agencyFk AND ap.warehouseFk = vWarehouse AND ap.provinceFk = a.provinceFk + JOIN agencyModeZone az ON az.agencyModeFk = vAgencia AND az.zone = ap.zone AND az.itemFk = 71 AND az.warehouseFk = vWarehouse; + + -- Coste + SELECT vRetailedPrice - SUM(cost) INTO vCost + FROM tmp.bionic_component; + + INSERT INTO tmp.bionic_component (warehouse_id, item_id, component_id, cost) + VALUES ( vWarehouse, vItem, vComponentCost,vCost); + + RETURN vCost; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `botanicExport_isUpdatable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `botanicExport_isUpdatable`(vEdiGenusFk MEDIUMINT,vEdiSpecieFk MEDIUMINT, + vCountryFk MEDIUMINT,vRestriction MEDIUMINT) RETURNS int(11) + DETERMINISTIC +BEGIN + DECLARE vIsUpdatable INTEGER; + SELECT COUNT(*) INTO vIsUpdatable + FROM botanicExport + WHERE ediGenusFk = vEdiGenusFk + AND (vEdiSpecieFk = ediSpecieFk OR IFNULL(vEdiSpecieFk,ediSpecieFk) IS NULL) + AND (vCountryFk = countryFk OR IFNULL(vCountryFk,countryFk) IS NULL) + AND vRestriction = restriction; +RETURN vIsUpdatable; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `buy_getUnitVolume` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `buy_getUnitVolume`(vSelf INT) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Calculates the unit volume occupied by a buy. + * + * @param vSelf The buy id + * @return The unit volume in cubic centimeters + */ + DECLARE vItem INT; + DECLARE vPackaging VARCHAR(10); + DECLARE vPacking INT; + + SELECT itemFk, packageFk, packing + INTO vItem, vPackaging, vPacking + FROM buy + WHERE id = vSelf; + + RETURN IFNULL(ROUND(item_getVolume(vItem, vPackaging) / vPacking), 0); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `buy_getVolume` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `buy_getVolume`(vSelf INT) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Calculates the volume occupied by a buy. + * + * @param vSelf The buy id + * @return The volume in cubic centimeters + */ + DECLARE vItem INT; + DECLARE vPackaging VARCHAR(10); + + SELECT itemFk, packageFk INTO vItem, vPackaging + FROM buy + WHERE id = vSelf; + + RETURN item_getVolume(vItem, vPackaging); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `buy_hasNotifyPassport` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `buy_hasNotifyPassport`(vBuyFk INT, vItemFk INT) RETURNS tinyint(1) + READS SQL DATA +BEGIN + DECLARE vHasPassport BOOL; + DECLARE vIsAlreadySent BOOL; + DECLARE vItemCategoryFk INT; + SELECT id INTO vItemCategoryFk FROM itemCategory WHERE code = 'plant'; + + SELECT COUNT(*) INTO vHasPassport + FROM botanicExport be + JOIN itemBotanical ib + ON be.ediGenusFk = ib.genusFk + AND IFNULL(be.ediSpecieFk, ib.specieFk) = ib.specieFk + AND be.restriction = 'pasaporte fitosanitario' + JOIN item i ON i.id = ib.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE ib.itemFk = vItemFk + AND it.categoryFk = vItemCategoryFk; + + IF vHasPassport THEN + SELECT COUNT(*) INTO vIsAlreadySent + FROM mail m + JOIN buy b ON b.id = vBuyFk + WHERE m.`body` LIKE CONCAT('%', b.ektFk, '%') + LIMIT 1; + END IF; + + RETURN vHasPassport AND NOT vIsAlreadySent; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `catalog_componentReverse` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `catalog_componentReverse`(vWarehouse INT, + vCost DECIMAL(10,3), + vM3 DECIMAL(10,3), + vAddressFk INT, + vZoneFk INT) RETURNS decimal(10,3) + DETERMINISTIC +BEGIN + /* Calcula los componentes para un cliente a partir de un coste y volumen + * @param vWarehouse + * @param vCost Valor de coste del articulo + * @param vM3 m3 del articulo + * @param vAddressFk + * @param vZoneFk + * @return vRetailedPrice precio de venta sin iva + * @return tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) + */ + + DECLARE vBoxVolume BIGINT; + DECLARE vCustomer INT; + DECLARE vComponentRecovery INT DEFAULT 17; + DECLARE vComponentMana INT DEFAULT 39; + DECLARE vDeliveryComponent INT DEFAULT 15; + DECLARE vComponentMargin INT DEFAULT 29; + DECLARE vComponentCost INT DEFAULT 28; + DECLARE vRetailedPrice DECIMAL(10,2); + DECLARE vItem INT DEFAULT 98; + + SELECT volume INTO vBoxVolume + FROM vn.packaging + WHERE id = '94'; + + SELECT clientFk INTO vCustomer FROM address WHERE id = vAddressFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.catalog_component; + CREATE TEMPORARY TABLE tmp.catalog_component ( + `warehouseFk` INT UNSIGNED NOT NULL, + `itemFk` INT NOT NULL, + `componentFk` INT UNSIGNED NOT NULL, + `cost` DECIMAL(10,4) NOT NULL, + INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), + UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)); + + -- Cost + INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) + SELECT vWarehouse, vItem, vComponentCost, vCost + FROM vn.rate + WHERE dated <= CURDATE() + AND warehouseFk = vWarehouse + ORDER BY dated DESC + LIMIT 1; + + -- Margen + INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) + SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost + FROM vn.rate + WHERE dated <= CURDATE() + AND warehouseFk = vWarehouse + ORDER BY dated DESC + LIMIT 1; + + -- Recobro + INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) + SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3) + FROM bi.claims_ratio + WHERE Id_Cliente = vCustomer AND recobro > 0.009; + + -- Componente de maná automático, en función del maná acumulado por el comercial. + INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) + SELECT vWarehouse, vItem, vComponentMana, ROUND(prices_modifier_rate, 3) + FROM client c + JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador + WHERE ms.prices_modifier_activated AND c.id = vCustomer LIMIT 1; + + -- Reparto + INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) + SELECT vWarehouse, vItem, vDeliveryComponent, + ROUND( + vM3 + * (z.price - z.bonus) + * z.inflation + / vBoxVolume, 4 + ) + FROM zone z + WHERE z.id = vZoneFk; + + -- Precio de venta + SELECT SUM(cost) INTO vRetailedPrice + FROM tmp.catalog_component; + + RETURN vRetailedPrice; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `clientGetDebt` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `clientGetDebt`(vClient INT, vDate DATE) RETURNS decimal(10,2) + READS SQL DATA +BEGIN +/** + * Devuelve el saldo de un cliente. + * + * @param vClient Identificador del cliente + * @param vDate Fecha hasta la que tener en cuenta + * @return Saldo del cliente + */ + DECLARE vDateEnd DATETIME; + DECLARE vDateIni DATETIME; + DECLARE vDebt DECIMAL(10,2); + DECLARE vHasDebt BOOLEAN; + + SELECT COUNT(*) INTO vHasDebt + FROM `client` c + WHERE c.id = vClient AND c.typeFk = 'normal'; + + IF NOT vHasDebt THEN + RETURN 0; + END IF; + + SET vDate = IFNULL(vDate, CURDATE()); + + SET vDateIni = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET vDateEnd = TIMESTAMP(vDate, '23:59:59'); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT id ticketFk + FROM ticket + WHERE clientFk = vClient + AND refFk IS NULL + AND shipped BETWEEN vDateIni AND vDateEnd; + + CALL vn.ticketGetTotal; + + SELECT IFNULL(SUM(t.amount), 0) INTO vDebt + FROM ( + SELECT SUM(total) amount + FROM tmp.ticketTotal + UNION ALL + SELECT SUM(amountPaid) + FROM receipt + WHERE clientFk = vClient + AND payed > vDateEnd + UNION ALL + SELECT SUM(amount) + FROM bi.customer_risk r + WHERE customer_id = vClient + UNION ALL + SELECT CAST(-SUM(amount) / 100 AS DECIMAL(10,2)) + FROM hedera.tpvTransaction + WHERE clientFk = vClient + AND receiptFk IS NULL + AND `status` = 'ok' + ) t; + + DROP TEMPORARY TABLE + tmp.ticket, + tmp.ticketTotal; + + RETURN vDebt; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `clientGetMana` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `clientGetMana`(vClient INT) RETURNS decimal(10,2) + READS SQL DATA +BEGIN +/** + * BERNAT: WORKING IN THIS FILE + * Devuelve el maná del cliente. + * + * @param vClient Id del cliente + * @return Maná del cliente + */ + + DECLARE vMana DECIMAL(10,2); + DECLARE vFromDated DATE; + DECLARE vHasMana BOOLEAN; + + SELECT COUNT(*) INTO vHasMana + FROM `client` c + WHERE c.id = vClient AND c.typeFk = 'normal'; + + IF NOT vHasMana THEN + RETURN 0; + END IF; + + SELECT max(dated) INTO vFromDated + FROM vn.clientManaCache; + + SELECT sum(mana) INTO vMana + FROM + ( + SELECT mana + FROM vn.clientManaCache + WHERE clientFk = vClient + AND dated = vFromDated + + UNION ALL + + SELECT s.quantity * Valor + FROM vn.ticket t + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.sale s on s.ticketFk = t.id + JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = s.id + WHERE Id_Componente IN (37, 39) + AND t.shipped > vFromDated + AND t.shipped < TIMESTAMPADD(DAY,1,CURDATE()) + AND a.clientFk = vClient + + UNION ALL + + SELECT - Entregado + FROM vn2008.Recibos r + JOIN vn2008.Clientes c using(Id_Cliente) + WHERE r.Id_Banco = 66 + AND r.Fechacobro > vFromDated + AND r.Fechacobro <= CURDATE() + AND c.Id_Cliente = vClient + + UNION ALL + + SELECT g.Importe + FROM vn2008.Greuges g + JOIN vn2008.Clientes c using(Id_Cliente) + WHERE g.Greuges_type_id = 3 -- Maná + AND g.Fecha > vFromDated + AND g.Fecha <= CURDATE() + AND c.Id_Cliente = vClient + + ) sub; + + RETURN IFNULL(vMana,0); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `clientGetSalesPerson` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `clientGetSalesPerson`(vClientFk INT, vDated DATE) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * DEPRECATED: use client_getSalesPerson + **/ + RETURN client_getSalesPerson(vClientFk, vDated); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `clientTaxArea` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `clientTaxArea`(vClientId INT, vCompanyId INT) RETURNS varchar(25) CHARSET utf8 +BEGIN +/** + * Devuelve el area de un cliente, + * intracomunitario, extracomunitario o nacional. + * + * @param vClient Id del cliente + * @param vCompanyFk Compañia desde la que se factura + * @return Código de area + */ + DECLARE vTaxArea VARCHAR(25); + DECLARE vCee INT; + + SELECT ct.Cee INTO vCee + FROM `client` c + JOIN country ct ON ct.id = c.countryFk + JOIN supplier s ON s.id = vCompanyId + WHERE + c.id = vClientId + AND c.isVies + AND c.countryFk != s.countryFk; + + IF vCee < 2 THEN + SET vTaxArea = 'CEE'; + ELSEIF vCee = 2 THEN + SET vTaxArea = 'WORLD'; + ELSE + SET vTaxArea = 'NATIONAL'; + END IF; + + RETURN vTaxArea; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `client_getFromPhone` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `client_getFromPhone`(vPhone VARCHAR(255)) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Searchs a customer associated to the phone number. + * + * @param vPhone The phone number + * @return The client id or %NULL if not found + */ + DECLARE vClient INT DEFAULT NULL; + + -- SET vPhone = vPhone COLLATE 'utf8_unicode_ci'; + + DROP TEMPORARY TABLE IF EXISTS tClient; + CREATE TEMPORARY TABLE tClient + ENGINE = MEMORY + SELECT id clientFk + FROM `client` + WHERE phone = vPhone + OR mobile = vPhone + UNION + SELECT clientFk + FROM address + WHERE phone = vPhone + OR mobile = vPhone + UNION + SELECT r.id_cliente + FROM vn2008.Relaciones r + JOIN vn2008.Contactos c ON r.Id_Contacto = c.Id_Contacto + WHERE c.telefono = vPhone + OR c.movil = vPhone; + + SELECT t.clientFk INTO vClient + FROM tClient t + JOIN `client` c ON c.id = t.clientFk + WHERE c.isActive + LIMIT 1; + + DROP TEMPORARY TABLE tClient; + + RETURN vClient; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `client_getSalesPerson` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `client_getSalesPerson`(vClientFk INT, vDated DATE) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo + * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de + * sharingcart y tercero la de clientes. + * + * @param vClientFk El id del cliente + * @param vDated Fecha a comprobar + * @return El id del comercial para la fecha dada + **/ + DECLARE vSalesPersonFk INT DEFAULT NULL; + DECLARE vWorkerSubstituteFk INT DEFAULT NULL; + DECLARE vLoop BOOLEAN; + + -- Obtiene el comercial original y el de sharingclient + + SELECT c.salesPersonFk, s.workerFk + INTO vSalesPersonFk, vWorkerSubstituteFk + FROM client c + LEFT JOIN sharingClient s + ON c.id = s.clientFk + AND vDated BETWEEN s.started AND s.ended + WHERE c.id = vClientFk + ORDER BY s.id + LIMIT 1; + + -- Si no hay ninguno en sharingclient busca en sharingcart + + IF vWorkerSubstituteFk IS NOT NULL + THEN + SET vSalesPersonFk = vWorkerSubstituteFk; + ELSEIF vSalesPersonFk IS NOT NULL + THEN + DROP TEMPORARY TABLE IF EXISTS tmp.stack; + CREATE TEMPORARY TABLE tmp.stack + (INDEX (substitute)) + ENGINE = MEMORY + SELECT vSalesPersonFk substitute; + + l: LOOP + SELECT workerSubstitute INTO vWorkerSubstituteFk + FROM sharingCart + WHERE vDated BETWEEN started AND ended + AND workerFk = vSalesPersonFk + ORDER BY id + LIMIT 1; + + IF vWorkerSubstituteFk IS NULL THEN + LEAVE l; + END IF; + + SELECT COUNT(*) > 0 INTO vLoop + FROM tmp.stack WHERE substitute = vWorkerSubstituteFk; + + IF vLoop THEN + LEAVE l; + END IF; + + INSERT INTO tmp.stack SET + substitute = vWorkerSubstituteFk; + + SET vSalesPersonFk = vWorkerSubstituteFk; + END LOOP; + + DROP TEMPORARY TABLE tmp.stack; + END IF; + + RETURN vSalesPersonFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `client_getSalesPersonByTicket` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `client_getSalesPersonByTicket`(vTicketFk INT) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Dado un id ticket, devuelve su comercial. + * Para más información ir a client_getSalesPerson() + * + * @param vClientFk El id del cliente + * @param vDated Fecha a comprobar + * @return El id del comercial para la fecha dada + **/ + DECLARE vClientFk INT; + DECLARE vDated DATE; + + SELECT clientFk, shipped + INTO vClientFk, vDated + FROM ticket WHERE id = vTicketFk; + + RETURN client_getSalesPerson(vClientFk, vDated); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `client_getSalesPersonCode` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `client_getSalesPersonCode`(vClientFk INT, vDated DATE) RETURNS varchar(3) CHARSET utf8 + DETERMINISTIC +BEGIN +/** + * Dado un id cliente y una fecha, devuelve su comercial. + * Para más información ir a client_getSalesPerson() + * + * @param vClientFk El id del cliente + * @param vDated Fecha a comprobar + * @return El código del comercial para la fecha dada + **/ + DECLARE vWorkerCode CHAR(3); + DECLARE vSalesPersonFk INT; + + SET vSalesPersonFk = client_getSalesPerson(vClientFk, vDated); + + SELECT code + INTO vWorkerCode + FROM worker + WHERE id = vSalesPersonFk; + + RETURN vWorkerCode; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `client_getSalesPersonCodeByTicket` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `client_getSalesPersonCodeByTicket`(vTicketFk INT) RETURNS varchar(3) CHARSET utf8 + DETERMINISTIC +BEGIN +/** + * Dado un id ticket, devuelve su comercial. + * Para más información ir a client_getSalesPerson() + * + * @param vClientFk El id del cliente + * @param vDated Fecha a comprobar + * @return El código del comercial para la fecha dada + **/ + DECLARE vClientFk INT; + DECLARE vDated DATE; + + SELECT clientFk, shipped + INTO vClientFk, vDated + FROM ticket WHERE id = vTicketFk; + + RETURN client_getSalesPersonCode(vClientFk, vDated); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `currentRate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `currentRate`(vCurrencyFk INT, vDated DATE) RETURNS decimal(10,4) +BEGIN + + DECLARE curRate DECIMAL(10,4); + + SELECT value INTO curRate + FROM referenceRate + WHERE dated <= vDated + AND currencyFk = vCurrencyFk + ORDER BY dated DESC + LIMIT 1; + +RETURN curRate; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `entry_calcCommission__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `entry_calcCommission__`( + vCurrentCommission INT, + vTravelFk INT, + vCurrencyFk INT +) RETURNS int(11) + READS SQL DATA +BEGIN + -- DEPRECATED: use entry_getComission + DECLARE vCommission INT; + + IF vCurrencyFk != 2 /* Dollar */ THEN + RETURN vCurrentCommission; + END IF; + + SELECT ROUND(-100 * (1 - (1 / r.rate))) INTO vCommission + FROM travel t + LEFT JOIN vn2008.reference_min r + ON r.moneda_id = vCurrencyFk AND r.`date` <= t.shipped + WHERE t.id = vTravelFk + ORDER BY r.`date` DESC + LIMIT 1; + + SET vCommission = IFNULL(vCommission, 0); + + RETURN vCommission; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `entry_getCommission` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `entry_getCommission`( + vTravelFk INT, + vCurrencyFk INT, + vSupplierFk INT +) RETURNS int(11) + READS SQL DATA +BEGIN + DECLARE vCommission INT; + DECLARE vCurrentCommission INT; + DECLARE vIsCurrencyUsd INT; + + SELECT count(*) INTO vIsCurrencyUsd + FROM currency c + WHERE c.code = 'USD' AND id = vCurrencyFk; + + IF NOT vIsCurrencyUsd THEN + SELECT commission INTO vCurrentCommission + FROM supplier s + WHERE s.id = vSupplierFk; + RETURN vCurrentCommission; + END IF; + + SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission + FROM travel t + LEFT JOIN referenceCurrent r ON r.currencyFk = vCurrencyFk AND r.`dated` <= t.shipped + WHERE t.id = vTravelFk + ORDER BY r.`dated` DESC + LIMIT 1; + + RETURN IFNULL(vCommission, 0); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `entry_getCommission__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `entry_getCommission__`( + vTravelFk INT, + vCurrencyFk INT, + vSupplierFk INT +) RETURNS int(11) + READS SQL DATA +BEGIN + -- bernat: working in this file + DECLARE vCommission INT; + DECLARE vCurrentCommission INT; + DECLARE vIsCurrencyUsd INT; + + SELECT count(*) INTO vIsCurrencyUsd + FROM currency c + WHERE c.code = 'USD' AND id = vCurrencyFk; + + IF NOT vIsCurrencyUsd THEN + SELECT commission INTO vCurrentCommission + FROM supplier s + WHERE s.id = vSupplierFk; + RETURN vCurrentCommission; + END IF; + + SELECT ROUND(-100 * (1 - (1 / r.rate))) INTO vCommission + FROM travel t + LEFT JOIN vn2008.reference_min r ON r.moneda_id = vCurrencyFk AND r.`date` <= t.shipped + WHERE t.id = vTravelFk + ORDER BY r.`date` DESC + LIMIT 1; + + RETURN IFNULL(vCommission, 0); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `entry_getCurrency` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `entry_getCurrency`( + vCurrency INT, + vSupplierFk INT +) RETURNS int(11) + READS SQL DATA +BEGIN + DECLARE vIsDollarAccount BOOL; + + SELECT account LIKE '___4______' INTO vIsDollarAccount + FROM vn.supplier WHERE id = vSupplierFk; + + IF vIsDollarAccount THEN + RETURN 2; + ELSE + RETURN vCurrency; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `floramondoNewItemFk` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `floramondoNewItemFk`() RETURNS int(11) +BEGIN + + DECLARE vItemFk INT; + + SELECT max(id) + 1 INTO vItemFk + FROM item + WHERE id BETWEEN 250000 AND 290000; + + RETURN 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 DROP FUNCTION IF EXISTS `getAlert3State` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getAlert3State`(vTicket INT) RETURNS varchar(45) CHARSET utf8 COLLATE utf8_unicode_ci + READS SQL DATA +BEGIN + DECLARE vDeliveryType INTEGER DEFAULT 0; + DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; + DECLARE vCode VARCHAR(45); + + SELECT am.deliveryMethodFk + INTO vDeliveryType + FROM ticket t + JOIN agencyMode am ON am.id = t.agencyModeFk + WHERE t.id = vTicket; + + CASE vDeliveryType + WHEN 1 THEN -- AGENCIAS + SET vCode = 'DELIVERED'; + + WHEN 2 THEN -- REPARTO + SET vCode = 'ON_DELIVERY'; + + ELSE -- MERCADO, OTROS + SELECT MIN(t.warehouseFk <> w.id) INTO isWaitingForPickUp + FROM ticket t + LEFT JOIN warehouse w + ON w.pickUpagencyModeFk = t.agencyModeFk + WHERE t.id = vTicket; + + IF isWaitingForPickUp THEN + SET vCode = 'WAITING_FOR_PICKUP'; + ELSE + SET vCode = 'DELIVERED'; + END IF; + END CASE; + RETURN vCode; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `getAlert3StateTest` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getAlert3StateTest`(vTicket INT) RETURNS varchar(45) CHARSET latin1 +BEGIN + DECLARE vDeliveryType INTEGER DEFAULT 0; + DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; + DECLARE vCode VARCHAR(45); + + SELECT + a.Vista + INTO vDeliveryType + FROM vn2008.Tickets t + JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia + WHERE Id_Ticket = vTicket; + + CASE vDeliveryType + WHEN 1 THEN -- AGENCIAS + SET vCode = 'DELIVERED'; + + WHEN 2 THEN -- REPARTO + SET vCode = 'ON_DELIVERY'; + + ELSE -- MERCADO, OTROS + SELECT t.warehouse_id <> w.warehouse_id INTO isWaitingForPickUp + FROM vn2008.Tickets t + LEFT JOIN vn2008.warehouse_pickup w + ON w.agency_id = t.Id_Agencia AND w.warehouse_id = t.warehouse_id + WHERE t.Id_Ticket = vTicket; + + IF isWaitingForPickUp THEN + SET vCode = 'WAITING_FOR_PICKUP'; + ELSE + SET vCode = 'DELIVERED'; + END IF; + END CASE; + RETURN vCode; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `getAlert3State__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getAlert3State__`(vTicket INT) RETURNS varchar(45) CHARSET utf8 COLLATE utf8_unicode_ci + READS SQL DATA +BEGIN + DECLARE vDeliveryType INTEGER DEFAULT 0; + DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; + DECLARE vCode VARCHAR(45); + + SELECT a.Vista + INTO vDeliveryType + FROM vn2008.Tickets t + JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia + WHERE Id_Ticket = vTicket; + + CASE vDeliveryType + WHEN 1 THEN -- AGENCIAS + SET vCode = 'DELIVERED'; + + WHEN 2 THEN -- REPARTO + SET vCode = 'ON_DELIVERY'; + + ELSE -- MERCADO, OTROS + SELECT MIN(t.warehouse_id <> w.warehouse_id) INTO isWaitingForPickUp + FROM vn2008.Tickets t + LEFT JOIN vn2008.warehouse_pickup w + ON w.agency_id = t.Id_Agencia + WHERE t.Id_Ticket = vTicket; + + IF isWaitingForPickUp THEN + SET vCode = 'WAITING_FOR_PICKUP'; + ELSE + SET vCode = 'DELIVERED'; + END IF; + END CASE; + RETURN vCode; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `getDueDate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getDueDate`(vDated DATE, vDayToPay INT) RETURNS date +BEGIN + DECLARE vDued DATE; + + IF vDayToPay = 0 THEN + RETURN vDated; + END IF; + + SET vDued = TIMESTAMPADD(DAY,vDayToPay MOD 30, LAST_DAY(TIMESTAMPADD(MONTH, vDayToPay DIV 30, vDated))); + + RETURN vDued; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `getInventoryDate` */; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getInventoryDate`() RETURNS date + DETERMINISTIC +BEGIN + RETURN vn2008.date_inv(); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP FUNCTION IF EXISTS `getNewItemId` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getNewItemId`() RETURNS int(11) +BEGIN + + DECLARE newItemId INT; + + SELECT i1.id + 1 INTO newItemId + FROM item i1 + LEFT JOIN item i2 ON i1.id + 1 = i2.id + WHERE i2.id IS NULL + ORDER BY i1.id + LIMIT 1; + + RETURN newItemId; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `getPlacementReserve` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getPlacementReserve`(vItemFk INT, vWarehouseFk INT) RETURNS varchar(25) CHARSET utf8 +BEGIN + + DECLARE vPlacementReserve VARCHAR(25); + + SELECT CONCAT(IFNULL(`code`,'--'), ' / ', IFNULL(reserve,'--')) INTO vPlacementReserve + FROM itemPlacement + WHERE itemFk = vItemFk + AND warehouseFk = vWarehouseFk; + +RETURN vPlacementReserve; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `getShipmentHour` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getShipmentHour`(vTicket INT) RETURNS int(11) + READS SQL DATA +BEGIN + DECLARE vShipmentHour INT; + + SELECT HOUR(shipped) INTO vShipmentHour + FROM ticket + WHERE id = vTicket; + + IF vShipmentHour = 0 + THEN + DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; + CREATE TEMPORARY TABLE tmp.production_buffer + ENGINE = MEMORY + SELECT am.agencyFk as agency_id + , t.warehouseFk as warehouse_id + , a.provinceFk as province_id + , 0 as Hora + , 0 as Departure + FROM ticket t + JOIN agencyMode am on am.id = t.agencyModeFk + JOIN address a on a.id = t.addressFk + WHERE t.id = vTicket; + + SELECT Hora INTO vShipmentHour + FROM tmp.production_buffer; + END IF; + + RETURN vShipmentHour; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `getSpecialPrice` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getSpecialPrice`(vItemFk int(11),vClientFk int(11)) RETURNS decimal(10,2) +BEGIN + DECLARE price DECIMAL(10,2); + + SELECT rate3 INTO price + FROM vn.priceFixed + WHERE itemFk = vItemFk + AND CURDATE() BETWEEN started AND ended ORDER BY created DESC LIMIT 1; + + SELECT `value` INTO price + FROM vn.specialPrice + WHERE itemFk = vItemFk + AND clientFk = vClientFk ; +RETURN price; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `getTicketToPrepare` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getTicketToPrepare`(`vWorker` INT, `vWarehouse` INT) RETURNS int(11) + READS SQL DATA +BEGIN +/** + * Devuelve el ticket que debe de preparar el trabajador + * + * @param vWorker Id del trabajador + * @param vWarehouse Id del almacén + * @return Id del ticket + * + * #UPDATED PAK 2019/08/16 + * #PENDING REVIEW + **/ + + DECLARE vToday DATETIME DEFAULT CURDATE(); + DECLARE vYesterday DATETIME; + DECLARE vTodayvMidniight DATETIME DEFAULT midnight(vToday); + DECLARE vTicket INT DEFAULT NULL; + DECLARE PREVIOUS_PREPARATION INT; + DECLARE vHasBeenPreviouslyPrepared INT DEFAULT 0; + + -- Si hay algun ticket previamente seleccionado, y se ha quedado sin empezar, lo recupera en primer lugar. + /* + SELECT i.Id_Ticket INTO vTicket + FROM vncontrol.inter i + JOIN vn.state s ON s.id = i.state_id + LEFT JOIN + (SELECT DISTINCT s.ticketFk + FROM vn.sale s + JOIN vn.saleTracking st ON st.saleFk = s.id + JOIN vn.ticketStateToday tst ON tst.ticket = s.ticketFk + WHERE st.created > CURDATE() + -- AND tst.`code` = 'ON_PREPARATION' + ) sub ON sub.ticketFk = i.Id_Ticket + WHERE odbc_date > CURDATE() + AND s.`code` = 'ON_PREPARATION' + AND i.Id_Trabajador = vWorker + AND sub.ticketFk IS NULL + LIMIT 1; + + IF vTicket IS NULL THEN + */ + SELECT id INTO PREVIOUS_PREPARATION + FROM vn.state + WHERE code LIKE 'PREVIOUS_PREPARATION'; + + SET vYesterday = TIMESTAMPADD(DAY,-1,vToday); + + DROP TEMPORARY TABLE IF EXISTS tmp.workerComercial; + CREATE TEMPORARY TABLE tmp.workerComercial + ENGINE = MEMORY + SELECT worker FROM `grant` g + JOIN grantGroup gg ON g.`group` = gg.id + WHERE gg.description = 'Comerciales'; + + DELETE wc.* + FROM tmp.workerComercial wc + JOIN `grant` g ON g.worker = wc.worker + JOIN grantGroup gg ON g.`group` = gg.id + WHERE gg.description = 'Gerencia'; + + DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; + CREATE TEMPORARY TABLE tmp.production_buffer + ENGINE = MEMORY + SELECT t.id as ticket + , am.agencyFk as agency_id + , t.warehouseFk as warehouse_id + , a.provinceFk as province_id + , IF (HOUR(t.shipped),HOUR(t.shipped),HOUR(z.`hour`)) as Hora + , HOUR(t.shipped) as Departure + , IF (MINUTE(t.shipped),MINUTE(t.shipped),MINUTE(z.`hour`)) as Minuto + , tls.code + , IFNULL(t.priority,0) loadingOrder + FROM ticket t + JOIN ticketState tls on t.id = tls.ticket + JOIN agencyMode am on am.id = t.agencyModeFk + JOIN address a on a.id = t.addressFk + LEFT JOIN tmp.workerComercial wc ON wc.worker = vWorker + LEFT JOIN vn.zone z ON z.id = t.zoneFk + WHERE t.shipped BETWEEN vYesterday AND vTodayvMidniight + AND t.warehouseFk = vWarehouse + AND + ( + (tls.code = 'PRINTED' AND wc.worker IS NULL) + OR + (tls.code ='PICKER_DESIGNED' AND tls.worker = vWorker) + OR + (tls.code = 'PRINTED_BACK') + OR + (tls.code = 'PRINTED PREVIOUS') + ); + + + SELECT ticket INTO vTicket + FROM tmp.production_buffer + ORDER BY (code = 'PICKER_DESIGNED') DESC, (code = 'PRINTED PREVIOUS') DESC ,Hora, Minuto, loadingOrder + LIMIT 1; + + -- Aviso de ticket para bajar + SELECT COUNT(*) INTO vHasBeenPreviouslyPrepared + FROM vncontrol.inter + WHERE Id_Ticket = vTicket + AND state_id = PREVIOUS_PREPARATION; + + IF vHasBeenPreviouslyPrepared AND ticketWarehouseGet(vTicket) = 1 THEN + + INSERT IGNORE INTO vn.ticketDown(ticketFk) VALUES(vTicket); + + END IF; + + -- END IF; + + RETURN vTicket; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `getTicketTrolleyLabelCount` */; +ALTER DATABASE `vn` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getTicketTrolleyLabelCount`(vTicket INT) RETURNS int(11) +BEGIN + +DECLARE vLabelCount INT DEFAULT 0; + +SELECT labelCount INTO vLabelCount +FROM ticketTrolley +WHERE ticket = vTicket; + +SET vLabelCount = vLabelCount +1 ; + +REPLACE ticketTrolley(ticket,labelCount) +SELECT vTicket, vLabelCount; + +RETURN vlabelCount; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP FUNCTION IF EXISTS `getUser` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getUser`() RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * @deprecated Use account.userGetId() + */ + RETURN account.userGetId(); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `getUserId` */; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getUserId`(userName varchar(30)) RETURNS int(11) +BEGIN + DECLARE vUser INT; + + SELECT id INTO vUser + FROM account.user + WHERE `name` = userName; + + RETURN vUser; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP FUNCTION IF EXISTS `getWorker` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getWorker`() RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * @deprecated Use myWorker_getId() + */ + DECLARE vUser INT; + + SELECT id INTO vUser + FROM worker + WHERE userFk = account.userGetId(); + + RETURN vUser; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `getWorkerCode` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `getWorkerCode`() RETURNS varchar(3) CHARSET utf8 +BEGIN +DECLARE vUserCode VARCHAR(3) CHARSET utf8 COLLATE utf8_unicode_ci; + +SELECT code INTO vUserCode +FROM worker +WHERE userFk = account.userGetId(); + +RETURN vUserCode; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `hasAnyNegativeBase` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `hasAnyNegativeBase`() RETURNS tinyint(1) + DETERMINISTIC +BEGIN + +/* Calcula si existe alguna base imponible negativa +* Requiere la tabla temporal vn.ticketToInvoice(id) +* +* returns BOOLEAN +*/ + DECLARE hasAnyNegativeBase BOOLEAN; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + (KEY (ticketFk)) + ENGINE = MEMORY + SELECT id ticketFk + FROM ticketToInvoice; + + CALL ticket_getTax(NULL); + + SELECT COUNT(*) INTO hasAnyNegativeBase + FROM( + SELECT SUM(taxableBase) as taxableBase + FROM tmp.ticketTax + GROUP BY pgcFk + HAVING taxableBase < 0 + ) t; + + DROP TEMPORARY TABLE tmp.ticketTax; + DROP TEMPORARY TABLE tmp.ticket; + + RETURN hasAnyNegativeBase; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `hasAnyNegativeBase__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `hasAnyNegativeBase__`() RETURNS tinyint(1) + DETERMINISTIC +BEGIN + +/* Calcula si existe alguna base imponible negativa +* Requiere la tabla temporal vn.ticketToInvoice(id) +* +* returns BOOLEAN +*/ + + DECLARE vCountry INT; + DECLARE hasAnyNegativeBase BOOLEAN; + + SELECT s.countryFk + INTO vCountry + FROM supplier s + JOIN ticket t ON t.companyFk = s.id + JOIN vn.ticketToInvoice tl ON tl.id = t.id + LIMIT 1; + + SELECT COUNT(*) INTO hasAnyNegativeBase + FROM ( + SELECT SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)) taxableBase + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN itemTaxCountry itc + ON itc.itemFk = i.id AND itc.countryFk = vCountry + JOIN vn.ticketToInvoice tl ON tl.id = s.ticketFk + GROUP BY itc.taxClassFk + HAVING taxableBase < 0 + ) t1 ; + + RETURN hasAnyNegativeBase; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `hasSomeNegativeBase` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `hasSomeNegativeBase`(vTicket INT) RETURNS tinyint(1) +BEGIN + + DECLARE vCountry INT; + DECLARE hasSomeNegativeBase BOOLEAN; + + SELECT s.countryFk + INTO vCountry + FROM supplier s + JOIN ticket t ON t.companyFk = s.id + WHERE t.id = vTicket; + + SELECT COUNT(*) INTO hasSomeNegativeBase + FROM ( + SELECT SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)) taxableBase + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN itemTaxCountry itc + ON itc.itemFk = i.id AND itc.countryFk = vCountry + WHERE s.ticketFk = vTicket + GROUP BY itc.taxClassFk + HAVING taxableBase < 0 + ) t1 ; + + RETURN hasSomeNegativeBase; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `hasZone` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `hasZone`(vLanded DATE, vAddress INT, vAgencyModeFk INT) RETURNS tinyint(1) + DETERMINISTIC +BEGIN + DECLARE vHasZone BOOLEAN DEFAULT FALSE; + + SELECT COUNT(*), id zoneFk, isIncluded INTO vHasZone, @trash, @trash FROM ( + SELECT z.id, + TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, + vLanded landed, + zi.isIncluded + FROM zoneGeo zgSon + JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt + JOIN zoneIncluded zi ON zi.geoFk = zgFather.id + JOIN zone z ON z.id = zi.zoneFk + JOIN zoneCalendar zc ON zc.zoneFk = z.id + AND zc.delivered = vLanded + AND z.agencyModeFk = vAgencyModeFk + AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) + WHERE zi.isIncluded + ORDER BY z.id, landed ASC, zgFather.depth DESC) t + GROUP BY id + HAVING isIncluded > 0 LIMIT 1; + RETURN vHasZone; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `invoiceOutAmount` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `invoiceOutAmount`(vInvoiceRef VARCHAR(15)) RETURNS decimal(10,2) +BEGIN + DECLARE totalAmount DECIMAL(10,2); + + SELECT SUM(vat) INTO totalAmount + FROM + ( + SELECT iot.vat + FROM invoiceOutTax iot + JOIN invoiceOut io ON io.id = iot.invoiceOutFk + WHERE io.ref = vInvoiceRef + UNION ALL + SELECT ioe.amount + FROM invoiceOutExpence ioe + JOIN invoiceOut io ON io.id = ioe.invoiceOutFk + WHERE io.ref = vInvoiceRef + ) t1; + +RETURN totalAmount; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `invoiceOut_getPath` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `invoiceOut_getPath`(vSelf INT) RETURNS varchar(255) CHARSET utf8 + DETERMINISTIC +BEGIN + DECLARE vIssued DATE; + DECLARE vSerial VARCHAR(15); + + SELECT issued, ref + INTO vIssued, vSerial + FROM invoiceOut WHERE id = vSelf; + + RETURN CONCAT_WS('/' + ,'invoice' + ,YEAR(vIssued) + ,MONTH(vIssued) + ,DAY(vIssued) + ,CONCAT(YEAR(vIssued), vSerial, '.pdf') + ); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `invoiceSerial` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `invoiceSerial`(vClientFk INT, vCompanyFk INT, vType CHAR(1)) RETURNS char(1) CHARSET utf8 + DETERMINISTIC +BEGIN + /** + * Obtiene la serie de de una factura + * dependiendo del area del cliente. + * + * @param vClientFk Id del cliente + * @param vCompanyFk Id de la empresa + * @param vType Tipo de factura ["R", "M", "G"] + * @return Serie de la factura + */ + DECLARE vTaxArea VARCHAR(25); + DECLARE vSerie CHAR(1); + + IF (SELECT hasInvoiceSimplified FROM client WHERE id = vClientFk) THEN + RETURN 'S'; + END IF; + + SELECT clientTaxArea(vClientFk, vCompanyFk) INTO vTaxArea; + SELECT invoiceSerialArea(vType,vTaxArea) INTO vSerie; + RETURN vSerie; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `invoiceSerialArea` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `invoiceSerialArea`(vType CHAR(1), vTaxArea VARCHAR(25)) RETURNS char(1) CHARSET utf8 COLLATE utf8_unicode_ci + DETERMINISTIC +BEGIN + + DECLARE vSerie CHAR(1); + + IF vType = 'R' THEN + SELECT + CASE vTaxArea + WHEN 'CEE' + THEN 'H' + WHEN 'WORLD' + THEN 'E' + WHEN 'NATIONAL' + THEN 'T' + END + INTO vSerie; + -- Factura multiple + ELSEIF vType = 'M' THEN + SELECT + CASE vTaxArea + WHEN 'CEE' + THEN 'H' + WHEN 'WORLD' + THEN 'E' + WHEN 'NATIONAL' + THEN 'M' + END + INTO vSerie; + -- Factura global + ELSEIF vType = 'G' THEN + SELECT + CASE vTaxArea + WHEN 'CEE' + THEN 'V' + WHEN 'WORLD' + THEN 'X' + WHEN 'NATIONAL' + THEN 'A' + END + INTO vSerie; + END IF; + RETURN vSerie; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `isIntrastatEntry` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `isIntrastatEntry`(vEntryFk INT) RETURNS int(11) +BEGIN + + DECLARE isIntrastatOperation BOOL DEFAULT FALSE; + DECLARE vSupplierCountry INT DEFAULT -1; + DECLARE vClientCountry INT DEFAULT -1; + + SELECT c.id INTO vSupplierCountry + FROM vn.country c + JOIN vn.supplier s ON s.countryFk = c.id + JOIN vn.entry e ON e.supplierFk = s.id + WHERE e.id = vEntryFk + AND c.isUeeMember = TRUE; + + SELECT c.id INTO vClientCountry + FROM vn.country c + JOIN vn.supplier s ON s.countryFk = c.id + JOIN vn.company co ON co.id = s.id + JOIN vn.entry e ON e.companyFk = co.id + WHERE e.id = vEntryFk + AND c.isUeeMember = TRUE; + + IF vSupplierCountry != vClientCountry AND vSupplierCountry * vClientCountry > 0 THEN + + SET isIntrastatOperation = TRUE; + + END IF; + + RETURN isIntrastatOperation; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `isPalletHomogeneus` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `isPalletHomogeneus`(vExpedition INT) RETURNS tinyint(1) +BEGIN + DECLARE vScanId INT; + DECLARE vDistinctRoutesInThePallet INT; + + SELECT scan_id INTO vScanId + FROM vn2008.scan_line + WHERE code = vExpedition + LIMIT 1; + + SELECT COUNT(*) INTO vDistinctRoutesInThePallet + FROM ( + SELECT DISTINCT t.Id_Ruta + FROM vn2008.scan_line sl + JOIN vn2008.expeditions e ON e.expeditions_id = sl.code + JOIN vn2008.Tickets t ON t.Id_Ticket = e.ticket_id + WHERE sl.scan_id = vScanId + AND t.Id_Ruta + ) t1; + + RETURN vDistinctRoutesInThePallet = 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 DROP FUNCTION IF EXISTS `itemPacking` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `itemPacking`(vBarcode VARCHAR(22), vWarehouseFk INT) RETURNS int(11) + DETERMINISTIC +BEGIN + + DECLARE vPacking INTEGER DEFAULT 0; + DECLARE vItemFk INTEGER; + + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; + + SELECT IFNULL(packing,0) INTO vPacking + FROM vn.buy + WHERE id = CAST(vBarcode AS DECIMAL(18,0)); + + + + + IF NOT vPacking THEN + CALL cache.last_buy_refresh(FALSE); + SELECT IFNULL(packing,1) INTO vPacking + FROM + (SELECT packing , created + FROM vn.itemShelving + WHERE itemFk = vItemFk + UNION ALL + SELECT b.packing, landing + FROM vn.buy b + JOIN cache.last_buy lb ON lb.buy_id = b.id + WHERE lb.warehouse_id = vWarehouseFk + AND b.itemFk = vItemFk + ) packings + ORDER BY created desc + LIMIT 1; + + END IF; + + RETURN vPacking; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `itemPlacementGet` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `itemPlacementGet`(vItemFk INT, vWarehouseFk INT) RETURNS varchar(25) CHARSET utf8 +BEGIN + + DECLARE vPlacementReserve VARCHAR(25); + + SELECT CONCAT(IFNULL(`code`,'--'), ' / ', IFNULL(reserve,'--')) INTO vPlacementReserve + FROM itemPlacement + WHERE itemFk = vItemFk + AND warehouseFk = vWarehouseFk; + +RETURN vPlacementReserve; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `itemShelvingPlacementSupply_ClosestGet` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `itemShelvingPlacementSupply_ClosestGet`(vParkingFk INT) RETURNS int(11) + READS SQL DATA +BEGIN + + /* Devuelve el parking más cercano.*/ + DECLARE vColumn INT; + DECLARE vClosestParkingFk INT; + DECLARE vSectorFk INT; + + SELECT p.column, sectorFk INTO vColumn, vSectorFk + FROM vn.parking p + WHERE p.id = vParkingFk; + + SELECT itemShelvingFk INTO vClosestParkingFk + FROM + ( + SELECT ABS(p.column - vColumn) as distance, itemShelvingFk + FROM vn.itemShelvingPlacementSupplyStock ispss + JOIN vn.parking p ON p.id = ispss.parkingFk + JOIN vn.itemPlacementSupplyList ipsl ON ipsl.sectorFk = ispss.sectorFk AND ipsl.itemFk = ispss.itemFk + WHERE p.sectorFk = vSectorFk + AND ipsl.saldo > 0 + ) sub + ORDER BY distance + LIMIT 1; + + RETURN vClosestParkingFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `itemTag_getIntValue` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `itemTag_getIntValue`(vValue VARCHAR(255)) RETURNS int(11) + DETERMINISTIC +BEGIN + IF vValue NOT REGEXP '^-?[0-9]+' THEN + RETURN NULL; + END IF; + + RETURN CAST(vValue AS SIGNED); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `item_getVolume` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `item_getVolume`(vSelf INT, vPackaging VARCHAR(10)) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Calculates the volume occupied by an item together + * with its packaging. + * + * @param vSelf The item id + * @param vPackaging The packaging id + * @return The volume in cubic centimeters + */ + DECLARE vVolume INT; + + SELECT SUM(IF(p.volume > 0, + p.volume, + p.width * p.depth * IF(p.height, p.height, i.size + 10) + )) INTO vVolume + FROM packaging p + JOIN item i ON i.id = vSelf + WHERE p.id = vPackaging; + + RETURN vVolume; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `messageSend` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `messageSend`(vRecipient VARCHAR(255) CHARSET utf8, vMessage TEXT CHARSET utf8) RETURNS int(11) +BEGIN + DECLARE result INT; + DECLARE vSenderFk INT; + + SELECT id INTO vSenderFk + FROM account.user WHERE `name` = account.userGetName(); + + RETURN (SELECT messageSendWithUser(vSenderFk, vRecipient, vMessage)); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `messageSendWithUser` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `messageSendWithUser`(vSenderFK INT, vRecipient VARCHAR(255) CHARSET utf8, vMessage TEXT CHARSET utf8) RETURNS int(11) + DETERMINISTIC +BEGIN + + DECLARE vCount INT; + DECLARE vUuid VARCHAR(255); + DECLARE vSendDate DATETIME DEFAULT NOW(); + DECLARE vSender VARCHAR(255) CHARSET utf8; + + SELECT `name` INTO vSender + FROM account.user WHERE id = vSenderFK; + + SET vRecipient = LOWER(vRecipient); + + DROP TEMPORARY TABLE IF EXISTS tRecipients; + CREATE TEMPORARY TABLE tRecipients + SELECT u.name finalRecipient + FROM account.mailAlias a + JOIN account.mailAliasAccount aa ON aa.mailAlias = a.id + JOIN account.user u ON u.id = aa.account + WHERE a.alias = vRecipient COLLATE utf8_unicode_ci + AND u.name != vSender + AND u.active + UNION + SELECT u.name FROM account.user u + WHERE u.name = vRecipient + AND u.active; + + SELECT COUNT(*) INTO vCount FROM tRecipients; + + IF vCount = 0 THEN + RETURN vCount; + END IF; + + SET vUuid = UUID(); + + INSERT INTO message + SET uuid = vUuid, + sender = vSender, + recipient = vRecipient, + message = vMessage, + sendDate = vSendDate; + + INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate) + SELECT vUuid, vSender, vRecipient, finalRecipient, vMessage, vSendDate + FROM tRecipients; + + DROP TEMPORARY TABLE tRecipients; + RETURN vCount; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `MIDNIGHT` */; +ALTER DATABASE `vn` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `MIDNIGHT`(vDate DATE) RETURNS datetime + DETERMINISTIC +BEGIN + RETURN TIMESTAMP(vDate,'23:59:59'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP FUNCTION IF EXISTS `myWorker_getId` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `myWorker_getId`() RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Returns the current worker id or the default worker id + * if current user cannot be retrieved. + * + * @return The worker id + */ + DECLARE vWorker INT; + + SELECT IFNULL(w.id, c.defaultWorkerFk) INTO vWorker + FROM worker w, workerConfig c + WHERE w.userFk = account.userGetId(); + + RETURN vWorker; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `nz` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `nz`(vQuantity DOUBLE) RETURNS double + DETERMINISTIC +BEGIN + + DECLARE vResult DOUBLE; + + SET vResult = IFNULL(vQuantity,0); + + RETURN vResult; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `orderTotalVolume` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `orderTotalVolume`(vOrderId INT) RETURNS decimal(10,3) + READS SQL DATA +BEGIN + -- Devuelte el volumen total de la orden sumada + DECLARE vWarehouseId INTEGER; + DECLARE vVolume DECIMAL(10,3); + + SELECT IFNULL(SUM(o.amount * i.compression * r.cm3)/1000000,0) INTO vVolume + FROM hedera.orderRow o + JOIN vn.item i ON i.id = o.itemFk + JOIN bi.rotacion r on r.Id_Article = o.itemFk AND r.warehouse_id = o.warehouseFk + WHERE o.orderFk = vOrderId; + + RETURN vVolume; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `orderTotalVolumeBoxes` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `orderTotalVolumeBoxes`(vOrderId INT) RETURNS decimal(10,3) +BEGIN + +/* + * Devuelve el volumen estimado del ticket sumado, en cajas + * + * idT Numero de ticket + * + */ + DECLARE vVolumeBoxM3 DOUBLE; + DECLARE vOrderTotalVolumeBoxes DECIMAL(10,1); + DECLARE vVnBoxId VARCHAR(10) DEFAULT '94'; + + SELECT volume / 1000000 INTO vVolumeBoxM3 FROM packaging WHERE id = vVnBoxId; + + SET vOrderTotalVolumeBoxes = orderTotalVolume(vOrderId) / vVolumeBoxM3; + + RETURN vOrderTotalVolumeBoxes; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `phytoPassport` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `phytoPassport`(vRef VARCHAR(15)) RETURNS text CHARSET utf8 +BEGIN +DECLARE vPhyto TEXT CHARSET utf8 COLLATE utf8_unicode_ci; +SELECT + GROUP_CONCAT(i.id, + ':', + ppa.denomination, + ' ', + pp.number, + CHAR(13,10) + SEPARATOR '') fitosanitario + INTO vPhyto +FROM + sale s + JOIN + ticket t ON t.id = s.ticketFk + JOIN + item i ON i.id = s.itemFk + JOIN + plantpassport pp ON pp.producerFk = i.producerFk + JOIN + plantpassportAuthority ppa ON ppa.id = pp.plantpassportAuthorityFk + JOIN + itemBotanicalWithGenus ib ON ib.itemFk = i.id + JOIN + botanicExport be ON be.restriction = 'pasaporte fitosanitario' + LEFT JOIN + ediGenus eg ON eg.id = be.ediGenusFk + LEFT JOIN + ediSpecie es ON es.id = be.ediSpecieFk +WHERE + t.refFk = vRef + AND ib.ediBotanic LIKE CONCAT(IFNULL(eg.latinGenusName, ''), + IF(latinSpeciesName > '', + CONCAT(' ', latinSpeciesName), + ''), + '%'); +RETURN vPhyto; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `ticketGetTotal` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `ticketGetTotal`(vTicketId INT) RETURNS decimal(10,2) + READS SQL DATA + DETERMINISTIC +BEGIN +/** + * Calcula el total con IVA de un ticket. + * + * @param vTicketId Identificador del ticket + * @return Total del ticket + */ + DECLARE vTotal DECIMAL(10,2); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + ENGINE = MEMORY + SELECT vTicketId ticketFk; + + CALL ticketGetTotal; + + SELECT total INTO vTotal FROM tmp.ticketTotal; + + DROP TEMPORARY TABLE + tmp.ticket, + tmp.ticketTotal; + + RETURN vTotal; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `ticketPositionInPath` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `ticketPositionInPath`(vTicketId INT) RETURNS varchar(10) CHARSET utf8 +BEGIN + + DECLARE vRestTicketsMaxOrder INT; + DECLARE vRestTicketsMinOrder INT; + DECLARE vRestTicketsPacking INT; + DECLARE vMyProductionOrder INT; + DECLARE vPosition VARCHAR(10) DEFAULT 'MID'; + DECLARE vMyPath INT; + DECLARE vMyWarehouse INT; + DECLARE PACKING_ORDER INT; + DECLARE vExpeditionsCount INT; + DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE; + +SELECT `order` + INTO PACKING_ORDER + FROM state + WHERE code = 'PACKING'; + +SELECT t.routeFk, t.warehouseFk, IFNULL(ts.productionOrder,0) + INTO vMyPath, vMyWarehouse, vMyProductionOrder + FROM ticket t + LEFT JOIN ticketState ts on ts.ticket = t.id + WHERE t.id = vTicketId; + +SELECT (ag.`name` = 'VN_VALENCIA') + INTO vIsValenciaPath + FROM vn2008.Rutas r + JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia + JOIN vn2008.agency ag on ag.agency_id = a.agency_id + WHERE r.Id_Ruta = vMyPath; + +IF vIsValenciaPath THEN -- Rutas Valencia + + SELECT COUNT(*) + INTO vExpeditionsCount + FROM expedition e + JOIN ticket t ON t.id = e.ticketFk + WHERE t.routeFk = vMyPath; + + SELECT MAX(ts.productionOrder), MIN(ts.productionOrder) + INTO vRestTicketsMaxOrder, vRestTicketsMinOrder + FROM ticket t + LEFT JOIN ticketState ts on t.id = ts.ticket + WHERE t.routeFk = vMyPath + AND t.warehouseFk = vMyWarehouse + AND t.id != vTicketid; + + SELECT COUNT(*) + INTO vRestTicketsPacking + FROM ticket t + LEFT JOIN ticketState ts on t.id = ts.ticket + WHERE ts.productionOrder = PACKING_ORDER + AND t.routeFk = vMyPath + AND t.warehouseFk = vMyWarehouse + AND t.id != vTicketid; + + IF vExpeditionsCount = 1 THEN + SET vPosition = 'FIRST'; + ELSEIF vRestTicketsMinOrder > PACKING_ORDER THEN + SET vPosition = 'LAST'; + ELSEIF vRestTicketsPacking THEN + SET vPosition = 'SHARED'; + ELSE + SET vPosition = 'MID'; + END IF; + +ELSE + SET vPosition = 'MID'; + +END IF; + +RETURN vPosition; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `ticketSplitCounter` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `ticketSplitCounter`(vTicketFk INT) RETURNS varchar(15) CHARSET utf8 COLLATE utf8_unicode_ci + READS SQL DATA +BEGIN + DECLARE vSplitCounter VARCHAR(15); + + SELECT CONCAT(OK,'/',Total, IF(OK = Total ,' LS','')) INTO vSplitCounter + FROM + ( + SELECT count(l.Id_Movimiento) as OK, COUNT(*) as Total + FROM vn.sale s + LEFT JOIN vn2008.movement_label l ON l.Id_Movimiento = s.id + WHERE ticketFk = vTicketFk + ) sub; + RETURN vSplitCounter; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `ticketTotalVolume` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `ticketTotalVolume`(vTicketId INT) RETURNS decimal(10,3) + READS SQL DATA +BEGIN + -- Devuelte el volumen total del ticket sumado + -- DECLARE vWarehouseId INTEGER; + -- DECLARE vShippedDate DATE; + DECLARE vVolume DECIMAL(10,3); + /* + SELECT warehouseFk, shipped INTO vWarehouseId,vShippedDate FROM vn.ticket WHERE id = vTicketId; + + SELECT IFNULL(SUM(s.quantity * i.compression * r.cm3)/1000000,0) INTO vVolume + FROM sale s + JOIN vn.item i ON i.id = s.itemFk + JOIN bi.rotacion r on r.Id_Article = s.itemFk AND r.warehouse_id = vWarehouseId + WHERE s.ticketFk = vTicketId; + */ + SELECT sum(volume) INTO vVolume + FROM saleVolume + WHERE ticketFk = vTicketId; + RETURN vVolume; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `ticketTotalVolumeBoxes` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `ticketTotalVolumeBoxes`(vTicketId INT) RETURNS decimal(10,1) + DETERMINISTIC +BEGIN + +/* + * Devuelve el volumen estimado del ticket sumado, en cajas + * + * vTicketId Numero de ticket + * + */ + + DECLARE vVolumeBoxM3 DOUBLE; + DECLARE vTicketTotalVolumeBoxes DECIMAL(10,1); + DECLARE vVnBoxId VARCHAR(10) DEFAULT '94'; + + SELECT volume / 1000000 INTO vVolumeBoxM3 FROM packaging WHERE id = vVnBoxId; + + SET vTicketTotalVolumeBoxes = ticketTotalVolume(vTicketId) / vVolumeBoxM3; + + RETURN vTicketTotalVolumeBoxes; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `ticketWarehouseGet` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `ticketWarehouseGet`(vTicketFk INT) RETURNS int(11) +BEGIN + + DECLARE vWarehouseFk INT; + + SELECT warehouseFk INTO vWarehouseFk + FROM ticket + WHERE id = vTicketFk; + + RETURN vWarehouseFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `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; + + -- Inserta los asientos contables + + SELECT account INTO vAccount + FROM bank 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 + ); + + RETURN NULL; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `timeWorkerControl_getDirection` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `timeWorkerControl_getDirection`(vUserFk INT, vTimed DATETIME) RETURNS varchar(6) CHARSET utf8 COLLATE utf8_unicode_ci + READS SQL DATA +BEGIN +/** + * Verifica la dirección de la fichada + * @param vUserFk Identificador del trabajador + * @param vTimed Hora de la fichada + * @return Retorna sentido de la fichada 'in, out, middle' + */ + + DECLARE vPrevious DATETIME ; + DECLARE vNext DATETIME ; + DECLARE vPreviousDirection VARCHAR(3) ; + DECLARE vNextDirection VARCHAR(3) ; + DECLARE vDayStayMax INT; + DECLARE vTimedSeconds INT; + DECLARE vLastTimeIn INT; + + SELECT UNIX_TIMESTAMP(vTimed) INTO vTimedSeconds; + + SELECT dayStayMax INTO vDayStayMax + FROM vn.workerTimeControlParams; + + SELECT timed, direction INTO vNext,vNextDirection + FROM vn.workerTimeControl + WHERE userFk = vUserFk + AND direction IN ('in','out') + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + + SELECT timed, direction INTO vPrevious, vPreviousDirection + FROM vn.workerTimeControl + WHERE userFk = vUserFk + AND direction IN ('in','out') + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN + RETURN 'middle'; + END IF; + + + IF (vTimedSeconds> UNIX_TIMESTAMP(vPrevious)) THEN + IF vPreviousDirection = 'in' THEN + RETURN 'out'; + ELSE + SELECT UNIX_TIMESTAMP(MAX(timed)) INTO vLastTimeIn + FROM vn.workerTimeControl + WHERE userFk = vUserFk + AND direction ='in' + AND timed < vPrevious; + IF vTimedSeconds - vLastTimeIn <= vDayStayMax THEN + RETURN 'out'; + END IF; + END IF; + END IF; + + RETURN 'in'; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `workerIsBoss` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `workerIsBoss`(vUserId INT) RETURNS int(11) +BEGIN +/** + * Comprueba por jerarquía si el trabajador actual es jefe + * de un trabajador en concreto. + * + * @param vUserId Id del trabajador que se desea comprobar. + * @return Revuelve verdadero si es jefe del empleado por escala jerárquica. + */ + DECLARE vWorkerId INT; + DECLARE vBossId INT; + + SELECT id INTO vWorkerId + FROM vn.worker + WHERE userFk = vUserId; + IF vWorkerId IS NULL THEN + CALL util.throw('USER_NOT_FOUND'); + END IF; + + DROP TEMPORARY TABLE IF EXISTS tCheckedWorker; + CREATE TEMPORARY TABLE tCheckedWorker + (PRIMARY KEY (workerFk)) + ENGINE = MEMORY + SELECT id workerFk FROM worker LIMIT 0; + LOOP + SELECT bossFk INTO vBossId + FROM vn.worker + WHERE id = vWorkerId; + IF (SELECT COUNT(*) FROM tCheckedWorker WHERE workerFk = vBossId) THEN + CALL util.throw('INFINITE_LOOP'); + END IF; + IF vBossId = vWorkerId THEN + RETURN FALSE; + ELSEIF vBossId = vn.getWorker() THEN + RETURN TRUE; + ELSE + INSERT INTO tCheckedWorker VALUES (vWorkerId); + SET vWorkerId = vBossId; + END IF; + END LOOP; + DROP TEMPORARY TABLE tCheckedWorker; + RETURN FALSE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `workerTimeControl_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `workerTimeControl_add`( vUserFk INT, vWarehouseFk INT, vTimed DATETIME, vIsManual BOOL) RETURNS int(11) + DETERMINISTIC +BEGIN + DECLARE vDirection VARCHAR(6); + DECLARE vLastIn DATETIME; + DECLARE vDayStayMax INT; + DECLARE vHasDirectionOut INT; + + SELECT dayStayMax INTO vDayStayMax + FROM vn.workerTimeControlParams; + + SELECT vn.timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; + + IF vDirection = 'out' THEN + + SELECT MAX(timed) INTO vLastIn + FROM vn.workerTimeControl + WHERE userFk = vUserFk + AND direction = 'in' + AND timed < vTimed; + + UPDATE vn.workerTimeControl wtc + SET wtc.direction = 'middle' + WHERE userFk = vUserFk + AND direction = 'out' + AND timed BETWEEN vLastIn AND vTimed; + + ELSE IF vDirection = 'in' THEN + + SELECT COUNT(*) INTO vHasDirectionOut + FROM vn.workerTimeControl wtc + WHERE userFk = vUserFk + AND direction = 'out' + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + + UPDATE vn.workerTimeControl wtc + SET wtc.direction = IF (vHasDirectionOut,'middle','out') + WHERE userFk = vUserFk + AND direction = 'in' + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + + END IF; + END IF; + + INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) + VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); + + +RETURN LAST_INSERT_ID(); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` 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 DROP FUNCTION IF EXISTS `zoneGeo_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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `zoneGeo_new`(vType VARCHAR(255), vName VARCHAR(255), vParentFk INT) RETURNS int(11) + NO SQL +BEGIN +/** + * Creates a new node a node from the #zoneGeo table. + * Also sets a mark to force the tree recalculation. + * + * @param vType The node type + * @param vName The node name + * @param vParentFk The parent node identifier + * @return The new node identifier + */ + DECLARE vSelf INT; + + INSERT INTO zoneGeo + SET `type` = vType, + `name` = vName, + parentFk = vParentFk; + + SET vSelf = LAST_INSERT_ID(); + + UPDATE zoneGeoRecalc SET isChanged = TRUE; + + RETURN vSelf; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `addNoteFromDelivery` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `addNoteFromDelivery`(idTicket INT,nota TEXT) +BEGIN + + DECLARE observationTypeFk INT DEFAULT 3; /*3 = REPARTIDOR*/ + + INSERT INTO ticketObservation(ticketFk,observationTypeFk,description) + VALUES (idTicket,observationTypeFk,nota) + ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(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 DROP PROCEDURE IF EXISTS `addressTaxArea` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `addressTaxArea`() + READS SQL DATA +BEGIN +/** + * Devuelve el taxArea para un conjunto de Consignatarios y empresas, + * + * @table tmp.addressCompany(addressFk, companyFk) valores a calcular + * @return tmp.addressTaxArea(addressFk,companyFk) + */ + + DECLARE vSpainCountryCode INT DEFAULT 1; + + DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; + CREATE TEMPORARY TABLE tmp.addressTaxArea + (PRIMARY KEY (addressFk, companyFk)) + ENGINE = MEMORY + SELECT CASE + WHEN (NOT cClient.isUeeMember OR NOT cSupplier.isUeeMember) AND s.countryFk != c.countryFk THEN + 'WORLD' + WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN + 'CEE' + WHEN a.isEqualizated AND c.countryFk = vSpainCountryCode THEN + 'EQU' + ELSE + 'NATIONAL' + END AS areaFk, ac.addressFk, ac.companyFk + FROM tmp.addressCompany ac + JOIN address a ON a.id = ac.addressFk + JOIN `client` c ON c.id = a.clientFk + JOIN country cClient ON cClient.id = c.countryFk + JOIN supplier s ON s.id = ac.companyFk + JOIN country cSupplier ON cSupplier.id = s.countryFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `agencyHourGetFirstShipped` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `agencyHourGetFirstShipped`(vAgencyMode INT, vAddress INT, vWarehouse INT) +BEGIN +/** + * DEPRECATED usar zoneGetFirstShipped +* Devuelve la primera fecha de envio disponible para una agencia en una direccion y un warehouse +* +* @param vAgencyMode id de la agencia en vn.agencyMode +* @param vAddress id de la direccion +* @param vWarehouse id del warehouse +* @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida +*/ +DECLARE vAgency INT; +DECLARE vShipped DATE; +DECLARE vLanded DATE DEFAULT CURDATE(); + SELECT agencyFk INTO vAgency FROM agencyMode WHERE id= vAgencyMode; + + l: LOOP + + CALL agencyHourGetShipped(vLanded,vAddress,vAgency); + SELECT shipped INTO vShipped + FROM tmp.agencyHourGetShipped + WHERE warehouseFk = vWarehouse LIMIT 1; + + IF vShipped THEN + LEAVE l; + END IF; + + SET vLanded = DATE_ADD(vLanded, INTERVAL +1 DAY); + + END LOOP; + + SELECT vShipped,vLanded; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `agencyHourGetLanded` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `agencyHourGetLanded`(vDated DATE, vAddress INT, vAgency INT, vWarehouse INT) +BEGIN +/** + * DEPRECATED usar zoneGetLanded + * Devuelve una tabla temporal con el dia de recepcion para vDated. + * + * @param vDated Fecha de preparacion de mercancia + * @param vAddress Id de consignatario, %NULL para recogida + * @param vAgency Id agencia + * @table tmp.agencyHourGetLanded Datos de recepción + */ + DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetLanded; + CREATE TEMPORARY TABLE tmp.agencyHourGetLanded + ENGINE = MEMORY + SELECT vWarehouse warehouseFk, landed FROM ( + SELECT * FROM ( + SELECT vWarehouse, TIMESTAMPADD(DAY, ah.substractDay, vDated) landed, ah.substractDay, ah.maxHour + FROM agencyHour ah + LEFT JOIN address a ON a.id = vAddress + WHERE (ah.weekDay = WEEKDAY(TIMESTAMPADD(DAY, ah.substractDay, vDated)) OR ah.weekDay IS NULL) + AND (ah.agencyFk = vAgency OR ah.agencyFk IS NULL) + AND ah.warehouseFk = vWarehouse + AND (ah.provinceFk = a.provinceFk OR ah.provinceFk IS NULL OR vAddress IS NULL) + ORDER BY ( + (ah.weekDay IS NOT NULL) + + (ah.agencyFk IS NOT NULL) + + (- ah.substractDay) + + ((ah.provinceFk IS NOT NULL)*3) + ) DESC + ) t + LIMIT 1 + ) t + WHERE IF(vDated = CURDATE(), t.maxHour > HOUR(NOW()), TRUE) AND t.substractDay < 225; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `agencyHourGetWarehouse` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `agencyHourGetWarehouse`(vAddress INT, vDate DATE, vWarehouse INT) +BEGIN +/** + * DEPRECATED usar zoneGetWarehouse + * Devuelve el listado de agencias disponibles para la fecha, + * dirección y warehouuse pasadas + * + * @param vAddress no puede ser NULL + * @param vWarehouse warehouse donde comprobaremos las agencias y fecha + * @param vDate Fecha de recogida + * @table agencyModeWarehouseList Listado de agencias disponibles + */ + DECLARE vAgency INT; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vCur CURSOR FOR + SELECT DISTINCT a.id + FROM agency a + JOIN agencyHour ah ON ah.agencyFk = a.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + IF vAddress IS NULL + THEN + CALL util.throw ('Address cannot be null'); + END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.agencyModeWarehouseList; + CREATE TEMPORARY TABLE tmp.agencyModeWarehouseList ( + id INT NOT NULL, + agency VARCHAR(20), + description VARCHAR(45), + deliveryMethodFk VARCHAR(45), + shipped DATE, + warehouse VARCHAR(45), + PRIMARY KEY(id) + ) + ENGINE = MEMORY; + + OPEN vCur; + FETCH vCur INTO vAgency; + + WHILE NOT vDone + DO + + INSERT INTO tmp.agencyModeWarehouseList + SELECT am.id, am.name, am.description,am.deliveryMethodFk, TIMESTAMPADD(DAY, -ah.substractDay, vDate), w.name + FROM agencyHour ah + LEFT JOIN address a ON a.id = vAddress + JOIN agencyMode am ON am.agencyFk = vAgency + JOIN warehouse w on w.id = ah.warehouseFk + WHERE ah.warehouseFk = vWarehouse + AND (weekDay = WEEKDAY(vDate) + OR weekDay IS NULL) + AND (ah.agencyFk = vAgency + OR ah.agencyFk IS NULL) + AND (ah.provinceFk = a.provinceFk + OR ah.provinceFk IS NULL + OR vAddress IS NULL) + AND TIMESTAMPADD(DAY, -ah.substractDay, vDate) >= CURDATE() + AND IF(TIMESTAMPADD(DAY, -ah.substractDay, vDate) = CURDATE(), ah.maxHour > HOUR(NOW()), TRUE) + ORDER BY ( + (ah.weekDay IS NOT NULL) + + (ah.agencyFk IS NOT NULL) + + ((ah.provinceFk IS NOT NULL) * 3) + ) DESC + LIMIT 1; + + + FETCH vCur INTO vAgency; + END WHILE; + + CLOSE vCur; + + SELECT * FROM tmp.agencyModeWarehouseList; + DROP TEMPORARY TABLE tmp.agencyModeWarehouseList; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `agencyHourListGetShipped` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `agencyHourListGetShipped`(vDate DATE, vAddress INT, vAgency INT) +BEGIN + /* * DEPRECATED usar zoneGetShipped +*/ + CALL vn.agencyHourGetShipped(vDate, vAddress, vAgency); + + SELECT * FROM tmp.agencyHourGetShipped; + + DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `available_calc` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `available_calc`( + vDate DATE, + vAddress INT, + vAgencyMode INT) +BEGIN +/** + * Calculates the available for all available stores + * according to the given parameters. + * + * @param vDate The delivery date + * @param vAddress The delivery address id + * @param vAgencyMode The shipping agency + * @return tmp.availableCalc(calcFk) The available cache ids + */ + DECLARE vCalcFk INT; + DECLARE vShipment DATE; + DECLARE vWarehouse INT; + DECLARE vDone BOOL; + + DECLARE cWarehouses CURSOR FOR + SELECT warehouseFk, shipped FROM tmp.zoneGetShipped; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + -- Establecemos los almacenes y las fechas que van a entrar al disponible + + CALL vn.zoneGetShippedWarehouse(vDate, vAddress, vAgencyMode); + + DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; + CREATE TEMPORARY TABLE tmp.availableCalc( + calcFk INT UNSIGNED, + PRIMARY KEY (calcFk) + ) + ENGINE = MEMORY; + + OPEN cWarehouses; + + l: LOOP + SET vDone = FALSE; + FETCH cWarehouses INTO vWarehouse, vShipment; + + IF vDone THEN + LEAVE l; + END IF; + + CALL `cache`.available_refresh(vCalcFk, FALSE, vWarehouse, vShipment); + + INSERT IGNORE INTO tmp.availableCalc + SET calcFk = vCalcFk; + END LOOP; + + CLOSE cWarehouses; + DROP TEMPORARY TABLE tmp.zoneGetShipped; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `buyUltimate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `buyUltimate`(vWarehouseFk SMALLINT, vDate DATE) +BEGIN +/** + * Calcula las últimas compras realizadas hasta una fecha + * + * @param vWarehouseFk Id del almacén + * @param vDate Compras hasta fecha + * @return tmp.buyUltimate + */ + CALL cache.last_buy_refresh (FALSE); + + DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate; + CREATE TEMPORARY TABLE tmp.buyUltimate + (PRIMARY KEY (itemFk, warehouseFk), + INDEX(itemFk)) + ENGINE = MEMORY + SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk + FROM cache.last_buy + WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL; + + CALL vn.buyUltimateFromInterval(vWarehouseFk, CURDATE(), vDate); + + REPLACE INTO tmp.buyUltimate + SELECT itemFk, buyFk, warehouseFk + FROM tmp.buyUltimateFromInterval + WHERE warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL; + + DROP TEMPORARY TABLE tmp.buyUltimateFromInterval; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `buyUltimateFromInterval` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `buyUltimateFromInterval`(vWarehouseFk SMALLINT, vStarted DATE, vEnded DATE) +BEGIN +/** + * Calcula las últimas compras realizadas + * desde un rango de fechas. + * + * @param vWarehouseFk Id del almacén + * @param vStarted Fecha inicial + * @param vEnded Fecha fin + * @return tmp.buyUltimateFromInterval + */ + IF vEnded IS NULL THEN + SET vEnded = vStarted; + END IF; + + IF vEnded < vStarted THEN + SET vStarted = TIMESTAMPADD(MONTH, -1, vEnded); + END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval; + CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval + (INDEX (itemFk), INDEX(buyFk)) ENGINE = MEMORY + SELECT + b.itemFk, + t.warehouseInFk warehouseFk, + MULTIMAX(t.landed, b.id) buyFk, + MAX(t.landed) landed + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vStarted AND vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.price2 > 0 + AND NOT b.isIgnored + GROUP BY itemFk, warehouseInFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `buy_afterUpsert` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `buy_afterUpsert`(vSelf INT) +BEGIN +/** + * Triggered actions when a buy is updated or inserted. + * + * @param vSelf The buy reference + */ + DECLARE vEntryFk INT; + DECLARE vItemFk INT; + DECLARE vStickers INT; + DECLARE vPacking INT; + DECLARE vWarehouse INT; + DECLARE vWarehouseOut INT; + DECLARE vIsMerchandise BOOL; + DECLARE vIsFeedStock BOOL; + + SELECT entryFk, itemFk, stickers, packing + INTO vEntryFk, vItemFk, vStickers, vPacking + FROM buy + WHERE id = vSelf; + + SELECT t.warehouseInFk, t.warehouseOutFk + INTO vWarehouse, vWarehouseOut + FROM entry e + JOIN travel t ON t.id = e.travelFk + WHERE e.id = vEntryFk; + + SELECT k.merchandise INTO vIsMerchandise + FROM itemCategory k + JOIN itemType it ON it.categoryFk = k.id + JOIN item i ON i.typeFk = it.id + WHERE i.id = vItemFk; + IF vIsMerchandise THEN + REPLACE bi.rotacion SET + Id_Article = vItemFk, + warehouse_id = vWarehouse, + cm3 = buy_getUnitVolume(vSelf); + END IF; + + SELECT isFeedStock INTO vIsFeedStock + FROM warehouse WHERE id = vWarehouseOut AND id <> 13; + + IF vIsFeedStock THEN + INSERT IGNORE INTO producer(`name`) + SELECT es.company_name + FROM buy b + JOIN edi.ekt be ON be.id = b.ektFk + JOIN edi.supplier es ON es.supplier_id = be.pro + WHERE b.id = vSelf; + + IF vn2008.has_notify_passport(vItemFk, vSelf) THEN + CALL vn.buy_notifyPassport(vSelf, vItemFk, vStickers, vPacking); + END IF; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `buy_afterUpsert__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `buy_afterUpsert__`(vSelf INT) +BEGIN +/** + * Triggered actions when a buy is updated or inserted. + * + * @param vSelf The buy reference + */ + DECLARE vEntryFk INT; + DECLARE vItemFk INT; + DECLARE vStickers INT; + DECLARE vPacking INT; + DECLARE vWarehouse INT; + DECLARE vWarehouseOut INT; + DECLARE vIsMerchandise BOOL; + DECLARE vIsFeedStock BOOL; + + SELECT entryFk, itemFk, stickers, packing + INTO vEntryFk, vItemFk, vStickers, vPacking + FROM buy + WHERE id = vSelf; + + SELECT t.warehouseInFk, t.warehouseOutFk + INTO vWarehouse, vWarehouseOut + FROM entry e + JOIN travel t ON t.id = e.travelFk + WHERE e.id = vEntryFk; + + SELECT k.merchandise INTO vIsMerchandise + FROM itemCategory k + JOIN itemType it ON it.categoryFk = k.id + JOIN item i ON i.typeFk = it.id + WHERE i.id = vItemFk; + + IF vIsMerchandise THEN + REPLACE bi.rotacion SET + Id_Article = vItemFk, + warehouse_id = vWarehouse, + cm3 = buy_getUnitVolume(vSelf); + END IF; + + SELECT isFeedStock INTO vIsFeedStock + FROM warehouse WHERE id = vWarehouseOut AND id <> 13; + + IF vIsFeedStock AND buy_hasNotifyPassport(vSelf, vItemFk) THEN + CALL buy_notifyPassport(vSelf, vItemFk, vStickers, vPacking); + INSERT IGNORE INTO producer(`name`) + SELECT es.company_name + FROM buy b + JOIN edi.ekt be ON be.id = b.ektFk + JOIN edi.supplier es ON es.supplier_id = be.pro + WHERE b.id = vSelf; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `buy_checkGrouping` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `buy_checkGrouping`(vGrouping INT) +BEGIN +/** + * Checks the buy grouping, throws an error if it's invalid. + * + * @param vGrouping The grouping + */ + IF vGrouping = 0 THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Grouping cannot be zero'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `buy_notifyPassport` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `buy_notifyPassport`( + IN vBuyFk INT, + IN vItemFk INT, + IN vStickers SMALLINT, + IN vPacking SMALLINT +) +BEGIN + INSERT INTO vn.mail(`subject`,`body`,`sender`) + SELECT 'Solicitar pasaporte', + CONCAT( + 'Etiquetas: ', IFNULL(vStickers, 0), + ', Packing: ', IFNULL(vPacking, 0), + ', Nombre: ', IFNULL(i.`name`, 0), + ', buy_edi: ', IFNULL(e.id, 0), + ', Nombre botánico: ', IFNULL(g.latin_genus_name, ''), ' ', IFNULL(s.latin_species_name, ''), + ', Productor: ',IFNULL(es.company_name, IFNULL(p.`name`, '')) + ) + ,'ekt@verdnatura.es' + FROM item i + LEFT JOIN itemBotanical ib ON ib.itemFk = i.id + LEFT JOIN edi.genus g ON g.genus_id = ib.genusFk + LEFT JOIN edi.specie s ON IFNULL(s.specie_id, ib.specieFk) = ib.specieFk + LEFT JOIN producer p ON p.id = i.producerFk + LEFT JOIN buy b ON b.id = vBuyFk + LEFT JOIN edi.ekt e ON b.ektFk = e.id + LEFT JOIN edi.supplier es ON es.supplier_id = e.pro + WHERE i.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 DROP PROCEDURE IF EXISTS `camaraFutureVolume` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `camaraFutureVolume`(vWarehouseFk INT, vDateStart DATE, vDateEnd DATE) +BEGIN + + DECLARE vDated DATE; + DECLARE vSectorVolume INT; + DECLARE vLastDayVolume INT; + DECLARE vMinCamara INT; + + SET vDated = vDateStart; + + DROP TEMPORARY TABLE IF EXISTS tmp.camara; + + IF vDateStart = CURDATE() THEN + + CREATE TEMPORARY TABLE tmp.camara + SELECT vDated as dated, + CONCAT('sector ', sectorFk) as place, + FLOOR(SUM(ish.visible * r.cm3)/1000000) as m3 + FROM vn.itemShelving ish + JOIN bi.rotacion r ON r.Id_Article = ish.itemFk AND r.warehouse_id = vWarehouseFk + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk + WHERE s.warehouseFk = vWarehouseFk + GROUP BY p.sectorFk; + + SELECT m3 + INTO vSectorVolume + FROM tmp.camara + WHERE place LIKE 'sector%'; + + CALL cache.visible_refresh(@calc_id, FALSE, 1); + + INSERT INTO tmp.camara(dated, place, m3) + SELECT vDated, 'nicho', + FLOOR((SUM(v.visible * r.cm3) / 1000000) - vSectorVolume ) as m3 + FROM cache.visible v + JOIN bi.rotacion r ON r.Id_Article = v.item_id AND r.warehouse_id = vWarehouseFk + JOIN vn.item i ON i.id = v.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE calc_id = @calc_id + AND ic.merchandise; + + INSERT INTO tmp.camara(dated, place, m3) + SELECT vDated, 'entradas', FLOOR(SUM(iei.amount * r.cm3) / 1000000) as m3 + FROM vn2008.item_entry_in iei + JOIN bi.rotacion r ON r.Id_Article = iei.item_id AND r.warehouse_id = vWarehouseFk + JOIN vn.item i ON i.id = iei.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE ic.merchandise + AND dat = vDated + AND NOT received + AND NOT isVirtualStock + AND iei.warehouse_id = vWarehouseFk; + + INSERT INTO tmp.camara(dated, place, m3) + SELECT vDated, 'salidas', FLOOR(SUM(ieo.amount * r.cm3) / 1000000) as m3 + FROM vn2008.item_entry_out ieo + JOIN bi.rotacion r ON r.Id_Article = ieo.item_id AND r.warehouse_id = vWarehouseFk + JOIN vn.item i ON i.id = ieo.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE ic.merchandise + AND dat = vDated + AND NOT delivered + AND NOT isVirtualStock + AND ieo.warehouse_id = vWarehouseFk; + + INSERT INTO tmp.camara(dated, place, m3) + SELECT vDated, 'ventas', FLOOR(SUM(io.amount * r.cm3) / 1000000) as m3 + FROM vn2008.item_out io + JOIN bi.rotacion r ON r.Id_Article = io.item_id AND r.warehouse_id = vWarehouseFk + JOIN vn.item i ON i.id = io.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.ticketStateToday tst ON tst.ticket = io.ticketFk + JOIN vn.ticket t ON t.id = io.ticketFk + WHERE ic.merchandise + AND ic.id != 7 + AND t.clientFk NOT IN (200,400,50,450) + AND dat BETWEEN vDated AND util.dayend(vDated) + AND NOT tst.isPicked + AND io.warehouse_id = vWarehouseFk; + + ELSE + + CREATE TEMPORARY TABLE tmp.camara + SELECT vDated as dated, + 'entradas' as place, + FLOOR(SUM(iei.amount * r.cm3) / 1000000) as m3 + FROM vn2008.item_entry_in iei + JOIN bi.rotacion r ON r.Id_Article = iei.item_id AND r.warehouse_id = vWarehouseFk + JOIN vn.item i ON i.id = iei.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE ic.merchandise + AND dat = vDated + AND NOT isVirtualStock + AND iei.warehouse_id = vWarehouseFk; + + INSERT INTO tmp.camara(dated, place, m3) + SELECT vDated, 'salidas', FLOOR(SUM(ieo.amount * r.cm3) / 1000000) as m3 + FROM vn2008.item_entry_out ieo + JOIN bi.rotacion r ON r.Id_Article = ieo.item_id AND r.warehouse_id = vWarehouseFk + JOIN vn.item i ON i.id = ieo.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE ic.merchandise + AND dat = vDated + AND ieo.warehouse_id = vWarehouseFk; + + INSERT INTO tmp.camara(dated, place, m3) + SELECT vDated, 'ventas', FLOOR(SUM(io.amount * r.cm3) / 1000000) as m3 + FROM vn2008.item_out io + JOIN bi.rotacion r ON r.Id_Article = io.item_id AND r.warehouse_id = vWarehouseFk + JOIN vn.item i ON i.id = io.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.ticket t ON t.id = io.ticketFk + WHERE ic.merchandise + AND dat BETWEEN vDated AND util.dayend(vDated) + AND ic.id != 7 + AND t.clientFk NOT IN (200,400,50,450) + AND io.warehouse_id = vWarehouseFk; + + END IF; + + -- Resto de dias + WHILE vDated < vDateEnd DO + + SELECT SUM(IFNULL(m3,0)) INTO vLastDayVolume + FROM tmp.camara + WHERE dated = vDated; + + SET vDated = TIMESTAMPADD(DAY, 1, vDated); + + INSERT INTO tmp.camara(dated, place, m3) + VALUES( vDated, 'camara', vLastDayVolume); + + INSERT INTO tmp.camara(dated, place, m3) + SELECT vDated, 'entradas', FLOOR(SUM(iei.amount * r.cm3) / 1000000) as m3 + FROM vn2008.item_entry_in iei + JOIN bi.rotacion r ON r.Id_Article = iei.item_id AND r.warehouse_id = vWarehouseFk + JOIN vn.item i ON i.id = iei.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE ic.merchandise + AND dat = vDated + AND NOT isVirtualStock + AND iei.warehouse_id = vWarehouseFk; + + INSERT INTO tmp.camara(dated, place, m3) + SELECT vDated, 'salidas', FLOOR(SUM(ieo.amount * r.cm3) / 1000000) as m3 + FROM vn2008.item_entry_out ieo + JOIN bi.rotacion r ON r.Id_Article = ieo.item_id AND r.warehouse_id = vWarehouseFk + JOIN vn.item i ON i.id = ieo.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE ic.merchandise + AND dat = vDated + AND ieo.warehouse_id = vWarehouseFk; + + INSERT INTO tmp.camara(dated, place, m3) + SELECT vDated, 'ventas', FLOOR(SUM(io.amount * r.cm3) / 1000000) as m3 + FROM vn2008.item_out io + JOIN bi.rotacion r ON r.Id_Article = io.item_id AND r.warehouse_id = vWarehouseFk + JOIN vn.item i ON i.id = io.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.ticket t ON t.id = io.ticketFk + WHERE ic.merchandise + AND dat BETWEEN vDated AND util.dayend(vDated) + AND ic.id != 7 + AND t.clientFk NOT IN (200,400,50,450) + AND io.warehouse_id = vWarehouseFk; + + END WHILE; + + SELECT min(m3) INTO vMinCamara + FROM + (SELECT dated, sum(m3) m3 + FROM tmp.camara + GROUP BY dated) sub; + + UPDATE tmp.camara + SET m3 = m3 - vMinCamara + WHERE place = 'camara'; + + SELECT camara.* FROM tmp.camara; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `carrosOficialesANoOficiales` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `carrosOficialesANoOficiales`() +BEGIN + +DECLARE done BOOL DEFAULT FALSE; +DECLARE vClientFk INT; +DECLARE vQuantity INT; +DECLARE vTicketFk INT; +DECLARE vAgencyTypeFk INT DEFAULT 628; + + +DECLARE rs CURSOR FOR + SELECT clientFk, sum(quantity) as carros + FROM `ticketPackaging` tp + JOIN ticket t ON t.id = tp.ticketFk + WHERE packagingFk = 'cc' + and t.shipped between '2017-10-30' AND '2019-01-06 23:59:59' + group by clientFk + having carros != 0; + +DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + +OPEN rs; + +FETCH rs INTO vClientFk, vQuantity; + +-- WHILE NOT done DO + + CALL vn.ticketCreate(vClientFk, '2019-01-06', 13, 442, NULL, vAgencyTypeFk, NULL, '2019-01-01', vTicketFk); + + INSERT INTO vn.ticketPackaging(ticketFk, packagingFk, quantity) + VALUES (vTicketFk, 'cc', - VQuantity); + + INSERT INTO vn.ticketPackaging(ticketFk, packagingFk, quantity) + VALUES (vTicketFk, 'dc', VQuantity); + + INSERT INTO vn.sale(ticketFk, itemFk, concept) + VALUES (vTicketFk, 90, 'Regularización CCs 2019'); + + CALL vn.`ticketStateUpdate`(vTicketFk, 'DELIVERED'); -- entregado + +-- FETCH rs INTO vClientFk, vQuantity; + +-- END WHILE; + + +CLOSE rs; + +SELECT vTicketFk; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `catalog_calcFromItem` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calcFromItem`( + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT, + vItemFk INT) +BEGIN +/** + * Calculates available and price for a single item. + * + * @param vItemFk The item id + * @return tmp.ticketCalculateItem + * @return tmp.ticketComponentPrice + * @return tmp.ticketComponent + * @return tmp.ticketLot + * @return tmp.zoneGetShipped + */ + DROP TEMPORARY TABLE IF EXISTS tmp.item; + CREATE TEMPORARY TABLE tmp.item + ENGINE = MEMORY + SELECT vItemFk itemFk; + + CALL ticketCalculate(vLanded, vAddressFk, vAgencyModeFk); + DROP TEMPORARY TABLE tmp.item; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `catalog_calculate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calculate`( + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT) +proc: BEGIN +/** + * Calcula los articulos disponibles y sus precios + * + * @table tmp.item(itemFk) Listado de artículos a calcular + * @param vLanded Fecha de recepcion de mercancia + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.ticketCalculateItem(itemFk, available, producer, + * item, size, stems, category, inkFk, image, origin, price) + * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) + * @return tmp.ticketComponent + * @return tmp.ticketComponentPrice + * @return tmp.zoneGetShipped + + **/ + + DECLARE vAvailableCalc INT; + DECLARE vShipped DATE; + DECLARE vClient INT; + DECLARE vWarehouseFk SMALLINT; + DECLARE vZoneFk INT; + DECLARE vDone BOOL; + DECLARE cTravelTree CURSOR FOR + SELECT id, warehouseFk, shipped FROM tmp.zoneGetShipped; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + -- Establece los almacenes y las fechas que van a entrar al disponible + + SELECT clientFk INTO vClient + FROM address WHERE id = vAddressFk; + + CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot( + `warehouseFk` smallint(5) unsigned NOT NULL, + `itemFk` int(11) NOT NULL, + `available` double DEFAULT NULL, + `buyFk` int(11) DEFAULT NULL, + `fix` tinyint(3) unsigned DEFAULT '0', + KEY `itemFk` (`itemFk`), + KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH + ) ENGINE=MEMORY DEFAULT CHARSET=utf8; + + OPEN cTravelTree; + + l: LOOP + SET vDone = FALSE; + FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; + + IF vDone THEN + LEAVE l; + END IF; + + CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); + CALL buyUltimate (vWarehouseFk, vShipped); + + INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk) + SELECT vWarehouseFk, + i.item_id, + IFNULL(i.available, 0), + bu.buyFk + FROM `cache`.available i + JOIN tmp.item br ON br.itemFk = i.item_id + LEFT JOIN item it ON it.id = i.item_id + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id + WHERE i.calc_id = vAvailableCalc + AND it.id != 100 + AND i.available > 0; + + DROP TEMPORARY TABLE tmp.buyUltimate; + END LOOP; + + CLOSE cTravelTree; + + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; + CREATE TEMPORARY TABLE tmp.ticketCalculateItem + ENGINE = MEMORY + SELECT + b.itemFk, + SUM(b.available) available, + p.name producer, + i.name item, + i.size size, + i.stems, + i.category, + i.inkFk, + i.image, + o.code origin, + bl.price, + bl.priceKg + FROM tmp.ticketLot b + JOIN item i ON b.itemFk = i.id + LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible + JOIN origin o ON o.id = i.originFk + JOIN ( + SELECT MIN(price) price, itemFk, MIN(priceKg) priceKg + FROM tmp.ticketComponentPrice + GROUP BY itemFk + ) bl ON bl.itemFk = b.itemFk + GROUP BY b.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 DROP PROCEDURE IF EXISTS `catalog_componentCalculate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate`( + vZoneFk INT, + vAddressFk INT, + vShipped DATE) +proc: BEGIN +/** + * Calcula los componentes de los articulos de tmp.ticketLot + * + * @param vZoneFk para calcular el transporte + * @param vAgencyModeFk Id del modo de agencia + * @param tmp.ticketLot (warehouseFk,available,itemFk,buyFk) + * + * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, + * packing, grouping, groupingMode, buyFk, typeFk) + * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) + */ + DECLARE vClientFk INT; + DECLARE vGeneralInflationCoefficient INT DEFAULT 1; + DECLARE vMinimumDensityWeight INT DEFAULT 167; + DECLARE vBoxFreightItem INT DEFAULT 71; + DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; + DECLARE vSpecialPriceComponent INT DEFAULT 10; + DECLARE vDeliveryComponent INT DEFAULT 15; + DECLARE vRecoveryComponent INT DEFAULT 17; + DECLARE vSellByPacketComponent INT DEFAULT 22; + DECLARE vBuyValueComponent INT DEFAULT 28; + DECLARE vMarginComponent INT DEFAULT 29; + DECLARE vDiscountLastItemComponent INT DEFAULT 32; + DECLARE vExtraBaggedComponent INT DEFAULT 38; + DECLARE vManaAutoComponent INT DEFAULT 39; + + SELECT volume INTO vBoxVolume + FROM vn.packaging + WHERE id = '94'; + + SELECT clientFk INTO vClientFK + FROM address + WHERE id = vAddressFk; + + SET @rate2 := 0; + SET @rate3 := 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; + CREATE TEMPORARY TABLE tmp.ticketComponentCalculate + (PRIMARY KEY (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT + tl.itemFk, tl.warehouseFk, tl.available, + IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, + IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, + IFNULL(pf.rate3, 0) AS minPrice, + IFNULL(pf.packing, b.packing) packing, + IFNULL(pf.`grouping`, b.`grouping`) `grouping`, + ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, + tl.buyFk, + i.typeFk, + IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping + FROM tmp.ticketLot tl + JOIN buy b ON b.id = tl.buyFk + JOIN item i ON i.id = tl.itemFk + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk + LEFT JOIN ( + SELECT * FROM ( + SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, z.warehouseFk + FROM priceFixed pf + JOIN zone z ON z.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0 + WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC + ) tpf + GROUP BY tpf.itemFk, tpf.warehouseFk + ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk + WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; + CREATE TEMPORARY TABLE tmp.ticketComponent ( + `warehouseFk` INT UNSIGNED NOT NULL, + `itemFk` INT NOT NULL, + `componentFk` INT UNSIGNED NOT NULL, + `cost` DECIMAL(10,4) NOT NULL, + INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), + UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)); + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vBuyValueComponent, + b.buyingValue + b.freightValue + b.packageValue + b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vMarginComponent, + tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; + CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY + SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk + FROM tmp.ticketComponent tc + GROUP BY tc.itemFk, warehouseFk; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3) + FROM tmp.ticketComponentBase tcb + JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk + WHERE cr.recobro > 0.009; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto + FROM tmp.ticketComponentBase tcb + JOIN `client` c on c.id = vClientFk + JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador + WHERE ms.prices_modifier_activated + HAVING manaAuto <> 0; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, + tcb.itemFk, + cr.id, + GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3) + FROM tmp.ticketComponentBase tcb + JOIN componentRate cr + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFK, + tcc.itemFk, + vDeliveryComponent, + vGeneralInflationCoefficient + * ROUND(( + i.compression + * r.cm3 + * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) + * IFNULL((z.price - z.bonus) + * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 + ) cost + FROM tmp.ticketComponentCalculate tcc + JOIN item i ON i.id = tcc.itemFk + JOIN zone z ON z.id = vZoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk + AND r.Id_Article = tcc.itemFk + HAVING cost <> 0; + + IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost + FROM tmp.ticketComponentCalculate tcc + JOIN vn.addressForPackaging ap + WHERE ap.addressFk = vAddressFk; + END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; + CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY + SELECT * FROM tmp.ticketComponent; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, + tcc.itemFk, + vSpecialPriceComponent, + sp.value - SUM(tcc.cost) sumCost + FROM tmp.ticketComponentCopy tcc + JOIN componentRate cr ON cr.id = tcc.componentFk + JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk + WHERE cr.classRate IS NULL + GROUP BY tcc.itemFk, tcc.warehouseFk + HAVING ABS(sumCost) > 0.001; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; + CREATE TEMPORARY TABLE tmp.ticketComponentSum + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate + FROM tmp.ticketComponent tc + JOIN componentRate cr ON cr.id = tc.componentFk + GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; + CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY + SELECT tcc.warehouseFk, + tcc.itemFk, + 1 rate, + IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 1) = 1 + AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 2 rate, + tcc.packing `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 + AND tcc.packing > 0 AND tcc.available >= tcc.packing) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 3 rate, + tcc.available `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 3) = 3 + GROUP BY tcs.warehouseFk, tcs.itemFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; + CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY + SELECT * FROM ( + SELECT * FROM tmp.ticketComponentRate ORDER BY price + ) t + GROUP BY itemFk, warehouseFk, `grouping`; + + DROP TEMPORARY TABLE + tmp.ticketComponentCalculate, + tmp.ticketComponentSum, + tmp.ticketComponentBase, + tmp.ticketComponentRate, + tmp.ticketComponentCopy; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clean` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clean`() +BEGIN + DECLARE vDateShort DATETIME; + DECLARE vOneYearAgo DATE; + DECLARE vFourYearsAgo DATE; + DECLARE v18Month DATE; + DECLARE v26Month DATE; + DECLARE v3Month DATE; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET vOneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); + SET vFourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); + SET v18Month = TIMESTAMPADD(MONTH, -18,CURDATE()); + SET v26Month = TIMESTAMPADD(MONTH, -26,CURDATE()); + SET v3Month = TIMESTAMPADD(MONTH, -3, CURDATE()); + + DELETE FROM workerTimeControlLog WHERE created < vDateShort; + DELETE FROM `message` WHERE sendDate < vDateShort; + DELETE FROM messageInbox WHERE sendDate < vDateShort; + DELETE FROM messageInbox WHERE sendDate < vDateShort; + DELETE FROM workerTimeControl WHERE timed < vFourYearsAgo; + DELETE FROM itemShelving WHERE created < CURDATE() AND visible = 0; + DELETE FROM ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); + DELETE FROM entryLog WHERE creationDate < vDateShort; + DELETE FROM expedition WHERE created < v26Month; + DELETE FROM sms WHERE created < v18Month; + DELETE FROM saleTracking WHERE created < vDateShort; + DELETE tobs FROM ticketObservation tobs + JOIN ticket t ON tobs.ticketFk = t.id WHERE t.shipped < vDateShort; + DELETE FROM sharingCart where ended < vDateShort; + DELETE FROM sharingClient where ended < vDateShort; + DELETE tw.* FROM ticketWeekly tw + LEFT JOIN sale s ON s.ticketFk = tw.ticketFk WHERE s.itemFk IS NULL; + DELETE FROM claim WHERE ticketCreated < v18Month; + DELETE FROM message WHERE sendDate < vDateShort; + DELETE sc FROM saleChecked sc + JOIN sale s ON sc.saleFk = s.id WHERE s.created < vDateShort; + DELETE bm + FROM buyMark bm + JOIN buy b ON b.id = bm.id + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed <= vDateShort; + DELETE FROM stowaway WHERE created < v3Month; + + -- Equipos duplicados + DELETE w.* + FROM workerTeam w + JOIN (SELECT id, team, workerFk, COUNT(*) - 1 as duplicated + FROM workerTeam + GROUP BY team,workerFk + HAVING duplicated + ) d ON d.team = w.team AND d.workerFk = w.workerFk AND d.id != w.id; + + -- CAP 29/10/2018 Mantenimiento tabla Movimientos_componentes + DELETE sc + FROM saleComponent sc + JOIN sale s + ON s.id= sc.saleFk + JOIN ticket t + ON t.id= s.ticketFk + WHERE t.shipped < v18Month; + CALL shelving_clean; + + CALL ticketPackagingRecovery; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clean__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clean__`() +BEGIN + DECLARE vDateShort DATETIME; + DECLARE oneYearAgo DATE; + DECLARE twoYearsAgo DATE; + DECLARE fourYearsAgo DATE; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); + SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE()); + SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); + + DELETE FROM vn.message WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo; + DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0; + DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); + CALL shelving_clean; + + CALL vn.ticketPackagingRecovery; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clearShelvingList` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clearShelvingList`(vShelvingFk VARCHAR(8)) +BEGIN + + UPDATE vn.itemShelving + SET visible = 0, available = 0 + WHERE shelvingFk COLLATE utf8_unicode_ci =vShelvingFk COLLATE utf8_unicode_ci; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientCreate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientCreate`( + vFirstname VARCHAR(50), + vSurnames VARCHAR(50), + vFi VARCHAR(9), + vAddress TEXT, + vPostcode CHAR(5), + vCity VARCHAR(25), + vProvinceFk SMALLINT(5), + vCompanyFk SMALLINT(5), + vPhone VARCHAR(11), + vUserFk INT) +BEGIN +/** + * Create new client + * + */ + DECLARE vPayMethodFk INT DEFAULT 4; + DECLARE vDueDay INT DEFAULT 5; + DECLARE vDefaultCredit DECIMAL(10, 2) DEFAULT 300.00; + DECLARE vIsTaxDataChecked TINYINT(1) DEFAULT 1; + DECLARE vHasCoreVnl BOOLEAN DEFAULT TRUE; + DECLARE vMandateTypeFk INT DEFAULT 2; + + INSERT INTO `client` ( + id, + name, + street, + fi, + phone, + provinceFk, + city, + postcode, + socialName, + payMethodFk, + dueDay, + credit, + isTaxDataChecked, + hasCoreVnl, + isEqualizated) + VALUES ( + vUserFk, + CONCAT('TR ', vFirstname, ' ', vSurnames), + vAddress, + TRIM(vFi), + vPhone, + vProvinceFk, + vCity, + vPostcode, + CONCAT(vSurnames, ' ', vFirstname), + vPayMethodFk, + vDueDay, + vDefaultCredit, + vIsTaxDataChecked, + vHasCoreVnl, + FALSE + ) ON duplicate key update + payMethodFk = vPayMethodFk, + dueDay = vDueDay, + credit = vDefaultCredit, + isTaxDataChecked = vIsTaxDataChecked, + hasCoreVnl = vHasCoreVnl, + isActive = TRUE; + + IF (SELECT COUNT(*) FROM mandate WHERE clientFk = vUserFk AND companyFk = vCompanyFk AND mandateTypeFk = vMandateTypeFk) = 0 THEN + INSERT INTO mandate (clientFk, companyFk, mandateTypeFk) + VALUES (vUserFk, vCompanyFk, vMandateTypeFk); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientDebtSpray` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientDebtSpray`(vClientFk INT) +BEGIN + + /* Reparte el saldo de un cliente en greuge en la cartera que corresponde, y desasigna el comercial + * + * + */ + + DECLARE vClientDebt DOUBLE; + + SELECT vn.clientGetDebt(vClientFk, CURDATE()) INTO vClientDebt; + + INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) + VALUES (vClientFk, 'Saldo pendiente', vClientDebt, CURDATE(), 5); + + CALL vn.clientGreugeSpray(vClientFk, TRUE, '', TRUE); + + INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) + SELECT vClientFk, 'Liquidación cliente', sum(amount), CURDATE(), 5 + FROM vn.greuge + WHERE clientFk = vClientFk; + + UPDATE vn.client + SET salesPersonFk = NULL + WHERE id = vClientFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientFreeze` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientFreeze`() +BEGIN + + UPDATE bi.defaulters d + JOIN vn.client c ON c.id = d.client + JOIN vn.config ON TRUE + SET c.isFreezed = TRUE, frozened = CURDATE() + WHERE d.amount > config.defaultersMaxAmount + AND d.`date` = CURDATE() + AND frozened IS NULL; + + IF day(CURDATE()) IN (5,15,25) THEN + + UPDATE vn.client c + JOIN bi.defaulters d ON d.client = c.id + JOIN vn.config ON TRUE + SET c.isFreezed = TRUE, frozened = CURDATE() + WHERE d.amount > config.defaultersMaxAmount + AND c.typeFk = 'normal' + AND d.date = CURDATE(); + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientGetDebt` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientGetDebt`(vDate DATE) +BEGIN +/** + * Calcula el riesgo para los clientes activos + * + * @table tmp.clientGetDebt(clientFk) + * @param vDate Fecha maxima de los registros + * @return tmp.risk + */ + DECLARE vStarted DATETIME DEFAULT TIMESTAMPADD(DAY, -35, CURDATE()); + DECLARE vEnded DATETIME; + + SET vEnded = TIMESTAMP(IFNULL(vDate, CURDATE()), '23:59:59'); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT id ticketFk, c.clientFk + FROM ticket t + JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk + WHERE refFk IS NULL + AND shipped BETWEEN vStarted AND vEnded; + + CALL ticketGetTotal(); + + DROP TEMPORARY TABLE IF EXISTS tClientRisk; + CREATE TEMPORARY TABLE tClientRisk + ENGINE = MEMORY + SELECT cr.customer_id clientFk, SUM(cr.amount) amount + FROM bi.customer_risk cr + JOIN tmp.clientGetDebt c ON c.clientFk = cr.customer_id + GROUP BY cr.customer_id; + + INSERT INTO tClientRisk + SELECT c.clientFk, SUM(r.amountPaid) + FROM receipt r + JOIN tmp.clientGetDebt c ON c.clientFk = r.clientFk + WHERE r.payed > vEnded + GROUP BY c.clientFk; + + INSERT INTO tClientRisk + SELECT t.clientFk, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)) + FROM hedera.tpvTransaction t + JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk + WHERE t.receiptFk IS NULL + AND t.status = 'ok' + GROUP BY t.clientFk; + + INSERT INTO tClientRisk + SELECT t.clientFk, total + FROM tmp.ticketTotal tt + JOIN tmp.ticket t ON t.ticketFk = tt.ticketFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.risk; + CREATE TEMPORARY TABLE tmp.risk + (PRIMARY KEY (clientFk)) + ENGINE = MEMORY + SELECT clientFk, SUM(amount) risk + FROM client c + JOIN tClientRisk cr ON cr.clientFk = c.id + WHERE c.isActive + GROUP BY c.id; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientGetDebtDiary` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientGetDebtDiary`(vClientFK INT, vCompanyFk INT) +BEGIN +/** + * Devuelve el registro de deuda + * + * @param vClientFK Id del cliente + * @param vCompanyFk Id de la empresa + */ + DECLARE vDone BOOL; + DECLARE vDate DATETIME; + DECLARE vTotalBalance DOUBLE DEFAULT 0.00; + DECLARE vCreated DATETIME; + DECLARE vIssued DATETIME; + DECLARE vBalance DOUBLE DEFAULT 0.00; + DECLARE cur CURSOR FOR + SELECT + created, + issued, + ROUND(amount, 2) AS balance + FROM invoiceOut + WHERE clientFk = vClientFk AND companyFk = vCompanyFk + UNION ALL + SELECT + created, + payed, + ROUND(-1 * amountPaid, 2) AS balance + FROM receipt + WHERE clientFk = vClientFk AND companyFk = vCompanyFk + ORDER BY issued, created; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN cur; + + proc: LOOP + SET vDone = FALSE; + + FETCH cur INTO vCreated, vIssued, vBalance; + + IF vDone THEN + LEAVE proc; + END IF; + + SET vTotalBalance = vTotalBalance + vBalance; + + IF CAST(ABS(vTotalBalance) AS UNSIGNED) = 0 THEN + SET vDate = vIssued; + SET vDone = TRUE; + END IF; + END LOOP; + + CLOSE cur; + + SELECT + issued, + CAST(debtOut AS DECIMAL(10,2)) debtOut, + CAST(debtIn AS DECIMAL(10,2)) debtIn, + ref, + companyFk, + priority + FROM + (SELECT + NULL AS issued, + SUM(amountUnpaid) AS debtOut, + NULL AS debtIn, + 'Saldo Anterior' AS ref, + companyFk, + 0 as priority + FROM + (SELECT SUM(amount) AS amountUnpaid, companyFk, 0 + FROM invoiceOut + WHERE clientFk = vClientFK + AND issued < vDate + GROUP BY companyFk + + UNION ALL + + SELECT SUM(-1 * amountPaid), companyFk, 0 + FROM receipt + WHERE clientFk = vClientFK + AND payed < vDate + GROUP BY companyFk) AS transactions + GROUP BY companyFk + + UNION ALL + + SELECT + issued, + amount as debtOut, + NULL AS debtIn, + ref, + companyFk, + 1 + FROM invoiceOut + WHERE clientFk = vClientFK + AND issued >= vDate + UNION ALL + + SELECT + r.payed, + NULL as debtOut, + r.amountPaid, + r.invoiceFk, + r.companyFk, + 0 + FROM receipt r + WHERE r.clientFk = vClientFK + AND r.payed >= vDate) t + INNER JOIN `client` c ON c.id = vClientFK + HAVING debtOut <> 0 OR debtIn <> 0 + ORDER BY issued, priority DESC, debtIn; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientGetDebt__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientGetDebt__`(vDate DATE) +BEGIN +/** + * Calcula el riesgo para los clientes activos + * + * @table tmp.clientGetDebt(clientFk) + * @param vDate Fecha maxima de los registros + * @return tmp.risk + */ + DECLARE vStarted DATETIME DEFAULT TIMESTAMPADD(DAY, - DAYOFMONTH(CURDATE()) - 5, CURDATE()); + DECLARE vEnded DATETIME; + + SET vEnded = TIMESTAMP(IFNULL(vDate, CURDATE()), '23:59:59'); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT id ticketFk, c.clientFk + FROM ticket t + JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk + WHERE refFk IS NULL + AND shipped BETWEEN vStarted AND vEnded; + + CALL ticketGetTotal(); + + DROP TEMPORARY TABLE IF EXISTS tClientRisk; + CREATE TEMPORARY TABLE tClientRisk + ENGINE = MEMORY + SELECT cr.customer_id clientFk, SUM(cr.amount) amount + FROM bi.customer_risk cr + JOIN tmp.clientGetDebt c ON c.clientFk = cr.customer_id + GROUP BY cr.customer_id; + + INSERT INTO tClientRisk + SELECT c.clientFk, SUM(r.amountPaid) + FROM receipt r + JOIN tmp.clientGetDebt c ON c.clientFk = r.clientFk + WHERE r.payed > vEnded + GROUP BY c.clientFk; + + INSERT INTO tClientRisk + SELECT t.clientFk, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)) + FROM hedera.tpvTransaction t + JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk + WHERE t.receiptFk IS NULL + AND t.status = 'ok' + GROUP BY t.clientFk; + + INSERT INTO tClientRisk + SELECT t.clientFk, total + FROM tmp.ticketTotal tt + JOIN tmp.ticket t ON t.ticketFk = tt.ticketFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.risk; + CREATE TEMPORARY TABLE tmp.risk + (PRIMARY KEY (clientFk)) + ENGINE = MEMORY + SELECT clientFk, SUM(amount) risk + FROM client c + JOIN tClientRisk cr ON cr.clientFk = c.id + WHERE c.isActive + GROUP BY c.id; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientGreugeSpray` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientGreugeSpray`(IN vClientFk INT, IN onlyForHisOwner BOOL, IN vWorkerCode VARCHAR(3), IN vWithMana BOOLEAN) +BEGIN + + DECLARE vGreuge DECIMAL(10,2); + DECLARE vOwner INT; + DECLARE vTotalSale INT; + DECLARE vGreugeTypeFk INT DEFAULT 5; -- HERENCIA + DECLARE vGreugeTypeMana INT DEFAULT 3;-- Maná + DECLARE vMana DECIMAL(10,2); + + SELECT vn.clientGetMana(vClientFk) INTO vMana; + + IF vWithMana AND vMana THEN + + INSERT INTO vn.greuge( clientFk, + description, + amount, + shipped, + greugeTypeFk) + VALUES( vClientFk, + 'Desasignación', + -1 * vMana, + CURDATE(), + vGreugeTypeMana); + + END IF; + + SELECT sum(amount) INTO vGreuge + FROM vn.greuge + WHERE clientFk = vClientFk; + + IF vGreuge != 0 THEN + + IF LENGTH(vWorkerCode) = 0 THEN + + SELECT salesPersonFk INTO vOwner + FROM vn.client + WHERE id = vClientFk; + + ELSE + + SELECT id INTO vOwner + FROM vn.worker + WHERE code = vWorkerCode COLLATE utf8_general_ci; + + END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientList; + CREATE TEMPORARY TABLE tmp.clientList + SELECT DISTINCT t.clientFk, floor(cr.yearSale / 12) AS monthSale + FROM vn.ticket t + JOIN vn.client c ON c.id = t.clientFk + JOIN vn.manaSpellers ms ON ms.worker = c.salesPersonFk + JOIN vn.claimRatio cr ON cr.clientFk = c.id + WHERE ms.worker = IF(onlyForHisOwner, vOwner, ms.worker) + AND t.shipped >= TIMESTAMPADD(MONTH,-1,CURDATE()) + AND c.id != vClientFk + HAVING monthSale > 100; + + SELECT SUM(monthSale) INTO vTotalSale + FROM tmp.clientList; + + INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) + SELECT clientFk, CONCAT('Cliente: ',vClientFk), vGreuge * monthSale / vTotalSale, CURDATE(), vGreugeTypeFk + FROM tmp.clientList + UNION ALL + SELECT vClientFk, 'Reparto greuge', -vGreuge, CURDATE(), vGreugeTypeFk; + + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientPackagingOverstock` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientPackagingOverstock`(vClientFk INT, vGraceDays INT ) +BEGIN + -- Bernat: WORKING IN THIS FILE + DROP TEMPORARY TABLE IF EXISTS tmp.clientPackagingOverstock; + CREATE TEMPORARY TABLE tmp.clientPackagingOverstock + ENGINE = MEMORY + SELECT itemFk, + sum(GotfromClient) - sum(SenttoClient) as devueltos, + sum(InvoicedtoClient) - sum(InvoicedfromClient) as facturados, + LEAST( + sum(GotfromClient) - sum(SenttoClient), + sum(InvoicedtoClient) - sum(InvoicedfromClient) + ) as abonables + + FROM + ( + + SELECT t.*, + IF(@month = month, 0, 1) monthEnd, + @month := month + FROM + ( + SELECT x.id as ticketFk, + date(x.shipped) as shipped, + x.itemFk, + IFNULL(cast(sum(x.InvoicedtoClient) as DECIMAL(10,0)),0) InvoicedtoClient, + IFNULL(cast(sum(x.InvoicedfromClient) as DECIMAL(10,0)),0) InvoicedfromClient, + IFNULL(cast(sum(x.SenttoClient) as DECIMAL(10,0)),0) SenttoClient, + IFNULL(cast(sum(x.GotfromClient) as DECIMAL(10,0)),0) GotfromClient, + i.name as concept, + x.refFk as invoice, + month(shipped) month, + x.companyFk + + FROM + ( + + SELECT t.id, + t.shipped, + IFNULL(pe.equivalentFk, s.itemFk) itemFk, + IF(s.quantity > 0, s.quantity, NULL) InvoicedtoClient, + IF(s.quantity < 0, -s.quantity, NULL) InvoicedfromClient, + NULL SenttoClient, + NULL GotfromClient, + t.refFk, + @month := 0 month, + t.companyFk + FROM vn.sale s + JOIN vn.ticket t on t.id = s.ticketFk + JOIN vn2008.Cubos c ON c.item_id = s.itemFk + LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = s.itemFk + WHERE t.clientFk = vClientFk + AND t.shipped > '2017-11-30' + AND c.Retornable + + UNION ALL + + SELECT NULL, + '2017-11-30', + IFNULL(pe.equivalentFk, tps.itemFk) itemFk, + tps.sent InvoicedtoClient, + tps.returned InvoicedfromClient, + NULL SenttoClient, + NULL GotfromClient, + 'Histórico', + NULL, + NULL + + FROM vn.ticketPackagingStartingStock tps + LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = tps.itemFk + WHERE tps.clientFk = vClientFk + AND tps.isForgetable = FALSE + + UNION ALL + + SELECT t.id, + t.shipped, + IFNULL(pe.equivalentFk, p.itemFk) itemFk, + NULL, + NULL, + IF(tp.quantity > 0 AND t.shipped <= TIMESTAMPADD(DAY, - vGraceDays, CURDATE()), tp.quantity, NULL) SenttoClient, + IF(tp.quantity < 0, -tp.quantity, NULL) GotfromClient, + NULL AS refFk, + NULL, + t.companyFk + FROM vn.ticketPackaging tp + JOIN vn.ticket t on t.id = tp.ticketFk + JOIN vn.packaging p ON p.id = tp.packagingFk + LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = p.itemFk + WHERE t.clientFk = vClientFk + AND t.shipped > '2017-11-21' ) x + + JOIN vn.item i ON x.itemFk = i.id + GROUP BY x.id, x.itemFk + + ) t + ORDER BY itemFk, shipped DESC + ) t2 + GROUP BY itemFk + +; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientPackagingOverstockReturn` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientPackagingOverstockReturn`(vClientFk INT, vGraceDays INT ) +BEGIN + + DECLARE vNewTicket INT DEFAULT 0; + + IF account.myUserHasRole('administrative') THEN + + CALL vn.clientPackagingOverstock(vClientFk,vGraceDays); + + CALL vn.ticketCreate( + vClientFk + ,curdate() + ,1 -- Silla FV + ,442 -- Verdnatura + ,NULL -- address + ,2 -- Rec_Silla + ,NULL -- route + ,curdate() + ,vNewTicket); + + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price) + SELECT vNewTicket, cpo.itemFk, - cpo.abonables, i.longName, p.price + FROM tmp.clientPackagingOverstock cpo + JOIN vn.item i ON i.id = cpo.itemFk + JOIN vn.packaging p ON p.itemFk = cpo.itemFk + WHERE cpo.abonables > 0; + + INSERT INTO vn.ticketPackaging(ticketFk, packagingFk, quantity) + SELECT vNewTicket, p.id, cpo.abonables + FROM tmp.clientPackagingOverstock cpo + JOIN vn.packaging p ON p.itemFk = cpo.itemFk + WHERE cpo.abonables > 0; + + END IF; + + SELECT vNewTicket; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientRandomSelection` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientRandomSelection`(vNumero INT) +BEGIN + + DECLARE vClient INT; + + SET @vIndex := 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.client; + + CREATE TEMPORARY TABLE tmp.client + SELECT io.clientFk, + FALSE as isSelected, + @vIndex := @vIndex + 1 id + FROM vn.client c + JOIN vn.invoiceOut io ON io.clientFk = c.id + JOIN vn.address a ON a.clientFk = c.id + JOIN vn.province p ON p.id = a.provinceFk + WHERE p.name = 'MADRID' + AND io.issued = '2019-01-31' + AND a.isDefaultAddress + AND c.name NOT LIKE 'TR %'; + + WHILE vNumero DO + + SET vClient = FLOOR(RAND() * @vIndex + 1); + + IF (SELECT isSelected FROM tmp.client WHERE id = vClient) = FALSE THEN + + UPDATE tmp.client + SET isSelected = TRUE + WHERE id = vClient; + + SET vNumero = vNumero - 1; + + END IF; + + END WHILE; + + SELECT * FROM tmp.client JOIN vn.client c ON c.id = clientFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientRemoveWorker` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientRemoveWorker`() +BEGIN + DECLARE done BOOL DEFAULT FALSE; + DECLARE vClientFk INT; + + DECLARE rs CURSOR FOR + SELECT c.clientFk + FROM tmp.clientGetDebt c + LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk + WHERE IFNULL(r.risk,0) = 0; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + SELECT cd.id as clientFk + FROM bs.clientDied cd + LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id + JOIN vn.client c ON c.id = cd.id + JOIN vn.province p ON p.id = c.provinceFk + JOIN vn.country co ON co.id = p.countryFk + WHERE cd.Aviso = 'TERCER AVISO' + AND cp.clientFk IS NULL + AND co.country NOT IN ('Portugal','Francia','España exento') + AND c.salesPersonFk IS NOT NULL; + + CALL vn.clientGetDebt(curdate()); + + DROP TEMPORARY TABLE IF EXISTS tmp.contador; + CREATE TEMPORARY TABLE tmp.contador (id INT) + ENGINE = MEMORY; + + OPEN rs; + FETCH rs INTO vClientFk; + + WHILE NOT done DO + INSERT INTO tmp.contador SET id = vClientFk; + CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); + UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk; + + INSERT INTO vn.clientLog (originFk, userFk, `action`, description) + VALUES (vClientFk, account.userGetId(), 'update', CONCAT('Se ha desasignado el cliente por que no ha comprado en 3 meses')); + + REPLACE bs.clientNewBorn(clientFk, shipped) + VALUES(vClientFk, CURDATE()); + FETCH rs INTO vClientFk; + END WHILE; + + CLOSE rs; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clonTravelComplete` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clonTravelComplete`(IN `vTravelFk` INT, IN `vDateStart` DATE, IN `vDateEnd` DATE, IN `vRef` VARCHAR(255)) +BEGIN + -- BERNAT: WORKING IN THIS FILE + DECLARE vTravelNew INT; + DECLARE vEntryNew INT; + DECLARE vDone BIT DEFAULT 0; + DECLARE vAuxEntryFk INT; + DECLARE vRsEntry CURSOR FOR + SELECT e.id + FROM vn.entry e + JOIN vn.travel t + ON t.id = e.travelFk + WHERE e.travelFk = vTravelFk; + + DECLARE vRsBuy CURSOR FOR + SELECT b.* + FROM vn.buy b + JOIN vn.entry e + ON b.entryFk = e.id + WHERE e.travelFk = vTravelNew and b.entryFk=entryNew + ORDER BY e.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + INSERT INTO vn.travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg) + SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg + FROM vn.travel + WHERE id = vTravelFk; + + SET vTravelNew = LAST_INSERT_ID(); + SET vDone = 0; + OPEN vRsEntry ; + FETCH vRsEntry INTO vAuxEntryFk; + + WHILE NOT vDone DO + INSERT INTO vn.entry (supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + travelFk, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk) + SELECT supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + vTravelNew, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk + FROM vn.entry + WHERE id = vAuxEntryFk; + + SET vEntryNew = LAST_INSERT_ID(); + + /* INSERT INTO vn.buy ( + entryFk, + itemFk, + amount, + buyingValue, + quantity, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isCkecked) + SELECT + vEntryNew, + itemFk, + amount, + buyingValue, + quantity, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isCkecked + FROM buy + WHERE entryFk = vAuxEntryFk;*/ + + INSERT INTO vn2008.Compres (Id_Entrada, + Id_Article, + Cantidad, + Costefijo, + Id_Cubo, + Etiquetas, + Portefijo, + Embalajefijo, + Comisionfija, + Packing, + `grouping`, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP, + Productor, + Vida, + punteo) + SELECT vEntryNew, + Id_Article, + Cantidad, + Costefijo, + Id_Cubo, + Etiquetas, + Portefijo, + Embalajefijo, + Comisionfija, + Packing, + `grouping`, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP, + Productor, + Vida, + punteo + FROM vn2008.Compres + WHERE Id_Entrada = vAuxEntryFk; + + + FETCH vRsEntry INTO vAuxEntryFk; + END WHILE; + CLOSE vRsEntry; + COMMIT; + END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collectionStickers_print` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `collectionStickers_print`(vCollectionFk INT) +BEGIN + + UPDATE vn.ticket t + JOIN vn.ticketCollection tc ON tc.ticketFk = t.id + SET t.notes = CONCAT('COL ',vCollectionFk,'-',tc.`level`) + WHERE tc.collectionFk = vCollectionFk; + + INSERT INTO vn.printServerQueue(reportFk, param1, workerFk) + SELECT 23, tc.ticketFk, getUser() + FROM vn.ticketCollection tc + WHERE tc.collectionFk = vCollectionFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `copyComponentsFromSaleList` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `copyComponentsFromSaleList`(vTargetTicketFk INT) +BEGIN + +/* Copy sales and components to the target ticket +* +* ¡¡¡¡ Requires tmp.saleList(saleFk, itemFk, quantity, concept, price, discount, orden) !!!!! +* +* param VTargetTicketFk id del ticket a rellenar +*/ + + INSERT INTO vn.sale(ticketFk, itemFk, quantity,concept,price,discount) + SELECT vTargetTicketFk, itemFk, quantity,concept,price,discount + FROM tmp.saleList + ORDER BY orden; + + SET @order = 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.newSaleList; + + CREATE TEMPORARY TABLE tmp.newSaleList + SELECT id as saleFk, @order := @order + 1 as orden + FROM vn.sale + WHERE ticketFk = vTargetTicketFk + ORDER BY saleFk; + + INSERT INTO vn.saleComponent(saleFk,componentFk,value) + SELECT ns.saleFk, sc.componentFk, sc.value + FROM vn.saleComponent sc + JOIN tmp.saleList s ON s.saleFk = sc.saleFk + JOIN tmp.newSaleList ns ON ns.orden = s.orden; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `createPedidoInterno` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `createPedidoInterno`(vItemFk INT,vQuantity INT) +BEGIN + + + UPDATE vn.item SET upToDown = vQuantity WHERE 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 DROP PROCEDURE IF EXISTS `cristalBall` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `cristalBall`() +BEGIN +/* +*se utiliza en campaña +* sirve para tener un control del stock en Silla y fuentes +* +*/ + +DECLARE vLastDate DATETIME DEFAULT '2019-10-30 23:59'; +DECLARE vWarehouse INT DEFAULT 1; +DECLARE vPalletVolume INT DEFAULT 2200000; + +SELECT date(sub2.dat) dat, + sub2.longName, + sub2.size, + sub2.subName, + cast(sub2.entra as decimal(10,1)) as entra, + cast(sub2.sale as decimal(10,1)) as sale, + sub2.itemFk, + @saldo := entra + sale + ifnull(fue.pal,0) + IF(sub2.itemFk = @item, @saldo, 0) as saldo, + @item := sub2.itemFk as kk, + cast(fue.pal as decimal(10,1)) as pal +FROM +( + SELECT * FROM + ( + SELECT e.dat, + e.item_id as itemFk, + i.longName, + i.size, + i.subName, + sum(e.amount * r.cm3) / vPalletVolume as entra, + 0 as sale + FROM vn2008.item_entry_in e + JOIN vn.item i ON i.id = e.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN bi.rotacion r ON r.Id_Article = e.item_id AND r.warehouse_id = e.warehouse_id + WHERE e.dat BETWEEN CURDATE() AND vLastDate + AND e.warehouse_id = vWarehouse + AND ic.merchandise + AND e.isVirtualStock is FALSE + GROUP BY e.dat, e.item_id + + UNION ALL + + SELECT s.dat, + s.item_id as itemFk, + i.longName, + i.size, + i.subName, + 0 as entra, + sum(s.amount * r.cm3) / vPalletVolume as sale + FROM vn2008.item_out s + JOIN vn.item i ON i.id = s.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN bi.rotacion r ON r.Id_Article = s.item_id AND r.warehouse_id = s.warehouse_id + WHERE s.dat BETWEEN CURDATE() AND vLastDate + AND s.warehouse_id = vWarehouse + AND ic.merchandise + GROUP BY date(s.dat), s.item_id + + UNION ALL + + SELECT util.yesterday(), + @item := st.item_id as itemFk, + i.longName, + i.size, + i.subName, + st.amount * r.cm3 / vPalletVolume , + @saldo := 0 + FROM cache.stock st + JOIN vn.item i ON i.id = st.item_id + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN bi.rotacion r ON r.Id_Article = st.item_id AND r.warehouse_id = st.warehouse_id + WHERE st.warehouse_id = vWarehouse + AND ic.merchandise + + ) sub + ORDER BY itemFk, dat, entra DESC) sub2 + LEFT JOIN + ( + SELECT itemFk, + - sum(ish.visible ) * r.cm3 / vPalletVolume as pal + FROM vn.itemShelving ish + JOIN bi.rotacion r ON r.Id_Article = ish.itemFk AND r.warehouse_id = 1 + LEFT JOIN vn.shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN vn.parking p ON p.id = sh.parkingFk + WHERE (sh.code = 'FUE' OR p.code = 'FUE-PI') + GROUP BY itemFk) fue ON fue.itemFk = sub2.itemFk AND sub2.dat = util.yesterday() + ; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `crypt` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `crypt`(vText VARCHAR(255), vKey VARCHAR(255), OUT vResult VARCHAR(255) ) +BEGIN + + DECLARE vEncryptedText VARCHAR(255) DEFAULT ''; + + DECLARE vKeyLength INT; + DECLARE vKeyPosition INT DEFAULT 1; + DECLARE vKeyChar VARCHAR(1); + + DECLARE vTextLength INT; + DECLARE vTextPosition INT DEFAULT 1; + DECLARE vTextChar VARCHAR(1); + + DECLARE vEncryptedChar VARCHAR(1); + DECLARE vEncryptedCharPosition INT; + + DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz'; + DECLARE vChainTextPosition INT; + DECLARE vChainKeyPosition INT; + DECLARE vChainLength INT; + + DECLARE vInvalidadChars VARCHAR(255) DEFAULT ''; + + SET vTextLength = LENGTH(vText); + SET vKeyLength = LENGTH(vKey); + SET vChainLength = LENGTH(vChain); + + WHILE vTextPosition <= vTextLength DO + + SET vTextChar = MID(vText,vTextPosition,1); + SET vKeyChar = MID(vKey,vKeyPosition,1); + + SET vChainTextPosition = LOCATE(vTextChar, vChain); + SET vInvalidadChars = IF(vChainTextPosition, vInvalidadChars, CONCAT(vInvalidadChars,vTextChar)); + SET vChainKeyPosition = LOCATE(vKeyChar, vChain); + SET vEncryptedCharPosition = vChainTextPosition + vChainKeyPosition; + + IF vEncryptedCharPosition > vChainLength THEN + + SET vEncryptedCharPosition = vEncryptedCharPosition - vChainLength; + + END IF; + + SET vEncryptedChar = MID(vChain, vEncryptedCharPosition,1); + + SET vEncryptedText = CONCAT(vEncryptedText, vEncryptedChar); + + SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1); + SET vTextPosition = vTextPosition + 1; + + END WHILE; + + SET vResult = IF(LENGTH(vInvalidadChars), CONCAT('Caracteres no válidos: ',vInvalidadChars),vEncryptedText); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `cryptOff` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `cryptOff`(vText VARCHAR(255), vKey VARCHAR(255), OUT vResult VARCHAR(255)) +BEGIN + + DECLARE vUncryptedText VARCHAR(255) DEFAULT ''; + + DECLARE vKeyLength INT; + DECLARE vKeyPosition INT DEFAULT 1; + DECLARE vKeyChar VARCHAR(1); + + DECLARE vTextLength INT; + DECLARE vTextPosition INT DEFAULT 1; + DECLARE vTextChar VARCHAR(1); + + DECLARE vUncryptedChar VARCHAR(1); + DECLARE vUncryptedCharPosition INT; + + DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz'; + DECLARE vChainTextPosition INT; + DECLARE vChainKeyPosition INT; + DECLARE vChainLength INT; + + SET vTextLength = LENGTH(vText); + SET vKeyLength = LENGTH(vKey); + SET vChainLength = LENGTH(vChain); + + WHILE vTextPosition <= vTextLength DO + + SET vTextChar = MID(vText,vTextPosition,1); + SET vKeyChar = MID(vKey,vKeyPosition,1); + + SET vChainTextPosition = LOCATE(vTextChar, vChain); + SET vChainKeyPosition = LOCATE(vKeyChar, vChain); + SET vUncryptedCharPosition = vChainTextPosition - vChainKeyPosition; + + IF vUncryptedCharPosition < 1 THEN + + SET vUncryptedCharPosition = vUncryptedCharPosition + vChainLength; + + END IF; + + SET vUncryptedChar = MID(vChain, vUncryptedCharPosition,1); + + SET vUncryptedText = CONCAT(vUncryptedText, vUncryptedChar); + + SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1); + SET vTextPosition = vTextPosition + 1; + + END WHILE; + + SET vResult = vUncryptedText; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `dayMinuteWorker` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `dayMinuteWorker`(vDateFrom DATETIME, vDateTo DATETIME) +BEGIN + +DECLARE vDateStart DATETIME DEFAULT DATE(vDateFrom); +DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDateTo); + +SET @ordr := 0; +SET @user := 0; + +DROP TEMPORARY TABLE IF EXISTS tmp.dayMinuteWorker; +CREATE TEMPORARY TABLE tmp.dayMinuteWorker + ENGINE = MEMORY + SELECT sub3.id, + sub3.hh as Hora, + sub3.mm as Minuto, + sub3.userFk, + sub3.code as CodigoTrabajador, + sub3.firstname as Nombre, + sub3.lastName as Apellidos, + sub3.warehouseFk as Almacen, + w.name as NombreAlmacen + FROM vn.warehouse w + JOIN + ( + SELECT id, + hh, + mm, + userFk, + code, + firstname, + lastName, + @ordr := IF(@user != userFk,0,@ordr), + IF(@ordr MOD 2, 'presente','--') as estado, + @ordr := IFNULL(sub2.`order`,@ordr), + @user := IFNULL(sub2.`userFk`,@user), + warehouseFk + FROM + ( + SELECT dm.id, + dm.hh, + dm.mm, + users.userFk, + sub.`order`, + users.code, + firstName, + lastName, + users.warehouseFk + FROM dayMinute dm + JOIN + ( + SELECT DISTINCT wtc.userFk , + code , + firstName, + lastName, + IFNULL(warehouseFk,1) warehouseFk + FROM vn.workerTimeControl wtc + JOIN vn.worker w ON w.userFk = wtc.userFk + WHERE timed BETWEEN vDateStart AND vDateEnd + ) users + + LEFT JOIN + ( + SELECT `order`, + wtc.userFk, + hour(timed) * 100 + minute(timed) as dayMinuteFk + FROM vn.workerTimeControl wtc + WHERE timed BETWEEN vDateStart AND vDateEnd + ORDER BY wtc.userFk, `order` + ) sub ON sub.dayMinuteFk = dm.id AND sub.userFk = users.userFk + ORDER BY userFk,dm.id + ) sub2 + ) sub3 ON sub3.warehouseFk = w.id + WHERE estado = 'presente' + AND sub3.id BETWEEN HOUR(vDateFrom) *100 + MINUTE(vDateFrom) AND HOUR(vDateTo) *100 + MINUTE(vDateTo); +-- SELECT * FROM tmp.dayMinuteWorker; + + END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `department_calcTree` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTree`() +BEGIN +/** + * Calculates the #path, #lft, #rgt, #sons and #depth columns of + * the #department table. To build the tree, it uses the #parentFk + * column. + */ + DECLARE vIndex INT DEFAULT 0; + DECLARE vSons INT; + + DROP TEMPORARY TABLE IF EXISTS tNestedTree; + CREATE TEMPORARY TABLE tNestedTree + SELECT id, path, lft, rgt, depth, sons + FROM department LIMIT 0; + + SET max_sp_recursion_depth = 5; + CALL department_calcTreeRec(NULL, '/', 0, vIndex, vSons); + SET max_sp_recursion_depth = 0; + + UPDATE department z + JOIN tNestedTree t ON t.id = z.id + SET z.path = t.path, + z.lft = t.lft, + z.rgt = t.rgt, + z.depth = t.depth, + z.sons = t.sons; + + DROP TEMPORARY TABLE tNestedTree; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `department_calcTreeRec` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTreeRec`( + vSelf INT, + vPath VARCHAR(255), + vDepth INT, + INOUT vIndex INT, + OUT vSons INT +) +BEGIN +/** + * Calculates and sets the #path, #lft, #rgt, #sons and #depth + * columns for all children of the passed node. Once calculated + * the last node rgt index and the number of sons are returned. + * To update it's children, this procedure calls itself recursively + * for each one. + * + * @vSelf The node identifier + * @vPath The initial path + * @vDepth The initial depth + * @vIndex The initial lft index + * @vSons The number of direct sons + */ + DECLARE vChildFk INT; + DECLARE vLft INT; + DECLARE vMySons INT; + DECLARE vDone BOOL; + DECLARE vChildren CURSOR FOR + SELECT id FROM department + WHERE (vSelf IS NULL AND parentFk IS NULL) + OR (vSelf IS NOT NULL AND parentFk = vSelf); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + SET vSons = 0; + + OPEN vChildren; + myLoop: LOOP + SET vDone = FALSE; + FETCH vChildren INTO vChildFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + SET vIndex = vIndex + 1; + SET vLft = vIndex; + SET vSons = vSons + 1; + + CALL department_calcTreeRec( + vChildFk, + CONCAT(vPath, vChildFk, '/'), + vDepth + 1, + vIndex, + vMySons + ); + + SET vIndex = vIndex + 1; + + INSERT INTO tNestedTree + SET id = vChildFk, + path = vPath, + lft = vLft, + rgt = vIndex, + depth = vDepth, + sons = vMySons; + END LOOP; + CLOSE vChildren; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `duaEntryValueUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `duaEntryValueUpdate`(vDuaFk INT) +BEGIN + + UPDATE duaEntry de + JOIN + ( SELECT b.entryFk, sum(b.quantity * b.buyingValue) as total + FROM buy b + JOIN duaEntry de ON de.entryFk = b.entryFk + WHERE duaFk = vDuaFk + GROUP BY b.entryFk + ) sub ON sub.entryFk = de.entryFk + + LEFT JOIN + (SELECT e.id, sum(iit.taxableBase) as euros + FROM entry e + JOIN invoiceInTax iit ON iit.invoiceInFk = e.invoiceInFk + JOIN duaEntry de ON de.entryFk = e.id + WHERE de.duaFk = vDuaFk + GROUP BY e.id + ) sub2 ON sub2.id = de.entryFk + + SET de.value = sub.total, + de.euroValue = sub2.euros + WHERE duaFk = vDuaFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `duaInvoiceInBooking` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `duaInvoiceInBooking`(vDuaFk INT) +BEGIN + + -- BERNAT: WORKING IN THIS FILE + DECLARE done BOOL DEFAULT FALSE; + DECLARE vInvoiceFk INT; + DECLARE vASIEN BIGINT DEFAULT 0; + DECLARE vCounter INT DEFAULT 0; + + DECLARE rs CURSOR FOR + SELECT e.invoiceInFk + FROM entry e + JOIN duaEntry de ON de.entryFk = e.id + JOIN invoiceIn ii ON ii.id = e.invoiceInFk + WHERE de.duaFk = vDuaFk + AND de.customsValue + AND ii.isBooked = FALSE; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + OPEN rs; + + UPDATE invoiceIn ii + JOIN entry e ON e.invoiceInFk = ii.id + JOIN duaEntry de ON de.entryFk = e.id + JOIN dua d ON d.id = de.duaFk + SET ii.isBooked = TRUE, + ii.booked = IFNULL(ii.booked,d.booked), + ii.operated = IFNULL(ii.operated,d.operated), + ii.issued = IFNULL(ii.issued,d.issued), + ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried), + e.isConfirmed = TRUE + WHERE d.id = vDuaFk; + + SELECT IFNULL(ASIEN,0) INTO vASIEN + FROM dua + WHERE id = vDuaFk; + + FETCH rs INTO vInvoiceFk; + + WHILE NOT done DO + + CALL invoiceInBookingMain(vInvoiceFk); + + IF vCounter > 0 OR vASIEN > 0 THEN + + UPDATE vn2008.XDiario x + JOIN vn.ledgerConfig lc ON lc.lastBookEntry = x.ASIEN + SET x.ASIEN = vASIEN; + + ELSE + + SELECT lastBookEntry INTO vASIEN FROM vn.ledgerConfig; + + END IF; + + SET vCounter = vCounter + 1; + + FETCH rs INTO vInvoiceFk; + + END WHILE; + + CLOSE rs; + + UPDATE dua + SET ASIEN = vASIEN + WHERE id = vDuaFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `duaParcialMake` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `duaParcialMake`(vDuaFk INT) +BEGIN + + DECLARE vNewDuaFk INT; + + INSERT INTO dua(awbFk,companyFk) + SELECT awbFk,companyFk + FROM dua + WHERE id = vDuaFk; + + SELECT LAST_INSERT_ID() INTO vNewDuaFk; + + INSERT INTO duaEntry(duaFk, entryFk, value, customsValue) + SELECT vNewDuaFk, entryFk, value, value - customsValue + FROM duaEntry + WHERE duaFk = vDuaFk + AND value != customsValue; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `duaTaxBooking` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `duaTaxBooking`(vDuaFk INT) +BEGIN + DECLARE vBookNumber INT; + DECLARE vBookDated DATE; + DECLARE vDiff DECIMAL(10,2); + DECLARE vApunte BIGINT; + + SELECT ASIEN, IFNULL(bookEntried, CURDATE()) INTO vBookNumber, vBookDated + FROM dua + WHERE id = vDuaFk; + + IF vBookNumber IS NULL OR NOT vBookNumber THEN + CALL ledger_next(vBookNumber); + END IF; + + -- Apunte de la aduana + + INSERT INTO XDiario( + ASIEN, + FECHA, + SUBCTA, + CONCEPTO, + EUROHABER, + SERIE, + empresa_id, + CLAVE, + FACTURA) + + SELECT + vBookNumber, + d.bookEntried, + '4700000999', + CONCAT('DUA ',d.code), + sum(di.amount * tr.rate / 100) EUROHABER, + 'R', + d.companyFk, + vDuaFk, + vDuaFk + FROM duaIntrastat di + JOIN intrastat ist ON ist.id = di.intrastatFk + JOIN (SELECT rate, taxClassFk + FROM + (SELECT rate, taxClassFk + FROM invoiceInTaxBookingAccount ta + WHERE ta.effectived <= vBookDated + ORDER BY ta.effectived DESC + ) tba + GROUP BY taxClassFk + ) tr ON tr.taxClassFk = ist.taxClassFk + JOIN dua d ON d.id = di.duaFk + WHERE di.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(s.countryFk IN (30, 1), 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 + ) tba + GROUP BY rate + ) tr ON tr.rate = dt.rate + JOIN supplier s ON s.id = d.companyFk + 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 + WHERE id = vApunte; + + UPDATE dua + SET ASIEN = vBookNumber + WHERE id = vDuaFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `duaTaxBooking__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `duaTaxBooking__`(vDuaFk INT) +BEGIN + -- BERNAT: WORKING IN THIS FILE + DECLARE vBookNumber INT; + DECLARE vBookDated DATE; + DECLARE vDiff DECIMAL(10,2); + DECLARE vApunte BIGINT; + + SELECT IFNULL(d.ASIEN,MAX(x.ASIEN) + 1 ) + INTO vBookNumber + FROM vn2008.XDiario x + LEFT JOIN dua d ON d.id = vDuaFk ; + + SELECT IFNULL(bookEntried, CURDATE()) INTO vBookDated + FROM dua + WHERE id = vDuaFk; + + -- Apunte de la aduana + + INSERT INTO vn2008.XDiario( + ASIEN, + FECHA, + SUBCTA, + CONCEPTO, + EUROHABER, + SERIE, + empresa_id, + CLAVE, + FACTURA) + + SELECT + vBookNumber, + d.bookEntried, + '4700000999', + CONCAT('DUA ',d.code), + sum(di.amount * tr.rate / 100) EUROHABER, + 'R', + d.companyFk, + vDuaFk, + vDuaFk + FROM duaIntrastat di + JOIN intrastat ist ON ist.id = di.intrastatFk + JOIN (SELECT rate, taxClassFk + FROM + (SELECT rate, taxClassFk + FROM invoiceInTaxBookingAccount ta + WHERE ta.effectived <= vBookDated + ORDER BY ta.effectived DESC + ) tba + GROUP BY taxClassFk + ) tr ON tr.taxClassFk = ist.taxClassFk + JOIN dua d ON d.id = di.duaFk + WHERE di.duaFk = vDuaFk; + + -- Apuntes por tipo de IVA y proveedor + + INSERT INTO vn2008.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(s.countryFk IN (30, 1), 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 + ) tba + GROUP BY rate + ) tr ON tr.rate = dt.rate + JOIN supplier s ON s.id = d.companyFk + WHERE d.id = vDuaFk + GROUP BY dt.rate; + + SELECT SUM(EURODEBE) -SUM(EUROHABER), MAX(id) INTO vDiff, vApunte + FROM vn2008.XDiario + WHERE ASIEN = vBookNumber; + + UPDATE vn2008.XDiario + SET BASEEURO = 100 * (EURODEBE - vDiff) / IVA, + EURODEBE = EURODEBE - vDiff + WHERE id = vApunte; + + UPDATE vn.dua + SET ASIEN = vBookNumber + WHERE id = vDuaFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `duaTaxUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `duaTaxUpdate`(vDuaFk INT) +BEGIN + + DECLARE vSPAIN INT DEFAULT 1; + DECLARE vDated DATE; + DECLARE vTotalDUABase DECIMAL(10,2); + + SELECT IFNULL(operated, CURDATE()) INTO vDated + FROM dua + WHERE id = vDuaFk; + + SELECT sum(amount) INTO vTotalDUABase + FROM duaIntrastat + WHERE duaFk = vDuaFk; + + DELETE FROM duaTax + WHERE duaFk = vDuaFk; + + INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base) + SELECT vDuaFk, supplierFk, taxClassFk, sum(sub.Base) as Base + FROM intrastat ist + JOIN + (SELECT + e.supplierFk, + i.intrastatFk, + CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) * di.amount/ tei.Base AS DECIMAL(10,2)) as Base + FROM buy b + JOIN item i ON i.id = b.itemFk + JOIN entry e ON e.id = b.entryFk + JOIN duaEntry de ON de.entryFk = e.id + JOIN + ( + SELECT i.intrastatFk, + CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) AS DECIMAL(10,2)) as Base + FROM buy b + JOIN item i ON i.id = b.itemFk + JOIN entry e ON e.id = b.entryFk + JOIN duaEntry de ON de.entryFk = e.id + WHERE de.duaFk = vDuaFk + GROUP BY i.intrastatFk + + ) tei ON tei.intrastatFk = i.intrastatFk + JOIN + ( + SELECT intrastatFk, sum(amount) as amount + FROM duaIntrastat + WHERE duaFk = vDuaFk + GROUP BY intrastatFK + ) di ON di.intrastatFk = i.intrastatFk + WHERE de.duaFk = vDuaFk + GROUP BY e.supplierFk, i.intrastatFk + HAVING Base + ) sub ON ist.id = sub.intrastatFk + GROUP BY ist.taxClassFk, sub.supplierFk; + + UPDATE duaTax dt + JOIN + (SELECT taxClassFk, rate + FROM + (SELECT taxClassFk, rate + FROM invoiceInTaxBookingAccount + WHERE effectived <= vDated + AND countryFk = vSPAIN + ORDER BY effectived DESC + ) ba1 + GROUP BY taxClassFk + ) ba2 ON dt.taxClassFk = ba2.taxClassFk + SET dt.rate = ba2.rate, + dt.tax = dt.base * ba2.rate / 100; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `energyMeter_record` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `energyMeter_record`(vInput INT, vActiveTime INT) +BEGIN + DECLARE vConsumption INT; + + SELECT consumption INTO vConsumption + FROM energyInput + WHERE input = vInput; + + INSERT INTO vn.energyMeter + SET + `input` = vInput, + `period` = DATE_FORMAT(NOW(), '%Y-%m-%d %H:00:00'), + `activeTime` = vActiveTime, + `consumption` = IFNULL((vConsumption / 3600) * vActiveTime, 0) + ON DUPLICATE KEY UPDATE + `activeTime` = `activeTime` + vActiveTime, + `consumption` = `consumption` + VALUES(`consumption`); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `entryConverter` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `entryConverter`(IN `vEntry` INT) +BEGIN + + DECLARE vWarehouseIn INT; + DECLARE vWarehouseOut INT; + DECLARE vTravel INT; + + DECLARE done BOOL DEFAULT FALSE; + + DECLARE vId_Entrada INT; + DECLARE vId_Article INT; + DECLARE vEtiquetas INT; + DECLARE vId_Cubo VARCHAR(10); + DECLARE vPacking INT; + DECLARE vGrouping INT; + DECLARE vCantidad INT; + DECLARE vCostefijo DECIMAL(10,3); + DECLARE vPortefijo DECIMAL(10,3); + DECLARE vEmbalajefijo DECIMAL(10); + DECLARE vComisionfija DECIMAL(10,3); + DECLARE vCaja INT; + DECLARE vNicho VARCHAR(5); + DECLARE vTarifa1 DECIMAL(10,2); + DECLARE vTarifa2 DECIMAL(10,2); + DECLARE vTarifa3 DECIMAL(10,2); + DECLARE vPVP DECIMAL(10,2); + DECLARE vCompra INT; + + DECLARE rs CURSOR FOR + SELECT + b.Id_Entrada, + b.Id_Article, + b.Etiquetas, + b.Id_Cubo, + b.Packing, + b.`grouping`, + b.Cantidad, + b.Costefijo, + b.Portefijo, + b.Embalajefijo, + b.Comisionfija, + b.caja, + b.Nicho, + b.Tarifa1, + b.Tarifa2, + b.Tarifa3, + b.PVP + FROM vn2008.Compres b + JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article + WHERE Id_Entrada = vEntry; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + SELECT warehouseInFk, warehouseOutFk, tr.id + INTO vWarehouseIn, vWarehouseOut, vTravel + FROM travel tr + JOIN entry e ON e.travelFk = tr.id + WHERE e.id = vEntry; + + UPDATE travel + SET warehouseInFk = vWarehouseOut, + warehouseOutFk = vWarehouseIn + WHERE id = vTravel; + + UPDATE vn2008.Compres c + LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article + SET Etiquetas = 0, Cantidad = 0 + WHERE c.Id_Entrada = vEntry + AND ic.espItemFk IS NULL; + + OPEN rs; + + DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + WHILE NOT done DO + + -- Primero la linea original con las cantidades invertidas + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + VALUES + ( + vId_Entrada, + vId_Article, + - vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + - vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP); + + -- Ahora la linea nueva, con el item genérico + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + SELECT + vId_Entrada, + genItemFk as Id_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP + FROM itemConversor + WHERE espItemFk = vId_Article; + + SELECT LAST_INSERT_ID() + INTO vCompra; + + REPLACE vn2008.Compres_mark(Id_Compra,`comment`) + SELECT vCompra, vId_Article; + + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + END WHILE; + + + CLOSE rs; + + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `entryDelivered` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `entryDelivered`(vDated DATE, vEntryFk INT) +BEGIN + + DECLARE vTravelFk INT; + + SELECT travelFk INTO vTravelFk + FROM vn.entry + WHERE id = vEntryFk; + + IF (SELECT COUNT(*) FROM vn.entry WHERE travelFk = vTravelFk) = 1 THEN + + UPDATE vn.travel SET shipped = LEAST(shipped, vDated), landed = vDated + WHERE id = vTravelFk; + + ELSE + + INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived) + SELECT LEAST(shipped, vDated), vDated, warehouseInFk, warehouseOutFk, agencyFk, CONCAT(account.userGetName(),' ', vEntryFk), TRUE, TRUE + FROM vn.travel WHERE id = vTravelFk; + + SELECT LAST_INSERT_ID() INTO vTravelFk; + + UPDATE vn.entry + SET travelFk = vTravelFk + WHERE id = vEntryFk; + + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `entryPrepare` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `entryPrepare`(IN `idE` BIGINT) +BEGIN + SELECT + b.quantity / b.packing AS Paquetes, + b.packing AS `Grouping`, + barcode, + 'ASEGURADO' AS asegurado, + ic.name, + ic.order, + s.name AS Consignatario, + e.supplierFk AS Id_Cliente, + e.isOrdered, + e.isConfirmed, + 10 AS Calidad, + LPAD(IFNULL(cpd.id, ip.code), + 5, + '0') AS path, + b.entryFk AS Id_Ticket, + t.landed AS Fecha, + b.itemFk, + b.quantity, + i.name AS Concepte, + i.size, + i.inkFk, + i.category, + o.code AS Origen, + 0 AS Bultos, + wIn.`name` AS Tipo, + 0 AS OK, + 0 AS Reservado, + i.stems, + b.id AS Id_Movimiento, + ip.code, + 'PEDIDO ASEGURADO' AS MSG, + 0 AS Seguro, + i.image, + pr.name AS producer + FROM vn.buy b + JOIN vn.entry e ON b.entryFk = e.id + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk + JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk + JOIN vn.item i ON i.id = b.itemFk + JOIN vn.itemType it ON it.id =i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.packaging pkg ON pkg.id = b.packageFk + LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk + LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN vn.supplier s ON s.id = e.supplierFk + LEFT JOIN vn.producer pr on pr.id = i.producerFk + LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway + WHERE + NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid + AND e.id = 158772 + AND i.typeFk IS NOT NULL + AND ic.merchandise IS NOT FALSE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `entrySplit_move` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `entrySplit_move`() +BEGIN + + /* CREATED PAK 08/09/2019 + * PENDING REVIEW + * + * + */ + + DROP TEMPORARY TABLE IF EXISTS itemList; + + CREATE TEMPORARY TABLE itemList + SELECT DISTINCT b.itemFk, es.delayedFk, es.receivedFk + FROM vn.buy b + JOIN vn.entrySplit es ON es.delayedFk = b.entryFk + JOIN vn.itemPlacement ip ON ip.itemFk = b.itemFk + WHERE ip.modificationDate > CURDATE(); + + INSERT INTO itemList + SELECT DISTINCT ish.itemFk, es.delayedFk, es.receivedFk + FROM vn.buy b + JOIN vn.entrySplit es ON es.delayedFk = b.entryFk + JOIN vn.itemShelving ish ON ish.itemFk = b.itemFk + WHERE ish.created > CURDATE(); + + + UPDATE vn.buy b + JOIN vn.itemList il ON il.delayedFk = b.entryFk AND b.itemFk = il.itemFk + SET b.entryFk = il.receivedFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `entryWithItem` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `entryWithItem`(IN `vShipmentWarehouse` INT, IN `vLandingWarehouse` INT, IN `vSale` INT, IN `vVolume` INT, IN netCost DECIMAL(10,2), IN `vInOutDate` DATE) +BEGIN + + DECLARE vTravel INT; + DECLARE vEntry INT; + DECLARE vBucket VARCHAR(10); + DECLARE vAgencyDirectFromProvider INT DEFAULT 15; + DECLARE vSupplierFk INT DEFAULT 963; + + + -- seleccionamos travel + SELECT t.id, e.id INTO vTravel, vEntry + FROM travel t LEFT JOIN entry e ON t.id = e.travelFk + WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse + AND t.warehouseInFk = vLandingWarehouse AND t.agencyFk = vAgencyDirectFromProvider AND e.supplierFk = vSupplierFk + LIMIT 1; + + -- creamos el travel si es necesario + IF IFNULL(vTravel, FALSE) = FALSE THEN + INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyFk) + VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse, vAgencyDirectFromProvider); + SELECT LAST_INSERT_ID() INTO vTravel; + END IF; + + -- creamos la Entrada si es necesario + IF IFNULL(vEntry, FALSE) = FALSE THEN + INSERT INTO entry (supplierFk, travelFk) + VALUES (vSupplierFk, vTravel); -- proveedor 'CONFECCION ARTIFICIAL' + SELECT LAST_INSERT_ID() INTO vEntry; + END IF; + + -- creamos el cubo si es necesario + SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; + IF vBucket IS NULL THEN + INSERT INTO packaging (id, volume) + VALUES (CONCAT('dm',vVolume/1000), vVolume); + SELECT LAST_INSERT_ID() INTO vBucket; + END IF; + + INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, `grouping`, stickers, buyingValue, price2, price3) + SELECT itemFk, + quantity, + vEntry, + vBucket, + 1 packing, + 1 `grouping`, + quantity, + netCost, + s.price, + s.price + FROM sale s + WHERE s.id = vSale; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `entry_getRate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `entry_getRate`(vEntry INT) +BEGIN + DECLARE vLanded DATE; + DECLARE vWarehouseFk INT; + + -- Obtiene fecha de llegada y almacén entrante + + SELECT landed, warehouseInFk INTO vLanded, vWarehouseFk + FROM vn.travel t + JOIN vn.entry e ON t.id = e.travelFk + WHERE e.id = vEntry; + + -- Prepara una tabla con las tarifas aplicables en funcion de la fecha y el almacén + + DROP TEMPORARY TABLE IF EXISTS tmp.rate; + CREATE TEMPORARY TABLE tmp.rate + ENGINE = MEMORY + SELECT * FROM + ( + SELECT * FROM + ( + SELECT rate0, rate1, rate2, rate3 + FROM vn.rate + WHERE dated <= vLanded + AND warehouseFk = vWarehouseFk + ORDER BY dated DESC + + ) sub + UNION ALL + SELECT rate0, rate1, rate2, rate3 + FROM rateConfig + ) sub2 + 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 DROP PROCEDURE IF EXISTS `expeditionGetFromRoute` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `expeditionGetFromRoute`( + vExpeditionFk INT) +BEGIN +/** + * Get all expeditions from route + */ + DECLARE vRouteFk INT DEFAULT 0; + + SELECT t.routeFk INTO vRouteFk + FROM vn.expedition exp + INNER JOIN ticket t on t.id = exp.ticketFk + WHERE exp.id = vExpeditionFk; + +SELECT exp.id, exp.ticketFk, exp.checked, t.routeFk,t.packages AS bultos , ts.alertLevel, a.street, a.city,a.postalCode,a.id AS addressFk,w.name AS warehouse + FROM vn.expedition exp + INNER JOIN ticket t ON t.id = exp.ticketFk + INNER JOIN vn.ticketState ts ON ts.ticketFk = exp.ticketFk + LEFT JOIN vn.address a ON t.addressFk = a.id + LEFT JOIN vn.warehouse w ON t.warehouseFk = w.id + WHERE t.routeFk = vRouteFk AND exp.isBox > 0; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `expeditionUpdateChecked` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `expeditionUpdateChecked`( + vExpeditionFk INT, vChecked INT) +BEGIN +/** + * Get all expeditions from route + */ + + UPDATE vn.expedition exp + SET exp.checked = vChecked + WHERE exp.id = vExpeditionFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `getDayExpeditions` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `getDayExpeditions`() +BEGIN + + SELECT + e.expeditions_id as expeditionFk, + date_format(e.odbc_date,'%Y-%m-%d') as expeditionDate, + e.ticket_id as ticketFk, + t.routeFk as routeFk + FROM vn2008.expeditions e + INNER JOIN vn.ticket t ON t.id = e.ticket_id + WHERE DATE(odbc_date) = CURDATE(); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `getDeliveryWorkers` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `getDeliveryWorkers`() +BEGIN +SELECT w.id, + concat(p.firstname," ",p.name) AS fullName, + w.code AS workerCode, + pwc.name, + rl.routeFk as routeLoader + FROM postgresql.person AS p + LEFT JOIN vn.worker AS w ON p.id_trabajador=w.id + LEFT JOIN (SELECT MIN(profile_id) AS pid, person_id FROM postgresql.profile GROUP BY person_id) AS pp ON p.person_id=pp.person_id + LEFT JOIN vn2008.profile_labour_payroll AS plp ON pp.pid=plp.profile_id + LEFT JOIN (SELECT MAX(business_id) AS bimax, client_id FROM postgresql.business GROUP BY client_id) AS pbv ON pbv.client_id = plp.profile_id + LEFT JOIN postgresql.business_labour AS pbl ON pbl.business_id = pbv.bimax + LEFT JOIN vn2008.department AS pd ON pd.department_id = pbl.department_id + LEFT JOIN postgresql.workcenter AS pwc ON pwc.workcenter_id=pbl.workcenter_id + LEFT JOIN vn.user u ON u.id=w.userFK + LEFT JOIN vn.routeLoadWorker rl ON rl.workerFk = w.id + WHERE p.id_trabajador Is Not Null + AND pd.name='REPARTO' + AND u.active<>0 + ORDER BY pwc.name ASC,p.firstname ASC; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `getItemUbication` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `getItemUbication`(vItemFk INT) +BEGIN + SELECT vn.barcodeToItem(vItemFk) INTO vItemFk; + + SELECT pk.code as Parking, + sh.code as Matricula, + ish.visible as visible, + ish.available as Disponible, + ish.level as level, + ish.created as created, + ish.itemFk as itemFk + FROM vn.itemShelving ish + JOIN vn.shelving sh ON sh.`code` = ish.shelvingFk + JOIN vn.parking pk ON pk.id = sh.parkingFk + WHERE ish.itemFk = 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 DROP PROCEDURE IF EXISTS `getItemVisibleAvailable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `getItemVisibleAvailable`( + vItem INT, + vDate DATE, + vWarehouse TINYINT, + vRefresh BOOL) +BEGIN + + /*deprecated usar vn.itemGetVisibleAvailable + jgf 2019/09/10 */ + DECLARE vVisibleCalc INT; + DECLARE vAvailableCalc INT; + + -- FIXME: Android app is always passing %TRUE for #vRefresh, this leads to DB performance issues + CALL cache.visible_refresh(vVisibleCalc, FALSE /*vRefresh*/, vWarehouse); + CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/, vWarehouse, vDate); + + SELECT a.Id_Article, a.Article, a.Medida, a.Tallos, + a.caja, O.Abreviatura AS origen, a.Color, tipo_id, + an.Nicho, a.Categoria, p.`name` AS producer, + v.visible, av.available, an.reserve + FROM vn2008.Articles a + LEFT JOIN vn2008.Articles_nicho an + ON a.Id_Article = an.Id_Article AND an.warehouse_id = vWarehouse + LEFT JOIN cache.visible v + ON v.item_id = a.Id_Article AND v.calc_id = vVisibleCalc + LEFT JOIN cache.available av + ON av.item_id = a.Id_Article AND av.calc_id = vAvailableCalc + LEFT JOIN vn2008.Origen O + ON O.id = a.id_origen + LEFT JOIN vn2008.producer p + ON p.producer_id = a.producer_id + WHERE (vItem IS NULL OR a.Id_Article = vItem); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `getPedidosInternos` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `getPedidosInternos`() +BEGIN + + SELECT id,name as description,upToDown as quantity FROM vn.item WHERE upToDown; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `intrastat_data_neto_Update` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `intrastat_data_neto_Update`(IN vinvoiceInFk INT) +BEGIN + +UPDATE vn2008.intrastat_data id + JOIN ( + SELECT i.intrastatFk, + sum(r.cm3 * b.quantity) * IF(i.density, i.density, it.density) / 1000000 as neto + FROM vn.entry e + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.buy b ON b.entryFk = e.id + JOIN vn.item i ON i.id = b.itemFk + join vn.itemType it ON it.id = i.typeFk + JOIN bi.rotacion r ON r.Id_Article = i.id AND tr.warehouseInFk = r.warehouse_id + WHERE e.invoiceInFk = vinvoiceInFk + GROUP BY i.intrastatFk) sub ON sub.intrastatFk = id.intrastat_id + SET id.neto = ROUND(sub.neto,1) + WHERE id.recibida_id = vInvoiceInFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `inventoryFailureAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `inventoryFailureAdd`() +BEGIN + +DECLARE done BOOL DEFAULT FALSE; +DECLARE vTicketFk INT; + +DECLARE rs CURSOR FOR + SELECT id FROM vn.ticket + WHERE shipped = util.yesterday() + AND clientFk = 400 + AND warehouseFk IN (1,44); + +DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + +OPEN rs; + +FETCH rs INTO vTicketFk; + +WHILE NOT done DO + + INSERT INTO vn.inventoryFailure(dated, itemFk, quantity, value, warehouseFk, throwerFk) + SELECT t.shipped, + s.itemFk, + s.quantity, + b.buyingValue + b.freightValue + b.packageValue + b.comissionValue, + t.warehouseFk, + w.id + FROM vn.ticket t + JOIN vn.sale s ON s.ticketFk = t.id + LEFT JOIN cache.last_buy lb ON lb.warehouse_id = t.warehouseFk AND item_id = s.itemFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.worker w ON w.code = LEFT(s.concept, 3) + WHERE t.id = vTicketFk + AND s.quantity > 0; + + FETCH rs INTO vTicketFk; + +END WHILE; + + +CLOSE rs; + + + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `inventoryMake` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `inventoryMake`(vDate DATE, vWh INT) +proc: BEGIN +/** + * Recalcula los inventarios de todos los almacenes, si vWh = 0 + * + * @param vDate Fecha de los nuevos inventarios + */ + + DECLARE vDone BOOL; + DECLARE vEntryFk INT; + DECLARE vTravelFk INT; + DECLARE vDateTime DATETIME DEFAULT TIMESTAMP(vDate, '00:00:00'); + DECLARE vDeleteDate DATE DEFAULT TIMESTAMPADD(DAY, -2, vDate); + DECLARE vDateLastInventory DATE; + DECLARE vDateYesterday DATETIME DEFAULT TIMESTAMPADD(SECOND,-1,vDate); + + DECLARE cWarehouses CURSOR FOR + SELECT id + FROM warehouse + WHERE isInventory AND vWh IN (0,id); + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SELECT vDateYesterday; + + OPEN cWarehouses; + SET @isModeInventory := TRUE; + l: LOOP + + SET vDone = FALSE; + FETCH cWarehouses INTO vWh; + + IF vDone THEN + LEAVE l; + END IF; + + SELECT MAX(landed) INTO vDateLastInventory + FROM travel tr + JOIN entry e ON e.travelFk = tr.id + JOIN buy b ON b.entryFk = e.id + WHERE warehouseOutFk = 13 + AND landed < vDate + AND e.supplierFk = 4 + AND warehouseInFk = vWh + AND NOT isRaid; + + -- Generamos travel, si no existe. + SET vTravelFK = 0; + + SELECT id INTO vTravelFk + FROM travel + WHERE warehouseOutFk = 13 + AND warehouseInFk = vWh + AND landed = vDate + AND agencyFk = 53 + AND ref = 'inventario' + LIMIT 1; + + IF NOT vTravelFK THEN + + INSERT INTO travel SET + warehouseOutFk = 13, + warehouseInFk = vWh, + shipped = vDateTime, + landed = vDate, + agencyFk = 53, + ref = 'inventario', + isDelivered = TRUE, + isReceived = TRUE; + + SELECT LAST_INSERT_ID() INTO vTravelFk; + + END IF; + + -- Generamos entrada si no existe, o la vaciamos. + SET vEntryFk = 0; + + SELECT id INTO vEntryFk + FROM entry + WHERE supplierFk = 4 + AND travelFk = vTravelFk; + + IF NOT vEntryFk THEN + + INSERT INTO entry SET + supplierFk = 4, + isConfirmed = TRUE, + isOrdered = TRUE, + travelFk = vTravelFk; + + SELECT LAST_INSERT_ID() INTO vEntryFk; + + ELSE + + DELETE FROM buy WHERE entryFk = vEntryFk; + + END IF; + + -- Preparamos tabla auxilar + DROP TEMPORARY TABLE IF EXISTS tmp.inventory; + + CREATE TEMPORARY TABLE tmp.inventory + ( + itemFk INT(11) NOT NULL PRIMARY KEY, + quantity int(11) DEFAULT '0', + buyingValue decimal(10,3) DEFAULT '0.000', + freightValue decimal(10,3) DEFAULT '0.000', + packing int(11) DEFAULT '0', + `grouping` smallint(5) unsigned NOT NULL DEFAULT '1', + groupingMode tinyint(4) NOT NULL DEFAULT 0 , + comissionValue decimal(10,3) DEFAULT '0.000', + packageValue decimal(10,3) DEFAULT '0.000', + packageFk varchar(10) COLLATE utf8_unicode_ci DEFAULT '--', + price1 decimal(10,2) DEFAULT '0.00', + price2 decimal(10,2) DEFAULT '0.00', + price3 decimal(10,2) DEFAULT '0.00', + minPrice decimal(10,2) DEFAULT '0.00', + producer varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + INDEX (itemFK)) + ENGINE = MEMORY ; + + -- Compras + INSERT INTO tmp.inventory(itemFk,quantity) + SELECT b.itemFk, sum(b.quantity) + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + WHERE tr.warehouseInFk = vWh + AND tr.landed BETWEEN vDateLastInventory + AND vDateYesterday + AND NOT isRaid + GROUP BY b.itemFk; + SELECT vDateLastInventory , vDateYesterday; + -- Traslados + INSERT INTO tmp.inventory(itemFk,quantity) + SELECT itemFk, quantityOut + FROM ( + SELECT b.itemFk, -sum(b.quantity) quantityOut + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + WHERE tr.warehouseOutFk = vWh + AND tr.shipped BETWEEN vDateLastInventory + AND vDateYesterday + AND NOT isRaid + GROUP BY b.itemFk + ) sub + ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.quantityOut; + + -- Ventas + INSERT INTO tmp.inventory(itemFk,quantity) + SELECT itemFk, saleOut + FROM ( + SELECT s.itemFk, -sum(s.quantity) saleOut + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + WHERE t.warehouseFk = vWh + AND t.shipped BETWEEN vDateLastInventory AND vDateYesterday + GROUP BY s.itemFk + ) sub + ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.saleOut; + + -- Actualiza valores de la ultima compra + + UPDATE tmp.inventory inv + JOIN cache.last_buy lb ON lb.item_id = inv.itemFk AND lb.warehouse_id = vWh + JOIN buy b ON b.id = lb.buy_id + SET + inv.buyingValue = b.buyingValue, + inv.freightValue = b.freightValue, + inv.packing = b.packing, + inv.`grouping` = b.`grouping`, + inv.groupingMode = b.groupingMode, + inv.comissionValue = b.comissionValue, + inv.packageValue = b.packageValue, + inv.packageFk = b.packageFk, + inv.price1 = b.price1, + inv.price2 = b.price2, + inv.price3 = b.price3, + inv.minPrice = b.minPrice, + inv.producer = b.producer; + + + INSERT INTO buy( itemFk, + quantity, + buyingValue, + freightValue, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + packageFk, + price1, + price2, + price3, + minPrice, + producer, + entryFk) + SELECT itemFk, + quantity, + buyingValue, + freightValue, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + packageFk, + price1, + price2, + price3, + minPrice, + producer, + vEntryFk + FROM tmp.inventory; + + SELECT vWh, count(*), NOW() FROM tmp.inventory; + + -- DROP TEMPORARY TABLE tmp.inventory; + + END LOOP; + + CLOSE cWarehouses; + + UPDATE config SET inventoried = vDate; + SET @isModeInventory := FALSE; + + DELETE e, t + FROM travel t + JOIN entry e ON e.travelFk = t.id + WHERE e.supplierFk = 4 + AND t.shipped <= vDeleteDate + AND (DAY(t.shipped) <> 1 OR shipped < TIMESTAMPADD(MONTH, -12, CURDATE())); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `inventoryMakeLauncher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `inventoryMakeLauncher`() +BEGIN +/** + * Recalcula los inventarios de todos los almacenes. + */ + + call vn.inventoryMake(TIMESTAMPADD(DAY, -10, CURDATE()), 0); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `inventoryMake__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `inventoryMake__`(vDate DATE, vWh INT) +proc: BEGIN +/** + * bernat WORKING IN THIS FILE + * Recalcula los inventarios de todos los almacenes, si vWh = 0 + * + * @param vDate Fecha de los nuevos inventarios + */ + + DECLARE vDone BOOL; + DECLARE vEntryFk INT; + DECLARE vTravelFk INT; + DECLARE vDateTime DATETIME DEFAULT TIMESTAMP(vDate, '00:00:00'); + DECLARE vDeleteDate DATE DEFAULT TIMESTAMPADD(DAY, -2, vDate); + DECLARE vDateLastInventory DATE; + DECLARE vDateYesterday DATETIME DEFAULT TIMESTAMPADD(SECOND,-1,vDate); + + DECLARE cWarehouses CURSOR FOR + SELECT id FROM vn.warehouse WHERE isInventory AND vWh IN (0,id); + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SELECT vDateYesterday; + + OPEN cWarehouses; + SET @isModeInventory := TRUE; + l: LOOP + + SET vDone = FALSE; + FETCH cWarehouses INTO vWh; + + IF vDone THEN + LEAVE l; + END IF; + + SELECT MAX(landed) INTO vDateLastInventory + FROM vn.travel tr + JOIN vn.entry e ON e.travelFk = tr.id + JOIN vn.buy b ON b.entryFk = e.id + WHERE warehouseOutFk = 13 + AND landed < vDate + AND e.supplierFk = 4 + AND warehouseInFk = vWh + AND NOT isRaid; + + -- Generamos travel, si no existe. + SET vTravelFK = 0; + + SELECT id INTO vTravelFk + FROM vn.travel + WHERE warehouseOutFk = 13 + AND warehouseInFk = vWh + AND landed = vDate + AND agencyFk = 53 + AND ref = 'inventario' + LIMIT 1; + + IF NOT vTravelFK THEN + + INSERT INTO vn.travel SET + warehouseOutFk = 13, + warehouseInFk = vWh, + shipped = vDateTime, + landed = vDate, + agencyFk = 53, + ref = 'inventario', + isDelivered = TRUE, + isReceived = TRUE; + + SELECT LAST_INSERT_ID() INTO vTravelFk; + + END IF; + + -- Generamos entrada si no existe, o la vaciamos. + SET vEntryFk = 0; + + SELECT id INTO vEntryFk + FROM vn.entry + WHERE supplierFk = 4 + AND travelFk = vTravelFk; + + IF NOT vEntryFk THEN + + INSERT INTO entry SET + supplierFk = 4, + isConfirmed = TRUE, + isOrdered = TRUE, + travelFk = vTravelFk; + + SELECT LAST_INSERT_ID() INTO vEntryFk; + + ELSE + + DELETE FROM vn.buy WHERE entryFk = vEntryFk; + + END IF; + + -- Preparamos tabla auxilar + DROP TEMPORARY TABLE IF EXISTS tmp.inventory; + + CREATE TEMPORARY TABLE tmp.inventory + ( + itemFk INT(11) NOT NULL PRIMARY KEY, + quantity int(11) DEFAULT '0', + buyingValue decimal(10,3) DEFAULT '0.000', + freightValue decimal(10,3) DEFAULT '0.000', + packing int(11) DEFAULT '0', + `grouping` smallint(5) unsigned NOT NULL DEFAULT '1', + groupingMode tinyint(4) NOT NULL DEFAULT 0 , + comissionValue decimal(10,3) DEFAULT '0.000', + packageValue decimal(10,3) DEFAULT '0.000', + packageFk varchar(10) COLLATE utf8_unicode_ci DEFAULT '--', + price1 decimal(10,2) DEFAULT '0.00', + price2 decimal(10,2) DEFAULT '0.00', + price3 decimal(10,2) DEFAULT '0.00', + minPrice decimal(10,2) DEFAULT '0.00', + producer varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + INDEX (itemFK)) + ENGINE = MEMORY ; + + -- Compras + INSERT INTO tmp.inventory(itemFk,quantity) + SELECT b.itemFk, sum(b.quantity) + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + WHERE tr.warehouseInFk = vWh + AND tr.landed BETWEEN vDateLastInventory + AND vDateYesterday + AND NOT isRaid + GROUP BY b.itemFk; + SELECT vDateLastInventory , vDateYesterday; + -- Traslados + INSERT INTO tmp.inventory(itemFk,quantity) + SELECT itemFk, quantityOut + FROM ( + SELECT b.itemFk, -sum(b.quantity) quantityOut + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + WHERE tr.warehouseOutFk = vWh + AND tr.shipped BETWEEN vDateLastInventory + AND vDateYesterday + AND NOT isRaid + GROUP BY b.itemFk + ) sub + ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.quantityOut; + + -- Ventas + INSERT INTO tmp.inventory(itemFk,quantity) + SELECT itemFk, saleOut + FROM ( + SELECT s.itemFk, -sum(s.quantity) saleOut + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + WHERE t.warehouseFk = vWh + AND t.shipped BETWEEN vDateLastInventory AND vDateYesterday + GROUP BY s.itemFk + ) sub + ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.saleOut; + + -- Actualiza valores de la ultima compra + + UPDATE tmp.inventory inv + JOIN cache.last_buy lb ON lb.item_id = inv.itemFk AND lb.warehouse_id = vWh + JOIN vn.buy b ON b.id = lb.buy_id + SET + inv.buyingValue = b.buyingValue, + inv.freightValue = b.freightValue, + inv.packing = b.packing, + inv.`grouping` = b.`grouping`, + inv.groupingMode = b.groupingMode, + inv.comissionValue = b.comissionValue, + inv.packageValue = b.packageValue, + inv.packageFk = b.packageFk, + inv.price1 = b.price1, + inv.price2 = b.price2, + inv.price3 = b.price3, + inv.minPrice = b.minPrice, + inv.producer = b.producer; + + + INSERT INTO vn.buy( itemFk, + quantity, + buyingValue, + freightValue, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + packageFk, + price1, + price2, + price3, + minPrice, + producer, + entryFk) + SELECT itemFk, + quantity, + buyingValue, + freightValue, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + packageFk, + price1, + price2, + price3, + minPrice, + producer, + vEntryFk + FROM tmp.inventory; + + SELECT vWh, count(*), NOW() FROM tmp.inventory; + + -- DROP TEMPORARY TABLE tmp.inventory; + + END LOOP; + + CLOSE cWarehouses; + + UPDATE vn2008.tblContadores SET FechaInventario = vDate; + SET @isModeInventory := FALSE; + + DELETE e, t + FROM vn.travel t + JOIN vn.entry e ON e.travelFk = t.id + WHERE e.supplierFk = 4 + AND t.shipped <= vDeleteDate + AND (DAY(t.shipped) <> 1 OR shipped < TIMESTAMPADD(MONTH, -12, CURDATE())); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenceMake` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceExpenceMake`(IN vInvoice INT) +BEGIN +/* Inserta las partidas de gasto correspondientes a la factura + * REQUIERE tabla ticketToInvoice + * @param vInvoice Numero de factura + */ + DELETE FROM invoiceOutExpence + WHERE invoiceOutFk = vInvoice; + + INSERT INTO invoiceOutExpence(invoiceOutFk, expenceFk, amount) + SELECT vInvoice, + expenceFk, + SUM(ROUND(quantity * price * (100 - discount)/100,2)) amount + FROM ticketToInvoice t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + GROUP BY i.expenceFk + HAVING amount != 0; + + INSERT INTO invoiceOutExpence(invoiceOutFk, expenceFk, amount) + SELECT vInvoice, + tst.expenceFk, + SUM(ROUND(ts.quantity * ts.price ,2)) amount + FROM ticketToInvoice t + JOIN ticketService ts ON ts.ticketFk = t.id + JOIN ticketServiceType tst ON tst.id = ts.ticketServiceTypeFk + HAVING amount != 0; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenceMake__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceExpenceMake__`(IN vInvoice INT) +BEGIN +/* Inserta las partidas de gasto correspondientes a la factura + * REQUIERE tabla ticketToInvoice + * + * @param vInvoice Numero de factura + * + */ + DELETE FROM invoiceOutExpence + WHERE invoiceOutFk = vInvoice; + + INSERT INTO invoiceOutExpence( + invoiceOutFk, + expenceFk, + amount + ) + SELECT + vInvoice, + expenceFk, + SUM(ROUND(quantity * price * (100 - discount)/100,2)) amount + FROM ticketToInvoice t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + GROUP BY i.expenceFk + HAVING amount != 0; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceFromAddress` */; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceFromAddress`(vMaxTicketDate DATETIME,vAddress INT,vCompany INT) +BEGIN + + DECLARE vMinDateTicket DATE DEFAULT TIMESTAMPADD(MONTH, -3, CURDATE()); + + SET vMaxTicketDate = vn2008.DAYEND(vMaxTicketDate); + + DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`; + + CREATE TEMPORARY TABLE `ticketToInvoice` + (PRIMARY KEY (`id`)) + ENGINE = MEMORY + SELECT Id_Ticket id FROM vn2008.Tickets WHERE (Fecha BETWEEN vMinDateTicket + AND vMaxTicketDate) AND Id_Consigna = vAddress + AND Factura IS NULL AND empresa_id = vCompany; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceFromClient` */; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceFromClient`(vMaxTicketDate DATETIME, vClient INT, vCompany INT) +BEGIN + + DECLARE vMinDateTicket DATE DEFAULT TIMESTAMPADD(YEAR, -3, CURDATE()); + + SET vMaxTicketDate = vn2008.DAYEND(vMaxTicketDate); + + DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`; + + CREATE TEMPORARY TABLE `ticketToInvoice` + (PRIMARY KEY (`id`)) + ENGINE = MEMORY + SELECT Id_Ticket id FROM vn2008.Tickets + WHERE Id_Cliente = vClient + AND Factura IS NULL + AND empresa_id = vCompany + AND (Fecha BETWEEN vMinDateTicket AND vMaxTicketDate) + ; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceFromTicket` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceFromTicket`(IN vTicket INT) +BEGIN + + DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`; + + CREATE TEMPORARY TABLE `ticketToInvoice` + (PRIMARY KEY (`id`)) + ENGINE = MEMORY + SELECT id FROM vn.ticket + WHERE id = vTicket AND refFk IS NULL; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceInBookingCommon` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceInBookingCommon`(vInvoiceInId INT, OUT vSerialNumber INT) +BEGIN + + DROP TEMPORARY TABLE IF EXISTS newInvoiceIn; + + CREATE TEMPORARY TABLE newInvoiceIn + SELECT + i.*, + YEAR(i.booked) datedYear, + CONCAT('s/fra',RIGHT(i.supplierRef,8),':',LEFT(s.name, 10)) conceptWithSupplier, + (cc.id = c.id) isSameCountry, + cit.id invoicesCount + FROM invoiceIn i + JOIN cplusInvoiceType472 cit ON cit.id = i.cplusInvoiceType472Fk + JOIN supplier s ON s.id = i.supplierFk + JOIN country c ON c.id = s.countryFk + JOIN supplier sc ON sc.id = i.companyFk + JOIN country cc ON cc.id = sc.countryFk + WHERE i.id = vInvoiceInId; + + DROP TEMPORARY TABLE IF EXISTS newSupplier; + CREATE TEMPORARY TABLE newSupplier + SELECT + s.*, + REPLACE(s.account,' ','') supplierAccount, + IF(c.CEE < 2, TRUE, FALSE) isUeeMember + FROM supplier s + JOIN newInvoiceIn n + JOIN country c ON c.id = s.countryFk + WHERE s.id = n.supplierFk; + + IF (SELECT isActive FROM newSupplier) = 0 THEN + CALL util.throw('INACTIVE_PROVIDER'); + END IF; + + SELECT IFNULL(MAX(i.serialNumber) + 1,1) + INTO vSerialNumber + FROM invoiceIn i + JOIN newInvoiceIn n + WHERE i.serial LIKE n.serial + AND YEAR(i.booked) = n.datedYear + AND i.companyFk = n.companyFk + GROUP BY i.companyFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceInBookingMain` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceInBookingMain`(vInvoiceInId INT) +BEGIN + DECLARE vTotalAmount,vTotalAmountDivisa DECIMAL(10,2); + DECLARE vBookNumber,vSerialNumber INT; + DECLARE vRate DECIMAL(10,4); + DECLARE vSerial VARCHAR(2); + + CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber); + + SELECT serial + INTO vSerial + FROM newInvoiceIn; + + SELECT SUM(iit.taxableBase * IF(vSerial = 'R', 1 +(tc.rate/100),1)), + SUM(iit.foreignValue * IF(vSerial = 'R', 1 +(tc.rate/100),1)), + iit.taxableBase/iit.foreignValue + INTO vTotalAmount, vTotalAmountDivisa, vRate + FROM newInvoiceIn i + JOIN invoiceInTax iit ON iit.invoiceInFk = i.id + JOIN taxCode tc ON iit.taxCodeFk = tc.id; + + CALL vn.ledger_next(vBookNumber); + + -- Apunte del proveedor + + INSERT INTO vn2008.XDiario( + ASIEN, + FECHA, + SUBCTA, + EUROHABER, + CONCEPTO, + CAMBIO, + HABERME, + NFACTICK, + CLAVE, + empresa_id) + SELECT + vBookNumber, + n.bookEntried, + s.supplierAccount, + vTotalAmount EUROHABER, + n.conceptWithSupplier, + vRate, + vTotalAmountDivisa, + n.invoicesCount, + vInvoiceInId, + n.companyFk + FROM newInvoiceIn n + JOIN newSupplier s; + + -- ----------------------------------------------------------- Linea de Gastos + INSERT INTO vn2008.XDiario (ASIEN, + FECHA, + SUBCTA, + CONTRA, + EURODEBE, + EUROHABER, + CONCEPTO, + CAMBIO, + DEBEME, + HABERME, + NFACTICK, + empresa_id + ) + SELECT vBookNumber ASIEN, + n.bookEntried FECHA, + IF(e.isWithheld,LPAD(RIGHT(s.supplierAccount,5),10,iit.expenceFk),iit.expenceFk) SUBCTA, + s.supplierAccount CONTRA, + IF(e.isWithheld,NULL,ABS(ROUND(SUM(iit.taxableBase),2))) EURODEBE, + IF(e.isWithheld,ABS(ROUND(SUM(iit.taxableBase),2)),NULL) EUROHABER, + n.conceptWithSupplier CONCEPTO, + vRate, + IF(e.isWithheld,NULL,ABS(ROUND(SUM(iit.foreignValue),2))) DEBEME, + IF(e.isWithheld,ABS(ROUND(SUM(iit.foreignValue),2)),NULL) HABERME, + n.invoicesCount NFACTICK, + n.companyFk empresa_id + FROM newInvoiceIn n + JOIN newSupplier s + JOIN invoiceInTax iit ON iit.invoiceInFk = n.id + JOIN taxCode tc ON tc.id = iit.taxCodeFk + JOIN expence e ON e.id = iit.expenceFk AND e.taxTypeFk = tc.taxTypeFk + WHERE iit.expenceFk != 5660000002 + GROUP BY iit.expenceFk; + + + -- -------------------------------------------------------------------- + -- ------- Lineas de IVA --------------- + -- -------------------------------------------------------------------- + + INSERT INTO vn2008.XDiario( ASIEN, + FECHA, + SUBCTA, + CONTRA, + EURODEBE, + BASEEURO, + CONCEPTO, + FACTURA, + IVA, + AUXILIAR, + SERIE, + TIPOOPE, + FECHA_EX, + FECHA_OP, + NFACTICK, + FACTURAEX, + L340, + LRECT349, + TIPOCLAVE, + TIPOEXENCI, + TIPONOSUJE, + TIPOFACT, + TIPORECTIF, + TERIDNIF, + TERNIF, + TERNOM, + FECREGCON, + empresa_id + ) + SELECT vBookNumber ASIEN, + n.bookEntried FECHA, + tc.code SUBCTA, + s.supplierAccount CONTRA, + SUM(ROUND(tc.rate/100*it.taxableBase + 0.0001,2)) EURODEBE, + SUM(it.taxableBase) BASEEURO, + GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, + vSerialNumber FACTURA, + tc.rate IVA, + IF(isUeeMember AND eWithheld.id IS NULL,'','*') AUXILIAR, + n.serial SERIE, + tt.TIPOOPE, + n.issued FECHA_EX, + n.operated FECHA_OP, + n.invoicesCount NFACTICK, + n.supplierRef FACTURAEX, + TRUE L340, + (isSameCountry OR NOT isUeeMember) LRECT349, + n.cplusTrascendency472Fk TIPOCLAVE, + n.cplusTaxBreakFk TIPOEXENCI, + n.cplusSubjectOpFk TIPONOSUJE, + n.cplusInvoiceType472Fk TIPOFACT, + n.cplusRectificationTypeFk TIPORECTIF, + iis.cplusTerIdNifFk TERIDNIF, + s.nif AS TERNIF, + s.name AS TERNOM, + n.booked FECREGCON, + n.companyFk + FROM newInvoiceIn n + JOIN newSupplier s + JOIN invoiceInTax it ON n.id = it.invoiceInFk + JOIN taxCode tc ON tc.id = it.taxCodeFk + JOIN taxType tt ON tt.id = tc.taxTypeFk + JOIN invoiceInSerial iis ON iis.code = tt.serial + JOIN expence e ON e.id = it.expenceFk + AND e.taxTypeFk = tc.taxTypeFk + LEFT JOIN (SELECT eWithheld.id + FROM invoiceInTax hold + JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld + WHERE hold.invoiceInFk = 58262 LIMIT 1 + ) eWithheld ON TRUE + WHERE tc.type != '-' + AND tc.isActive + GROUP BY tc.rate; + + -- Linea iva inversor sujeto pasivo + + INSERT INTO vn2008.XDiario( ASIEN, + FECHA, + SUBCTA, + CONTRA, + EUROHABER, + BASEEURO, + CONCEPTO, + FACTURA, + IVA, + AUXILIAR, + SERIE, + TIPOOPE, + FECHA_EX, + FECHA_OP, + NFACTICK, + FACTURAEX, + L340, + LRECT349, + TIPOCLAVE, + TIPOEXENCI, + TIPONOSUJE, + TIPOFACT, + TIPORECTIF, + TERIDNIF, + TERNIF, + TERNOM, + empresa_id + ) + + SELECT vBookNumber ASIEN, + n.bookEntried FECHA, + tcLink.code SUBCTA, + s.supplierAccount CONTRA, + ROUND(tcLink.rate/100*SUM(it.taxableBase) + 0.0001,2) EUROHABER, + ROUND(SUM(it.taxableBase),2) BASEEURO, + GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, + vSerialNumber FACTURA, + tcLink.rate IVA, + '*' AUXILIAR, + n.serial SERIE, + tt.TIPOOPE, + n.issued FECHA_EX, + n.operated FECHA_OP, + n.invoicesCount NFACTICK, + n.supplierRef FACTURAEX, + FALSE L340, + (isSameCountry OR NOT isUeeMember) LRECT349, + 1 TIPOCLAVE, + n.cplusTaxBreakFk TIPOEXENCI, + n.cplusSubjectOpFk TIPONOSUJE, + n.cplusInvoiceType472Fk TIPOFACT, + n.cplusRectificationTypeFk TIPORECTIF, + iis.cplusTerIdNifFk TERIDNIF, + s.nif AS TERNIF, + s.name AS TERNOM, + n.companyFk + FROM newInvoiceIn n + JOIN newSupplier s + JOIN invoiceInTax it ON n.id = it.invoiceInFk + JOIN taxCode tc ON tc.id = it.taxCodeFk + JOIN taxType tt ON tt.id = tc.taxTypeFk + JOIN invoiceInSerial iis ON iis.code = tt.serial + JOIN taxCode tcLink ON tcLink.link = tc.link + AND tc.id != tcLink.id + AND tc.link + JOIN expence e ON e.id = it.expenceFk + AND e.taxTypeFk = tc.taxTypeFk + WHERE tc.isActive + AND (tc.type = 'S' OR MID(s.supplierAccount,4,1) = '1') + GROUP BY tcLink.rate, e.id; + + -- Actualización del registro original + UPDATE invoiceIn ii + JOIN newInvoiceIn ni ON ii.id = ni.id + SET ii.serialNumber = vSerialNumber, + ii.isBooked = TRUE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceInBookingMain__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceInBookingMain__`(vInvoiceInId INT) +BEGIN + DECLARE vTotalAmount,vTotalAmountDivisa DECIMAL(10,2); + DECLARE vBookNumber,vSerialNumber INT; + DECLARE vRate DECIMAL(10,4); + DECLARE vSerial VARCHAR(2); + + CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber); + + SELECT serial + INTO vSerial + FROM newInvoiceIn; + + SELECT SUM(iit.taxableBase * IF(vSerial = 'R', 1 +(tc.rate/100),1)), + SUM(iit.foreignValue * IF(vSerial = 'R', 1 +(tc.rate/100),1)), + iit.taxableBase/iit.foreignValue + INTO vTotalAmount, vTotalAmountDivisa, vRate + FROM newInvoiceIn i + JOIN invoiceInTax iit ON iit.invoiceInFk = i.id + JOIN taxCode tc ON iit.taxCodeFk = tc.id; + + SELECT MAX(ASIEN) + 1 + INTO vBookNumber + FROM vn2008.XDiario; + + -- Apunte del proveedor + + INSERT INTO vn2008.XDiario( + ASIEN, + FECHA, + SUBCTA, + EUROHABER, + CONCEPTO, + CAMBIO, + HABERME, + NFACTICK, + CLAVE, + empresa_id) + SELECT + vBookNumber, + n.bookEntried, + s.supplierAccount, + vTotalAmount EUROHABER, + n.conceptWithSupplier, + vRate, + vTotalAmountDivisa, + n.invoicesCount, + vInvoiceInId, + n.companyFk + FROM newInvoiceIn n + JOIN newSupplier s; + + -- ----------------------------------------------------------- Linea de Gastos + INSERT INTO vn2008.XDiario ( + ASIEN, + FECHA, + SUBCTA, + CONTRA, + EURODEBE, + EUROHABER, + CONCEPTO, + CAMBIO, + DEBEME, + HABERME, + NFACTICK, + empresa_id + ) + SELECT + vBookNumber ASIEN, + n.bookEntried FECHA, + if( + e.isWithheld, + LPAD(RIGHT(s.supplierAccount,5),10,iit.expenceFk), + iit.expenceFk + ) SUBCTA, + s.supplierAccount CONTRA, + if( + e.isWithheld, + NULL, + ABS(ROUND(SUM(iit.taxableBase),2)) + ) EURODEBE, + if( + e.isWithheld, + ABS(ROUND(SUM(iit.taxableBase),2)), + NULL + ) EUROHABER, + n.conceptWithSupplier CONCEPTO, + vRate, + if( + e.isWithheld, + NULL, + ABS(ROUND(SUM(iit.foreignValue),2)) + ) DEBEME, + if( + e.isWithheld, + ABS(ROUND(SUM(iit.foreignValue),2)), + NULL + ) HABERME, + n.invoicesCount NFACTICK, + n.companyFk empresa_id + FROM newInvoiceIn n + JOIN newSupplier s + JOIN invoiceInTax iit ON iit.invoiceInFk = n.id + JOIN taxCode tc ON tc.id = iit.taxCodeFk + JOIN expence e ON e.id = iit.expenceFk AND e.taxTypeFk = tc.taxTypeFk + WHERE iit.expenceFk != 5660000002 + GROUP BY iit.expenceFk; + + + -- -------------------------------------------------------------------- + -- ------- Lineas de IVA --------------- + -- -------------------------------------------------------------------- + + INSERT INTO vn2008.XDiario( + ASIEN, + FECHA, + SUBCTA, + CONTRA, + EURODEBE, + BASEEURO, + CONCEPTO, + FACTURA, + IVA, + AUXILIAR, + SERIE, + TIPOOPE, + FECHA_EX, + FECHA_OP, + NFACTICK, + FACTURAEX, + L340, + LRECT349, + TIPOCLAVE, + TIPOEXENCI, + TIPONOSUJE, + TIPOFACT, + TIPORECTIF, + TERIDNIF, + TERNIF, + TERNOM, + FECREGCON, + empresa_id + ) + SELECT vBookNumber ASIEN, + n.bookEntried FECHA, + tc.code SUBCTA, + s.supplierAccount CONTRA, + SUM(ROUND(tc.rate/100*it.taxableBase + 0.0001,2)) EURODEBE, + SUM(it.taxableBase) BASEEURO, + GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, + vSerialNumber FACTURA, + tc.rate IVA, + IF(isUeeMember AND eWithheld.id IS NULL,'','*') AUXILIAR, + n.serial SERIE, + tt.TIPOOPE, + n.issued FECHA_EX, + n.operated FECHA_OP, + n.invoicesCount NFACTICK, + n.supplierRef FACTURAEX, + TRUE L340, + (isSameCountry OR NOT isUeeMember) LRECT349, + n.cplusTrascendency472Fk TIPOCLAVE, + n.cplusTaxBreakFk TIPOEXENCI, + n.cplusSubjectOpFk TIPONOSUJE, + n.cplusInvoiceType472Fk TIPOFACT, + n.cplusRectificationTypeFk TIPORECTIF, + iis.cplusTerIdNifFk TERIDNIF, + s.nif AS TERNIF, + s.name AS TERNOM, + n.booked FECREGCON, + n.companyFk + + FROM newInvoiceIn n + JOIN newSupplier s + JOIN invoiceInTax it ON n.id = it.invoiceInFk + JOIN taxCode tc ON tc.id = it.taxCodeFk + JOIN taxType tt ON tt.id = tc.taxTypeFk + JOIN invoiceInSerial iis ON iis.code = tt.serial + JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk + LEFT JOIN + (SELECT eWithheld.id + FROM invoiceInTax hold + JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld + WHERE hold.invoiceInFk = 58262 LIMIT 1 + ) eWithheld ON TRUE + WHERE tc.type != '-' + AND tc.isActive + GROUP BY tc.rate; + + -- Linea iva inversor sujeto pasivo + + INSERT INTO vn2008.XDiario( + ASIEN, + FECHA, + SUBCTA, + CONTRA, + EUROHABER, + BASEEURO, + CONCEPTO, + FACTURA, + IVA, + AUXILIAR, + SERIE, + TIPOOPE, + FECHA_EX, + FECHA_OP, + NFACTICK, + FACTURAEX, + L340, + LRECT349, + TIPOCLAVE, + TIPOEXENCI, + TIPONOSUJE, + TIPOFACT, + TIPORECTIF, + TERIDNIF, + TERNIF, + TERNOM, + empresa_id + ) + + SELECT + vBookNumber ASIEN, + n.bookEntried FECHA, + tcLink.code SUBCTA, + s.supplierAccount CONTRA, + ROUND(tcLink.rate/100*SUM(it.taxableBase) + 0.0001,2) EUROHABER, + ROUND(SUM(it.taxableBase),2) BASEEURO, + GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, + vSerialNumber FACTURA, + tcLink.rate IVA, + '*' AUXILIAR, + n.serial SERIE, + tt.TIPOOPE, + n.issued FECHA_EX, + n.operated FECHA_OP, + n.invoicesCount NFACTICK, + n.supplierRef FACTURAEX, + FALSE L340, + (isSameCountry OR NOT isUeeMember) LRECT349, + 1 TIPOCLAVE, + n.cplusTaxBreakFk TIPOEXENCI, + n.cplusSubjectOpFk TIPONOSUJE, + n.cplusInvoiceType472Fk TIPOFACT, + n.cplusRectificationTypeFk TIPORECTIF, + iis.cplusTerIdNifFk TERIDNIF, + s.nif AS TERNIF, + s.name AS TERNOM, + n.companyFk + + FROM newInvoiceIn n + JOIN newSupplier s + JOIN invoiceInTax it ON n.id = it.invoiceInFk + JOIN taxCode tc ON tc.id = it.taxCodeFk + JOIN taxType tt ON tt.id = tc.taxTypeFk + JOIN invoiceInSerial iis ON iis.code = tt.serial + JOIN taxCode tcLink ON tcLink.link = tc.link AND tc.id != tcLink.id AND tc.link + JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk + WHERE tc.isActive + AND (tc.type = 'S' OR MID(s.supplierAccount,4,1) = '1') + GROUP BY tcLink.rate, e.id; + + -- Actualización del registro original + UPDATE invoiceIn ii + JOIN newInvoiceIn ni ON ii.id = ni.id + SET ii.serialNumber = vSerialNumber, + ii.isBooked = TRUE; + + UPDATE vn.config + SET ASIEN = 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 DROP PROCEDURE IF EXISTS `invoiceInTaxMakeByDua` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceInTaxMakeByDua`(vDuaFk INT) +BEGIN + + DECLARE done BOOL DEFAULT FALSE; + DECLARE vInvoiceInFk INT; + + DECLARE rs CURSOR FOR + SELECT invoiceInFk + FROM entry e + JOIN duaEntry de ON de.entryFk = e.id + WHERE de.duaFk = vDuaFk; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + OPEN rs; + + FETCH rs INTO vInvoiceInFk; + + WHILE NOT done DO + + CALL vn2008.recibidaIvaInsert(vInvoiceInFk); + CALL vn2008.recibidaVencimientoReplace(vInvoiceInFk); + + FETCH rs INTO vInvoiceInFk; + + END WHILE; + + CLOSE rs; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutAgain` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutAgain`(IN vInvoiceRef VARCHAR(15), vTaxArea VARCHAR(25)) +BEGIN + +/* Para tickets ya facturados, vuelve a repetir el proceso de facturación. +* +* @param vInvoiceFk Numero de factura +* @param vTaxArea Numero de factura +*/ + + DECLARE vInvoiceFk INT; + DECLARE vCountry INT; + DECLARE vTaxArea VARCHAR(15); + DECLARE vSpainCountryCode INT DEFAULT 1; + + SELECT id INTO vInvoiceFk + FROM invoiceOut + WHERE ref = vInvoiceRef; + + UPDATE invoiceOut + SET hasPdf = 0 + WHERE id = vInvoiceFk; + + SELECT s.countryFk INTO vCountry + FROM supplier s + JOIN invoiceOut io ON io.companyFk = s.id + WHERE io.id = vInvoiceFk; + + DROP TEMPORARY TABLE IF EXISTS ticketToInvoice; + + CREATE TEMPORARY TABLE ticketToInvoice + SELECT id + FROM ticket + WHERE refFk = vInvoiceRef; + + CALL invoiceExpenceMake(vInvoiceFk); + + CALL invoiceTaxMake(vInvoiceFk,vTaxArea); + + UPDATE invoiceOut io + JOIN ( + SELECT SUM(amount) AS total + FROM invoiceOutExpence + WHERE invoiceOutFk = vInvoiceFk + ) base + JOIN ( + SELECT SUM(vat) AS total + FROM invoiceOutTax + WHERE invoiceOutFk = vInvoiceFk + ) vat + SET io.amount = base.total + vat.total + WHERE io.id = vInvoiceFk; + + CALL vn.invoiceOutBooking(vInvoiceFk); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutBooking` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutBooking`(IN vInvoice INT) +BEGIN +/* Asienta la factura emitida +* +* param vInvoice factura_id +*/ + DECLARE vBookNumber INT; + DECLARE vExpenceConcept VARCHAR(50); + DECLARE vIsUeeMember BOOL DEFAULT TRUE; + DECLARE vSpainCountryFk INT; + DECLARE vOldBookNumber INT; + + SELECT id INTO vSpainCountryFk FROM country WHERE code = 'ES'; + + SELECT ASIEN + INTO vOldBookNumber + FROM XDiario x + JOIN invoiceOut io ON io.id = vInvoice + WHERE x.SERIE = io.serial + AND x.FACTURA = RIGHT(io.ref, LENGTH(io.ref) - 1) + LIMIT 1; + + DELETE + FROM XDiario + WHERE ASIEN = vOldBookNumber; + + 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, + opDate.FECHA_OP, + io.issued AS FECHA, + 1 AS NFACTICK, + IF(ic.correctingFk,'D','') AS TIPOOPE, + io.cplusTrascendency477Fk AS TIPOCLAVE, + io.cplusTaxBreakFk AS TIPOEXENCI, + io.cplusSubjectOpFk AS TIPONOSUJE, + io.cplusInvoiceType477Fk AS TIPOFACT, + ic.cplusRectificationTypeFk AS TIPORECTIF, + io.companyFk, + RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum, + IF(ct.politicalCountryFk = vSpainCountryFk, vSpainCountryFk, IF(ct.isUeeMember = vIsUeeMember,2,4)) AS TERIDNIF, + CONCAT(IF(ct.isUeeMember = vIsUeeMember AND ct.politicalCountryFk <> 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 + FROM invoiceOut io + JOIN ( + SELECT GREATEST(MAX(shipped), TIMESTAMPADD(DAY,-15,io.issued)) as FECHA_OP + FROM ticket t + JOIN invoiceOut io ON io.ref = t.refFk + WHERE io.id = vInvoice ) opDate + 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 + WHERE io.id = vInvoice; + + CALL vn.ledger_next(vBookNumber); + + -- Linea del cliente + INSERT INTO XDiario( + ASIEN, + FECHA, + SUBCTA, + EURODEBE, + CONCEPTO, + FECHA_EX, + FECHA_OP, + empresa_id + ) + SELECT + vBookNumber AS ASIEN, + rs.FECHA, + rs.clientBookingAccount AS SUBCTA, + rs.totalAmount AS EURODEBE, + rs.simpleConcept AS CONCEPTO, + rs.FECHA_EX, + rs.FECHA_OP, + rs.companyFk AS empresa_id + 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.expenceFk 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 invoiceOutExpence ioe + WHERE ioe.invoiceOutFk = vInvoice; + + SELECT GROUP_CONCAT(`name` SEPARATOR ',') + INTO vExpenceConcept + FROM expence e + JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id + WHERE ioe.invoiceOutFk = vInvoice; + + -- 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, + rs.FECHA, + iot.pgcFk AS SUBCTA, + rs.clientBookingAccount AS CONTRA, + iot.vat AS EUROHABER, + iot.taxableBase AS BASEEURO, + CONCAT(vExpenceConcept,' : ',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, + rs.SERIE, + rs.SERIE_RT, + rs.FACTU_RT, + rs.RECTIFICA, + rs.FECHA_RT, + rs.FECHA_OP, + rs.FECHA_EX, + rs.TIPOOPE, + rs.NFACTICK, + rs.TERIDNIF, + rs.TERNIF, + rs.TERNOM, + pgc.mod340 AS L340, + pgc.cplusTrascendency477Fk AS TIPOCLAVE, + pgc.cplusTaxBreakFk as TIPOEXENCI, + rs.TIPONOSUJE, + rs.TIPOFACT, + rs.TIPORECTIF, + rs.companyFk AS empresa_id + 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. + WHERE iot.invoiceOutFk = vInvoice; + + UPDATE invoiceOut + SET booked = CURDATE() + WHERE id = vInvoice; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutBookingRange` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutBookingRange`() +BEGIN + +/* Reasentar facturas +*/ + + + DECLARE vInvoice INT; + DECLARE vContador INT DEFAULT 0; + + DECLARE done BOOL DEFAULT FALSE; + + DECLARE rs CURSOR FOR + SELECT io.id + FROM invoiceOut io + WHERE RIGHT(ref,7) BETWEEN 1724215 AND 1724224 + AND serial = 'T'; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + OPEN rs; + + FETCH rs INTO vInvoice; + + WHILE NOT done DO + + CALL invoiceOutBooking(vInvoice); + + FETCH rs INTO vInvoice ; + + SET vContador = vContador + 1; + + IF vContador MOD 50 = 0 THEN + + SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS; + + END IF; + + END WHILE; + + CLOSE rs; + + SELECT CONCAT(vContador, ' total') AS FACTURAS_ASENTADAS; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutBooking__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutBooking__`(IN vInvoice INT) +BEGIN +-- bernat: working in this file +/* Asienta la factura emitida +* +* param vInvoice factura_id +*/ + + DECLARE vBookNumber INT; + DECLARE vExpenceConcept VARCHAR(50); + DECLARE isUEENotSpain INT DEFAULT 1; + DECLARE vSpain INT DEFAULT 1; + DECLARE vOldBookNumber INT; + + SELECT ASIEN + INTO vOldBookNumber + FROM vn2008.XDiario x + JOIN vn.invoiceOut io ON io.id = vInvoice + WHERE x.SERIE = io.serial + AND x.FACTURA = RIGHT(io.ref, LENGTH(io.ref) - 1) + LIMIT 1; + + DELETE + FROM vn2008.XDiario + WHERE ASIEN = vOldBookNumber; + + 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, + opDate.FECHA_OP, + io.issued AS FECHA, + 1 AS NFACTICK, + IF(ic.correctingFk,'D','') AS TIPOOPE, + io.cplusTrascendency477Fk AS TIPOCLAVE, + io.cplusTaxBreakFk AS TIPOEXENCI, + io.cplusSubjectOpFk AS TIPONOSUJE, + io.cplusInvoiceType477Fk AS TIPOFACT, + ic.cplusRectificationTypeFk AS TIPORECTIF, + io.companyFk, + RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum, + IF(ct.politicalCountryFk = vSpain, 1, IF(ct.CEE = isUEENotSpain,2,4)) AS TERIDNIF, + CONCAT(IF(ct.CEE = isUEENotSpain,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 + + FROM invoiceOut io + JOIN ( + SELECT GREATEST(MAX(shipped), TIMESTAMPADD(DAY,-15,io.issued)) as FECHA_OP + FROM ticket t + JOIN invoiceOut io ON io.ref = t.refFk + WHERE io.id = vInvoice ) opDate + 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 + WHERE io.id = vInvoice; + + SELECT MAX(ASIEN) + 1 + INTO vBookNumber + FROM vn2008.XDiario; + + -- Linea del cliente + INSERT INTO vn2008.XDiario( + ASIEN, + FECHA, + SUBCTA, + EURODEBE, + CONCEPTO, + FECHA_EX, + FECHA_OP, + empresa_id + ) + SELECT + vBookNumber AS ASIEN, + rs.FECHA, + rs.clientBookingAccount AS SUBCTA, + rs.totalAmount AS EURODEBE, + rs.simpleConcept AS CONCEPTO, + rs.FECHA_EX, + rs.FECHA_OP, + rs.companyFk AS empresa_id + FROM rs; + + -- Lineas de gasto + INSERT INTO vn2008.XDiario( + ASIEN, + FECHA, + SUBCTA, + CONTRA, + EUROHABER, + CONCEPTO, + FECHA_EX, + FECHA_OP, + empresa_id + ) + SELECT + vBookNumber AS ASIEN, + rs.FECHA, + ioe.expenceFk 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 invoiceOutExpence ioe + WHERE ioe.invoiceOutFk = vInvoice; + + SELECT GROUP_CONCAT(`name` SEPARATOR ',') + INTO vExpenceConcept + FROM expence e + JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id + WHERE ioe.invoiceOutFk = vInvoice; + + -- Lineas de IVA + INSERT INTO vn2008.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, + rs.FECHA, + iot.pgcFk AS SUBCTA, + rs.clientBookingAccount AS CONTRA, + iot.vat AS EUROHABER, + iot.taxableBase AS BASEEURO, + CONCAT(vExpenceConcept,' : ',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, + rs.SERIE, + rs.SERIE_RT, + rs.FACTU_RT, + rs.RECTIFICA, + rs.FECHA_RT, + rs.FECHA_OP, + rs.FECHA_EX, + rs.TIPOOPE, + rs.NFACTICK, + rs.TERIDNIF, + rs.TERNIF, + rs.TERNOM, + pgc.mod340 AS L340, + pgc.cplusTrascendency477Fk AS TIPOCLAVE, + pgc.cplusTaxBreakFk as TIPOEXENCI, + rs.TIPONOSUJE, + rs.TIPOFACT, + rs.TIPORECTIF, + rs.companyFk AS empresa_id + 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. + WHERE iot.invoiceOutFk = vInvoice; + + UPDATE invoiceOut + SET booked = CURDATE() + WHERE id = vInvoice; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutBooking___` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutBooking___`(IN vInvoice INT) +BEGIN +/* Asienta la factura emitida +* ULTIMA VERSION +* param vInvoice factura_id +*/ + DECLARE vBookNumber INT; + DECLARE vExpenceConcept VARCHAR(50); + DECLARE vIsUeeMember BOOL DEFAULT TRUE; + DECLARE vSpainCountryFk INT; + DECLARE vOldBookNumber INT; + + SELECT id INTO vSpainCountryFk FROM country WHERE code = 'ES'; + + SELECT ASIEN + INTO vOldBookNumber + FROM XDiario x + JOIN invoiceOut io ON io.id = vInvoice + WHERE x.SERIE = io.serial + AND x.FACTURA = RIGHT(io.ref, LENGTH(io.ref) - 1) + LIMIT 1; + + DELETE + FROM XDiario + WHERE ASIEN = vOldBookNumber; + + 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, + opDate.FECHA_OP, + io.issued AS FECHA, + 1 AS NFACTICK, + IF(ic.correctingFk,'D','') AS TIPOOPE, + io.cplusTrascendency477Fk AS TIPOCLAVE, + io.cplusTaxBreakFk AS TIPOEXENCI, + io.cplusSubjectOpFk AS TIPONOSUJE, + io.cplusInvoiceType477Fk AS TIPOFACT, + ic.cplusRectificationTypeFk AS TIPORECTIF, + io.companyFk, + RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum, + IF(ct.politicalCountryFk = vSpainCountryFk, vSpainCountryFk, IF(ct.isUeeMember = vIsUeeMember,2,4)) AS TERIDNIF, + CONCAT(IF(ct.isUeeMember = vIsUeeMember,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 + FROM invoiceOut io + JOIN ( + SELECT GREATEST(MAX(shipped), TIMESTAMPADD(DAY,-15,io.issued)) as FECHA_OP + FROM ticket t + JOIN invoiceOut io ON io.ref = t.refFk + WHERE io.id = vInvoice ) opDate + 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 + WHERE io.id = vInvoice; + + CALL vn.ledger_next(vBookNumber); + + -- Linea del cliente + INSERT INTO XDiario( + ASIEN, + FECHA, + SUBCTA, + EURODEBE, + CONCEPTO, + FECHA_EX, + FECHA_OP, + empresa_id + ) + SELECT + vBookNumber AS ASIEN, + rs.FECHA, + rs.clientBookingAccount AS SUBCTA, + rs.totalAmount AS EURODEBE, + rs.simpleConcept AS CONCEPTO, + rs.FECHA_EX, + rs.FECHA_OP, + rs.companyFk AS empresa_id + 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.expenceFk 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 invoiceOutExpence ioe + WHERE ioe.invoiceOutFk = vInvoice; + + SELECT GROUP_CONCAT(`name` SEPARATOR ',') + INTO vExpenceConcept + FROM expence e + JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id + WHERE ioe.invoiceOutFk = vInvoice; + + -- 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, + rs.FECHA, + iot.pgcFk AS SUBCTA, + rs.clientBookingAccount AS CONTRA, + iot.vat AS EUROHABER, + iot.taxableBase AS BASEEURO, + CONCAT(vExpenceConcept,' : ',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, + rs.SERIE, + rs.SERIE_RT, + rs.FACTU_RT, + rs.RECTIFICA, + rs.FECHA_RT, + rs.FECHA_OP, + rs.FECHA_EX, + rs.TIPOOPE, + rs.NFACTICK, + rs.TERIDNIF, + rs.TERNIF, + rs.TERNOM, + pgc.mod340 AS L340, + pgc.cplusTrascendency477Fk AS TIPOCLAVE, + pgc.cplusTaxBreakFk as TIPOEXENCI, + rs.TIPONOSUJE, + rs.TIPOFACT, + rs.TIPORECTIF, + rs.companyFk AS empresa_id + 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. + WHERE iot.invoiceOutFk = vInvoice; + + UPDATE invoiceOut + SET booked = CURDATE() + WHERE id = vInvoice; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutDelete` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutDelete`(vRef VARCHAR(15)) +BEGIN + + UPDATE ticket + SET refFk = NULL + WHERE refFk = vRef; + + DELETE + FROM invoiceOut + WHERE ref = vRef; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutFix_BI_RE_IVA` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutFix_BI_RE_IVA`() +BEGIN + +DECLARE done BOOL DEFAULT FALSE; +DECLARE vInvoice INT; + +DECLARE rs CURSOR FOR + SELECT factura_id + FROM vn2008.Facturas + WHERE Importe != BI7 + BI16 + RE4 + RE1 + IVA7 + IVA16 + AND Fecha >= '2017-07-01'; + +DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + +OPEN rs; + +FETCH rs INTO vInvoice; + +SELECT vInvoice, done; + +WHILE NOT done DO + + UPDATE invoiceOut io + JOIN ( + SELECT SUM(amount) AS total + FROM invoiceOutExpence + WHERE invoiceOutFk = vInvoice + ) base + JOIN ( + SELECT SUM(vat) AS total + FROM invoiceOutTax + WHERE invoiceOutFk = vInvoice + ) vat + SET io.amount = base.total + vat.total + WHERE io.id = vInvoice; + + UPDATE vn2008.Facturas + SET BI16 = 0, + BI7 = 0, + RE1 = 0, + RE4 = 0, + IVA7 = 0, + IVA16 = 0 + WHERE factura_id = vInvoice; + + UPDATE vn2008.Facturas f + JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id + SET f.BI16 = iot.taxableBase, f.IVA16 = iot.vat + WHERE f.factura_id = vInvoice + AND iot.pgcFk IN ('4770000021' ,'4770000215', '4770000002','4771000000','4770000000','4770000020'); + + UPDATE vn2008.Facturas f + JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id + SET f.RE4 = iot.vat + WHERE f.factura_id = vInvoice + AND iot.pgcFk = '4770000521'; + + UPDATE vn2008.Facturas f + JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id + SET f.BI7 = iot.taxableBase, f.IVA7 = iot.vat + WHERE f.factura_id = vInvoice + AND iot.pgcFk IN ('4770000010' ,'4770000101'); + + UPDATE vn2008.Facturas f + JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id + SET f.RE1 = iot.vat + WHERE f.factura_id = vInvoice + AND iot.pgcFk = '4770000110'; + +FETCH rs INTO vInvoice; + +END WHILE; + + +CLOSE rs; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutListByCompany` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutListByCompany`(vCompany INT, vStarted DATE, vEnded DATE) +BEGIN + +SELECT + c.socialName as RazonSocial, + c.fi as NIF, + io.ref as Factura, + io.serial as Serie, + io.issued as Fecha, + io.amount as Importe, + c.id as Id_Cliente, + iot.taxableBase as Base, + pgc.rate as Tipo, + iot.vat as Cuota, + pgc.name as Concepto + + FROM vn.invoiceOut io + JOIN vn.invoiceOutTax iot ON iot.invoiceOutFk = io.id + JOIN vn.client c ON c.id = io.clientFk + JOIN vn.pgc ON pgc.code = iot.pgcFk + WHERE io.companyFk = vCompany + AND io.issued BETWEEN vStarted AND vEnded + ORDER BY io.ref DESC; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutTaxAndExpence` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutTaxAndExpence`() +BEGIN + +/* Para tickets ya facturados, vuelve a repetir el proceso de facturación. +* +* @param vInvoice Numero de factura +*/ + + DECLARE vInvoice INT; + DECLARE vInvoiceRef VARCHAR(15); + DECLARE vCountry INT; + DECLARE vTaxArea VARCHAR(15); + DECLARE vContador INT DEFAULT 0; + + DECLARE done BOOL DEFAULT FALSE; + + DECLARE rs CURSOR FOR + SELECT id,ref + FROM invoiceOut io + + WHERE issued >= '2017-07-01' + AND companyFk = 1381 + AND io.amount IS NULL + ; + + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + OPEN rs; + + FETCH rs INTO vInvoice ,vInvoiceRef; + + WHILE NOT done DO + + SELECT s.countryFk + INTO vCountry + FROM supplier s + JOIN invoiceOut io ON io.companyFk = s.id + WHERE io.id = vInvoice; + + SELECT IF(c.isEqualizated AND i.taxAreaFk = 'NATIONAL','EQU',i.taxAreaFk) + INTO vTaxArea + FROM invoiceOutSerial i + JOIN invoiceOut io ON io.serial = i.code + JOIN client c ON c.id = io.clientFk + WHERE io.id = vInvoice; + + DROP TEMPORARY TABLE IF EXISTS ticketToInvoice; + + CREATE TEMPORARY TABLE ticketToInvoice + SELECT id + FROM ticket + WHERE refFk = vInvoiceRef; + + CALL invoiceExpenceMake(vInvoice); + CALL invoiceTaxMake(vInvoice,vCountry,vTaxArea); + + FETCH rs INTO vInvoice ,vInvoiceRef; + + SET vContador = vContador + 1; + + IF vContador MOD 50 = 0 THEN + + SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS; + + END IF; + + END WHILE; + + CLOSE rs; + + SELECT CONCAT(vContador, ' total') AS FACTURAS_ASENTADAS; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOut_new` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOut_new`( + vSerial VARCHAR(255), + vInvoiceDate DATETIME, + vTaxArea VARCHAR(25), + OUT vNewInvoiceId INT) +BEGIN + +/* Creación de facturas emitidas. +* REQUIERE previamente tabla ticketToInvoice. +* +* @param vSerial, vInvoiceDate,vTaxArea +* +* @return vNewInvoiceId +*/ + + DECLARE vSpainCountryCode INT DEFAULT 1; + DECLARE vIsAnySaleToInvoice BOOL; + DECLARE vNewRef VARCHAR(255); + DECLARE vWorker INT DEFAULT vn.getWorker(); + DECLARE vCompany INT; + DECLARE vClient INT; + DECLARE vCplusStandardInvoiceTypeFk INT DEFAULT 1; + DECLARE vCplusCorrectingInvoiceTypeFk INT DEFAULT 6; + DECLARE vCplusSimplifiedInvoiceTypeFk INT DEFAULT 2; + DECLARE vCorrectingSerial VARCHAR(1) DEFAULT 'R'; + DECLARE vSimplifiedSerial VARCHAR(1) DEFAULT 'S'; + + SET vInvoiceDate = IFNULL(vInvoiceDate,CURDATE()); + + SELECT t.clientFk, t.companyFk + INTO vClient, vCompany + FROM ticketToInvoice tt + JOIN ticket t ON t.id = tt.id + LIMIT 1; + + -- Elimina tickets sense moviments +/* UPDATE ticket t + JOIN ticketToInvoice ti ON ti.id = t.id + LEFT JOIN sale s ON s.ticketFk = ti.id + LEFT JOIN expedition e ON e.ticketFk = t.id + LEFT JOIN ticketPackaging tp ON tp.ticketFk = t.id + SET t.shipped = '2000-02-01 00:00:00' + WHERE s.ticketFk IS NULL AND e.ticketFk IS NULL AND e.ticketFk IS NULL; +*/ + -- Eliminem de ticketToInvoice els tickets que no han de ser facturats + DELETE ti.* + FROM ticketToInvoice ti + JOIN ticket t ON t.id = ti.id + JOIN client c ON c.id = t.clientFk + WHERE YEAR(t.shipped) < 2001 + OR c.isTaxDataChecked = FALSE; + + SELECT SUM(quantity * price * (100 - discount)/100) + INTO vIsAnySaleToInvoice + FROM sale s + JOIN ticketToInvoice t on t.id = s.ticketFk; + + IF vIsAnySaleToInvoice THEN + + -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial + -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial + INSERT INTO invoiceOut + ( + ref, + serial, + issued, + clientFk, + dued, + companyFk, + cplusInvoiceType477Fk + ) + SELECT + 1, + vSerial, + vInvoiceDate, + vClient, + getDueDate(vInvoiceDate, dueDay), + vCompany, + IF(vSerial = vCorrectingSerial, + vCplusCorrectingInvoiceTypeFk, + IF(vSerial = vSimplifiedSerial, + vCplusSimplifiedInvoiceTypeFk, + vCplusStandardInvoiceTypeFk)) + FROM client + WHERE id = vClient; + + + SET vNewInvoiceId = LAST_INSERT_ID(); + + SELECT ref + INTO vNewRef + FROM invoiceOut + WHERE id = vNewInvoiceId; + + UPDATE ticket t + JOIN ticketToInvoice ti ON ti.id = t.id + SET t.refFk = vNewRef; + + DROP TEMPORARY TABLE IF EXISTS tmp.updateInter; + CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY + SELECT s.id,ti.id ticket_id,vWorker Id_Trabajador + FROM ticketToInvoice ti + LEFT JOIN vn.ticketState ts ON ti.id = ts.ticket + JOIN state s + WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = vn.getAlert3State(ti.id); + + INSERT INTO vncontrol.inter(state_id,Id_Ticket,Id_Trabajador) + SELECT * FROM tmp.updateInter; + + + INSERT INTO ticketLog (action, userFk,originFk, description) + SELECT 'UPDATE',account.userGetId(),ti.id, CONCAT('Crea factura ',vNewRef) + FROM ticketToInvoice ti; + + CALL invoiceExpenceMake(vNewInvoiceId); + CALL invoiceTaxMake(vNewInvoiceId,vTaxArea); + + UPDATE invoiceOut io + JOIN ( + SELECT SUM(amount) AS total + FROM invoiceOutExpence + WHERE invoiceOutFk = vNewInvoiceId + ) base + JOIN ( + SELECT SUM(vat) AS total + FROM invoiceOutTax + WHERE invoiceOutFk = vNewInvoiceId + ) vat + SET io.amount = base.total + vat.total + WHERE io.id = vNewInvoiceId; + + END IF; + + DROP TEMPORARY TABLE `ticketToInvoice`; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOut_newFromClient` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOut_newFromClient`(vClientFk INT, vSerial CHAR(1), vShipped DATE, vCompanyFk INT, vTaxArea VARCHAR(25), OUT vInvoiceId INT) +BEGIN +/** + * Factura los tickets de un cliente + * @param vTicketFk Id del ticket + * @param vSerial Serie de factura + * @return Id factura + */ + CALL invoiceFromClient(vShipped, vClientFk, vCompanyFk); + CALL invoiceOut_new(vSerial, CURDATE(), vTaxArea, vInvoiceId); + + IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN + CALL invoiceOutBooking(vInvoiceId); + INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(1, 3, vInvoiceId); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOut_newFromTicket` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOut_newFromTicket`(vTicketFk INT, vSerial CHAR(1), vTaxArea VARCHAR(25), OUT vInvoiceId INT) +BEGIN +/** + * Factura un ticket + * @param vTicketFk Id del ticket + * @param vSerial Serie de factura + * @param vTaxArea Area de la factura en caso de querer forzarlo, + * en la mayoria de los casos poner NULL + * @return vInvoiceId + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + CALL invoiceFromTicket(vTicketFk); + CALL invoiceOut_new(vSerial, CURDATE(), vTaxArea, vInvoiceId); + + IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN + CALL invoiceOutBooking(vInvoiceId); + INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(1, 3, vInvoiceId); + END IF; + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceTaxMake` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `invoiceTaxMake`(vInvoice INT, vTaxArea VARCHAR(25)) +BEGIN +/** + * Factura un conjunto de tickets. + * + * @param vInvoice, vTaxAreaFk + * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular + * @return tmp.ticketAmount + * @return tmp.ticketTax Impuesto desglosado para cada ticket. + */ + DELETE FROM invoiceOutTax + WHERE invoiceOutFk = vInvoice; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + (KEY (ticketFk)) + ENGINE = MEMORY + SELECT id ticketFk + FROM ticketToInvoice; + + CALL ticket_getTax(vTaxArea); + + INSERT INTO invoiceOutTax( + invoiceOutFk, + pgcFk, + taxableBase, + vat + ) + SELECT vInvoice, + pgcFk, + SUM(taxableBase) as BASE, + CAST(SUM(taxableBase) * rate / 100 AS DECIMAL (10,2)) + FROM tmp.ticketTax + GROUP BY pgcFk + HAVING BASE; + + DROP TEMPORARY TABLE tmp.ticket; + DROP TEMPORARY TABLE tmp.ticketTax; + DROP TEMPORARY TABLE tmp.ticketAmount; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemCard` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemCard`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT, isBarcode BOOL) +BEGIN + + DECLARE vCacheVisibleFk INT; + DECLARE vCacheAvailableFk INT; + DECLARE vVisibleAltillo INT; + DECLARE vItemFk INT; + + IF isBarcode THEN + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; + ELSE + SELECT i.id INTO vItemFk + FROM vn.item i + WHERE i.name LIKE CONCAT('%',vBarcode,'%') + ORDER BY i.id ASC + LIMIT 1; + END IF; + + + IF vItemFk IS NULL THEN + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; + END IF; + + + + CALL cache.visible_refresh(vCacheVisibleFk, FALSE,vWarehouseFk); + CALL cache.available_refresh(vCacheAvailableFk, FALSE,vWarehouseFk, CURDATE()); + /* + SELECT max(id) INTO vCacheVisibleFk + FROM cache.cache_calc + WHERE cacheName = 'visible' + AND params = vWarehouseFk; + + SELECT max(id) INTO vCacheAvailableFk + FROM cache.cache_calc + WHERE cacheName = 'available' + AND params = CONCAT(vWarehouseFk,'/',date(CURDATE())); + */ + /* + SELECT sum(visible) INTO vVisibleAltillo + FROM vn.itemShelving ish + JOIN vn.shelving sh ON sh.`code` = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk + WHERE ish.itemFk = vItemFk + AND s.warehouseFk = vWarehouseFk; + */ + SELECT visible INTO vVisibleAltillo + FROM vn.itemShelvingStock + WHERE itemFk = vItemFk AND warehouseFk = vWarehouseFk; + + CALL vn2008.item_last_buy_(vWarehouseFk,vItemFk); + + SELECT i.id, + i.longName, + i.tag5, + i.value5, + i.tag6, + i.value6, + i.tag7, + i.value7, + i.image, + i.size, + i.stems, + i.category, + i.minimum as min, + i.upToDown as repo, + p.name as producer, + o.code as origin, + ip.code as nicho, + ip.reserve as reserva, + v.visible - IFNULL(vVisibleAltillo,0) as enNicho, + a.available, + vVisibleAltillo as enAltillo, + v.visible as total, + c.`grouping` as `grouping`, + c.Packing as packing + FROM vn.item i + LEFT JOIN vn.producer p ON p.id = i.producerFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN vn.itemPlacement ip ON ip.itemFk = i.id + LEFT JOIN cache.visible v ON v.calc_id = vCacheVisibleFk AND v.item_id = i.id + LEFT JOIN cache.available a ON a.calc_id = vCacheAvailableFk AND a.item_id = i.id + LEFT JOIN + (SELECT b.item_id,c.`grouping`,c.Packing + FROM vn2008.t_item_last_buy b + INNER JOIN vn2008.Compres c ON c.Id_Compra = b.buy_id + where b.warehouse_id = vWarehouseFk) c + ON i.id= c.item_id + WHERE i.id = vItemFk + AND IFNULL(ip.warehouseFk, vWarehouseFk) = vWarehouseFk; + + DROP TEMPORARY TABLE vn2008.t_item_last_buy; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemDiary` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemDiary`(IN vItemId INT, IN vWarehouse INT) +BEGIN + DECLARE vDateInventory DATETIME; + DECLARE vCurdate DATE DEFAULT CURDATE(); + DECLARE vDayEnd DATETIME DEFAULT util.dayEnd(vCurdate); + -- traduccion: date, alertLevel, origin, reference, name, In, Out, Balance + SELECT inventoried INTO vDateInventory FROM config; + SET @a = 0; + SELECT DATE(date) AS date, + alertLevel, + stateName, + origin, + reference, + clientFk, + name, + `in`, + `out`, + @a := @a + IFNULL(`in`,0) - IFNULL(`out`,0) as balance, + isPicked, + isTicket + FROM + ( SELECT tr.landed as date, + b.quantity as `in`, + NULL as `out`, + IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, + st.name AS stateName, + s.name as name, + e.ref as reference, + e.id as origin, + s.id as clientFk, + TRUE isPicked, + FALSE AS isTicket + 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 alertLevel al ON al.alertLevel = + CASE + WHEN tr.isReceived != FALSE THEN 3 + WHEN tr.isDelivered THEN 1 + ELSE 0 + END + JOIN state st ON st.code = al.code + WHERE tr.landed >= vDateInventory + AND vWarehouse = tr.warehouseInFk + AND b.itemFk = vItemId + AND e.isInventory = 0 + AND e.isRaid = 0 + UNION ALL + + SELECT tr.shipped as date, + NULL as `in`, + b.quantity as `out`, + IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, + st.name AS stateName, + s.name as name, + e.ref as reference, + e.id as origin, + s.id as clientFk, + TRUE isPicked, + FALSE AS isTicket + 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 alertLevel al ON al.alertLevel = + CASE + WHEN tr.isReceived != FALSE THEN 3 + WHEN tr.isDelivered THEN 1 + ELSE 0 + END + JOIN state st ON st.code = al.code + WHERE tr.shipped >= vDateInventory + AND vWarehouse =tr.warehouseOutFk + AND s.id <> 4 + AND b.itemFk = vItemId + AND e.isInventory = 0 + AND w.isFeedStock = 0 + AND e.isRaid = 0 + UNION ALL + + SELECT t.shipped as date, + NULL as `in`, + s.quantity as `out`, + al.alertLevel as alertLevel, + st.name AS stateName, + t.nickname as name, + t.refFk as reference, + t.id as origin, + t.clientFk, + stk.id as isPicked, -- TRUE as isPicked + TRUE as isTicket + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + LEFT JOIN ticketState ts ON ts.ticket = t.id + LEFT JOIN state st ON st.code = ts.code + JOIN client c ON c.id = t.clientFk + JOIN alertLevel al ON al.alertLevel = + CASE + WHEN t.shipped < vCurdate THEN 3 + WHEN t.shipped > vDayEnd THEN 0 + ELSE IFNULL(ts.alertLevel, 0) + END + LEFT JOIN saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = 14 -- comentar + WHERE t.shipped >= vDateInventory + AND s.itemFk = vItemId + AND vWarehouse =t.warehouseFk + ) AS itemDiary + ORDER BY date, isTicket, alertLevel DESC, isPicked DESC, `in` DESC, `out` DESC; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemDiary__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemDiary__`(IN vItemId INT, IN vWarehouse INT) +BEGIN + -- BERNAT WORKING IN THIS FILE + DECLARE vDateInventory DATETIME; + DECLARE vCurdate DATE DEFAULT CURDATE(); + DECLARE vDayEnd DATETIME DEFAULT util.dayEnd(vCurdate); + -- traduccion: date, alertLevel, origin, reference, name, In, Out, Balance + SELECT Fechainventario INTO vDateInventory FROM vn2008.tblContadores; + SET @a = 0; + SELECT DATE(date) AS date, + alertLevel, + stateName, + origin, + reference, + clientFk, + name, + `in`, + `out`, + @a := @a + IFNULL(`in`,0) - IFNULL(`out`,0) as balance, + isPicked, + isTicket + FROM + ( SELECT tr.landed as date, + b.quantity as `in`, + NULL as `out`, + IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, + st.name AS stateName, + s.name as name, + e.ref as reference, + e.id as origin, + s.id as clientFk, + TRUE isPicked, + FALSE AS isTicket + 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.alertLevel al ON al.alertLevel = + CASE + WHEN tr.isReceived != FALSE THEN 3 + WHEN tr.isDelivered THEN 1 + ELSE 0 + END + JOIN vn.state st ON st.code = al.code + WHERE tr.landed >= vDateInventory + AND vWarehouse = tr.warehouseInFk + AND b.itemFk = vItemId + AND e.isInventory = 0 + AND e.isRaid = 0 + UNION ALL + + SELECT tr.shipped as date, + NULL as `in`, + b.quantity as `out`, + IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, + st.name AS stateName, + s.name as name, + e.ref as reference, + e.id as origin, + s.id as clientFk, + TRUE isPicked, + FALSE AS isTicket + 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.alertLevel al ON al.alertLevel = + CASE + WHEN tr.isReceived != FALSE THEN 3 + WHEN tr.isDelivered THEN 1 + ELSE 0 + END + JOIN vn.state st ON st.code = al.code + WHERE tr.shipped >= vDateInventory + AND vWarehouse =tr.warehouseOutFk + AND s.id <> 4 + AND b.itemFk = vItemId + AND e.isInventory = 0 + AND w.isFeedStock = 0 + AND e.isRaid = 0 + UNION ALL + + SELECT t.shipped as date, + NULL as `in`, + s.quantity as `out`, + al.alertLevel as alertLevel, + st.name AS stateName, + t.nickname as name, + t.refFk as reference, + t.id as origin, + t.clientFk, + stk.id as isPicked, -- TRUE as isPicked + TRUE as isTicket + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + LEFT JOIN vn.ticketState ts ON ts.ticket = t.id + JOIN vn.client c ON c.id = t.clientFk + JOIN vn.alertLevel al ON al.alertLevel = + CASE + WHEN t.shipped < vCurdate THEN 3 + WHEN t.shipped > vDayEnd THEN 0 + ELSE IFNULL(ts.alertLevel, 0) + END + JOIN vn.state st ON st.code = al.code + LEFT JOIN vn.saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = 14 -- comentar + WHERE t.shipped >= vDateInventory + AND s.itemFk = vItemId + AND vWarehouse =t.warehouseFk + ) AS itemDiary + ORDER BY date, isTicket, alertLevel DESC, isPicked DESC, `in` DESC, `out` DESC; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemFuentesBalance` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemFuentesBalance`(vDaysInFuture INT) +BEGIN + + CALL cache.stock_refresh(FALSE); + + SELECT alt.itemFk, + i.longName, + i.size, + i.subName, + v.amount as visible, + alt.reserva, + sale.venta, + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, + IFNULL(v.amount,0) - reserva + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as saldo + FROM vn.item i + JOIN ( + SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS reserva + FROM vn.itemShelving ish + LEFT JOIN vn.shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN vn.parking p ON p.id = sh.parkingFk + WHERE (ish.shelvingFk = 'FUE' + OR p.code = 'FUE-PI') + GROUP BY ish.itemFk + ) alt ON alt.itemFk = i.id + LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = 1 + LEFT JOIN ( + SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as venta + FROM vn2008.item_out + WHERE dat BETWEEN CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(curdate())) + AND warehouse_id = 1 + GROUP BY item_id + ) sale ON sale.item_id = alt.itemFk + LEFT JOIN ( + SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as compra + FROM vn2008.item_entry_in + WHERE dat BETWEEN CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(curdate())) + AND warehouse_id = 1 + AND isVirtualStock = FALSE + GROUP BY item_id + ) buy ON buy.item_id = alt.itemFk + LEFT JOIN ( + SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as traslado + FROM vn2008.item_entry_out + WHERE dat BETWEEN CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(curdate())) + AND warehouse_id = 1 + GROUP BY item_id + ) mov ON mov.item_id = alt.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 DROP PROCEDURE IF EXISTS `itemGetVisibleAvailable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemGetVisibleAvailable`( + vItem INT, + vDate DATE, + vWarehouse TINYINT, + vRefresh BOOL) +BEGIN + + DECLARE vVisibleCalc INT; + DECLARE vAvailableCalc INT; + DECLARE vVisibleAltillo INT; + + CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/, vWarehouse, vDate); + CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse); + + + + SELECT visible INTO vVisibleAltillo + FROM vn.itemShelvingStock + WHERE itemFk = vItem + AND warehouseFk = vWarehouse; + + IF vRefresh THEN + + DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; + CREATE TEMPORARY TABLE vn2008.tmp_item + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT vItem item_id, 0 stock, 0 visible; + + SELECT i.id, i.longName, i.box, i.typeFk, + i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, + ip.code, ip.reserve, + vi.visible - IFNULL(vVisibleAltillo,0) AS visible, + av.available + FROM vn.item i + LEFT JOIN vn.itemPlacement ip + ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse + LEFT JOIN vn2008.tmp_item v + ON v.item_id = i.id + LEFT JOIN cache.available av + ON av.calc_id = vAvailableCalc AND av.item_id = i.id + LEFT JOIN cache.visible vi + ON vi.calc_id = vVisibleCalc AND vi.item_id = i.id + LEFT JOIN cache.stock st + ON st.warehouse_id = vWarehouse AND st.item_id = i.id + WHERE (vItem IS NULL OR i.id = vItem); + + ELSE + + SELECT i.id, i.longName, i.box, i.typeFk, + i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, + ip.code, ip.reserve, + v.visible - IFNULL(vVisibleAltillo,0) AS visible, + av.available + FROM vn.item i + LEFT JOIN vn.itemPlacement ip + ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse + LEFT JOIN cache.visible v + ON v.item_id = i.id AND v.calc_id = vVisibleCalc + LEFT JOIN cache.available av + ON av.item_id = i.id AND av.calc_id = vAvailableCalc + WHERE (vItem IS NULL OR i.id = vItem); + + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemLastEntries` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemLastEntries`(IN `vItem` INT, IN `vDays` DATE) +BEGIN + SELECT + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.`grouping`, + b.groupingMode, + i.stems, + b.quantity, + b.buyingValue, + b.packageFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE b.itemFk = vItem And tr.shipped BETWEEN vDays AND CURDATE() + ORDER BY tr.landed DESC , b.id DESC; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemPlacementFromTicket` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementFromTicket`(vTicket INT) +BEGIN +/** + * Llama a itemPlacementUpdateVisible + * de los articulos de la tabla temporal tmp.itemPlacement(itemFk) + * @treturn tmp.itemPlacement + * @param vTicket Id del Ticket + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.itemPlacement; + CREATE TEMPORARY TABLE tmp.itemPlacement + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT s.itemFk + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + WHERE t.id = vTicket; + + CALL itemPlacementUpdateVisible(); + + DROP TEMPORARY TABLE tmp.itemPlacement; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemPlacementReloadVisible` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementReloadVisible`() +BEGIN +/** + * Reemplaza únicamente el campo itemPlacement.pickable + * restando al cache.visible los valores de las tablas + * itemShelving y los tickets con estado impreso + * que aun no han sido preparados. + */ + + DECLARE vCalc INT; + DECLARE vTodayIni DATE DEFAULT CURDATE(); + DECLARE vTodayEnd DATETIME DEFAULT util.dayend(vTodayIni); + DECLARE vproductionOrderPrinted INT DEFAULT 4; + DECLARE vWarehouseSillaFv INT DEFAULT 1; + + UPDATE itemPlacement SET pickable = 0; + + CALL cache.visible_refresh(vCalc, FALSE, vWarehouseSillaFv); +-- SELECT * FROM cache.visible v; + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelving; + CREATE TEMPORARY TABLE tmp.itemShelving + SELECT itemFk, IFNULL(SUM(visible),0) visible + FROM itemShelving its + GROUP BY its.itemFk; +-- SELECT * FROM tmp.itemShelving; + DROP TEMPORARY TABLE IF EXISTS tmp.itemPlacement; + CREATE TEMPORARY TABLE tmp.itemPlacement + SELECT s.itemFk, cast(SUM(s.quantity) AS UNSIGNED) visible + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id AND productionOrder = vproductionOrderPrinted + JOIN sale s ON s.ticketFk = t.id + WHERE t.shipped BETWEEN vTodayIni AND vTodayEnd + GROUP BY s.itemFk; +-- SELECT * FROM tmp.itemPlacement; + +/*SELECT v.item_id, vWarehouseSillaFv, v.visible - IFNULL(tis.visible,0) - IFNULL(tip.visible,0) + FROM cache.visible v + LEFT JOIN tmp.itemShelving tis ON tis.itemFk = v.item_id + LEFT JOIN tmp.itemPlacement tip ON tip.itemFk = v.item_id + WHERE v.calc_id = vCalc; + */ + INSERT INTO itemPlacement(itemFk, warehouseFk, pickable) + SELECT v.item_id, vWarehouseSillaFv, v.visible - IFNULL(tis.visible,0) - IFNULL(tip.visible,0) + FROM cache.visible v + LEFT JOIN tmp.itemShelving tis ON tis.itemFk = v.item_id + LEFT JOIN tmp.itemPlacement tip ON tip.itemFk = v.item_id + WHERE v.calc_id = vCalc + ON DUPLICATE KEY UPDATE pickable = VALUES(pickable); + + DROP TEMPORARY TABLE tmp.itemShelving; + DROP TEMPORARY TABLE tmp.itemPlacement; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemPlacementSave` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementSave`( + vCode VARCHAR(22), + vPlacement VARCHAR(10), + vWarehouseFk INT ) +BEGIN + DECLARE vItemFk INT; + SET vItemFk = barcodeToItem(vCode); + + IF ASCII(vPlacement) > 57 THEN + INSERT INTO itemPlacement(itemFk, warehouseFk, reserve, pickable) + VALUES(vItemFk, vWarehouseFk, vPlacement, 0) + ON DUPLICATE KEY UPDATE reserve = vPlacement, modificationDate = NOW(); + ELSE + INSERT INTO itemPlacement(itemFk, warehouseFk, code) + VALUES(vItemFk, vWarehouseFk, vPlacement) + ON DUPLICATE KEY UPDATE code = vPlacement, modificationDate = NOW(); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemPlacementSupplyAiming` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementSupplyAiming`(vShelvingFk VARCHAR(10), quantity INT, vItemFk INT) +BEGIN + + SELECT ish.itemFk, + ish.longName, + ish.size, + ish.subName, + ish.itemShelvingFk, + ish.shelving, + ish.stock, + LEAST(ish.stock,quantity) as total, + CONCAT( + CAST(FLOOR(LEAST(ish.stock,quantity) / ish.packing) AS DECIMAL(10,0)), + ' x ', + ish.packing, + IF ( + LEAST(ish.stock,quantity) MOD ish.packing, + CONCAT(' + ',CAST(LEAST(ish.stock,quantity) MOD ish.packing AS DECIMAL(10,0))), + '' + ), + ' = ', + LEAST(ish.stock,quantity) + ) as proposal + FROM vn.itemShelvingPlacementSupplyStock ish + WHERE ish.shelving = vShelvingFk COLLATE utf8_general_ci + AND ish.itemFk = 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 DROP PROCEDURE IF EXISTS `itemPlacementSupplyCloseOrder` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementSupplyCloseOrder`(vId INT, vQuantity INT) +BEGIN + + UPDATE vn.itemPlacementSupply + SET priority = 10 + WHERE id = vId; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemPlacementSupplyGetOrder` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementSupplyGetOrder`(vSector INT ) +BEGIN + + DECLARE vId INT; + DECLARE vLastParkingFk INT; + DECLARE vNextParkingFk INT; + + SELECT sh.parkingFk INTO vLastParkingFk + FROM vn.itemShelvingPlacementSupply isps + JOIN vn.itemShelving ish ON ish.id = isps.itemShelvingFk + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + WHERE isps.userFk = getUser() + ORDER BY isps.created DESC + LIMIT 1; + + SET vNextParkingFk = vn.itemShelvingPlacementSupply_ClosestGet(vLastParkingFk); + + SELECT ipsl.id INTO vId + FROM vn.itemPlacementSupplyList ipsl + JOIN vn.itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk + WHERE ipsl.saldo > 0 + AND (ipsl.repoUserFk is NULL OR ipsl.repoUserFk = getUser()) + AND ipsl.sectorFk = vSector + ORDER BY ipsl.repoUserFk DESC, ipsl.priority DESC, (ispss.parkingFk = vNextParkingFk) DESC, ispss.parking DESC, ipsl.created + LIMIT 1; + + UPDATE vn.itemPlacementSupply + SET repoUserFk = getUser() + WHERE id = vId; + + SELECT * FROM vn.itemPlacementSupplyList + WHERE id = vId + AND sectorFk = vSector; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemPlacementSupplyGetOrder__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementSupplyGetOrder__`(vSector INT ) +BEGIN + + DECLARE vId INT; + + SELECT id INTO vId + FROM vn.itemPlacementSupplyList ipsl + WHERE Saldo > 0 + AND (repoUserFk is NULL OR repoUserFk = getUser()) + AND ipsl.sectorFk = vSector + ORDER BY priority DESC, parking DESC, created + LIMIT 1; + + UPDATE vn.itemPlacementSupply + SET repoUserFk = getUser() + WHERE id = vId; + + SELECT * FROM vn.itemPlacementSupplyList + WHERE id = vId + AND sectorFk = vSector; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemPlacementSupplyStockGetTargetList` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementSupplyStockGetTargetList`(vItemFk INT,vSectorFk INT) +BEGIN + + SELECT shelving, parking, sum(stock) as stockTotal,created + FROM + ( + SELECT `ispss`.`itemShelvingFk` AS `itemShelvingFk`, + `ispss`.`itemFk` AS `itemFk`, + `ispss`.`quantity` AS `quantity`, + `ispss`.`packing` AS `packing`, + `ispss`.`stock` AS `stock`, + `ispss`.`longName` AS `longName`, + `ispss`.`size` AS `size`, + `ispss`.`subName` AS `subName`, + `ispss`.`shelving` AS `shelving`, + `ispss`.`parking` AS `parking`, + `ispss`.`created` AS `created`, + `ispss`.`priority` AS `priority`, + `ispss`.`parkingFk` AS `parkingFk`, + `ispss`.`sectorFk` AS `sectorFk` + FROM vn.itemShelvingPlacementSupplyStock ispss + LEFT JOIN vn.parking p ON p.code = parking + WHERE itemFk = vItemFk + -- AND p.sectorFk = vSectorFk + AND stock > 0 + ORDER BY priority DESC + ) sub + GROUP BY shelving + ORDER BY parking ASC; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemPlacementUpdateVisible` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemPlacementUpdateVisible`() +BEGIN +/** + * Reemplaza únicamente el campo itemPlacement.pickable + * de los articulos de la tabla temporal tmp.itemPlacement(itemFk) + * restando al cache.visible los valores de las tablas + * itemShelving y los tickets con estado impreso + * que aun no han sido preparados. + */ + DECLARE vCalc INT; + DECLARE vTodayIni DATE DEFAULT CURDATE(); + DECLARE vTodayEnd DATETIME DEFAULT util.dayend(vTodayIni); + DECLARE vproductionOrderPrinted INT DEFAULT 4; + DECLARE vWarehouseSillaFv INT DEFAULT 1; + + UPDATE itemPlacement SET pickable = 0; + + CALL cache.visible_refresh(vCalc, FALSE, vWarehouseSillaFv); +SELECT * FROM cache.visible v; + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelving; + CREATE TEMPORARY TABLE tmp.itemShelving + SELECT its.itemFk, IFNULL(SUM(visible),0) visible + FROM itemShelving its + JOIN tmp.itemPlacement tip ON tip.itemFk = its.itemFk + GROUP BY its.itemFk; +SELECT * FROM tmp.itemShelving; + +SELECT s.itemFk, cast(SUM(s.quantity) AS UNSIGNED) visible + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id AND productionOrder = vproductionOrderPrinted + JOIN sale s ON s.ticketFk = t.id + JOIN tmp.itemPlacement tip ON tip.itemFk = s.itemFk + WHERE t.shipped BETWEEN vTodayIni AND vTodayEnd + GROUP BY s.itemFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT s.itemFk, cast(SUM(s.quantity) AS UNSIGNED) visible + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id AND productionOrder = vproductionOrderPrinted + JOIN sale s ON s.ticketFk = t.id + JOIN tmp.itemPlacement tip ON tip.itemFk = s.itemFk + WHERE t.shipped BETWEEN vTodayIni AND vTodayEnd + GROUP BY s.itemFk; +SELECT * FROM tmp.ticket; + +SELECT v.item_id, vWarehouseSillaFv, v.visible - IFNULL(tis.visible,0) - IFNULL(tik.visible,0) + FROM cache.visible v + LEFT JOIN tmp.itemShelving tis ON tis.itemFk = v.item_id + LEFT JOIN tmp.ticket tik ON tik.itemFk = v.item_id + WHERE v.calc_id = vCalc; + + INSERT INTO itemPlacement(itemFk, warehouseFk, pickable) + SELECT v.item_id, vWarehouseSillaFv, v.visible - IFNULL(tis.visible,0) - IFNULL(tik.visible,0) + FROM cache.visible v + LEFT JOIN tmp.itemShelving tis ON tis.itemFk = v.item_id + LEFT JOIN tmp.ticket tik ON tik.itemFk = v.item_id + WHERE v.calc_id = vCalc + ON DUPLICATE KEY UPDATE pickable = VALUES(pickable); + + DROP TEMPORARY TABLE tmp.itemShelving; + 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 DROP PROCEDURE IF EXISTS `itemRefreshTags` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemRefreshTags`(IN vItem INT) +BEGIN +/** + * Actualiza la tabla item, los campos "cache" de tags + * + * @param vItem El id del articulo. Si es NULL, equivale a todos. + **/ + DECLARE vInkId VARCHAR(3) DEFAULT NULL; + DECLARE vSize INT DEFAULT NULL; + DECLARE vOriginId INT DEFAULT NULL; + DECLARE vProducerId INT DEFAULT NULL; + DECLARE vStems INT DEFAULT NULL; + + UPDATE item i + LEFT JOIN itemTag it1 ON it1.priority = 1 AND it1.itemFk = i.id + LEFT JOIN itemTag it2 ON it2.priority = 2 AND it2.itemFk = i.id + LEFT JOIN itemTag it3 ON it3.priority = 3 AND it3.itemFk = i.id + SET i.longName = CONCAT_WS(' ', it1.`value`, it2.`value`, it3.`value`) + WHERE (vItem IS NULL OR vItem = i.id); + + UPDATE item i + LEFT JOIN itemTag it1 ON it1.priority = 1 AND it1.itemFk = i.id + LEFT JOIN tagAbbreviation ta1 ON ta1.`value` = it1.`value` + LEFT JOIN itemTag it2 ON it2.priority = 2 AND it2.itemFk = i.id + LEFT JOIN tagAbbreviation ta2 ON ta2.`value` = it2.`value` + LEFT JOIN itemTag it3 ON it3.priority = 3 AND it3.itemFk = i.id + LEFT JOIN tagAbbreviation ta3 ON ta3.`value` = it3.`value` + SET i.`name` = CONCAT_WS(' ', + IFNULL(ta1.abbreviation,it1.`value`), + IFNULL(ta2.abbreviation,it2.`value`), + IFNULL(ta3.abbreviation,it3.`value`)) + WHERE (vItem IS NULL OR vItem = i.id); + + UPDATE item i + LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 4 + SET i.subName = it.`value` + WHERE (vItem IS NULL OR vItem = i.id); + + UPDATE item i + LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 5 + LEFT JOIN tag t ON t.id = it.tagFk + SET tag5 = t.name, value5 = it.`value` + WHERE (vItem IS NULL OR vItem = i.id); + + UPDATE item i + LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 6 + LEFT JOIN tag t ON t.id = it.tagFk + SET tag6 = t.name, value6 = it.`value` + WHERE (vItem IS NULL OR vItem = i.id); + + UPDATE item i + LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 7 + LEFT JOIN tag t ON t.id = it.tagFk + SET i.tag7 = t.name, i.value7 = it.`value` + WHERE (vItem IS NULL OR vItem = i.id); + + UPDATE item i + LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 8 + LEFT JOIN tag t ON t.id = it.tagFk + SET tag8 = t.name, value8 = it.`value` + WHERE (vItem IS NULL OR vItem = i.id); + + UPDATE item i + LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 9 + LEFT JOIN tag t ON t.id = it.tagFk + SET tag9 = t.name, value9 = it.`value` + WHERE (vItem IS NULL OR vItem = i.id); + + UPDATE item i + LEFT JOIN itemTag it ON it.itemFk = i.id AND it.priority = 10 + LEFT JOIN tag t ON t.id = it.tagFk + SET tag10 = t.name, value10 = it.`value` + WHERE (vItem IS NULL OR vItem = i.id); + + IF vItem IS NOT NULL THEN + -- Al insertar el tag color se modifica también el antiguo campo color + SELECT i.id INTO vInkId FROM ink i + JOIN itemTag it ON it.tagFk = 1 AND i.`name` = it.`value` + WHERE vItem = it.itemFk + LIMIT 1; + + IF vInkId > '' THEN + UPDATE item SET inkFk = vInkId WHERE id = vItem; + END IF; + + -- Al insertar el tag origen se modifica también en la tabla item + SELECT o.id INTO vOriginId FROM origin o + JOIN itemTag it ON it.tagFk = 35 AND o.`name` = it.`value` + WHERE vItem = it.itemFk + LIMIT 1; + + IF vOriginId > '' THEN + UPDATE item SET originFk = vOriginId WHERE id = vItem; + END IF; + + -- Al insertar el tag medida se modifica también en la tabla item + SELECT it.`value` INTO vSize + FROM itemTag it + WHERE vItem = it.itemFk AND it.tagFk IN (4, 8) + LIMIT 1; + + IF vSize > '' THEN + UPDATE item SET size = vSize WHERE id = vItem; + END IF; + + -- Al insertar el tag productor se modifica también en la tabla item + SELECT p.id INTO vProducerId FROM producer p + JOIN itemTag it ON it.tagFk = 37 AND p.`name` = it.`value` + WHERE vItem = it.itemFk + LIMIT 1; + + IF vProducerId > '' THEN + UPDATE item SET producerFk = vProducerId WHERE id = vItem; + END IF; + + -- Al insertar el tag tallos se modifica también en la tabla item + SELECT CAST(it.`value` as signed) INTO vStems + FROM itemTag it + WHERE vItem = it.itemFk AND it.tagFk = 23 + LIMIT 1; + + IF vStems > 0 THEN + UPDATE item SET stems = vStems WHERE id = vItem; + END IF; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemSaveMin` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemSaveMin`(min INT,vBarcode VARCHAR(22)) +BEGIN + + DECLARE vItemFk INT; + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; + + UPDATE vn.item SET minimum = min WHERE 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 DROP PROCEDURE IF EXISTS `itemSearchShelving` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemSearchShelving`(`vShelvingFk` VARCHAR(3)) +BEGIN + SELECT p.`column` AS col , p.`row` + FROM vn.shelving s + JOIN parking p ON s.parkingFk = p.id + WHERE s.`code` = vShelvingFk COLLATE utf8_general_ci; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingDelete` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingDelete`(vId INT) +BEGIN + + DELETE FROM vn.itemShelving WHERE id = vId; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingEdit` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingEdit`(vVisible INT,vPacking INT,vId INT) +BEGIN + + UPDATE vn.itemShelving SET available = vVisible, visible = vVisible, packing = vPacking WHERE id = vId; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingList` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingList`(IN `vShelvingFk` VARCHAR(8)) +BEGIN + + /*MODIFICADA POR QUIQUE: OBTENEMOS DEEP Y PARKING*/ + SELECT ish.itemFk as item, + IFNULL(i.longName, CONCAT(i.name, ' ',i.size)) as description, + ish.visible as visible, + ceil(ish.visible/ish.packing) as stickers, + ish.packing as packing, + p.`column` as col, + p.`row` as `row`, + p.`code` as `code`, + ish.id, + s.priority + FROM vn.itemShelving ish + JOIN vn.item i ON i.id = ish.itemFk + INNER JOIN vn.shelving s ON vShelvingFk = s.code COLLATE utf8_unicode_ci + LEFT JOIN vn.parking p ON s.parkingFk = p.id + WHERE ish.shelvingFk COLLATE utf8_unicode_ci =vShelvingFk COLLATE utf8_unicode_ci; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingMake` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingMake`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vShelve` VARCHAR(2), IN `vDeep` INT, IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, IN `vLevel` INT) +BEGIN + + + + DECLARE vItemFk INT; + + + + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; + + + SELECT itemFk INTO vItemFk + FROM vn.buy b + WHERE b.id = vItemFk; + + + IF (SELECT COUNT(*) FROM vn.shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN + + INSERT IGNORE INTO vn.parking(`code`) VALUES(vShelvingFk); + INSERT INTO vn.shelving(`code`, parkingFk) + SELECT vShelvingFk, id + FROM vn.parking + WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; + + END IF; + + + + IF (SELECT COUNT(*) FROM vn.itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking) = 1 THEN + + UPDATE vn.itemShelving SET quantity = quantity+vQuantity,visible = visible+vQuantity,available = available+vQuantity + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; + + ELSE + INSERT INTO itemShelving( itemFk, + shelvingFk, + shelve, + deep, + quantity, + visible, + available, + `grouping`, + packing, + packagingFk, + level) + SELECT + vItemFk, + vShelvingFk, + vShelve, + vDeep, + vQuantity, + vQuantity, + vQuantity, + IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) as `grouping`, + IF(vPacking = 0, b.packing, vPacking) as packing, + IF(vPackagingFk = '', b.packageFk, vPackagingFk) as packaging, + vLevel + FROM vn.item i + LEFT JOIN bi.Last_buy_id lb ON i.id = lb.Id_Article AND lb.warehouse_id = vWarehouseFk + LEFT JOIN vn.buy b ON b.id = lb.Id_Compra + WHERE i.id = vItemFk; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingMakeFromDate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vShelve` VARCHAR(2), IN `vDeep` INT, IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, IN `vLevel` INT,`vCreated` VARCHAR(22)) +BEGIN + + + + DECLARE vItemFk INT; + + + + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; + + + SELECT itemFk INTO vItemFk + FROM vn.buy b + WHERE b.id = vItemFk; + + + IF (SELECT COUNT(*) FROM vn.shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN + + INSERT IGNORE INTO vn.parking(`code`) VALUES(vShelvingFk); + INSERT INTO vn.shelving(`code`, parkingFk) + SELECT vShelvingFk, id + FROM vn.parking + WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; + + END IF; + + IF (SELECT COUNT(*) FROM vn.itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking) = 1 THEN + + UPDATE vn.itemShelving SET quantity = quantity+vQuantity,visible = visible+vQuantity,available = available+vQuantity, created = vCreated + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; + + ELSE + INSERT INTO itemShelving( itemFk, + shelvingFk, + shelve, + deep, + quantity, + visible, + available, + created, + `grouping`, + packing, + packagingFk, + level) + SELECT + vItemFk, + vShelvingFk, + vShelve, + vDeep, + vQuantity, + vQuantity, + vQuantity, + vCreated, + IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) as `grouping`, + IF(vPacking = 0, b.packing, vPacking) as packing, + IF(vPackagingFk = '', b.packageFk, vPackagingFk) as packaging, + vLevel + FROM vn.item i + LEFT JOIN bi.Last_buy_id lb ON i.id = lb.Id_Article AND lb.warehouse_id = vWarehouseFk + LEFT JOIN vn.buy b ON b.id = lb.Id_Compra + WHERE i.id = vItemFk; + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingMatch` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingMatch`(vEntryFk INT, vAllTravel BOOLEAN, vFromTimed DATETIME, vToTimed DATETIME) +BEGIN + + DECLARE vTravelFk INT; + + SELECT travelFk INTO vTravelFk + FROM entry + WHERE id = vEntryFk; + + SELECT i.id, i.longName, i.size, i.subName, b.stickers, ish.etiquetas, b.printed + FROM item i + JOIN ( + SELECT itemFk, sum(stickers) AS stickers, sum(printedStickers) as printed + FROM buy b + JOIN entry e ON e.id = b.entryFk + WHERE IF(vAllTravel , travelFk = vTravelFk, b.entryFk = vEntryFk) + GROUP BY itemFk + ) b ON b.itemFk = i.id + LEFT JOIN ( + SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas + FROM itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking pk ON pk.id = sh.parkingFk + WHERE ish.created BETWEEN vFromTimed AND vToTimed + GROUP BY itemFk + ) ish ON ish.itemFk = id + WHERE b.stickers OR ish.etiquetas; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingPlacementSupplyAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingPlacementSupplyAdd`(vItemShelvingFk INT, vItemPlacementSupplyFk INT, vQuantity INT) +BEGIN + + INSERT INTO vn.itemShelvingPlacementSupply( itemShelvingFk, + itemPlacementSupplyFk, + quantity, + userFk) + VALUES ( vItemShelvingFk, + vItemPlacementSupplyFk, + vQuantity, + getUser()); + + UPDATE vn.itemShelving + SET quantity = quantity - vQuantity, + visible = visible - vQuantity, + available = available - vQuantity + WHERE id = vItemShelvingFk; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingProblem` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingProblem`(vSectorFk INT) +BEGIN + + DECLARE vVisibleCache INT; + DECLARE vWarehouseFk INT; + + SELECT warehouseFk INTO vWarehouseFk + FROM vn.sector + WHERE id = vSectorFk; + + CALL cache.visible_refresh (vVisibleCache, FALSE, vWarehouseFk); + + SELECT t.id as ticketFk, + CAST(s.quantity AS DECIMAL(10,0)) as Cantidad, + s.itemFk, + s.concept, + v.visible - GREATEST(0,iss.visible) + IFNULL(sub3.transit,0) as Nicho, + i.subName, + GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Altillo, + s.id as saleFk, + IFNULL(sub3.transit,0) transit, + v.visible, s.isPicked, s.reserved, t.shipped, tst.productionOrder, mm.Id_Movimiento + FROM vn.ticket t + JOIN vn.ticketState tst ON tst.ticketFk = t.id + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN cache.visible v ON s.itemFk = v.item_id AND v.calc_id = vVisibleCache + LEFT JOIN vn2008.Movimientos_mark mm ON mm.Id_Movimiento = s.id AND mm.stateFk = 26 + JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id + LEFT JOIN + (SELECT itemFk, sum(saldo) as transit + FROM vn.itemPlacementSupplyList + WHERE saldo > 0 + AND sectorFk = vSectorFk + GROUP BY itemFk) sub3 ON sub3.itemFk = i.id + WHERE v.visible + IFNULL(sub3.transit,0) - GREATEST(0,iss.visible) < s.quantity + AND IFNULL(sub3.transit,0) < s.quantity + AND s.isPicked = FALSE + AND s.reserved = FALSE + AND t.shipped BETWEEN CURDATE() AND MIDNIGHT(CURDATE()) + AND tst.isPreviousPreparable = TRUE + AND t.warehouseFk = vWarehouseFk + AND iss.sectorFk = vSectorFk + AND mm.Id_Movimiento IS NULL + ORDER BY itemFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingRadar` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingRadar`(vSectorFk INT) +BEGIN + DECLARE vWarehouseFk INT; + DECLARE vCalcVisibleFk INT; + DECLARE vCalcAvailableFk INT; + + SELECT warehouseFk INTO vWarehouseFk + FROM vn.sector + WHERE id = vSectorFk; + + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); + CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, CURDATE()); + + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; + CREATE TEMPORARY TABLE tmp.itemShelvingRadar + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT iss.itemFk, + 0 `hour`, + 0 `minute`, + ip.`code` itemPlacementCode, + i.longName, + i.size, + i.subName producer, + i.upToDown, + a.available, + IFNULL(v.visible,0) - IFNULL(iss.visible,0) dayEndVisible, + IFNULL(v.visible,0) - IFNULL(iss.visible,0) firstNegative, + IFNULL(v.visible,0) - IFNULL(iss.visible,0) itemPlacementVisible, + i.minimum * b.packing itemPlacementSize, + ips.onTheWay, + iss.visible itemShelvingStock, + IFNULL(v.visible,0) visible, + b.isPickedOff, + iss.sectorFk + FROM vn.itemShelvingStock iss + JOIN vn.item i on i.id = iss.itemFk + LEFT JOIN vn.itemPlacement ip ON ip.itemFk = iss.itemFk AND ip.warehouseFk = vWarehouseFk + 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) + AND iss.sectorFk = vSectorFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime; + CREATE TEMPORARY TABLE tmp.itemOutTime + SELECT *,SUM(amount) quantity + FROM + (SELECT item_id itemFk, + amount, + IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, + IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes + FROM vn2008.item_out io + JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.item_id + 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 > CURDATE() + AND st.isChecked + ) stPrevious ON `stPrevious`.`saleFk` = io.saleFk + WHERE t.warehouseFk = vWarehouseFk + AND s.isPicked = 0 + AND NOT io.Reservado + AND stPrevious.saleFk IS NULL + AND io.dat >= CURDATE() + AND io.dat < CURDATE()+1 + ) sub + GROUP BY itemFk, hours, minutes; + + INSERT INTO tmp.itemShelvingRadar (itemFk) + SELECT itemFk FROM tmp.itemOutTime + ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, + firstNegative = if (firstNegative < 0, firstNegative, firstNegative + quantity), + `hour` = ifnull(if (firstNegative > 0 , `hour`, hours),0), + `minute` = ifnull(if (firstNegative > 0, `minute`, minutes),0); + + SELECT * FROM tmp.itemShelvingRadar; + + DROP TEMPORARY TABLE tmp.itemShelvingRadar; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingRadar_Entry` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingRadar_Entry`(vEntryFk INT) +BEGIN + + DECLARE vWarehouseFk INT DEFAULT 1; + DECLARE vCalcVisibleFk INT; + DECLARE vCalcAvailableFk INT; + DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(CURDATE()); + + CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1); + CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, CURDATE()); + + DROP TEMPORARY TABLE IF EXISTS tmp.item; + CREATE TEMPORARY TABLE tmp.item + ENGINE = MEMORY + SELECT DISTINCT itemFk + FROM vn.buy + WHERE entryFk = vEntryFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.item2; + CREATE TEMPORARY TABLE tmp.item2 + ENGINE = MEMORY + SELECT * + FROM tmp.item; + + SELECT i.id as itemFk, + i.minimum, + CAST(IFNULL(v.visible,0) - IFNULL(iss.visible,0) AS DECIMAL(10,0)) as enNicho, + CAST(IFNULL(a.available,0) AS DECIMAL(10,0)) as disponible, + CAST(IFNULL(v.visible,0) - IFNULL(iss.visible,0) - ts.todaySold AS DECIMAL(10,0)) as finalDia + FROM vn.item i + JOIN tmp.item ti ON ti.itemFk = i.id + LEFT JOIN cache.visible v ON v.calc_id = vCalcVisibleFk AND v.item_id = i.id + LEFT JOIN cache.available a ON i.id = a.item_id AND a.calc_id = vCalcAvailableFk + LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id + LEFT JOIN ( SELECT s.itemFk, sum(s.quantity) as todaySold + FROM vn.sale s + JOIN tmp.item2 ti ON ti.itemFk = s.itemFk + JOIN vn.ticket t ON t.id = s.ticketFk + LEFT JOIN vn.ticketState tst ON tst.ticketFk = t.id + WHERE t.shipped BETWEEN CURDATE() AND vTodayDayEnd + AND t.warehouseFk = vWarehouseFk + AND IFNULL(tst.productionOrder,0) < 5 + GROUP BY s.itemFK + ) ts ON ts.itemFk = i.id; + + + DROP TEMPORARY TABLE tmp.item; + DROP TEMPORARY TABLE tmp.item2; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSaleAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingSaleAdd`(vItemShelvingFk INT, saleFk INT, vQuantity INT) +BEGIN + +IF saleFk <> 0 THEN + INSERT INTO vn.itemShelvingSale( itemShelvingFk, + saleFk, + quantity, + userFk) + VALUES ( vItemShelvingFk, + saleFk, + vQuantity, + getUser()); + + +END IF; + UPDATE vn.itemShelving SET quantity = (quantity - vQuantity), available = (available - vQuantity), visible = (visible - vQuantity) + WHERE id = vItemShelvingFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSaleSupplyAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingSaleSupplyAdd`(vItemShelvingFk INT, saleFk INT, vQuantity INT,idMovimiento INT) +BEGIN + + INSERT INTO vn.itemShelvingSale( itemShelvingFk, + saleFk, + quantity, + userFk) + VALUES ( vItemShelvingFk, + saleFk, + vQuantity, + getUser()); + + UPDATE vn.itemShelving + SET quantity = quantity - vQuantity, + visible = visible - vQuantity, + available = available - vQuantity + WHERE id = vItemShelvingFk; + + UPDATE vn2008.Movimientos_mark + SET valor = 1 + WHERE Id_Movimiento = idMovimiento; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingTicketSource` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingTicketSource`(vTicketFk INT) +BEGIN + DECLARE vCalcFk INT; + DECLARE vWarehouseFk INT; + + SELECT warehouseFk INTO vWarehouseFk + FROM vn.ticket + WHERE id = vTicketFk; + SET vCalcFk = cache.ticketShippingCalcIdGet(vWarehouseFk); + + SELECT + s.id, + ubication, + s.quantity, + sis.quantity as Reserved, + s.itemFk, + s.concept, + s.ticketFk, + s.isPicked, + ish.packing, + FLOOR(sis.quantity / ish.packing) as stickers, + sis.quantity MOD ish.packing as rest, + ts.shippingHour, + ts.shippingMinute + FROM vn.saleItemShelving sis + JOIN vn.itemShelving ish ON ish.id = sis.itemShelvingFk + JOIN vn.sale s ON s.id = sis.saleFk + JOIN cache.ticketShipping ts ON ts.calc_id = vCalcFk AND ts.ticketFk = vTicketFk + WHERE s.ticketFk = vTicketFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingTransfer` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelvingTransfer`(vItemFk INT,shelvingFkO VARCHAR(22),shelvingFkD VARCHAR(22),vQuantity INT) +BEGIN + + DECLARE vPacking INT; + DECLARE vDate VARCHAR(22); + + SELECT packing INTO vPacking + FROM vn.itemShelving + WHERE shelvingFk = shelvingFkO COLLATE utf8_unicode_ci AND itemFk = vItemFk + LIMIT 1; + + SELECT created INTO vDate + FROM vn.itemShelving + WHERE shelvingFk = shelvingFkO COLLATE utf8_unicode_ci AND itemFk = vItemFk + LIMIT 1; + + UPDATE vn.itemShelving + SET quantity = quantity - ( vPacking * vQuantity ), + visible = visible - ( vPacking * vQuantity ), + available = available - ( vPacking * vQuantity ) + WHERE shelvingFk = shelvingFkO COLLATE utf8_unicode_ci AND itemFk = vItemFk; + + CALL vn.itemShelvingMakeFromDate(shelvingFkD,vItemFk,'A',0,( vPacking * vQuantity ),'',0,vPacking,1,1,vDate); + + SELECT true; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemStock` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemStock`(vWarehouseFk SMALLINT, vDated DATETIME, vItemFk INT) +BEGIN +/** + * Calcula el stock del vWarehouseFk desde FechaInventario hasta vDated + * @param vWarehouse warehouse id + * @param vDated max date to filter + * @param vItemFk item id + **/ + SET vDated = TIMESTAMP(DATE(vDated), '00:00:00'); + + DROP TEMPORARY TABLE IF EXISTS tmp.itemList; + CREATE TEMPORARY TABLE tmp.itemList + (UNIQUE INDEX i USING HASH (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(quantity) stock, SUM(quantity) visible, SUM(quantity) available FROM ( + SELECT itemFk, quantity + FROM itemTicketOut + WHERE shipped >= CURDATE() AND shipped < vDated + AND warehouseFk = vWarehouseFk + AND (vItemFk IS NULL OR itemFk = vItemFk) + UNION ALL + SELECT itemFk, quantity + FROM itemEntryIn + WHERE landed >= CURDATE() AND landed < vDated + AND warehouseInFk = vWarehouseFk + AND (vItemFk IS NULL OR itemFk = vItemFk) + UNION ALL + SELECT itemFk, quantity + FROM itemEntryOut + WHERE shipped >= CURDATE() AND shipped < vDated + AND warehouseOutFk = vWarehouseFk + AND (vItemFk IS NULL OR itemFk = vItemFk) + ) t + GROUP BY itemFk HAVING stock != 0; + + CALL `cache`.stock_refresh (FALSE); + + INSERT INTO tmp.itemList (itemFk,stock,visible,available) + SELECT item_id,amount,amount,amount + FROM `cache`.stock + WHERE warehouse_id = vWarehouseFk AND (vItemFk IS NULL OR vItemFk = item_id) + ON DUPLICATE KEY UPDATE + stock = stock + VALUES(stock), + visible = visible + VALUES(visible), + available = available + VALUES(available); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemStockUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemStockUpdate`( + vItemFk INT, + vWarehouseFk INT, + vNewVisible INT, + vIsTrash BOOLEAN) +BEGIN + + DECLARE vTicketFk INT; + DECLARE vClientFk INT; + DECLARE vCompanyVnlFk INT DEFAULT 442; + DECLARE vAgencyModeOthersFk INT DEFAULT 2; + DECLARE vVisible INT DEFAULT 0; + DECLARE vCalc INT; + DECLARE vCurrentTime VARCHAR(5); + + CALL cache.visible_refresh(vCalc, FALSE, vWarehouseFk); + + SELECT IFNULL(visible,0) INTO vVisible + FROM cache.visible + WHERE calc_id = vCalc + AND item_id = vItemFk; + + SELECT IF(vIsTrash,200,400) INTO vClientFk; + + SELECT t.id INTO vTicketFk + FROM vn.ticket t + JOIN vn.address a ON a.id=t.addressFk + WHERE t.warehouseFk = vWarehouseFk + AND t.clientFk = vClientFk + AND DATE(t.shipped) = CURDATE() + AND a.isDefaultAddress + LIMIT 1; + + IF vTicketFk IS NULL THEN + + CALL vn.ticketCreateWithoutZone(vClientFk, CURDATE(), vWarehouseFk, vCompanyVnlFk, NULL, vAgencyModeOthersFk, NULL, CURDATE(), account.userGetId(),vTicketFk); + + END IF; + + INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) + SELECT vTicketFk, vItemFk, CONCAT(longName," ",vn.getWorkerCode(), " ",LEFT(CAST(NOW() AS TIME),5)), vVisible - vNewVisible,0,0 + FROM vn.item + WHERE id = vItemFk; + + UPDATE cache.visible + SET visible = vNewVisible + 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 DROP PROCEDURE IF EXISTS `itemStockVisible_verify` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemStockVisible_verify`(vItemFk INT, vQuantity INT) +BEGIN + + INSERT INTO vn.itemShelving(itemFk, + shelvingFk, + quantity, + visible, + available, + packing) + VALUES( vItemFk, + 'FAL', + -vQuantity, + -vQuantity, + -vQuantity, + -vQuantity); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemTagMake` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemTagMake`(vItemFk INT) +BEGIN + +/* * Crea los tags usando la tabla plantilla itemTag + * y si no existe a partir de la ficha del artículo. + * @param vItemFk El item al que se le añaden los tags +*/ + DECLARE vInk VARCHAR(50); + DECLARE vSize INTEGER; + DECLARE vCategory VARCHAR(3); + DECLARE vProducer VARCHAR(50); + DECLARE vOrigin VARCHAR(20); + DECLARE vTypeFk INTEGER; + + DELETE FROM itemTag + WHERE itemFk = vItemFk; + + SELECT typeFk INTO vTypeFk + FROM item + WHERE id = vItemFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT vItemFk, itt.tagFk, NULL, itt.priority + FROM itemTag it + LEFT JOIN itemTypeTag itt ON itt.itemTypeFk = vTypeFk + WHERE it.itemFk = vItemFk; + + IF (SELECT COUNT(*) FROM itemTag WHERE itemFk = vItemFk LIMIT 1) = 0 THEN + + SELECT ik.name, i.size, i.category, p.name, o.name + INTO vInk, vSize, vCategory, vProducer, vOrigin + FROM item i + LEFT JOIN ink ik ON ik.id = i.inkFk + LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible + LEFT JOIN origin o ON o.id = i.originFk + WHERE i.id = vItemFk; + + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) + VALUES(vItemFk, 1, vInk, 1); + + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) + VALUES (vItemFk, 8, vSize, 2); + + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) + VALUES(vItemFk, 47, vCategory, 3); + + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) + VALUES(vItemFk, 37, vProducer, 4); + + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) + VALUES(vItemFk, 35, vOrigin, 5); + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemTagReorder` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemTagReorder`(itemTypeFk INT) +BEGIN + +DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vItem INT; + + DECLARE cur CURSOR FOR + SELECT id + FROM upda; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + SET @isTriggerDisabled = TRUE; + + DROP TEMPORARY TABLE IF EXISTS upda; + create temporary table upda + SELECT DISTINCT i.id + FROM vn.item i + WHERE i.typeFk = itemTypeFk; + + UPDATE itemTag it + JOIN item i ON i.id = it.itemFk + JOIN itemTypeTag itt ON itt.itemTypeFk = i.typeFk AND itt.tagFk = it.tagFk + SET it.priority = itt.priority + WHERE itt.itemTypeFk = itemTypeFk; + + OPEN cur; + proc: LOOP + SET vDone = FALSE; + FETCH cur INTO vItem; + IF vDone THEN + LEAVE proc; + END IF; + CALL vn.itemRefreshTags(vItem); + END LOOP; + CLOSE cur; + SET @isTriggerDisabled = FALSE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemTagReorderByName` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemTagReorderByName`(vName VARCHAR(255)) +BEGIN + +DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vItem INT; + + DECLARE cur CURSOR FOR + SELECT id + FROM upda; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + SET @isTriggerDisabled = TRUE; + + DROP TEMPORARY TABLE IF EXISTS upda; + CREATE TEMPORARY TABLE upda + SELECT DISTINCT i.id + FROM vn.item i + WHERE i.name LIKE CONCAT(vName,'%'); + + UPDATE itemTag it + JOIN item i ON i.id = it.itemFk + JOIN itemTypeTag itt ON itt.itemTypeFk = i.typeFk AND itt.tagFk = it.tagFk + SET it.priority = itt.priority + WHERE itt.itemTypeFk = itemTypeFk; + + OPEN cur; + proc: LOOP + SET vDone = FALSE; + FETCH cur INTO vItem; + IF vDone THEN + LEAVE proc; + END IF; + CALL vn.itemRefreshTags(vItem); + END LOOP; + CLOSE cur; + SET @isTriggerDisabled = FALSE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemTagReplace` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemTagReplace`(fromItemFk INT, toItemFk INT) +BEGIN + + + DELETE FROM itemTag + WHERE itemFk = toItemFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT toItemFk, tagFk, value, priority + FROM itemTag + WHERE itemFk = fromItemFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemTopSeller` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemTopSeller`() +BEGIN + DECLARE vCategoryFk INTEGER; + DECLARE vDone INT DEFAULT FALSE; + DECLARE rs CURSOR FOR + SELECT DISTINCT id + FROM vn.itemCategory + WHERE merchandise <> FALSE; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + RESIGNAL; + END; + + DROP TABLE IF EXISTS tmp.topSellerMin; + CREATE TEMPORARY TABLE tmp.topSellerMin ENGINE = MEMORY + SELECT s.itemFk, SUM(s.quantity) AS total, v.tipo_id typeFk + FROM vn.sale s + INNER JOIN bs.ventas v ON v.Id_Movimiento = s.id + WHERE v.fecha BETWEEN TIMESTAMPADD(DAY, - 7, CURDATE()) AND CURDATE() + GROUP BY s.itemFk; + + DROP TABLE IF EXISTS tmp.topSeller; + CREATE TEMPORARY TABLE tmp.topSeller + ( + `id` int(11) NOT NULL DEFAULT '0', + `typeFk` smallint(5) unsigned NOT NULL, + `itemCategoryFk` int(10) unsigned NOT NULL, + `total` bigint(21) NOT NULL DEFAULT '0' + ) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + + OPEN rs; + read_loop: LOOP + FETCH rs INTO vCategoryFk; + + IF vDone THEN + LEAVE read_loop; + END IF; + + INSERT INTO tmp.topSeller + SELECT tsm.itemFk, tsm.typeFk, it.categoryFk, tsm.total + FROM tmp.topSellerMin tsm + INNER JOIN vn.itemType it ON it.id = tsm.typeFk + WHERE it.categoryFk = vCategoryFk + ORDER BY tsm.itemFk ,tsm.total DESC + LIMIT 5; + + END LOOP; + CLOSE rs; + + SELECT i.name ,i.id, i.image, i.typeFk, it.categoryFk AS itemCategoryFk, + ic.name AS itemCategoryName, it.name AS itemTypeName, ts.total + FROM tmp.topSeller ts + INNER JOIN vn.item i ON i.id = ts.id + INNER JOIN vn.itemType it ON it.id = ts.typeFk + INNER JOIN vn.itemCategory ic ON ic.id = it.categoryFk; + + DROP TABLE IF EXISTS topSellerMin; + DROP TABLE IF EXISTS tmp.topSeller; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemUpdateTag` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemUpdateTag`(IN vItem BIGINT) +BEGIN + + +UPDATE item i +JOIN producer p ON p.id = i.producerFk +SET i.subName = p.name +WHERE p.isVisible +AND (vItem IS NULL OR vItem = i.id); + +UPDATE item i +JOIN itemTag it ON it.itemFk = i.id +JOIN tag t ON t.id = it.tagFk +SET tag5 = t.name, value5 = it.value +WHERE it.priority = 1 +AND (vItem IS NULL OR vItem = i.id); + +UPDATE item i +JOIN itemTag it ON it.itemFk = i.id +JOIN tag t ON t.id = it.tagFk +SET tag6 = t.name, value6 = it.value +WHERE it.priority = 2 +AND (vItem IS NULL OR vItem = it.itemFk); + +UPDATE item i +JOIN itemTag it ON it.itemFk = i.id +JOIN tag t ON t.id = it.tagFk +SET tag7 = t.name, value7 = it.value +WHERE it.priority = 3 +AND (vItem IS NULL OR vItem = it.itemFk); + +UPDATE item i +JOIN itemTag it ON it.itemFk = i.id +JOIN tag t ON t.id = it.tagFk +SET tag8 = t.name, value8 = it.value +WHERE it.priority = 4 +AND (vItem IS NULL OR vItem = it.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 DROP PROCEDURE IF EXISTS `item_GetVisible` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `item_GetVisible`(vWarehouse SMALLINT, vItem INT) +BEGIN + DECLARE vTomorrow DATETIME DEFAULT TIMESTAMPADD(DAY, 1, CURDATE()); + + INSERT INTO vn2008.tmp_item (item_id, visible) + SELECT item_id, SUM(amount) amount + FROM ( + SELECT i.itemFk AS item_id, quantity AS amount + FROM itemTicketOut i + LEFT JOIN ticketState ts ON ts.ticketFk = i.ticketFk + JOIN state s ON s.id = ts.stateFk + LEFT JOIN (SELECT DISTINCT saleFk + FROM saleTracking st + JOIN state s ON s.id = st.stateFk + WHERE st.created > CURDATE() + AND (s.isPicked OR st.isChecked) + ) stPrevious ON `stPrevious`.`saleFk` = i.saleFk + WHERE i.warehouseFk = vWarehouse + AND (vItem IS NULL OR i.itemFk = vItem) + AND (s.isPicked OR i.reserved OR stPrevious.saleFk ) + AND i.shipped >= CURDATE() AND i.shipped < vTomorrow + UNION ALL + SELECT iei.itemFk, quantity + FROM itemEntryIn iei + LEFT JOIN itemPlacement ip ON ip.itemFk = iei.itemFk AND ip.warehouseFk = vWarehouse + WHERE (iei.isReceived != FALSE /*OR ip.modificationDate > CURDATE()*/) + AND iei.landed >= CURDATE() AND iei.landed < vTomorrow + AND iei.warehouseInFk = vWarehouse + AND (vItem IS NULL OR iei.itemFk = vItem) + AND iei.isVirtualStock is FALSE + UNION ALL + SELECT itemFk, quantity + FROM itemEntryOut + WHERE isDelivered != FALSE + AND shipped >= CURDATE() AND shipped < vTomorrow + AND warehouseOutFk = vWarehouse + AND (vItem IS NULL OR itemFk = vItem) + ) t + GROUP BY item_id + ON DUPLICATE KEY UPDATE + visible = IFNULL(stock,0) + VALUES(visible); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ledger_next` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ledger_next`(OUT vNewBookEntry INT) +BEGIN + + UPDATE vn.ledgerConfig SET lastBookEntry = LAST_INSERT_ID(lastBookEntry + 1); + SET vNewBookEntry = LAST_INSERT_ID(); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `logAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `logAdd`(vOriginFk INT, vActionCode VARCHAR(45), vEntity VARCHAR(45), vDescription TEXT) +BEGIN +/** + * Guarda las acciones realizadas por el usuario + * + * @param vOriginFk Id del registro de origen + * @param vActionCode Código de la acción {insert | delete | update} + * @param vEntity Nombre que hace referencia a la tabla. + * @param descripcion Descripción de la acción realizada por el usuario + */ + + CALL logAddWithUser(vOriginFk, account.userGetId(), vActionCode, vEntity, vDescription); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `logAddWithUser` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `logAddWithUser`(vOriginFk INT, vUserId INT, vActionCode VARCHAR(45), vEntity VARCHAR(45), vDescription TEXT) +BEGIN + /** + * Guarda las acciones realizadas por el usuario + * + * @param vOriginFk Id del registro de origen + * @param vActionCode Código de la acción {insert | delete | update} + * @param vEntity Nombre que hace referencia a la tabla. + * @param descripcion Descripción de la acción realizada por el usuario + */ + DECLARE vTableName VARCHAR(255) DEFAULT CONCAT(IFNULL(vEntity, ''), 'Log'); + + SET @sqlQuery = CONCAT( + 'INSERT INTO vn.', vTableName, ' SET originFk = ?, userFk = ?, action = ?, description = ?' + ); + SET @originFk = vOriginFk; + SET @userFk = vUserId; + SET @action = vActionCode; + SET @description = vDescription; + + PREPARE stmt FROM @sqlQuery; + EXECUTE stmt USING @originFk, @userFk, @action, @description; + DEALLOCATE PREPARE stmt; + + SET @sqlQuery = NULL; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `logShow` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `logShow`(vOriginFk INT, vEntity VARCHAR(45)) +BEGIN +/** + * Muestra las acciones realizadas por el usuario + * + * @param vOriginFk Id del registro de origen + * @param vEntity Nombre que hace referencia a la tabla. + */ + DECLARE vTableName VARCHAR(45); + + SET vTableName = CONCAT(vEntity, 'Log'); + + SET @qryLog := CONCAT( + 'SELECT ot.id, ot.originFk, ot.userFk, u.name, ot.action, ot.creationDate, ot.description FROM ', vTableName, ' AS ot', + ' INNER JOIN account.user u ON u.id = ot.userFk', + ' WHERE ot.originFk = ', vOriginFk, ' ORDER BY ot.creationDate DESC' + ); + + PREPARE stmt FROM @qryLog; + EXECUTE stmt; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `makeNewItem` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `makeNewItem`() +BEGIN + + DECLARE newItemFk INT; + + SELECT getNewItemId() INTO newItemFk; + + INSERT INTO item(id,name,typeFk,originFk) + SELECT newItemFk, 'Nuevo artículo', 78,39; + + SELECT newItemFk; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `manaSpellersRequery` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `manaSpellersRequery`(vWorkerFk INTEGER) +BEGIN + + DECLARE vWorkerIsExcluded BOOLEAN; + DECLARE vFromDated DATE; + DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,CURDATE()); + + SELECT COUNT(*) INTO vWorkerIsExcluded + FROM bs.manaSpellersExcluded + WHERE workerFk = vWorkerFk; + + IF NOT vWorkerIsExcluded THEN + + SELECT max(dated) INTO vFromDated + FROM clientManaCache; + + REPLACE bs.workerMana (workerFk, amount) + SELECT vWorkerFk, sum(mana) FROM + ( + SELECT s.quantity * sc.value as mana + FROM ticket t + JOIN address a ON a.id = t.addressFk + JOIN client c ON c.id = a.clientFk + JOIN sale s ON s.ticketFk = t.id + JOIN saleComponent sc ON sc.saleFk = s.id + WHERE c.salesPersonFk = vWorkerFk AND componentFk IN (39, 37) -- maná auto y maná + AND t.shipped > vFromDated AND t.shipped < vToDated + + UNION ALL + + SELECT - r.amountPaid + FROM receipt r + JOIN client c ON c.id = r.clientFk + WHERE c.salesPersonFk = vWorkerFk AND bankFk = 66 + AND payed > vFromDated + + UNION ALL + + SELECT g.amount + FROM greuge g + JOIN client c ON c.id = g.clientFk + WHERE c.salesPersonFk = vWorkerFk AND g.greugeTypeFk = 3 -- Maná + AND g.shipped > vFromDated and g.shipped < CURDATE() + + UNION ALL + + SELECT mana + FROM clientManaCache cc + JOIN client c ON c.id = cc.clientFk + WHERE c.salesPersonFk = vWorkerFk AND cc.dated = vFromDated + ) sub; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `mergeTicketUnattended` */; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `mergeTicketUnattended`(IN vMainTicket INT(11), IN hasSameAgency BOOLEAN) +BEGIN + + DECLARE isBilled BOOLEAN; + DECLARE arrayTickets VARCHAR(255); + + SELECT Factura IS NOT NULL INTO isBilled FROM vn2008.Tickets WHERE Id_Ticket = vMainTicket; + + IF NOT isBilled THEN + + SELECT GROUP_CONCAT(distinct T.Id_Ticket) INTO arrayTickets + FROM vn2008.Tickets T LEFT JOIN vn.ticketState ts ON T.Id_Ticket = ts.ticket + JOIN vn2008.Tickets ticketOriginal ON ticketOriginal.Id_Ticket = vMainTicket + AND T.empresa_id = ticketOriginal.empresa_id + AND T.Id_Consigna = ticketOriginal.Id_Consigna + AND DATE(T.Fecha) = DATE(ticketOriginal.Fecha) + AND T.warehouse_id = ticketOriginal.warehouse_id + AND IF(hasSameAgency <> 0,T.Id_Agencia = ticketOriginal.Id_Agencia,TRUE) + LEFT JOIN vn.ticketState tsOriginal ON ticketOriginal.Id_Ticket = tsOriginal.ticket + WHERE ts.alertLevel < 3 + AND T.Factura IS NULL + AND T.Anotadoencaja = FALSE + AND T.Id_Ticket <> vMainTicket + AND ts.alertLevel = tsOriginal.alertLevel; + + CALL mergeTicketWithArray(vMainTicket,arrayTickets); + + 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 */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `mergeTicketWithArray` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `mergeTicketWithArray`(IN vMainTicket INT(11), IN arrayTickets VARCHAR(50)) +BEGIN + + DECLARE isBilled BOOLEAN; + DECLARE messageLog VARCHAR(50); + DECLARE company INT; + DECLARE messageForSplit VARCHAR(255); + DECLARE vMainSplit INT; + DECLARE worker INT(3); + + SELECT Factura IS NOT NULL INTO isBilled FROM vn2008.Tickets WHERE Id_Ticket = vMainTicket; + + IF NOT isBilled THEN + + SELECT Id_Trabajador INTO worker from vn2008.Trabajadores where user_id = account.userGetId(); + + DROP TEMPORARY TABLE IF EXISTS vn2008.Tickets_to_fusion; + + -- He usado el util.exec porque da error la variable strId_Tickets puesta dentro del IN() + CALL util.exec(sql_printf(' + CREATE TEMPORARY TABLE vn2008.Tickets_to_fusion + SELECT Id_Ticket, Localizacion + FROM vn2008.Tickets T + WHERE Id_Ticket IN (%s);',arrayTickets)); + + INSERT INTO vn2008.ticket_observation (Id_Ticket,observation_type_id,text) + SELECT vMainTicket,observation_type_id,CONCAT(' Ticket ', Id_Ticket, ':' , tco.text, '. ') + FROM vn2008.Tickets_to_fusion tf + INNER JOIN vn2008.ticket_observation tco USING(Id_Ticket) + ON DUPLICATE KEY UPDATE `text` = CONCAT(ticket_observation.`text`,CONCAT(' Ticket ', VALUES(Id_Ticket), ':' , VALUES(`text`), '. ')); + + UPDATE vn2008.Movimientos M + JOIN vn2008.Tickets_to_fusion USING(Id_Ticket) + SET M.Id_Ticket = vMainTicket; + + UPDATE vn2008.expeditions M + JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = M.ticket_id + SET M.ticket_id = vMainTicket; + + UPDATE vn.ticketPackaging tp + JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = tp.ticketFk + SET tp.ticketFk = vMainTicket; + + UPDATE vn2008.Tickets + SET Bultos = (SELECT COUNT(*) FROM vn2008.expeditions WHERE ticket_id = vMainTicket AND EsBulto) + WHERE Id_Ticket = vMainTicket; + + UPDATE vn2008.Tickets + JOIN vn2008.Tickets_to_fusion USING(Id_Ticket) + SET Fecha = TIMESTAMPADD(YEAR,-1 * (YEAR(Fecha)-2000), Fecha), Id_Ruta = NULL; + + UPDATE vn.ticketLog tl + JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = tl.originFk + SET tl.originFk = vMainTicket; + + UPDATE vn2008.Tickets + SET Localizacion = CONCAT(Tickets.Localizacion,' ',IFNULL((SELECT GROUP_CONCAT(Localizacion SEPARATOR ' ') FROM vn2008.Tickets_to_fusion),'')) + WHERE Id_Ticket = vMainTicket; + + UPDATE vn2008.Splits s + RIGHT JOIN vn2008.Tickets_to_fusion t USING(Id_Ticket) + SET s.Id_Ticket = vMainTicket; + + UPDATE vn2008.Ordenes o + RIGHT JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = o.ticketFk + SET o.ticketFk = vMainTicket; + + IF (SELECT COUNT(*) FROM vn2008.Splits WHERE Id_Ticket=vMainTicket) > 1 THEN + + SELECT Id_Split INTO vMainSplit FROM vn2008.Splits WHERE Id_Ticket = vMainTicket LIMIT 1; + + SELECT group_concat(Notas,',') INTO messageForSplit FROM vn2008.Splits WHERE Id_Ticket = vMainTicket; + UPDATE vn2008.Splits SET Notas = messageForSplit WHERE Id_Split=vMainSplit; + UPDATE vn2008.Split_lines sl JOIN vn2008.Splits s USING (Id_Split) SET sl.Id_Split=vMainSplit WHERE Id_Ticket=vMainTicket; + DELETE FROM vn2008.Splits WHERE Id_Ticket=vMainTicket AND Id_Split<>vMainSplit; + END IF; + + SELECT GROUP_CONCAT(Id_Ticket SEPARATOR ',') into messageLog FROM vn2008.Tickets_to_fusion; + CALL vn2008.Ditacio(vMainTicket,'Fusion','T',worker,messageLog,NULL); + + DELETE ts FROM vn2008.Tickets_state ts JOIN vn2008.Tickets_to_fusion t USING(Id_Ticket); + + DROP TEMPORARY TABLE vn2008.Tickets_to_fusion; + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `mergeTicketWithArray__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `mergeTicketWithArray__`(IN vMainTicket INT(11), IN arrayTickets VARCHAR(50)) +BEGIN + + DECLARE isBilled BOOLEAN; + DECLARE messageLog VARCHAR(50); + DECLARE company INT; + DECLARE messageForSplit VARCHAR(255); + DECLARE vMainSplit INT; + DECLARE worker INT(3); + + SELECT Factura IS NOT NULL INTO isBilled FROM vn2008.Tickets WHERE Id_Ticket = vMainTicket; + + IF NOT isBilled THEN + + SELECT Id_Trabajador INTO worker from vn2008.Trabajadores where user_id = account.userGetId(); + IF worker IS NULL THEN + SET worker = 20; + END IF; + + DROP TEMPORARY TABLE IF EXISTS vn2008.Tickets_to_fusion; + + -- He usado el util.exec porque da error la variable strId_Tickets puesta dentro del IN() + CALL util.exec(sql_printf(' + CREATE TEMPORARY TABLE vn2008.Tickets_to_fusion + SELECT Id_Ticket, Localizacion + FROM vn2008.Tickets T + WHERE Id_Ticket IN (%s);',arrayTickets)); + + INSERT INTO vn2008.ticket_observation (Id_Ticket,observation_type_id,text) + SELECT vMainTicket,observation_type_id,CONCAT(' Ticket ', Id_Ticket, ':' , tco.text, '. ') + FROM vn2008.Tickets_to_fusion tf + INNER JOIN vn2008.ticket_observation tco USING(Id_Ticket) + ON DUPLICATE KEY UPDATE `text` = CONCAT(ticket_observation.`text`,CONCAT(' Ticket ', VALUES(Id_Ticket), ':' , VALUES(`text`), '. ')); + + UPDATE vn2008.Movimientos M + JOIN vn2008.Tickets_to_fusion USING(Id_Ticket) + SET M.Id_Ticket = vMainTicket; + + UPDATE vn2008.expeditions M + JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = M.ticket_id + SET M.ticket_id = vMainTicket; + + UPDATE vn.ticketPackaging tp + JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = tp.ticketFk + SET tp.ticketFk = vMainTicket; + + UPDATE vn2008.Tickets + SET Bultos = (SELECT COUNT(*) FROM vn2008.expeditions WHERE ticket_id = vMainTicket AND EsBulto) + WHERE Id_Ticket = vMainTicket; + + UPDATE vn2008.Tickets + JOIN vn2008.Tickets_to_fusion USING(Id_Ticket) + SET Fecha = TIMESTAMPADD(YEAR,-1 * (YEAR(Fecha)-2000), Fecha), Id_Ruta = NULL; + + UPDATE vn.ticketLog tl + JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = tl.originFk + SET tl.originFk = vMainTicket; + + UPDATE vn2008.Tickets + SET Localizacion = CONCAT(Tickets.Localizacion,' ',IFNULL((SELECT GROUP_CONCAT(Localizacion SEPARATOR ' ') FROM vn2008.Tickets_to_fusion),'')) + WHERE Id_Ticket = vMainTicket; + + UPDATE vn2008.Splits s + RIGHT JOIN vn2008.Tickets_to_fusion t USING(Id_Ticket) + SET s.Id_Ticket = vMainTicket; + + UPDATE vn2008.Ordenes o + RIGHT JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = o.ticketFk + SET o.ticketFk = vMainTicket; + + IF (SELECT COUNT(*) FROM vn2008.Splits WHERE Id_Ticket=vMainTicket) > 1 THEN + + SELECT Id_Split INTO vMainSplit FROM vn2008.Splits WHERE Id_Ticket = vMainTicket LIMIT 1; + + SELECT group_concat(Notas,',') INTO messageForSplit FROM vn2008.Splits WHERE Id_Ticket = vMainTicket; + UPDATE vn2008.Splits SET Notas = messageForSplit WHERE Id_Split=vMainSplit; + UPDATE vn2008.Split_lines sl JOIN vn2008.Splits s USING (Id_Split) SET sl.Id_Split=vMainSplit WHERE Id_Ticket=vMainTicket; + DELETE FROM vn2008.Splits WHERE Id_Ticket=vMainTicket AND Id_Split<>vMainSplit; + END IF; + + SELECT GROUP_CONCAT(Id_Ticket SEPARATOR ',') into messageLog FROM vn2008.Tickets_to_fusion; + CALL vn2008.Ditacio(vMainTicket,'Fusion','T',worker,messageLog,NULL); + + DELETE ts FROM vn2008.Tickets_state ts JOIN vn2008.Tickets_to_fusion t USING(Id_Ticket); + + DROP TEMPORARY TABLE vn2008.Tickets_to_fusion; + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nestAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nestAdd`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45), IN `vParentFk` INT, IN `vChild` VARCHAR(100)) +BEGIN + DECLARE vSql TEXT; + DECLARE vTableClone VARCHAR(45); + + SET vTableClone = CONCAT(vTable, 'Clone'); + + CALL util.exec(CONCAT('DROP TEMPORARY TABLE IF EXISTS tmp.', vTableClone)); + CALL util.exec(CONCAT( + 'CREATE TEMPORARY TABLE tmp.', vTableClone, + ' ENGINE = MEMORY' + ' SELECT * FROM ', vScheme, '.', vTable + )); + + -- Check parent childs + SET vSql = sql_printf(' + SELECT COUNT(c.id) INTO @childs + FROM %t.%t p + LEFT JOIN %t.%t c ON c.lft BETWEEN p.lft AND p.rgt AND c.id != %v + WHERE p.id = %v', + vScheme, vTable, 'tmp', vTableClone, vParentFk, vParentFk); + SET @qrySql := vSql; + + PREPARE stmt FROM @qrySql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + + -- Select left from last child + IF @childs = 0 THEN + SET vSql = sql_printf('SELECT lft INTO @vLeft FROM %t.%t WHERE id = %v', vScheme, vTable, vParentFk); + SET @qrySql := vSql; + ELSE + SET vSql = sql_printf(' + SELECT c.rgt INTO @vLeft + FROM %t.%t p + JOIN %t.%t c ON c.lft BETWEEN p.lft AND p.rgt + WHERE p.id = %v + ORDER BY c.lft + DESC LIMIT 1', + vScheme, vTable, 'tmp', vTableClone, vParentFk); + SET @qrySql := vSql; + END IF; + + PREPARE stmt FROM @qrySql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + + -- Update right + SET vSql = sql_printf('UPDATE %t.%t SET rgt = rgt + 2 WHERE rgt > %v ORDER BY rgt DESC', vScheme, vTable, @vLeft); + SET @qrySql := vSql; + + PREPARE stmt FROM @qrySql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + + SET vSql = sql_printf('UPDATE %t.%t SET lft = lft + 2 WHERE lft > %v ORDER BY lft DESC', vScheme, vTable, @vLeft); + SET @qrySql := vSql; + + PREPARE stmt FROM @qrySql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + + -- Escape character + SET vChild = REPLACE(vChild, "'", "\\'"); + + -- Add child + SET vSql = sql_printf('INSERT INTO %t.%t (name, lft, rgt) VALUES (%v, %v, %v)', vScheme, vTable, vChild, @vLeft + 1, @vLeft + 2); + SET @qrySql := vSql; + + PREPARE stmt FROM @qrySql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + + CALL util.exec(CONCAT('DROP TEMPORARY TABLE tmp.', vTableClone)); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nestLeave` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nestLeave`(vScheme VARCHAR(45), vTable VARCHAR(45), vParentFk INT) +BEGIN + DROP TEMPORARY TABLE IF EXISTS tmp.tree; + + CALL util.exec(CONCAT( + 'CREATE TEMPORARY TABLE tmp.tree ', + 'SELECT + node.id, + node.name, + node.lft, + node.rgt, + node.depth, + node.sons + FROM ', + vScheme, '.', vTable, ' AS node, ', + vScheme, '.', vTable, ' AS parent ', + 'WHERE + node.lft BETWEEN parent.lft AND parent.rgt + AND node.depth = parent.depth + 1 + AND parent.id = ', vParentFk, ' ' + 'GROUP BY node.id + ORDER BY node.lft')); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nestTree` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nestTree`( + vSourceSchema VARCHAR(45), + vSourceTable VARCHAR(45), + vDestinationSchema VARCHAR(45), + vDestinationTable VARCHAR(45)) +BEGIN + DECLARE vTableClone VARCHAR(45); + + SET vTableClone = CONCAT(vSourceTable, 'Clone'); + + CALL util.exec(CONCAT('DROP TEMPORARY TABLE IF EXISTS tmp.', vTableClone)); + CALL util.exec(CONCAT( + 'CREATE TEMPORARY TABLE tmp.', vTableClone, + ' ENGINE = MEMORY', + ' SELECT * FROM ', vSourceSchema, '.', vSourceTable + )); + + CALL util.exec(CONCAT( + 'TRUNCATE TABLE ', vDestinationSchema, '.', vDestinationTable)); + CALL util.exec(CONCAT( + 'INSERT INTO ', vDestinationSchema, '.', vDestinationTable, + '(id, name, lft, rgt, depth, sons)', + 'SELECT + node.id, + node.name, + node.lft, + node.rgt, + COUNT(parent.id) - 1 depth, + CAST((node.rgt - node.lft - 1) / 2 as DECIMAL) as sons + FROM ', + vSourceSchema, '.', vSourceTable, ' AS node,', + 'tmp.', vTableClone, ' AS parent ', + 'WHERE node.lft + BETWEEN parent.lft AND parent.rgt + GROUP BY node.id + ORDER BY node.lft')); + + CALL util.exec(CONCAT('DROP TEMPORARY TABLE tmp.', vTableClone)); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nextShelvingCodeMake` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nextShelvingCodeMake`() +BEGIN + + DECLARE newShelving VARCHAR(3); + DECLARE vCode VARCHAR(3); + + SELECT MAX(code) INTO vCode + FROM vn.shelving + WHERE isPrinted = FALSE; + + SET @a1 := ASCII(MID(vCode,1,1)); + SET @a2 := ASCII(MID(vCode,2,1)); + SET @a3 := ASCII(MID(vCode,3,1)) + 1; + + IF @a3 > 90 THEN + + SET @a3 = 65; + SET @a2 = @a2 + 1; + + IF @a2 > 90 THEN + + SET @a2 = 65; + SET @a1 = @a1 + 1; + + IF @a1 > 90 THEN + + SET @a1 = 65; + + END IF; + + END IF; + + END IF; + + SET newShelving = CHAR(@a1,@a2,@a3 USING utf8); + + INSERT INTO vn.shelving(code) VALUES(newShelving); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `observationAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `observationAdd`(vOriginFk INT, vTableCode VARCHAR(45), vDescription TEXT) +BEGIN +/** + * Guarda las observaciones realizadas por el usuario + * + * @param vOriginFk Id del registro de origen + * @param vTypeCode Código que referencia a la tabla. + * @param descripcion Texto de la observacion + */ + DECLARE vTableName VARCHAR(45); + + SET vTableName = CONCAT(vTableCode,'Observation'); + + IF ISNULL(vTableName) THEN + CALL util.throw('CODE_NOT_FOUND'); + END IF; + + SET @qryLog := CONCAT( + 'INSERT INTO ', vTableName, ' (originFk, userFk, description)', + ' VALUES (', vOriginFk, ', ', account.userGetId(), ', "', vDescription, '")' + ); + + PREPARE stmt FROM @qryLog; + EXECUTE stmt; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `orderCreate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `orderCreate`( + vLanded DATE, + vAgencyMode INT, + vAddress INT, + vSourceApp VARCHAR(10), + OUT vOrderId INT) +BEGIN + + DECLARE vDeliveryMethod INT; + DECLARE vClient INT; + + SELECT deliveryMethodFk INTO vDeliveryMethod + FROM vn.agencyMode + WHERE id = vAgencyMode; + + SELECT clientFk INTO vClient + FROM vn.address + WHERE id = vAddress; + + INSERT INTO hedera.order(date_send,customer_id,delivery_method_id,agency_id,address_id,source_app) + VALUES( vLanded,vClient ,vDeliveryMethod,vAgencyMode ,vAddress ,vSourceApp); + + SET vOrderId = LAST_INSERT_ID(); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `orderDelete` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `orderDelete`(IN vId INT) +BEGIN + + DELETE FROM hedera.`order` where id = vId; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `orderListCreate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `orderListCreate`( + vLanded DATE, + vAgencyMode INT, + vAddress INT, + vSourceApp VARCHAR(10)) +BEGIN + + DECLARE vOrderId INT; + CALL vn.orderCreate(vLanded,vAgencyMode,vAddress,vSourceApp,vOrderId); + SELECT vOrderId; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `orderListVolume` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `orderListVolume`(IN vOrderId INT) +BEGIN + + SELECT + o.id, + o.itemFk, + i.description, + o.amount, + round(r.cm3 * i.compression * o.amount / 1000000,3) as volume + FROM hedera.orderRow o + JOIN vn.item i ON i.id = o.itemFk + JOIN bi.rotacion r ON r.Id_Article = o.itemFk AND r.warehouse_id = o.warehouseFk + WHERE o.orderFk = vOrderId; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `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 vAgenciaEmbalajes INT DEFAULT 628; + DECLARE vComponentCost INT DEFAULT 28; + DECLARE vGraceDate DATE; + DECLARE vZoneFk INT; + + 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 */ + + 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 vDate + 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 GREATEST(COUNT(*),vIsAllInvoiceable) + INTO vIsInvoiceable + FROM tmp.packageToInvoicePositives; + + SELECT id INTO vZoneFk FROM vn.zone WHERE agencyModeFk = vAgenciaEmbalajes LIMIT 1; + + IF vIsInvoiceable THEN + + CALL vn.ticketCreateWithoutZone(vClient, vDate, vWarehouse, vCompany, NULL, vAgenciaEmbalajes, NULL, vDate, account.userGetId(), 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; + + UPDATE ticket SET zoneFk = vZoneFk WHERE id = 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 DROP PROCEDURE IF EXISTS `packingListPrinted` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `packingListPrinted`(ticketFk INT) +BEGIN + + UPDATE vn2008.Movimientos_mark mm + JOIN vn2008.Movimientos m ON m.Id_Movimiento = mm.Id_Movimiento + SET mm.valor = 2 -- Impreso + WHERE mm.valor = 1 -- Listo para imprimir + AND mm.stateFk = 9 -- Encajando + AND m.Id_Ticket = ticketFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `packingListSwitch` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `packingListSwitch`(saleFk INT) +BEGIN + + DECLARE valueFk INT; + DECLARE encajando INT DEFAULT 9; + + SELECT valor INTO valueFk + FROM vn2008.Movimientos_mark + WHERE Id_Movimiento = saleFk + AND stateFk = encajando; + + SET valueFk = (IFNULL(valueFk,0) + 1) MOD 3; + + REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, stateFk) + VALUES(saleFk,valueFk,getWorker(),encajando); + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `parking_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `parking_add`(vFromColumn INT, vToColumn INT, vFromRow INT, vToRow INT, vSectorFk INT) +BEGIN + + DECLARE vColumn INT; + DECLARE vRow INT; + DECLARE vMaxId INT; + + SET vColumn = vFromColumn; + SET vRow = vFromRow; + + SELECT MAX(id) INTO vMaxId + FROM vn.parking; + + WHILE vColumn <= vToColumn DO + + WHILE vRow <= vToRow DO + + INSERT IGNORE INTO vn.parking(`column`, `row`, sectorFk, `code`) + VALUES (vColumn, vRow, vSectorFk, CONCAT(LPAD(vColumn,3,'0'),'-',LPAD(vRow, 2,'0'))); + + SET vRow = vRow + 1; + + END WHILE; + + SET vRow = vFromRow; + + SET vColumn = vColumn + 1; + + END WHILE; + + SELECT * FROM vn.parking WHERE id > vMaxId; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `payRoll` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `payRoll`(IN vFromDated DATE, IN vToDated DATE, IN vFromPaid DATE, IN vToPaid DATE, IN vPartTime BOOL) +BEGIN + + SET @userFk := 0; + + SELECT CONCAT(w.lastName,', ',w.firstname) AS Trabajador, + CAST(Sum((wj.total + wj.permission + wj.lunch)* wj.priceOrdinaryHour + wj.hollyday * wj.priceHollydayHour + + wj.nocturn * wj.priceNocturnHour + + wj.extra * wj.priceExtraHour) AS DECIMAL(10,2)) AS salario, + CAST(Sum(wj.permission) AS DECIMAL(10,2)) AS permission, + CAST(Sum(wj.total) AS DECIMAL(10,2)) AS total, + CAST(Sum(wj.nocturn) AS DECIMAL(10,2)) AS nocturn, + CAST(Sum(wj.hollyday) AS DECIMAL(10,2)) AS hollyday, + CAST(Sum(wj.lunch) AS DECIMAL(10,2)) AS lunch, + CAST(Sum(wj.extra) AS DECIMAL(10,2)) AS extra, + CAST(Sum(wj.contractJourney) AS DECIMAL(10,2)) AS contractJourney, + d.name AS departamento, + CAST(Sum((wj.contractJourney + wj.permission) * wj.priceOrdinaryHour) AS DECIMAL(10,2)) AS teorico, + CAST(Sum((wj.lunch + wj.permission + wj.total) * wj.priceordinaryhour) AS DECIMAL(10,2)) AS practico, + CAST(Sum(wj.nocturn * wj.pricenocturnhour) AS DECIMAL(10,2)) AS nocturno, + CAST(Sum(wj.hollyday * wj.priceHollydayHour) AS DECIMAL(10,2)) AS festivos, + CAST(Sum(wj.extra * wj.priceextrahour) AS DECIMAL(10,2)) AS extras, + MAX(wj.businessFk) as businessFk, + Min(b.date_start) AS fromDated, + Max(b.date_end) AS toDated, + blp.importepactado, + bl.porhoras, + IF(wj.userFk != @userFk, CAST(IFNULL(a.Anticipos,0) AS DECIMAL(10,2)), 0) AS Anticipos, + IF(wj.userFk != @userFk, CAST(IFNULL(se.SaldoEuros,0) AS DECIMAL(10,2)), 0) AS SaldoEuros, + @userFk := wj.userFk as userFk + + FROM vn.worker w + JOIN vn.workerJourney wj ON w.userFk = wj.userFk + JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk + JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id + JOIN vn2008.department d ON bl.department_id = d.department_id + JOIN postgresql.business_labour_payroll blp ON bl.business_id = blp.business_id + JOIN postgresql.business b ON b.business_id = wj.businessFk + LEFT JOIN + (SELECT userFk, sum(debe) as Anticipos + FROM postgresql.income_employee ie + JOIN postgresql.person pe ON ie.person_id = pe.person_id + JOIN vn.worker w ON w.id = pe.id_trabajador + WHERE odbc_date BETWEEN vFromPaid AND vToPaid + AND id_incomeType = 14 -- Salario + GROUP BY userFk + ) a ON a.userFk = wj.userFk + LEFT JOIN + (SELECT userFk, sum(debe) - sum(haber) as SaldoEuros + FROM postgresql.income_employee ie + JOIN postgresql.person pe ON ie.person_id = pe.person_id + JOIN vn.worker w ON w.id = pe.id_trabajador + GROUP BY userFk + ) se ON se.userFk = wj.userFk + WHERE wj.dated BETWEEN vFromDated AND vToDated + AND IF(vPartTime,cl.hours_week <= 40,cl.hours_week = 40) + GROUP BY wj.userFk + ORDER BY w.lastName, w.firstname; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `printTrolleyLabel` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `printTrolleyLabel`(vTicket INT, vPrinter INT, vReport INT) +BEGIN +/** + * Inserta en la cola de impresion una nueva etiqueta de carro, para el sacador + * + * @param vTicket Numero del ticket + * @param vPrinter Numero de impresora + * @param vReport Numero del informe + **/ + DECLARE vlabelCount INT DEFAULT 0; + DECLARE PRIORITY INT DEFAULT 3; + DECLARE vWorker INT; + DECLARE vShipmentHour VARCHAR(10); + + SELECT getTicketTrolleyLabelCount(vTicket) INTO vLabelCount; + SELECT getWorker() INTO vWorker; + SELECT CONCAT(getShipmentHour(vTicket),':00') INTO vShipmentHour; + + INSERT INTO printingQueue(printer + , priority + , report + , `text` + , worker + , text2 + , text3) + VALUES (vPrinter + , PRIORITY + , vReport + , vTicket + , vWorker + , vLabelCount + , vShipmentHour); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productionSectorList` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `productionSectorList`(vSectorFk INT) +BEGIN + + SELECT 0,999999,0 INTO @sameTicket, @ticket, @litrosTicket; + + + SELECT @litrosTicket := IF(sub.ticketFk = @ticket, @litrosTicket + Litros, Litros) as LitrosTicket, + @sameTicket := IF(sub.ticketFk = @ticket, @sameTicket, IF(@sameTicket, 0 , 1)) as sameTicket, + sub.*, + @ticket := ticketFk + FROM + ( + SELECT * FROM + ( + SELECT isa.*, + cast(max(isa.quantity mod isa.packing) as DECIMAL(10,0)) as picos, + sum(isa.available) as totalAvailable, + IF (HOUR(isa.shipped),HOUR(isa.shipped), HOUR(isa.`hour`)) Hora, + IF (MINUTE(isa.shipped),MINUTE(isa.shipped), MINUTE(isa.`hour`)) Minuto, + i.subName, + CAST(isa.physicalVolume * 1000 AS DECIMAL(10,0)) as Litros + FROM vn.itemShelvingAvailable isa + JOIN vn.item i ON i.id = isa.itemFk + JOIN vn.sector s ON s.id = isa.sectorFk + WHERE IF(s.isPreviousPreparedByPacking, (MOD(TRUNCATE(isa.quantity,0), isa.packing)= 0 ), TRUE) + AND isa.isPreviousPreparable = TRUE + AND isa.sectorFk = vSectorFk + AND isa.quantity > 0 + AND isa.sectorFk = vSectorFk + GROUP BY saleFk + HAVING isa.quantity <= totalAvailable + ) sub2 + ORDER BY Hora, Minuto, ticketFk + ) sub + ; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `refund` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `refund`(IN vOriginTicket INT, OUT vNewTicket INT) +BEGIN + + DECLARE vDone BIT DEFAULT 0; + DECLARE vCustomer MEDIUMINT; + DECLARE vWarehouse TINYINT; + DECLARE vCompany MEDIUMINT; + DECLARE vAddress MEDIUMINT; + DECLARE vRefundAgencyMode INT; + DECLARE vItemFk INT; + DECLARE vQuantity DECIMAL (10,2); + DECLARE vConcept VARCHAR(50); + DECLARE vPrice DECIMAL (10,2); + DECLARE vDiscount TINYINT; + DECLARE vSaleNew INT; + DECLARE vSaleMain INT; + DECLARE vZoneFk INT; + + DECLARE vRsMainTicket CURSOR FOR + SELECT id, itemFk, - quantity, concept, price, discount + FROM vn.sale + WHERE ticketFk = vOriginTicket; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; + + SELECT id INTO vRefundAgencyMode + FROM agencyMode WHERE `name` = 'ABONO'; + + SELECT clientFk, warehouseFk, companyFk, addressFk + INTO vCustomer, vWarehouse, vCompany, vAddress + FROM ticket + WHERE id = vOriginTicket; + + SELECT id INTO vZoneFk + FROM zone WHERE agencyModeFk = vRefundAgencyMode + ORDER BY (warehouseFk = vWarehouse) DESC + LIMIT 1; + + INSERT INTO vn2008.Tickets ( + Id_Cliente, + Fecha, + Id_Consigna, + Id_Agencia, + Alias, + warehouse_id, + empresa_id, + landing, + zoneFk + ) + SELECT + vCustomer, + CURDATE(), + vAddress, + vRefundAgencyMode, + a.nickname, + vWarehouse, + vCompany, + CURDATE(), + vZoneFk + FROM address a + WHERE a.id = vAddress; + + SET vNewTicket = LAST_INSERT_ID(); + + SET vDone := 0; + OPEN vRsMainTicket ; + FETCH vRsMainTicket INTO vSaleMain, vItemFk, vQuantity, vConcept, vPrice, vDiscount; + + WHILE NOT vDone DO + + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price, discount) + VALUES( vNewTicket, vItemFk, vQuantity, vConcept, vPrice, vDiscount ); + + SET vSaleNew = LAST_INSERT_ID(); + + INSERT INTO vn.saleComponent(saleFk,componentFk,`value`) + SELECT vSaleNew,componentFk,`value` + FROM vn.saleComponent + WHERE saleFk = vSaleMain; + + FETCH vRsMainTicket INTO vSaleMain, vItemFk, vQuantity, vConcept, vPrice, vDiscount; + + END WHILE; + CLOSE vRsMainTicket; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `replaceMovimientosMark` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `replaceMovimientosMark`( + idMovimiento INT, + detalle INT, + originalQuantity INT, + idTrabajador INT, + stateFk INT, + originFk INT, + userFk INT, + actionString VARCHAR(50), + description VARCHAR(100)) +BEGIN + REPLACE INTO vn2008.Movimientos_mark(Id_Movimiento, valor, original_quantity, Id_Trabajador, stateFk) + VALUES(idMovimiento,detalle,originalQuantity,idTrabajador,stateFk); + /*INSERT INTO vn.ticketLog (originFk, userFk, action , description) + VALUES(originFk, userFk, actionString, 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 DROP PROCEDURE IF EXISTS `riskAllClients` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `riskAllClients`(maxRiskDate DATE) +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.client_list; + CREATE TEMPORARY TABLE tmp.client_list + (PRIMARY KEY (Id_Cliente)) + ENGINE = MEMORY + SELECT id Id_Cliente, null grade FROM vn.client; + + CALL vn2008.risk_vs_client_list(maxRiskDate); + + SELECT + c.RazonSocial, + c.Id_Cliente, + c.Credito, + CAST(r.risk as DECIMAL (10,2)) risk, + CAST(c.Credito - r.risk as DECIMAL (10,2)) Diferencia, + c.Id_Pais + FROM + vn2008.Clientes c + JOIN tmp.risk r ON r.Id_Cliente = c.Id_Cliente + JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente + GROUP BY c.Id_cliente; + + DROP TEMPORARY TABLE IF EXISTS tmp.risk; + DROP TEMPORARY TABLE IF EXISTS tmp.client_list; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `routeGateAsign` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `routeGateAsign`(vDevice VARCHAR(30), vRouteFk INT) +BEGIN + + UPDATE routeGate + SET displayText = NULL, + routeFk = NULL, + freeTickets = NULL, + expeditions = NULL, + scanned = NULL, + flag = NULL, + pallets = NULL, + lastScanned = NULL + WHERE routeFk = vRouteFk; + + UPDATE routeGate + SET routeFk = vRouteFk + WHERE deviceId = vDevice COLLATE utf8_general_ci; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `routeGateUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `routeGateUpdate`() +BEGIN + + UPDATE vn.routeGate rg + LEFT JOIN vn.routesControl rc ON rg.routeFk = rc.routeFk + LEFT JOIN vn.route r ON r.id = rg.routeFk + LEFT JOIN vn2008.Agencias a ON a.Id_Agencia = r.agencyModeFk + LEFT JOIN + ( + SELECT Id_Ruta, count(*) AS pedidosLibres + FROM vn2008.Tickets t + JOIN vn2008.Tickets_state ts ON t.Id_Ticket = ts.Id_Ticket + JOIN vncontrol.inter i ON i.inter_id = ts.inter_id + JOIN vn2008.state s ON i.state_id = s.id AND s.alert_level < 2 + WHERE t.Fecha BETWEEN CURDATE() AND util.dayend(CURDATE()) + AND t.warehouse_id IN (1,44) + AND Id_Ruta + GROUP BY Id_Ruta + ) t ON t.Id_Ruta = rg.routeFk + SET rg.scanned = rc.scanned, + rg.expeditions = rc.expeditions, + rg.flag = a.flag, + rg.freeTickets = t.pedidosLibres, + rg.pallets = rc.pallets, + rg.lastScanned = rc.lastScanned, + rg.displayText = IF(rg.routeFk is null, rg.displayText, rg.routeFk MOD 1000), + rg.ready = IF(rg.freeTickets, FALSE, rg.ready); + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `routeGuessPriority` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `routeGuessPriority`(IN vRuta INT) +BEGIN +/* Usa los valores del ultimo año para adivinar el orden de los tickets en la ruta + * vRuta id ruta +*/ + +UPDATE ticket mt + JOIN ( + SELECT tt.addressFk, ROUND(IFNULL(AVG(t.priority),0),0) AS priority + FROM ticket t + JOIN ticket tt ON tt.addressFk = t.addressFk + WHERE t.shipped > TIMESTAMPADD(YEAR,-1,CURDATE()) + AND tt.routeFk = vRuta + GROUP BY addressFk + ) sub ON sub.addressFk = mt.addressFk + SET mt.priority = sub.priority + WHERE mt.routeFk = vRuta; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `routeSetOk` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `routeSetOk`( + vRouteFk INT) +BEGIN + + UPDATE vn.route r + SET r.isOk = 1 + WHERE r.id = vRouteFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `routeUpdateM3` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `routeUpdateM3`(vRoute INT) +BEGIN + + UPDATE vn.route r + JOIN (SELECT routeFk, SUM(volume) AS m3 + FROM saleVolume + WHERE routeFk = vRoute + ) v ON v.routeFk = r.id + SET r.m3 = v.m3; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `rutasAnalyze` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `rutasAnalyze`(vYear INT, vMonth INT) +BEGIN + +/* Analiza los costes de las rutas de reparto y lo almacena en la tabla Rutas_Master +* +* PAK 15/4/2019 +*/ + + DELETE FROM bi.rutasBoard + WHERE year = vYear AND month = vMonth; + + -- Rellenamos la tabla con los datos de las rutas VOLUMETRICAS, especialmente con los bultos "virtuales" + INSERT INTO bi.rutasBoard(year, + month, + warehouse_id, + Id_Ruta, + Id_Agencia, + km, + Dia, + Fecha, + Bultos, + Matricula, + Tipo, + Terceros) + SELECT YEAR(r.created), + MONTH(r.created), + GREATEST(1,a.warehouseFk), + r.id, + r.agencyModeFk, + r.kmEnd - r.kmStart, + DAYNAME(r.created), + r.created, + SUM(sv.volume / ebv.m3), + v.numberPlate, + IF(ISNULL(`r`.`cost`), 'P', 'A'), + r.cost + FROM vn.route r + JOIN vn.ticket t ON t.routeFk = r.id + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vn.agency a ON a.id = am.agencyFk + LEFT JOIN vn.vehicle v ON v.id = r.vehicleFk + JOIN vn.saleVolume sv ON sv.ticketFk = t.id + JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = 71 + WHERE YEAR(r.created) = vYear AND MONTH(r.created) = vMonth + AND z.isVolumetric + GROUP BY r.id; + + -- Rellenamos la tabla con los datos de las rutas NO VOLUMETRICAS, especialmente con los bultos "virtuales" + INSERT INTO bi.rutasBoard(year, + month, + warehouse_id, + Id_Ruta, + Id_Agencia, + km, + Dia, + Fecha, + Bultos, + Matricula, + Tipo, + Terceros) + SELECT YEAR(r.created), + MONTH(r.created), + GREATEST(1,a.warehouseFk), + r.id, + r.agencyModeFk, + r.kmEnd - r.kmStart, + DAYNAME(r.created), + r.created, + SUM(t.packages), + v.numberPlate, + IF(ISNULL(`r`.`cost`), 'P', 'A'), + r.cost + FROM vn.route r + JOIN vn.ticket t ON t.routeFk = r.id + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vn.agency a ON a.id = am.agencyFk + LEFT JOIN vn.vehicle v ON v.id = r.vehicleFk + WHERE YEAR(r.created) = vYear AND MONTH(r.created) = vMonth + AND z.isVolumetric = FALSE + GROUP BY r.id + ON DUPLICATE KEY UPDATE Bultos = Bultos + VALUES(Bultos); + + -- Coste REAL de cada bulto "virtual", de acuerdo con el valor apuntado a mano en la ruta + UPDATE bi.rutasBoard r + INNER JOIN vn2008.Rutas_Master rm ON rm.año = r.year AND rm.mes = r.month AND rm.warehouse_id = r.warehouse_id + SET r.coste_bulto = IF(r.Tipo ='A', r.Terceros, r.km * rm.coste_km ) / r.Bultos + WHERE r.Bultos > 0 + AND rm.año = vYear + AND rm.mes = vMonth; + + -- Coste PRACTICO de cada bulto, de acuerdo con los componentes de tipo AGENCIA en cada linea de venta + UPDATE bi.rutasBoard r + JOIN ( + SELECT t.routeFk, sum(s.quantity * sc.value) practicoTotal + FROM vn.route r + JOIN vn.time tm ON tm.dated = r.created + JOIN vn.ticket t ON t.routeFk = r.id + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.saleComponent sc ON sc.saleFk = s.id + JOIN vn.componentRate cr ON cr.id = sc.componentFk + JOIN vn.componentTypeRate ctr ON ctr.id = cr.componentTypeRate + WHERE ctr.type = 'agencia' + AND tm.year = vYear + AND tm.month = vMonth + GROUP BY r.id + ) sub ON sub.routeFk = r.Id_Ruta + SET r.practico = sub.practicoTotal / r.Bultos; + + -- Coste TEORICO de una caja "virtual" para cada ruta, teniendo en cuenta que hay carros, pallets, etc + UPDATE bi.rutasBoard r + JOIN ( + SELECT t.routeFk, + SUM(z.price/ ebv.ratio)/ count(*) AS BultoTeoricoMedio + FROM vn.ticket t + JOIN vn.route r ON r.id = t.routeFk + JOIN vn.time tm ON tm.dated = r.created + JOIN vn.expedition e ON e.ticketFk = t.id + JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.isBox + JOIN vn.address ad ON ad.id = t.addressFk + JOIN vn.client c ON c.id = ad.clientFk + JOIN vn.zone z ON z.id = t.zoneFk + WHERE tm.year = vYear + AND tm.month = vMonth + AND z.isVolumetric = FALSE + GROUP BY t.routeFk) sub ON r.Id_Ruta = sub.routeFk + SET r.teorico = sub.BultoTeoricoMedio; + + -- Coste VOLUMETRICO TEORICO de una caja "virtual" para cada ruta + UPDATE bi.rutasBoard r + JOIN ( + SELECT t.routeFk, + SUM(freight) AS BultoTeoricoMedio + FROM vn.ticket t + JOIN vn.route r ON r.id = t.routeFk + JOIN vn.time tm ON tm.dated = r.created + JOIN vn.saleFreight sf ON sf.ticketFk = t.id + JOIN vn.client c ON c.id = sf.clientFk + JOIN vn.zone z ON z.id = t.zoneFk + WHERE tm.year = vYear + AND tm.month = vMonth + AND z.isVolumetric != FALSE + GROUP BY t.routeFk) sub ON r.Id_Ruta = sub.routeFk + SET r.teorico = sub.BultoTeoricoMedio / r.Bultos; + + -- La diferencia entre el teorico y el practico se deberia de cobrar en greuges, cada noche + UPDATE bi.rutasBoard r + JOIN ( + SELECT t.routeFk, + Sum(g.amount) AS greuge + FROM vn.ticket t + JOIN vn.route r ON r.id = t.routeFk + JOIN vn.time tm ON tm.dated = r.created + JOIN vn.greuge g ON g.ticketFk = t.id + JOIN vn.greugeType gt ON gt.id = g.greugeTypeFk + WHERE tm.year = vYear + AND tm.month = vMonth + AND gt.name = 'Diferencia portes' + GROUP BY t.routeFk) sub ON r.Id_Ruta = sub.routeFk + SET r.greuge = sub.greuge / r.Bultos; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `saleItemShelvingDelete` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingDelete`(vSaleFk INT) +BEGIN + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + SET ish.visible = sis.quantity + ish.visible, + ish.available = sis.quantity + ish.visible + WHERE sis.saleFk = vSaleFk; + + DELETE FROM vn.saleItemShelving + WHERE saleFk = vSaleFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `saleItemShelvingIsPicked` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingIsPicked`(vTicketFk INT, vIsPicked BOOL) +BEGIN + + DECLARE vStateFk INT; + + SELECT id INTO vStateFk + FROM state + WHERE code = 'PREVIOUS_PREPARATION'; + + UPDATE vn.sale s + JOIN vn.saleItemShelving sis ON sis.saleFk = s.id + SET s.isPicked = vIsPicked + WHERE s.ticketFk = vTicketFk; + + REPLACE vn2008.Movimientos_mark(Id_Movimiento, Valor, original_quantity, Id_Trabajador, stateFk) + SELECT s.id, s.isPicked, s.quantity, getWorker(), vStateFk + FROM sale s + JOIN vn.saleItemShelving sis ON sis.saleFk = s.id + WHERE s.ticketFk = vTicketFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `saleItemShelvingMake` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingMake`(IN `vTicketFk` INT, IN `vSectorFk` INT) +BEGIN + + SET @rest:= CAST(0 AS DECIMAL(10,0)); + SET @saleFk := CAST(0 AS DECIMAL(10,0)); + SET @reserved := CAST(0 AS DECIMAL(10,0)); + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN sale s ON s.id = sis.saleFk + SET ish.visible = sis.quantity + ish.visible, + ish.available = sis.quantity + ish.visible + WHERE s.ticketFk = vTicketFk; + + DELETE sis.* + FROM saleItemShelving sis + JOIN sale s ON s.id = sis.saleFk + WHERE s.ticketFk = vTicketFk; + + INSERT INTO saleItemShelving( saleFk, + itemShelvingFk, + quantity, + ubication) + SELECT saleFk, + itemShelvingFk, + CAST(Reserved as DECIMAL(10,0)) as Reserved, + ubication + FROM + (SELECT saleFk, + itemShelvingFk, + ubication, + @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, + @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, + @rest := @rest - @reserved, + @saleFk := saleFk + FROM + ( SELECT s.id as saleFk, + ish.created, + ish.id as itemShelvingFk, + ish.available, + s.quantity, + ish.packing, + CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk + JOIN vn.parking p ON p.sectorFk = sc.id + JOIN vn.shelving sh ON sh.parkingFk = p.id + JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk + WHERE t.id = vTicketFk + AND sc.id = vSectorFk + AND s.quantity MOD ish.packing = 0 + AND s.quantity >= ish.packing + ORDER BY s.id, + sh.priority DESC, + ish.packing DESC, + ish.created + ) sub + ) sub2 + WHERE Reserved > 0; + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN vn.sale s ON s.id = sis.saleFk + SET ish.available = ish.visible - sis.quantity, + ish.visible = ish.visible - sis.quantity + WHERE s.ticketFk = vTicketFk + AND s.isPicked = FALSE; + + CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `saleMove` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `saleMove`(IN vSaleFk BIGINT, IN vQuantity BIGINT) +BEGIN + + DECLARE vclientFk INT; + DECLARE vShipped DATE; + DECLARE vWarehouseFk INT; + DECLARE vCompanyFk INT; + DECLARE vAddressFk INT; + DECLARE vAgencyModeFk INT; + DECLARE vNewTicket BIGINT; + DECLARE vNewSale BIGINT; + DECLARE vLanded DATE; + DECLARE vDateStart DATETIME; + DECLARE vDateEnd DATETIME; + DECLARE vAuxId INT; + DECLARE vNumLine INT; + DECLARE vItemFk INT; + + SELECT clientFk,shipped,warehouseFk,companyFk,addressFk,agencyModeFk,landed,t.id + INTO vclientFk,vShipped,vWarehouseFk,vCompanyFk,vAddressFk,vAgencyModeFk,vLanded,vAuxId + FROM ticket t + JOIN sale s ON s.ticketFk=t.id + WHERE s.id = vSaleFk; + + SET vDateStart = TIMESTAMP(vShipped); + SET vDateEnd = TIMESTAMP(vShipped, '23:59:59'); + + SELECT t.id INTO vNewTicket + FROM ticket t + JOIN ticketState ts ON ts.ticketFk=t.id + WHERE t.addressFk = vAddressFk + AND t.warehouseFk = vWarehouseFk + AND t.agencyModeFk = vAgencyModeFk + AND t.landed <=> vLanded + AND t.shipped BETWEEN vDateStart AND vDateEnd + AND t.refFk IS NULL + AND t.clientFk <> 1118 + AND t.id <> vAuxId + AND IFNULL(ts.alertLevel,0) = 0 + LIMIT 1; + +IF vNewTicket IS NULL + THEN + CALL vn.ticket_Clone(vAuxId, vNewTicket); + /*CALL vn2008.bionic_calc_ticket(vNewTicket);*/ + END IF; + + INSERT INTO ticketTracking(ticketFk, workerFk, stateFk) + SELECT vNewTicket, getWorker(), s.id + FROM state s + WHERE s.code = 'FIXING'; + + + /*parche para campapña, eliminar y modificar el front*/ +SELECT COUNT(id) INTO vNumLine + FROM sale s + WHERE s.ticketFk = vNewTicket AND s.itemFk = (SELECT itemFk FROM sale WHERE id = vSaleFk); + + IF vNumLine = 0 THEN + + INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) + SELECT vNewTicket, itemFk, concept, vQuantity, price, discount + FROM sale s + WHERE s.id = vSaleFk; + + SELECT LAST_INSERT_ID() INTO vNewSale; + + INSERT INTO saleComponent(saleFk, componentFk, `value`) + SELECT vNewSale, componentFk, `value` + FROM saleComponent + WHERE saleFk = vSaleFk; + +ELSE IF vQuantity <> 0 THEN + + SELECT itemFk INTO vItemFk FROM sale WHERE id = vSaleFk; + UPDATE sale SET quantity = vQuantity + WHERE ticketFk = vNewTicket AND itemFk = vItemFk; + +END IF; +END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `saleMove__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `saleMove__`(IN vSaleFk BIGINT, IN vQuantity BIGINT) +BEGIN + + DECLARE vclientFk INT; + DECLARE vShipped DATE; + DECLARE vWarehouseFk INT; + DECLARE vCompanyFk INT; + DECLARE vAddressFk INT; + DECLARE vAgencyModeFk INT; + DECLARE vNewTicket BIGINT; + DECLARE vNewSale BIGINT; + DECLARE vLanded DATE; + DECLARE vDateStart DATETIME; + DECLARE vDateEnd DATETIME; + DECLARE vAuxId INT; + DECLARE vNumLine INT; + DECLARE vItemFk INT; + + SELECT clientFk,shipped,warehouseFk,companyFk,addressFk,agencyModeFk,landed,t.id + INTO vclientFk,vShipped,vWarehouseFk,vCompanyFk,vAddressFk,vAgencyModeFk,vLanded,vAuxId + FROM ticket t + JOIN sale s ON s.ticketFk=t.id + WHERE s.id = vSaleFk; + + SET vDateStart = TIMESTAMP(vShipped); + SET vDateEnd = TIMESTAMP(vShipped, '23:59:59'); + + SELECT t.id INTO vNewTicket + FROM ticket t + JOIN ticketState ts ON ts.ticketFk=t.id + WHERE t.addressFk = vAddressFk + AND t.warehouseFk = vWarehouseFk + AND t.agencyModeFk = vAgencyModeFk + AND t.landed <=> vLanded + AND t.shipped BETWEEN vDateStart AND vDateEnd + AND t.refFk IS NULL + AND t.clientFk <> 1118 + AND t.id <> vAuxId + AND IFNULL(ts.alertLevel,0) = 0 + LIMIT 1; + +IF vNewTicket IS NULL + THEN + CALL ticketCreate(vclientFk , vShipped , vWarehouseFk , vCompanyFk , vAddressFk , vAgencyModeFk , NULL,vLanded , vNewTicket); + /*CALL vn2008.bionic_calc_ticket(vNewTicket);*/ + END IF; + + INSERT INTO ticketTracking(ticketFk, workerFk, stateFk) + SELECT vNewTicket, getWorker(), s.id + FROM state s + WHERE s.code = 'FIXING'; + + + /*parche para campapña, eliminar y modificar el front*/ +SELECT COUNT(id) INTO vNumLine + FROM sale s + WHERE s.ticketFk = vNewTicket AND s.itemFk = (SELECT itemFk FROM sale WHERE id = vSaleFk); + + IF vNumLine = 0 THEN + + INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) + SELECT vNewTicket, itemFk, concept, vQuantity, price, discount + FROM sale s + WHERE s.id = vSaleFk; + + SELECT LAST_INSERT_ID() INTO vNewSale; + + INSERT INTO saleComponent(saleFk, componentFk, `value`) + SELECT vNewSale, componentFk, `value` + FROM saleComponent + WHERE saleFk = vSaleFk; + +ELSE IF vQuantity <> 0 THEN + + SELECT itemFk INTO vItemFk FROM sale WHERE id = vSaleFk; + UPDATE sale SET quantity = vQuantity + WHERE ticketFk = vNewTicket AND itemFk = vItemFk; + +END IF; +END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `salePreparingList` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `salePreparingList`(IN ticketFk BIGINT) +BEGIN + + SELECT t.clientFk, + t.shipped, + a.nickname, + s.ticketFk, + s.itemFk, + s.quantity, + s.concept, + s.reserved, + s.id saleFk, + i.size, + i.inkFk, + i.stems, + i.image, + i.subName, + b.`grouping`, + ip.code as placement, + lpad(ifnull(cooler_path_detail_id, ip.code),5,'0') as path, + IF(stPrevious.saleFk,TRUE,FALSE) as isPreviousSelected, + stPrevious.isChecked as isPrevious, + stPrepared.isChecked as isPrepared, + stControled.isChecked as isControled, + ib.code as barcode + + FROM vn.ticket t + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = t.warehouseFk + LEFT JOIN vn2008.cooler_path_detail cpd on left(ip.code,3) = cpd.pasillo + LEFT JOIN bi.Last_buy_id lb ON lb.Id_Article = i.id AND lb.warehouse_id = t.warehouseFk + LEFT JOIN vn.buy b ON b.id = lb.Id_Compra + LEFT JOIN vn.saleTracking stPrevious ON stPrevious.saleFk = s.id AND stPrevious.stateFk = 26 + LEFT JOIN vn.saleTracking stPrepared ON stPrepared.saleFk = s.id AND stPrepared.stateFk = 14 + LEFT JOIN vn.saleTracking stControled ON stControled.saleFk = s.id AND stControled.stateFk = 8 + LEFT JOIN vn.itemBarcode ib ON ib.itemFk = i.id + + WHERE t.id = ticketFk + GROUP BY s.id; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `saleSplit` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `saleSplit`(vSaleFk INT, vQuantity INT) +BEGIN + + + DECLARE vNewSaleFk INT; + + INSERT INTO vn.sale(itemFk, + concept, + price, + discount, + quantity, + ticketFk, + isPriceFixed) + SELECT s.itemFk, + i.longName, + s.price, + s.discount, + vQuantity, + s.ticketFk, + s.isPriceFixed + FROM vn.sale s + JOIN vn.item i ON i.id = s.itemFk + WHERE s.id = vSaleFk; + + UPDATE vn.sale s + JOIN vn.item i ON i.id = s.itemFk + SET s.quantity = s.quantity - vQuantity, s.concept = i.longName + WHERE s.id = vSaleFk; + + SELECT LAST_INSERT_ID() INTO vNewSaleFk; + + INSERT INTO vn.saleComponent( saleFk, + componentFk, + value) + SELECT vNewSaleFk, + componentFk, + value + FROM vn.saleComponent + WHERE saleFk = vSaleFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `saleTracking_del` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `saleTracking_del`(vSaleFk INT, vState VARCHAR(50)) +BEGIN + + DELETE FROM itemShelvingSale + WHERE saleFk = vSaleFk; + + DELETE st.* + FROM vn.saleTracking st + JOIN vn.state s ON s.id = st.stateFk + WHERE st.saleFk = vSaleFk + AND s.code = vState COLLATE utf8_unicode_ci; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `saleTracking_new` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `saleTracking_new`( vSaleFK INT, + vIsChecked BOOLEAN, + vOriginalQuantity INT, + vWorkerFk INT, + vAction VARCHAR(50), + vState VARCHAR(50)) +BEGIN + + REPLACE vn.saleTracking(saleFk, + isChecked, + originalQuantity, + workerFk, + actionFk, + stateFk) + SELECT vSaleFk, + vIsChecked, + vOriginalQuantity, + vWorkerFk, + a.accion_id, + s.id + FROM vncontrol.accion a + JOIN vn.state s + WHERE s.code = vState COLLATE utf8_unicode_ci + AND a.accion = vAction COLLATE utf8_unicode_ci; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sale_calculateComponent` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `sale_calculateComponent`(vSale INT, vOption INT) +proc: BEGIN + + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vTicket BIGINT; + DECLARE vItem BIGINT; + DECLARE vLanded DATE; + DECLARE vTicketFree BOOLEAN DEFAULT TRUE; + DECLARE vZoneFk INTEGER; + + SELECT NOT (t.refFk IS NOT NULL OR ts.alertLevel > 0) OR s.price = 0, s.ticketFk, s.itemFk , t.zoneFk + INTO vTicketFree, vTicket, vItem, vZoneFk + FROM vn.ticket t + JOIN vn.sale s ON s.ticketFk = t.id + LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id + WHERE s.id = vSale + LIMIT 1; + + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.agencyModeFk, t.landed + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded + FROM agencyMode a + JOIN ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicket; + + IF IFNULL(vZoneFk,0) = 0 THEN + CALL util.throw('ticket dont have zone'); + END IF; + + CALL buyUltimate (vWarehouseFk, vShipped); + + DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk + FROM tmp.buyUltimate + WHERE itemFk = vItem; + + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT vSale saleFk,vWarehouseFk warehouseFk; + + IF vOption IS NULL THEN + SET vOption = IF(vTicketFree,1,6); + END IF; + + CALL ticketComponentUpdateSale(vOption); + + INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) + VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); + + 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 DROP PROCEDURE IF EXISTS `saveLoadWorker` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `saveLoadWorker`(routeFk INT, workerFk INT) +BEGIN + + +REPLACE INTO vn.routeLoadWorker(routeFk, workerFk) +VALUES(routeFk,workerFk); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `scanTreeCreate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `scanTreeCreate`() +BEGIN + CALL nestTree( + 'vn2008', + 'scan', + 'vn2008', + 'scanTree' + ); + + UPDATE vn2008.scanTree st + JOIN ( + SELECT sl.scan_id, + MAX(sl.odbc_date) lastScanned, + COUNT(DISTINCT t.routeFk) routeCount, + MIN(t.routeFk) mod 1000 as minRoute, + MAX(t.routeFk) mod 1000 as maxRoute, + COUNT(sl.scan_line_id) as scanned + FROM vn2008.scan_line sl + JOIN expedition e ON e.id = sl.`code` + JOIN ticket t ON t.id = e.ticketFk + WHERE t.routeFk + GROUP BY sl.scan_id + ) rs ON rs.scan_id = st.id + SET st.lastScanned = rs.lastScanned, + st.routeCount = rs.routeCount, + st.minRoute = rs.minRoute, + st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), + st.scanned = rs.scanned; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `setPlacementReserve` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `setPlacementReserve`(vItemFk INT, vPlacement VARCHAR(10), vWarehouseFk INT ) +BEGIN + + DECLARE vReserve VARCHAR(10); + DECLARE vReserveOLD VARCHAR(10); + DECLARE vPlacementOLD VARCHAR(10); + + SELECT code, reserve INTO vPlacementOLD, vReserveOLD + FROM itemPlacement + WHERE itemFk = vItemFk + AND warehouseFk = vWarehouseFk; + + IF ASCII(vPlacement) > 57 THEN + + SET vReserve = vPlacement; + SET vPlacement = vPlacementOLD; + + ELSE + + SET vReserve = vReserveOLD; + + END IF; + + REPLACE itemPlacement(itemFk, warehouseFk, code,reserve) + VALUES(vItemFk, vWarehouseFk, vPlacement, vReserve); + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `shelvingChange` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `shelvingChange`(IN `vShelvingO` VARCHAR(8), IN `vShelvingD` VARCHAR(8)) +BEGIN + + UPDATE vn.itemShelving + SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci + WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `shelvingFuture` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `shelvingFuture`(vSectorFk INT) +BEGIN + + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vItemFk INT; + DECLARE vItemShelvingRest INT; + DECLARE vItemShelvingFk INT; + DECLARE vItemShelvingCreated DATE; + DECLARE vSaleRest INT; + DECLARE vSaleDated DATE; + DECLARE vWarehouseFk INT; + + DECLARE rsItem CURSOR FOR + SELECT DISTINCT itemFk + FROM vn.itemShelvingStock + WHERE sectorFk = vSectorFk + AND visible > 0; + + DECLARE rsItemShelving CURSOR FOR + SELECT ish.id, + ish.visible, + date(ish.created) + FROM vn.itemShelving ish + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + WHERE ish.itemFk = vItemFk + AND ish.visible > 0 + AND p.sectorFk = vSectorFk + ORDER BY date(ish.created), ish.visible; + + DECLARE rsSale CURSOR FOR + SELECT - floor(sum(io.amount)) as sold, + date(io.dat) as dated + FROM vn2008.item_out io + LEFT JOIN tmp.ticketFree tf ON tf.ticketFk = io.ticketFk + WHERE (dat BETWEEN util.tomorrow() AND '2019-10-31' + OR + (dat BETWEEN CURDATE() AND util.dayEnd(CURDATE()) AND tf.ticketFk IS NOT NULL)) + AND item_id = vItemFk + AND io.warehouse_id = vWarehouseFk + GROUP BY dated; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SELECT warehouseFk INTO vWarehouseFk + FROM vn.sector + WHERE id = vSectorFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketFree; + CREATE TEMPORARY TABLE tmp.ticketFree + SELECT ticket as ticketFk + FROM vn.ticketStateToday tst + JOIN vn.state s ON s.id = tst.state + WHERE s.isPicked = FALSE; + + DROP TEMPORARY TABLE IF EXISTS tmp.result; + CREATE TEMPORARY TABLE tmp.result + SELECT ish.id as itemShelvingFk, + date(ish.created) as created, + ish.visible, + 0 as reserve, + CAST('2019-10-31' AS DATE) as picked, + ish.shelvingFk, + 0 as Litros, + p.code as parkingCode + FROM vn.itemShelving ish + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + WHERE ish.visible > 0 + AND p.sectorFk = vSectorFk + ORDER BY date(ish.created), ish.visible; + + UPDATE tmp.result r + JOIN (SELECT ish.id, floor(sum(ish.visible * r.cm3) / 1000) as Litros + FROM vn.itemShelving ish + JOIN bi.rotacion r ON r.Id_Article = ish.itemFk AND r.warehouse_id = vWarehouseFk + GROUP BY ish.id) sub ON r.itemShelvingFk = sub.id + SET r.Litros = sub.Litros; + + ALTER TABLE tmp.result + ADD PRIMARY KEY (itemShelvingFk); + + OPEN rsItem; + + FETCH rsItem INTO vItemFk; + + -- TRUNCATE tmp.log; + + WHILE NOT vDone DO + + OPEN rsItemShelving; + OPEN rsSale; + + FETCH rsSale INTO vSaleRest, vSaleDated; + FETCH rsItemShelving INTO vItemShelvingFk, vItemShelvingRest, vItemShelvingCreated; + /* + INSERT INTO tmp.log(vItemFk, vItemShelvingRest, vSaleRest, vSalePicked,ifSide) + VALUES (vItemFk, vItemShelvingRest, vSaleRest, vSaleDated, '0'); + */ + bucle: LOOP + + IF vDone THEN + + LEAVE bucle; + + END IF; + + IF vSaleRest >= vItemShelvingRest THEN + /* + INSERT INTO tmp.log(vItemFk, vItemShelvingRest, vSaleRest, vSalePicked,ifSide) + VALUES (vItemFk, vItemShelvingRest, vSaleRest, vSaleDated, '1'); + */ + SET vSaleRest = vSaleRest - vItemShelvingRest; + + UPDATE tmp.result + SET reserve = reserve + vItemShelvingRest, + picked = LEAST(picked, vSaleDated) + WHERE itemShelvingFk = vItemShelvingFk; + + FETCH rsItemShelving INTO vItemShelvingFk, vItemShelvingRest, vItemShelvingCreated; + + IF vSaleRest = 0 THEN + + FETCH rsSale INTO vSaleRest, vSaleDated; + + END IF; + + ELSE + /* + INSERT INTO tmp.log(vItemFk, vItemShelvingRest, vSaleRest, vSalePicked,ifSide) + VALUES (vItemFk, vItemShelvingRest, vSaleRest, vSaleDated, '2'); + */ + SET vItemShelvingRest = vItemShelvingRest - vSaleRest; + + UPDATE tmp.result + SET reserve = reserve + vSaleRest, + picked = LEAST(picked, vSaleDated) + WHERE itemShelvingFk = vItemShelvingFk; + + FETCH rsSale INTO vSaleRest, vSaleDated; + + END IF; + + END LOOP; + + CLOSE rsItemShelving; + CLOSE rsSale; + /* + INSERT INTO tmp.log(vItemFk, vItemShelvingRest, vSaleRest, vSalePicked,ifSide) + VALUES (vItemFk, vItemShelvingRest, vSaleRest, vSaleDated, '4'); + */ + SET vDone = FALSE; + + FETCH rsItem INTO vItemFk; + + END WHILE; + + CLOSE rsItem; + + SELECT * FROM tmp.result + ORDER BY created, visible; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `shelvingPark` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `shelvingPark`(IN `vShelvingFk` VARCHAR(8), IN `vParkingCode` VARCHAR(8)) +BEGIN + + DECLARE vParkingFk INT DEFAULT 0; + DECLARE idParking INT; + DECLARE vColumn VARCHAR(3); + DECLARE vRow VARCHAR(2); + DECLARE vReturn VARCHAR(50); + + /*ELIMINAR ESPACIOS*/ + SET vParkingCode = replace(vParkingCode,' ','') ; + + /*SINO EXISTE EL PARKING LO CREAMOS*/ + SELECT id INTO idParking + FROM vn.parking + WHERE code = vParkingCode COLLATE utf8_unicode_ci; + + IF idParking IS NULL THEN + IF LOCATE('-',vParkingCode) = 4 THEN + SELECT SUBSTRING_INDEX(vParkingCode,'-',1) INTO vColumn; + SELECT SUBSTRING_INDEX(vParkingCode,'-',-1) INTO vRow; + INSERT INTO vn.parking(`column`,`row`,code,sectorFk) + VALUES(vColumn,vRow,vParkingCode,1); + END IF; + END IF; + /*FIN INSERTAR PARKING*/ + + + SELECT id INTO vParkingFk + FROM vn.parking + WHERE `code` = vParkingCode COLLATE utf8_unicode_ci; + + IF length(vShelvingFk) > 6 THEN + + REPLACE vn.ticketParking(ticketFk,parkingFk) + VALUES (vShelvingFk, vParkingFk); + -- deprecated: eliminar despues de campaña PAK 2019-10-08 + REPLACE vn.shelving(code, parkingFk, isPrinted, parked) + VALUES(vShelvingFk, vParkingFk, TRUE, NOW()); + -- fin deprecated + CALL vn.ticketStatePrevious(vShelvingFk); + + ELSE + + + UPDATE vn.shelving + SET parkingFk = vParkingFk, parked = NOW() + WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; + + SELECT (COUNT(*) > 0) AS IsUpdated + FROM vn.shelving + WHERE parkingFk = vParkingFk + AND `code` = vShelvingFk COLLATE utf8_unicode_ci; + + END IF; + + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `shelvingPark_Beta__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `shelvingPark_Beta__`(IN `vShelvingFk` VARCHAR(8), IN `vParkingCode` VARCHAR(8)) +BEGIN + + DECLARE vParkingFk INT DEFAULT 0; + DECLARE idParking INT; + DECLARE vColumn VARCHAR(3); + DECLARE vRow VARCHAR(2); + DECLARE vReturn VARCHAR(50); + + /*ELIMINAR ESPACIOS*/ + SET vParkingCode = replace(vParkingCode,' ','') ; + + /*SINO EXISTE EL PARKING LO CREAMOS*/ + SELECT id INTO idParking + FROM vn.parking + WHERE code = vParkingCode COLLATE utf8_unicode_ci; + + IF idParking IS NULL THEN + IF LOCATE('-',vParkingCode) = 4 THEN + SELECT SUBSTRING_INDEX(vParkingCode,'-',1) INTO vColumn; + SELECT SUBSTRING_INDEX(vParkingCode,'-',-1) INTO vRow; + INSERT INTO vn.parking(`column`,`row`,code,sectorFk) + VALUES(vColumn,vRow,vParkingCode,2); + END IF; + END IF; + /*FIN INSERTAR PARKING*/ + + + SELECT id INTO vParkingFk + FROM vn.parking + WHERE `code` = vParkingCode COLLATE utf8_unicode_ci; + + IF length(vShelvingFk) > 6 THEN + + REPLACE vn.ticketParking(ticketFk,parkingFk) + VALUES (vShelvingFk, vParkingFk); + + REPLACE vn.shelving(code, parkingFk, isPrinted, parked) + VALUES(vShelvingFk, vParkingFk, TRUE, NOW()); + + CALL vn.ticketStatePrevious(vShelvingFk); + + ELSE + + + UPDATE vn.shelving + SET parkingFk = vParkingFk, parked = NOW() + WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; + + SELECT (COUNT(*) > 0) AS IsUpdated + FROM vn.shelving + WHERE parkingFk = vParkingFk + AND `code` = vShelvingFk COLLATE utf8_unicode_ci; + + END IF; + + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `shelving_clean` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `shelving_clean`() +BEGIN + + DELETE FROM vn.shelving + WHERE length(code) > 3 + AND parked < TIMESTAMPADD(WEEK,-1,CURDATE()); + + UPDATE vn.shelving sh + LEFT JOIN vn.itemShelving its ON its.shelvingFk = sh.`code` + SET isPrinted = 0 + WHERE isPrinted = 1 + AND its.id IS NULL + AND ( sh.parked IS NULL + OR + sh.parked < TIMESTAMPADD(MONTH,-1,CURDATE()) + ); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sinComponentes` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `sinComponentes`() +BEGIN + DECLARE v_done BOOL DEFAULT FALSE; + DECLARE vSaleFk INTEGER; + DECLARE vCur CURSOR FOR +SELECT s.id + FROM vn.ticket t + JOIN vn.client clt ON clt.id = t.clientFk + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType tp ON tp.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = tp.categoryFk + LEFT JOIN tmp.coste c ON c.id = s.id + WHERE t.shipped >= '2019-10-01' AND t.shipped <= '2019-10-30' + AND c.id IS NULL + AND clt.isActive != 0 + AND ic.merchandise != 0 + GROUP BY s.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET v_done = TRUE; + +DROP TEMPORARY TABLE IF EXISTS tmp.coste; + +DROP TEMPORARY TABLE IF EXISTS tmp.coste; +CREATE TEMPORARY TABLE tmp.coste + (primary key (id)) ENGINE = MEMORY + SELECT s.id + FROM vn.ticket t + JOIN vn.client clt ON clt.id = t.clientFk + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType tp ON tp.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = tp.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 AND ct.id = 1 + WHERE t.shipped >= '2019-10-01' + AND ic.merchandise != 0; + + + OPEN vCur; + + l: LOOP + SET v_done = FALSE; + FETCH vCur INTO vSaleFk; + + IF v_done THEN + LEAVE l; + END IF; + + CALL vn.ticketCalculateSaleForcePrice2(vSaleFk); + END LOOP; + + CLOSE vCur; + END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `solunionRiskRequest` */; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `solunionRiskRequest`() +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.client_list; + CREATE TEMPORARY TABLE tmp.client_list + (PRIMARY KEY (Id_Cliente)) + ENGINE = MEMORY + SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc + JOIN vn.creditInsurance ci ON cc.id = ci.creditClassification + WHERE dateEnd IS NULL + ORDER BY ci.creationDate DESC) t1 GROUP BY Id_Cliente; + + CALL vn2008.risk_vs_client_list(CURDATE()); + + SELECT + c.Id_Cliente, c.Cliente, c.Credito credito_vn, c.creditInsurance solunion, cast(r.risk as DECIMAL(10,0)) riesgo_vivo, + cast(c.creditInsurance - r.risk as decimal(10,0)) margen_vivo, + f.Consumo consumo_anual, c.Vencimiento, ci.grade + FROM + vn2008.Clientes c + JOIN tmp.risk r ON r.Id_Cliente = c.Id_Cliente + JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente + JOIN bi.facturacion_media_anual f ON c.Id_Cliente = f.Id_Cliente + GROUP BY Id_cliente; + + DROP TEMPORARY TABLE IF EXISTS tmp.risk; + DROP TEMPORARY TABLE IF EXISTS tmp.client_list; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `stockBuyed` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `stockBuyed`(vDate DATE) +BEGIN + DECLARE vVolume DECIMAL(10,2); + DECLARE vWarehouse INT DEFAULT 7; + + CALL stockTraslation(vDate); + + SELECT Volumen INTO vVolume FROM vn2008.Cubos WHERE Id_Cubo = 'cc' LIMIT 1; + + INSERT INTO stockBuyed(user, buyed, `date`) + SELECT tr.user_id, SUM(0.6 * ( amount / c.packing ) * vn.buy_getVolume(Id_Compra))/vVolume buyed, vDate + FROM tmp_item i + JOIN vn2008.Articles a ON a.Id_Article = i.item_id + JOIN vn2008.Tipos t ON a.tipo_id = t.tipo_id + JOIN vn2008.reinos r ON r.id = t.reino_id + JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = t.Id_Trabajador + JOIN vn2008.t_item_last_buy ilb ON ilb.item_id = Id_Article AND ilb.warehouse_id = vWarehouse + JOIN vn2008.Compres c ON c.Id_compra = ilb.buy_id + WHERE r.display <> 0 + GROUP BY tr.Id_Trabajador + ON DUPLICATE KEY UPDATE buyed = VALUES(buyed); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `stockBuyedByWorker` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `stockBuyedByWorker`(vDate DATE, vWorker INT) +BEGIN + + DECLARE vVolume DECIMAL(10,2); + DECLARE vWarehouse INT DEFAULT 7; + CALL stockTraslation(vDate); + + SELECT Volumen INTO vVolume FROM vn2008.Cubos WHERE Id_Cubo = 'cc' LIMIT 1; + + SELECT c.Id_Entrada, a.Id_Article, a.Article, i.amount Cantidad, (0.6 * ( i.amount / c.packing ) * vn.buy_getVolume(Id_Compra))/vVolume buyed + FROM tmp_item i + JOIN vn2008.Articles a ON a.Id_Article = i.item_id + JOIN vn2008.Tipos t ON a.tipo_id = t.tipo_id + JOIN vn2008.reinos r ON r.id = t.reino_id + JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = t.Id_Trabajador + JOIN vn2008.t_item_last_buy ilb ON ilb.item_id = a.Id_Article AND ilb.warehouse_id = vWarehouse + JOIN vn2008.Compres c ON c.Id_compra = ilb.buy_id + WHERE r.display <> 0 AND tr.user_id = vWorker; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `stockBuyedByWorkerTest` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `stockBuyedByWorkerTest`(vDate DATE, vWorker INT) +BEGIN + + DECLARE vVolume DECIMAL(10,2); + DECLARE vWarehouse INT DEFAULT 7; + CALL stockTraslationTest(vDate); + + SELECT Volumen INTO vVolume FROM vn2008.Cubos WHERE Id_Cubo = 'cc' LIMIT 1; + + SELECT c.Id_Entrada, a.Id_Article, a.Article, i.amount Cantidad, (0.6 * ( i.amount / c.packing ) * vn.buy_getVolume(Id_Compra))/vVolume buyed + FROM tmp.item i + JOIN vn2008.Articles a ON a.Id_Article = i.item_id + JOIN vn2008.Tipos t ON a.tipo_id = t.tipo_id + JOIN vn2008.reinos r ON r.id = t.reino_id + JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = t.Id_Trabajador + JOIN vn2008.t_item_last_buy ilb ON ilb.item_id = a.Id_Article AND ilb.warehouse_id = vWarehouse + JOIN vn2008.Compres c ON c.Id_compra = ilb.buy_id + WHERE r.display <> 0 AND tr.user_id = vWorker; + DROP TEMPORARY TABLE IF EXISTS tmp_item; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `stockTraslation` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `stockTraslation`(vDate DATE) +BEGIN + /** + * Calcula el stock del vWarehouse desde FechaInventario hasta v_date + sin tener en cuenta las salidas del mismo dia vDate + para ver el transporte a reservar + **/ + + DECLARE vWarehouse INT DEFAULT 7; + + DELETE FROM stockBuyed WHERE `date` = vDate; + + DROP TEMPORARY TABLE IF EXISTS tmp_item; + CREATE TEMPORARY TABLE tmp_item + (UNIQUE INDEX i USING HASH (item_id)) + ENGINE = MEMORY + SELECT item_id, SUM(amount) amount FROM vn2008.item_entry_in + WHERE dat = vDate and vDate >= CURDATE() + AND warehouse_id = vWarehouse + AND isVirtualStock is FALSE + GROUP BY item_id HAVING amount != 0; + + CALL `cache`.stock_refresh (FALSE); + + INSERT INTO tmp_item (item_id,amount) + SELECT item_id,s.amount FROM `cache`.stock s + WHERE warehouse_id = vWarehouse + ON DUPLICATE KEY UPDATE + amount = tmp_item.amount + VALUES(amount); + + CALL vn2008.item_last_buy_(vWarehouse,vDate); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `stockTraslationTest` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `stockTraslationTest`(vDate DATE) +BEGIN + /** + * Calcula el stock del vWarehouse desde FechaInventario hasta v_date + sin tener en cuenta las salidas del mismo dia vDate + para ver el transporte a reservar + **/ + + DECLARE vWarehouse INT DEFAULT 7; + + DELETE FROM stockBuyed WHERE `date` = vDate; + DROP TEMPORARY TABLE IF EXISTS tmp.item; + + CREATE TEMPORARY TABLE tmp.item ( + `item_id` INT, + `amount` DECIMAL(10, 2) DEFAULT 0.00, + PRIMARY KEY(item_id) + ) ENGINE = MEMORY; + + + IF vDate >= CURDATE() THEN + INSERT INTO tmp.item + SELECT item_id, SUM(amount) amount + FROM vn2008.item_entry_in + WHERE dat = vDate + AND warehouse_id = vWarehouse + GROUP BY item_id HAVING amount != 0; + END IF; + + CALL `cache`.stock_refresh (FALSE); + + INSERT INTO tmp.item (item_id,amount) + SELECT item_id,s.amount FROM `cache`.stock s + WHERE warehouse_id = vWarehouse + ON DUPLICATE KEY UPDATE + amount = tmp.item.amount + VALUES(amount); + + CALL vn2008.item_last_buy_(vWarehouse,vDate); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `stowawayBoarding` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `stowawayBoarding`(IN vShipFk INT, IN vStowawayFk INT) +BEGIN + + REPLACE stowaway(shipFk, id) + VALUES (vShipFk, vStowawayFk); + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT id, vShipFk, getWorker() + FROM state + WHERE code = 'BOARDING'; + + -- FIXME No crear ticket 98 + INSERT INTO sale(ticketFk, itemFk, quantity, concept) + VALUES(vShipFk, 98,1, CONCAT('POLIZÓN! ',vStowawayFk)); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `stowawayUnBoarding` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `stowawayUnBoarding`(vShipFk INT, vStowawayFk INT) +BEGIN + + DECLARE vWorker VARCHAR(255); + + DELETE FROM stowaway + WHERE shipFk = vShipFk AND id = vStowawayFk; + + DELETE tt FROM ticketTracking tt + JOIN state s ON s.id = tt.stateFk + WHERE code = 'BOARDING' AND ticketFk = vShipFk; + + DELETE FROM sale + WHERE ticketFk = vShipFk AND itemFk = 98 AND concept = CONCAT('POLIZÓN! ',vStowawayFk); + + SELECT u.`name` INTO vWorker + FROM account.user u JOIN vn.worker w ON w.userFk = u.id + WHERE w.id = vn2008.Averiguar_ComercialCliente_IdTicket_Id(vStowawayFk); + + SELECT messageSend(vWorker,CONCAT('El ticket: ', vStowawayFk, ' ha dejado de ser un polizón')) INTO @a; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `subordinateGetList` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `subordinateGetList`(vBossFk INT) +BEGIN + DECLARE vBossId INT; + DECLARE vDone BOOL; + DECLARE workerCur CURSOR FOR + SELECT workerFk + FROM tmp.subordinate + WHERE NOT isChecked; + + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR 1062 BEGIN + CALL util.throw('INFINITE_LOOP'); + END; + + DROP TEMPORARY TABLE IF EXISTS tmp.subordinate; + + CREATE TEMPORARY TABLE tmp.subordinate + (PRIMARY KEY (workerFk)) + ENGINE = MEMORY + SELECT vBossFk AS workerFk, 0 AS isChecked; + + WHILE (SELECT COUNT(*) FROM tmp.subordinate WHERE NOT isChecked) > 0 DO + OPEN workerCur; + workerLoop: LOOP + SET vDone = FALSE; + + FETCH workerCur INTO vBossId; + + IF vDone THEN + LEAVE workerLoop; + END IF; + + INSERT INTO tmp.subordinate + SELECT id, 0 + FROM worker + WHERE bossFk = vBossId; + + UPDATE tmp.subordinate + SET isChecked = 1 + WHERE workerFk = vBossId; + END LOOP; + + CLOSE workerCur; + END WHILE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `supplierExpenses` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `supplierExpenses`(vEnded DATE) +BEGIN + + DROP TEMPORARY TABLE IF EXISTS openingBalance; + + CREATE TEMPORARY TABLE openingBalance( + dueDated DATE + , supplierFk INT NOT NULL + , companyFk INT NOT NULL + , eurAmount DOUBLE NOT NULL + , foreignAmount DOUBLE NOT NULL + , PRIMARY KEY(supplierFk, companyFk)) + ENGINE = MEMORY; + + -- Calcula el balance inicial y final de cada proveedor + INSERT INTO openingBalance + SELECT MAX(dueDated), + supplierFk, + companyFk, + sum(amount) eurAmount, + sum(divisa) foreignAmount + FROM ( + SELECT p.dueDated, + p.supplierFk, + p.companyFk, + p.amount, + p.divisa + FROM payment p + JOIN currency c ON c.id = p.currencyFk + JOIN company co ON co.id = p.companyFk + WHERE p.dueDated > '2014-12-31' + AND p.dueDated <= vEnded + AND co.`code` = 'VNL' + AND c.`code` <> 'EUR' + UNION ALL + + SELECT iidd.dueDated, + ii.supplierFk, + ii.companyFk, + - iidd.amount, + - iidd.foreignValue + FROM invoiceIn ii + JOIN invoiceInDueDay iidd ON ii.id = iidd.invoiceInFk + JOIN currency c ON c.id = ii.currencyFk + JOIN company co ON co.id = ii.companyFk + WHERE iidd.dueDated > '2014-12-31' + AND iidd.dueDated <= vEnded + AND ii.isBooked AND co.`code` = 'VNL' + AND c.`code` <> 'EUR' + UNION ALL + + SELECT se.dueDated, + se.supplierFk, + se.companyFk, + - se.amount, + 0 + FROM supplierExpense se + JOIN currency c ON c.id = se.currencyFk + JOIN company co ON co.id = se.companyFk + WHERE se.dueDated > '2014-12-31' + AND se.dueDated <= vEnded + AND co.`code` = 'VNL' AND c.`code` <> 'EUR' + ) sub + GROUP BY companyFk, supplierFk; + + SELECT ob.dueDated + , ob.supplierFk + , ob.companyFk + , ob.eurAmount + , s.`name` + FROM openingBalance ob + LEFT JOIN supplier s ON s.id = ob.supplierFk + WHERE ob.eurAmount <> 0 AND ob.foreignAmount = 0; + + DROP TEMPORARY TABLE openingBalance; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `supplierPackaging_ReportSource` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `supplierPackaging_ReportSource`(vFromDated DATE, vSupplierFk INT) +BEGIN + + SELECT * FROM + ( + SELECT supplierFk, itemFk, longName, supplier, entryFk, landed, `out`, `in`, almacen + FROM supplierPackaging + WHERE supplierFk = vSupplierFk + AND landed >= vFromDated + + UNION ALL + + SELECT vSupplierFk, itemFk, longName, supplier, 'anterior', vFromDated, sum(`out`), sum(`in`), NULL + FROM supplierPackaging + WHERE supplierFk = vSupplierFk + AND landed < vFromDated + GROUP BY itemFk + ) sub + ORDER BY itemFk, landed; + + + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketBoxesView` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketBoxesView`(IN vTicketFk INT) +BEGIN + + SELECT s.id, + s.itemFk, + s.concept, + floor(s.quantity / b.packing) as Cajas, + b.packing, + s.isPicked, + i.size + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN cache.last_buy lb on lb.warehouse_id = t.warehouseFk AND lb.item_id = s.itemFk + JOIN buy b on b.id = lb.buy_id + JOIN packaging p on p.id = b.packageFk + WHERE s.quantity >= b.packing + AND t.id = vTicketFk + AND p.isBox + GROUP BY s.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 DROP PROCEDURE IF EXISTS `ticketBuiltTime` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketBuiltTime`(vDate DATE) +BEGIN + + DECLARE vDateStart DATETIME DEFAULT DATE(vDate); + DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketBuiltTime; + + CREATE TEMPORARY TABLE tmp.ticketBuiltTime + ENGINE = MEMORY + SELECT t.id as ticketFk ,t.shipped, IFNULL(builtTime, vDateEnd) as builtTime + FROM + vn.ticket t + LEFT JOIN + ( + SELECT ticketFk, builtTime + FROM + ( + SELECT + Id_Ticket as ticketFk, + odbc_date as builtTime + FROM + vncontrol.inter + WHERE odbc_date BETWEEN vDateStart AND vDateEnd + ORDER BY Id_Ticket, odbc_date DESC + ) sub + GROUP BY ticketFk + ) sub2 ON sub2.ticketFk = t.id + WHERE t.shipped BETWEEN vDate AND util.dayEnd(vDate) + AND t.clientFk NOT IN (50,400,200) + AND t.companyFk = 442 + + ; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketCalculate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculate`( + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT) +proc: BEGIN +-- OBSOLETO utilizar catalog_calculate + CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketCalculateClon` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT) +BEGIN + /* + * @vTicketNew id del nuevo ticket clonado + * @vTicketOld id ticket original, a partir del qual se clonara el nuevo + * Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo + */ + DECLARE vShipped DATE; + DECLARE vClient INT; + DECLARE vWarehouse SMALLINT; + DECLARE vAgencyMode INT; + DECLARE vAddress INT; + DECLARE vLanded DATE; + DECLARE vAgency INT; + + REPLACE INTO orderTicket(orderFk,ticketFk) + SELECT orderFk, vTicketNew + FROM orderTicket + WHERE ticketFk = vTicketOld; + + SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk + INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency + FROM vn.agencyMode a + JOIN vn.ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicketNew; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; + CALL zoneGetShippedWarehouse(vLanded, vAddress, vAgencyMode); + DELETE FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouse; + + CALL buyUltimate(vWarehouse, vShipped); -- rellena la tabla tmp.buyUltimate con la ultima compra + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; + + CALL ticketComponentCalculate(vAddress,vAgencyMode); + + -- Bionizamos lineas con Preu = 0 + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT s.id saleFk, vWarehouse warehouseFk + FROM sale s + JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew AND s.price = 0; + + CALL ticketComponentUpdateSale(1); + + -- Bionizamos lineas con Preu > 0 + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT s.id saleFk, vWarehouse warehouseFk + FROM sale s + JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew + AND s.price > 0; + + CALL ticketComponentUpdateSale(6); + + IF vLanded IS NULL THEN + CALL zoneGetLanded(vShipped, vAddress, vAgency,vWarehouse); + UPDATE ticket t + JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk + SET t.landed = zgl.landed + WHERE t.id = vTicketNew; + END IF; + + -- Log + CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket'); + + -- Limpieza + DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate; + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketCalculateFromType` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateFromType`( vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT, + vTypeFk INT) +BEGIN + DROP TEMPORARY TABLE IF EXISTS tmp.item; + CREATE TEMPORARY TABLE tmp.item + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT id itemFk FROM vn.item + WHERE typeFk = vTypeFk; + + CALL ticketCalculate(vLanded, vAddressFk, vAgencyModeFk); + DROP TEMPORARY TABLE tmp.item; + DROP TEMPORARY TABLE tmp.ticketLot; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketCalculatePurge` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculatePurge`() +BEGIN + DROP TEMPORARY TABLE + tmp.ticketCalculateItem, + tmp.ticketComponentPrice, + tmp.ticketComponent, + tmp.ticketLot, + tmp.zoneGetShipped; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketCalculateSale` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSale`(IN vSale BIGINT) +proc: BEGIN +-- OBSOLETO USAR: sale_calculateComponent(vSale, NULL) + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vTicket BIGINT; + DECLARE vItem BIGINT; + DECLARE vLanded DATE; + DECLARE vTicketFree BOOLEAN DEFAULT TRUE; + DECLARE vZoneFk INTEGER; + + SELECT NOT (t.refFk IS NOT NULL OR ts.alertLevel > 0) OR s.price = 0, s.ticketFk, s.itemFk , t.zoneFk + INTO vTicketFree, vTicket, vItem, vZoneFk + FROM vn.ticket t + JOIN vn.sale s ON s.ticketFk = t.id + LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id + WHERE s.id = vSale + LIMIT 1; + + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.agencyModeFk, t.landed + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded + FROM agencyMode a + JOIN ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicket; + + IF IFNULL(vZoneFk,0) = 0 THEN + CALL util.throw('ticket dont have zone'); + END IF; + + CALL buyUltimate (vWarehouseFk, vShipped); + + DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk + FROM tmp.buyUltimate + WHERE itemFk = vItem; + + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT vSale saleFk,vWarehouseFk warehouseFk; + + CALL ticketComponentUpdateSale(IF(vTicketFree,1,6)); + + INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) + VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); + + 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 DROP PROCEDURE IF EXISTS `ticketCalculateSaleForcePrice` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSaleForcePrice`(IN vSale BIGINT) +proc: BEGIN + + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAddressFk INT; + DECLARE vTicket BIGINT; + DECLARE vItem BIGINT; + DECLARE vLanded DATE; + DECLARE vZoneFk INT; + DECLARE vHasZone BOOLEAN DEFAULT FALSE; + + + SELECT ticketFk, itemFk + INTO vTicket, vItem + FROM sale + WHERE id = vSale; + + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.landed, t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vLanded, vZoneFk + FROM agencyMode a + JOIN ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicket; + + IF vZoneFk IS NULL THEN + CALL util.throw('ticket without zone'); + END IF; + + CALL buyUltimate (vWarehouseFk, vShipped); + + DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk + FROM tmp.buyUltimate + WHERE itemFk = vItem; + + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT vSale saleFk,vWarehouseFk warehouseFk; + + CALL ticketComponentUpdateSale(1); + + INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) + VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); + + 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 DROP PROCEDURE IF EXISTS `ticketCalculateSaleForcePrice2` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSaleForcePrice2`(IN vSale BIGINT) +proc: BEGIN + + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAddressFk INT; + DECLARE vTicket BIGINT; + DECLARE vItem BIGINT; + DECLARE vLanded DATE; + DECLARE vZoneFk INT; + DECLARE vHasZone BOOLEAN DEFAULT FALSE; + + + SELECT ticketFk, itemFk + INTO vTicket, vItem + FROM sale + WHERE id = vSale; + + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.landed, t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vLanded, vZoneFk + FROM agencyMode a + JOIN ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicket; + + IF vZoneFk IS NULL THEN + CALL util.throw('ticket without zone'); + END IF; + + CALL buyUltimate (vWarehouseFk, vShipped); + + DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk + FROM tmp.buyUltimate + WHERE itemFk = vItem; + + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT vSale saleFk,vWarehouseFk warehouseFk; + + CALL ticketComponentUpdateSale(1); + + INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) + VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); + + 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 DROP PROCEDURE IF EXISTS `ticketCalculateSale__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateSale__`(IN vSale BIGINT) +proc: BEGIN + + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vTicket BIGINT; + DECLARE vItem BIGINT; + DECLARE vLanded DATE; + DECLARE vTicketFree BOOLEAN DEFAULT TRUE; + DECLARE vZoneFk INTEGER; + + SELECT FALSE + INTO vTicketFree + FROM vn.ticket t + JOIN vn.sale s ON s.ticketFk = t.id + LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id + WHERE s.id = vSale + AND (t.refFk != "" OR (ts.alertLevel > 0 AND s.price != 0)) + LIMIT 1; + + SELECT ticketFk, itemFk + INTO vTicket, vItem + FROM sale + WHERE id = vSale; + + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.agencyModeFk, t.landed + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded + FROM agencyMode a + JOIN ticket t ON t.agencyModeFk = a.id + WHERE t.id = vTicket; + + CALL zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + + SELECT id INTO vZoneFk + FROM tmp.zoneGetShipped + WHERE warehouseFk = vWarehouseFk + AND shipped = vShipped; + + IF IFNULL(vZoneFk,0) = 0 THEN + CALL util.throw('not zone with this parameters'); + END IF; + + CALL buyUltimate (vWarehouseFk, vShipped); + + DELETE FROM tmp.buyUltimate WHERE itemFk != vItem; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, vItem itemFk, buyFk + FROM tmp.buyUltimate + WHERE itemFk = vItem; + + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT vSale saleFk,vWarehouseFk warehouseFk; + + CALL ticketComponentUpdateSale(IF(vTicketFree,1,6)); + + INSERT INTO vn.ticketLog (originFk, userFk, `action`, description) + VALUES (vTicket, account.userGetId(), 'update', CONCAT('Bionizo linea id ', vSale)); + + 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 DROP PROCEDURE IF EXISTS `ticketClosure` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosure`() +BEGIN +/** + * Realiza el cierre de todos los + * tickets de la table ticketClosure. + */ + DECLARE vDone BOOL; + DECLARE vClientFk INT; + DECLARE vTicketFk INT; + DECLARE vIsTaxDataChecked BOOL; + DECLARE vCompanyFk INT; + DECLARE vShipped DATE; + DECLARE vPriority INT DEFAULT 1; + DECLARE vReportDeliveryNote INT DEFAULT 1; + DECLARE vNewInvoiceId INT; + DECLARE vHasDailyInvoice BOOL; + DECLARE vWithPackage BOOL; + + DECLARE cur CURSOR FOR + SELECT ticketFk FROM tmp.ticketClosure; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + RESIGNAL; + END; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2; + CREATE TEMPORARY TABLE tmp.ticketClosure2 + SELECT ticketFk FROM tmp.ticketClosure; + INSERT INTO tmp.ticketClosure + SELECT id FROM stowaway s + JOIN tmp.ticketClosure2 tc ON s.shipFk = tc.ticketFk; + OPEN cur; + + proc: LOOP + SET vDone = FALSE; + + FETCH cur INTO vTicketFk; + + IF vDone THEN + LEAVE proc; + END IF; + + -- ticketClosure start + SELECT + c.id, + c.isTaxDataChecked, + t.companyFk, + t.shipped, + co.hasDailyInvoice, + w.isManaged + INTO vClientFk, + vIsTaxDataChecked, + vCompanyFk, + vShipped, + vHasDailyInvoice, + vWithPackage + FROM ticket t + JOIN `client` c ON c.id = t.clientFk + JOIN province p ON p.id = c.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.id = vTicketFk; + + INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) + (SELECT vTicketFk, p.id, COUNT(*) + FROM expedition e + JOIN packaging p ON p.itemFk = e.itemFk + WHERE e.ticketFk = vTicketFk AND p.isPackageReturnable + AND vWithPackage + GROUP BY p.itemFk); + + -- No retornables o no catalogados + INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) + (SELECT e.itemFk, vTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.itemFk, vClientFk), 1 + FROM expedition e + JOIN item i ON i.id = e.itemFk + LEFT JOIN packaging p ON p.itemFk = i.id + WHERE e.ticketFk = vTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 + AND getSpecialPrice(e.itemFk, vClientFk) > 0 + GROUP BY e.itemFk); + + IF(vHasDailyInvoice) THEN + + -- Facturacion rapida + CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', NULL); + -- Facturar si está contabilizado + IF vIsTaxDataChecked THEN + + -- JGF cau 12220 + -- IF (SELECT clientTaxArea(vClientFk, vCompanyFk)) = 'NATIONAL' THEN + CALL invoiceOut_newFromClient( + vClientFk, + (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), + vShipped, + vCompanyFk, + NULL, + vNewInvoiceId); + /*ELSE + CALL invoiceOut_newFromTicket(vTicketFk, (SELECT invoiceSerial(vClientFk, vCompanyFk, 'R')), NULL, vNewInvoiceId); + END IF;*/ + + END IF; + ELSE + -- Albaran_print + CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL); + INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); + END IF; + + -- ticketClosure end + END LOOP; + + CLOSE cur; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureAgencyList` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureAgencyList`(vWarehouseFk INT, vDateTo DATE) +BEGIN +/** + * Inserta los tickets de todos los almacenes en la tabla temporal + * para ser cerrados. + * + * @param vWarehouseFk Id del almacén + * @param vDate Fecha del cierre + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; + + CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY ( + SELECT + t.id AS ticketFk + FROM expedition e + INNER JOIN ticket t ON t.id = e.ticketFk + INNER JOIN tmp.ticketClosureAgencyList al ON al.agencyModeFk = t.agencyModeFk + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + WHERE + ts.alertLevel = 2 + AND t.warehouseFk = vWarehouseFk + AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo + AND t.refFk IS NULL + GROUP BY e.ticketFk); + + DROP TEMPORARY TABLE tmp.ticketClosureAgencyList; + + CALL ticketClosure(); + + DROP TEMPORARY TABLE tmp.ticketClosure; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureAgencyListAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureAgencyListAdd`(vAgencyModeFk INT) +BEGIN +/** + * Prepara un listado de agencias sobre los que se realizará el cierre. + * Es necesario llamar al procedimiento por cada agencia. + * + * @param vAgencyModeFk Id almacén + */ + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.ticketClosureAgencyList ( + `agencyModeFk` INT, + PRIMARY KEY(agencyModeFk)) ENGINE = MEMORY; + + INSERT INTO tmp.ticketClosureAgencyList(agencyModeFk) VALUES(vAgencyModeFk); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureMultiWarehouse` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureMultiWarehouse`(vDateTo DATE) +BEGIN +/** + * Inserta los tickets de todos los almacenes en la tabla temporal + * para ser cerrados. + * + * @param vDate Fecha del cierre + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; + + CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY ( + SELECT + t.id AS ticketFk + FROM expedition e + INNER JOIN ticket t ON t.id = e.ticketFk + INNER JOIN warehouse w ON w.id = t.warehouseFk AND hasComission + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + WHERE + ts.alertLevel = 2 + AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo + AND t.refFk IS NULL + GROUP BY e.ticketFk); + + CALL ticketClosure(); + + DROP TEMPORARY TABLE tmp.ticketClosure; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureRoute` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureRoute`( vRouteFk INT) +BEGIN +/** + * Inserta los tickets de la ruta en la tabla temporal + * para ser cerrados. + * + * @param vWarehouseFk Almacén a cerrar + * @param vRouteFk Ruta a cerrar + * @param vDate Fecha del cierre + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; + + CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY ( + SELECT + t.id AS ticketFk + FROM expedition e + INNER JOIN ticket t ON t.id = e.ticketFk + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + WHERE + ts.alertLevel = 2 + AND t.routeFk = vRouteFk + AND t.refFk IS NULL + GROUP BY e.ticketFk); + + CALL ticketClosure(); + + DROP TEMPORARY TABLE tmp.ticketClosure; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureTicket` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureTicket`(vTicketFk INT) +BEGIN + +/** + * Inserta el ticket en la tabla temporal + * para ser cerrado. + * + * @param vTicketFk Id del ticket + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; + + CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY ( + SELECT + t.id AS ticketFk + FROM expedition e + INNER JOIN ticket t ON t.id = e.ticketFk + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + WHERE + ts.alertLevel = 2 + AND t.id = vTicketFk + AND t.refFk IS NULL + GROUP BY e.ticketFk); + + CALL ticketClosure(); + + DROP TEMPORARY TABLE tmp.ticketClosure; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureWarehouse` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureWarehouse`(vWarehouseFk INT, vDateTo DATE) +BEGIN +/** + * Inserta los tickets del almacen en la tabla temporal + * para ser cerrados. + * + * @param vWarehouseFk Almacén a cerrar + * @param vDate Fecha del cierre + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; + + CREATE TEMPORARY TABLE ticketClosure ENGINE = MEMORY( + SELECT + t.id AS ticketFk + FROM expedition e + INNER JOIN ticket t ON t.id = e.ticketFk + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + WHERE + ts.alertLevel = 2 + AND t.warehouseFk = vWarehouseFk + AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo + AND t.refFk IS NULL + GROUP BY e.ticketFk); + + CALL ticketClosure(); + + DROP TEMPORARY TABLE tmp.ticketClosure; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentCalculate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate`( + vAddressFk INT, + vAgencyModeFk INT) +proc: BEGIN +-- OBSOLETO usar catalog_componentCalculate +/** + * Calcula los componentes de un ticket + * + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id del modo de agencia + * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, + * packing, grouping, groupingMode, buyFk, typeFk) + * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) + */ + + DECLARE vClientFk INT; + DECLARE vGeneralInflationCoefficient INT DEFAULT 1; + DECLARE vMinimumDensityWeight INT DEFAULT 167; + DECLARE vBoxFreightItem INT DEFAULT 71; + DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; + DECLARE vSpecialPriceComponent INT DEFAULT 10; + DECLARE vDeliveryComponent INT DEFAULT 15; + DECLARE vRecoveryComponent INT DEFAULT 17; + DECLARE vSellByPacketComponent INT DEFAULT 22; + DECLARE vBuyValueComponent INT DEFAULT 28; + DECLARE vMarginComponent INT DEFAULT 29; + DECLARE vDiscountLastItemComponent INT DEFAULT 32; + DECLARE vExtraBaggedComponent INT DEFAULT 38; + DECLARE vManaAutoComponent INT DEFAULT 39; + + + + SELECT volume INTO vBoxVolume + FROM vn.packaging + WHERE id = '94'; + + SELECT clientFk INTO vClientFK + FROM address + WHERE id = vAddressFk; + + SET @rate2 := 0; + SET @rate3 := 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; + CREATE TEMPORARY TABLE tmp.ticketComponentCalculate + (PRIMARY KEY (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT + tl.itemFk, tl.warehouseFk, tl.available, + IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, + IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, + IFNULL(pf.rate3, 0) AS minPrice, + IFNULL(pf.packing, b.packing) packing, + IFNULL(pf.`grouping`, b.`grouping`) `grouping`, + ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, + tl.buyFk, + i.typeFk, + IF(i.hasKgPrice,b.weight / b.packing, NULL) weightGrouping + FROM tmp.ticketLot tl + JOIN buy b ON b.id = tl.buyFk + JOIN item i ON i.id = tl.itemFk + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk + LEFT JOIN ( + SELECT * FROM ( + SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, aho.warehouseFk + FROM priceFixed pf + JOIN tmp.zoneGetShipped aho ON pf.warehouseFk = aho.warehouseFk OR pf.warehouseFk = 0 + WHERE aho.shipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC + ) tpf + GROUP BY tpf.itemFk, tpf.warehouseFk + ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk + WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; + CREATE TEMPORARY TABLE tmp.ticketComponent ( + `warehouseFk` INT UNSIGNED NOT NULL, + `itemFk` INT NOT NULL, + `componentFk` INT UNSIGNED NOT NULL, + `cost` DECIMAL(10,4) NOT NULL, + INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), + UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)); + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vBuyValueComponent, + b.buyingValue + b.freightValue + b.packageValue + b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vMarginComponent, + tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; + CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY + SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk + FROM tmp.ticketComponent tc + GROUP BY tc.itemFk, warehouseFk; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3) + FROM tmp.ticketComponentBase tcb + JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk + WHERE cr.recobro > 0.009; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto + FROM tmp.ticketComponentBase tcb + JOIN `client` c on c.id = vClientFk + JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador + WHERE ms.prices_modifier_activated + HAVING manaAuto <> 0; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, + tcb.itemFk, + cr.id, + GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3) + FROM tmp.ticketComponentBase tcb + JOIN componentRate cr + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFK, + tcc.itemFk, + vDeliveryComponent, + vGeneralInflationCoefficient + * ROUND(( + i.compression + * r.cm3 + * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) + * IFNULL((z.price - z.bonus) + * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 + ) cost + FROM tmp.ticketComponentCalculate tcc + JOIN item i ON i.id = tcc.itemFk + JOIN agencyMode am ON am.id = vAgencyModeFk + JOIN `address` a ON a.id = vAddressFk + JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = tcc.warehouseFk + JOIN zone z ON z.id = zgs.id + LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk + AND r.Id_Article = tcc.itemFk + HAVING cost <> 0; + + IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost + FROM tmp.ticketComponentCalculate tcc + JOIN vn.addressForPackaging ap + WHERE ap.addressFk = vAddressFk; + END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; + CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY + SELECT * FROM tmp.ticketComponent; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, + tcc.itemFk, + vSpecialPriceComponent, + sp.value - SUM(tcc.cost) sumCost + FROM tmp.ticketComponentCopy tcc + JOIN componentRate cr ON cr.id = tcc.componentFk + JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk + WHERE cr.classRate IS NULL + GROUP BY tcc.itemFk, tcc.warehouseFk + HAVING ABS(sumCost) > 0.001; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; + CREATE TEMPORARY TABLE tmp.ticketComponentSum + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate + FROM tmp.ticketComponent tc + JOIN componentRate cr ON cr.id = tc.componentFk + GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; + CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY + SELECT tcc.warehouseFk, + tcc.itemFk, + 1 rate, + IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, + CAST(SUM(tcs.sumCost) / weightGrouping AS DECIMAL(10,2)) priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 1) = 1 + AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 2 rate, + tcc.packing `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 + AND tcc.packing > 0 AND tcc.available >= tcc.packing) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 3 rate, + tcc.available `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 3) = 3 + GROUP BY tcs.warehouseFk, tcs.itemFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; + CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY + SELECT * FROM ( + SELECT * FROM tmp.ticketComponentRate ORDER BY price + ) t + GROUP BY itemFk, warehouseFk, `grouping`; + + DROP TEMPORARY TABLE + tmp.ticketComponentCalculate, + tmp.ticketComponentSum, + tmp.ticketComponentBase, + tmp.ticketComponentRate, + tmp.ticketComponentCopy; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentMakeUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentMakeUpdate`( + vTicketFk INT, + vClientFk INT, + vAgencyModeFk INT, + vAddressFk INT, + vWarehouseFk TINYINT, + vCompanyFk SMALLINT, + vShipped DATETIME, + vLanded DATE, + vIsDeleted BOOLEAN, + vHasToBeUnrouted BOOLEAN, + vOption INT) +BEGIN + + + CALL vn.ticketComponentPreview (vTicketFk, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk); + CALL vn.ticketComponentUpdate ( + vTicketFk, + vClientFk, + vAgencyModeFk, + vAddressFk, + vWarehouseFk, + vCompanyFk, + vShipped, + vLanded, + vIsDeleted, + vHasToBeUnrouted, + vOption + ); + + DROP TEMPORARY TABLE + tmp.ticketComponent, + tmp.ticketComponentPrice; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPreview` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPreview`( + vTicketFk INT, + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT, + vWarehouseFk SMALLINT) +BEGIN +-- OBSOLETO usar ticket_componentPreview + DECLARE vShipped DATE; + DECLARE vBuyOrderItem INT DEFAULT 100; + + DECLARE vHasDataChanged BOOL DEFAULT FALSE; + DECLARE vHasAddressChanged BOOL; + DECLARE vHasAgencyModeChanged BOOL DEFAULT FALSE; + DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE; + + DECLARE vAddressTypeRateFk INT DEFAULT NULL; + DECLARE vAgencyModeTypeRateFk INT DEFAULT NULL; + + DECLARE vHasChangeAll BOOL DEFAULT FALSE; + + SELECT DATE(landed) <> vLanded, + addressFk <> vAddressFk, + agencyModeFk <> vAgencyModeFk, + warehouseFk <> vWarehouseFk + INTO + vHasDataChanged, + vHasAddressChanged, + vHasAgencyModeChanged, + vHasWarehouseChanged + FROM vn.ticket t + WHERE t.id = vTicketFk; + + IF vHasDataChanged OR vHasWarehouseChanged THEN + SET vHasChangeAll = TRUE; + END IF; + + IF vHasAddressChanged THEN + SET vAddressTypeRateFk = 5; + END IF; + + IF vHasAgencyModeChanged THEN + SET vAgencyModeTypeRateFk = 6; + END IF; + + CALL zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + + SELECT shipped INTO vShipped + FROM tmp.zoneGetShipped + WHERE warehouseFk = vWarehouseFk; + + CALL buyUltimate(vWarehouseFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( + SELECT + vWarehouseFk AS warehouseFk, + NULL AS available, + s.itemFk, + bu.buyFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + AND s.itemFk != vBuyOrderItem + GROUP BY bu.warehouseFk, bu.itemFk); + + CALL ticketComponentCalculate(vAddressFk, vAgencyModeFk); + + REPLACE INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT t.warehouseFk, s.itemFk, sc.componentFk, sc.value + FROM saleComponent sc + JOIN sale s ON s.id = sc.saleFk + JOIN ticket t ON t.id = s.ticketFk + JOIN componentRate cr ON cr.id = sc.componentFk + WHERE s.ticketFk = vTicketFk + AND (cr.isRenewable = FALSE + OR + (NOT vHasChangeAll + AND (NOT (cr.componentTypeRate <=> vAddressTypeRateFk + OR cr.componentTypeRate <=> vAgencyModeTypeRateFk)))); + + SET @shipped = vShipped; + + DROP TEMPORARY TABLE + tmp.zoneGetShipped, + tmp.buyUltimate, + tmp.ticketLot; + + IF IFNULL(vShipped, CURDATE() - 1) < CURDATE() THEN + CALL util.throw('NO_AGENCY_AVAILABLE'); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPriceDifference` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPriceDifference`( + vTicketFk INT, + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT, + vWarehouseFk INT) +BEGIN +/** + * Devuelve las diferencias de precio + * de los movimientos de un ticket. + * + * @param vTicketFk Id del ticket + * @param vLanded Fecha de recepcion + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id del modo de agencia + * @param vWarehouseFk Id del almacén + */ + CALL vn.ticketComponentPreview(vTicketFk, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk); + + SELECT s.itemFk, + i.name, + i.size, + i.category, + IFNULL(s.quantity, 0) AS quantity, + IFNULL(s.price, 0) AS price, + ROUND(SUM(tc.cost), 2) AS newPrice, + s.quantity * (s.price - ROUND(SUM(tc.cost), 2)) difference, + s.id AS saleFk + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN ticket t ON t.id = s.ticketFk + LEFT JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk + AND tc.warehouseFk = t.warehouseFk + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk = tc.componentFk + LEFT JOIN componentRate cr ON cr.id = tc.componentFk + WHERE + t.id = vTicketFk + AND IF(sc.componentFk IS NULL + AND cr.classRate IS NOT NULL, FALSE, TRUE) + GROUP BY s.id ORDER BY s.id; + + DROP TEMPORARY TABLE + tmp.ticketComponent, + tmp.ticketComponentPrice; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentUpdate`( + vTicketFk INT, + vClientFk INT, + vAgencyModeFk INT, + vAddressFk INT, + vWarehouseFk TINYINT, + vCompanyFk SMALLINT, + vShipped DATETIME, + vLanded DATE, + vIsDeleted BOOLEAN, + vHasToBeUnrouted BOOLEAN, + vOption INT) +BEGIN + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN + + UPDATE ticket t + JOIN address a ON a.id = vAddressFk + SET t.nickname = a.nickname + WHERE t.id = vTicketFk; + + END IF; + + UPDATE ticket t + SET + t.clientFk = vClientFk, + t.agencyModeFk = vAgencyModeFk, + t.addressFk = vAddressFk, + t.warehouseFk = vWarehouseFk, + t.companyFk = vCompanyFk, + t.landed = vLanded, + t.shipped = vShipped, + t.isDeleted = vIsDeleted + WHERE + t.id = vTicketFk; + + IF vHasToBeUnrouted THEN + UPDATE ticket t SET t.routeFk = NULL + WHERE t.id = vTicketFk; + END IF; + + IF vOption <> 8 THEN + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) + ENGINE = MEMORY + SELECT id AS saleFk, vWarehouseFk warehouseFk + FROM sale s WHERE s.ticketFk = vTicketFk; + + CALL ticketComponentUpdateSale (vOption); + + DROP TEMPORARY TABLE tmp.sale; + END IF; + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentUpdateSale` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentUpdateSale`(vOption INT) +BEGIN +/** + * A partir de la tabla tmp.sale, crea los Movimientos_componentes + * y modifica el campo Preu de la tabla Movimientos + * + * @param i_option integer tipo de actualizacion + * @param table tmp.sale tabla memory con el campo saleFk, warehouseFk + **/ + DECLARE vComponentFk INT; + DECLARE vRenewComponents BOOLEAN; + DECLARE vKeepPrices BOOLEAN; + + CASE vOption + WHEN 1 THEN + SET vRenewComponents = TRUE; + SET vKeepPrices = FALSE; + WHEN 2 THEN + SET vComponentFk = 17; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + WHEN 3 THEN + SET vComponentFk = 37; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + WHEN 4 THEN + SET vComponentFk = 34; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + WHEN 5 THEN + SET vComponentFk = 35; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + WHEN 6 THEN + SET vComponentFk = 36; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + WHEN 7 THEN + REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.8, 3) + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk NOT IN (28, 29) + GROUP BY s.id; + + REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, 29, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.2, 3) + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk NOT IN (28, 29) + GROUP BY s.id; + + SET vRenewComponents = FALSE; + SET vKeepPrices = FALSE; + WHEN 8 THEN + DELETE sc.* + FROM tmp.sale tmps JOIN saleComponent sc ON sc.saleFk = tmps.saleFk; + + REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100)), 3) + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id; + + SET vRenewComponents = FALSE; + SET vKeepPrices = FALSE; + WHEN 9 THEN + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + END CASE; + + IF vRenewComponents THEN + DELETE sc.* + FROM tmp.sale tmps + JOIN saleComponent sc ON sc.saleFk = tmps.saleFk + JOIN componentRate cr ON cr.id = sc.componentFk + WHERE cr.isRenewable; + + REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, tc.componentFk, tc.cost + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id + JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk = tc.componentFk + LEFT JOIN componentRate cr ON cr.id = tc.componentFk + WHERE IF(sc.componentFk IS NULL AND NOT cr.isRenewable, FALSE, TRUE); + END IF; + + IF vKeepPrices THEN + REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, vComponentFk, ROUND((s.price * (100 - s.discount) / 100) - SUM(sc.value), 3) dif + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + WHERE sc.saleFk <> vComponentFk + GROUP BY s.id + HAVING dif <> 0; + ELSE + UPDATE sale s + JOIN item i on i.id = s.itemFk + JOIN itemType it on it.id = i.typeFk + JOIN (SELECT SUM(sc.value) sumValue, sc.saleFk + FROM saleComponent sc + JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk + GROUP BY sc.saleFk) sc ON sc.saleFk = s.id + SET s.price = sumValue + WHERE it.code != 'PRT' ; + + REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, 21, ROUND((s.price * (100 - s.discount) / 100) - SUM(value), 3) saleValue + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + WHERE sc.componentFk != 21 + GROUP BY s.id + HAVING ROUND(saleValue, 4) <> 0; + END IF; + + UPDATE sale s + JOIN ( + SELECT SUM(sc.value) sumValue, sc.saleFk + FROM saleComponent sc + JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk + JOIN componentRate cr ON cr.id = sc.componentFk + JOIN componentTypeRate ctr on ctr.id = cr.componentTypeRate AND ctr.base + GROUP BY sc.saleFk) sc ON sc.saleFk = s.id + SET s.priceFixed = sumValue, s.isPriceFixed = 1; + + DELETE sc.* + FROM saleComponent sc + JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk + JOIN sale s on s.id = sc.saleFk + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE it.code = 'PRT'; + + INSERT INTO saleComponent(saleFk, componentFk, value) + SELECT s.id, 15, s.price + FROM sale s + JOIN tmp.sale tmps ON tmps.saleFk = s.id + JOIN item i ON i.id = s.itemFK + JOIN itemType it ON it.id = i.typeFk + WHERE it.code = 'PRT' AND s.price > 0; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketCreate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreate`( + vClientId INT + ,vShipped DATE + ,vWarehouseId INT + ,vCompanyFk INT + ,vAddressFk INT + ,vAgencyType INT + ,vRouteFk INT + ,vlanded DATE + ,OUT vNewTicket INT) +BEGIN + CALL `ticketCreateWithUser`(vClientId, vShipped, vWarehouseId, vCompanyFk, vAddressFk, vAgencyType, vRouteFk, vlanded, account.userGetId(), vNewTicket); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketCreateWithoutZone` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`( + vClientId INT + ,vShipped DATE + ,vWarehouseFk INT + ,vCompanyFk INT + ,vAddressFk INT + ,vAgencyModeFk INT + ,vRouteFk INT + ,vLanded DATE + ,vUserId INT + ,OUT vNewTicket INT) +BEGIN + + DECLARE vZoneFk INT; + + IF vClientId IS NULL THEN + CALL util.throw ('CLIENT_NOT_ESPECIFIED'); + END IF; + + IF NOT vAddressFk OR vAddressFk IS NULL THEN + SELECT id INTO vAddressFk + FROM address + WHERE clientFk = vClientId AND isDefaultAddress; + END IF; + + IF NOT vAgencyModeFk OR vAgencyModeFk IS NULL THEN + SELECT agencyModeFk INTO vAgencyModeFk + FROM address + WHERE clientFk = vClientId AND isDefaultAddress; + END IF; + + CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + + SELECT id INTO vZoneFk FROM tmp.zoneGetShipped + WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; + + INSERT INTO vn2008.Tickets ( + Id_Cliente, + Fecha, + Id_Consigna, + Id_Agencia, + Alias, + warehouse_id, + Id_Ruta, + empresa_id, + landing, + zoneFk + ) + SELECT + vClientId, + IFNULL(vShipped,vLanded), + a.id, + IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk), + a.nickname, + vWarehouseFk, + IF(vRouteFk,vRouteFk,NULL), + vCompanyFk, + vLanded, + vZoneFk + FROM address a + JOIN agencyMode am ON am.id = a.agencyModeFk + WHERE a.id = vAddressFk; + + SET vNewTicket = LAST_INSERT_ID(); + + INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) + SELECT vNewTicket, ao.observationTypeFk, ao.description + FROM addressObservation ao + JOIN address a ON a.id = ao.addressFk + WHERE a.id = vAddressFk; + + -- CALL logAddWithUser(vNewTicket, vUserId, 'insert', 'ticket', CONCAT('Ha creado el ticket', ' ', vNewTicket)); + INSERT INTO vn.ticketLog + SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); + + IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT id, vNewTicket, getWorker() + FROM state + WHERE `code` = 'DELIVERED'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketCreateWithUser` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`( + vClientId INT + ,vShipped DATE + ,vWarehouseFk INT + ,vCompanyFk INT + ,vAddressFk INT + ,vAgencyModeFk INT + ,vRouteFk INT + ,vLanded DATE + ,vUserId INT + ,OUT vNewTicket INT) +BEGIN + + DECLARE vZoneFk INT; + + IF vClientId IS NULL THEN + CALL util.throw ('CLIENT_NOT_ESPECIFIED'); + END IF; + + IF NOT vAddressFk OR vAddressFk IS NULL THEN + SELECT id INTO vAddressFk + FROM address + WHERE clientFk = vClientId AND isDefaultAddress; + END IF; + + IF vAgencyModeFk IS NOT NULL THEN + + CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + + SELECT id INTO vZoneFk FROM tmp.zoneGetShipped + WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; + + IF vZoneFk IS NULL OR vZoneFk = 0 THEN + CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); + END IF; + END IF; + INSERT INTO ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + routeFk, + companyFk, + landed, + zoneFk + ) + SELECT + vClientId, + IFNULL(vShipped,vLanded), + a.id, + vAgencyModeFk, + a.nickname, + vWarehouseFk, + IF(vRouteFk,vRouteFk,NULL), + vCompanyFk, + vLanded, + vZoneFk + FROM address a + JOIN agencyMode am ON am.id = a.agencyModeFk + WHERE a.id = vAddressFk; + + SET vNewTicket = LAST_INSERT_ID(); + + INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) + SELECT vNewTicket, ao.observationTypeFk, ao.description + FROM addressObservation ao + JOIN address a ON a.id = ao.addressFk + WHERE a.id = vAddressFk; + + INSERT INTO vn.ticketLog + SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); + + IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT id, vNewTicket, getWorker() + FROM state + WHERE `code` = 'DELIVERED'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketDown_PrintableSelection` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketDown_PrintableSelection`(vSectorFk INT) +BEGIN + + UPDATE vn.ticketDown td + JOIN + (SELECT DISTINCT t.id + FROM vn.ticket t + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id + JOIN vn.itemShelving ish ON ish.id = iss.itemShelvingFk + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + WHERE p.sectorFk = vSectorFk + ) sub ON sub.id = td.ticketFk + JOIN vn.ticketDown_SelectionType tdst ON tdst.description = 'FREE' + JOIN vn.ticketDown_SelectionType tdst2 ON tdst2.description = 'SELECTED' + SET td.selected = tdst2.id + WHERE td.selected = tdst.id; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketFilter` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketFilter`() +BEGIN +/** + * Obtiene un listado de tickets + * junto con el precio total y los problemas + * + * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular + * @return Listado de tickets + */ + CALL ticketGetTotal(); + CALL ticketGetProblems(); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketFilter; + CREATE TEMPORARY TABLE tmp.ticketFilter ENGINE = MEMORY + SELECT t.*, tt.total, tp.problem + FROM tmp.ticket t + JOIN tmp.ticketTotal tt ON tt.ticketFk = t.ticketFk + LEFT JOIN tmp.ticketProblems tp ON tp.ticketFk = t.ticketFk; + + DROP TEMPORARY TABLE + tmp.ticket, + tmp.ticketTotal, + tmp.ticketProblems; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketGetProblems` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetProblems`() +BEGIN + + DECLARE vWarehouse INT; + DECLARE vDate DATE; + DECLARE vAvailableCache INT; + DECLARE vVisibleCache INT; + DECLARE vDone INT DEFAULT 0; + + DECLARE vCursor CURSOR FOR + SELECT DISTINCT tt.warehouseFk, date(tt.shipped) + FROM tmp.ticketGetProblems tt + WHERE DATE(tt.shipped) BETWEEN CURDATE() + AND TIMESTAMPADD(DAY, 1.9, CURDATE()); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketProblems; + CREATE TEMPORARY TABLE tmp.ticketProblems ( + ticketFk INT(11) PRIMARY KEY, + isFreezed INTEGER(1) DEFAULT 0, + risk DECIMAL(10,2) DEFAULT 0, + hasTicketRequest INTEGER(1) DEFAULT 0, + isAvailable INTEGER(1) DEFAULT 1 + ) ENGINE = MEMORY; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketList; + CREATE TEMPORARY TABLE tmp.ticketList + (PRIMARY KEY (ticketFk)) + ENGINE = MEMORY + SELECT tp.ticketFk, c.id clientFk + FROM tmp.ticketGetProblems tp + JOIN vn.client c ON c.id = tp.clientFk; + + + INSERT INTO tmp.ticketProblems(ticketFk, isFreezed) + SELECT DISTINCT tl.ticketFk, 1 + FROM tmp.ticketList tl + JOIN vn.client c ON c.id = tl.clientFk + WHERE c.isFreezed; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + (PRIMARY KEY (clientFk)) + ENGINE = MEMORY + SELECT DISTINCT clientFk + FROM tmp.ticketList; + + CALL clientGetDebt(CURDATE()); + + + INSERT INTO tmp.ticketProblems(ticketFk, risk) + SELECT DISTINCT tl.ticketFk, r.risk + FROM tmp.ticketList tl + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.agencyMode a ON t.agencyModeFk = a.id + JOIN tmp.risk r ON r.clientFk = t.clientFk + JOIN vn.client c ON c.id = t.clientFk + WHERE r.risk > c.credit + 10 + AND a.deliveryMethodFk != 3 + ON DUPLICATE KEY UPDATE + risk = r.risk; + + INSERT INTO tmp.ticketProblems(ticketFk, hasTicketRequest) + SELECT DISTINCT tl.ticketFk, 1 + FROM tmp.ticketList tl + JOIN vn.ticketRequest tr ON tr.ticketFk = tl.ticketFk + WHERE tr.isOK IS NULL + ON DUPLICATE KEY UPDATE + hasTicketRequest = 1; + + OPEN vCursor; + + WHILE NOT vDone + DO + FETCH vCursor INTO vWarehouse, vDate; + + CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouse); + CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouse, vDate); + + + INSERT INTO tmp.ticketProblems(ticketFk, isAvailable) + SELECT tl.ticketFk, 0 + FROM tmp.ticketList tl + JOIN vn.ticket t ON t.id = tl.ticketFk + LEFT 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 + LEFT JOIN cache.available av ON av.item_id = i.id + AND av.calc_id = vAvailableCache + WHERE date(t.shipped) = vDate + AND categoryFk != 6 + AND IFNULL(av.available, 0) < 0 + AND s.isPicked = FALSE + AND NOT i.generic + AND vWarehouse = t.warehouseFk + GROUP BY tl.ticketFk + ON DUPLICATE KEY UPDATE + isAvailable = 0; + + INSERT INTO tmp.ticketProblems(ticketFk, isAvailable) + SELECT tl.ticketFk, 0 + FROM tmp.ticketList tl + JOIN vn.ticket t ON t.id = tl.ticketFk + LEFT 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 + LEFT JOIN cache.visible v ON i.id = v.item_id AND v.calc_id = vVisibleCache + LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache + WHERE IFNULL(av.available, 0) >= 0 + AND s.quantity > IFNULL(v.visible, 0) + AND s.isPicked = FALSE + AND s.reserved = FALSE + AND it.categoryFk != 6 + AND date(t.shipped) = vDate + AND NOT i.generic + AND CURDATE() = vDate + AND t.warehouseFk = vWarehouse + GROUP BY tl.ticketFk + ON DUPLICATE KEY UPDATE + isAvailable = 0; + + END WHILE; + + CLOSE vCursor; + + SELECT * FROM tmp.ticketProblems; + + DROP TEMPORARY TABLE + tmp.clientGetDebt, + tmp.ticketList; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTax` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTax`() + READS SQL DATA +BEGIN +/** + * Calcula la base imponible, el IVA y el recargo de equivalencia para + * un conjunto de tickets. + * + * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular + * @return tmp.ticketAmount + * @return tmp.ticketTax Impuesto desglosado para cada ticket. + + */ + DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; + CREATE TEMPORARY TABLE tmp.addressCompany + (INDEX (addressFk, companyFk)) + ENGINE = MEMORY + SELECT DISTINCT t.addressFk, t.companyFk + FROM tmp.ticket tmpTicket + JOIN ticket t ON t.id = tmpTicket.ticketFk; + + CALL addressTaxArea (); + + + /** Solo se calcula la base imponible (taxableBase) y el impuesto se calculará posteriormente + * No se debería cambiar el sistema por problemas con los decimales + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; + CREATE TEMPORARY TABLE tmp.ticketTax + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT tmpTicket.ticketFk, + bp.pgcFk, + SUM(s.quantity * s.price * (100 - s.discount)/100 ) AS taxableBase, + pgc.rate, + tc.code + FROM tmp.ticket tmpTicket + JOIN sale s ON s.ticketFk = tmpTicket.ticketFk + JOIN item i ON i.id = s.itemFk + JOIN ticket t ON t.id = tmpTicket.ticketFk + JOIN supplier su ON su.id = t.companyFk + JOIN tmp.addressTaxArea ata + ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk + JOIN itemTaxCountry itc + ON itc.itemFk = i.id AND itc.countryFk = su.countryFk + JOIN bookingPlanner bp + ON bp.countryFk = su.countryFk + AND bp.taxAreaFk = ata.areaFk + AND bp.taxClassFk = itc.taxClassFk + JOIN pgc ON pgc.code = bp.pgcFk + JOIN taxClass tc ON tc.id = bp.taxClassFk + GROUP BY tmpTicket.ticketFk, pgc.code,pgc.rate + HAVING taxableBase != 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketServiceTax; + CREATE TEMPORARY TABLE tmp.ticketServiceTax + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT tt.ticketFk, + SUM(ts.quantity * ts.price) AS taxableBase, + pgc.rate, + tc.code + FROM tmp.ticketTax tt + JOIN ticketService ts ON ts.ticketFk = tt.ticketFk + JOIN ticket t ON t.id = tt.ticketFk + JOIN supplier su ON su.id = t.companyFk + JOIN tmp.addressTaxArea ata + ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk + JOIN bookingPlanner bp + ON bp.countryFk = su.countryFk + AND bp.taxAreaFk = ata.areaFk + AND bp.taxClassFk = ts.taxClassFk + JOIN pgc ON pgc.code = bp.pgcFk AND pgc.rate = tt.rate + JOIN taxClass tc ON tc.id = bp.taxClassFk + GROUP BY tt.ticketFk, tt.code,tt.rate + HAVING taxableBase != 0; + + UPDATE tmp.ticketTax tt + JOIN tmp.ticketServiceTax ts ON tt.ticketFk = ts.ticketFk AND tt.code = ts.code AND tt.rate = ts.rate + SET tt.taxableBase = tt.taxableBase + ts.taxableBase; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; + CREATE TEMPORARY TABLE tmp.ticketAmount + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT ticketFk, taxableBase, SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax,code + FROM tmp.ticketTax + GROUP BY ticketFk, code; + + DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; + DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTaxAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTaxAdd`(vTicketFk INT) +BEGIN +/** + * Añade un ticket a la tabla tmp.ticket para calcular + * el IVA y el recargo de equivalencia y devuelve el resultado. + */ + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + ENGINE = MEMORY + SELECT vTicketFk ticketFk; + + CALL vn.ticketGetTax(); + + SELECT + tt.ticketFk, + CAST(tt.taxableBase AS DECIMAL(10, 2)) AS taxableBase, + CAST(tt.rate * tt.taxableBase / 100 AS DECIMAL(10, 2)) AS tax, + pgc.*, + CAST(IF(pe.equFk IS NULL, taxableBase, 0) AS DECIMAL(10, 2)) AS Base, + pgc.rate / 100 as vatPercent + FROM tmp.ticketTax tt + JOIN vn.pgc ON pgc.code = tt.pgcFk + LEFT JOIN vn.pgcEqu pe ON pe.equFk = pgc.code; + + DROP TEMPORARY TABLE tmp.ticket; + DROP TEMPORARY TABLE tmp.ticketTax; + DROP TEMPORARY TABLE tmp.ticketAmount; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTax_new` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTax_new`() + READS SQL DATA +BEGIN +/** + * Calcula la base imponible, el IVA y el recargo de equivalencia para + * un conjunto de tickets. + * + * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular + * @return tmp.ticketTax Impuesto desglosado para cada ticket + * @return tmp.ticketAmount + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; + CREATE TEMPORARY TABLE tmp.addressCompany + (INDEX (addressFk, companyFk)) + ENGINE = MEMORY + SELECT DISTINCT t.addressFk, t.companyFk + FROM tmp.ticket tmpTicket + JOIN ticket t ON t.id = tmpTicket.ticketFk; + + CALL addressTaxArea (); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; + CREATE TEMPORARY TABLE tmp.ticketTax + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT tmpTicket.ticketFk, + bp.pgcFk, + SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) + ) AS taxableBase, + SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) + ) * pgc.rate / 100 AS tax, + tc.code + + FROM tmp.ticket tmpTicket + JOIN sale s ON s.ticketFk = tmpTicket.ticketFk + JOIN item i ON i.id = s.itemFk + JOIN ticket t ON t.id = tmpTicket.ticketFk + JOIN supplier su ON su.id = t.companyFk + JOIN tmp.addressTaxArea ata + ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk + JOIN itemTaxCountry itc + ON itc.itemFk = i.id AND itc.countryFk = su.countryFk + JOIN bookingPlanner bp + ON bp.countryFk = su.countryFk + AND bp.taxAreaFk = ata.areaFk + AND bp.taxClassFk = itc.taxClassFk + JOIN pgc ON pgc.code = bp.pgcFk + JOIN taxClass tc ON tc.id = bp.taxClassFk + GROUP BY tmpTicket.ticketFk, pgc.code + HAVING taxableBase != 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; + CREATE TEMPORARY TABLE tmp.ticketAmount + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT ticketFk, taxableBase, SUM(tax) tax + FROM tmp.ticketTax + GROUP BY ticketFk, code; + + DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; + DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTotal` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTotal`() + READS SQL DATA +BEGIN +/** + * Calcula el total con IVA para un conjunto de tickets. + * + * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular + * @return tmp.ticketTotal Total para cada ticket + */ + CALL ticketGetTax; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketTotal; + CREATE TEMPORARY TABLE tmp.ticketTotal + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT t.ticketFk, IFNULL(SUM(ta.taxableBase + ta.tax), 0.0) AS total + FROM tmp.ticket t + LEFT JOIN tmp.ticketAmount ta ON t.ticketFk = ta.ticketFk + GROUP BY ticketFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; + DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketGetVisibleAvailable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetVisibleAvailable`( + vTicket INT) +BEGIN + DECLARE vVisibleCalc INT; + DECLARE vAvailableCalc INT; + DECLARE vShipped DATE; + DECLARE vWarehouse TINYINT; + DECLARE vAlertLevel INT; + + SELECT t.warehouseFk, t.shipped, ts.alertLevel INTO vWarehouse, vShipped, vAlertLevel + FROM ticket t + LEFT JOIN ticketState ts ON ts.ticketFk = vTicket + WHERE t.id = vTicket; + + IF vAlertLevel IS NULL OR vAlertLevel = 0 THEN + IF vShipped >= CURDATE() THEN + CALL cache.available_refresh(vAvailableCalc, FALSE, vWarehouse, vShipped); + END IF; + IF vShipped = CURDATE() THEN + CALL cache.visible_refresh(vVisibleCalc, FALSE, vWarehouse); + END IF; + END IF; + + SELECT s.id, s.itemFk, s.quantity, s.concept, s.price, s.reserved, s.discount, v.visible, av.available, it.image, it.subName + FROM sale s + LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCalc + LEFT JOIN cache.available av ON av.item_id = s.itemFk AND av.calc_id = vAvailableCalc + LEFT JOIN item it ON it.id = s.itemFk + WHERE s.ticketFk = vTicket + ORDER BY s.concept; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketListCreate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketListCreate`( + vClientId INT + ,vShipped DATE + ,vWarehouseId INT + ,vCompanyFk INT + ,vAddressFk INT + ,vAgencyType INT + ,vRouteFk INT + ,vlanded DATE) +BEGIN + + DECLARE vNewTicket INT; + CALL vn.ticketCreate(vClientId, vShipped, vWarehouseId, vCompanyFk, vAddressFk, vAgencyType, vRouteFk, vlanded,vNewTicket); + SELECT vNewTicket; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketListVolume` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketListVolume`(IN vTicketId INT) +BEGIN + + DECLARE vWarehouseId INTEGER; + DECLARE vShippedDate DATE; + + SELECT warehouseFk, shipped INTO vWarehouseId,vShippedDate FROM vn.ticket WHERE id = vTicketId; + + SELECT s.quantity, + round(r.cm3 * i.compression * s.quantity / 1000000,3) as m3, + s.itemFk, + s.id AS saleFk, + s.concept, + t.agencyModeFk + FROM sale s + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.ticket t on t.id = s.ticketFk + JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk + WHERE s.ticketFk = vTicketId; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketNotInvoicedByClient` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketNotInvoicedByClient`(vClientFk INT) +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + + CREATE TEMPORARY TABLE tmp.ticket + SELECT id ticketFk + FROM ticket + WHERE refFk IS NULL + AND clientFk = vClientFk + AND shipped > '2001-01-01'; + + CALL vn.ticketGetTotal; + + SELECT c.id, + c.name as Cliente, + t.shipped as Fecha, + t.id as Id_Ticket, + CAST(tt.total AS DECIMAL(10,2)) as Importe + FROM tmp.ticketTotal tt + JOIN ticket t ON t.id = tt.ticketFk + JOIN client c ON c.id = t.ClientFk; + + DROP TEMPORARY TABLE + tmp.ticket, + tmp.ticketTotal; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketPackagingRecovery` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketPackagingRecovery`() +BEGIN + + /* Recupera los embalajes que han caido en el cliente 31 */ + + DECLARE done BOOL DEFAULT FALSE; + DECLARE vClientFk INT; + DECLARE vTicketFk INT; + DECLARE vTicketNewFk INT; + DECLARE vWarehouseFk INT; + DECLARE vShipped DATE; + DECLARE vCompanyFk INT; + DECLARE vAgenciaEmbalajesFk INT DEFAULT 628; + + DECLARE rs CURSOR FOR + SELECT DISTINCT tp.ticketFk, a.clientFk, t.warehouseFk, t.shipped, t.companyFk + FROM ticket t + JOIN ticketPackaging tp ON t.id = tp.ticketFk + JOIN address a ON a.id = t.addressFk + WHERE t.clientFk = 31 + AND t.shipped > '2001-01-01'; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + OPEN rs; + + FETCH rs INTO vTicketFk, vClientFk, vWarehouseFk, vShipped, vCompanyFk; + + WHILE NOT done DO + + CALL vn.ticketCreate(vClientFk,vShipped,vWarehouseFk,vCompanyFk, NULL, NULL, NULL, + vShipped,vTicketNewFk); + + UPDATE vn.ticketPackaging set ticketFk = vTicketNewFk WHERE ticketFk = vTicketFk; + + CALL vn.ticketStateUpdate(vTicketNewFk, 'DELIVERED'); + + INSERT INTO vn.sale(ticketFk, itemFk, concept) VALUES(vTicketNewFk,90,CONCAT('Embalajes ',vTicketFk)); + + FETCH rs INTO vTicketFk, vClientFk, vWarehouseFk, vShipped, vCompanyFk; + + END WHILE; + + CLOSE rs; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketSplitCounter` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketSplitCounter`(vTicketFk INT) +BEGIN + +SELECT CONCAT(OK,'/',Total, IF(OK = Total ,' LS','')) + FROM + ( + SELECT sum(if(l.Id_Movimiento != 0,1,0)) as OK, COUNT(*) as Total + FROM vn.sale s + LEFT JOIN movement_label l ON l.Id_Movimiento = s.id + WHERE ticketFk = vTicketFk + ) sub; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketStatePrevious` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketStatePrevious`(vTicketFk INT) +BEGIN + + DECLARE vControlFk INT; + DECLARE vLastWorkerFk INT; + DECLARE vStateId INT; + + SELECT MAX(inter_id) INTO vControlFk + FROM vncontrol.inter + WHERE Id_Ticket = vTicketFk; + + IF (SELECT s.code + FROM vn.state s + JOIN vncontrol.inter i ON i.state_id = s.id + WHERE i.inter_id = vControlFk) + = 'PREVIOUS_PREPARATION' THEN + + SELECT inter_id, Id_Trabajador + INTO vControlFk,vLastWorkerFk + FROM vncontrol.inter i + JOIN vn.state s ON i.state_id = s.id + WHERE Id_Ticket = vTicketFk + AND inter_id < vControlFk + AND s.code != 'PREVIOUS_PREPARATION' + ORDER BY inter_id DESC + LIMIT 1; + /* + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador, Id_Supervisor) + SELECT state_id, Id_Ticket, vLastWorkerFk, vn.getWorker() + FROM vncontrol.inter + WHERE inter_id = vControlFk; + */ + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador, Id_Supervisor) + SELECT s.nextStateFk, i.Id_Ticket, vLastWorkerFk, vn.getWorker() + FROM vncontrol.inter i + JOIN vn.state s ON i.state_id = s.id + WHERE inter_id = vControlFk; + + SELECT state_id INTO vStateId + FROM vncontrol.inter + WHERE inter_id = vControlFk; + + END IF; + + /*DELETE FROM vn2008.Movimientos_mark + WHERE Id_Movimiento IN (SELECT Id_Movimiento FROM vn2008.Movimientos WHERE Id_Ticket = vTicketFk) + AND valor <> 1 + AND stateFk = 26; */ + + SELECT TRUE AS IsUpdated; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketStateUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45)) +BEGIN + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT id, vTicketFk, getWorker() + FROM vn.state + WHERE `code` = vStateCode collate utf8_unicode_ci; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByAddress` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketToInvoiceByAddress`( + vStarted DATE, + vEnded DATETIME, + vAddress INT, + vCompany INT + ) +BEGIN + + SET vEnded = util.dayEnd(vEnded); + + DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice; + + CREATE TEMPORARY TABLE vn.ticketToInvoice + SELECT id + FROM vn.ticket + WHERE addressFk = vAddress + AND companyFk = vCompany + AND shipped BETWEEN vStarted AND vEnded + AND refFk IS NULL; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByClient` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketToInvoiceByClient`( + vStarted DATE, + vEnded DATETIME, + vClient INT, + vCompany INT + ) +BEGIN + + SET vEnded = util.dayEnd(vEnded); + + DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice; + + CREATE TEMPORARY TABLE vn.ticketToInvoice + SELECT id + FROM vn.ticket + WHERE clientFk = vClient + AND companyFk = vCompany + AND shipped BETWEEN vStarted AND vEnded + AND refFk IS NULL; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByDate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketToInvoiceByDate`( + vStarted DATE, + vEnded DATETIME, + vClient INT, + vCompany INT + ) +BEGIN + + SET vEnded = util.dayEnd(vEnded); + + DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice; + + CREATE TEMPORARY TABLE vn.ticketToInvoice + SELECT id + FROM vn.ticket + WHERE clientFk = vClient + AND companyFk = vCompany + AND shipped BETWEEN vStarted AND vEnded + AND refFk IS NULL; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByRef` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketToInvoiceByRef`(IN vInvoiceRef VARCHAR(15)) +BEGIN + +/* Para tickets ya facturados, vuelve a repetir el proceso de facturación. +* +* @param vInvoiceRef Factura +*/ + + DECLARE vInvoice INT; + DECLARE vCountry INT; + DECLARE vTaxArea VARCHAR(15); + DECLARE vSpainCountryCode INT DEFAULT 1; + + SELECT id + INTO vInvoice + FROM vn.invoiceOut + WHERE ref = vInvoiceRef; + + SELECT s.countryFk + INTO vCountry + FROM vn.supplier s + JOIN vn.invoiceOut io ON io.companyFk = s.id + WHERE io.id = vInvoice; + + SELECT IF( + c.isEqualizated + AND c.countryFk = vSpainCountryCode + AND i.taxAreaFk = 'NATIONAL', + 'EQU', + i.taxAreaFk + ) + INTO vTaxArea + FROM vn.invoiceOutSerial i + JOIN vn.invoiceOut io ON io.serial = i.code + JOIN vn.client c ON c.id = io.clientFk + WHERE io.id = vInvoice; + + DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice; + + CREATE TEMPORARY TABLE vn.ticketToInvoice + SELECT id + FROM vn.ticket + WHERE refFk = vInvoiceRef; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketToPrePrepare` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketToPrePrepare`(IN vIdTicket INT, IN viewAll BOOL, IN vSectorFk INT) +BEGIN + +/* Tickets con estado 26 para preaprar en altillo +*/ +IF viewAll IS true THEN + SELECT stpp.*,ispss.created,ispss.sectorFk + FROM vn.salesToPrePrepare stpp + LEFT JOIN vn.itemShelvingPlacementSupplyStock ispss + ON ispss.itemShelvingFk = (SELECT itemShelvingFk FROM vn.itemShelvingPlacementSupplyStock WHERE itemFk = stpp.Id_Article AND sectorFk = vSectorFk ORDER BY parking ASC LIMIT 1) + LEFT JOIN vn.parking p ON p.id = ispss.parkingFk + WHERE stpp.Id_Ticket = vIdTicket + ORDER BY p.column ASC; +ELSE + SELECT * + FROM vn.ticketToPrepare ttp + WHERE ttp.Id_Ticket = vIdTicket; + +END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketTrackingAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketTrackingAdd`(vTicketFk INT, vState VARCHAR(25) CHARSET UTF8, vWorkerFk INT) +BEGIN +/** + * Inserta un registro de cambios en un ticket. + * @param vTicketFk Id del ticket + * @param vState Código del estado + * @param vWorkerFk Id del trabajador + */ + INSERT INTO ticketTracking (stateFk, ticketFk, workerFk) + SELECT s.id, vTicketFk, vWorkerFk FROM state s WHERE s.code = vState; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketVolumeByDate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketVolumeByDate`(vDate DATE) +BEGIN + + DECLARE vDateStart DATETIME DEFAULT DATE(vDate); + DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketVolumeByDate; + + CREATE TEMPORARY TABLE tmp.ticketVolumeByDate + ENGINE = MEMORY + SELECT s.ticketFk, + CAST(SUM(r.cm3 * s.quantity) / 1000000 AS DECIMAL(10,2)) as m3 + FROM sale s + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.ticket t on t.id = s.ticketFk + JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk + WHERE ic.merchandise + AND t.shipped BETWEEN vDateStart AND vDateEnd + GROUP BY s.ticketFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketVolumeByDate_ventas` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketVolumeByDate_ventas`(vDate DATE) +BEGIN + + DECLARE vDateStart DATETIME DEFAULT DATE(vDate); + DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketVolumeByDate; + + CREATE TEMPORARY TABLE tmp.ticketVolumeByDate + ENGINE = MEMORY + SELECT s.ticketFk, + CAST(SUM(r.cm3 * s.quantity) / 1000000 AS DECIMAL(10,2)) as m3 + FROM sale s + JOIN bs.ventas v ON v.Id_Movimiento = s.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.ticket t on t.id = s.ticketFk + JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk + WHERE ic.merchandise + AND t.shipped BETWEEN vDateStart AND vDateEnd + AND it.name NOT IN ('Accesorios Funerarios','Composiciones planta','Composición bajo pedido','Coronas y centros') + GROUP BY s.ticketFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticketVolumeByDate_ventas_Artificial` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketVolumeByDate_ventas_Artificial`(vDate DATE) +BEGIN + + DECLARE vDateStart DATETIME DEFAULT DATE(vDate); + DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketVolumeByDate_Artificial; + + CREATE TEMPORARY TABLE tmp.ticketVolumeByDate_Artificial + ENGINE = MEMORY + SELECT s.ticketFk, + CAST(SUM(r.cm3 * s.quantity) / 1000000 AS DECIMAL(10,2)) as m3 + FROM sale s + JOIN bs.ventas v ON v.Id_Movimiento = s.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.sector sc ON sc.id = i.sectorFk + JOIN vn.ticket t on t.id = s.ticketFk + JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk + WHERE sc.description = 'Artificial' + AND t.shipped BETWEEN vDateStart AND vDateEnd + GROUP BY s.ticketFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_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_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_Clone`(vOriginalTicket INT, OUT vNewTicket INT) +BEGIN + INSERT INTO ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + companyFk, + landed, + zoneFk + ) + SELECT + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + companyFk, + landed, + zoneFk + FROM ticket + WHERE id = vOriginalTicket; + + SET vNewTicket = LAST_INSERT_ID(); + + INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) + SELECT vNewTicket, ao.observationTypeFk, ao.description + FROM addressObservation ao + JOIN ticket t ON t.addressFk = ao.addressFk + WHERE t.id = vNewTicket; + + INSERT INTO ticketLog + SET originFk = vNewTicket, userFk = account.myUserGetId(), `action` = 'insert', + description = CONCAT('Ha creado el ticket:', ' ', vNewTicket, ' clonando el ', vOriginalTicket); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_componentMakeUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentMakeUpdate`( + vTicketFk INT, + vClientFk INT, + vAgencyModeFk INT, + vAddressFk INT, + vZoneFk INT, + vWarehouseFk TINYINT, + vCompanyFk SMALLINT, + vShipped DATETIME, + vLanded DATE, + vIsDeleted BOOLEAN, + vHasToBeUnrouted BOOLEAN, + vOption INT) +BEGIN + + CALL vn.ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); + CALL vn.ticket_componentUpdate ( + vTicketFk, + vClientFk, + vAgencyModeFk, + vAddressFk, + vZoneFk, + vWarehouseFk, + vCompanyFk, + vShipped, + vLanded, + vIsDeleted, + vHasToBeUnrouted, + vOption + ); + + DROP TEMPORARY TABLE + tmp.ticketComponent, + tmp.ticketComponentPrice; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_componentPreview` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentPreview`( + vTicketFk INT, + vLanded DATE, + vAddressFk INT, + vZoneFk INT, + vWarehouseFk SMALLINT) +BEGIN +/** + * Calcula los componentes de los articulos de un ticket + * + * @param vTicketFk id del ticket + * @param vLanded nueva fecha de entrega + * @param vAddressFk nuevo consignatario + * @param vZoneFk nueva zona + * @param vWarehouseFk nuevo warehouse + * + * @return tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + */ + DECLARE vShipped DATE; + DECLARE vBuyOrderItem INT DEFAULT 100; + + DECLARE vHasDataChanged BOOL DEFAULT FALSE; + DECLARE vHasAddressChanged BOOL; + DECLARE vHasZoneChanged BOOL DEFAULT FALSE; + DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE; + + DECLARE vAddressTypeRateFk INT DEFAULT NULL; + DECLARE vAgencyModeTypeRateFk INT DEFAULT NULL; + + DECLARE vHasChangeAll BOOL DEFAULT FALSE; + + SELECT DATE(landed) <> vLanded, + addressFk <> vAddressFk, + zoneFk <> vZoneFk, + warehouseFk <> vWarehouseFk + INTO + vHasDataChanged, + vHasAddressChanged, + vHasZoneChanged, + vHasWarehouseChanged + FROM vn.ticket t + WHERE t.id = vTicketFk; + + IF vHasDataChanged OR vHasWarehouseChanged THEN + SET vHasChangeAll = TRUE; + END IF; + + IF vHasAddressChanged THEN + SET vAddressTypeRateFk = 5; + END IF; + + IF vHasZoneChanged THEN + SET vAgencyModeTypeRateFk = 6; + END IF; + + SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped + FROM zone + WHERE id = vZoneFk; + + CALL buyUltimate(vWarehouseFk, vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( + SELECT + vWarehouseFk AS warehouseFk, + NULL AS available, + s.itemFk, + bu.buyFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + AND s.itemFk != vBuyOrderItem + GROUP BY bu.warehouseFk, bu.itemFk); + + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); + + REPLACE INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT t.warehouseFk, s.itemFk, sc.componentFk, sc.value + FROM saleComponent sc + JOIN sale s ON s.id = sc.saleFk + JOIN ticket t ON t.id = s.ticketFk + JOIN componentRate cr ON cr.id = sc.componentFk + WHERE s.ticketFk = vTicketFk + AND (cr.isRenewable = FALSE + OR + (NOT vHasChangeAll + AND (NOT (cr.componentTypeRate <=> vAddressTypeRateFk + OR cr.componentTypeRate <=> vAgencyModeTypeRateFk)))); + + SET @shipped = vShipped; + + DROP TEMPORARY TABLE + tmp.buyUltimate, + tmp.ticketLot; + + IF vShipped IS NULL THEN + CALL util.throw('NO_ZONE_AVAILABLE'); + END IF; + + IF vShipped < CURDATE() THEN + CALL util.throw('ERROR_PAST_SHIPMENT'); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_componentUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentUpdate`( + vTicketFk INT, + vClientFk INT, + vAgencyModeFk INT, + vAddressFk INT, + vZoneFk INT, + vWarehouseFk TINYINT, + vCompanyFk SMALLINT, + vShipped DATETIME, + vLanded DATE, + vIsDeleted BOOLEAN, + vHasToBeUnrouted BOOLEAN, + vOption INT) +BEGIN + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN + + UPDATE ticket t + JOIN address a ON a.id = vAddressFk + SET t.nickname = a.nickname + WHERE t.id = vTicketFk; + + END IF; + + UPDATE ticket t + SET + t.clientFk = vClientFk, + t.agencyModeFk = vAgencyModeFk, + t.addressFk = vAddressFk, + t.zoneFk = vZoneFk, + t.warehouseFk = vWarehouseFk, + t.companyFk = vCompanyFk, + t.landed = vLanded, + t.shipped = vShipped, + t.isDeleted = vIsDeleted + WHERE + t.id = vTicketFk; + + IF vHasToBeUnrouted THEN + UPDATE ticket t SET t.routeFk = NULL + WHERE t.id = vTicketFk; + END IF; + + IF vOption <> 8 THEN + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) + ENGINE = MEMORY + SELECT id AS saleFk, vWarehouseFk warehouseFk + FROM sale s WHERE s.ticketFk = vTicketFk; + + CALL ticketComponentUpdateSale (vOption); + + DROP TEMPORARY TABLE tmp.sale; + END IF; + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_getTax` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_getTax`(vTaxArea VARCHAR(25)) + READS SQL DATA +BEGIN +/** + * Calcula la base imponible, el IVA y el recargo de equivalencia para + * un conjunto de tickets. + * + * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular + * @return tmp.ticketAmount + * @return tmp.ticketTax Impuesto desglosado para cada ticket. + */ + DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; + CREATE TEMPORARY TABLE tmp.addressCompany + (INDEX (addressFk, companyFk)) + ENGINE = MEMORY + SELECT DISTINCT t.addressFk, t.companyFk + FROM tmp.ticket tmpTicket + JOIN ticket t ON t.id = tmpTicket.ticketFk; + + CALL addressTaxArea (); + + IF vTaxArea > '' THEN + UPDATE tmp.addressTaxArea + SET areaFk = vTaxArea; + END IF; + /** Solo se calcula la base imponible (taxableBase) y el impuesto se calculará posteriormente + * No se debería cambiar el sistema por problemas con los decimales + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; + CREATE TEMPORARY TABLE tmp.ticketTax + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT * FROM ( + SELECT tmpTicket.ticketFk, + bp.pgcFk, + SUM(s.quantity * s.price * (100 - s.discount)/100 ) AS taxableBase, + pgc.rate, + tc.code, + bp.priority + FROM tmp.ticket tmpTicket + JOIN sale s ON s.ticketFk = tmpTicket.ticketFk + JOIN item i ON i.id = s.itemFk + JOIN ticket t ON t.id = tmpTicket.ticketFk + JOIN supplier su ON su.id = t.companyFk + JOIN tmp.addressTaxArea ata + ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk + JOIN itemTaxCountry itc + ON itc.itemFk = i.id AND itc.countryFk = su.countryFk + JOIN bookingPlanner bp + ON bp.countryFk = su.countryFk + AND bp.taxAreaFk = ata.areaFk + AND bp.taxClassFk = itc.taxClassFk + JOIN pgc ON pgc.code = bp.pgcFk + JOIN taxClass tc ON tc.id = bp.taxClassFk + GROUP BY tmpTicket.ticketFk, pgc.code,pgc.rate + HAVING taxableBase != 0) t + ORDER BY priority; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketServiceTax; + CREATE TEMPORARY TABLE tmp.ticketServiceTax + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT tt.ticketFk, + SUM(ts.quantity * ts.price) AS taxableBase, + pgc.rate, + tc.code + FROM tmp.ticketTax tt + JOIN ticketService ts ON ts.ticketFk = tt.ticketFk + JOIN ticket t ON t.id = tt.ticketFk + JOIN supplier su ON su.id = t.companyFk + JOIN tmp.addressTaxArea ata + ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk + JOIN bookingPlanner bp + ON bp.countryFk = su.countryFk + AND bp.taxAreaFk = ata.areaFk + AND bp.taxClassFk = ts.taxClassFk + JOIN pgc ON pgc.code = bp.pgcFk AND pgc.rate = tt.rate + JOIN taxClass tc ON tc.id = bp.taxClassFk + GROUP BY tt.ticketFk, tt.code,tt.rate + HAVING taxableBase != 0; + + UPDATE tmp.ticketTax tt + JOIN tmp.ticketServiceTax ts ON tt.ticketFk = ts.ticketFk AND tt.code = ts.code AND tt.rate = ts.rate + SET tt.taxableBase = tt.taxableBase + ts.taxableBase; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; + CREATE TEMPORARY TABLE tmp.ticketAmount + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT ticketFk, taxableBase, SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax,code + FROM tmp.ticketTax + GROUP BY ticketFk, code; + + DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; + DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_insertZone` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_insertZone`() +BEGIN + DECLARE vDone INT DEFAULT 0; + DECLARE vFechedTicket INT; + DECLARE vLanded DATE; + DECLARE vAddressFk INT; + DECLARE vAgencyModeFk INT; + DECLARE vWarehouseFk INT; + DECLARE vCursor CURSOR FOR + SELECT id, landed, addressFk, agencyModeFk, warehouseFk + FROM vn.ticket WHERE shipped >= '2019-07-01'; + DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET vDone = 1; + + OPEN vCursor; + REPEAT + FETCH vCursor INTO vFechedTicket, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk; + CALL zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + UPDATE vn.ticket t + JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = vWarehouseFk + SET zoneFk = zgs.id + WHERE t.id = vFechedTicket; + + UNTIL vDone END REPEAT; + DROP TEMPORARY TABLE tmp.zoneGetShipped; + CLOSE vCursor; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_priceDifference` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_priceDifference`( + vTicketFk INT, + vLanded DATE, + vAddressFk INT, + vZoneFk INT, + vWarehouseFk INT) +BEGIN +/** + * Devuelve las diferencias de precio + * de los movimientos de un ticket. + * + * @param vTicketFk Id del ticket + * @param vLanded Fecha de recepcion + * @param vAddressFk Id del consignatario + * @param vZoneFk Id de la zona + * @param vWarehouseFk Id del almacén + */ + CALL vn.ticket_componentPreview(vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); + + SELECT s.itemFk, + i.name, + i.size, + i.category, + IFNULL(s.quantity, 0) AS quantity, + IFNULL(s.price, 0) AS price, + ROUND(SUM(tc.cost), 2) AS newPrice, + s.quantity * (s.price - ROUND(SUM(tc.cost), 2)) difference, + s.id AS saleFk + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN ticket t ON t.id = s.ticketFk + LEFT JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk + AND tc.warehouseFk = t.warehouseFk + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk = tc.componentFk + LEFT JOIN componentRate cr ON cr.id = tc.componentFk + WHERE + t.id = vTicketFk + AND IF(sc.componentFk IS NULL + AND cr.classRate IS NOT NULL, FALSE, TRUE) + GROUP BY s.id ORDER BY s.id; + + DROP TEMPORARY TABLE + tmp.ticketComponent, + tmp.ticketComponentPrice; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_recalcComponents` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT ) +proc: BEGIN + +/** + * Este procedimiento trata de "rebionizar" un ticket, + * eliminando los componentes existentes e insertandolos de nuevo + * + * @param vTicketFk Id del ticket + * @return tmp.buyUltimate + */ + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vLanded DATE; + DECLARE vIsTicketEditable BOOLEAN; + + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE + INTO vIsTicketEditable + FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket + WHERE id = vTicketFk; + + SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded + FROM ticket + WHERE id = vTicketFk; + + CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); + + CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, + s.itemFk, bu.buyFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + GROUP BY s.itemFk; + + CALL vn.ticketComponentCalculate(vAddressFk,vAgencyModeFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT id saleFk, vWarehouseFk warehouseFk + FROM sale s + WHERE s.ticketFk = vTicketFk; + + CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios + + IF vLanded IS NULL THEN + + CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); + + UPDATE vn2008.Tickets t + SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) + WHERE Id_Ticket = vTicketFk; + + DROP TEMPORARY TABLE tmp.zoneGetLanded; + + END IF; + + DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE tmp.ticketComponentPrice; + DROP TEMPORARY TABLE tmp.ticketComponent; + DROP TEMPORARY TABLE tmp.sale; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ticket_recalcComponentsForcePrice` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponentsForcePrice`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN ) +proc: BEGIN + +/** + * Este procedimiento trata de "rebionizar" un ticket, + * eliminando los componentes existentes e insertandolos de nuevo + * + * @param vTicketFk Id del ticket + * @return tmp.buyUltimate + */ + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vAgencyModeFk INT; + DECLARE vAddressFk INT; + DECLARE vLanded DATE; + + IF vIsTicketEditable IS NULL THEN + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE + INTO vIsTicketEditable + FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket + WHERE id = vTicketFk; + END IF; + SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded + FROM ticket + WHERE id = vTicketFk; + + CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); + + CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot + SELECT vWarehouseFk warehouseFk, NULL available, + s.itemFk, bu.buyFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + GROUP BY s.itemFk; + + CALL vn.ticketComponentCalculate(vAddressFk,vAgencyModeFk); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) ENGINE = MEMORY + SELECT id saleFk, vWarehouseFk warehouseFk + FROM sale s + WHERE s.ticketFk = vTicketFk; + + CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios + + IF vLanded IS NULL THEN + + CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); + + UPDATE vn2008.Tickets t + SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) + WHERE Id_Ticket = vTicketFk; + + DROP TEMPORARY TABLE tmp.zoneGetLanded; + + END IF; + + DROP TEMPORARY TABLE tmp.buyUltimate; + DROP TEMPORARY TABLE tmp.ticketComponentPrice; + DROP TEMPORARY TABLE tmp.ticketComponent; + DROP TEMPORARY TABLE tmp.sale; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `timeBusiness_calculate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN + -- BERNAT: WORKING IN THIS FILE +/** + * Horas que debe trabajar un empleado según contrato y día. + * @param vDatedFrom workerTimeControl + * @param vDatedTo workerTimeControl + * @table tmp.user(userFk) + * @return tmp.timeBusinessCalculate + */ + DECLARE vHoursFullTime INT DEFAULT 40; + + DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate; + DROP TEMPORARY TABLE IF EXISTS tmp.businessFullTime; + + CREATE TEMPORARY TABLE tmp.timeBusinessCalculate + SELECT dated, + businessFk, + userFk, + departmentFk, + hourStart, + hourEnd, + timeWorkSeconds, + SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal, + timeWorkSeconds / 3600 timeWorkDecimal, + timeWorkSeconds timeBusinessSeconds, + SEC_TO_TIME(timeWorkSeconds) timeBusinessSexagesimal, + timeWorkSeconds / 3600 timeBusinessDecimal, + type, + permissionrate, + hoursWeek + FROM(SELECT t.dated, + b.business_id businessFk, + w.userFk, + bl.department_id departmentFk, + IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,2) ORDER BY j.start ASC SEPARATOR '-')) hourStart , + IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.end,2) ORDER BY j.end ASC SEPARATOR '-')) hourEnd, + IF(cl.hours_week = vHoursFullTime, 0, IFNULL(SUM(TIME_TO_SEC(j.end)) - SUM(TIME_TO_SEC(j.start)),0)) timeWorkSeconds, + cs.type, + cs.permissionRate, + cl.hours_week hoursWeek + FROM vn.time t + LEFT JOIN postgresql.business b ON t.dated BETWEEN b.date_start AND ifnull(b.date_end, vDatedTo ) + LEFT JOIN postgresql.profile AS pr ON b.client_id = pr.profile_id + LEFT JOIN postgresql.person AS p ON pr.person_id = p.person_id + LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id + JOIN tmp.`user` u ON u.userFK = w.userFK + JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id + LEFT JOIN postgresql.business_labour_payroll AS bp ON bl.business_id = bp.business_id + LEFT JOIN postgresql.professional_category AS pc ON bl.professional_category_id = pc.professional_category_id + LEFT JOIN postgresql.workcenter AS wc ON bl.workcenter_id = wc.workcenter_id + LEFT JOIN postgresql.calendar_labour_type AS cl ON bl.calendar_labour_type_id = cl.calendar_labour_type_id + LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(t.dated)+1 + LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and ce.date = t.dated + LEFT JOIN postgresql.calendar_state cs ON cs.calendar_state_id = ce.calendar_state_id + WHERE t.dated BETWEEN vDatedFrom AND vDatedTo + GROUP BY w.userFk,dated + )sub; + + + UPDATE tmp.timeBusinessCalculate t + SET t.timeWorkSeconds = vHoursFullTime / 5 * 3600, + t.timeWorkSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600), + t.timeWorkDecimal = vHoursFullTime / 5, + t.timeBusinessSeconds = vHoursFullTime / 5 * 3600, + t.timeBusinessSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600), + t.timeBusinessDecimal = vHoursFullTime / 5 + WHERE DAYOFWEEK(t.dated) IN(2,3,4,5,6) AND hoursWeek = vHoursFullTime ; + + UPDATE tmp.timeBusinessCalculate t + SET t.timeWorkSeconds = t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate) , + t.timeWorkSexagesimal = SEC_TO_TIME(t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate)), + t.timeWorkDecimal = t.timeWorkDecimal - (t.timeWorkDecimal * permissionrate) + WHERE permissionrate <> 0; + + UPDATE tmp.timeBusinessCalculate t + JOIN postgresql.calendar_labour cl ON cl.day = t.dated + JOIN postgresql.business_labour bl ON bl.business_id = t.businessFk AND bl.workcenter_id = cl.workcenter_id + SET t.timeWorkSeconds = 0, + t.timeWorkSexagesimal = 0, + t.timeWorkDecimal = 0, + t.permissionrate = 1, + t.type = 'Festivo' + WHERE t.type IS NULL; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `timeBusiness_calculateAll` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `timeBusiness_calculateAll`(vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN + +/** + * @param vDatedFrom workerTimeControl + * @param vDatedTo workerTimeControl + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; + + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + SELECT userFk + FROM vn.worker w + JOIN vn.`user` u ON u.id = w.userFk + WHERE userFk IS NOT NULL AND u.active = TRUE; + + CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); + + DROP TEMPORARY TABLE tmp.`user`; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `timeBusiness_calculateByDepartment` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `timeBusiness_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN + +/** + * @param vDepartmentFk + * @param vDatedFrom workerTimeControl + * @param vDatedTo workerTimeControl + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; + + CREATE TEMPORARY TABLE tmp.`user` + SELECT DISTINCT w.userFk + FROM postgresql.business AS b + LEFT JOIN postgresql.profile AS pr ON pr.profile_id = b.client_id + LEFT JOIN postgresql.person AS p ON p.person_id = pr.person_id + LEFT JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id + LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id + LEFT JOIN vn.department AS d ON bl.department_id = d.id + WHERE ((b.date_start BETWEEN vDatedFrom AND vDatedTo OR b.date_end BETWEEN vDatedFrom AND vDatedTo) OR + (b.date_end IS NULL AND b.date_start <= vDatedTo) OR + (b.date_start <= vDatedFrom AND b.date_end >= vDatedTo) + ) AND bl.department_id = vDepartmentFk + ORDER BY b.date_end DESC; + + CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); + + DROP TEMPORARY TABLE tmp.`user`; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `timeBusiness_calculateByUser` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `timeBusiness_calculateByUser`(vUserFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN + +/** + * @param vUserFk + * @param vDatedFrom workerTimeControl + * @param vDatedTo workerTimeControl + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; + + CREATE TEMPORARY TABLE tmp.`user` + SELECT id userFk + FROM user + WHERE id = vUserFk; + CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); + + DROP TEMPORARY TABLE tmp.`user`; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `timeBusiness_calculateByWorker` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `timeBusiness_calculateByWorker`(vWorkerFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN + +/** + * @param vWorkerFk + * @param vDatedFrom workerTimeControl + * @param vDatedTo workerTimeControl + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; + + CREATE TEMPORARY TABLE tmp.`user` + SELECT u.id userFk + FROM vn.user u + JOIN vn.worker w ON w.userFk = u.id + WHERE w.id = vWorkerFk; + + CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); + + DROP TEMPORARY TABLE tmp.`user`; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `timeControl_calculate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `timeControl_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN + +/** + * Horas totales trabajadas a partir de las fichadas, tiene en cuenta los descansos y fichadas impares + * (si hay fichadas impares nop devuelve info) + * @param vDatedFrom workerTimeControl + * @param vDatedTo workerTimeControl + * @table tmp.user(userFk) + * @return tmp.timeControlCalculate + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; + + CREATE TEMPORARY TABLE tmp.timeControlCalculate + SELECT userFk, + dated, + IF( timeWork >= 18000, @timeWork:=timeWork + 1200, @timeWork:=timeWork) timeWorkSeconds, + SEC_TO_TIME(@timeWork ) timeWorkSexagesimal, + @timeWork / 3600 timeWorkDecimal + FROM (SELECT wtc.userFk, + DATE(wtc.timed) dated, + SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))) timeWork + FROM vn.workerTimeControl wtc + JOIN tmp.`user` w ON w.userFk = wtc.userFk + WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo + GROUP BY wtc.userFk,dated + ORDER BY userFk,dated + )sub + WHERE sub.timeWork > 0; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `timeControl_calculateAll` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `timeControl_calculateAll`(vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN + +/** + * @param vDatedFrom workerTimeControl + * @param vDatedTo workerTimeControl + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; + + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + SELECT userFk + FROM vn.worker w + JOIN vn.`user` u ON u.id = w.userFk + WHERE userFk IS NOT NULL; + + CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); + + DROP TEMPORARY TABLE tmp.`user`; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `timeControl_calculateByDepartment` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `timeControl_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN + +/** + * @param vDepartmentFk + * @param vDatedFrom workerTimeControl + * @param vDatedTo workerTimeControl + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; + + CREATE TEMPORARY TABLE tmp.`user` + SELECT DISTINCT w.userFk + FROM postgresql.business AS b + LEFT JOIN postgresql.profile AS pr ON pr.profile_id = b.client_id + LEFT JOIN postgresql.person AS p ON p.person_id = pr.person_id + LEFT JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id + LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id + LEFT JOIN vn.department AS d ON bl.department_id = d.id + WHERE ((b.date_start BETWEEN vDatedFrom AND vDatedTo OR b.date_end BETWEEN vDatedFrom AND vDatedTo) OR + (b.date_end IS NULL AND b.date_start <= vDatedTo) OR + (b.date_start <= vDatedFrom AND b.date_end >= vDatedTo) + ) AND bl.department_id = vDepartmentFk + ORDER BY b.date_end DESC; + + CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); + + DROP TEMPORARY TABLE tmp.`user`; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `timeControl_calculateByUser` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `timeControl_calculateByUser`(vUserFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN + +/** + * @param vUserFk + * @param vDatedFrom workerTimeControl + * @param vDatedTo workerTimeControl + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; + + CREATE TEMPORARY TABLE tmp.`user` + SELECT id userFk + FROM user + WHERE id = vUserFk; + CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); + + DROP TEMPORARY TABLE tmp.`user`; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `timeControl_calculateByWorker` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `timeControl_calculateByWorker`(vWorkerFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN + +/** + * @param vWorkerFk + * @param vDatedFrom workerTimeControl + * @param vDatedTo workerTimeControl + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; + + CREATE TEMPORARY TABLE tmp.`user` + SELECT u.id userFk + FROM vn.user u + JOIN vn.worker w ON w.userFk = u.id + WHERE w.id = vWorkerFk; + + CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); + + DROP TEMPORARY TABLE tmp.`user`; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `timeWorkerControl_check` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `timeWorkerControl_check`(vUserFk INT, vDated DATE,vTabletFk VARCHAR(100)) +proc: BEGIN +/** + * deprecated call workerTimeControl_check + */ +CALL vn.workerTimeControl_check(vUserFk,vDated,vTabletFk); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `travel_checkDates` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `travel_checkDates`(vShipped DATE, vLanded DATE) +BEGIN +/** + * Checks the landing/shipment dates of travel, throws an error + * ir they are not correct. + * + * @param vShipped The shipment date + * @param vLanded The landing date + */ + + IF vLanded < vShipped THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Landing cannot be lesser than shipment'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `travel_doRecalc` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `travel_doRecalc`() +BEGIN +/** + * Recounts the number of entries of changed travels. + */ + DECLARE vDone BOOL; + DECLARE vTravelFk INT; + DECLARE vTotalEntries INT; + + DECLARE cCur CURSOR FOR + SELECT travelFk FROM travelRecalc; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + OPEN cCur; + + myLoop: LOOP + SET vDone = FALSE; + FETCH cCur INTO vTravelFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + SELECT COUNT(*) INTO vTotalEntries + FROM entry + WHERE travelFk = vTravelFk; + + UPDATE travel + SET totalEntries = vTotalEntries + WHERE id = vTravelFk; + + DELETE FROM travelRecalc WHERE travelFk = vTravelFk; + END LOOP; + + CLOSE cCur; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `travel_requestRecalc` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `travel_requestRecalc`(vSelf INT) +proc: BEGIN +/** + * Adds a request to recount the number of entries for the travel. + * + * @param vSelf The travel reference + */ + IF vSelf IS NULL THEN + LEAVE proc; + END IF; + + INSERT IGNORE INTO travelRecalc SET travelFk = vSelf; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `travel_weeklyClone` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `travel_weeklyClone`(vSinceWeek INT, vToWeek INT) +BEGIN + DECLARE vCounter INT; + + SET vCounter = vSinceWeek; + vWeekLoop :LOOP + INSERT IGNORE INTO travel (shipped, landed, warehouseOutFk, warehouseInFk, agencyFk, ref, cargoSupplierFk) + SELECT @a := TIMESTAMPADD(DAY,vCounter * 7 - WEEKDAY(CURDATE()) - 1 + weekDay,CURDATE()), + @a := TIMESTAMPADD(DAY,duration,@a), + warehouseOutFk, + warehouseInFk, + agencyModeFk, + ref, + cargoSupplierFk + FROM travel_cloneWeekly; + IF vCounter = vToWeek THEN + LEAVE vWeekLoop; + END IF; + SET vCounter = vCounter + 1; + END LOOP; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `typeTagMake` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `typeTagMake`(vTypeFk INT) +BEGIN + + DELETE it.* + FROM itemTag it + JOIN item i ON i.id = it.itemFk + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, CONCAT(i.size,' cm'), 1 + FROM item i + JOIN tag t ON t.name = 'Longitud' COLLATE utf8_general_ci + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, i.category, 5 + FROM item i + JOIN tag t ON t.name = 'Categoria' COLLATE utf8_general_ci + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, ink.name, 2 + FROM item i + JOIN tag t ON t.name = 'Color' COLLATE utf8_general_ci + JOIN ink ON ink.id = i.inkFk + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, p.name, 3 + FROM item i + JOIN tag t ON t.name = 'Productor' COLLATE utf8_general_ci + JOIN producer p ON p.id = i.producerFk + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, o.name, 4 + FROM item i + JOIN tag t ON t.name = 'Origen' COLLATE utf8_general_ci + JOIN origin o ON o.id = i.originFk + WHERE i.typeFk = vTypeFk; + /* + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, i.stems, 6 + FROM item i + JOIN tag t ON t.name = 'Tallos' COLLATE utf8_general_ci + WHERE i.typeFk = vTypeFk; + */ +-- CALL itemTagArrangedUpdate(NULL); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `updatePedidosInternos` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `updatePedidosInternos`(vItemFk INT) +BEGIN + + UPDATE vn.item SET upToDown = 0 WHERE 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 DROP PROCEDURE IF EXISTS `warehouseFitting` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `warehouseFitting`(IN vWhOrigin INT , IN vWhDestiny INT) +BEGIN + DECLARE vCacheVisibleOriginFk INT; + DECLARE vCacheVisibleDestinyFk INT; + + CALL cache.visible_refresh(vCacheVisibleOriginFk, FALSE, vWhOrigin); + CALL cache.visible_refresh(vCacheVisibleDestinyFk, FALSE, vWhDestiny); + + SELECT i.id itemFk, + i.longName, + i.size, + i.subName, + vOrigin.visible AS Origen, + vDestiny.visible Destino + + FROM vn.item i + JOIN vn.itemType it ON it.id = i.typeFk + LEFT JOIN cache.visible vOrigin ON vOrigin.calc_id = vCacheVisibleOriginFk AND vOrigin.item_id = i.id + LEFT JOIN cache.visible vDestiny ON vDestiny.calc_id = vCacheVisibleDestinyFk AND vDestiny.item_id = i.id + WHERE (vOrigin.visible OR vDestiny.visible) + AND it.categoryFk < 6 + ORDER BY IF(vOrigin.visible,0,1), longName, size, subName; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `warehouseFitting_byTravel` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `warehouseFitting_byTravel`(IN vTravelFk INT) +BEGIN + + DECLARE vWhOrigin INT; + DECLARE vWhDestiny INT; + + SELECT warehouseInFk, warehouseOutFk INTO vWhDestiny, vWhOrigin + FROM vn.travel + WHERE id = vTravelFk; + + CALL vn.warehouseFitting(vWhOrigin, vWhDestiny); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerCalculateBoss` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerCalculateBoss`(vWorker INT) +BEGIN +/** +* Actualiza la tabla workerBosses +* vWorker: id del trabajador +* +*/ + DECLARE vBoss INT; + DECLARE vWorkerCompare INT DEFAULT vWorker; + + l: LOOP + SELECT bossFk INTO vBoss + FROM vn.worker + WHERE id=vWorkerCompare; + + IF vBoss=0 OR vWorkerCompare=vBoss THEN + LEAVE l; + END IF; + + REPLACE INTO vn.workerBosses(workerFk,bossFk) + VALUES(vWorker,vBoss); + + SET vWorkerCompare = vBoss; + + END LOOP; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerCreate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerCreate`( + vFirstname VARCHAR(50), + vSurnames VARCHAR(50), + vFi VARCHAR(9), + vWorkerCode CHAR(3), + vBossFk INT, + vUserFk INT +) +BEGIN +/** + * Create new worker + * + */ + INSERT INTO worker(code, firstName, lastName, fi, userFk, bossFk) + VALUES (vWorkerCode, vFirstname, vSurnames, vFi, vUserFk, vBossFk); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerCreateExternal` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerCreateExternal`( + vFirstName VARCHAR(50), + vSurname1 VARCHAR(50), + vSurname2 VARCHAR(50), + vUser VARCHAR(20), + vPassword VARCHAR(50), + vWorkerCode VARCHAR(3), + vRole INT(2) + ) +BEGIN + + DECLARE vUserId INT; + DECLARE vWorkerPako INT DEFAULT 2; + DECLARE vSurnames VARCHAR(100); + + INSERT INTO account.user(name,password,role) + SELECT vUser,MD5(vPassword),vRole; + + SET vUserId = LAST_INSERT_ID(); + /* + INSERT INTO vn.worker(firstName,lastName,bossFk,workerCode,user_id) + SELECT vFirstName,CONCAT(vSurname1,' ',vSurname2),2,vWorkerCode,vUser; + */ + + IF vSurname2 IS NULL THEN + SET vSurnames = vSurname1; + ELSE + SET vSurnames = CONCAT(vSurname1, ' ', vSurname2); + END IF; + + INSERT INTO vn2008.Trabajadores(Nombre, Apellidos, boss, CodigoTrabajador, user_id) + SELECT vFirstName, vSurnames, vWorkerPako, vWorkerCode, vUserId; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerDepartmentByDate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerDepartmentByDate`(vDate DATE) +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.workerDepartmentByDate; + CREATE TEMPORARY TABLE tmp.workerDepartmentByDate + ENGINE = MEMORY + SELECT + w.userFk, + p.name, + p.firstname, + d.name AS department, + d.department_id as departmentFk, + b.date_start, + d.production, + CAST(12 * blp.importepactado / clt.hours_week / 52 AS DECIMAL(10,2)) as costeHora + + FROM postgresql.person p + JOIN postgresql.profile pr ON p.person_id = pr.person_id + JOIN postgresql.business b ON b.client_id = pr.profile_id + JOIN postgresql.business_labour bl ON bl.business_id = b.business_id + JOIN postgresql.calendar_labour_type clt ON clt.calendar_labour_type_id = bl.calendar_labour_type_id + JOIN postgresql.business_labour_payroll blp ON blp.business_id = b.business_id + JOIN vn2008.department d ON d.department_id = bl.department_id + JOIN vn.worker w ON w.id = p.id_trabajador + WHERE b.date_start <= vDate AND IFNULL(b.date_end,'3000-01-01') > vDate + ; + + -- SELECT * FROM tmp.workerDepartmentByDate; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerDisable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `workerDisable`(vUserId int) +BEGIN + + DELETE FROM account.account + WHERE id = vUserId; + + UPDATE account.user + SET role = 2 + WHERE id = vUserId; + + DELETE FROM pbx.sip + WHERE user_id = vUserId; + + UPDATE `client` c + JOIN payMethod p ON p.name = 'CONTADO' + SET c.credit = 0, c.payMethodFk = p.id, hasCoreVnl = FALSE + WHERE c.id = vUserId; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerDisableAll` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerDisableAll`() +BEGIN + DECLARE done BOOL DEFAULT FALSE; + DECLARE vUserFk INT; + + DECLARE rs CURSOR FOR + SELECT a.id + FROM ((SELECT * FROM (select date_end,date_start,business_id, client_id + FROM postgresql.business + ORDER BY client_id, date_end IS NULL DESC , date_end DESC) + c GROUP BY client_id) c + INNER JOIN postgresql.business b ON c.client_id = b.client_id AND c.business_id = b.business_id + INNER JOIN postgresql.profile pr ON b.client_id = pr.profile_id + INNER JOIN postgresql.person p ON pr.person_id = p.person_id + + INNER JOIN vn.worker w ON p.id_trabajador = w.id) + INNER JOIN account.account a ON w.userFk = a.id + WHERE ((b.date_end) IS NOT NULL + AND (b.date_end) < CURDATE() + AND (b.date_end) > TIMESTAMPADD(DAY, -70,CURDATE()) ); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + OPEN rs; + + FETCH rs INTO vUserFk; + + WHILE NOT done DO + CALL workerDisable(vUserFk); + FETCH rs INTO vUserFk; + + END WHILE; + + CLOSE rs; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerForAllCalculateBoss` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerForAllCalculateBoss`() +BEGIN +/** +* Actualiza la tabla workerBosses utilizando el procedimiento +* vn.workerCalculateBoss(), actualiza todos los trabajadores en esa tabla +* +*/ + DECLARE vWorker INT; + DECLARE vDone BOOL; + + DECLARE cur CURSOR FOR + SELECT id FROM worker; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN cur; + + l: LOOP + SET vDone = FALSE; + FETCH cur INTO vWorker; + + IF vDone THEN + LEAVE l; + END IF; + + CALL workerCalculateBoss(vWorker); + END LOOP; + + CLOSE cur; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerJourneyReplace` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerJourneyReplace`(vFromDate DATE, vToDate DATE, vUserFk INT) +BEGIN + + /* Actualiza la tabla workerJourney para que actue como caché permanente revisable de las jornadas laborales. + * vUserFk es opcional. El valor 0 indica que se tenga en cuenta a todos los usuarios. + * + * PAK Julio '18 + */ + + DELETE + FROM workerJourney + WHERE dated BETWEEN vFromDate AND vToDate + AND isPaid = FALSE + AND isUpdated = FALSE + AND vUserFk IN (0,userFk); + + + -- Se inicia la tabla con todas las fechas posibles para cada uno de los trabajadores que han fichado en el rango de fechas. + INSERT IGNORE INTO workerJourney(userFk, dated, businessFk) + SELECT w.userFk, tm.dated, b.business_id + FROM vn.worker w + JOIN postgresql.person pe ON pe.id_trabajador = w.id + JOIN postgresql.profile p ON p.person_id = pe.person_id + JOIN postgresql.business b ON b.client_id = p.profile_id + JOIN postgresql.business_labour bl ON bl.business_id = b.business_id + JOIN vn.time tm ON tm.dated BETWEEN b.date_start AND IFNULL(b.date_end,CURDATE()) + WHERE b.date_start <= vToDate + AND IFNULL(b.date_end, CURDATE()) >= vFromDate + AND bl.porhoras + AND vUserFk IN (0,w.userFk); + + + + + + -- Se actualiza la cantidad total de horas prácticas, así como el tiempo de almuerzo remunerado, si corresponde + + /*UPDATE workerJourney wj + JOIN workerTimeControl_Journey j ON wj.dated = j.dated AND wj.userFk = j.userFk + SET wj.total = j.Journey, + wj.lunch = IF(j.Journey < 5,0,0.33) + WHERE wj.dated BETWEEN vFromDate AND vToDate + AND wj.isPaid = FALSE + AND wj.isUpdated = FALSE + AND vUserFk IN (0,wj.userFk); */ + + + IF vUserFk = 0 THEN + CALL vn.timeControl_calculateAll( vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59')); + ELSE + CALL vn.timeControl_calculateByUser( vUserFk, vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59')); + END IF; + + UPDATE workerJourney wj + JOIN tmp.timeControlCalculate t ON wj.dated = t.dated AND wj.userFk = t.userFk + SET wj.total = CAST(IF(t.timeWorkDecimal >= 5.33,t.timeWorkDecimal-0.33,t.timeWorkDecimal) AS DECIMAL (10,2)), + wj.lunch = IF(t.timeWorkDecimal >= 5.33,0.33,0) + WHERE wj.dated BETWEEN vFromDate AND vToDate + AND wj.isPaid = FALSE + AND wj.isUpdated = FALSE + AND vUserFk IN (0,wj.userFk); + + DROP TEMPORARY TABLE tmp.timeControlCalculate; + + + + /********** NOCTURNIDAD ************/ + DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControl; + + CREATE TEMPORARY TABLE tmp.workerTimeControl + SELECT w.*, 0 as Non + FROM vn.workerTimeControl w + WHERE timed BETWEEN vFromDate AND vToDate + AND vUserFk IN (0,userFk) + ORDER BY userFk, timed; + + -- Regalamos un segundo para evitar que hayan fichadas en las horas claves de inicio y fin de la nocturnidad. + UPDATE tmp.workerTimeControl + SET timed = TIMESTAMPADD(SECOND,-1,timed) + WHERE TIME(timed) IN ('06:00:00','22:00:00'); + + -- Fichada virtual a las 6:00 h, hora en que empieza la jornada diurna + INSERT INTO tmp.workerTimeControl(userFk, timed) + SELECT userFk, TIMESTAMPADD(HOUR, 6, DATE(timed)) + FROM vn.workerTimeControl + WHERE vUserFk IN (0,userFk) + GROUP BY userFk, DATE(timed); + + -- Fichada virtual a las 22:00 h, momento en que empieza la jornada nocturna. + INSERT INTO tmp.workerTimeControl(userFk, timed) + SELECT userFk, TIMESTAMPADD(HOUR, 22, DATE(timed)) + FROM vn.workerTimeControl + WHERE vUserFk IN (0,userFk) + GROUP BY userFk, DATE(timed); + + -- Establece el orden en que se han de leer las fichadas + CALL vn.workerTimeControlSetOrder; + + -- Marca los impares para facilitar la consulta siguiente + UPDATE tmp.workerTimeControl + SET Non = 1 + WHERE `order` mod 2; + + -- Actualizamos la nocturnidad + UPDATE workerJourney wj + JOIN + ( SELECT userFk, Dia, sum(Nocturnidad) as Nocturnidad FROM + ( + SELECT userFk, + date(timed) as Dia, + (( + IF( TIME(timed) < '06:00:00' OR (TIME(timed) = '06:00:00' AND Non = FALSE ) , IF(Non,-1,1),0) + + + IF(TIME(timed) > '22:00:00' OR (TIME(timed) = '22:00:00' AND Non = TRUE), If(Non,-1,1),0) + ) + * (HOUR(`timed`) + MINUTE(`timed`) / 60) + ) as Nocturnidad + FROM tmp.workerTimeControl + ) sub + GROUP BY Dia, userFk + HAVING Nocturnidad + ) night ON night.userFk = wj.userFk AND night.Dia = wj.dated + SET wj.nocturn = night.Nocturnidad + WHERE wj.isPaid = FALSE AND isUpdated = FALSE; + + -- Horas téoricas y precio de la hora ordinaria + UPDATE vn.workerJourney wj + JOIN postgresql.business_labour_payroll blp ON blp.business_id = wj.businessFk + JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk + JOIN postgresql.calendar_labour_type pclt ON pclt.calendar_labour_type_id = bl.calendar_labour_type_id + SET wj.priceOrdinaryHour = (12 * blp.importepactado) / (52 * pclt.hours_week), + wj.contractJourney = pclt.hours_week/5 + WHERE wj.dated BETWEEN vFromDate AND vToDate + AND vUserFk IN (0,wj.userFk) + AND wj.isPaid = FALSE + AND isUpdated = FALSE; + + -- Precio Extras, Vacaciones y Nocturnas + UPDATE vn.workerJourney wj + JOIN + ( + SELECT dated, hollidayInc, nightInc, extraInc + FROM ( + SELECT tm.dated , hollidayInc, nightInc, extraInc + FROM vn.time tm + JOIN vn.workerHourPrice whp ON tm.dated >= whp.dated + ORDER BY tm.dated, whp.dated DESC + ) sub + GROUP BY dated + ) conv ON conv.dated = wj.dated + SET wj.priceHollydayHour = wj.priceOrdinaryHour * conv.hollidayInc, + wj.priceNocturnHour = wj.priceOrdinaryHour * conv.nightInc, + wj.priceExtraHour = wj.priceOrdinaryHour * conv.extraInc + WHERE wj.dated BETWEEN vFromDate AND vToDate + AND vUserFk IN (0,wj.userFk) + AND wj.isPaid = FALSE + AND wj.isUpdated = FALSE; + + -- Elimina el precio de las horas extras para los contratos parciales. + UPDATE vn.workerJourney wj + JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk + JOIN postgresql.calendar_labour_type clt ON clt.calendar_labour_type_id = bl.calendar_labour_type_id + SET wj.priceExtraHour = 0 + WHERE clt.isPartial + AND wj.dated BETWEEN vFromDate AND vToDate + AND vUserFk IN (0,wj.userFk) + AND wj.isPaid = FALSE + AND wj.isUpdated = FALSE; + + -- Bajas, vacaciones y festivos personales + /* UPDATE vn.workerJourney wj + JOIN postgresql.calendar_employee pce ON pce.date = wj.dated AND pce.business_id = wj.businessFk + JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk + SET wj.permission = IF(pce.calendar_state_id = 6, 0.5, 1) * wj.contractJourney, + wj.contractJourney = IF(pce.calendar_state_id = 6, 0.5, 0) * wj.contractJourney,-- Vacaciones medio dia + wj.hollyday = wj.total - IF(pce.calendar_state_id = 6, 0.5, 0) * wj.contractJourney + WHERE wj.dated BETWEEN vFromDate AND vToDate + AND vUserFk IN (0,wj.userFk) + AND wj.isPaid = FALSE + AND wj.isUpdated = FALSE;*/ + + UPDATE vn.workerJourney wj + JOIN postgresql.calendar_employee pce ON pce.date = wj.dated AND pce.business_id = wj.businessFk + JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk + JOIN postgresql.calendar_state cs ON cs.calendar_state_id = pce.calendar_state_id + SET wj.permission = cs.permissionRate * wj.contractJourney, + wj.contractJourney = IF(cs.permissionRate = 1, 0, cs.permissionRate) * wj.contractJourney, + wj.hollyday = wj.total - IF(cs.permissionRate = 1, 0, cs.permissionRate) * wj.contractJourney + WHERE cs.permissionRate > 0 + AND wj.dated BETWEEN vFromDate AND vToDate + AND vUserFk IN (0,wj.userFk) + AND wj.isPaid = FALSE + AND wj.isUpdated = FALSE; + + + + + -- Festivos por centro de trabajo + UPDATE vn.workerJourney wj + JOIN postgresql.calendar_labour pcl ON pcl.day = wj.dated + JOIN postgresql.business_labour pbl ON wj.businessFk = pbl.business_id AND pbl.workcenter_id = pcl.workcenter_id + SET wj.hollyday = wj.total, + wj.permission = wj.contractJourney, + wj.contractJourney = 0 + WHERE wj.dated BETWEEN vFromDate AND vToDate + AND vUserFk IN (0,wj.userFk) + AND wj.isPaid = FALSE + AND wj.isUpdated = FALSE; + + -- Domingos + UPDATE vn.workerJourney + SET hollyday = total, + contractJourney = 0 + WHERE weekday(dated) = 6 + AND dated BETWEEN vFromDate AND vToDate + AND vUserFk IN (0,userFk) + AND isPaid = FALSE + AND isUpdated = FALSE; + + -- Sábados + UPDATE vn.workerJourney + SET contractJourney = 0 + WHERE weekday(dated) = 5 + AND dated BETWEEN vFromDate AND vToDate + AND vUserFk IN (0,userFk) + AND isPaid = FALSE + AND isUpdated = FALSE; + + + -- Horas extras + UPDATE workerJourney + SET extra = lunch + total - contractJourney + WHERE dated BETWEEN vFromDate AND vToDate + AND vUserFk IN (0,userFk) + AND isPaid = FALSE + AND isUpdated = FALSE; + + -- Contratos NO por horas + INSERT IGNORE INTO workerJourney( userFk, + dated, + businessFk, + priceOrdinaryHour, + contractJourney, + total) + SELECT w.userFk, + tm.dated, + b.business_id, + (12 * blp.importepactado) / (52 * pclt.hours_week) as priceOrdinaryHour, + IF(weekday(tm.dated) IN (5,6),0, pclt.hours_week/5) as contractJourney, + IF(weekday(tm.dated) IN (5,6),0, pclt.hours_week/5) as total + FROM vn.worker w + JOIN postgresql.person pe ON pe.id_trabajador = w.id + JOIN postgresql.profile p ON p.person_id = pe.person_id + JOIN postgresql.business b ON b.client_id = p.profile_id + JOIN postgresql.business_labour bl ON bl.business_id = b.business_id + JOIN postgresql.calendar_labour_type pclt ON pclt.calendar_labour_type_id = bl.calendar_labour_type_id + JOIN postgresql.business_labour_payroll blp ON blp.business_id = b.business_id + JOIN vn.time tm ON tm.dated BETWEEN b.date_start AND IFNULL(b.date_end,CURDATE()) + WHERE b.date_start <= vToDate + AND IFNULL(b.date_end, CURDATE()) >= vFromDate + AND bl.porhoras = FALSE + AND vUserFk IN (0,w.userFk); + + -- Elimina dias sin fichadas ni contrato + /* DELETE FROM workerJourney + WHERE contractJourney = 0 + AND total = 0 + AND permission = 0 + AND dated BETWEEN vFromDate AND vToDate + AND vUserFk IN (0,userFk) + AND isPaid = FALSE + AND isUpdated = FALSE; +*/ +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerJourneyReplaceLauncher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerJourneyReplaceLauncher`() +BEGIN + + DECLARE vDateStart DATE; + DECLARE vDateEnd DATE; + + SET vDateStart = TIMESTAMPADD(MONTH,-1,CURDATE()); + SET vDateEnd = util.yesterday(); + + CALL vn.workerJourneyReplace(vDateStart,vDateEnd,0); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerJourney_Replace` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerJourney_Replace`(vFromDate DATE, vToDate DATE, vUserFk INT) +BEGIN + /* Actualiza la tabla workerJourney para que actue como caché permanente revisable de las jornadas laborales. + * vUserFk es opcional. El valor 0 indica que se tenga en cuenta a todos los usuarios.8 + */ + + DELETE FROM workerJourney + WHERE dated BETWEEN vFromDate AND vToDate + AND IFNULL(vUserFk, userFk) = userFk; + + IF vUserFk IS NULL THEN + CALL vn.timeControl_calculateAll( vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59')); + CALL vn.timeBusiness_calculateAll( vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59')); + ELSE + CALL vn.timeControl_calculateByUser( vUserFk, vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59')); + CALL vn.timeBusiness_calculateByUser( vUserFk, vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59')); + END IF; + + -- Se inicia la tabla con todas las fechas posibles para cada uno de los trabajadores que han fichado en el rango de fechas. + INSERT IGNORE INTO workerJourney(userFk, dated, businessFk) + SELECT tbc.userFk, tbc.dated, tbc.businessFk + FROM tmp.timeBusinessCalculate tbc; + + -- Se actualiza la cantidad total de horas prácticas, así como el tiempo de almuerzo remunerado, si corresponde + UPDATE workerJourney wj + JOIN tmp.timeControlCalculate t ON wj.dated = t.dated AND wj.userFk = t.userFk + SET wj.total = CAST(IF(t.timeWorkDecimal >= 5.33,t.timeWorkDecimal-0.33,t.timeWorkDecimal) AS DECIMAL (10,2)), + wj.lunch = IF(t.timeWorkDecimal >= 5.33,0.33,0) + WHERE wj.dated BETWEEN vFromDate AND vToDate + AND wj.isPaid = FALSE + AND wj.isUpdated = FALSE + AND IFNULL(vUserFk, wj.userFk) = wj.userFk; + + DROP TEMPORARY TABLE tmp.timeControlCalculate; + + /********** NOCTURNIDAD ************/ + DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControl; + + CREATE TEMPORARY TABLE tmp.workerTimeControl + SELECT w.*, 0 as Non + FROM vn.workerTimeControl w + WHERE timed BETWEEN vFromDate AND vToDate + AND IFNULL(vUserFk, userFk) = userFk + ORDER BY userFk, timed; + + -- Regalamos un segundo para evitar que hayan fichadas en las horas claves de inicio y fin de la nocturnidad. + UPDATE tmp.workerTimeControl + SET timed = TIMESTAMPADD(SECOND,-1,timed) + WHERE TIME(timed) IN ('06:00:00','22:00:00'); + + -- Fichada virtual a las 6:00 h, hora en que empieza la jornada diurna + INSERT INTO tmp.workerTimeControl(userFk, timed) + SELECT userFk, TIMESTAMPADD(HOUR, 6, DATE(timed)) + FROM vn.workerTimeControl + WHERE IFNULL(vUserFk, userFk) = userFk + GROUP BY userFk, DATE(timed); + + -- Fichada virtual a las 22:00 h, momento en que empieza la jornada nocturna. + INSERT INTO tmp.workerTimeControl(userFk, timed) + SELECT userFk, TIMESTAMPADD(HOUR, 22, DATE(timed)) + FROM vn.workerTimeControl + WHERE IFNULL(vUserFk, userFk) = userFk + GROUP BY userFk, DATE(timed); + + -- Establece el orden en que se han de leer las fichadas + CALL vn.workerTimeControlSetOrder; + + -- Marca los impares para facilitar la consulta siguiente + UPDATE tmp.workerTimeControl + SET Non = 1 + WHERE `order` mod 2; + + -- Actualizamos la nocturnidad + UPDATE workerJourney wj + JOIN + (SELECT userFk, Dia, sum(Nocturnidad) as Nocturnidad FROM + (SELECT userFk, + date(timed) as Dia, + ((IF( TIME(timed) < '06:00:00' OR (TIME(timed) = '06:00:00' AND Non = FALSE ) , IF(Non,-1,1),0) + +IF(TIME(timed) > '22:00:00' OR (TIME(timed) = '22:00:00' AND Non = TRUE), If(Non,-1,1),0) + )* (HOUR(`timed`) + MINUTE(`timed`) / 60) + ) as Nocturnidad + FROM tmp.workerTimeControl + ) sub + GROUP BY Dia, userFk + HAVING Nocturnidad + ) night ON night.userFk = wj.userFk AND night.Dia = wj.dated + SET wj.nocturn = night.Nocturnidad + WHERE wj.isPaid = FALSE AND isUpdated = FALSE; + + + -- Precios de hora ordinaria, Extras, Vacaciones y Nocturnas + -- Falta importe pactado en el procedimiento ¿? + UPDATE vn.workerJourney wj + JOIN postgresql.business_labour_payroll blp ON blp.business_id = wj.businessFk + JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk + JOIN postgresql.calendar_labour_type pclt ON pclt.calendar_labour_type_id = bl.calendar_labour_type_id + JOIN (SELECT dated, hollidayInc, nightInc, extraInc + FROM ( SELECT tm.dated , hollidayInc, nightInc, extraInc + FROM vn.time tm + JOIN vn.workerHourPrice whp ON tm.dated >= whp.dated + ORDER BY tm.dated, whp.dated DESC + ) sub + GROUP BY dated + ) conv ON conv.dated = wj.dated + SET + wj.priceOrdinaryHour = @priceOrdinaryHour := FORMAT((12 * blp.importepactado) / (52 * pclt.hours_week),2), + wj.priceHollydayHour = @priceOrdinaryHour * conv.hollidayInc, + wj.priceNocturnHour = @priceOrdinaryHour * conv.nightInc, + wj.priceExtraHour = @priceOrdinaryHour * conv.extraInc + WHERE wj.dated BETWEEN vFromDate AND vToDate + AND IFNULL(vUserFk, userFk) = userFk + AND wj.isPaid = FALSE + AND isUpdated = FALSE; + + -- Horas téoricas bajas, vacaciones y festivos personales + UPDATE vn.workerJourney wj + JOIN tmp.timeBusinessCalculate b ON b.dated = wj.dated AND b.userFk = wj.userFk + SET wj.permission = b.timeBusinessDecimal * b.permissionRate, + wj.contractJourney = b.timeWorkDecimal + WHERE wj.dated BETWEEN vFromDate AND vToDate + AND IFNULL(vUserFk, wj.userFk) = wj.userFk + AND wj.isPaid = FALSE + AND wj.isUpdated = FALSE; + + UPDATE vn.workerJourney wj + JOIN tmp.timeBusinessCalculate b ON b.dated = wj.dated AND b.userFk = wj.userFk + SET wj.hollyday = wj.total - b.timeWorkDecimal + WHERE wj.dated BETWEEN vFromDate AND vToDate + AND IFNULL(vUserFk, wj.userFk) = wj.userFk + AND wj.isPaid = FALSE + AND wj.isUpdated = FALSE + AND b.permissionRate > 0 ; + + -- Horas extras + UPDATE workerJourney + SET extra = lunch + total - contractJourney + WHERE dated BETWEEN vFromDate AND vToDate + AND IFNULL(vUserFk, userFk) = userFk + AND isPaid = FALSE + AND isUpdated = FALSE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControlAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControlAdd`(IN vUserFk INT, IN vWarehouseFk INT, IN vDated DATETIME) +BEGIN + + /*INSERT INTO workerTimeControl(userFk, timed, manual, warehouseFk) + VALUES(vUserFk, vDated, FALSE, vWarehouseFk); + + CALL vn.workerTimeControlSOWP(vUserFk , vDated);*/ + + CALL vn.workerTimeControl_add(vUserFk,vWarehouseFk,NOW(),FALSE); + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControlNonDays` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControlNonDays`() +BEGIN + + SELECT wtc.userFk, date(wtc.timed) as Fecha , COUNT(wtc.`order`) as maxOrder, c.name as worker, wb.code as Boss, CONCAT (au.name, "@verdnatura.es") AS bossMail + FROM workerTimeControl wtc + JOIN worker w ON w.userFk = wtc.userFk + LEFT JOIN worker wb ON wb.id = w.bossFk + JOIN client c ON c.id = wtc.userFk + LEFT JOIN account.user au ON au.id = wb.userFK + WHERE timed BETWEEN TIMESTAMPADD(YEAR,-5,CURDATE()) AND CURDATE() + GROUP BY userFk, date(timed) + HAVING maxOrder mod 2 = 1 + ORDER BY Boss; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControlPinGenerate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControlPinGenerate`( + vWorkerFk INT) +BEGIN +/** + * Create new pin for workerFk or new pin for all workers if vWorkerFk is null + * + */ + + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControlSetOrder` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControlSetOrder`() +BEGIN + + SET @order := 1; + SET @userFk := 0; + SET @day := 0; + + UPDATE tmp.workerTimeControl + SET `order` = IF(userFk = @userFk AND day(timed) = @day, @order := @order + 1, @order := 1), + userFk = @userFk := userFk, + manual = manual + (0 * @day := day(timed)) + ORDER BY userFk, timed; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControlSetOrder_by_User_and_dateRange` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControlSetOrder_by_User_and_dateRange`(vUserFk INT, vStarted DATE, vFinished DATE) +BEGIN + + SET @order := 0; + SET @day := '2000-01-01'; + + UPDATE vn.workerTimeControl w + SET w.`order` = @order := IF(@day = @day := date(timed), @order, 0) + 1 + WHERE w.userFk = vUserFk + AND w.timed BETWEEN vStarted AND util.dayend(vFinished) + ORDER BY w.timed; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControlSOWP` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControlSOWP`(IN vUserFk INT, IN vDated DATE) +BEGIN + SET @order := 0; + + UPDATE workerTimeControl + SET `order` = @order := @order + 1 + WHERE vUserFk =userFk + AND vDated = DATE(timed) + ORDER BY timed; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL) +BEGIN + SELECT vn.workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); + CALL vn.workerTimeControlSOWP(vUserFk, vTimed); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_add__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_add__`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL) +BEGIN + + DECLARE vDirection VARCHAR(6); + DECLARE vLastIn DATETIME; + DECLARE vDayStayMax INT; + DECLARE vHasDirectionOut INT; + + SELECT dayStayMax INTO vDayStayMax + FROM vn.workerTimeControlParams; + + SELECT vn.timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; + + IF vDirection = 'out' THEN + + SELECT MAX(timed) INTO vLastIn + FROM vn.workerTimeControl + WHERE userFk = vUserFk + AND direction = 'in' + AND timed < vTimed; + + UPDATE vn.workerTimeControl wtc + SET wtc.direction = 'middle' + WHERE userFk = vUserFk + AND direction = 'out' + AND timed BETWEEN vLastIn AND vTimed; + + ELSE IF vDirection = 'in' THEN + + SELECT COUNT(*) INTO vHasDirectionOut + FROM vn.workerTimeControl wtc + WHERE userFk = vUserFk + AND direction = 'out' + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + + UPDATE vn.workerTimeControl wtc + SET wtc.direction = IF (vHasDirectionOut,'middle','out') + WHERE userFk = vUserFk + AND direction = 'in' + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + + END IF; + END IF; + + INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) + VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); + + CALL vn.workerTimeControlSOWP(vUserFk, vTimed); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_check` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_check`(vUserFk INT, vDated DATE,vTabletFk VARCHAR(100)) +proc: BEGIN +/** + * Verifica si el empleado puede fichar en el momento actual, si puede fichar llama a vn.workerTimeControlAdd + * + * @param vUserFk Identificador del trabajador + * @return Retorna si encuentra un problema 'odd','maxTimeWork','breakDay','breakWeek' ; + * En caso de tener algun problema retorna el primero que encuentra + */ + DECLARE vLastIn DATETIME ; + DECLARE vLastOut DATETIME ; + DECLARE vDayWorkMax INT; + DECLARE vDayBreak INT; + DECLARE vWeekBreak INT ; + DECLARE vWeekScope INT; + DECLARE vDayStayMax INT; + DECLARE vProblem VARCHAR(20) DEFAULT NULL; + DECLARE vTimedWorked INT; + DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL; + DECLARE vDepartmentFk INT; + + SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax + INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax + FROM vn.workerTimeControlParams; + + SELECT MAX(timed) INTO vLastIn + FROM vn.workerTimeControl + WHERE userFk = vUserFk + AND direction = 'in'; + + SELECT MAX(timed) INTO vLastOut + FROM vn.workerTimeControl + WHERE userFk = vUserFk + AND direction = 'out'; + + IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA + + -- VERIFICAR DESCANSO DIARIO + IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN + SELECT "Descansos 12 h" AS problem; + LEAVE proc; + END IF; + + -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ + IF (SELECT MOD(COUNT(*),2) -- <>0 + FROM vn.workerTimeControl + WHERE userFk = vUserFk + AND timed >= vLastIn + ) THEN + SELECT "Dias con fichadas impares" AS problem; + LEAVE proc; + END IF; + + -- VERIFICAR VACACIONES + SELECT cs.type INTO vCalendarStateType + FROM postgresql.calendar_employee ce + JOIN postgresql.business b USING(business_id) + JOIN postgresql.profile pr ON pr.profile_id = b.client_id + JOIN postgresql.person p ON p.person_id = pr.person_id + JOIN postgresql.calendar_state cs USING(calendar_state_id) + JOIN vn.worker w ON w.id = p.id_trabajador + WHERE ce.date = CURDATE() + AND cs.isAllowedToWork = FALSE + AND w.userFk = vUserFk + LIMIT 1; + + IF(LENGTH(vCalendarStateType)) THEN + SELECT vCalendarStateType AS problem; + LEAVE proc; + END IF; + + + -- VERIFICAR CONTRATO EN VIGOR + IF (SELECT COUNT(*) + FROM postgresql.business b + JOIN postgresql.profile pr ON pr.profile_id = b.client_id + JOIN postgresql.person p ON p.person_id = pr.person_id + JOIN vn.worker w ON w.id = p.id_trabajador + WHERE w.userFk = vUserFk + AND b.date_start <= vDated + AND IFNULL(b.date_end,vDated) >= vDated + ) = 0 THEN + SELECT "No hay un contrato en vigor" AS problem; + LEAVE proc; + END IF; + + -- VERIFICAR DESCANSO SEMANAL + SET @vHasBreakWeek:= FALSE; + SET @vLastTimed:= UNIX_TIMESTAMP((NOW() - INTERVAL vWeekScope SECOND)); + + DROP TEMPORARY TABLE IF EXISTS tmp.trash; + CREATE TEMPORARY TABLE tmp.trash + SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias, + @vLastTimed:= UNIX_TIMESTAMP(timed) + FROM workerTimeControl + WHERE timed>= (NOW() - INTERVAL vWeekScope SECOND) + AND userFk= vUserFk + AND direction IN ('in','out') + ORDER BY timed ASC; + + IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA + SELECT "Descansos 36 h" AS problem; + LEAVE proc; + END IF; + + DROP TEMPORARY TABLE tmp.trash; + + ELSE -- DIA ACTUAL + + -- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO + SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(NOW()), 0) INTO vTimedWorked + FROM vn.workerTimeControl wtc + WHERE userFk = vUserFk + AND timed >= vLastIn + ORDER BY timed; + + IF vTimedWorked > vDayWorkMax THEN + SELECT "Jornadas" AS problem; + LEAVE proc; + END IF; + + END IF; + + -- VERIFICAR DEPARTAMENTO + IF vTabletFk IS NOT NULL THEN + SELECT wtcu.departmentFk INTO vDepartmentFk + FROM vn.workerTimeControlUserInfo wtcu + WHERE wtcu.userFk = vUserFk; + IF (SELECT COUNT(td.tabletFk) + FROM vn.tabletDepartment td + WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk + ) = 0 THEN + SELECT "No perteneces a este departamento." AS problem; + LEAVE proc; + END IF; + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_remove` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_remove`(IN vUserFk INT, IN vTimed DATETIME) +BEGIN + + DECLARE vDirectionRemove VARCHAR(6); + DECLARE vDirectionPrevious VARCHAR(6); + DECLARE vTimedPrevious DATETIME; + + SELECT direction INTO vDirectionRemove + FROM vn.workerTimeControl + WHERE userFk = vUserFk + AND timed = vTimed ; + + IF vDirectionRemove = 'out' THEN + + SELECT timed, direction INTO vTimedPrevious, vDirectionPrevious + FROM vn.workerTimeControl + WHERE userFk = vUserFk + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + IF vDirectionPrevious = "middle" THEN + UPDATE vn.workerTimeControl + SET direction = "out" + WHERE userFk = vUserFk + AND timed = vTimedPrevious; + END IF; + + ELSE IF vDirectionRemove = 'in' THEN + + UPDATE vn.workerTimeControl + SET direction = "in" + WHERE userFk = vUserFk + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + END IF; + + END IF; + + DELETE FROM vn.workerTimeControl + WHERE userFk = vUserFk + AND timed = vTimed; + + CALL vn.workerTimeControlSOWP(vUserFk, vTimed); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_repair` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_repair`() +proc: BEGIN +/** + * Corrige las fichadas + * + */ + +/*1- poner todos a middle*/ +UPDATE vn.workerTimeControl SET direction = 'middle'; + +/*2- poner los out*/ +UPDATE vn.workerTimeControl wtc + JOIN + (SELECT userFk,MAX(timed) maxTimed FROM + (SELECT id, userFk, timed, date(timed) dated + FROM vn.workerTimeControl + ) sub + GROUP BY userFk,dated + )sub + SET direction = "out" + WHERE wtc.userFk = sub.userFk + AND wtc.timed = sub.maxTimed; + + /*3- poner los in*/ +UPDATE vn.workerTimeControl wtc + JOIN + (SELECT userFk,MIN(timed) maxTimed FROM + (SELECT id, userFk, timed, date(timed) dated + FROM vn.workerTimeControl + ) sub + GROUP BY userFk,dated + )sub + SET direction = "in" + WHERE wtc.userFk = sub.userFk + AND wtc.timed = sub.maxTimed ; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerWeekControl` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerWeekControl`(vUserFk INT, vDated DATE, vTabletFk VARCHAR(100)) +BEGIN + +/* Devuelve la cantidad de descansos de 12h y de 36 horas que ha disfrutado el trabajador +* en la semana inmediatamente anterior a la fecha que pasa como parámetro. +* +* UPDATED PAK 2019/09/02 +* PENDING REVIEW +*/ + +DECLARE vDescansos12h INT; +DECLARE vDescansos36h INT; +DECLARE vJornadas INT; +DECLARE vImpares INT; +DECLARE vHasSignedToday BOOLEAN; +DECLARE v12hoursInMinutes INT DEFAULT 719; +DECLARE v36hoursInMinutes INT DEFAULT 2159; +DECLARE vCantWork VARCHAR(50) DEFAULT ''; +DECLARE vDepartmentFk INT; +DECLARE isEnabled BOOLEAN DEFAULT TRUE; + + +SELECT COUNT(*) INTO vHasSignedToday + FROM vn.workerTimeControl WHERE timed >= vDated AND userFk = vUserFk; + +SET @day := 0; +SET @lastTimed := NOW(); + +SELECT SUM(IF(interval_in_minutes >= v12hoursInMinutes,1,0)), SUM(FLOOR(interval_in_minutes/ v36hoursInMinutes)) , SUM(jornadas) + INTO vDescansos12h, vDescansos36h, vJornadas + FROM + ( + SELECT fichada_anterior, fichada_actual, interval_in_minutes, jornadas + FROM + ( + SELECT @lastTimed fichada_anterior, + timed, + CAST(time_to_sec(timediff(timed,@lastTimed )) / 60 AS UNSIGNED) as interval_in_minutes, + IF(day(timed) != @day, 1, 0) as jornadas, + @day := day(timed) dia_del_mes, + @lastTimed := timed fichada_actual + FROM + ( + SELECT day(timed) as dayNumber, dayname(timed) as dayName, timed + FROM + (SELECT TIMESTAMPADD(DAY, -11, NOW()) as timed, vUserFk as userFk -- Fichada virtual para los en los que no se ha trabajado la semana anterior + UNION ALL + SELECT timed, userFk + FROM vn.workerTimeControl wtc + WHERE userFk = vUserFk + AND timed >= TIMESTAMPADD(DAY, -10,vDated) + UNION ALL + SELECT IF(vHasSignedToday, '2000-01-01 00:00', NOW()) as timed, vUserFk + ) sub4 + ORDER BY timed + ) sub + + ) sub2 + WHERE fichada_actual >= TIMESTAMPADD(WEEK, -1, vDated) + ) sub3 ; + +SELECT IFNULL(SUM(impar),0) into vImpares +FROM ( + SELECT day(timed) as dayNumber, + count(*) mod 2 as impar + FROM vn.workerTimeControl wtc + WHERE userFk = vUserFk + AND timed >= TIMESTAMPADD(WEEK, -1,vDated) AND timed < vDated + GROUP BY dayNumber + ) sub; + +-- Vacaciones +SELECT cs.type INTO vCantWork + FROM postgresql.calendar_employee ce + JOIN postgresql.business b USING(business_id) + JOIN postgresql.profile pr ON pr.profile_id = b.client_id + JOIN postgresql.person p ON p.person_id = pr.person_id + JOIN postgresql.calendar_state cs USING(calendar_state_id) + JOIN vn.worker w ON w.id = p.id_trabajador + WHERE ce.date = CURDATE() + AND cs.isAllowedToWork = FALSE + AND w.userFk = vUserFk + LIMIT 1; + +-- Contrato en vigor +SELECT IF(COUNT(*),vCantWork,'Sin contrato') INTO vCantWork + FROM postgresql.business b + JOIN postgresql.profile pr ON pr.profile_id = b.client_id + JOIN postgresql.person p ON p.person_id = pr.person_id + JOIN vn.worker w ON w.id = p.id_trabajador + WHERE w.userFk = vUserFk + AND b.date_start <= vDated + AND IFNULL(b.date_end,vDated) >= vDated; + +-- Departamento si vTabletFk es 0 no hacemos comprobacion (Madrid y Vilassar) +IF vTabletFk <> '0' THEN +-- 1 Obtener el departamento del usuario + SELECT wtcu.departmentFk INTO vDepartmentFk + FROM vn.workerTimeControlUserInfo wtcu + WHERE wtcu.userFk = vUserFk; +-- 2 Comprobar si la tablet pertenece al departamento + SELECT COUNT(td.tabletFk) INTO isEnabled + FROM vn.tabletDepartment td + WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk; + +END IF; + + + +IF vJornadas IS NOT NULL THEN + + SELECT 'Jornadas' as Item, vJornadas as Cantidad, 'Correcto' AS Análisis + + UNION ALL + + SELECT 'Descansos 12 h' as Item, vDescansos12h as Cantidad, IF(vDescansos12h >= vJornadas, 'Correcto','Error: 1 por jornada') as Análisis + + UNION ALL + + SELECT 'Descansos 36 h' as Item, vDescansos36h as Cantidad, IF(vDescansos36h / 2 >= FLOOR(vJornadas/10), 'Correcto','Error: mínimo 2 cada 14 dias') as Análisis + + UNION ALL + + SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, IF(vImpares = 0, 'Correcto','Error') as Análisis + + UNION ALL + + SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, + '' as Cantidad, + IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis + + UNION ALL + + SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis + + ; + +ELSE + + + SELECT 'Jornadas' as Item, vJornadas as Cantidad, 'Correcto' AS Análisis + + UNION ALL + + SELECT 'Descansos 12 h' as Item, vDescansos12h as Cantidad, 'Correcto' as Análisis + + UNION ALL + + SELECT 'Descansos 36 h' as Item, vDescansos36h as Cantidad, 'Correcto' as Análisis + + UNION ALL + + SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, 'Correcto' as Análisis + + UNION ALL + + SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, + '' as Cantidad, IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis + + UNION ALL + + SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis + ; + +END IF; + + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerWeekTiming` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerWeekTiming`(vUserFk INT, vDated DATE) +BEGIN + +/* +* Muestra una tabla con los 7 dias inmediatamente anteriores a la fecha proporcionada +* y las fichadas de cada dia, en columnas por dia +* +*/ + +CALL vn.workerTimeControlSetOrder_by_User_and_dateRange(vUserFk,TIMESTAMPADD(DAY,-8,vDated),vDated); + +DROP TEMPORARY TABLE IF EXISTS tmp.workerWeekTiming; +CREATE TEMPORARY TABLE tmp.workerWeekTiming +SELECT orden `orden`, + max(hace7dias) 7_dias_antes, + max(hace6dias) 6_dias_antes, + max(hace5dias) 5_dias_antes, + max(hace4dias) 4_dias_antes, + max(hace3dias) 3_dias_antes, + max(antesdeayer) 2_dias_antes, + max(ayer) 1_dia_antes, + max(hoy) mismo_dia + FROM + ( + SELECT IF(dias = 7, fichada, '') as hace7dias, + IF(dias = 6, fichada, '') as hace6dias, + IF(dias = 5, fichada, '') as hace5dias, + IF(dias = 4, fichada, '') as hace4dias, + IF(dias = 3, fichada, '') as hace3dias, + IF(dias = 2, fichada, '') as antesdeayer, + IF(dias = 1, fichada, '') as ayer, + IF(dias = 0, fichada, '') as hoy, + orden + + FROM + ( + SELECT `order` as orden, datediff(vDated, timed) as dias, date(timed) as fecha, TIME_FORMAT(timed,'%H:%i') as fichada + FROM vn.workerTimeControl wtc + WHERE userFk = vUserFk + AND timed >= TIMESTAMPADD(DAY, -7, vDated) + ) sub + )sub2 + GROUP BY orden + ; + +DROP TEMPORARY TABLE IF EXISTS tmp.workerWeekTiming_Aux; +CREATE TEMPORARY TABLE tmp.workerWeekTiming_Aux + SELECT * FROM tmp.workerWeekTiming; + +INSERT INTO tmp.workerWeekTiming( 7_dias_antes,6_dias_antes,5_dias_antes,4_dias_antes,3_dias_antes,2_dias_antes,1_dia_antes,mismo_dia) + VALUES('total','','','','','','',''); + +INSERT INTO tmp.workerWeekTiming( orden, 7_dias_antes,6_dias_antes,5_dias_antes,4_dias_antes,3_dias_antes,2_dias_antes,1_dia_antes, mismo_dia) +SELECT 0, + IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(7_dias_antes), TIME_TO_SEC(7_dias_antes)))),'%H:%i'),''), + IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(6_dias_antes), TIME_TO_SEC(6_dias_antes)))),'%H:%i'),''), + IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(5_dias_antes), TIME_TO_SEC(5_dias_antes)))),'%H:%i'),''), + IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(4_dias_antes), TIME_TO_SEC(4_dias_antes)))),'%H:%i'),''), + IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(3_dias_antes), TIME_TO_SEC(3_dias_antes)))),'%H:%i'),''), + IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(2_dias_antes), TIME_TO_SEC(2_dias_antes)))),'%H:%i'),''), + IFNULL(DATE_FORMAT(SEC_TO_TIME(SUM(IF(orden MOD 2, - TIME_TO_SEC(1_dia_antes), TIME_TO_SEC(1_dia_antes)))),'%H:%i'),''), + '' + FROM tmp.workerWeekTiming_Aux; + +INSERT INTO tmp.workerWeekTiming_Aux( orden, 1_dia_antes) +SELECT 0, ROUND(( + IFNULL(TIME_TO_SEC(7_dias_antes),0) + + IFNULL(TIME_TO_SEC(6_dias_antes),0) + + IFNULL(TIME_TO_SEC(5_dias_antes),0) + + IFNULL(TIME_TO_SEC(4_dias_antes),0) + + IFNULL(TIME_TO_SEC(3_dias_antes),0) + + IFNULL(TIME_TO_SEC(2_dias_antes),0) + + IFNULL(TIME_TO_SEC(1_dia_antes),0) + ) / 3600,1) + FROM tmp.workerWeekTiming + WHERE orden = 0; + + +INSERT INTO tmp.workerWeekTiming( 7_dias_antes,6_dias_antes,5_dias_antes,4_dias_antes,3_dias_antes,2_dias_antes,1_dia_antes,mismo_dia) + SELECT '','','','','','',1_dia_antes,'' + FROM tmp.workerWeekTiming_Aux + WHERE orden = 0; + +SELECT 7_dias_antes,6_dias_antes,5_dias_antes,4_dias_antes,3_dias_antes,2_dias_antes,1_dia_antes,mismo_dia FROM tmp.workerWeekTiming; + +DROP TEMPORARY TABLE tmp.workerWeekTiming; +DROP TEMPORARY TABLE tmp.workerWeekTiming_Aux; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `worker_getHierarch` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `worker_getHierarch`(vBoss INT) +BEGIN + DECLARE EXIT HANDLER FOR 1062 BEGIN + CALL util.throw('INFINITE_LOOP'); + END; + + DROP TEMPORARY TABLE IF EXISTS workerHierarch; + CREATE TEMPORARY TABLE workerHierarch + (PRIMARY KEY (workerFk)) + ENGINE = MEMORY + SELECT vBoss AS workerFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.workerHierarchList; + CREATE TEMPORARY TABLE tmp.workerHierarchList + (PRIMARY KEY (workerFk)) + ENGINE = MEMORY + SELECT vBoss AS workerFk, 0 AS isChecked; + + + WHILE (SELECT COUNT(*) FROM tmp.workerHierarchList WHERE NOT isChecked) > 0 DO + + INSERT INTO tmp.workerHierarchList + SELECT w.id, 0 + FROM worker w + JOIN workerHierarch wh ON wh.workerFk = w.bossFk; + + UPDATE tmp.workerHierarchList whl + JOIN workerHierarch wh ON wh.workerFk = whl.workerFk + SET whl.isChecked = 1; + + TRUNCATE workerHierarch; + + INSERT INTO workerHierarch + SELECT workerFk + FROM tmp.workerHierarchList + WHERE NOT isChecked; + + END WHILE; + + DROP TEMPORARY TABLE IF EXISTS workerHierarch; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workingHours` */; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workingHours`(username varchar(255), logon boolean) +BEGIN + DECLARE userid int(11); + + SELECT vn.getUserId(username) INTO userid; + SELECT username, userid; + IF userid IS NOT NULL THEN + IF (logon) THEN + CALL vn.workingHoursTimeIn(userid); + ELSE + CALL vn.workingHoursTimeOut(userid); + END IF; + 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 */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `workingHoursTimeIn` */; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workingHoursTimeIn`(vUserId INT(11)) +BEGIN + INSERT INTO vn.workingHours (timeIn, userId) + VALUES (NOW(),vUserId); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `workingHoursTimeOut` */; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workingHoursTimeOut`(vUserId INT(11)) +BEGIN + UPDATE vn.workingHours + SET timeOut = NOW() + WHERE userId = vUserId + AND DATE(timeIn) = CURDATE(); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `wrongEqualizatedClient` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `wrongEqualizatedClient`() +BEGIN + SELECT clientFk, c.name, c.isActive, c.isTaxDataChecked, count(ie) as num + FROM vn.client c + JOIN + ( + SELECT DISTINCT + `a`.`clientFk` , + a.isEqualizated = 0 as ie + + FROM + `vn`.`address` `a` + ) sub ON sub.clientFk = c.id + WHERE c.hasToInvoiceByAddress = FALSE + + GROUP BY clientFk + HAVING num > 1 + UNION ALL + SELECT DISTINCT c.id, c.name, c.isActive, c.isTaxDataChecked,1 + FROM + `vn`.`address` `a` + JOIN `vn`.`client` `c` ON `c`.`id` = `a`.`clientFk` + WHERE ABS(a.isEqualizated) <> ABS(c.isEqualizated) + AND c.hasToInvoiceByAddress = FALSE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `xdiarioNextId` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `xdiarioNextId`() +BEGIN + DECLARE vNewAsien INT; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT bookFk + 1 INTO vNewAsien FROM config FOR UPDATE; + UPDATE config SET bookFk = vNewAsien; + COMMIT; + + SELECT vNewAsien; + + DROP TEMPORARY TABLE IF EXISTS tmp.xdiarioNextId; + CREATE TEMPORARY TABLE tmp.xdiarioNextId AS + SELECT vNewAsien ; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGeo_calcTree` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGeo_calcTree`() +BEGIN +/** + * Calculates the #path, #lft, #rgt, #sons and #depth columns of + * the #zoneGeo table. To build the tree, it uses the #parentFk + * column. + */ + DECLARE vIndex INT DEFAULT 0; + DECLARE vSons INT; + + DROP TEMPORARY TABLE IF EXISTS tNestedTree; + CREATE TEMPORARY TABLE tNestedTree + SELECT id, path, lft, rgt, depth, sons + FROM zoneGeo LIMIT 0; + + SET max_sp_recursion_depth = 5; + CALL zoneGeo_calcTreeRec(NULL, '/', 0, vIndex, vSons); + SET max_sp_recursion_depth = 0; + + UPDATE zoneGeo z + JOIN tNestedTree t ON t.id = z.id + SET z.path = t.path, + z.lft = t.lft, + z.rgt = t.rgt, + z.depth = t.depth, + z.sons = t.sons; + + DROP TEMPORARY TABLE tNestedTree; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGeo_calcTreeRec` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGeo_calcTreeRec`( + vSelf INT, + vPath VARCHAR(255), + vDepth INT, + INOUT vIndex INT, + OUT vSons INT +) +BEGIN +/** + * Calculates and sets the #path, #lft, #rgt, #sons and #depth + * columns for all children of the passed node. Once calculated + * the last node rgt index and the number of sons are returned. + * To update it's children, this procedure calls itself recursively + * for each one. + * + * @vSelf The node identifier + * @vPath The initial path + * @vDepth The initial depth + * @vIndex The initial lft index + * @vSons The number of direct sons + */ + DECLARE vChildFk INT; + DECLARE vLft INT; + DECLARE vMySons INT; + DECLARE vDone BOOL; + DECLARE vChildren CURSOR FOR + SELECT id FROM zoneGeo + WHERE (vSelf IS NULL AND parentFk IS NULL) + OR (vSelf IS NOT NULL AND parentFk = vSelf); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + SET vSons = 0; + + OPEN vChildren; + myLoop: LOOP + SET vDone = FALSE; + FETCH vChildren INTO vChildFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + SET vIndex = vIndex + 1; + SET vLft = vIndex; + SET vSons = vSons + 1; + + CALL zoneGeo_calcTreeRec( + vChildFk, + CONCAT(vPath, vChildFk, '/'), + vDepth + 1, + vIndex, + vMySons + ); + + SET vIndex = vIndex + 1; + + INSERT INTO tNestedTree + SET id = vChildFk, + path = vPath, + lft = vLft, + rgt = vIndex, + depth = vDepth, + sons = vMySons; + END LOOP; + CLOSE vChildren; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGeo_checkName` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGeo_checkName`(vName VARCHAR(255)) +BEGIN + IF vName = '' THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Column `name` cannot be empty'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGeo_delete` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGeo_delete`(vSelf INT) +BEGIN +/** + * Deletes a node from the #zoneGeo table. Also sets a mark + * to force the tree recalculation. + * + * @vSelf The node identifier + */ + DELETE FROM zoneGeo WHERE id = vSelf; + UPDATE zoneGeoRecalc SET isChanged = TRUE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGeo_doCalc` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGeo_doCalc`() +proc: BEGIN +/** + * Recalculates the zones tree. + */ + DECLARE vIsChanged BOOL; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.zoneGeo_doCalc'); + RESIGNAL; + END; + + IF !GET_LOCK('vn.zoneGeo_doCalc', 0) THEN + LEAVE proc; + END IF; + + SELECT isChanged INTO vIsChanged + FROM zoneGeoRecalc; + + IF vIsChanged THEN + UPDATE zoneGeoRecalc SET isChanged = FALSE; + CALL vn.zoneGeo_calcTree; + END IF; + + DO RELEASE_LOCK('vn.zoneGeo_doCalc'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGeo_setParent` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGeo_setParent`(vSelf INT, vParentFk INT) +BEGIN +/** + * Updates the parent of a node. Also sets a mark + * to force the tree recalculation. + * + * @vSelf The node identifier + * @vParentFk The new parent identifier + */ + UPDATE zoneGeo SET parentFk = vParentFk + WHERE id = vSelf; + + UPDATE zoneGeoRecalc SET isChanged = TRUE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGeo_throwNotEditable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGeo_throwNotEditable`() +BEGIN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Column `geoFk` cannot be modified'; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGetAgency` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetAgency`(vAddress INT, vLanded DATE) +BEGIN +/** + * Devuelve el listado de agencias disponibles para la fecha + * y dirección pasadas. + * + * @param vAddress Id de dirección de envío, %NULL si es recogida + * @param vDate Fecha de recogida + * @select Listado de agencias disponibles + */ + + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM address a + JOIN town t ON t.provinceFk = a.provinceFk + JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode + WHERE a.id = vAddress + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + LIMIT 1; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency; + CREATE TEMPORARY TABLE tmp.zoneGetAgency + (INDEX (agencyModeFk)) ENGINE = MEMORY + SELECT * FROM ( + SELECT * FROM ( + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, + am.deliveryMethodFk, + TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, + zi.isIncluded, + z.warehouseFk, + z.id zoneFk + FROM zoneGeo zgSon + JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt + JOIN zoneIncluded zi ON zi.geoFk = zgFather.id + JOIN zone z ON z.id = zi.zoneFk + JOIN zoneCalendar zc ON zc.zoneFk = z.id + JOIN agencyMode am ON am.id = z.agencyModeFk + WHERE zgSon.`id` = vGeoFk + AND zc.delivered = vLanded + AND TIMESTAMPADD(DAY,-z.travelingDays, vLanded) >= CURDATE() + AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) + ORDER BY z.id, zgFather.depth DESC, zi.isIncluded DESC) t + GROUP BY zoneFk + HAVING isIncluded > 0 + ORDER BY shipped) t + GROUP BY agencyModeFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGetFirstShipped` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetFirstShipped`(vAgencyModeFk INT, vAddress INT, vWarehouseFk INT) +BEGIN +/** +* Devuelve la primera fecha de envio disponible para una agencia en una direccion y un warehouse +* +* @param vAgencyMode id de la agencia en vn.agencyMode +* @param vAddress id de la direccion +* @param vWarehouse id del warehouse +* @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida +*/ + + + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM address a + JOIN town t ON t.provinceFk = a.provinceFk + JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode + WHERE a.id = vAddress + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + LIMIT 1; + + SELECT * FROM ( + SELECT TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) shipped, + zc.delivered landed, + zi.isIncluded + FROM zoneGeo zgSon + JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt + JOIN zoneIncluded zi ON zi.geoFk = zgFather.id + JOIN zone z ON z.id = zi.zoneFk + JOIN zoneCalendar zc ON zc.zoneFk = z.id + WHERE zgSon.`id` = vGeoFk + AND z.agencyModeFk = vAgencyModeFk + AND z.warehouseFk = vWarehouseFk + AND TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) >= CURDATE() + AND IF(TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) + ORDER BY landed ASC, zgFather.depth DESC) t + HAVING isIncluded > 0 LIMIT 1; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGetLanded` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) +BEGIN +/** +* Devuelve una tabla temporal con el dia de recepcion para vShipped. +* +* @param vShipped Fecha de preparacion de mercancia +* @param vAddressFk Id de consignatario, %NULL para recogida +* @param vAgencyModeFk Id agencia +* @table tmp.zoneGetLanded Datos de recepción +*/ + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM address a + JOIN town t ON t.provinceFk = a.provinceFk + JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode + WHERE a.id = vAddressFk + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + LIMIT 1; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; + CREATE TEMPORARY TABLE tmp.zoneGetLanded + ENGINE = MEMORY + SELECT + id zoneFk, + vShipped shipped, + delivered landed, + vWarehouseFk warehouseFk, + agencyModeFk, + isIncluded + FROM ( + SELECT zi.isIncluded, zc.delivered, z.id, z.agencyModeFk + FROM vn.zoneGeo zgSon + JOIN vn.zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt + JOIN zoneIncluded zi ON zi.geoFk = zgFather.id + JOIN zone z ON z.id = zi.zoneFk + JOIN zoneCalendar zc ON zc.zoneFk = z.id + WHERE zgSon.`id` = vGeoFk + AND zc.delivered = TIMESTAMPADD(DAY,z.travelingDays, vShipped) + AND IF(vShipped = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) + AND z.agencyModeFk = vAgencyModeFk + AND z.warehouseFk = vWarehouseFk + ORDER BY zgFather.depth DESC) t + GROUP BY zoneFk + HAVING isIncluded > 0 + LIMIT 1; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGetShipped` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShipped`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) +BEGIN +/** + * Devuelve la mínima fecha de envía para cada warehouse + * + * @param vLanded La fecha de recepcion + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.zoneGetShipped + */ + + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM address a + JOIN town t ON t.provinceFk = a.provinceFk + JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode + WHERE a.id = vAddressFk + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + LIMIT 1; + + SELECT * FROM ( + SELECT * FROM ( + SELECT z.id zoneFk, + TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, + vLanded landed, + vWarehouseFk warehouseFk, + z.agencyModeFk, + zi.isIncluded + FROM zoneGeo zgSon + JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt + JOIN zoneIncluded zi ON zi.geoFk = zgFather.id + JOIN zone z ON z.id = zi.zoneFk + JOIN zoneCalendar zc ON zc.zoneFk = z.id + WHERE zgSon.`id` = vGeoFk + AND zc.delivered = vLanded + AND z.agencyModeFk = vAgencyModeFk + AND z.warehouseFk = vWarehouseFk + AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) + ORDER BY z.id, zgFather.depth DESC, isIncluded DESC) t + GROUP BY zoneFk + HAVING isIncluded > 0 + ORDER BY shipped) + t + GROUP BY agencyModeFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGetShippedWarehouse` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) +BEGIN +/** + * Devuelve la mínima fecha de envío para cada warehouse + * + * @param vLanded La fecha de recepcion + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.zoneGetShipped + */ + + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM address a + JOIN town t ON t.provinceFk = a.provinceFk + JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode + WHERE a.id = vAddressFk + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + LIMIT 1; + + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; + CREATE TEMPORARY TABLE tmp.zoneGetShipped + ENGINE = MEMORY + SELECT * FROM ( + SELECT * FROM ( + SELECT z.id, + TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, + zi.isIncluded,z.warehouseFk + FROM zoneGeo zgSon + JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt + JOIN zoneIncluded zi ON zi.geoFk = zgFather.id + JOIN zone z ON z.id = zi.zoneFk + JOIN zoneCalendar zc ON zc.zoneFk = z.id + WHERE zgSon.`id` = vGeoFk + AND zc.delivered = vLanded + AND z.agencyModeFk = vAgencyModeFk + AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) + ORDER BY z.id, shipped ASC, zgFather.depth DESC, zi.isIncluded DESC) t + GROUP BY warehouseFk, id + HAVING isIncluded > 0 + ORDER BY shipped) t + GROUP BY warehouseFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGetWarehouse` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT) +BEGIN +/** +* Devuelve el listado de agencias disponibles para la fecha, + * dirección y warehouse pasadas + * + * @param vAddress + * @param vWarehouse warehouse + * @param vLanded Fecha de recogida + * @select Listado de agencias disponibles + */ + + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM address a + JOIN town t ON t.provinceFk = a.provinceFk + JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode + WHERE a.id = vAddress + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + LIMIT 1; + + + SELECT * FROM ( + SELECT * FROM ( + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, + am.deliveryMethodFk, + TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, + z.warehouseFk, + zi.isIncluded, + z.id zoneFk + FROM zoneGeo zgSon + JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt + JOIN zoneIncluded zi ON zi.geoFk = zgFather.id + JOIN zone z ON z.id = zi.zoneFk + JOIN zoneCalendar zc ON zc.zoneFk = z.id + JOIN agencyMode am ON am.id = z.agencyModeFk + WHERE zgSon.`id` = vGeoFk + AND delivered = vLanded + AND z.warehouseFk = vWarehouse + AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) + ORDER BY z.id, zgFather.depth DESC) t + GROUP BY zoneFk + HAVING isIncluded > 0) t + GROUP BY agencyModeFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getLeaves` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLeaves`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255) +) +BEGIN + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id FROM zoneGeo + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + ELSEIF vParentFk IS NULL THEN + INSERT INTO tNodes + SELECT geoFk FROM zoneIncluded + WHERE zoneFk = vSelf; + END IF; + + IF vParentFk IS NULL THEN + DROP TEMPORARY TABLE IF EXISTS tChilds; + CREATE TEMPORARY TABLE tChilds + ENGINE = MEMORY + SELECT id FROM tNodes; + + DROP TEMPORARY TABLE IF EXISTS tParents; + CREATE TEMPORARY TABLE tParents + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF ROW_COUNT() = 0 THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE + tChilds, + tParents; + END IF; + + IF !vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + SELECT g.id, + g.`name`, + g.parentFk, + g.sons, + isIncluded selected + FROM zoneGeo g + JOIN tNodes n ON n.id = g.id + LEFT JOIN zoneIncluded i + ON i.geoFk = g.id AND i.zoneFk = vSelf + ORDER BY depth, selected DESC, `name`; + + DROP TEMPORARY TABLE tNodes; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Current Database: `vncontrol` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vncontrol` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; + +USE `vncontrol`; + +-- +-- Table structure for table `accion` +-- + +DROP TABLE IF EXISTS `accion`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `accion` ( + `accion_id` int(11) NOT NULL AUTO_INCREMENT, + `accion` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`accion_id`) +) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `fallo__` +-- + +DROP TABLE IF EXISTS `fallo__`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `fallo__` ( + `queja_id` int(10) unsigned NOT NULL, + `accion_id` int(11) NOT NULL, + PRIMARY KEY (`queja_id`,`accion_id`), + KEY `accion` (`accion_id`,`queja_id`), + KEY `fallo` (`queja_id`), + CONSTRAINT `accion` FOREIGN KEY (`accion_id`) REFERENCES `accion` (`accion_id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `inter` +-- + +DROP TABLE IF EXISTS `inter`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!50503 SET character_set_client = utf8mb4 */; +CREATE TABLE `inter` ( + `inter_id` int(11) NOT NULL AUTO_INCREMENT, + `state_id` tinyint(3) unsigned NOT NULL, + `fallo_id` int(10) unsigned NOT NULL DEFAULT '21', + `nota` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `Id_Ticket` int(11) DEFAULT NULL, + `Id_Trabajador` int(11) DEFAULT NULL, + `Id_Supervisor` int(11) DEFAULT NULL, + PRIMARY KEY (`inter_id`), + KEY `currante` (`Id_Trabajador`), + KEY `responsable` (`Id_Supervisor`), + KEY `ticket` (`Id_Ticket`), + KEY `inter_state` (`state_id`), + KEY `inter_id` (`Id_Ticket`,`inter_id`) USING BTREE, + CONSTRAINT `currante` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `inter_ibfk_1` FOREIGN KEY (`Id_Ticket`) REFERENCES `vn`.`ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `inter_state` FOREIGN KEY (`state_id`) REFERENCES `vn`.`state` (`id`) ON UPDATE CASCADE, + CONSTRAINT `responsable` FOREIGN KEY (`Id_Supervisor`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=22162842 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `ticketTracking_beforeInsert` + BEFORE INSERT ON `inter` + FOR EACH ROW +BEGIN +/* + -- PAK 08/05/18 Los tickets no se pueden marcar como servidos en el futuro + + IF NEW.state_id = 16 AND (SELECT date(landed) FROM vn.ticket WHERE id = NEW.Id_Ticket) > CURDATE() THEN -- Entregado + SET NEW.state_id = 22; -- ¿ Fecha ? + END IF; +*//* + -- PAK 08/05/18 Los sacadores no deben de poner los tickets en revisión + + DECLARE vIsSacador BOOL; + + IF NEW.state_id = 6 THEN -- Revisión + SELECT COUNT(*) > 0 INTO vIsSacador + FROM inter + WHERE state_id = 5 -- Preparacion + AND Id_Trabajador = NEW.Id_Trabajador + AND Id_Ticket = NEW.Id_Ticket; + + IF vIsSacador THEN + SET NEW.state_id = 5; + END IF; + END IF; +*//* + -- PAK 08/05/18 Este código parece fósil. Lo comento. + + DECLARE contados INT; + DECLARE vSupervisor INT; + + SELECT Id_Trabajador INTO vSupervisor + FROM vn2008.Trabajadores WHERE user_id = account.userGetId(); + + SET NEW.Id_Supervisor = IFNULL(vSupervisor,20); + + IF NEW.state_id = 5 THEN -- Preparación + SELECT COUNT(Id_Ticket) INTO contados + FROM vncontrol.inter + WHERE state_id = 5 + AND Id_Ticket = NEW.Id_Ticket + AND IFNULL(Id_Supervisor,-1) <> vSupervisor + AND TIMESTAMPADD(SECOND, 60, odbc_date) >= NOW(); + + IF contados <> 0 THEN + CALL util.throw ('FALLO_AL_INSERTAR'); + END IF; + END IF; +*/ +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vncontrol`.`ticketTracking_afterInsert` + AFTER INSERT ON `inter` + FOR EACH ROW +BEGIN + REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name) + SELECT NEW.Id_Ticket, NEW.inter_id, `name` + FROM vn.state + WHERE id = NEW.state_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_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vncontrol`.`ticketTracking_afterUpdate` + AFTER UPDATE ON `inter` + FOR EACH ROW +BEGIN + DECLARE vTicketFk INT; + DECLARE vTicketTrackingFk INT; + DECLARE vStateName VARCHAR(15); + + IF NEW.state_id <> OLD.state_id THEN + REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name) + SELECT NEW.Id_Ticket, NEW.inter_id, `name` + FROM vn.state + WHERE id = NEW.state_id; + END IF; + + IF NEW.Id_Ticket <> OLD.Id_Ticket THEN + SELECT i.Id_Ticket, i.inter_id, s.`name` + INTO vTicketFk, vTicketTrackingFk, vStateName + FROM vncontrol.inter i + JOIN vn.state s ON i.state_id = s.id + WHERE Id_Ticket = NEW.Id_Ticket + ORDER BY odbc_date DESC + LIMIT 1; + + IF vTicketFk > 0 THEN + REPLACE INTO vn.ticketLastState(ticketFk, ticketTrackingFk,name) + VALUES(vTicketFk, vTicketTrackingFk, vStateName); + END IF; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vncontrol`.`ticketTracking_afterDelete` + AFTER DELETE ON `inter` + FOR EACH ROW +BEGIN + DECLARE vTicketFk INT; + DECLARE vTicketTrackingFk INT; + DECLARE vStateName VARCHAR(15); + + DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' + BEGIN + DELETE FROM vn.ticketLastState + WHERE ticketFk = OLD.Id_Ticket; + END; + + SELECT i.Id_Ticket, i.inter_id, s.`name` + INTO vTicketFk, vTicketTrackingFk, vStateName + FROM vncontrol.inter i + JOIN vn.state s ON i.state_id = s.id + WHERE Id_Ticket = OLD.Id_Ticket + ORDER BY odbc_date DESC + LIMIT 1; + + IF vTicketFk > 0 THEN + REPLACE INTO vn.ticketLastState(ticketFk, ticketTrackingFk,name) + VALUES(vTicketFk, vTicketTrackingFk, vStateName); + 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 */ ; + +-- +-- Dumping events for database 'vncontrol' +-- + +-- +-- Dumping routines for database 'vncontrol' +-- +/*!50003 DROP PROCEDURE IF EXISTS `clean` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clean`() +BEGIN + DECLARE vDate DATETIME DEFAULT TIMESTAMPADD(MONTH, -2, CURDATE()); + DELETE i FROM inter i JOIN vn.ticket t ON i.Id_Ticket = t.id + WHERE t.shipped <= vDate; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Current Database: `account` +-- + +USE `account`; + +-- +-- Final view structure for view `accountDovecot` +-- + +/*!50001 DROP VIEW IF EXISTS `accountDovecot`*/; +/*!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`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `accountDovecot` AS select `u`.`name` AS `name`,`u`.`password` AS `password` from (`user` `u` join `account` `a` on((`a`.`id` = `u`.`id`))) where `u`.`active` */; +/*!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 `emailUser` +-- + +/*!50001 DROP VIEW IF EXISTS `emailUser`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `emailUser` AS select `u`.`id` AS `userFk`,concat(`u`.`name`,'@',`mc`.`domain`) AS `email` from (`user` `u` join `mailConfig` `mc`) */; +/*!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 `myRole` +-- + +/*!50001 DROP VIEW IF EXISTS `myRole`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myRole` AS select `r`.`inheritsFrom` AS `id` from (`roleRole` `r` join `user` `u` on((`u`.`role` = `r`.`role`))) where (`u`.`id` = `MYUSERGETID`()) */; +/*!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 `myUser` +-- + +/*!50001 DROP VIEW IF EXISTS `myUser`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myUser` AS select `u`.`id` AS `id`,`u`.`name` AS `name`,`u`.`active` AS `active`,`u`.`email` AS `email`,`u`.`nickname` AS `nickname`,`u`.`lang` AS `lang`,`u`.`role` AS `role`,`u`.`recoverPass` AS `recoverPass` from `user` `u` where (`u`.`name` = `myUserGetName`()) */ +/*!50002 WITH CASCADED CHECK OPTION */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Current Database: `bi` +-- + +USE `bi`; + +-- +-- Final view structure for view `analisis_grafico_ventas` +-- + +/*!50001 DROP VIEW IF EXISTS `analisis_grafico_ventas`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `analisis_grafico_ventas` AS select `analisis_ventas`.`Año` AS `Año`,`analisis_ventas`.`Semana` AS `Semana`,sum(`analisis_ventas`.`Importe`) AS `Importe` from `analisis_ventas` group by `analisis_ventas`.`Año`,`analisis_ventas`.`Semana` */; +/*!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 `analisis_ventas_simple` +-- + +/*!50001 DROP VIEW IF EXISTS `analisis_ventas_simple`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `analisis_ventas_simple` AS select `analisis_ventas`.`Año` AS `Año`,`analisis_ventas`.`Semana` AS `Semana`,sum(`analisis_ventas`.`Importe`) AS `Importe` from `analisis_ventas` group by `analisis_ventas`.`Año`,`analisis_ventas`.`Semana` */; +/*!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 `customerRiskOverdue` +-- + +/*!50001 DROP VIEW IF EXISTS `customerRiskOverdue`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `customerRiskOverdue` AS select `cr`.`customer_id` AS `customer_id`,`cr`.`amount` AS `amount`,`cr`.`company_id` AS `company_id` from (((`bi`.`customer_risk` `cr` join `vn`.`company` `co` on((`co`.`id` = `cr`.`company_id`))) join `vn`.`client` `c` on((`cr`.`customer_id` = `c`.`id`))) join `vn`.`payMethod` `pm` on((`pm`.`id` = `c`.`payMethodFk`))) where (`cr`.`amount` and `co`.`isDefaulter` and `pm`.`outstandingDebt` and (`c`.`typeFk` = 'normal')) union all select `i`.`clientFk` AS `Id_Cliente`,-(round(`i`.`amount`,2)) AS `importe`,`i`.`companyFk` AS `empresa_id` from (((`vn`.`invoiceOut` `i` join `vn`.`client` `c` on((`i`.`clientFk` = `c`.`id`))) join `vn`.`company` `co` on((`co`.`id` = `i`.`companyFk`))) join `vn`.`payMethod` `pm` on((`pm`.`id` = `c`.`payMethodFk`))) where ((`i`.`issued` > (curdate() + interval -(101) day)) and ((`i`.`dued` + interval `pm`.`graceDays` day) > curdate()) and (`i`.`amount` > 0) and `co`.`isDefaulter` and `pm`.`outstandingDebt` and (`c`.`typeFk` = 'normal')) */; +/*!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 `saleVolume` +-- + +/*!50001 DROP VIEW IF EXISTS `saleVolume`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `saleVolume` AS select `s`.`id` AS `saleFk`,sum((((`r`.`cm3` * `i`.`compression`) * `s`.`quantity`) / 1000000)) AS `m3` from (((`vn`.`ticket` `t` join `vn`.`sale` `s` on((`s`.`ticketFk` = `t`.`id`))) join `vn`.`item` `i` on((`i`.`id` = `s`.`itemFk`))) join `bi`.`rotacion` `r` on(((`r`.`Id_Article` = `i`.`id`) and (`r`.`warehouse_id` = `t`.`warehouseFk`)))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Current Database: `bs` +-- + +USE `bs`; + +-- +-- Final view structure for view `bajasLaborales` +-- + +/*!50001 DROP VIEW IF EXISTS `bajasLaborales`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `bajasLaborales` AS select `p`.`firstname` AS `firstname`,`p`.`name` AS `name`,`b`.`business_id` AS `business_id`,max(`ce`.`date`) AS `lastDate`,max(ifnull(`b`.`date_end`,curdate())) AS `endContract`,`cs`.`type` AS `type`,cast(count(0) as decimal(10,0)) AS `dias`,`w`.`userFk` AS `userFk` from (((((`postgresql`.`calendar_employee` `ce` join `postgresql`.`business` `b` on((`b`.`business_id` = `ce`.`business_id`))) join `postgresql`.`profile` `pr` on((`pr`.`profile_id` = `b`.`client_id`))) join `postgresql`.`person` `p` on((`p`.`person_id` = `pr`.`person_id`))) join `postgresql`.`calendar_state` `cs` on((`cs`.`calendar_state_id` = `ce`.`calendar_state_id`))) join `vn`.`worker` `w` on((`w`.`id` = `p`.`id_trabajador`))) where ((`ce`.`date` >= (curdate() + interval -(1) year)) and (`cs`.`type` not in ('Vacaciones','Vacaciones 1/2 día','Compensar','Festivo'))) group by `p`.`firstname`,`p`.`name`,`cs`.`type` having (`endContract` >= curdate()) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `lastIndicators` +-- + +/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `lastIndicators` AS select `i`.`updated` AS `updated`,`i`.`lastYearSales` AS `lastYearSales`,(`i`.`lastYearSales` - `yi`.`lastYearSales`) AS `incLastYearSales`,`i`.`totalGreuge` AS `totalGreuge`,(`i`.`totalGreuge` - `yi`.`totalGreuge`) AS `incTotalGreuge`,`i`.`latePaymentRate` AS `latePaymentRate`,(`i`.`latePaymentRate` - `yi`.`latePaymentRate`) AS `incLatePaymentRate`,`i`.`countEmployee` AS `countEmployee`,(`i`.`countEmployee` - `yi`.`countEmployee`) AS `incCountEmployee`,`i`.`averageMana` AS `averageMana`,(`i`.`averageMana` - `yi`.`averageMana`) AS `incAverageMana`,`i`.`bankingPool` AS `bankingPool`,(`i`.`bankingPool` - `yi`.`bankingPool`) AS `incbankingPool`,`i`.`lastMonthActiveClients` AS `lastMonthActiveClients`,(`i`.`lastMonthActiveClients` - `yi`.`lastMonthActiveClients`) AS `incLastMonthActiveClients`,`i`.`lastMonthLostClients` AS `lastMonthLostClients`,(`i`.`lastMonthLostClients` - `yi`.`lastMonthLostClients`) AS `incLastMonthLostClients`,`i`.`lastMonthNewClients` AS `lastMonthNewClients`,(`i`.`lastMonthNewClients` - `yi`.`lastMonthNewClients`) AS `incLastMonthNewClients`,`i`.`lastMonthWebBuyingRate` AS `lastMonthWebBuyingRate`,(`i`.`lastMonthWebBuyingRate` - `yi`.`lastMonthWebBuyingRate`) AS `incLastMonthWebBuyingRate`,`i`.`productionHours` AS `productionHours`,`i`.`dailyWorkersCost` AS `dailyWorkersCost`,`i`.`volumeM3` AS `volumeM3`,`i`.`salesValue` AS `salesValue`,`i`.`valueM3` AS `valueM3`,`i`.`hoursM3` AS `hoursM3`,`i`.`workerCostM3` AS `workerCostM3`,`i`.`salesWorkersCostRate` AS `salesWorkersCostRate`,`i`.`thisWeekSales` AS `thisWeekSales`,`i`.`lastYearWeekSales` AS `lastYearWeekSales` from (`indicators` `i` join `indicators` `yi` on((`yi`.`updated` = (select (max(`indicators`.`updated`) + interval -(1) day) from `indicators`)))) where (`i`.`updated` = (select max(`indicators`.`updated`) from `indicators`)) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `m3Silla` +-- + +/*!50001 DROP VIEW IF EXISTS `m3Silla`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `m3Silla` AS select `m3`.`fecha` AS `fecha`,`m3`.`year` AS `year`,`m3`.`month` AS `month`,`m3`.`week` AS `week`,`m3`.`day` AS `day`,`m3`.`dayName` AS `dayName`,cast(sum(`m3`.`m3`) as decimal(10,0)) AS `Volumen`,cast(sum(`m3`.`euros`) as decimal(10,0)) AS `Euros` from `m3` where (`m3`.`warehouseFk` in (1,44)) group by `m3`.`fecha` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `m3analisis` +-- + +/*!50001 DROP VIEW IF EXISTS `m3analisis`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `m3analisis` AS select `m`.`fecha` AS `fecha`,`m`.`year` AS `year`,`m`.`month` AS `month`,`m`.`week` AS `week`,`m`.`day` AS `day`,`m`.`dayName` AS `dayName`,`m`.`Volumen` AS `Volumen`,`m`.`Euros` AS `Euros`,`h`.`Departamento` AS `Departamento`,`h`.`Horas` AS `Horas`,`h`.`Salarios` AS `Salarios`,(`h`.`Horas` / `m`.`Volumen`) AS `tiempoM3`,(`m`.`Euros` / `m`.`Volumen`) AS `valorM3`,(`h`.`Salarios` / `m`.`Volumen`) AS `costeLaboralM3`,(`h`.`Salarios` / `m`.`Euros`) AS `costeEuros`,(`h`.`Salarios` / `h`.`Horas`) AS `precioHora` from (`bs`.`m3Silla` `m` join `bs`.`horasSilla` `h` on((`h`.`Fecha` = `m`.`fecha`))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `manaSpellersExcluded` +-- + +/*!50001 DROP VIEW IF EXISTS `manaSpellersExcluded`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `manaSpellersExcluded` AS select `m`.`Id_Trabajador` AS `workerFk` from `mana_spellers_excluded` `m` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `mana_spellers` +-- + +/*!50001 DROP VIEW IF EXISTS `mana_spellers`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `mana_spellers` AS select `wm`.`workerFk` AS `Id_Trabajador`,`wm`.`size` AS `size`,`wm`.`amount` AS `used`,`wm`.`pricesModifierRate` AS `prices_modifier_rate`,`wm`.`isPricesModifierActivated` AS `prices_modifier_activated`,`wm`.`minRate` AS `minRate`,`wm`.`maxRate` AS `maxRate` from `vn`.`workerMana` `wm` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `mermas` +-- + +/*!50001 DROP VIEW IF EXISTS `mermas`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `mermas` AS select `w`.`code` AS `Comprador`,`it`.`name` AS `Familia`,`i`.`id` AS `Referencia`,`i`.`name` AS `Item`,`s`.`quantity` AS `Cantidad`,(((`b`.`buyingValue` + `b`.`freightValue`) + `b`.`comissionValue`) + `b`.`packageValue`) AS `Coste_Unitario`,(`s`.`quantity` * (((`b`.`buyingValue` + `b`.`freightValue`) + `b`.`comissionValue`) + `b`.`packageValue`)) AS `Importe`,`c`.`name` AS `Cliente`,`s`.`ticketFk` AS `ticketFk`,`t`.`shipped` AS `Fecha` from (((((((`vn`.`worker` `w` join `vn`.`itemType` `it` on((`it`.`workerFk` = `w`.`id`))) join `vn`.`item` `i` on((`i`.`typeFk` = `it`.`id`))) join `vn`.`sale` `s` on((`s`.`itemFk` = `i`.`id`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`client` `c` on((`c`.`id` = `t`.`clientFk`))) left join `bi`.`Last_buy_id` `lb` on(((`lb`.`Id_Article` = `s`.`itemFk`) and (`lb`.`warehouse_id` = `t`.`warehouseFk`)))) left join `vn`.`buy` `b` on((`b`.`id` = `lb`.`Id_Compra`))) where ((`t`.`shipped` > '2018-01-01') and (`c`.`isRelevant` or (`c`.`id` in (200,400)))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `workerMana` +-- + +/*!50001 DROP VIEW IF EXISTS `workerMana`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerMana` AS select `m`.`Id_Trabajador` AS `workerFk`,`m`.`used` AS `amount` from `bs`.`mana_spellers` `m` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Current Database: `cache` +-- + +USE `cache`; + +-- +-- Current Database: `edi` +-- + +USE `edi`; + +-- +-- Current Database: `hedera` +-- + +USE `hedera`; + +-- +-- Final view structure for view `mainAccountBank` +-- + +/*!50001 DROP VIEW IF EXISTS `mainAccountBank`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `mainAccountBank` AS select `e`.`name` AS `name`,`a`.`iban` AS `iban` from ((`hedera`.`mainAccount` `c` join `vn`.`supplierAccount` `a` on((`a`.`id` = `c`.`accountFk`))) join `vn`.`bankEntity` `e` on((`e`.`id` = `a`.`bankEntityFk`))) */; +/*!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 `myAddress` +-- + +/*!50001 DROP VIEW IF EXISTS `myAddress`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myAddress` AS select `t`.`id` AS `id`,`t`.`clientFk` AS `clientFk`,`t`.`street` AS `street`,`t`.`city` AS `city`,`t`.`postalCode` AS `postalCode`,`t`.`provinceFk` AS `provinceFk`,`t`.`nickname` AS `nickname`,`t`.`isDefaultAddress` AS `isDefaultAddress`,`t`.`isActive` AS `isActive`,`t`.`longitude` AS `longitude`,`t`.`latitude` AS `latitude`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`agencyModeFk` AS `agencyModeFk` from `vn`.`address` `t` where (`t`.`clientFk` = `account`.`myUserGetId`()) */ +/*!50002 WITH CASCADED CHECK OPTION */; +/*!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 `myBasket` +-- + +/*!50001 DROP VIEW IF EXISTS `myBasket`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myBasket` AS select `o`.`id` AS `id`,`o`.`date_make` AS `made`,`o`.`date_send` AS `sent`,`o`.`customer_id` AS `clientFk`,`o`.`delivery_method_id` AS `deliveryMethodFk`,`o`.`agency_id` AS `agencyModeFk`,`o`.`address_id` AS `addressFk`,`o`.`company_id` AS `companyFk`,`o`.`note` AS `notes` from `hedera`.`order` `o` where (`o`.`id` = `MYBASKET_GETID`()) */ +/*!50002 WITH CASCADED CHECK OPTION */; +/*!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 `myBasketDefaults` +-- + +/*!50001 DROP VIEW IF EXISTS `myBasketDefaults`*/; +/*!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`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myBasketDefaults` AS select coalesce(`dm`.`code`,`cm`.`code`) AS `deliveryMethod`,coalesce(`ad`.`agencyModeFk`,`oc`.`defaultAgencyFk`) AS `agencyModeFk`,`c`.`defaultAddressFk` AS `addressFk`,`oc`.`defaultAgencyFk` AS `defaultAgencyFk` from ((((((`hedera`.`orderConfig` `oc` join `vn`.`agencyMode` `ca` on((`ca`.`id` = `oc`.`defaultAgencyFk`))) join `vn`.`deliveryMethod` `cm` on((`cm`.`id` = `ca`.`deliveryMethodFk`))) left join `vn`.`client` `c` on((`c`.`id` = `account`.`myUserGetId`()))) left join `vn`.`address` `ad` on((`ad`.`id` = `c`.`defaultAddressFk`))) left join `vn`.`agencyMode` `a` on((`a`.`id` = `ad`.`agencyModeFk`))) left join `vn`.`deliveryMethod` `dm` on((`dm`.`id` = `a`.`deliveryMethodFk`))) */; +/*!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 `myBasketItem` +-- + +/*!50001 DROP VIEW IF EXISTS `myBasketItem`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myBasketItem` AS select `r`.`id` AS `id`,`r`.`orderFk` AS `orderFk`,`r`.`warehouseFk` AS `warehouseFk`,`r`.`itemFk` AS `itemFk`,`r`.`amount` AS `amount`,`r`.`price` AS `price` from `hedera`.`orderRow` `r` where (`r`.`orderFk` = `MYBASKET_GETID`()) */ +/*!50002 WITH CASCADED CHECK OPTION */; +/*!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 `myClient` +-- + +/*!50001 DROP VIEW IF EXISTS `myClient`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myClient` AS select `c`.`id` AS `id`,`c`.`isToBeMailed` AS `isToBeMailed`,`c`.`defaultAddressFk` AS `defaultAddressFk`,`c`.`credit` AS `credit` from `vn`.`client` `c` where (`c`.`id` = `account`.`myUserGetId`()) */ +/*!50002 WITH CASCADED CHECK OPTION */; +/*!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 `myInvoice` +-- + +/*!50001 DROP VIEW IF EXISTS `myInvoice`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myInvoice` AS select `i`.`id` AS `id`,`i`.`ref` AS `ref`,`i`.`issued` AS `issued`,`i`.`amount` AS `amount`,`i`.`hasPdf` AS `hasPdf` from `vn`.`invoiceOut` `i` where (`i`.`clientFk` = `account`.`myUserGetId`()) */; +/*!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 `myMenu` +-- + +/*!50001 DROP VIEW IF EXISTS `myMenu`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myMenu` AS select `t`.`id` AS `id`,`t`.`path` AS `path`,`t`.`description` AS `description`,`t`.`parentFk` AS `parentFk` from (`hedera`.`menu` `t` join `account`.`myRole` `r` on((`r`.`id` = `t`.`roleFk`))) order by `t`.`parentFk`,`t`.`displayOrder`,`t`.`id` */; +/*!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 `myOrder` +-- + +/*!50001 DROP VIEW IF EXISTS `myOrder`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myOrder` AS select `o`.`id` AS `id`,`o`.`date_send` AS `landed`,`o`.`customer_id` AS `clientFk`,`o`.`delivery_method_id` AS `deliveryMethodFk`,`o`.`agency_id` AS `agencyModeFk`,`o`.`address_id` AS `addressFk`,`o`.`company_id` AS `companyFk`,`o`.`note` AS `note`,`o`.`source_app` AS `sourceApp`,`o`.`confirmed` AS `isConfirmed`,`o`.`date_make` AS `created`,`o`.`first_row_stamp` AS `firstRowStamp`,`o`.`confirm_date` AS `confirmed` from `hedera`.`order` `o` where (`o`.`customer_id` = `account`.`myUserGetId`()) */; +/*!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 `myOrderRow` +-- + +/*!50001 DROP VIEW IF EXISTS `myOrderRow`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myOrderRow` AS select `orw`.`id` AS `id`,`orw`.`order_id` AS `Fk`,`orw`.`item_id` AS `itemFk`,`orw`.`warehouse_id` AS `warehouseFk`,`orw`.`shipment` AS `shipped`,`orw`.`amount` AS `amount`,`orw`.`price` AS `price`,`orw`.`rate` AS `rate`,`orw`.`created` AS `created`,`orw`.`Id_Movimiento` AS `saleFk` from (`hedera`.`order_row` `orw` join `hedera`.`myOrder` `o` on((`o`.`id` = `orw`.`order_id`))) */ +/*!50002 WITH CASCADED CHECK OPTION */; +/*!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 `myOrderTicket` +-- + +/*!50001 DROP VIEW IF EXISTS `myOrderTicket`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myOrderTicket` AS select `o`.`id` AS `orderFk`,`ot`.`ticketFk` AS `ticketFk` from (`hedera`.`myOrder` `o` join `hedera`.`orderTicket` `ot` on((`ot`.`orderFk` = `o`.`id`))) */; +/*!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 `myTicket` +-- + +/*!50001 DROP VIEW IF EXISTS `myTicket`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myTicket` AS select `t`.`id` AS `id`,`t`.`clientFk` AS `clientFk`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`shipped` AS `shipped`,`t`.`landed` AS `landed`,`t`.`nickname` AS `nickname`,`t`.`agencyModeFk` AS `agencyModeFk`,`t`.`refFk` AS `refFk`,`t`.`addressFk` AS `addressFk`,`t`.`location` AS `location`,`t`.`companyFk` AS `companyFk` from `vn`.`ticket` `t` where (`t`.`clientFk` = `account`.`myUserGetId`()) */; +/*!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 `myTicketRow` +-- + +/*!50001 DROP VIEW IF EXISTS `myTicketRow`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myTicketRow` AS select `s`.`id` AS `id`,`s`.`itemFk` AS `itemFk`,`s`.`ticketFk` AS `ticketFk`,`s`.`concept` AS `concept`,`s`.`quantity` AS `quantity`,`s`.`price` AS `price`,`s`.`discount` AS `discount`,`s`.`reserved` AS `reserved`,`s`.`isPicked` AS `isPicked` from (`vn`.`sale` `s` join `hedera`.`myTicket` `t` on((`s`.`ticketFk` = `t`.`id`))) */ +/*!50002 WITH CASCADED CHECK OPTION */; +/*!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 `myTicketState` +-- + +/*!50001 DROP VIEW IF EXISTS `myTicketState`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myTicketState` AS select `t`.`id` AS `id`,`t`.`clientFk` AS `clientFk`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`shipped` AS `shipped`,`t`.`landed` AS `landed`,`t`.`nickname` AS `nickname`,`t`.`agencyModeFk` AS `agencyModeFk`,`t`.`refFk` AS `refFk`,`t`.`addressFk` AS `addressFk`,`t`.`location` AS `location`,`t`.`companyFk` AS `companyFk`,`ts`.`alertLevel` AS `alertLevel`,`ts`.`code` AS `code` from (`vn`.`ticket` `t` left join `vn`.`ticketState` `ts` on((`ts`.`ticketFk` = `t`.`id`))) where (`t`.`clientFk` = `account`.`myUserGetId`()) */; +/*!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 `myTpvTransaction` +-- + +/*!50001 DROP VIEW IF EXISTS `myTpvTransaction`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `myTpvTransaction` AS select `t`.`id` AS `id`,`t`.`merchantFk` AS `merchantFk`,`t`.`clientFk` AS `clientFk`,`t`.`receiptFk` AS `receiptFk`,`t`.`amount` AS `amount`,`t`.`response` AS `response`,`t`.`status` AS `status`,`t`.`created` AS `created` from `hedera`.`tpvTransaction` `t` where (`t`.`clientFk` = `account`.`myUserGetId`()) */; +/*!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 `orderTicket` +-- + +/*!50001 DROP VIEW IF EXISTS `orderTicket`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `orderTicket` AS select `b`.`orderFk` AS `orderFk`,`b`.`ticketFk` AS `ticketFk` from `vn`.`orderTicket` `b` */; +/*!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 `order_component` +-- + +/*!50001 DROP VIEW IF EXISTS `order_component`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `order_component` AS select `t`.`rowFk` AS `order_row_id`,`t`.`componentFk` AS `component_id`,`t`.`price` AS `price` from `orderRowComponent` `t` */; +/*!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 `order_row` +-- + +/*!50001 DROP VIEW IF EXISTS `order_row`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `order_row` AS select `t`.`id` AS `id`,`t`.`orderFk` AS `order_id`,`t`.`itemFk` AS `item_id`,`t`.`warehouseFk` AS `warehouse_id`,`t`.`shipment` AS `shipment`,`t`.`amount` AS `amount`,`t`.`price` AS `price`,`t`.`rate` AS `rate`,`t`.`created` AS `created`,`t`.`saleFk` AS `Id_Movimiento` from `orderRow` `t` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Current Database: `nst` +-- + +USE `nst`; + +-- +-- Current Database: `pbx` +-- + +USE `pbx`; + +-- +-- Final view structure for view `cdrConf` +-- + +/*!50001 DROP VIEW IF EXISTS `cdrConf`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `cdrConf` AS select `c`.`call_date` AS `calldate`,`c`.`clid` AS `clid`,`c`.`src` AS `src`,`c`.`dst` AS `dst`,`c`.`dcontext` AS `dcontext`,`c`.`channel` AS `channel`,`c`.`dst_channel` AS `dstchannel`,`c`.`last_app` AS `lastapp`,`c`.`last_data` AS `lastdata`,`c`.`duration` AS `duration`,`c`.`billsec` AS `billsec`,`c`.`disposition` AS `disposition`,`c`.`ama_flags` AS `amaflags`,`c`.`account_code` AS `accountcode`,`c`.`unique_id` AS `uniqueid`,`c`.`user_field` AS `userfield` from `cdr` `c` */; +/*!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 `followmeConf` +-- + +/*!50001 DROP VIEW IF EXISTS `followmeConf`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `followmeConf` AS select `f`.`extension` AS `name`,`c`.`music` AS `music`,`c`.`context` AS `context`,`c`.`takeCall` AS `takecall`,`c`.`declineCall` AS `declinecall` from (`followme` `f` join `followmeConfig` `c`) */; +/*!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 `followmeNumberConf` +-- + +/*!50001 DROP VIEW IF EXISTS `followmeNumberConf`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `followmeNumberConf` AS select `f`.`extension` AS `name`,1 AS `ordinal`,`f`.`phone` AS `phonenumber`,`c`.`timeout` AS `timeout` from (`followme` `f` join `followmeConfig` `c`) */; +/*!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 `queueConf` +-- + +/*!50001 DROP VIEW IF EXISTS `queueConf`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `queueConf` AS select `q`.`name` AS `name`,`c`.`strategy` AS `strategy`,`c`.`timeout` AS `timeout`,`c`.`retry` AS `retry`,`c`.`weight` AS `weight`,`c`.`maxLen` AS `maxlen`,`c`.`ringInUse` AS `ringinuse` from (`queue` `q` join `queueConfig` `c` on((`q`.`config` = `c`.`id`))) */; +/*!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 `queueMemberConf` +-- + +/*!50001 DROP VIEW IF EXISTS `queueMemberConf`*/; +/*!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`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `queueMemberConf` AS select `m`.`id` AS `uniqueid`,`m`.`queue` AS `queue_name`,concat('SIP/',`m`.`extension`) AS `interface`,0 AS `paused` from `queueMember` `m` union all select `p`.`id` AS `id`,`p`.`queue` AS `queue`,concat('Local/',`p`.`phone`,'@outgoing') AS `phone`,0 AS `paused` from `queuePhone` `p` */; +/*!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 `sipConf` +-- + +/*!50001 DROP VIEW IF EXISTS `sipConf`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `sipConf` AS select `s`.`user_id` AS `id`,`s`.`extension` AS `name`,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`.`careInvite` AS `careinvite`,`c`.`insecure` AS `insecure`,`c`.`transport` AS `transport`,`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 */; + +-- +-- Current Database: `postgresql` +-- + +USE `postgresql`; + +-- +-- Current Database: `salix` +-- + +USE `salix`; + +-- +-- Final view structure for view `Account` +-- + +/*!50001 DROP VIEW IF EXISTS `Account`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `Account` AS select `u`.`id` AS `id`,`u`.`name` AS `name`,`u`.`password` AS `password`,`u`.`role` AS `roleFk`,`u`.`active` AS `active`,`u`.`email` AS `email`,`u`.`created` AS `created`,`u`.`updated` AS `updated` from `account`.`user` `u` */; +/*!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 `Role` +-- + +/*!50001 DROP VIEW IF EXISTS `Role`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `Role` AS select `r`.`id` AS `id`,`r`.`name` AS `name`,`r`.`description` AS `description`,`r`.`created` AS `created`,`r`.`modified` AS `modified` from `account`.`role` `r` */; +/*!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 `RoleMapping` +-- + +/*!50001 DROP VIEW IF EXISTS `RoleMapping`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `RoleMapping` AS select ((`u`.`id` * 1000) + `r`.`inheritsFrom`) AS `id`,'USER' AS `principalType`,`u`.`id` AS `principalId`,`r`.`inheritsFrom` AS `roleId` from (`account`.`user` `u` join `account`.`roleRole` `r` on((`r`.`role` = `u`.`role`))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Current Database: `stock` +-- + +USE `stock`; + +-- +-- Current Database: `util` +-- + +USE `util`; + +-- +-- Current Database: `vn` +-- + +USE `vn`; + +-- +-- Final view structure for view `absenceType` +-- + +/*!50001 DROP VIEW IF EXISTS `absenceType`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `absenceType` AS select `cs`.`calendar_state_id` AS `id`,`cs`.`type` AS `name`,`cs`.`rgb` AS `rgb`,`cs`.`code` AS `code` from `postgresql`.`calendar_state` `cs` */; +/*!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 `annualAverageInvoiced` +-- + +/*!50001 DROP VIEW IF EXISTS `annualAverageInvoiced`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `annualAverageInvoiced` AS select `e`.`Id_Cliente` AS `clientFk`,`e`.`Consumo` AS `invoiced` from `bi`.`facturacion_media_anual` `e` */; +/*!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 `claimRatio` +-- + +/*!50001 DROP VIEW IF EXISTS `claimRatio`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `claimRatio` AS select `bi`.`claims_ratio`.`Id_Cliente` AS `clientFk`,`bi`.`claims_ratio`.`Consumo` AS `yearSale`,`bi`.`claims_ratio`.`Reclamaciones` AS `claimAmount`,`bi`.`claims_ratio`.`Ratio` AS `claimingRate`,`bi`.`claims_ratio`.`recobro` AS `priceIncreasing`,`bi`.`claims_ratio`.`inflacion` AS `packingRate` from `bi`.`claims_ratio` */; +/*!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 `clientManaCache` +-- + +/*!50001 DROP VIEW IF EXISTS `clientManaCache`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `clientManaCache` AS select `mc`.`Id_Cliente` AS `clientFk`,`mc`.`Mana` AS `mana`,`mc`.`dated` AS `dated` from `bs`.`manaCustomer` `mc` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `clientRisk` +-- + +/*!50001 DROP VIEW IF EXISTS `clientRisk`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `clientRisk` AS select `c`.`customer_id` AS `clientFk`,`c`.`company_id` AS `companyFk`,`c`.`amount` AS `amount` from `bi`.`customer_risk` `c` */; +/*!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 `cmr_list` +-- + +/*!50001 DROP VIEW IF EXISTS `cmr_list`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `cmr_list` AS select `cmr`.`id` AS `cmrFk`,`cmr`.`ticketFk` AS `ticketFk`,`cmr`.`truckPlate` AS `truckPlate`,`cmr`.`observations` AS `observations`,`cmr`.`senderInstruccions` AS `senderInstruccions`,`cmr`.`paymentInstruccions` AS `paymentInstruccions`,`cmr`.`specialAgreements` AS `specialAgreements`,`cmr`.`created` AS `created`,`t`.`addressFk` AS `addressFk`,`t`.`shipped` AS `shipped`,`a`.`nickname` AS `clientName`,`a`.`postalCode` AS `clientPostalCode`,`a`.`street` AS `clientStreet`,`a`.`city` AS `clientCity`,`p`.`name` AS `clientProvince`,`co`.`country` AS `clientCountry`,`su`.`name` AS `companyName`,`su`.`street` AS `companyStreet`,`su`.`postCode__` AS `companyPostCode`,`su`.`city` AS `companyCity`,`sc`.`country` AS `companyCountry`,`w`.`addressName` AS `warehouseAddress`,`c`.`name` AS `clientOficialName`,ifnull(`ags`.`name`,`agm`.`name`) AS `carrierName`,`ags`.`street` AS `carrierStreet`,`ags`.`postCode` AS `carrierPostCode`,`ags`.`city` AS `carrierCity`,`sco`.`country` AS `carrierCountry`,ifnull(`a`.`phone`,`c`.`phone`) AS `phone`,ifnull(`a`.`mobile`,`c`.`mobile`) AS `mobile` from ((((((((((((`cmr` join `ticket` `t` on((`t`.`id` = `cmr`.`ticketFk`))) join `address` `a` on((`a`.`id` = `t`.`addressFk`))) join `province` `p` on((`p`.`id` = `a`.`provinceFk`))) join `country` `co` on((`co`.`id` = `p`.`countryFk`))) join `warehouse` `w` on((`w`.`id` = `t`.`warehouseFk`))) join `supplier` `su` on((`su`.`id` = `t`.`companyFk`))) join `country` `sc` on((`sc`.`id` = `su`.`countryFk`))) join `client` `c` on((`c`.`id` = `t`.`clientFk`))) join `agencyMode` `agm` on((`agm`.`id` = `t`.`agencyModeFk`))) join `agency` `ag` on((`ag`.`id` = `agm`.`agencyFk`))) left join `supplier` `ags` on((`ags`.`id` = `ag`.`supplierFk`))) left join `country` `sco` on((`sco`.`id` = `ags`.`countryFk`))) */; +/*!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 `collectionReportSource` +-- + +/*!50001 DROP VIEW IF EXISTS `collectionReportSource`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `collectionReportSource` AS select `tc`.`collectionFk` AS `collectionFk`,`tc`.`ticketFk` AS `ticketFk`,`s`.`itemFk` AS `itemFk`,`s`.`concept` AS `concept`,`i`.`size` AS `size`,`s`.`quantity` AS `quantity`,`ip`.`code` AS `nicho`,`tc`.`level` AS `level` from (((((`collection` `c` join `ticketCollection` `tc` on((`tc`.`collectionFk` = `c`.`id`))) join `ticket` `t` on((`t`.`id` = `tc`.`ticketFk`))) join `sale` `s` on((`s`.`ticketFk` = `t`.`id`))) join `item` `i` on((`i`.`id` = `s`.`itemFk`))) join `itemPlacement` `ip` on(((`ip`.`itemFk` = `s`.`itemFk`) and (`ip`.`warehouseFk` = `t`.`warehouseFk`)))) */; +/*!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 `component` +-- + +/*!50001 DROP VIEW IF EXISTS `component`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `component` AS select `t`.`Id_Componente` AS `id`,`t`.`Componente` AS `name`,`t`.`tarifa_componentes_series_id` AS `typeFk`,`t`.`tarifa_class` AS `classRate`,`t`.`tax` AS `tax`,`t`.`is_renewable` AS `isRenewable` from `bi`.`tarifa_componentes` `t` */; +/*!50001 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 `componentRate` +-- + +/*!50001 DROP VIEW IF EXISTS `componentRate`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `componentRate` AS select `t`.`Id_Componente` AS `id`,`t`.`Componente` AS `name`,`t`.`tarifa_componentes_series_id` AS `componentTypeRate`,`t`.`tarifa_class` AS `classRate`,`t`.`tax` AS `tax`,`t`.`is_renewable` AS `isRenewable`,`t`.`code` AS `code` from `bi`.`tarifa_componentes` `t` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `componentType` +-- + +/*!50001 DROP VIEW IF EXISTS `componentType`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `componentType` AS select `t`.`tarifa_componentes_series_id` AS `id`,`t`.`Serie` AS `type`,`t`.`base` AS `base`,`t`.`margen` AS `isMargin` from `bi`.`tarifa_componentes_series` `t` */; +/*!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 `componentTypeRate` +-- + +/*!50001 DROP VIEW IF EXISTS `componentTypeRate`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `componentTypeRate` AS select `t`.`tarifa_componentes_series_id` AS `id`,`t`.`Serie` AS `type`,`t`.`base` AS `base` from `bi`.`tarifa_componentes_series` `t` */; +/*!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 `defaulter` +-- + +/*!50001 DROP VIEW IF EXISTS `defaulter`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `defaulter` AS select `d`.`client` AS `clientFk`,`d`.`date` AS `created`,`d`.`amount` AS `amount`,`d`.`defaulterSince` AS `defaulterSinced`,`d`.`hasChanged` AS `hasChanged` from `bi`.`defaulters` `d` */; +/*!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 `departmentTree` +-- + +/*!50001 DROP VIEW IF EXISTS `departmentTree`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `departmentTree` AS select `node`.`id` AS `id`,concat(repeat(repeat(' ',5),(count(`parent`.`id`) - 1)),`node`.`name`) AS `dep` from (`department` `node` join `department` `parent`) where (`node`.`lft` between `parent`.`lft` and `parent`.`rgt`) group by `node`.`id` order by `node`.`lft` */; +/*!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 `ediGenus` +-- + +/*!50001 DROP VIEW IF EXISTS `ediGenus`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `ediGenus` AS select `g`.`genus_id` AS `id`,`g`.`latin_genus_name` AS `latinGenusName`,`g`.`entry_date` AS `entried`,`g`.`expiry_date` AS `dued`,`g`.`change_date_time` AS `modified` from `edi`.`genus` `g` */; +/*!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 `ediSpecie` +-- + +/*!50001 DROP VIEW IF EXISTS `ediSpecie`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `ediSpecie` AS select `s`.`specie_id` AS `id`,`s`.`genus_id` AS `genusFk`,`s`.`latin_species_name` AS `latinSpeciesName`,`s`.`entry_date` AS `entried`,`s`.`expiry_date` AS `dued`,`s`.`change_date_time` AS `modified` from `edi`.`specie` `s` */; +/*!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 `exchangeInsuranceEntry` +-- + +/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceEntry`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `exchangeInsuranceEntry` AS select max(`tr`.`landed`) AS `dated`,cast(sum(((`b`.`buyingValue` + `b`.`freightValue`) * `b`.`quantity`)) as decimal(10,2)) AS `Dolares`,cast((sum(((`b`.`buyingValue` + `b`.`freightValue`) * `b`.`quantity`)) / sum(((((100 + `e`.`commission`) / 100) * (`b`.`buyingValue` + `b`.`freightValue`)) * `b`.`quantity`))) as decimal(10,4)) AS `rate` from ((`entry` `e` join `buy` `b` on((`e`.`id` = `b`.`entryFk`))) join `travel` `tr` on((`tr`.`id` = `e`.`travelFk`))) where ((`tr`.`landed` between '2016-01-31' and curdate()) and (`e`.`commission` < 0) and (`e`.`currencyFk` = 2)) group by month(`tr`.`landed`),year(`tr`.`landed`) */; +/*!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 `exchangeInsuranceIn` +-- + +/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceIn`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `exchangeInsuranceIn` AS select `exchangeInsuranceInPrevious`.`dated` AS `dated`,sum(`exchangeInsuranceInPrevious`.`amount`) AS `amount`,cast((sum((`exchangeInsuranceInPrevious`.`amount` * `exchangeInsuranceInPrevious`.`rate`)) / sum(`exchangeInsuranceInPrevious`.`amount`)) as decimal(10,4)) AS `rate` from `vn`.`exchangeInsuranceInPrevious` group by `exchangeInsuranceInPrevious`.`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 `exchangeInsuranceOut` +-- + +/*!50001 DROP VIEW IF EXISTS `exchangeInsuranceOut`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `exchangeInsuranceOut` AS select `p`.`received` AS `received`,sum(`p`.`divisa`) AS `divisa`,(sum(`p`.`divisa`) / sum(`p`.`amount`)) AS `rate` from (`vn`.`payment` `p` join `vn`.`bank` `b` on((`b`.`id` = `p`.`bankFk`))) where ((`p`.`currencyFk` = 2) and (`b`.`cash` = 0) and (`p`.`supplierFk` <> 2213)) group by `p`.`received` */; +/*!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 = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `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 `vn`.`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 `vn`.`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 `vn`.`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 `firstTicketShipped` +-- + +/*!50001 DROP VIEW IF EXISTS `firstTicketShipped`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `firstTicketShipped` AS select min(`ticket`.`shipped`) AS `shipped`,`ticket`.`clientFk` AS `clientFk` from `ticket` where (`ticket`.`shipped` > '2001-01-01') group by `ticket`.`clientFk` */; +/*!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 `floraHollandBuyedItems` +-- + +/*!50001 DROP VIEW IF EXISTS `floraHollandBuyedItems`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `floraHollandBuyedItems` AS select `b`.`itemFk` AS `itemFk`,`i`.`longName` AS `longName`,`b`.`quantity` AS `quantity`,`b`.`buyingValue` AS `buyingValue`,`tr`.`landed` AS `landed`,`e`.`companyFk` AS `companyFk` from (((((`buy` `b` join `item` `i` on((`b`.`itemFk` = `i`.`id`))) join `itemType` `it` on((`it`.`id` = `i`.`typeFk`))) join `itemCategory` `ic` on((`ic`.`id` = `it`.`categoryFk`))) join `entry` `e` on((`e`.`id` = `b`.`entryFk`))) join `travel` `tr` on(((`tr`.`id` = `e`.`travelFk`) and (`ic`.`id` not in (8,6)) and (`b`.`buyingValue` <> 0) and (`b`.`quantity` <> 0) and (`e`.`supplierFk` in (1664,1665,1666,1465,1433))))) */; +/*!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 `holiday` +-- + +/*!50001 DROP VIEW IF EXISTS `holiday`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `holiday` AS select `cl`.`calendar_labour_legend_id` AS `holidayDetailFk`,`cl`.`calendar_free_id` AS `holidayTypeFk`,`cl`.`workcenter_id` AS `workCenterFk`,`cl`.`day` AS `dated` from `postgresql`.`calendar_labour` `cl` */; +/*!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 `holidayDetail` +-- + +/*!50001 DROP VIEW IF EXISTS `holidayDetail`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `holidayDetail` AS select `cll`.`calendar_labour_legend_id` AS `id`,`cll`.`descripcion` AS `description` from `postgresql`.`calendar_labour_legend` `cll` */; +/*!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 `holidayLegend` +-- + +/*!50001 DROP VIEW IF EXISTS `holidayLegend`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `holidayLegend` AS select `cll`.`calendar_labour_legend_id` AS `id`,`cll`.`descripcion` AS `description` from `postgresql`.`calendar_labour_legend` `cll` */; +/*!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 `holidayType` +-- + +/*!50001 DROP VIEW IF EXISTS `holidayType`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `holidayType` AS select `cf`.`calendar_free_id` AS `id`,`cf`.`type` AS `name`,`cf`.`rgb` AS `rgb` from `postgresql`.`calendar_free` `cf` */; +/*!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 `inkL10n` +-- + +/*!50001 DROP VIEW IF EXISTS `inkL10n`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `inkL10n` AS select `k`.`id` AS `id`,ifnull(`i`.`name`,`k`.`name`) AS `name` from (`ink` `k` left join `inkI18n` `i` on(((`i`.`inkFk` = `k`.`id`) and (`i`.`lang` = `util`.`lang`())))) */; +/*!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 `invoiceCorrectionDataSource` +-- + +/*!50001 DROP VIEW IF EXISTS `invoiceCorrectionDataSource`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `invoiceCorrectionDataSource` AS select `s`.`itemFk` AS `itemFk`,`s`.`quantity` AS `quantity`,`s`.`concept` AS `concept`,`s`.`price` AS `price`,`s`.`discount` AS `discount`,`t`.`refFk` AS `refFk`,`s`.`id` AS `saleFk`,`t`.`shipped` AS `shipped` from (`sale` `s` join `ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) */; +/*!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 `itemBotanicalWithGenus` +-- + +/*!50001 DROP VIEW IF EXISTS `itemBotanicalWithGenus`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemBotanicalWithGenus` AS select `ib`.`itemFk` AS `itemFk`,ifnull(`ib`.`botanical`,concat(`g`.`latinGenusName`,' ',ifnull(`s`.`latinSpeciesName`,''))) AS `ediBotanic` from ((`vn`.`itemBotanical` `ib` left join `vn`.`ediGenus` `g` on((`g`.`id` = `ib`.`genusFk`))) left join `vn`.`ediSpecie` `s` on((`s`.`id` = `ib`.`specieFk`))) */; +/*!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 `itemCategoryL10n` +-- + +/*!50001 DROP VIEW IF EXISTS `itemCategoryL10n`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemCategoryL10n` AS select `c`.`id` AS `id`,ifnull(`i`.`name`,`c`.`name`) AS `name` from (`itemCategory` `c` left join `itemCategoryI18n` `i` on(((`i`.`categoryFk` = `c`.`id`) and (`i`.`lang` = `util`.`lang`())))) */; +/*!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 `itemEntryIn` +-- + +/*!50001 DROP VIEW IF EXISTS `itemEntryIn`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemEntryIn` AS select `t`.`warehouseInFk` AS `warehouseInFk`,`t`.`landed` AS `landed`,`b`.`itemFk` AS `itemFk`,`b`.`quantity` AS `quantity`,`t`.`isReceived` AS `isReceived`,`e`.`isRaid` AS `isVirtualStock`,`e`.`id` AS `entryFk` from ((`buy` `b` join `entry` `e` on((`b`.`entryFk` = `e`.`id`))) join `travel` `t` on((`e`.`travelFk` = `t`.`id`))) where ((`e`.`isInventory` = 0) and (`b`.`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 */; + +-- +-- Final view structure for view `itemEntryOut` +-- + +/*!50001 DROP VIEW IF EXISTS `itemEntryOut`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemEntryOut` AS select `t`.`warehouseOutFk` AS `warehouseOutFk`,`t`.`shipped` AS `shipped`,`b`.`itemFk` AS `itemFk`,-(`b`.`quantity`) AS `quantity`,`t`.`isDelivered` AS `isDelivered`,`e`.`id` AS `entryFk` from ((`buy` `b` join `entry` `e` on((`b`.`entryFk` = `e`.`id`))) join `travel` `t` on((`e`.`travelFk` = `t`.`id`))) where ((`e`.`isInventory` = 0) and (`e`.`isRaid` = 0) and (`b`.`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 */; + +-- +-- Final view structure for view `itemPlacementSupplyList` +-- + +/*!50001 DROP VIEW IF EXISTS `itemPlacementSupplyList`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemPlacementSupplyList` AS select `ips`.`id` AS `id`,`ips`.`itemFk` AS `itemFk`,`ips`.`quantity` AS `quantity`,`ips`.`priority` AS `priority`,ifnull(`isps`.`created`,`ips`.`created`) AS `created`,`ips`.`userFk` AS `userFk`,`ips`.`repoUserFk` AS `repoUserFk`,(`ips`.`quantity` - sum(ifnull(`isps`.`quantity`,0))) AS `saldo`,concat(`i`.`longName`,' ',`i`.`size`) AS `longName`,`i`.`subName` AS `subName`,`i`.`size` AS `size`,`w`.`code` AS `workerCode`,`rw`.`code` AS `repoCode`,max(`p`.`code`) AS `parking`,`ips`.`sectorFk` AS `sectorFk` from (((((((`itemPlacementSupply` `ips` join `item` `i` on((`i`.`id` = `ips`.`itemFk`))) left join `worker` `w` on((`w`.`userFk` = `ips`.`userFk`))) left join `worker` `rw` on((`rw`.`userFk` = `ips`.`repoUserFk`))) left join `itemShelvingPlacementSupply` `isps` on((`isps`.`itemPlacementSupplyFk` = `ips`.`id`))) left join `itemShelving` `ish` on((`ish`.`id` = `isps`.`itemShelvingFk`))) left join `shelving` `s` on((`ish`.`shelvingFk` = `s`.`code`))) left join `parking` `p` on((`s`.`parkingFk` = `p`.`id`))) where (`ips`.`created` >= curdate()) group by `ips`.`priority`,`ips`.`id`,`p`.`sectorFk` */; +/*!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 `itemPlacementSupplyList__` +-- + +/*!50001 DROP VIEW IF EXISTS `itemPlacementSupplyList__`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemPlacementSupplyList__` AS select `ips`.`id` AS `id`,`ips`.`itemFk` AS `itemFk`,`ips`.`quantity` AS `quantity`,`ips`.`priority` AS `priority`,`ips`.`created` AS `created`,`ips`.`userFk` AS `userFk`,`ips`.`repoUserFk` AS `repoUserFk`,(`ips`.`quantity` - sum(ifnull(`isps`.`quantity`,0))) AS `saldo`,concat(`i`.`longName`,' ',`i`.`size`) AS `longName`,`i`.`subName` AS `subName`,`i`.`size` AS `size`,`w`.`code` AS `workerCode`,`rw`.`code` AS `repoCode`,max(`p`.`code`) AS `parking`,max(`p`.`sectorFk`) AS `sectorFk` from (((((((`itemPlacementSupply` `ips` join `itemShelving` `ish` on((`ish`.`itemFk` = `ips`.`itemFk`))) join `item` `i` on((`i`.`id` = `ish`.`itemFk`))) left join `worker` `w` on((`w`.`userFk` = `ips`.`userFk`))) left join `worker` `rw` on((`rw`.`userFk` = `ips`.`repoUserFk`))) left join `itemShelvingPlacementSupply` `isps` on((`isps`.`itemPlacementSupplyFk` = `ips`.`id`))) left join `shelving` `s` on((`ish`.`shelvingFk` = `s`.`code`))) left join `parking` `p` on((`s`.`parkingFk` = `p`.`id`))) where (`ips`.`created` >= curdate()) group by `ips`.`priority`,`ips`.`id`,`p`.`sectorFk` */; +/*!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 `itemShelvingAvailable` +-- + +/*!50001 DROP VIEW IF EXISTS `itemShelvingAvailable`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemShelvingAvailable` AS select `s`.`id` AS `saleFk`,`tst`.`updated` AS `Modificado`,`s`.`ticketFk` AS `ticketFk`,0 AS `isPicked`,`s`.`itemFk` AS `itemFk`,`s`.`quantity` AS `quantity`,`s`.`concept` AS `concept`,`i`.`size` AS `size`,`st`.`name` AS `Estado`,`st`.`sectorProdPriority` AS `sectorProdPriority`,`stock`.`visible` AS `available`,`stock`.`sectorFk` AS `sectorFk`,`stock`.`shelvingFk` AS `matricula`,`stock`.`parkingFk` AS `parking`,`stock`.`itemShelvingFk` AS `itemShelving`,`am`.`name` AS `Agency`,`t`.`shipped` AS `shipped`,`stock`.`grouping` AS `grouping`,`stock`.`packing` AS `packing`,`z`.`hour` AS `hour`,`st`.`isPreviousPreparable` AS `isPreviousPreparable`,`sv`.`physicalVolume` AS `physicalVolume` from (((((((((`vn`.`sale` `s` join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`agencyMode` `am` on((`am`.`id` = `t`.`agencyModeFk`))) join `vn`.`ticketStateToday` `tst` on((`tst`.`ticket` = `t`.`id`))) join `vn`.`state` `st` on((`st`.`id` = `tst`.`state`))) join `vn`.`item` `i` on((`i`.`id` = `s`.`itemFk`))) join `vn`.`itemShelvingStock` `stock` on((`stock`.`itemFk` = `i`.`id`))) left join `vn`.`saleTracking` `stk` on((`stk`.`saleFk` = `s`.`id`))) left join `vn`.`zone` `z` on((`z`.`id` = `t`.`zoneFk`))) left join `vn`.`saleVolume` `sv` on((`sv`.`saleFk` = `s`.`id`))) where ((`t`.`shipped` between `util`.`yesterday`() and `util`.`dayend`(curdate())) and isnull(`stk`.`id`) and (`stock`.`visible` > 0) and isnull(`stk`.`saleFk`) and `st`.`sectorProdPriority`) */; +/*!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 `itemShelvingList` +-- + +/*!50001 DROP VIEW IF EXISTS `itemShelvingList`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemShelvingList` AS select `ish`.`shelvingFk` AS `shelvingFk`,`ish`.`visible` AS `visible`,`ish`.`created` AS `created`,`pk`.`code` AS `parking`,`ish`.`itemFk` AS `itemFk`,`i`.`longName` AS `longName`,`i`.`size` AS `size`,`i`.`subName` AS `subName`,`sh`.`parked` AS `parked` from (((`itemShelving` `ish` join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) join `item` `i` on((`i`.`id` = `ish`.`itemFk`))) left join `parking` `pk` on((`pk`.`id` = `sh`.`parkingFk`))) order by `ish`.`created` */; +/*!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 `itemShelvingPlacementSupplyStock` +-- + +/*!50001 DROP VIEW IF EXISTS `itemShelvingPlacementSupplyStock`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemShelvingPlacementSupplyStock` AS select `ish`.`id` AS `itemShelvingFk`,`ish`.`itemFk` AS `itemFk`,`ish`.`quantity` AS `quantity`,`ish`.`packing` AS `packing`,`ish`.`visible` AS `stock`,`i`.`longName` AS `longName`,`i`.`size` AS `size`,`i`.`subName` AS `subName`,`sh`.`code` AS `shelving`,`p`.`code` AS `parking`,`ish`.`created` AS `created`,ifnull(`sh`.`priority`,1) AS `priority`,`p`.`id` AS `parkingFk`,`p`.`sectorFk` AS `sectorFk` from (((((`itemShelving` `ish` join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) left join `parking` `p` on((`p`.`id` = `sh`.`parkingFk`))) join `item` `i` on((`i`.`id` = `ish`.`itemFk`))) left join `itemShelvingSale` `iss` on((`iss`.`itemShelvingFk` = `ish`.`id`))) left join `itemShelvingPlacementSupply` `isps` on((`isps`.`itemShelvingFk` = `ish`.`id`))) group by `ish`.`id` */; +/*!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 `itemShelvingPlacementSupplyStock__` +-- + +/*!50001 DROP VIEW IF EXISTS `itemShelvingPlacementSupplyStock__`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemShelvingPlacementSupplyStock__` AS select `ish`.`id` AS `itemShelvingFk`,`ish`.`itemFk` AS `itemFk`,`ish`.`quantity` AS `quantity`,`ish`.`packing` AS `packing`,`ish`.`visible` AS `stock`,`i`.`longName` AS `longName`,`i`.`size` AS `size`,`i`.`subName` AS `subName`,`sh`.`code` AS `shelving`,`p`.`code` AS `parking`,`ish`.`created` AS `created`,ifnull(`sh`.`priority`,1) AS `priority` from (((((`itemShelving` `ish` join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) left join `parking` `p` on((`p`.`id` = `sh`.`parkingFk`))) join `item` `i` on((`i`.`id` = `ish`.`itemFk`))) left join `itemShelvingSale` `iss` on((`iss`.`itemShelvingFk` = `ish`.`id`))) left join `itemShelvingPlacementSupply` `isps` on((`isps`.`itemShelvingFk` = `ish`.`id`))) group by `ish`.`id` */; +/*!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 `itemShelvingSaleSum` +-- + +/*!50001 DROP VIEW IF EXISTS `itemShelvingSaleSum`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemShelvingSaleSum` AS select `iss`.`id` AS `id`,`iss`.`itemShelvingFk` AS `itemShelvingFk`,`iss`.`saleFk` AS `saleFk`,sum(`iss`.`quantity`) AS `quantity`,`iss`.`created` AS `created`,`p`.`sectorFk` AS `sectorFk` from (((`itemShelvingSale` `iss` join `itemShelving` `ish` on((`ish`.`id` = `iss`.`itemShelvingFk`))) join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) join `parking` `p` on((`p`.`id` = `sh`.`parkingFk`))) group by `iss`.`saleFk` */; +/*!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 `itemShelvingStock` +-- + +/*!50001 DROP VIEW IF EXISTS `itemShelvingStock`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemShelvingStock` AS select `ish`.`itemFk` AS `itemFk`,sum(`ish`.`visible`) AS `visible`,min(`ish`.`packing`) AS `packing`,min(`ish`.`grouping`) AS `grouping`,`s`.`description` AS `sector`,sum(`ish`.`visible`) AS `visibleOriginal`,sum(`issr`.`removed`) AS `removed`,`p`.`sectorFk` AS `sectorFk`,`s`.`warehouseFk` AS `warehouseFk`,`ish`.`shelvingFk` AS `shelvingFk`,`p`.`code` AS `parkingCode`,`sh`.`parkingFk` AS `parkingFk`,`ish`.`id` AS `itemShelvingFk`,`ish`.`created` AS `created` from ((((`itemShelving` `ish` left join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) left join `parking` `p` on((`p`.`id` = `sh`.`parkingFk`))) left join `sector` `s` on((`s`.`id` = `p`.`sectorFk`))) left join `itemShelvingStockRemoved` `issr` on((`issr`.`itemShelvingFk` = `ish`.`id`))) where ((`ish`.`visible` <> 0) and `p`.`sectorFk`) group by `ish`.`itemFk`,`p`.`sectorFk` */; +/*!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 `itemShelvingStockFull` +-- + +/*!50001 DROP VIEW IF EXISTS `itemShelvingStockFull`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemShelvingStockFull` AS select `ish`.`itemFk` AS `itemFk`,`ish`.`visible` AS `quantity`,`ish`.`packing` AS `packing`,`ish`.`grouping` AS `grouping`,`s`.`description` AS `sector`,`issr`.`removed` AS `removed`,`p`.`sectorFk` AS `sectorFk`,`s`.`warehouseFk` AS `warehouseFk`,`ish`.`shelvingFk` AS `shelvingFk`,`p`.`code` AS `parkingCode`,`sh`.`parkingFk` AS `parkingFk`,`ish`.`id` AS `itemShelvingFk`,`ish`.`created` AS `created` from ((((`itemShelving` `ish` join `shelving` `sh` on((`sh`.`code` = `ish`.`shelvingFk`))) join `parking` `p` on((`p`.`id` = `sh`.`parkingFk`))) join `sector` `s` on((`s`.`id` = `p`.`sectorFk`))) left join `itemShelvingStockRemoved` `issr` on((`issr`.`itemShelvingFk` = `ish`.`id`))) */; +/*!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 `itemShelvingStockRemoved` +-- + +/*!50001 DROP VIEW IF EXISTS `itemShelvingStockRemoved`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemShelvingStockRemoved` AS select `ish`.`id` AS `itemShelvingFk`,`ish`.`itemFk` AS `itemFk`,(sum(ifnull(`iss`.`quantity`,0)) + sum(ifnull(`isps`.`quantity`,0))) AS `removed` from ((`itemShelving` `ish` left join `itemShelvingSale` `iss` on((`iss`.`itemShelvingFk` = `ish`.`id`))) left join `itemShelvingPlacementSupply` `isps` on((`isps`.`itemShelvingFk` = `ish`.`id`))) group by `ish`.`id` */; +/*!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 `itemTagged` +-- + +/*!50001 DROP VIEW IF EXISTS `itemTagged`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemTagged` AS select distinct `itemTag`.`itemFk` AS `itemFk` from `itemTag` */; +/*!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 `itemTicketOut` +-- + +/*!50001 DROP VIEW IF EXISTS `itemTicketOut`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemTicketOut` AS select `t`.`warehouseFk` AS `warehouseFk`,`t`.`shipped` AS `shipped`,`s`.`itemFk` AS `itemFk`,-(`s`.`quantity`) AS `quantity`,`s`.`isPicked` AS `isPicked`,`s`.`reserved` AS `reserved`,`t`.`refFk` AS `refFk`,`s`.`id` AS `saleFk`,`s`.`ticketFk` AS `ticketFk` from (`sale` `s` join `ticket` `t` on((`s`.`ticketFk` = `t`.`id`))) 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 */; + +-- +-- Final view structure for view `itemTypeL10n` +-- + +/*!50001 DROP VIEW IF EXISTS `itemTypeL10n`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `itemTypeL10n` AS select `t`.`id` AS `id`,ifnull(`i`.`name`,`t`.`name`) AS `name` from (`itemType` `t` left join `itemTypeI18n` `i` on(((`i`.`typeFk` = `t`.`id`) and (`i`.`lang` = `util`.`LANG`())))) */; +/*!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 `originL10n` +-- + +/*!50001 DROP VIEW IF EXISTS `originL10n`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `originL10n` AS select `o`.`id` AS `id`,ifnull(`i`.`name`,`o`.`name`) AS `name` from (`origin` `o` left join `originI18n` `i` on(((`i`.`originFk` = `o`.`id`) and (`i`.`lang` = `util`.`lang`())))) */; +/*!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 `packageEquivalentItem` +-- + +/*!50001 DROP VIEW IF EXISTS `packageEquivalentItem`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `packageEquivalentItem` AS select `i`.`itemFk` AS `itemFk`,`ie`.`itemFk` AS `equivalentFk` from ((`packageEquivalent` `pe` join `packaging` `i` on((`i`.`id` = `pe`.`packageFk`))) join `packaging` `ie` on((`ie`.`id` = `pe`.`equivalentFk`))) */; +/*!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 `personMedia` +-- + +/*!50001 DROP VIEW IF EXISTS `personMedia`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `personMedia` AS select `p`.`id_trabajador` AS `workerFk`,`m`.`value` AS `mediaValue` from ((((`postgresql`.`person` `p` join `postgresql`.`profile` `po` on((`po`.`person_id` = `p`.`person_id`))) join `postgresql`.`profile_media` `pom` on((`pom`.`profile_id` = `po`.`profile_id`))) join `postgresql`.`media` `m` on((`m`.`media_id` = `pom`.`media_id`))) join `postgresql`.`media_type` `mt` on((`mt`.`media_type_id` = `m`.`media_type_id`))) where (`mt`.`name` = 'movil personal') */; +/*!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 `role` +-- + +/*!50001 DROP VIEW IF EXISTS `role`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `role` AS select `account`.`role`.`id` AS `id`,`account`.`role`.`name` AS `name`,`account`.`role`.`description` AS `description`,`account`.`role`.`hasLogin` AS `hasLogin` from `account`.`role` */; +/*!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 `saleFreight` +-- + +/*!50001 DROP VIEW IF EXISTS `saleFreight`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `saleFreight` AS select `s`.`ticketFk` AS `ticketFk`,`t`.`clientFk` AS `clientFk`,`t`.`routeFk` AS `routeFk`,`s`.`id` AS `saleFk`,`t`.`zoneFk` AS `zoneFk`,`t`.`companyFk` AS `companyFk`,`t`.`shipped` AS `shipped`,`zc`.`price` AS `price`,((((`s`.`quantity` * `r`.`cm3`) * `zc`.`price`) * `i`.`compression`) / `cb`.`volume`) AS `freight`,(((`s`.`quantity` * `r`.`cm3`) * `i`.`compression`) / 1000000) AS `volume` from (((((`vn`.`sale` `s` join `vn`.`item` `i` on((`i`.`id` = `s`.`itemFk`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`packaging` `cb` on((`cb`.`id` = '94'))) join `bi`.`rotacion` `r` on(((`r`.`Id_Article` = `s`.`itemFk`) and (`r`.`warehouse_id` = `t`.`warehouseFk`)))) join `vn`.`zoneCalendar` `zc` on(((`zc`.`zoneFk` = `t`.`zoneFk`) and (`zc`.`delivered` = `t`.`landed`)))) */; +/*!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 `saleVolume` +-- + +/*!50001 DROP VIEW IF EXISTS `saleVolume`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `saleVolume` AS select `s`.`ticketFk` AS `ticketFk`,`s`.`id` AS `saleFk`,ifnull(round(((((`i`.`compression` * (greatest(`i`.`density`,167) / 167)) * `r`.`cm3`) * `s`.`quantity`) / 1000),2),0) AS `litros`,`t`.`routeFk` AS `routeFk`,`t`.`shipped` AS `shipped`,(((`s`.`quantity` * `r`.`cm3`) * `i`.`compression`) / 1000000) AS `volume`,((((`s`.`quantity` * `r`.`cm3`) * `i`.`compression`) * (greatest(`i`.`density`,167) / 167)) / 1000000) AS `physicalWeight`,(((`s`.`quantity` * `r`.`cm3`) * `i`.`density`) / 1000000) AS `weight`,(((`s`.`quantity` * `r`.`cm3`) * `i`.`compression`) / 1000000) AS `physicalVolume` from (((`vn`.`sale` `s` join `vn`.`item` `i` on((`i`.`id` = `s`.`itemFk`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `bi`.`rotacion` `r` on(((`r`.`Id_Article` = `s`.`itemFk`) and (`r`.`warehouse_id` = `t`.`warehouseFk`)))) */; +/*!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 `supplierPackaging` +-- + +/*!50001 DROP VIEW IF EXISTS `supplierPackaging`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `supplierPackaging` AS select `e`.`supplierFk` AS `supplierFk`,`b`.`itemFk` AS `itemFk`,`i`.`longName` AS `longName`,`s`.`name` AS `supplier`,`b`.`entryFk` AS `entryFk`,`tr`.`landed` AS `landed`,-(least(`b`.`quantity`,0)) AS `out`,greatest(`b`.`quantity`,0) AS `in`,`w`.`name` AS `almacen` from ((((((`buy` `b` join `item` `i` on((`i`.`id` = `b`.`itemFk`))) join `packaging` `p` on((`p`.`itemFk` = `i`.`id`))) join `entry` `e` on((`e`.`id` = `b`.`entryFk`))) join `supplier` `s` on((`s`.`id` = `e`.`supplierFk`))) join `travel` `tr` on((`tr`.`id` = `e`.`travelFk`))) join `warehouse` `w` on((`w`.`id` = `tr`.`warehouseInFk`))) where `p`.`isPackageReturnable` */; +/*!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 `tagL10n` +-- + +/*!50001 DROP VIEW IF EXISTS `tagL10n`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `tagL10n` AS select `t`.`id` AS `id`,ifnull(`i`.`name`,`t`.`name`) AS `name` from (`tag` `t` left join `tagI18n` `i` on(((`i`.`tagFk` = `t`.`id`) and (`i`.`lang` = `util`.`LANG`())))) */; +/*!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 `ticketGetVolume__` +-- + +/*!50001 DROP VIEW IF EXISTS `ticketGetVolume__`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `ticketGetVolume__` AS select `s`.`ticketFk` AS `ticketFk`,`t`.`routeFk` AS `routeFk`,`s`.`id` AS `saleFk`,`t`.`shipped` AS `shipped`,(((`s`.`quantity` * `r`.`cm3`) * `i`.`compression`) / 1000000) AS `volume` from (((`vn`.`sale` `s` join `vn`.`item` `i` on((`i`.`id` = `s`.`itemFk`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `bi`.`rotacion` `r` on(((`r`.`Id_Article` = `s`.`itemFk`) and (`r`.`warehouse_id` = `t`.`warehouseFk`)))) */; +/*!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 `ticketNotInvoiced` +-- + +/*!50001 DROP VIEW IF EXISTS `ticketNotInvoiced`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `ticketNotInvoiced` AS select `t`.`companyFk` AS `companyFk`,`cm`.`code` AS `companyCode`,`t`.`clientFk` AS `clientFk`,`c`.`name` AS `clientName`,`t`.`shipped` AS `shipped`,cast(sum((((`s`.`quantity` * `s`.`price`) * (100 - `s`.`discount`)) / 100)) as decimal(10,2)) AS `value` from (((`ticket` `t` join `sale` `s` on((`s`.`ticketFk` = `t`.`id`))) join `client` `c` on((`c`.`id` = `t`.`clientFk`))) join `company` `cm` on((`cm`.`id` = `t`.`companyFk`))) where (isnull(`t`.`refFk`) and (`t`.`shipped` > '2017-01-01')) group by `t`.`id` */; +/*!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 `ticketPreviousPreparingList` +-- + +/*!50001 DROP VIEW IF EXISTS `ticketPreviousPreparingList`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `ticketPreviousPreparingList` AS select `t`.`id` AS `ticketFk`,`w`.`code` AS `code`,count(`st`.`id`) AS `saleLines`,sum((`st`.`isChecked` <> 0)) AS `alreadyMadeSaleLines`,(sum((`st`.`isChecked` <> 0)) / count(`st`.`id`)) AS `madeRate`,`st`.`created` AS `created`,`i`.`sectorFk` AS `sectorFk`,`p`.`code` AS `parking` from (((((((`ticket` `t` join `sale` `s` on((`s`.`ticketFk` = `t`.`id`))) join `item` `i` on((`i`.`id` = `s`.`itemFk`))) join `saleTracking` `st` on((`st`.`saleFk` = `s`.`id`))) join `state` on((`state`.`id` = `st`.`stateFk`))) left join `worker` `w` on((`w`.`id` = `st`.`workerFk`))) left join `ticketParking` `tp` on((`tp`.`ticketFk` = `t`.`id`))) left join `parking` `p` on((`p`.`id` = `tp`.`parkingFk`))) where ((`state`.`code` = 'PREVIOUS_PREPARATION') and (`t`.`shipped` >= (curdate() + interval -(1) day))) group by `s`.`ticketFk`,`i`.`sectorFk` */; +/*!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 `ticketState` +-- + +/*!50001 DROP VIEW IF EXISTS `ticketState`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `ticketState` AS select `i`.`odbc_date` AS `updated`,`i`.`state_id` AS `stateFk`,`i`.`Id_Trabajador` AS `workerFk`,`tls`.`ticketFk` AS `ticketFk`,`s`.`id` AS `state`,`s`.`order` AS `productionOrder`,`s`.`alertLevel` AS `alertLevel`,`s`.`code` AS `code`,`tls`.`ticketFk` AS `ticket`,`i`.`Id_Trabajador` AS `worker`,`s`.`isPreviousPreparable` AS `isPreviousPreparable`,`s`.`isPicked` AS `isPicked` from ((`vn`.`ticketLastState` `tls` join `vncontrol`.`inter` `i` on((`i`.`inter_id` = `tls`.`ticketTrackingFk`))) join `vn`.`state` `s` on((`s`.`id` = `i`.`state_id`))) */; +/*!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 `ticketStateToday` +-- + +/*!50001 DROP VIEW IF EXISTS `ticketStateToday`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `ticketStateToday` AS select `ts`.`ticket` AS `ticket`,`ts`.`state` AS `state`,`ts`.`productionOrder` AS `productionOrder`,`ts`.`alertLevel` AS `alertLevel`,`ts`.`worker` AS `worker`,`ts`.`code` AS `code`,`ts`.`updated` AS `updated`,`ts`.`isPicked` AS `isPicked` from (`vn`.`ticketState` `ts` join `vn`.`ticket` `t` on((`t`.`id` = `ts`.`ticket`))) where (`t`.`shipped` between curdate() and `MIDNIGHT`(curdate())) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `ticketTracking` +-- + +/*!50001 DROP VIEW IF EXISTS `ticketTracking`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `ticketTracking` AS select `i`.`inter_id` AS `id`,`i`.`state_id` AS `stateFk`,`i`.`odbc_date` AS `created`,`i`.`Id_Ticket` AS `ticketFk`,`i`.`Id_Trabajador` AS `workerFk` from `vncontrol`.`inter` `i` */; +/*!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 `user` +-- + +/*!50001 DROP VIEW IF EXISTS `user`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `user` AS select `account`.`user`.`id` AS `id`,`account`.`user`.`name` AS `name`,`account`.`user`.`password` AS `password`,`account`.`user`.`role` AS `role`,`account`.`user`.`active` AS `active`,`account`.`user`.`recoverPass` AS `recoverPass`,`account`.`user`.`lastPassChange` AS `lastPassChange` from `account`.`user` */; +/*!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 `workerCalendar` +-- + +/*!50001 DROP VIEW IF EXISTS `workerCalendar`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerCalendar` AS select `ce`.`business_id` AS `businessFk`,`p`.`id_trabajador` AS `workerFk`,`ce`.`calendar_state_id` AS `absenceTypeFk`,`ce`.`date` AS `dated` from (((`postgresql`.`person` `p` join `postgresql`.`profile` `pr` on((`pr`.`person_id` = `p`.`person_id`))) join `postgresql`.`business` `b` on((`b`.`client_id` = `pr`.`profile_id`))) join `postgresql`.`calendar_employee` `ce` on((`ce`.`business_id` = `b`.`business_id`))) */; +/*!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 `workerDepartment` +-- + +/*!50001 DROP VIEW IF EXISTS `workerDepartment`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerDepartment` AS select `p`.`id_trabajador` AS `workerFk`,`d`.`id` AS `departmentFk` from (((`postgresql`.`person` `p` join `postgresql`.`profile` `pr` on((`pr`.`person_id` = `p`.`person_id`))) left join (`postgresql`.`business` `b` left join `postgresql`.`business_labour` `bl` on((`b`.`business_id` = `bl`.`business_id`))) on((`pr`.`profile_id` = `b`.`client_id`))) join `vn`.`department` `d` on((`d`.`id` = `bl`.`department_id`))) where ((isnull(`b`.`date_end`) and (`b`.`date_start` <= curdate())) or ((`b`.`date_end` > curdate()) and (`b`.`date_start` <= curdate()))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `workerLabour` +-- + +/*!50001 DROP VIEW IF EXISTS `workerLabour`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerLabour` AS select `b`.`business_id` AS `businessFk`,`p`.`id_trabajador` AS `workerFk`,`bl`.`workcenter_id` AS `workCenterFk`,`b`.`date_start` AS `started`,`b`.`date_end` AS `ended`,`d`.`id` AS `departmentFk` from ((((`postgresql`.`person` `p` join `postgresql`.`profile` `pr` on((`pr`.`person_id` = `p`.`person_id`))) join `postgresql`.`business` `b` on((`b`.`client_id` = `pr`.`profile_id`))) join `postgresql`.`business_labour` `bl` on((`b`.`business_id` = `bl`.`business_id`))) join `vn`.`department` `d` on((`d`.`id` = `bl`.`department_id`))) order by `b`.`date_start` desc */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `workerMana__` +-- + +/*!50001 DROP VIEW IF EXISTS `workerMana__`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerMana__` AS select `ms`.`Id_Trabajador` AS `workerFk`,`ms`.`size` AS `size`,`ms`.`used` AS `amount`,`ms`.`prices_modifier_rate` AS `pricesModifierRate`,`ms`.`prices_modifier_activated` AS `isPricesModifierActivated`,`ms`.`minRate` AS `minRate`,`ms`.`maxRate` AS `maxRate` from `bs`.`mana_spellers` `ms` */; +/*!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 `workerMedia` +-- + +/*!50001 DROP VIEW IF EXISTS `workerMedia`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerMedia` AS select `p`.`id_trabajador` AS `workerFk`,`m`.`value` AS `mediaValue` from ((((`postgresql`.`person` `p` join `postgresql`.`profile` `po` on((`po`.`person_id` = `p`.`person_id`))) join `postgresql`.`profile_media` `pom` on((`pom`.`profile_id` = `po`.`profile_id`))) join `postgresql`.`media` `m` on((`m`.`media_id` = `pom`.`media_id`))) join `postgresql`.`media_type` `mt` on((`mt`.`media_type_id` = `m`.`media_type_id`))) where (`mt`.`name` = 'movil empresa') */; +/*!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 `workerTeamCollegues` +-- + +/*!50001 DROP VIEW IF EXISTS `workerTeamCollegues`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerTeamCollegues` AS select distinct `w`.`workerFk` AS `workerFk`,`t`.`workerFk` AS `collegueFk` from (`workerTeam` `w` join `workerTeam` `t` on((`w`.`team` = `t`.`team`))) */; +/*!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 `workerTimeControlUserInfo` +-- + +/*!50001 DROP VIEW IF EXISTS `workerTimeControlUserInfo`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerTimeControlUserInfo` AS select `u`.`id` AS `userFk`,`w`.`firstName` AS `name`,`w`.`lastName` AS `surname`,`u`.`name` AS `user`,`u`.`password` AS `password`,`u`.`bcryptPassword` AS `bcryptPassword`,`wd`.`departmentFk` AS `departmentFk`,left(`w`.`fi`,8) AS `dni` from ((`account`.`user` `u` join `vn`.`worker` `w` on((`w`.`userFk` = `u`.`id`))) left join `vn`.`workerDepartment` `wd` on((`wd`.`workerFk` = `w`.`id`))) */; +/*!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 `workerTimeControlWorking` +-- + +/*!50001 DROP VIEW IF EXISTS `workerTimeControlWorking`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerTimeControlWorking` AS select `wtc`.`userFk` AS `userFk`,`wtc`.`timed` AS `timed`,`w`.`firstName` AS `name`,`w`.`lastName` AS `surname`,`pm`.`mediaValue` AS `phone`,`wm`.`mediaValue` AS `workerPhone`,`d`.`name` AS `department`,`wc`.`name` AS `workerCenter`,count(`wtc`.`order`) AS `maxOrder` from (((((((`vn`.`workerTimeControl` `wtc` join `vn`.`worker` `w` on((`w`.`userFk` = `wtc`.`userFk`))) left join `vn`.`personMedia` `pm` on((`pm`.`workerFk` = `w`.`id`))) left join `vn`.`workerMedia` `wm` on((`wm`.`workerFk` = `w`.`id`))) left join `vn`.`workerDepartment` `wd` on((`wd`.`workerFk` = `w`.`id`))) left join `vn`.`department` `d` on((`d`.`id` = `wd`.`departmentFk`))) left join `vn`.`workerLabour` `wl` on((`wl`.`businessFk` = (select `wl2`.`businessFk` from `vn`.`workerLabour` `wl2` where (`wl2`.`workerFk` = `w`.`id`) order by `wl2`.`started` desc limit 1)))) left join `vn`.`workCenter` `wc` on((`wc`.`id` = `wl`.`workCenterFk`))) where (cast(`wtc`.`timed` as date) = curdate()) group by `wtc`.`userFk` having ((`maxOrder` % 2) = 1) order by `wtc`.`timed` desc */; +/*!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 `workerTimeControl_Journey` +-- + +/*!50001 DROP VIEW IF EXISTS `workerTimeControl_Journey`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerTimeControl_Journey` AS select `wtc`.`userFk` AS `userFk`,cast(`wtc`.`timed` as date) AS `dated`,cast(sum((if((`wtc`.`order` % 2),-(1),1) * (hour(`wtc`.`timed`) + (minute(`wtc`.`timed`) / 60)))) as decimal(10,2)) AS `Journey`,dayname(`wtc`.`timed`) AS `dayName`,`w`.`lastName` AS `name`,`w`.`firstName` AS `firstname` from (`workerTimeControl` `wtc` join `worker` `w` on((`w`.`userFk` = `wtc`.`userFk`))) group by cast(`wtc`.`timed` as date),`wtc`.`userFk` */; +/*!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 `workerTimeJourneyNG` +-- + +/*!50001 DROP VIEW IF EXISTS `workerTimeJourneyNG`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerTimeJourneyNG` AS select `wtc`.`userFk` AS `userFk`,cast(`wtc`.`timed` as date) AS `dated`,(if((`wtc`.`order` % 2),-(1),1) * (hour(`wtc`.`timed`) + (minute(`wtc`.`timed`) / 60))) AS `Journey`,dayname(`wtc`.`timed`) AS `dayName`,`w`.`lastName` AS `name`,`w`.`firstName` AS `firstname` from (`workerTimeControl` `wtc` join `worker` `w` on((`w`.`userFk` = `wtc`.`userFk`))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Current Database: `vncontrol` +-- + +USE `vncontrol`; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2019-12-13 8:42:46 diff --git a/db/export-data.sh b/db/export-data.sh new file mode 100755 index 000000000..fd690854a --- /dev/null +++ b/db/export-data.sh @@ -0,0 +1,87 @@ +#!/bin/bash + +DUMPED_FILE="dump/dumpedFixtures.sql" +INI_FILE="config.production.ini" + +dump_tables() { + SCHEMA=$1 + echo "USE \`$SCHEMA\`;" >> "$DUMPED_FILE" + mysqldump --defaults-file="$INI_FILE" --no-create-info --skip-triggers $@ >> "$DUMPED_FILE" +} + +echo "" > "$DUMPED_FILE" + +TABLES=( + util + config +) +dump_tables ${TABLES[@]} + +TABLES=( + account + role + roleInherit + roleRole +) +dump_tables ${TABLES[@]} + +TABLES=( + salix + ACL + fieldAcl +) +dump_tables ${TABLES[@]} + +TABLES=( + vn + alertLevel + bookingPlanner + cplusInvoiceType477 + cplusSubjectOp + cplusTaxBreak + pgc + tag + claimResponsible + claimReason + claimRedelivery + claimResult + ticketUpdateAction + state + sample + department +) +dump_tables ${TABLES[@]} + + + +TABLES=( + bi + tarifa_componentes + tarifa_componentes_series +) +dump_tables ${TABLES[@]} + +TABLES=( + cache + cache +) +dump_tables ${TABLES[@]} + +TABLES=( + hedera + imageCollection + tpvError + tpvResponse +) +dump_tables ${TABLES[@]} + +TABLES=( + postgresql + calendar_labour_type + labour_agreement + media_type + professional_category + profile_type + workcenter +) +dump_tables ${TABLES[@]} diff --git a/db/export-structure.sh b/db/export-structure.sh new file mode 100755 index 000000000..da1d23daf --- /dev/null +++ b/db/export-structure.sh @@ -0,0 +1,106 @@ +#!/bin/bash + +SCHEMAS=( + account + bi + bs + cache + edi + hedera + nst + pbx + postgresql + salix + stock + util + vn + vncontrol +) + +IGNORETABLES=( + --ignore-table=bi.last_Id_Cubo + --ignore-table=bi.v_clientes_jerarquia + --ignore-table=bi.v_ventas_contables + --ignore-table=bs.horasSilla + --ignore-table=bs.productionIndicators + --ignore-table=bs.VentasPorCliente + --ignore-table=bs.v_ventas + --ignore-table=edi.supplyOffer + --ignore-table=postgresql.currentWorkersStats + --ignore-table=vn.accounting__ + --ignore-table=vn.agencyModeZone + --ignore-table=vn.agencyProvince + --ignore-table=vn.agencyWarehouse + --ignore-table=vn.awb + --ignore-table=vn.botanicExport__ + --ignore-table=vn.clientDefaultCompany + --ignore-table=vn.color + --ignore-table=vn.comparative + --ignore-table=vn.comparativeFilter + --ignore-table=vn.coolerPath + --ignore-table=vn.coolerPathDetail + --ignore-table=vn.department__ + --ignore-table=vn.doc + --ignore-table=vn.entity + --ignore-table=vn.especialPrice + --ignore-table=vn.exchangeInsurance + --ignore-table=vn.exchangeInsuranceInPrevious + --ignore-table=vn.exchangeReportSource + --ignore-table=vn.grant + --ignore-table=vn.grantGroup + --ignore-table=vn.invoiceCorrection__ + --ignore-table=vn.invoiceIn + --ignore-table=vn.invoiceInAwb + --ignore-table=vn.invoiceInDueDay + --ignore-table=vn.invoiceInEntry + --ignore-table=vn.invoiceInIntrastat + --ignore-table=vn.invoiceInTax + --ignore-table=vn.itemTaxCountrySpain + --ignore-table=vn.mail__ + --ignore-table=vn.manaSpellers + --ignore-table=vn.outgoingInvoiceKk + --ignore-table=vn.payment + --ignore-table=vn.paymentExchangeInsurance + --ignore-table=vn.payrollCenter + --ignore-table=vn.plantpassport + --ignore-table=vn.plantpassportAuthority + --ignore-table=vn.preparationException + --ignore-table=vn.priceFixed__ + --ignore-table=vn.printer + --ignore-table=vn.printingQueue + --ignore-table=vn.printServerQueue__ + --ignore-table=vn.promissoryNote + --ignore-table=vn.rate + --ignore-table=vn.referenceRate__ + --ignore-table=vn.routesControl + --ignore-table=vn.salesToPrePrepare + --ignore-table=vn.specialPrice__ + --ignore-table=vn.ticketDownBuffer + --ignore-table=vn.ticketeToPreparePrepared + --ignore-table=vn.ticketObservation__ + --ignore-table=vn.ticketRequest__ + --ignore-table=vn.ticketToPrepare + --ignore-table=vn.till__ + --ignore-table=vn.time + --ignore-table=vn.travelThermograph__ + --ignore-table=vn.travel_cloneWeekly + --ignore-table=vn.unary + --ignore-table=vn.unaryScan + --ignore-table=vn.unaryScanLine + --ignore-table=vn.unaryScanLineBuy + --ignore-table=vn.unaryScanLineExpedition + --ignore-table=vn.warehouseAlias__ + --ignore-table=vn.warehouseJoined + --ignore-table=vn.workerTeam__ + --ignore-table=vn.XDiario__ +) +mysqldump \ + --defaults-file=config.production.ini \ + --default-character-set=utf8 \ + --column-statistics=0 \ + --no-data --comments \ + --triggers --routines --events \ + --databases \ + ${SCHEMAS[@]} \ + ${IGNORETABLES[@]} \ + > dump/structure.sql diff --git a/db/import-changes.sh b/db/import-changes.sh new file mode 100755 index 000000000..2b80654d3 --- /dev/null +++ b/db/import-changes.sh @@ -0,0 +1,119 @@ +#!/bin/bash + +FORCE=FALSE + +usage() { + echo "[ERROR] Usage: $0 [-f] [environment]" + exit 1 +} + +while getopts ":f" option +do + case $option in + f) + FORCE=TRUE + ;; + \?|:) + usage + ;; + esac +done + +shift $(($OPTIND - 1)) + +ENV=$1 +DIR="$(dirname "${BASH_SOURCE[0]}")" + +# Production protection + +if [ "$ENV" == "production" ]; then + echo "" + echo " ( ( ) ( ( ) ) " + echo " )\ ))\ ) ( /( )\ ) ( ))\ ) ( /( ( /( " + echo "(()/(()/( )\()|()/( ( )\ ) /(()/( )\()) )\())" + echo " /(_))(_)|(_)\ /(_)) )\ (((_) ( )(_))(_)|(_)\ ((_)\ " + echo "(_))(_)) ((_|_))_ _ ((_))\___(_(_()|_)) ((_) _((_)" + echo "| _ \ _ \ / _ \| \| | | ((/ __|_ _|_ _| / _ \| \| |" + echo "| _/ /| (_) | |) | |_| || (__ | | | | | (_) | . |" + echo "|_| |_|_\ \___/|___/ \___/ \___| |_| |___| \___/|_|\_|" + echo "" + + if [ "$FORCE" != "TRUE" ]; then + read -p "[INTERACTIVE] Are you sure? (Default: no) [yes|no]: " ANSWER + + if [ "$ANSWER" != "yes" ]; then + echo "[INFO] Aborting changes." + exit + fi + fi +fi + +# Configuration file + +if [ -z "$ENV" ]; then + INI_FILE="$DIR/config.ini" +else + INI_FILE="$DIR/config.$ENV.ini" +fi + +if [ ! -f "$INI_FILE" ]; then + echo "[ERROR] Config file doesn't exists: $INI_FILE" + exit 2 +fi + +echo "[INFO] Using config file: $INI_FILE" + +# Fetching database version + +GET_VERSION="SELECT dbVersion FROM util.config LIMIT 1" +DB_VERSION=`echo "$GET_VERSION" | mysql --defaults-file="$INI_FILE" --silent --raw` + +echo "[INFO] Current database version: $DB_VERSION" + +if [[ ! "$DB_VERSION" =~ ^[0-9]+$ ]]; then + echo "[ERROR] Cannot fetch the database version." + exit 3 +fi + +# Applying changes + +N_CHANGES=0 + +for DIR_PATH in "$DIR/changes/"*; do + DIR_NAME=$(basename $DIR_PATH) + DIR_VERSION=${DIR_NAME:0:5} + + if [[ ! "$DIR_NAME" =~ ^[0-9]{5}(-[a-zA-Z0-9]+)?$ ]]; then + echo "[WARN] Ignoring wrong directory name: $DIR_NAME" + continue + fi + if [ "$DB_VERSION" -ge "$DIR_VERSION" ]; then + echo "[INFO] Ignoring already applied version: $DIR_NAME" + continue + fi + + echo "[INFO] Applying version: $DIR_NAME" + + for FILE in "$DIR_PATH/"*; do + FILE_NAME=$(basename "$FILE") + + if [[ ! "$FILE_NAME" =~ ^[0-9]{2}-[a-zA-Z0-9_]+\.sql$ ]]; then + echo "[WARN] Ignoring wrong file name: $FILE_NAME" + continue + fi + + echo "[INFO] -> $FILE_NAME" + mysql --defaults-file="$INI_FILE" --comments < $FILE + N_CHANGES=$((N_CHANGES + 1)) + done + + UPDATE_VERSION="UPDATE util.config SET dbVersion='$DIR_VERSION'" + echo "$UPDATE_VERSION" | mysql --defaults-file="$INI_FILE" +done + +if [ "$N_CHANGES" -eq "0" ]; then + echo "[INFO] No changes applied." +else + echo "[INFO] Changes applied succesfully." +fi + diff --git a/db/tests.js b/db/tests.js new file mode 100644 index 000000000..74ea9a80b --- /dev/null +++ b/db/tests.js @@ -0,0 +1,39 @@ +process.on('warning', warning => { + console.log(warning.name); + console.log(warning.message); + console.log(warning.stack); +}); + +let verbose = false; + +if (process.argv[2] === '--v') + verbose = true; + +let app = require(`vn-loopback/server/server`); +app.boot(); +loopbackApp = 'vn-loopback/server/server'; + +let Jasmine = require('jasmine'); +let jasmine = new Jasmine(); +let SpecReporter = require('jasmine-spec-reporter').SpecReporter; + +let serviceSpecs = [ + './tests/**/*[sS]pec.js' +]; + +jasmine.loadConfig({ + spec_dir: 'db', + spec_files: serviceSpecs, + helpers: [] +}); + +jasmine.addReporter(new SpecReporter({ + spec: { + // displayStacktrace: 'summary', + displaySuccessful: verbose, + displayFailedSpec: true, + displaySpecDuration: true + } +})); + +jasmine.execute(); diff --git a/db/tests/cache/last_buy_refresh.spec.js b/db/tests/cache/last_buy_refresh.spec.js new file mode 100644 index 000000000..0036e2762 --- /dev/null +++ b/db/tests/cache/last_buy_refresh.spec.js @@ -0,0 +1,46 @@ +const app = require(`${loopbackApp}`); +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +describe('last_buy_refresh()', () => { + it(`should store some data on cache.last_buy`, async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + + stmt = new ParameterizedSQL('CALL cache.last_buy_refresh(true)'); + stmts.push(stmt); + + let lastBuyTableIndex = stmts.push(`SELECT * FROM cache.last_buy ORDER BY item_id ASC`) - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + let lastBuyTable = result[lastBuyTableIndex]; + + expect(lastBuyTable.length).toEqual(12); + + expect(lastBuyTable[0].item_id).toEqual(1); + expect(lastBuyTable[1].item_id).toEqual(1); + expect(lastBuyTable[2].item_id).toEqual(1); + expect(lastBuyTable[3].item_id).toEqual(2); + expect(lastBuyTable[4].item_id).toEqual(2); + expect(lastBuyTable[5].item_id).toEqual(3); + + expect(lastBuyTable[0].warehouse_id).toEqual(1); + expect(lastBuyTable[1].warehouse_id).toEqual(3); + expect(lastBuyTable[2].warehouse_id).toEqual(5); + expect(lastBuyTable[3].warehouse_id).toEqual(1); + expect(lastBuyTable[4].warehouse_id).toEqual(5); + expect(lastBuyTable[5].warehouse_id).toEqual(1); + + expect(lastBuyTable[1].buy_id).toEqual(10); + expect(lastBuyTable[0].buy_id).toEqual(3); + expect(lastBuyTable[2].buy_id).toEqual(13); + expect(lastBuyTable[3].buy_id).toEqual(4); + expect(lastBuyTable[4].buy_id).toEqual(14); + expect(lastBuyTable[5].buy_id).toEqual(5); + }); +}); diff --git a/db/tests/vn/buyUltimate.spec.js b/db/tests/vn/buyUltimate.spec.js new file mode 100644 index 000000000..8a5e6a3df --- /dev/null +++ b/db/tests/vn/buyUltimate.spec.js @@ -0,0 +1,55 @@ +const app = require('vn-loopback/server/server'); +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +describe('buyUltimate()', () => { + const today = new Date(); + it(`should create buyUltimate temporal table and update it's values`, async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + + let params = { + warehouseFk: 1, + date: today + }; + + stmt = new ParameterizedSQL('CALL vn.buyUltimate(?, ?)', [ + params.warehouseFk, + params.date + ]); + stmts.push(stmt); + + let buyUltimateTableIndex = stmts.push(`SELECT * FROM tmp.buyUltimate ORDER BY itemFk ASC`) - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + let buyUltimateTable = result[buyUltimateTableIndex]; + + expect(buyUltimateTable.length).toEqual(6); + + expect(buyUltimateTable[0].itemFk).toEqual(1); + expect(buyUltimateTable[1].itemFk).toEqual(2); + expect(buyUltimateTable[2].itemFk).toEqual(3); + expect(buyUltimateTable[3].itemFk).toEqual(4); + expect(buyUltimateTable[4].itemFk).toEqual(8); + expect(buyUltimateTable[5].itemFk).toEqual(9); + + expect(buyUltimateTable[0].warehouseFk).toEqual(1); + expect(buyUltimateTable[1].warehouseFk).toEqual(1); + expect(buyUltimateTable[2].warehouseFk).toEqual(1); + expect(buyUltimateTable[3].warehouseFk).toEqual(1); + expect(buyUltimateTable[4].warehouseFk).toEqual(1); + expect(buyUltimateTable[5].warehouseFk).toEqual(1); + + expect(buyUltimateTable[1].buyFk).toEqual(4); + expect(buyUltimateTable[0].buyFk).toEqual(3); + expect(buyUltimateTable[2].buyFk).toEqual(5); + expect(buyUltimateTable[3].buyFk).toEqual(8); + expect(buyUltimateTable[4].buyFk).toEqual(6); + expect(buyUltimateTable[5].buyFk).toEqual(7); + }); +}); diff --git a/db/tests/vn/buyUltimateFromInterval.spec.js b/db/tests/vn/buyUltimateFromInterval.spec.js new file mode 100644 index 000000000..b5e6970f7 --- /dev/null +++ b/db/tests/vn/buyUltimateFromInterval.spec.js @@ -0,0 +1,132 @@ +const app = require('vn-loopback/server/server'); +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +describe('buyUltimateFromInterval()', () => { + let today; + let future; + beforeAll(() => { + let now = new Date(); + now.setHours(0, 0, 0, 0); + today = now; + + let futureDate = new Date(now); + let futureMonth = now.getMonth() + 1; + futureDate.setMonth(futureMonth); + future = futureDate; + }); + + it(`should create a temporal table with it's data`, async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + + let params = { + warehouseFk: 1, + started: today, + ended: today + }; + + stmt = new ParameterizedSQL('CALL vn.buyUltimateFromInterval(?, ?, ?)', [ + params.warehouseFk, + params.started, + params.ended + ]); + stmts.push(stmt); + + let buyUltimateFromIntervalTableIndex = stmts.push(`SELECT * FROM tmp.buyUltimateFromInterval`) - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + let buyUltimateFromIntervalTable = result[buyUltimateFromIntervalTableIndex]; + + expect(buyUltimateFromIntervalTable.length).toEqual(2); + + expect(buyUltimateFromIntervalTable[0].itemFk).toEqual(1); + expect(buyUltimateFromIntervalTable[1].itemFk).toEqual(3); + + expect(buyUltimateFromIntervalTable[0].warehouseFk).toEqual(1); + expect(buyUltimateFromIntervalTable[1].warehouseFk).toEqual(1); + + expect(buyUltimateFromIntervalTable[0].buyFk).toEqual(3); + expect(buyUltimateFromIntervalTable[1].buyFk).toEqual(5); + + expect(buyUltimateFromIntervalTable[0].landed).toEqual(today); + expect(buyUltimateFromIntervalTable[1].landed).toEqual(today); + }); + + it(`should create a temporal table with it's data in which started value is assigned to ended`, async() => { + let params = { + warehouseFk: 1, + started: today, + ended: null + }; + + let query = ` + START TRANSACTION; + CALL vn.buyUltimateFromInterval(?, ?, ?); + SELECT * FROM tmp.buyUltimateFromInterval; + ROLLBACK;`; + + let result = await app.models.Ticket.rawSql(query, [ + params.warehouseFk, + params.started, + params.ended + ]); + + let buyUltimateFromIntervalTable = result[2]; + + expect(buyUltimateFromIntervalTable.length).toEqual(2); + + expect(buyUltimateFromIntervalTable[0].itemFk).toEqual(1); + expect(buyUltimateFromIntervalTable[1].itemFk).toEqual(3); + + expect(buyUltimateFromIntervalTable[0].warehouseFk).toEqual(1); + expect(buyUltimateFromIntervalTable[1].warehouseFk).toEqual(1); + + expect(buyUltimateFromIntervalTable[0].buyFk).toEqual(3); + expect(buyUltimateFromIntervalTable[1].buyFk).toEqual(5); + + expect(buyUltimateFromIntervalTable[0].landed).toEqual(today); + expect(buyUltimateFromIntervalTable[1].landed).toEqual(today); + }); + + it(`should create a temporal table with it's data in which ended value is a date in the future`, async() => { + let params = { + warehouseFk: 1, + started: today, + ended: future + }; + + let query = ` + START TRANSACTION; + CALL vn.buyUltimateFromInterval(?, ?, ?); + SELECT * FROM tmp.buyUltimateFromInterval; + ROLLBACK;`; + + let result = await app.models.Ticket.rawSql(query, [ + params.warehouseFk, + params.started, + params.ended + ]); + + let buyUltimateFromIntervalTable = result[2]; + + expect(buyUltimateFromIntervalTable.length).toEqual(2); + + expect(buyUltimateFromIntervalTable[0].itemFk).toEqual(1); + expect(buyUltimateFromIntervalTable[1].itemFk).toEqual(3); + + expect(buyUltimateFromIntervalTable[0].warehouseFk).toEqual(1); + expect(buyUltimateFromIntervalTable[1].warehouseFk).toEqual(1); + + expect(buyUltimateFromIntervalTable[0].buyFk).toEqual(3); + expect(buyUltimateFromIntervalTable[1].buyFk).toEqual(5); + + expect(buyUltimateFromIntervalTable[0].landed).toEqual(today); + expect(buyUltimateFromIntervalTable[1].landed).toEqual(today); + }); +}); diff --git a/db/tests/vn/logAddWithUser.spec.js b/db/tests/vn/logAddWithUser.spec.js new file mode 100644 index 000000000..8711769d0 --- /dev/null +++ b/db/tests/vn/logAddWithUser.spec.js @@ -0,0 +1,42 @@ +const app = require('vn-loopback/server/server'); +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +describe('logAddWithUser()', () => { + it('should log any action taken by the user in a table ending in Log', async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + + let params = { + ticketFk: 1, + userId: 9, + actionCode: 'update', + targetEntity: 'ticket', + description: 'we are testing stuff' + }; + + stmt = new ParameterizedSQL('CALL vn.logAddWithUser(?, ?, ?, ?, ?)', [ + params.ticketFk, + params.userId, + params.actionCode, + params.targetEntity, + params.description + ]); + stmts.push(stmt); + + stmt = new ParameterizedSQL('SELECT * FROM vn.ticketLog WHERE description = ?', [ + params.description + ]); + let ticketLogIndex = stmts.push(stmt) - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + savedDescription = result[ticketLogIndex][0].description; + + expect(savedDescription).toEqual(params.description); + }); +}); diff --git a/db/tests/vn/orderConfirmWithUser.spec.js b/db/tests/vn/orderConfirmWithUser.spec.js new file mode 100644 index 000000000..f2a3d0c4e --- /dev/null +++ b/db/tests/vn/orderConfirmWithUser.spec.js @@ -0,0 +1,37 @@ +const app = require('vn-loopback/server/server'); +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +// #1885 +xdescribe('order_confirmWithUser()', () => { + it('should confirm an order', async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + + let params = { + orderFk: 10, + userId: 9 + }; + // problema: la funcion order_confirmWithUser tiene una transacción, por tanto esta nunca hace rollback + stmt = new ParameterizedSQL('CALL hedera.order_confirmWithUser(?, ?)', [ + params.orderFk, + params.userId + ]); + stmts.push(stmt); + + stmt = new ParameterizedSQL('SELECT confirmed FROM hedera.order WHERE id = ?', [ + params.orderFk + ]); + let orderIndex = stmts.push(stmt) - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + savedDescription = result[orderIndex][0].confirmed; + + expect(savedDescription).toBeTruthy(); + }); +}); diff --git a/db/tests/vn/ticketCalculateClon.spec.js b/db/tests/vn/ticketCalculateClon.spec.js new file mode 100644 index 000000000..4015d57db --- /dev/null +++ b/db/tests/vn/ticketCalculateClon.spec.js @@ -0,0 +1,105 @@ +const app = require('vn-loopback/server/server'); +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +describe('ticket ticketCalculateClon()', () => { + const today = new Date(); + it('should add the ticket to the order containing the original ticket', async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + + let params = { + clientFk: 101, + shipped: today, + warehouseFk: 1, + companyFk: 442, + addressFk: 121, + agencyType: 23, + routeFk: 1, + landed: today, + userId: 21, + originalTicketId: 11 + }; + + stmt = new ParameterizedSQL('CALL vn.ticketCreateWithUser(?, ?, ?, ?, ?, ?, ?, ?, ?, @result)', [ + params.clientFk, + params.shipped, + params.warehouseFk, + params.companyFk, + params.addressFk, + params.agencyType, + params.routeFk, + params.landed, + params.userId + ]); + stmts.push(stmt); + + stmt = new ParameterizedSQL('CALL vn.ticketCalculateClon(@result, ?)', [params.originalTicketId]); + stmts.push(stmt); + + let orderIndex = stmts.push(`SELECT * FROM vn.orderTicket WHERE ticketFk = @result`) - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + let expectedOrder = 11; + let newestTicketIdInFixtures = 21; + + expect(result[orderIndex][0].orderFk).toEqual(expectedOrder); + expect(result[orderIndex][0].ticketFk).toBeGreaterThan(newestTicketIdInFixtures); + }); + + it('should add the ticket to the order containing the original ticket and generate landed value if it was null', async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + + let params = { + clientFk: 101, + shipped: today, + warehouseFk: 1, + companyFk: 442, + addressFk: 121, + agencyType: 23, + routeFk: 1, + landed: null, + userId: 21, + originalTicketId: 11 + }; + + stmt = new ParameterizedSQL('CALL vn.ticketCreateWithUser(?, ?, ?, ?, ?, ?, ?, ?, ?, @result)', [ + params.clientFk, + params.shipped, + params.warehouseFk, + params.companyFk, + params.addressFk, + params.agencyType, + params.routeFk, + params.landed, + params.userId + ]); + stmts.push(stmt); + + stmt = new ParameterizedSQL('CALL vn.ticketCalculateClon(@result, ?)', [params.originalTicketId]); + stmts.push(stmt); + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + + let error; + + try { + await app.models.Ticket.rawStmt(sql); + } catch (e) { + error = e; + } + + expect(error).toBeDefined(); + expect(error.statusCode).toBe(500); + expect(error.code).toBe('ER_SIGNAL_EXCEPTION'); + }); +}); diff --git a/db/tests/vn/ticketComponentUpdateSale.spec.js b/db/tests/vn/ticketComponentUpdateSale.spec.js new file mode 100644 index 000000000..9e252200b --- /dev/null +++ b/db/tests/vn/ticketComponentUpdateSale.spec.js @@ -0,0 +1,294 @@ +const app = require('vn-loopback/server/server'); +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +describe('ticketComponentUpdateSale()', () => { + it(`should update the sale price when option ONE using the base components and reclaculate only the ones with isRenewable TRUE`, async() => { + let stmts = []; + let stmt; + + let params = { + warehouseFk: 1, + ticketFk: 13 + }; + + stmts.push('START TRANSACTION'); + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.sale'); + + // createSaleTempTable code comes from vn.ticketComponentUpdate procedure + let createSaleTempTable = ` + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) + ENGINE = MEMORY + SELECT id AS saleFk, ? warehouseFk + FROM sale s WHERE s.ticketFk = ? + `; + + stmt = new ParameterizedSQL(createSaleTempTable, [ + params.warehouseFk, + params.ticketFk + ]); + stmts.push(stmt); + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent'); + + // createTicketComponentTable code comes partially from vn.ticketComponenetCalculate procedure + let createTicketComponentTable = ` + CREATE TEMPORARY TABLE tmp.ticketComponent ( + warehouseFk INT UNSIGNED NOT NULL, + itemFk INT NOT NULL, + componentFk INT UNSIGNED NOT NULL, + cost DECIMAL(10,4) NOT NULL, + INDEX itemWarehouse USING BTREE (itemFk ASC, warehouseFk ASC), + UNIQUE INDEX itemWarehouseComponent (itemFk ASC, warehouseFk ASC, componentFk ASC)) + `; + + stmts.push(createTicketComponentTable); + + let insertTicketComponentTable = ` + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + VALUES + (1 , 4 , 15 , 999.00), + (1 , 4 , 17 , 2.00), + (1 , 4 , 22 , 999.00), + (1 , 4 , 28 , 1.00), + (1 , 4 , 29 , 2.00), + (1 , 4 , 32 , 999.00), + (1 , 4 , 39 , 1.00) + `; + + stmts.push(insertTicketComponentTable); + + let updateComponentTwentyNine = ` + UPDATE vn.saleComponent + SET value = '5' + WHERE saleFk = 26 AND componentFk = 29 + `; + + stmts.push(updateComponentTwentyNine); + + let updateComponentTwentyEight = ` + UPDATE vn.saleComponent + SET value = '5' + WHERE saleFk = 26 AND componentFk = 28 + `; + + stmts.push(updateComponentTwentyEight); + + let priceFixtedToZero = ` + UPDATE vn.sale + SET priceFixed = 0 + WHERE id = 26 + `; + + stmts.push(priceFixtedToZero); + + let firstSalePriceIndexBefore = stmts.push('SELECT price FROM vn.sale WHERE id = 26') - 1; + + stmts.push('CALL vn.ticketComponentUpdateSale(1)'); + + let firstSalePriceIndexAfter = stmts.push('SELECT price FROM vn.sale WHERE id = 26') - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + expect(result[firstSalePriceIndexBefore][0].price).toEqual(1.72); + expect(result[firstSalePriceIndexAfter][0].price).toEqual(1005); + }); + + it(`should keep the sale price when option TWO using the base components and save the difference in a new component`, async() => { + let stmts = []; + let stmt; + + let params = { + warehouseFk: 1, + ticketFk: 13 + }; + + stmts.push('START TRANSACTION'); + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.sale'); + + // createSaleTempTable code comes from vn.ticketComponentUpdate procedure + let createSaleTempTable = ` + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) + ENGINE = MEMORY + SELECT id AS saleFk, ? warehouseFk + FROM sale s WHERE s.ticketFk = ? + `; + + stmt = new ParameterizedSQL(createSaleTempTable, [ + params.warehouseFk, + params.ticketFk + ]); + stmts.push(stmt); + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent'); + + // createTicketComponentTable code comes partially from vn.ticketComponenetCalculate procedure + let createTicketComponentTable = ` + CREATE TEMPORARY TABLE tmp.ticketComponent ( + warehouseFk INT UNSIGNED NOT NULL, + itemFk INT NOT NULL, + componentFk INT UNSIGNED NOT NULL, + cost DECIMAL(10,4) NOT NULL, + INDEX itemWarehouse USING BTREE (itemFk ASC, warehouseFk ASC), + UNIQUE INDEX itemWarehouseComponent (itemFk ASC, warehouseFk ASC, componentFk ASC)) + `; + + stmts.push(createTicketComponentTable); + + let insertTicketComponentTable = ` + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + VALUES + (1 , 4 , 15 , 999.00), + (1 , 4 , 17 , 2.00), + (1 , 4 , 22 , 999.00), + (1 , 4 , 28 , 1.00), + (1 , 4 , 29 , 2.00), + (1 , 4 , 32 , 999.00), + (1 , 4 , 39 , 1.00) + `; + + stmts.push(insertTicketComponentTable); + + let updateComponentTwentyNine = ` + UPDATE vn.saleComponent + SET value = '5' + WHERE saleFk = 26 AND componentFk = 29 + `; + + stmts.push(updateComponentTwentyNine); + + let updateComponentTwentyEight = ` + UPDATE vn.saleComponent + SET value = '5' + WHERE saleFk = 26 AND componentFk = 28 + `; + + stmts.push(updateComponentTwentyEight); + + let priceFixtedToZero = ` + UPDATE vn.sale + SET priceFixed = 0 + WHERE id = 26 + `; + + stmts.push(priceFixtedToZero); + + let firstSalePriceIndexBefore = stmts.push('SELECT price FROM vn.sale WHERE id = 26') - 1; + + stmts.push('CALL vn.ticketComponentUpdateSale(2)'); + + let addedComponentIndex = stmts.push('SELECT * FROM vn.saleComponent WHERE saleFk = 26 AND componentFk = 17') - 1; + let firstSalePriceIndexAfter = stmts.push('SELECT price FROM vn.sale WHERE id = 26') - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + expect(result[addedComponentIndex][0].value).toEqual(-1003.28); + expect(result[firstSalePriceIndexBefore][0].price).toEqual(result[firstSalePriceIndexAfter][0].price); + }); + + it(`should not change the sale price when option SEVEN, instead it stores 80% and 20% of the price in two components and any price difference in a third one`, async() => { + let stmts = []; + let stmt; + + let params = { + warehouseFk: 1, + ticketFk: 1 + }; + + stmts.push('START TRANSACTION'); + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.sale'); + + // createSaleTempTable code comes from vn.ticketComponentUpdate procedure + let createSaleTempTable = ` + CREATE TEMPORARY TABLE tmp.sale + (PRIMARY KEY (saleFk)) + ENGINE = MEMORY + SELECT id AS saleFk, ? warehouseFk + FROM sale s WHERE s.ticketFk = ? + `; + + stmt = new ParameterizedSQL(createSaleTempTable, [ + params.warehouseFk, + params.ticketFk + ]); + stmts.push(stmt); + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent'); + + // createTicketComponentTable code comes partially from vn.ticketComponenetCalculate procedure + let createTicketComponentTable = ` + CREATE TEMPORARY TABLE tmp.ticketComponent ( + warehouseFk INT UNSIGNED NOT NULL, + itemFk INT NOT NULL, + componentFk INT UNSIGNED NOT NULL, + cost DECIMAL(10,4) NOT NULL, + INDEX itemWarehouse USING BTREE (itemFk ASC, warehouseFk ASC), + UNIQUE INDEX itemWarehouseComponent (itemFk ASC, warehouseFk ASC, componentFk ASC)) + `; + + stmts.push(createTicketComponentTable); + + let insertTicketComponentTable = ` + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + VALUES + (1 , 2 , 29 , 999.00), + (1 , 2 , 28 , 2.00), + (1 , 4 , 29 , 999.00), + (1 , 4 , 28 , 1.00) + `; + + stmts.push(insertTicketComponentTable); + + let updateComponentTwentyEight = ` + UPDATE vn.saleComponent + SET value = '5' + WHERE saleFk = 1 AND componentFk = 28 + `; + + stmts.push(updateComponentTwentyEight); + + let updateComponentTwentyNine = ` + UPDATE vn.saleComponent + SET value = '5' + WHERE saleFk = 1 AND componentFk = 29 + `; + + stmts.push(updateComponentTwentyNine); + + let priceFixtedToZero = ` + UPDATE vn.sale + SET priceFixed = 0 + WHERE id = 1 + `; + + stmts.push(priceFixtedToZero); + + let firstSalePriceIndexBefore = stmts.push('SELECT price FROM vn.sale WHERE id = 1') - 1; + + stmts.push('CALL vn.ticketComponentUpdateSale(7)'); + + let componentTwentyEightIndex = stmts.push('SELECT * FROM vn.saleComponent WHERE saleFk = 1 AND componentFk = 28') - 1; + let componentTwentyNineIndex = stmts.push('SELECT * FROM vn.saleComponent WHERE saleFk = 1 AND componentFk = 29') - 1; + let firstSalePriceIndexAfter = stmts.push('SELECT price FROM vn.sale WHERE id = 1') - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + expect(result[componentTwentyEightIndex][0].value).toEqual(79.517); + expect(result[componentTwentyNineIndex][0].value).toEqual(19.879); + expect(result[firstSalePriceIndexBefore][0].price).toEqual(result[firstSalePriceIndexAfter][0].price); + }); +}); + diff --git a/db/tests/vn/ticketCreateWithUser.spec.js b/db/tests/vn/ticketCreateWithUser.spec.js new file mode 100644 index 000000000..51ebfe000 --- /dev/null +++ b/db/tests/vn/ticketCreateWithUser.spec.js @@ -0,0 +1,200 @@ +const app = require('vn-loopback/server/server'); +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +describe('ticket ticketCreateWithUser()', () => { + const today = new Date(); + it('should confirm the procedure creates the expected ticket', async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + + let params = { + clientFk: 101, + shipped: today, + warehouseFk: 1, + companyFk: 442, + addressFk: 121, + agencyModeFk: 1, + routeFk: null, + landed: today, + userId: 18 + }; + + stmt = new ParameterizedSQL(`CALL vn.ticketCreateWithUser(?, ?, ?, ?, ?, ?, ?, ?, ?, @newTicketId)`, [ + params.clientFk, + params.shipped, + params.warehouseFk, + params.companyFk, + params.addressFk, + params.agencyModeFk, + params.routeFk, + params.landed, + params.userId + ]); + stmts.push(stmt); + + let ticketResultIndex = stmts.push(`SELECT * FROM vn.ticket WHERE id = @newTicketId`) - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + let ticketResult = result[ticketResultIndex][0]; + + + expect(ticketResult.id).toBeGreaterThan(21); + expect(ticketResult.clientFk).toEqual(params.clientFk); + expect(ticketResult.warehouseFk).toEqual(params.warehouseFk); + expect(ticketResult.companyFk).toEqual(params.companyFk); + expect(ticketResult.addressFk).toEqual(params.addressFk); + expect(ticketResult.agencyModeFk).toEqual(params.agencyModeFk); + expect(ticketResult.routeFk).toEqual(params.routeFk); + }); + + it('should confirm the procedure creates the expected observations in the ticket', async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + + let params = { + clientFk: 101, + shipped: today, + warehouseFk: 1, + companyFk: 442, + addressFk: 121, + agencyModeFk: 1, + routeFk: null, + landed: today, + userId: 18 + }; + + stmt = new ParameterizedSQL('CALL vn.ticketCreateWithUser(?, ?, ?, ?, ?, ?, ?, ?, ?, @newTicketId)', [ + params.clientFk, + params.shipped, + params.warehouseFk, + params.companyFk, + params.addressFk, + params.agencyModeFk, + params.routeFk, + params.landed, + params.userId + ]); + stmts.push(stmt); + + let ticketObsevationsIndex = stmts.push(`SELECT * FROM vn.ticketObservation WHERE ticketFk = @newTicketId`) - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + let firstTicketObservation = result[ticketObsevationsIndex][0]; + let secondTicketObservation = result[ticketObsevationsIndex][1]; + let thirdTicketObservation = result[ticketObsevationsIndex][2]; + + expect(firstTicketObservation.observationTypeFk).toEqual(1); + expect(firstTicketObservation.description).toEqual('under the floor'); + expect(secondTicketObservation.observationTypeFk).toEqual(2); + expect(secondTicketObservation.description).toEqual('wears leather and goes out at night'); + expect(thirdTicketObservation.observationTypeFk).toEqual(3); + expect(thirdTicketObservation.description).toEqual('care with the dog'); + }); + + it('should confirm the procedure sets address if it received it null', async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + + let params = { + clientFk: 101, + shipped: today, + warehouseFk: 1, + companyFk: 442, + addressFk: 0, + agencyModeFk: 1, + routeFk: null, + landed: today, + userId: 18 + }; + + stmt = new ParameterizedSQL(`CALL vn.ticketCreateWithUser(?, ?, ?, ?, ?, ?, ?, ?, ?, @newTicketId)`, [ + params.clientFk, + params.shipped, + params.warehouseFk, + params.companyFk, + params.addressFk, + params.agencyModeFk, + params.routeFk, + params.landed, + params.userId + ]); + + stmts.push(stmt); + + let ticketAddressIndex = stmts.push(`SELECT addressFk FROM vn.ticket WHERE id = @newTicketId`) - 1; + + stmt = new ParameterizedSQL(`SELECT id FROM vn.address WHERE clientFk = ? AND isDefaultAddress = 1`, [ + params.clientFk, + ]); + let clientDefaultAddressIndex = stmts.push(stmt) - 1; + stmts.push('ROLLBACK'); + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + let ticketAddress = result[ticketAddressIndex][0]; + let clientDefaultAddress = result[clientDefaultAddressIndex][0]; + + expect(ticketAddress.addressFk).toEqual(clientDefaultAddress.id); + }); + + it('should confirm the procedure creates the state as delivered if the client has isCreatedAsServed TRUE', async() => { + let stmts = []; + let stmt; + + stmts.push('START TRANSACTION'); + + let params = { + clientFk: 101, + shipped: today, + warehouseFk: 1, + companyFk: 442, + addressFk: 121, + agencyModeFk: 1, + routeFk: null, + landed: today, + userId: 18 + }; + + stmt = new ParameterizedSQL(`UPDATE vn.client SET isCreatedAsServed = 1 WHERE id = ?`, [ + params.clientFk, + ]); + stmts.push(stmt); + + stmt = new ParameterizedSQL(`CALL vn.ticketCreateWithUser(?, ?, ?, ?, ?, ?, ?, ?, ?, @newTicketId)`, [ + params.clientFk, + params.shipped, + params.warehouseFk, + params.companyFk, + params.addressFk, + params.agencyModeFk, + params.routeFk, + params.landed, + params.userId + ]); + stmts.push(stmt); + stmts.push(`select @newTicketId`); + let ticketStateCodeIndex = stmts.push(`SELECT code FROM vn.ticketState WHERE ticketFk = @newTicketId`) - 1; + + stmts.push('ROLLBACK'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await app.models.Ticket.rawStmt(sql); + + let ticketStateCode = result[ticketStateCodeIndex][0].code; + + expect(ticketStateCode).toEqual('FREE'); + }); +}); diff --git a/docker-compose.tpl.yml b/docker-compose.tpl.yml deleted file mode 100644 index 1777118a7..000000000 --- a/docker-compose.tpl.yml +++ /dev/null @@ -1,12 +0,0 @@ -version: '2' -services: - nginx: - container_name: "${BRANCH_NAME}-nginx" - image: "nginx:${TAG}" - privileged: true - build: - context: ./services/nginx - ports: - - "80:80" - mem_limit: 200m - links: [] diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000..ff53b238d --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,45 @@ +version: '3.7' +services: + front: + image: registry.verdnatura.es/salix-front:${BRANCH_NAME:?} + build: + context: . + dockerfile: front/Dockerfile + ports: + - ${FRONT_PORT:?}:80 + deploy: + replicas: 3 + back: + image: registry.verdnatura.es/salix-back:${BRANCH_NAME:?} + build: . + ports: + - ${BACK_PORT:?}:3000 + environment: + - NODE_ENV + 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/storage/pdfs:/var/lib/salix/pdfs + - /mnt/storage/dms:/var/lib/salix/dms + deploy: + replicas: 6 +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/dms/c4c/1.txt b/e2e/dms/c4c/1.txt new file mode 100644 index 000000000..5ef648a88 --- /dev/null +++ b/e2e/dms/c4c/1.txt @@ -0,0 +1 @@ +It works! \ No newline at end of file diff --git a/e2e/dms/c81/2.txt b/e2e/dms/c81/2.txt new file mode 100644 index 000000000..5ef648a88 --- /dev/null +++ b/e2e/dms/c81/2.txt @@ -0,0 +1 @@ +It works! \ No newline at end of file diff --git a/e2e/dms/ecc/3.txt b/e2e/dms/ecc/3.txt new file mode 100644 index 000000000..5ef648a88 --- /dev/null +++ b/e2e/dms/ecc/3.txt @@ -0,0 +1 @@ +It works! \ No newline at end of file diff --git a/e2e/helpers/components_selectors.js b/e2e/helpers/components_selectors.js deleted file mode 100644 index 488d002e0..000000000 --- a/e2e/helpers/components_selectors.js +++ /dev/null @@ -1,19 +0,0 @@ -// eslint max-len: ["error", 500] -// eslint key-spacing: ["error", 500] - -// delete me, this comment is to add a commit -export default { - vnTextfield: 'vn-textfield > div > input', - vnTextarea: 'vn-textarea', - vnSubmit: 'vn-submit > input', - vnTopbar: 'vn-topbar > header', - vnIcon: 'vn-icon', - vnModuleContainer: 'vn-module-container > a', - vnSearchBar: 'vn-searchbar > form > vn-horizontal', - vnFloatButton: 'vn-float-button > button', - vnMenuItem: 'vn-menu-item > li > a', - vnAutocomplete: 'vn-autocomplete', - vnCheck: 'vn-check', - vnIconButton: 'vn-icon-button', - vnItemSummary: 'vn-item-summary > vn-card > div > vn-vertical' -}; diff --git a/e2e/helpers/config.js b/e2e/helpers/config.js index d52f08b39..8e5bda96c 100644 --- a/e2e/helpers/config.js +++ b/e2e/helpers/config.js @@ -1,3 +1,3 @@ -export default { - url: 'http://localhost:5000/' +module.exports = { + url: 'http://localhost:5000' }; diff --git a/e2e/helpers/extensions.js b/e2e/helpers/extensions.js index 7f146d30e..03a50bc45 100644 --- a/e2e/helpers/extensions.js +++ b/e2e/helpers/extensions.js @@ -1,204 +1,464 @@ -import config from './config.js'; +/* eslint no-invalid-this: "off" */ + import Nightmare from 'nightmare'; import {URL} from 'url'; +import config from './config.js'; -Nightmare.action('login', function(userName, done) { - this.goto(`${config.url}auth/?apiKey=salix`) - .wait(`vn-login input[name=user]`) - .write(`vn-login input[name=user]`, userName) - .write(`vn-login input[name=password]`, 'nightmare') - .click(`vn-login input[type=submit]`) - // FIXME: Wait for dom to be ready: https://github.com/segmentio/nightmare/issues/481 - .wait(1000) - .then(done); -}); +let currentUser; -Nightmare.action('changeLanguageToEnglish', function(done) { - this.wait('#lang') - .evaluate(selector => { - return document.querySelector(selector).title; - }, '#lang') - .then(title => { - if (title === 'Change language') { - this.then(done); - } else { - this.click('#lang') - .click('vn-main-menu [vn-id="langs-menu"] ul > li[name="en"]') - .then(done); - } - }); -}); +let actions = { + clickIfExists: async function(selector) { + let exists = await this.exists(selector); + if (exists) await this.click(selector); + return exists; + }, -Nightmare.action('waitForLogin', function(userName, done) { - this.login(userName) - .waitForURL('#!/') - .url() - .changeLanguageToEnglish() - .then(done); -}); + parsedUrl: async function() { + return new URL(await this.url()); + }, -Nightmare.action('parsedUrl', function(done) { - this.url() - .then(url => { - done(null, new URL(url)); - }); -}); + waitUntilNotPresent: async function(selector) { + await this.wait(selector => { + return document.querySelector(selector) == null; + }, selector); + }, -Nightmare.action('getInnerText', function(selector, done) { - this.wait(selector) - .evaluate_now(function(elementToSelect) { - return document.querySelector(elementToSelect).innerText; - }, done, selector); -}); + changeLanguageToEnglish: async function() { + let langSelector = '.user-popover vn-autocomplete[ng-model="$ctrl.lang"]'; -Nightmare.action('getInputValue', function(selector, done) { - this.wait(selector) - .evaluate_now(function(elementToSelect) { - return document.querySelector(elementToSelect).value; - }, done, selector); -}); + let lang = await this.waitToClick('#user') + .wait(langSelector) + .waitToGetProperty(`${langSelector} input`, 'value'); -Nightmare.action('clearInput', function(selector, done) { - let backSpaces = []; - for (let i = 0; i < 50; i += 1) { - backSpaces.push('\u0008'); - } - this.wait(selector) - .type(selector, backSpaces.join('')) - .then(done); -}); + if (lang !== 'English') + await this.autocompleteSearch(langSelector, 'English'); + }, -Nightmare.action('write', function(selector, text, done) { - this.wait(selector) - .type(selector, text) - .then(done); -}); + doLogin: async function(userName, password) { + if (password == null) password = 'nightmare'; + await this.wait(`vn-login [name=user]`) + .clearInput(`vn-login [name=user]`) + .write(`vn-login [name=user]`, userName) + .write(`vn-login [name=password]`, password) + .click(`vn-login button[type=submit]`); + }, -Nightmare.action('waitToClick', function(selector, done) { - this.wait(selector) - .click(selector) - .then(done); -}); + login: async function(userName) { + if (currentUser !== userName) { + let accountClicked = await this.clickIfExists('#user'); -Nightmare.action('isVisible', function(selector, done) { - this.wait(selector) - .evaluate_now(elementSelector => { - const selectorMatches = document.querySelectorAll(elementSelector); - const element = selectorMatches[0]; - if (selectorMatches.length > 1) { - throw new Error(`multiple matches of ${elementSelector} found`); - } - let isVisible = false; - if (element) { - const eventHandler = event => { - event.preventDefault(); - isVisible = true; - }; - element.addEventListener('mouseover', eventHandler); - const elementBoundaries = element.getBoundingClientRect(); - const x = elementBoundaries.left + element.offsetWidth / 2; - const y = elementBoundaries.top + element.offsetHeight / 2; - const elementInCenter = document.elementFromPoint(x, y); - const elementInTopLeft = document.elementFromPoint(elementBoundaries.left, elementBoundaries.top); - const elementInBottomRight = document.elementFromPoint(elementBoundaries.right, elementBoundaries.bottom); - const e = new MouseEvent('mouseover', { - view: window, - bubbles: true, - cancelable: true + if (accountClicked) { + let buttonSelector = '.vn-dialog.shown button[response=accept]'; + await this.waitToClick('#logout') + .wait(buttonSelector => { + return document.querySelector(buttonSelector) != null + || location.hash == '#!/login'; + }, buttonSelector); + await this.clickIfExists(buttonSelector); + } + + try { + await this.waitForURL('#!/login'); + } catch (e) { + await this.goto(`${config.url}/#!/login`); + } + + await this.doLogin(userName, null) + .waitForURL('#!/') + .changeLanguageToEnglish(); + + currentUser = userName; + } else + await this.waitToClick('a[ui-sref=home]'); + }, + + waitForLogin: async function(userName) { + await this.login(userName); + }, + + selectModule: async function(moduleName) { + let snakeName = moduleName.replace(/[\w]([A-Z])/g, m => { + return m[0] + '-' + m[1]; + }).toLowerCase(); + + await this.waitToClick(`vn-home a[ui-sref="${moduleName}.index"]`) + .waitForURL(snakeName); + }, + + loginAndModule: async function(userName, moduleName) { + await this.login(userName) + .selectModule(moduleName); + }, + + datePicker: async function(selector, changeMonth, day) { + let date = new Date(); + if (changeMonth) date.setMonth(date.getMonth() + changeMonth); + date.setDate(day ? day : 16); + date = date.toISOString().substr(0, 10); + + await this.wait(selector) + .evaluate((selector, date) => { + let input = document.querySelector(selector).$ctrl.input; + input.value = date; + input.dispatchEvent(new Event('change')); + }, selector, date); + }, + + pickTime: async function(selector, time) { + await this.wait(selector) + .evaluate((selector, time) => { + let input = document.querySelector(selector).$ctrl.input; + input.value = time; + input.dispatchEvent(new Event('change')); + }, selector, time); + }, + + clearTextarea: function(selector) { + return this.wait(selector) + .evaluate(inputSelector => { + return document.querySelector(inputSelector).value = ''; + }, selector); + }, + + clearInput: function(selector) { + return this.wait(selector) + .evaluate(selector => { + let $ctrl = document.querySelector(selector).closest('.vn-field').$ctrl; + $ctrl.field = null; + $ctrl.$.$apply(); + $ctrl.input.dispatchEvent(new Event('change')); + }, selector); + }, + + getProperty: function(selector, property) { + return this.evaluate((selector, property) => { + return document.querySelector(selector)[property].replace(/\s+/g, ' ').trim(); + }, selector, property); + }, + + waitPropertyLength: function(selector, property, minLength) { + return this.wait((selector, property, minLength) => { + const element = document.querySelector(selector); + return element && element[property] != null && element[property] !== '' && element[property].length >= minLength; + }, selector, property, minLength) + .getProperty(selector, property); + }, + + waitPropertyValue: function(selector, property, status) { + return this.wait(selector) + .wait((selector, property, status) => { + const element = document.querySelector(selector); + return element[property] === status; + }, selector, property, status); + }, + + waitToGetProperty: function(selector, property) { + return this.wait((selector, property) => { + const element = document.querySelector(selector); + + return element && element[property] != null && element[property] !== ''; + }, selector, property) + .getProperty(selector, property); + }, + + write: function(selector, text) { + return this.wait(selector) + .type(selector, text); + }, + + waitToClick: function(selector) { + return this.wait(selector) + .click(selector); + }, + + focusElement: function(selector) { + return this.wait(selector) + .evaluate(selector => { + let element = document.querySelector(selector); + element.focus(); + }, selector); + }, + + isVisible: function(selector) { + return this.wait(selector) + .evaluate(elementSelector => { + let selectorMatches = document.querySelectorAll(elementSelector); + let element = selectorMatches[0]; + + if (selectorMatches.length > 1) + throw new Error(`Multiple matches of ${elementSelector} found`); + + let isVisible = false; + if (element) { + let eventHandler = event => { + event.preventDefault(); + isVisible = true; + }; + element.addEventListener('mouseover', eventHandler); + let rect = element.getBoundingClientRect(); + let x = rect.left + rect.width / 2; + let y = rect.top + rect.height / 2; + let elementInCenter = document.elementFromPoint(x, y); + let elementInTopLeft = document.elementFromPoint(rect.left, rect.top); + let elementInBottomRight = document.elementFromPoint(rect.right, rect.bottom); + + let e = new MouseEvent('mouseover', { + view: window, + bubbles: true, + cancelable: true, + }); + + if (elementInCenter) + elementInCenter.dispatchEvent(e); + + if (elementInTopLeft) + elementInTopLeft.dispatchEvent(e); + + if (elementInBottomRight) + elementInBottomRight.dispatchEvent(e); + + element.removeEventListener('mouseover', eventHandler); + } + return isVisible; + }, selector); + }, + + waitImgLoad: function(selector) { + return this.wait(selector) + .wait(selector => { + const imageReady = document.querySelector(selector).complete; + return imageReady; + }, selector); + }, + + clickIfVisible: function(selector) { + return this.wait(selector) + .isVisible(selector) + .then(visible => { + if (visible) + return this.click(selector); + + throw new Error(`invisible selector: ${selector}`); }); - if (elementInCenter) { - elementInCenter.dispatchEvent(e); - } - if (elementInTopLeft) { - elementInTopLeft.dispatchEvent(e); - } - if (elementInBottomRight) { - elementInBottomRight.dispatchEvent(e); - } - element.removeEventListener('mouseover', eventHandler); - } - return isVisible; - }, done, selector); -}); + }, -Nightmare.action('selectText', function(selector, done) { - this.wait(selector) - .evaluate(elementToSelect => { - const range = document.createRange(); - range.selectNodeContents(document.querySelector(elementToSelect)); - const sel = window.getSelection(); - sel.removeAllRanges(); - sel.addRange(range); - }, selector) - .mouseup(selector) - .then(done); -}); + countElement: function(selector) { + return this.evaluate(selector => { + return document.querySelectorAll(selector).length; + }, selector); + }, -Nightmare.action('countSearchResults', function(selector, done) { - this.evaluate_now(selector => { - return document.querySelectorAll(selector).length; - }, done, selector); -}); + waitForNumberOfElements: function(selector, count) { + return this.wait((selector, count) => { + return document.querySelectorAll(selector).length === count; + }, selector, count); + }, -Nightmare.action('waitForNumberOfElements', function(selector, count, done) { - this.wait((resultSelector, expectedCount) => { - return document.querySelectorAll(resultSelector).length === expectedCount; - }, selector, count) - .then(done); -}); + waitForClassNotPresent: function(selector, className) { + return this.wait(selector) + .wait((selector, className) => { + if (!document.querySelector(selector).classList.contains(className)) + return true; + }, selector, className); + }, -Nightmare.action('waitForTextInElement', function(selector, name, done) { - this.wait(selector) - .wait((resultSelector, expectedText) => { - return document.querySelector(resultSelector).innerText.toLowerCase().includes(expectedText.toLowerCase()); - }, selector, name) - .then(done); -}); + waitForClassPresent: function(selector, className) { + return this.wait(selector) + .wait((elementSelector, targetClass) => { + if (document.querySelector(elementSelector).classList.contains(targetClass)) + return true; + }, selector, className); + }, -Nightmare.action('waitForTextInInput', function(selector, name, done) { - this.wait(selector) - .wait((resultSelector, expectedText) => { - return document.querySelector(resultSelector).value.toLowerCase().includes(expectedText.toLowerCase()); - }, selector, name) - .then(done); -}); + waitForTextInElement: function(selector, text) { + return this.wait(selector) + .wait((selector, text) => { + return document.querySelector(selector).innerText.toLowerCase().includes(text.toLowerCase()); + }, selector, text); + }, -Nightmare.action('waitForInnerText', function(selector, done) { - this.wait(selector) - .wait(selector => { - let innerText = document.querySelector(selector).innerText; - return innerText != null && innerText != ''; - }, selector) - .evaluate_now(selector => { - return document.querySelector(selector).innerText; - }, done, selector); -}); + waitForTextInInput: function(selector, text) { + return this.wait(selector) + .wait((selector, text) => { + return document.querySelector(selector).value.toLowerCase().includes(text.toLowerCase()); + }, selector, text); + }, -Nightmare.action('waitForEmptyInnerText', function(selector, done) { - this.wait(selector => { - return document.querySelector(selector).innerText == ''; - }, selector) - .then(done); -}); + waitForInnerText: function(selector) { + return this.wait(selector) + .wait(selector => { + const innerText = document.querySelector(selector).innerText; + return innerText != null && innerText != ''; + }, selector) + .evaluate(selector => { + return document.querySelector(selector).innerText; + }, selector); + }, -Nightmare.action('waitForSnackbarReset', function(done) { - this.click('vn-snackbar button') - .waitForEmptyInnerText('vn-snackbar .text') - .then(done); -}); + waitForEmptyInnerText: function(selector) { + return this.wait(selector => { + return document.querySelector(selector).innerText == ''; + }, selector); + }, -Nightmare.action('waitForSnackbar', function(done) { - this.wait(500) - .waitForInnerText('vn-snackbar .text') - .then(value => { - this.waitForSnackbarReset() - .then(() => done(null, value)); + waitForURL: function(hashURL) { + return this.wait(hash => { + return document.location.hash.includes(hash); + }, hashURL); + }, + + waitForShapes: function(selector) { + return this.wait(selector) + .evaluate(selector => { + const shapes = document.querySelectorAll(selector); + const shapesList = []; + + for (const shape of shapes) + shapesList.push(shape.innerText); + + + return shapesList; + }, selector); + }, + waitForSnackbar: function() { + return this.wait(500) + .waitForShapes('vn-snackbar .shape .text'); + }, + + waitForLastShape: function(selector) { + return this.wait(selector) + .evaluate(selector => { + const shape = document.querySelector(selector); + + return shape.innerText; + }, selector); + }, + + waitForLastSnackbar: function() { + return this.wait(500) + .waitForSpinnerLoad() + .waitForLastShape('vn-snackbar .shape .text'); + }, + + accessToSearchResult: function(searchValue) { + return this.clearInput('vn-searchbar input') + .write('vn-searchbar input', searchValue) + .click('vn-searchbar vn-icon[icon="search"]') + .wait(100) + .waitForNumberOfElements('.search-result', 1) + .evaluate(() => { + return document.querySelector('ui-view vn-card vn-table') != null; + }) + .then(result => { + if (result) + return this.waitToClick('ui-view vn-card vn-td'); + + return this.waitToClick('ui-view vn-card a'); + }); + }, + + accessToSection: function(sectionRoute) { + return this.wait(`vn-left-menu`) + .evaluate(sectionRoute => { + return document.querySelector(`vn-left-menu li li > a[ui-sref="${sectionRoute}"]`) != null; + }, sectionRoute) + .then(nested => { + if (nested) { + this.waitToClick('vn-left-menu vn-item-section > vn-icon[icon=keyboard_arrow_down]') + .wait('vn-left-menu .expanded'); + } + + return this.waitToClick(`vn-left-menu li > a[ui-sref="${sectionRoute}"]`) + .waitForSpinnerLoad(); + }); + }, + + autocompleteSearch: function(autocompleteSelector, searchValue) { + return this.waitToClick(`${autocompleteSelector} input`) + .write(`.vn-drop-down.shown input`, searchValue) + .waitToClick(`.vn-drop-down.shown li.active`) + .wait((autocompleteSelector, searchValue) => { + return document.querySelector(`${autocompleteSelector} input`).value + .toLowerCase() + .includes(searchValue.toLowerCase()); + }, autocompleteSelector, searchValue); + }, + + reloadSection: function(sectionRoute) { + return this.waitToClick('vn-icon[icon="desktop_windows"]') + .wait('vn-card.summary') + .waitToClick(`vn-left-menu li > a[ui-sref="${sectionRoute}"]`); + }, + + forceReloadSection: function(sectionRoute) { + return this.waitToClick('vn-icon[icon="desktop_windows"]') + .waitToClick('button[response="accept"]') + .wait('vn-card.summary') + .waitToClick(`vn-left-menu li > a[ui-sref="${sectionRoute}"]`); + }, + + checkboxState: function(selector) { + return this.wait(selector) + .evaluate(selector => { + let checkbox = document.querySelector(selector); + switch (checkbox.$ctrl.field) { + case null: + return 'intermediate'; + case true: + return 'checked'; + default: + return 'unchecked'; + } + }, selector); + }, + + isDisabled: function(selector) { + return this.wait(selector) + .evaluate(selector => { + let element = document.querySelector(selector); + return element.$ctrl.disabled; + }, selector); + }, + + waitForStylePresent: function(selector, property, value) { + return this.wait((selector, property, value) => { + const element = document.querySelector(selector); + return element.style[property] == value; + }, selector, property, value); + }, + + waitForSpinnerLoad: function() { + return this.waitUntilNotPresent('vn-topbar vn-spinner'); + }, + + waitForWatcherData: function(selector) { + return this.wait(selector) + .wait(selector => { + const watcher = document.querySelector(selector); + let orgData = watcher.$ctrl.orgData; + return !angular.equals({}, orgData) && orgData != null; + }, selector) + .waitForSpinnerLoad(); + } +}; + +for (let name in actions) { + Nightmare.action(name, function(...args) { + let fnArgs = args.slice(0, args.length - 1); + let done = args[args.length - 1]; + + actions[name].apply(this, fnArgs) + .then(res => done(null, res)) + .catch(err => { + let stringArgs = fnArgs + .map(i => typeof i == 'function' ? 'Function' : i) + .join(', '); + + let orgMessage = err.message.startsWith('.wait()') + ? '.wait() timed out' + : err.message; + + done(new Error(`.${name}(${stringArgs}) failed: ${orgMessage}`)); + }); }); -}); - -Nightmare.action('waitForURL', function(hashURL, done) { - this.wait(hash => { - return document.location.hash.includes(hash); - }, hashURL) - .then(done); -}); +} diff --git a/e2e/helpers/helpers.js b/e2e/helpers/helpers.js deleted file mode 100644 index a7866c2d2..000000000 --- a/e2e/helpers/helpers.js +++ /dev/null @@ -1,14 +0,0 @@ -import createNightmare from './nightmare'; -export default myCreateNightmare; - -function myCreateNightmare() { - let nightmare = createNightmare(); - nightmare.header('Accept-Language', 'en'); - - afterAll(() => { - return nightmare - .end(); - }); - - return nightmare; -} diff --git a/e2e/helpers/nightmare.js b/e2e/helpers/nightmare.js index 9f28d0151..5b87f2dca 100644 --- a/e2e/helpers/nightmare.js +++ b/e2e/helpers/nightmare.js @@ -1,26 +1,29 @@ -/* eslint no-console: 0 */ -import Nightmare from 'nightmare'; +const Nightmare = require('nightmare'); +const config = require('./config.js'); -export default function createNightmare(width = 1280, height = 720) { - const nightmare = new Nightmare({show: true, typeInterval: 10, x: 0, y: 0}).viewport(width, height); +let nightmare; - nightmare.on('page', (type, message, error) => { - fail(error); - }); +module.exports = function createNightmare(width = 1280, height = 800) { + if (nightmare) + return nightmare; - nightmare.on('dom-ready', function() { - nightmare.inject('js', `${__dirname}/nightmareModifiers.js`); - }); + nightmare = new Nightmare({ + show: process.env.E2E_SHOW, + typeInterval: 10, + x: 0, + y: 0, + waitTimeout: 2000, + // openDevTools: {mode: 'detach'} + }).viewport(width, height); - nightmare.on('console', (type, message) => { + nightmare.on('console', (type, message, ...args) => { if (type === 'error') { - fail(message); - } - if (type === 'log') { - // console.log(message); - } + console[type](message, ...args); + throw new Error(message); + } else + console[type](message, ...args); }); - return nightmare; -} -jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; + nightmare.header('Accept-Language', 'en'); + return nightmare.goto(config.url); +}; diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index ab30e2db7..bb23c9d96 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -1,265 +1,744 @@ -// eslint max-len: ["error", 500] -// eslint key-spacing: ["error", 500] -import components from './components_selectors.js'; export default { globalItems: { - logOutButton: `#logout`, - applicationsMenuButton: `#apps`, - applicationsMenuVisible: `vn-main-menu [vn-id="apps-menu"] ul`, - clientsButton: `vn-main-menu [vn-id="apps-menu"] ul > li:nth-child(1)` - }, - moduleAccessView: { - clientsSectionButton: `${components.vnModuleContainer}[ui-sref="clients"]`, - itemsSectionButton: `${components.vnModuleContainer}[ui-sref="item.index"]` + applicationsMenuButton: '#apps', + applicationsMenuVisible: '.modules-menu', + clientsButton: '.modules-menu > li[ui-sref="client.index"]', + itemsButton: '.modules-menu > li[ui-sref="item.index"]', + ticketsButton: '.modules-menu > li[ui-sref="ticket.index"]', + invoiceOutButton: '.modules-menu > li[ui-sref="invoiceOut.index"]', + claimsButton: '.modules-menu > li[ui-sref="claim.index"]', + returnToModuleIndexButton: 'a[ui-sref="order.index"]', + userMenuButton: '#user', + userLocalWarehouse: '.user-popover vn-autocomplete[ng-model="$ctrl.localWarehouseFk"]', + userLocalBank: '.user-popover vn-autocomplete[ng-model="$ctrl.localBankFk"]', + userLocalCompany: '.user-popover vn-autocomplete[ng-model="$ctrl.localCompanyFk"]', + userWarehouse: '.user-popover vn-autocomplete[ng-model="$ctrl.warehouseFk"]', + userCompany: '.user-popover vn-autocomplete[ng-model="$ctrl.companyFk"]', + userConfigFirstAutocompleteClear: '#localWarehouse .icons > vn-icon[icon=clear]', + userConfigSecondAutocompleteClear: '#localBank .icons > vn-icon[icon=clear]', + userConfigThirdAutocompleteClear: '#localCompany .icons > vn-icon[icon=clear]', + acceptButton: '.vn-confirm.shown button[response=accept]' }, clientsIndex: { - searchClientInput: `${components.vnTextfield}`, - searchButton: `${components.vnSearchBar} > vn-icon-button > button`, - searchResult: `vn-item-client a`, - createClientButton: `${components.vnFloatButton}` + searchClientInput: `vn-textfield input`, + searchButton: 'vn-searchbar vn-icon[icon="search"]', + searchResult: 'vn-client-index .vn-item', + createClientButton: `vn-float-button`, + othersButton: 'vn-left-menu li[name="Others"] > a' }, createClientView: { - name: `${components.vnTextfield}[name="name"]`, - taxNumber: `${components.vnTextfield}[name="fi"]`, - socialName: `${components.vnTextfield}[name="socialName"]`, - userName: `${components.vnTextfield}[name="userName"]`, - email: `${components.vnTextfield}[name="email"]`, - salesPersonInput: `vn-autocomplete[field="$ctrl.client.salesPersonFk"] input`, - salesBruceBannerOption: `vn-autocomplete[field="$ctrl.client.salesPersonFk"] vn-drop-down ul > li:nth-child(1)`, - createButton: `${components.vnSubmit}` + name: `vn-textfield input[name="name"]`, + taxNumber: `vn-textfield input[name="fi"]`, + socialName: `vn-textfield input[name="socialName"]`, + street: `vn-textfield input[name="street"]`, + postcode: `vn-textfield input[name="postcode"]`, + city: `vn-textfield input[name="city"]`, + province: `vn-autocomplete[ng-model="$ctrl.client.provinceFk"]`, + country: `vn-autocomplete[ng-model="$ctrl.client.countryFk"]`, + userName: `vn-textfield input[name="userName"]`, + email: `vn-textfield input[name="email"]`, + salesPersonAutocomplete: `vn-autocomplete[ng-model="$ctrl.client.salesPersonFk"]`, + createButton: `button[type=submit]`, + cancelButton: 'vn-button[href="#!/client/index"]' + }, + clientDescriptor: { + moreMenu: 'vn-client-descriptor vn-icon-menu[icon=more_vert]', + simpleTicketButton: '.vn-drop-down.shown li[name="Simple ticket"]' }, clientBasicData: { - basicDataButton: `${components.vnMenuItem}[ui-sref="clientCard.basicData"]`, - nameInput: `${components.vnTextfield}[name="name"]`, - contactInput: `${components.vnTextfield}[name="contact"]`, - phoneInput: `${components.vnTextfield}[name="phone"]`, - mobileInput: `${components.vnTextfield}[name="mobile"]`, - faxInput: `${components.vnTextfield}[name="fax"]`, - emailInput: `${components.vnTextfield}[name="email"]`, - salesPersonInput: `${components.vnAutocomplete}[field="$ctrl.client.salesPersonFk"] input`, - salesPersonOptionOne: `${components.vnAutocomplete}[field="$ctrl.client.salesPersonFk"] vn-drop-down ul > li:nth-child(1)`, - channelInput: `${components.vnAutocomplete}[field="$ctrl.client.contactChannelFk"] input`, - channelMetropolisOption: `${components.vnAutocomplete}[field="$ctrl.client.contactChannelFk"] vn-drop-down ul > li:nth-child(3)`, - saveButton: `${components.vnSubmit}` + basicDataButton: 'vn-left-menu a[ui-sref="client.card.basicData"]', + nameInput: 'vn-textfield[ng-model="$ctrl.client.name"] input', + contactInput: 'vn-textfield[ng-model="$ctrl.client.contact"] input', + phoneInput: 'vn-textfield[ng-model="$ctrl.client.phone"] input', + mobileInput: 'vn-textfield[ng-model="$ctrl.client.mobile"] input', + emailInput: 'vn-textfield[ng-model="$ctrl.client.email"] input', + salesPersonAutocomplete: 'vn-autocomplete[ng-model="$ctrl.client.salesPersonFk"]', + channelAutocomplete: 'vn-autocomplete[ng-model="$ctrl.client.contactChannelFk"]', + saveButton: `button[type=submit]` }, clientFiscalData: { - fiscalDataButton: `${components.vnMenuItem}[ui-sref="clientCard.fiscalData"]`, - socialNameInput: `${components.vnTextfield}[name="socialName"]`, - fiscalIdInput: `${components.vnTextfield}[name="fi"]`, - equalizationTaxCheckboxLabel: `${components.vnCheck}[label='Is equalizated'] > label > input`, - acceptPropagationButton: `vn-client-fiscal-data > vn-confirm button[response=ACCEPT]`, - addressInput: `${components.vnTextfield}[name="street"]`, - cityInput: `${components.vnTextfield}[name="city"]`, - postcodeInput: `${components.vnTextfield}[name="postcode"]`, - provinceInput: `${components.vnAutocomplete}[field="$ctrl.client.provinceFk"] input`, - provinceFifthOption: `${components.vnAutocomplete}[field="$ctrl.client.provinceFk"] vn-drop-down ul > li:nth-child(5)`, - countryInput: `${components.vnAutocomplete}[field="$ctrl.client.countryFk"] input`, - countryThirdOption: `${components.vnAutocomplete}[field="$ctrl.client.countryFk"] vn-drop-down ul > li:nth-child(3)`, - activeCheckboxLabel: `${components.vnCheck}[label='Active'] > label`, - invoiceByAddressCheckboxInput: `${components.vnCheck}[label='Invoice by address'] > label > input`, - verifiedDataCheckboxInput: `${components.vnCheck}[label='Verified data'] > label > input`, - hasToInvoiceCheckboxLabel: `${components.vnCheck}[label='Has to invoice'] > label`, - invoiceByMailCheckboxLabel: `${components.vnCheck}[label='Invoice by mail'] > label`, - viesCheckboxInput: `${components.vnCheck}[label='Vies'] > label > input`, - saveButton: `${components.vnSubmit}` + fiscalDataButton: 'vn-left-menu a[ui-sref="client.card.fiscalData"]', + socialNameInput: `vn-textfield input[name="socialName"]`, + fiscalIdInput: `vn-textfield input[name="fi"]`, + equalizationTaxCheckbox: 'vn-check[ng-model="$ctrl.client.isEqualizated"]', + acceptPropagationButton: '.vn-confirm.shown button[response=accept]', + addressInput: `vn-textfield input[name="street"]`, + postcodeInput: `vn-textfield input[name="postcode"]`, + cityInput: `vn-textfield input[name="city"]`, + provinceAutocomplete: 'vn-autocomplete[ng-model="$ctrl.client.provinceFk"]', + countryAutocomplete: 'vn-autocomplete[ng-model="$ctrl.client.countryFk"]', + activeCheckbox: 'vn-check[label="Active"]', + frozenCheckbox: 'vn-check[label="Frozen"]', + invoiceByAddressCheckbox: 'vn-check[label="Invoice by address"]', + verifiedDataCheckbox: 'vn-check[label="Verified data"]', + hasToInvoiceCheckbox: 'vn-check[label="Has to invoice"]', + invoiceByMailCheckbox: 'vn-check[label="Invoice by mail"]', + viesCheckbox: 'vn-check[label="Vies"]', + saveButton: `button[type=submit]`, + watcher: 'vn-client-fiscal-data vn-watcher' }, - clientPayMethod: { - payMethodButton: `${components.vnMenuItem}[ui-sref="clientCard.billingData"]`, - payMethodInput: `${components.vnAutocomplete}[field="$ctrl.client.payMethodFk"] input`, - payMethodIBANOption: `${components.vnAutocomplete}[field="$ctrl.client.payMethodFk"] vn-drop-down ul > li:nth-child(5)`, - payMethodOptionOne: `${components.vnAutocomplete}[field="$ctrl.client.payMethodFk"] vn-drop-down ul > li:nth-child(2)`, - IBANInput: `${components.vnTextfield}[name="iban"]`, - dueDayInput: `${components.vnTextfield}[name="dueDay"]`, - cancelNotificationButton: 'vn-client-billing-data > vn-confirm button[response=CANCEL]', - receivedCoreVNHCheckbox: `${components.vnCheck}[label='Received core VNH'] > label > input`, - receivedCoreVNLCheckbox: `${components.vnCheck}[label='Received core VNL'] > label > input`, - receivedB2BVNLCheckbox: `${components.vnCheck}[label='Received B2B VNL'] > label > input`, - saveButton: `${components.vnSubmit}` + clientBillingData: { + payMethodAutocomplete: 'vn-client-billing-data vn-autocomplete[ng-model="$ctrl.client.payMethodFk"]', + IBANInput: `vn-client-billing-data vn-textfield input[name="iban"]`, + dueDayInput: `vn-client-billing-data vn-input-number input[name="dueDay"]`, + receivedCoreLCRCheckbox: 'vn-client-billing-data vn-check[label="Received LCR"]', + receivedCoreVNLCheckbox: 'vn-client-billing-data vn-check[label="Received core VNL"]', + receivedB2BVNLCheckbox: 'vn-client-billing-data vn-check[label="Received B2B VNL"]', + swiftBicAutocomplete: 'vn-client-billing-data vn-autocomplete[ng-model="$ctrl.client.bankEntityFk"]', + clearswiftBicButton: 'vn-client-billing-data vn-autocomplete[ng-model="$ctrl.client.bankEntityFk"] .icons > vn-icon[icon=clear]', + newBankEntityButton: 'vn-client-billing-data vn-icon-button[vn-tooltip="New bank entity"] > button', + newBankEntityName: '.vn-dialog.shown vn-textfield[label="Name"] input', + newBankEntityBIC: '.vn-dialog.shown vn-textfield[label="Swift / BIC"] input', + newBankEntityCode: '.vn-dialog.shown vn-textfield[label="Entity Code"] input', + acceptBankEntityButton: '.vn-dialog.shown button[response="accept"]', + saveButton: `button[type=submit]`, + watcher: 'vn-client-billing-data vn-watcher' }, clientAddresses: { - addressesButton: `${components.vnMenuItem}[ui-sref="clientCard.addresses.list"]`, - createAddress: `${components.vnFloatButton}`, - defaultCheckboxInput: `${components.vnCheck}[label='Default'] > label > input`, - consigneeInput: `${components.vnTextfield}[name="nickname"]`, - streetAddressInput: `${components.vnTextfield}[name="street"]`, - postcodeInput: `${components.vnTextfield}[name="postalCode"]`, - cityInput: `${components.vnTextfield}[name="city"]`, - provinceInput: `${components.vnAutocomplete}[field="$ctrl.address.provinceFk"] input`, - provinceSecondOption: `${components.vnAutocomplete}[field="$ctrl.address.provinceFk"] vn-drop-down ul > li:nth-child(2)`, - agencyInput: `${components.vnAutocomplete}[field="$ctrl.address.agencyModeFk"] input`, - agenctySecondOption: `${components.vnAutocomplete}[field="$ctrl.address.agencyModeFk"] vn-drop-down ul > li:nth-child(2)`, - phoneInput: `${components.vnTextfield}[name="phone"]`, - mobileInput: `${components.vnTextfield}[name="mobile"]`, - defaultAddress: 'vn-client-addresses > vn-vertical > vn-card > div > vn-horizontal:nth-child(2) > vn-one > vn-horizontal > vn-one > div:nth-child(2)', - secondMakeDefaultStar: 'vn-client-addresses > vn-vertical > vn-card > div > vn-horizontal:nth-child(3) > vn-one > vn-horizontal > vn-none > i', - firstEditButton: `${components.vnIconButton}[icon='edit']`, - secondEditButton: `vn-horizontal:nth-child(3) > vn-one > vn-horizontal > a > ${components.vnIconButton}[icon='edit']`, - activeCheckbox: `${components.vnCheck}[label='Enabled'] > label > input`, - equalizationTaxCheckboxLabel: `${components.vnCheck}[label='Is equalizated'] > label > input`, - firstObservationTypeSelect: `${components.vnAutocomplete}[field="observation.observationTypeFk"]:nth-child(1) input`, - firstObservationTypeSelectOptionOne: `${components.vnAutocomplete}[field="observation.observationTypeFk"] vn-drop-down ul > li:nth-child(1)`, - firstObservationDescriptionInput: `vn-horizontal:nth-child(3) > vn-textfield[label="Description"] > div > input`, - secondObservationTypeSelect: `${components.vnAutocomplete}[field="observation.observationTypeFk"]:nth-child(2) input`, - secondObservationTypeSelectOptionTwo: `${components.vnAutocomplete}[field="observation.observationTypeFk"] vn-drop-down ul > li:nth-child(2)`, - secondObservationDescriptionInput: `vn-horizontal:nth-child(4) > vn-textfield[label="Description"] > div > input`, - thirdObservationTypeSelect: `${components.vnAutocomplete}[field="observation.observationTypeFk"]:nth-child(3) input`, - thirdObservationTypeSelectOptionThree: `${components.vnAutocomplete}[field="observation.observationTypeFk"] vn-drop-down ul > li:nth-child(3)`, - thirdObservationDescriptionInput: `vn-horizontal:nth-child(5) > vn-textfield[label="Description"] > div > input`, - addObservationButton: `${components.vnIcon}[icon="add_circle"]`, - saveButton: `${components.vnSubmit}` + addressesButton: 'vn-left-menu a[ui-sref="client.card.address.index"]', + createAddress: `vn-client-address-index vn-float-button`, + defaultCheckboxInput: 'vn-check[label="Default"]', + consigneeInput: `vn-textfield input[name="nickname"]`, + streetAddressInput: `vn-textfield input[name="street"]`, + postcodeInput: `vn-textfield input[name="postalCode"]`, + cityInput: `vn-textfield input[name="city"]`, + provinceAutocomplete: 'vn-autocomplete[ng-model="$ctrl.address.provinceFk"]', + agencyAutocomplete: 'vn-autocomplete[ng-model="$ctrl.address.agencyModeFk"]', + phoneInput: `vn-textfield input[name="phone"]`, + mobileInput: `vn-textfield input[name="mobile"]`, + defaultAddress: 'vn-client-address-index div:nth-child(1) div[name="street"]', + secondMakeDefaultStar: 'vn-client-address-index vn-card div:nth-child(2) vn-icon-button[icon="star_border"]', + firstEditAddress: 'vn-client-address-index div:nth-child(1) > a', + secondEditAddress: 'vn-client-address-index div:nth-child(2) > a', + activeCheckbox: 'vn-check[label="Enabled"]', + equalizationTaxCheckbox: 'vn-client-address-edit vn-check[label="Is equalizated"]', + firstObservationTypeAutocomplete: 'vn-client-address-edit [name=observations] :nth-child(1) [ng-model="observation.observationTypeFk"]', + firstObservationDescriptionInput: 'vn-client-address-edit [name=observations] :nth-child(1) [ng-model="observation.description"] input', + secondObservationTypeAutocomplete: 'vn-client-address-edit [name=observations] :nth-child(2) [ng-model="observation.observationTypeFk"]', + secondObservationDescriptionInput: 'vn-client-address-edit [name=observations] :nth-child(2) [ng-model="observation.description"] input', + addObservationButton: 'vn-client-address-edit div[name="observations"] vn-icon-button[icon="add_circle"]', + saveButton: `button[type=submit]`, + cancelCreateAddressButton: 'button[ui-sref="client.card.address.index"]', + cancelEditAddressButton: 'vn-client-address-edit > form > vn-button-bar > vn-button > button', + watcher: 'vn-client-address-edit vn-watcher' }, clientWebAccess: { - webAccessButton: `${components.vnMenuItem}[ui-sref="clientCard.webAccess"]`, - enableWebAccessCheckbox: `${components.vnCheck}[label='Enable web access'] > label > input`, - userNameInput: `${components.vnTextfield}[name="name"]`, - saveButton: `${components.vnSubmit}` + webAccessButton: 'vn-left-menu a[ui-sref="client.card.webAccess"]', + enableWebAccessCheckbox: 'vn-check[label="Enable web access"]', + userNameInput: `vn-textfield input[name="name"]`, + saveButton: `button[type=submit]` }, clientNotes: { - notesButton: `${components.vnMenuItem}[ui-sref="clientCard.notes.list"]`, - addNoteFloatButton: `${components.vnFloatButton}`, - noteInput: `${components.vnTextarea}[label="Note"]`, - saveButton: `${components.vnSubmit}`, - firstNoteText: 'vn-client-notes .text' + addNoteFloatButton: `vn-float-button`, + noteInput: 'vn-textarea[label="Note"]', + saveButton: `button[type=submit]`, + firstNoteText: 'vn-client-note .text' }, clientCredit: { - creditButton: `${components.vnMenuItem}[ui-sref="clientCard.credit.list"]`, - addCreditFloatButton: `${components.vnFloatButton}`, - creditInput: `${components.vnTextfield}[name="credit"]`, - saveButton: `${components.vnSubmit}`, - firstCreditText: 'vn-client-credit-list .list-element' + addCreditFloatButton: `vn-float-button`, + creditInput: `vn-input-number input[name="credit"]`, + saveButton: `button[type=submit]`, + firstCreditText: 'vn-client-credit-index vn-card vn-table vn-tbody > vn-tr' }, clientGreuge: { - greugeButton: `${components.vnMenuItem}[ui-sref="clientCard.greuge.list"]`, - addGreugeFloatButton: `${components.vnFloatButton}`, - amountInput: `${components.vnTextfield}[name="amount"]`, - descriptionInput: `${components.vnTextfield}[name="description"]`, - typeInput: `${components.vnAutocomplete}[field="$ctrl.greuge.greugeTypeFk"] input`, - typeSecondOption: `${components.vnAutocomplete}[field="$ctrl.greuge.greugeTypeFk"] vn-drop-down ul > li`, - saveButton: `${components.vnSubmit}`, - firstGreugeText: 'vn-client-greuge-list .list-element' + addGreugeFloatButton: `vn-float-button`, + amountInput: `vn-input-number input[name="amount"]`, + descriptionInput: `vn-textfield input[name="description"]`, + typeAutocomplete: 'vn-autocomplete[ng-model="$ctrl.greuge.greugeTypeFk"]', + saveButton: `button[type=submit]`, + firstGreugeText: 'vn-client-greuge-index vn-card vn-table vn-tbody > vn-tr' }, clientMandate: { - mandateButton: `${components.vnMenuItem}[ui-sref="clientCard.mandate"]`, - firstMandateText: 'vn-client-mandate .list-element' + firstMandateText: 'vn-client-mandate vn-card vn-table vn-tbody > vn-tr' }, clientInvoices: { - invoicesButton: `${components.vnMenuItem}[ui-sref="clientCard.invoices"]`, - firstInvoiceText: 'vn-client-invoices .list-element' + firstInvoiceText: 'vn-client-invoice vn-card vn-table vn-tbody > vn-tr' }, - itemsIndex: { - createItemButton: `${components.vnFloatButton}`, - searchResult: `vn-item-product a`, - searchResultPreviewButton: `vn-item-product .buttons > [icon="desktop_windows"]`, - searchResultCloneButton: `vn-item-product .buttons > [icon="icon-clone"]`, - acceptClonationAlertButton: `vn-item-list [vn-id="clone"] [response="ACCEPT"]`, - searchItemInput: `${components.vnTextfield}`, - searchButton: `${components.vnSearchBar} > vn-icon-button > button`, - closeItemSummaryPreview: 'vn-item-list [vn-id="preview"] button.close' - }, - itemCreateView: { - name: `${components.vnTextfield}[name="name"]`, - typeSelect: `${components.vnAutocomplete}[field="$ctrl.item.typeFk"] input`, - typeSelectOptionOne: `${components.vnAutocomplete}[field="$ctrl.item.typeFk"] vn-drop-down ul > li:nth-child(2)`, - intrastatSelect: `${components.vnAutocomplete}[field="$ctrl.item.intrastatFk"] input`, - intrastatSelectOptionOne: `${components.vnAutocomplete}[field="$ctrl.item.intrastatFk"] vn-drop-down ul > li:nth-child(2)`, - originSelect: `${components.vnAutocomplete}[field="$ctrl.item.originFk"] input`, - originSelectOptionOne: `${components.vnAutocomplete}[field="$ctrl.item.originFk"] vn-drop-down ul > li:nth-child(2)`, - expenceSelect: `${components.vnAutocomplete}[field="$ctrl.item.expenceFk"] input`, - expenceSelectOptionOne: `${components.vnAutocomplete}[field="$ctrl.item.expenceFk"] vn-drop-down ul > li:nth-child(2)`, - createButton: `${components.vnSubmit}` + clientLog: { + logButton: 'vn-left-menu a[ui-sref="client.card.log"]', + lastModificationDate: 'vn-client-log > vn-log vn-table vn-tbody > vn-tr > vn-td:nth-child(1)', + lastModificationPreviousValue: 'vn-client-log vn-table vn-td.before', + lastModificationCurrentValue: 'vn-client-log vn-table vn-td.after' }, + clientBalance: { + balanceButton: 'vn-left-menu a[ui-sref="client.card.balance.index"]', + companyAutocomplete: 'vn-client-balance-index vn-autocomplete[ng-model="$ctrl.companyFk"]', + newPaymentButton: `vn-float-button`, + newPaymentBank: '.vn-dialog.shown vn-autocomplete[ng-model="$ctrl.receipt.bankFk"]', + newPaymentAmountInput: '.vn-dialog.shown vn-input-number[ng-model="$ctrl.receipt.amountPaid"] input', + saveButton: '.vn-dialog.shown vn-button[label="Save"]', + firstBalanceLine: 'vn-client-balance-index vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(8)' + + }, + webPayment: { + confirmFirstPaymentButton: 'vn-client-web-payment vn-tr:nth-child(1) vn-icon-button[icon="done_all"]', + firstPaymentConfirmed: 'vn-client-web-payment vn-tr:nth-child(1) vn-icon[icon="check"]' + }, + dms: { + deleteFileButton: 'vn-client-dms-index vn-tr:nth-child(1) vn-icon-button[icon="delete"]', + firstDocWorker: 'vn-client-dms-index vn-td:nth-child(8) > span', + firstDocWorkerDescriptor: '.vn-popover.shown vn-worker-descriptor', + acceptDeleteButton: '.vn-confirm.shown button[response="accept"]' + }, + itemsIndex: { + searchIcon: 'vn-searchbar vn-icon[icon="search"]', + createItemButton: `vn-float-button`, + searchResult: 'vn-item-index a.vn-tr', + searchResultPreviewButton: 'vn-item-index .buttons > [icon="desktop_windows"]', + searchResultCloneButton: 'vn-item-index .buttons > [icon="icon-clone"]', + acceptClonationAlertButton: '.vn-confirm.shown [response="accept"]', + searchItemInput: 'vn-searchbar vn-textfield input', + searchButton: 'vn-searchbar vn-icon[icon="search"]', + closeItemSummaryPreview: '.vn-popup.shown', + fieldsToShowButton: 'vn-item-index vn-table > div > div > vn-icon-button[icon="menu"]', + fieldsToShowForm: '.vn-dialog.shown form', + firstItemImage: 'vn-item-index vn-tbody > a:nth-child(1) > vn-td:nth-child(1) > img', + firstItemImageTd: 'vn-item-index vn-table a:nth-child(1) vn-td:nth-child(1)', + firstItemId: 'vn-item-index vn-tbody > a:nth-child(1) > vn-td:nth-child(2)', + idCheckbox: '.vn-dialog.shown form vn-horizontal:nth-child(2) > vn-check', + stemsCheckbox: '.vn-dialog.shown form vn-horizontal:nth-child(3) > vn-check', + sizeCheckbox: '.vn-dialog.shown form vn-horizontal:nth-child(4) > vn-check', + nicheCheckbox: '.vn-dialog.shown form vn-horizontal:nth-child(5) > vn-check', + typeCheckbox: '.vn-dialog.shown form vn-horizontal:nth-child(6) > vn-check', + categoryCheckbox: '.vn-dialog.shown form vn-horizontal:nth-child(7) > vn-check', + intrastadCheckbox: '.vn-dialog.shown form vn-horizontal:nth-child(8) > vn-check', + originCheckbox: '.vn-dialog.shown form vn-horizontal:nth-child(9) > vn-check', + buyerCheckbox: '.vn-dialog.shown form vn-horizontal:nth-child(10) > vn-check', + destinyCheckbox: '.vn-dialog.shown form vn-horizontal:nth-child(11) > vn-check', + taxClassCheckbox: '.vn-dialog.shown form vn-horizontal:nth-child(12) > vn-check', + saveFieldsButton: '.vn-dialog.shown vn-horizontal:nth-child(16) > vn-button > button' + }, + itemCreateView: { + temporalName: `vn-textfield input[name="provisionalName"]`, + typeAutocomplete: 'vn-autocomplete[ng-model="$ctrl.item.typeFk"]', + intrastatAutocomplete: 'vn-autocomplete[ng-model="$ctrl.item.intrastatFk"]', + originAutocomplete: 'vn-autocomplete[ng-model="$ctrl.item.originFk"]', + createButton: `button[type=submit]`, + cancelButton: 'vn-button[ui-sref="item.index"]' + }, + itemDescriptor: { + goBackToModuleIndexButton: 'vn-item-descriptor a[href="#!/item/index"]', + moreMenu: 'vn-item-descriptor vn-icon-menu[icon=more_vert]', + moreMenuRegularizeButton: '.vn-drop-down.shown li[name="Regularize stock"]', + regularizeQuantityInput: '.vn-dialog.shown tpl-body > div > vn-textfield input', + regularizeWarehouseAutocomplete: '.vn-dialog.shown vn-autocomplete[ng-model="$ctrl.warehouseFk"]', + editButton: 'vn-item-descriptor vn-float-button[icon="edit"]', + regularizeSaveButton: '.vn-dialog.shown tpl-buttons > button', + inactiveIcon: 'vn-item-descriptor vn-icon[icon="icon-unavailable"]', + navigateBackToIndex: 'vn-item-descriptor vn-icon[icon="chevron_left"]' + }, itemBasicData: { + basicDataButton: 'vn-left-menu a[ui-sref="item.card.basicData"]', goToItemIndexButton: 'vn-item-descriptor [ui-sref="item.index"]', - basicDataButton: `${components.vnMenuItem}[ui-sref="item.card.data"]`, - typeSelect: `${components.vnAutocomplete}[field="$ctrl.item.typeFk"] input`, - typeSelectOptionTwo: `${components.vnAutocomplete}[field="$ctrl.item.typeFk"] vn-drop-down ul > li:nth-child(2)`, - intrastatSelect: `${components.vnAutocomplete}[field="$ctrl.item.intrastatFk"] input`, - intrastatSelectOptionOne: `${components.vnAutocomplete}[field="$ctrl.item.intrastatFk"] vn-drop-down ul > li:nth-child(1)`, - nameInput: `vn-horizontal:nth-child(2) > ${components.vnTextfield}`, - relevancyInput: `vn-horizontal:nth-child(3) > ${components.vnTextfield}`, - originSelect: `${components.vnAutocomplete}[field="$ctrl.item.originFk"] input`, - originSelectOptionTwo: `${components.vnAutocomplete}[field="$ctrl.item.originFk"] vn-drop-down ul > li:nth-child(2)`, - expenceSelect: `${components.vnAutocomplete}[field="$ctrl.item.expenceFk"] input`, - expenceSelectOptionTwo: `${components.vnAutocomplete}[field="$ctrl.item.expenceFk"] vn-drop-down ul > li:nth-child(2)`, - submitBasicDataButton: `${components.vnSubmit}` + typeAutocomplete: 'vn-autocomplete[ng-model="$ctrl.item.typeFk"]', + intrastatAutocomplete: 'vn-autocomplete[ng-model="$ctrl.item.intrastatFk"]', + nameInput: 'vn-textfield[label="Name"] input', + relevancyInput: 'vn-input-number[ng-model="$ctrl.item.relevancy"] input', + originAutocomplete: 'vn-autocomplete[ng-model="$ctrl.item.originFk"]', + expenseAutocomplete: 'vn-autocomplete[ng-model="$ctrl.item.expenseFk"]', + longNameInput: 'vn-textfield[ng-model="$ctrl.item.longName"] input', + isActiveCheckbox: 'vn-check[label="Active"]', + priceInKgCheckbox: 'vn-check[label="Price in kg"]', + submitBasicDataButton: `button[type=submit]` }, itemTags: { goToItemIndexButton: 'vn-item-descriptor [ui-sref="item.index"]', - tagsButton: `${components.vnMenuItem}[ui-sref="item.card.tags"]`, - firstTagSelect: `vn-item-tags vn-horizontal:nth-child(2) > ${components.vnAutocomplete}[field="itemTag.tagFk"] input`, - firstTagSelectOptionOne: `vn-item-tags vn-horizontal:nth-child(2) > ${components.vnAutocomplete}[field="itemTag.tagFk"] vn-drop-down ul > li:nth-child(1)`, - firstValueInput: `vn-item-tags vn-horizontal:nth-child(2) > vn-textfield[label="Value"] > div > input`, - firstRelevancyInput: `vn-horizontal:nth-child(2) > vn-textfield[label="Relevancy"] > div > input`, - secondTagSelect: `vn-item-tags vn-horizontal:nth-child(3) > ${components.vnAutocomplete}[field="itemTag.tagFk"] input`, - secondTagSelectOptionOne: `vn-item-tags vn-horizontal:nth-child(3) > ${components.vnAutocomplete}[field="itemTag.tagFk"] vn-drop-down ul > li:nth-child(1)`, - secondValueInput: `vn-item-tags vn-horizontal:nth-child(3) > vn-textfield[label="Value"] > div > input`, - secondRelevancyInput: `vn-horizontal:nth-child(3) > vn-textfield[label="Relevancy"] > div > input`, - thirdTagSelect: `vn-item-tags vn-horizontal:nth-child(4) > ${components.vnAutocomplete}[field="itemTag.tagFk"] input`, - thirdTagSelectOptionOne: `vn-item-tags vn-horizontal:nth-child(4) > ${components.vnAutocomplete}[field="itemTag.tagFk"] vn-drop-down ul > li:nth-child(1)`, - thirdValueInput: `vn-item-tags vn-horizontal:nth-child(4) > vn-textfield[label="Value"] > div > input`, - thirdRelevancyInput: `vn-horizontal:nth-child(4) > vn-textfield[label="Relevancy"] > div > input`, - fourthTagSelect: `vn-item-tags vn-horizontal:nth-child(5) > ${components.vnAutocomplete}[field="itemTag.tagFk"] input`, - fourthTagSelectOptionOne: `vn-item-tags vn-horizontal:nth-child(5) > ${components.vnAutocomplete}[field="itemTag.tagFk"] vn-drop-down ul > li:nth-child(1)`, - fourthValueInput: `vn-item-tags vn-horizontal:nth-child(5) > vn-textfield[label="Value"] > div > input`, - fourthRelevancyInput: `vn-horizontal:nth-child(5) > vn-textfield[label="Relevancy"] > div > input`, - fifthRemoveTagButton: `vn-item-tags vn-horizontal:nth-child(6) > ${components.vnIcon}[icon="remove_circle_outline"]`, - fifthTagSelect: `vn-item-tags vn-horizontal:nth-child(6) > ${components.vnAutocomplete}[field="itemTag.tagFk"] input`, - fifthTagSelectOptionFive: `vn-item-tags vn-horizontal:nth-child(6) > ${components.vnAutocomplete}[field="itemTag.tagFk"] vn-drop-down ul > li:nth-child(5)`, - fifthValueInput: `vn-item-tags vn-horizontal:nth-child(6) > vn-textfield[label="Value"] > div > input`, - fifthRelevancyInput: `vn-horizontal:nth-child(6) > vn-textfield[label="Relevancy"] > div > input`, - addItemTagButton: `${components.vnIcon}[icon="add_circle"]`, - submitItemTagsButton: `${components.vnSubmit}` + tagsButton: 'vn-left-menu a[ui-sref="item.card.tags"]', + fourthTagAutocomplete: 'vn-item-tags vn-horizontal:nth-child(4) > vn-autocomplete[ng-model="itemTag.tagFk"]', + fourthValueInput: 'vn-item-tags vn-horizontal:nth-child(4) > vn-textfield[label="Value"] input', + fourthRelevancyInput: 'vn-item-tags vn-horizontal:nth-child(4) > vn-textfield[label="Relevancy"] input', + fourthRemoveTagButton: 'vn-item-tags vn-horizontal:nth-child(4) vn-icon-button[icon="delete"]', + fifthTagAutocomplete: 'vn-item-tags vn-horizontal:nth-child(5) > vn-autocomplete[ng-model="itemTag.tagFk"]', + fifthValueInput: 'vn-item-tags vn-horizontal:nth-child(5) > vn-textfield[label="Value"] input', + fifthRelevancyInput: 'vn-item-tags vn-horizontal:nth-child(5) > vn-textfield[label="Relevancy"] input', + sixthTagAutocomplete: 'vn-item-tags vn-horizontal:nth-child(6) > vn-autocomplete[ng-model="itemTag.tagFk"]', + sixthValueInput: 'vn-item-tags vn-horizontal:nth-child(6) > vn-textfield[label="Value"] input', + sixthRelevancyInput: 'vn-item-tags vn-horizontal:nth-child(6) > vn-textfield[label="Relevancy"] input', + seventhTagAutocomplete: 'vn-item-tags vn-horizontal:nth-child(7) > vn-autocomplete[ng-model="itemTag.tagFk"]', + seventhValueInput: 'vn-item-tags vn-horizontal:nth-child(7) > vn-textfield[label="Value"] input', + seventhRelevancyInput: 'vn-item-tags vn-horizontal:nth-child(7) > vn-textfield[label="Relevancy"] input', + addItemTagButton: 'vn-item-tags vn-icon-button[icon="add_circle"]', + submitItemTagsButton: `vn-item-tags button[type=submit]` }, itemTax: { - taxButton: `${components.vnMenuItem}[ui-sref="item.card.tax"]`, - firstClassSelect: `vn-horizontal:nth-child(2) > ${components.vnAutocomplete}[field="tax.taxClassFk"] input`, - firstClassSelectOptionTwo: `vn-horizontal:nth-child(2) > ${components.vnAutocomplete} vn-drop-down ul > li:nth-child(2)`, - secondClassSelect: `vn-horizontal:nth-child(3) > ${components.vnAutocomplete}[field="tax.taxClassFk"] input`, - secondClassSelectOptionOne: `vn-horizontal:nth-child(3) > ${components.vnAutocomplete} vn-drop-down ul > li:nth-child(1)`, - thirdClassSelect: `vn-horizontal:nth-child(4) > ${components.vnAutocomplete}[field="tax.taxClassFk"] input`, - thirdClassSelectOptionTwo: `vn-horizontal:nth-child(4) > ${components.vnAutocomplete} vn-drop-down ul > li:nth-child(2)`, - submitTaxButton: `${components.vnSubmit}` + undoChangesButton: 'vn-item-tax vn-button-bar > vn-button[label="Undo changes"]', + firstClassAutocomplete: 'vn-item-tax vn-horizontal:nth-child(1) > vn-autocomplete[ng-model="tax.taxClassFk"]', + secondClassAutocomplete: 'vn-item-tax vn-horizontal:nth-child(2) > vn-autocomplete[ng-model="tax.taxClassFk"]', + thirdClassAutocomplete: 'vn-item-tax vn-horizontal:nth-child(3) > vn-autocomplete[ng-model="tax.taxClassFk"]', + submitTaxButton: `vn-item-tax button[type=submit]` }, itemBarcodes: { - barcodeButton: `${components.vnMenuItem}[ui-sref="item.card.itemBarcode"]`, - addBarcodeButton: `${components.vnIcon}[icon="add_circle"]`, - thirdCodeInput: `vn-horizontal:nth-child(4) > ${components.vnTextfield}`, - submitBarcodesButton: `${components.vnSubmit}`, - firstCodeRemoveButton: `vn-horizontal:nth-child(2) > vn-one > ${components.vnIcon}[icon="remove_circle_outline"]` + addBarcodeButton: 'vn-item-barcode vn-icon[icon="add_circle"]', + thirdCodeInput: `vn-item-barcode vn-horizontal:nth-child(3) > vn-textfield input`, + submitBarcodesButton: `vn-item-barcode button[type=submit]`, + firstCodeRemoveButton: 'vn-item-barcode vn-horizontal vn-none vn-icon[icon="delete"]' }, itemNiches: { - nicheButton: `${components.vnMenuItem}[ui-sref="item.card.niche"]`, - addNicheButton: `${components.vnIcon}[icon="add_circle"]`, - firstWarehouseSelect: `${components.vnAutocomplete}[field="itemNiche.warehouseFk"] input`, - firstWarehouseSelectSecondOption: `${components.vnAutocomplete}[field="itemNiche.warehouseFk"] vn-drop-down ul > li:nth-child(2)`, - secondWarehouseSelect: `vn-horizontal:nth-child(3) > ${components.vnAutocomplete}[field="itemNiche.warehouseFk"] input`, - thirdWarehouseSelect: `vn-horizontal:nth-child(4) > ${components.vnAutocomplete}[field="itemNiche.warehouseFk"] input`, - thirdWarehouseSelectFourthOption: `vn-horizontal:nth-child(4) > ${components.vnAutocomplete}[field="itemNiche.warehouseFk"] vn-drop-down ul > li:nth-child(4)`, - secondNicheRemoveButton: `vn-horizontal:nth-child(3) > vn-one > ${components.vnIcon}[icon="remove_circle_outline"]`, - firstCodeInput: `vn-horizontal:nth-child(2) > ${components.vnTextfield}`, - secondCodeInput: `vn-horizontal:nth-child(3) > ${components.vnTextfield}`, - thirdCodeInput: `vn-horizontal:nth-child(4) > ${components.vnTextfield}`, - submitNichesButton: `${components.vnSubmit}` + addNicheButton: 'vn-item-niche vn-icon[icon="add_circle"]', + firstWarehouseAutocomplete: 'vn-item-niche vn-autocomplete[ng-model="niche.warehouseFk"]', + firstCodeInput: 'vn-item-niche vn-horizontal:nth-child(1) > vn-textfield[label="Code"] input', + secondWarehouseAutocomplete: 'vn-item-niche vn-horizontal:nth-child(2) > vn-autocomplete[ng-model="niche.warehouseFk"]', + secondCodeInput: 'vn-item-niche vn-horizontal:nth-child(2) > vn-textfield[label="Code"] input', + secondNicheRemoveButton: 'vn-item-niche vn-horizontal:nth-child(2) > vn-none > vn-icon-button[icon="delete"]', + thirdWarehouseAutocomplete: 'vn-item-niche vn-horizontal:nth-child(3) > vn-autocomplete[ng-model="niche.warehouseFk"]', + thirdCodeInput: 'vn-item-niche vn-horizontal:nth-child(3) > vn-textfield[label="Code"] input', + submitNichesButton: `vn-item-niche button[type=submit]` }, itemBotanical: { - botanicalButton: `${components.vnMenuItem}[ui-sref="item.card.botanical"]`, - botanicalInput: `vn-horizontal:nth-child(2) > ${components.vnTextfield}`, - genusSelect: `${components.vnAutocomplete}[field="$ctrl.botanical.genusFk"] input`, - genusSelectOptionOne: `${components.vnAutocomplete}[field="$ctrl.botanical.genusFk"] vn-drop-down ul > li:nth-child(1)`, - genusSelectOptionTwo: `${components.vnAutocomplete}[field="$ctrl.botanical.genusFk"] vn-drop-down ul > li:nth-child(2)`, - speciesSelect: `${components.vnAutocomplete}[field="$ctrl.botanical.specieFk"] input`, - speciesSelectOptionOne: `${components.vnAutocomplete}[field="$ctrl.botanical.specieFk"] vn-drop-down ul > li:nth-child(1)`, - speciesSelectOptionTwo: `${components.vnAutocomplete}[field="$ctrl.botanical.specieFk"] vn-drop-down ul > li:nth-child(2)`, - submitBotanicalButton: `${components.vnSubmit}` + botanicalInput: `vn-item-botanical vn-horizontal:nth-child(1) > vn-textfield input`, + genusAutocomplete: 'vn-item-botanical vn-autocomplete[ng-model="$ctrl.botanical.genusFk"]', + speciesAutocomplete: 'vn-item-botanical vn-autocomplete[ng-model="$ctrl.botanical.specieFk"]', + submitBotanicalButton: `vn-item-botanical button[type=submit]` }, itemSummary: { - basicData: `${components.vnItemSummary} > vn-horizontal:nth-child(1) > vn-one:nth-child(2) > vn-vertical > p:nth-child(2)`, - vat: `${components.vnItemSummary} > vn-horizontal:nth-child(1) > vn-one:nth-child(3) > vn-vertical > p`, - tags: `${components.vnItemSummary} > vn-horizontal:nth-child(2) > vn-one:nth-child(1) > p`, - niche: `${components.vnItemSummary} > vn-horizontal:nth-child(2) > vn-one:nth-child(2) > vn-vertical > p:nth-child(2)`, - botanical: `${components.vnItemSummary} > vn-horizontal:nth-child(2) > vn-one:nth-child(3) > vn-vertical > p`, - barcode: `${components.vnItemSummary} > vn-horizontal:nth-child(2) > vn-one:nth-child(4) > vn-vertical > p` + basicData: 'vn-item-summary [name="basicData"]', + vat: 'vn-item-summary [name="tax"]', + tags: 'vn-item-summary [name="tags"]', + niche: 'vn-item-summary [name="niche"]', + botanical: 'vn-item-summary [name="botanical"]', + barcode: 'vn-item-summary [name="barcode"]' + }, + itemDiary: { + secondTicketId: 'vn-item-diary vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(2) > span', + firstBalance: 'vn-item-diary vn-tbody > vn-tr:nth-child(1) > vn-td.balance', + fourthBalance: 'vn-item-diary vn-tbody > vn-tr:nth-child(4) > vn-td.balance', + warehouseAutocomplete: 'vn-item-diary vn-autocomplete[ng-model="$ctrl.warehouseFk"]', + }, + itemLog: { + anyLineCreated: 'vn-item-log > vn-log vn-tbody > vn-tr', + fifthLineCreatedProperty: 'vn-item-log > vn-log vn-tbody > vn-tr:nth-child(5) > vn-td > vn-one:nth-child(3) > div span:nth-child(3)', + }, + ticketSummary: { + header: 'vn-ticket-summary > vn-card > h5', + state: 'vn-ticket-summary vn-label-value[label="State"] > section > span', + route: 'vn-ticket-summary vn-label-value[label="Route"] > section > span > a', + total: 'vn-ticket-summary vn-one.taxes > p:nth-child(3) > strong', + sale: 'vn-ticket-summary [name="sales"] vn-table > div > vn-tbody > vn-tr', + firstSaleItemId: 'vn-ticket-summary [name="sales"] vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(2) > span', + firstSaleDescriptorImage: '.vn-popover.shown vn-item-descriptor img', + itemDescriptorPopover: '.vn-popover.shown vn-item-descriptor', + itemDescriptorPopoverItemDiaryButton: 'vn-item-descriptor a[href="#!/item/2/diary?warehouseFk=5&ticketFk=20"]', + popoverDiaryButton: '.vn-popover.shown vn-item-descriptor vn-icon[icon="icon-transaction"]', + firstSaleQuantity: 'vn-ticket-summary [name="sales"] vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(3)', + firstSaleDiscount: 'vn-ticket-summary [name="sales"] vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(6)', + invoiceOutRef: 'vn-ticket-summary > vn-card > vn-horizontal > vn-one:nth-child(1) > vn-label-value:nth-child(6) > section > span', + setOk: 'vn-ticket-summary vn-button[label="SET OK"] > button' + }, + ticketsIndex: { + openAdvancedSearchButton: 'vn-searchbar .append vn-icon[icon="arrow_drop_down"]', + advancedSearchInvoiceOut: 'vn-ticket-search-panel vn-textfield[ng-model="filter.refFk"] input', + newTicketButton: 'vn-ticket-index > a', + searchResult: 'vn-ticket-index vn-card > vn-table > div > vn-tbody > a.vn-tr', + searchWeeklyResult: 'vn-ticket-weekly-index vn-table vn-tbody > vn-tr', + searchResultDate: 'vn-ticket-index vn-table vn-tbody > a:nth-child(1) > vn-td:nth-child(5)', + searchTicketInput: `vn-searchbar input`, + searchWeeklyTicketInput: `vn-searchbar input`, + searchWeeklyClearInput: 'vn-searchbar vn-icon[icon=clear]', + advancedSearchButton: 'vn-ticket-search-panel button[type=submit]', + searchButton: 'vn-searchbar vn-icon[icon="search"]', + searchWeeklyButton: 'vn-searchbar vn-icon[icon="search"]', + moreMenu: 'vn-ticket-index vn-icon-menu[icon=more_vert]', + menuWeeklyTickets: 'vn-left-menu [ui-sref="ticket.weekly.index"]', + sixthWeeklyTicket: 'vn-ticket-weekly-index vn-table vn-tr:nth-child(6) vn-autocomplete[ng-model="weekly.weekDay"] input', + weeklyTicket: 'vn-ticket-weekly-index vn-table > div > vn-tbody > vn-tr', + firstWeeklyTicketDeleteIcon: 'vn-ticket-weekly-index vn-tr:nth-child(1) vn-icon-button[icon="delete"]', + acceptDeleteTurn: '.vn-confirm.shown button[response="accept"]' + }, + createTicketView: { + clientAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.clientFk"]', + addressAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.addressFk"]', + deliveryDateInput: 'vn-ticket-create vn-date-picker[ng-model="$ctrl.landed"]', + warehouseAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.warehouseFk"]', + agencyAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.ticket.agencyModeFk"]', + createButton: `button[type=submit]` + }, + ticketDescriptor: { + idLabelValue: 'vn-ticket-descriptor vn-label-value[label="Id"]', + stateLabelValue: 'vn-ticket-descriptor vn-label-value[label="State"]', + goBackToModuleIndexButton: 'vn-ticket-descriptor a[ui-sref="ticket.index"]', + moreMenu: 'vn-ticket-descriptor vn-icon-menu[icon=more_vert]', + moreMenuAddStowaway: '.vn-drop-down.shown li[name="Add stowaway"]', + moreMenuDeleteStowawayButton: '.vn-drop-down.shown li[name="Delete stowaway"]', + moreMenuAddToTurn: '.vn-drop-down.shown li[name="Add turn"]', + moreMenuDeleteTicket: '.vn-drop-down.shown li[name="Delete ticket"]', + moreMenuMakeInvoice: '.vn-drop-down.shown li[name="Make invoice"]', + moreMenuChangeShippedHour: '.vn-drop-down.shown li[name="Change shipped hour"]', + changeShippedHourDialog: '.vn-dialog.shown', + changeShippedHourInput: '.vn-dialog.shown [ng-model="$ctrl.newShipped"]', + addStowawayDialogFirstTicket: '.vn-dialog.shown vn-table vn-tbody vn-tr', + shipButton: 'vn-ticket-descriptor vn-icon[icon="icon-stowaway"]', + thursdayButton: '.vn-popup.shown vn-tool-bar > vn-button:nth-child(4)', + saturdayButton: '.vn-popup.shown vn-tool-bar > vn-button:nth-child(6)', + acceptDeleteButton: '.vn-dialog.shown button[response="accept"]', + acceptChangeHourButton: '.vn-dialog.shown button[response="accept"]', + descriptorDeliveryDate: 'vn-ticket-descriptor > div > div.body > div.attributes > vn-label-value:nth-child(6) > section > span', + acceptInvoiceOutButton: '.vn-confirm.shown button[response="accept"]', + acceptDeleteStowawayButton: '.vn-dialog.shown button[response="accept"]' + }, + ticketNotes: { + firstNoteRemoveButton: 'vn-icon[icon="delete"]', + addNoteButton: 'vn-icon[icon="add_circle"]', + firstNoteTypeAutocomplete: 'vn-autocomplete[ng-model="observation.observationTypeFk"]', + firstDescriptionInput: 'vn-textfield[label="Description"] input', + submitNotesButton: `button[type=submit]` + }, + ticketExpedition: { + expeditionButton: 'vn-left-menu a[ui-sref="ticket.card.expedition"]', + secondExpeditionRemoveButton: 'vn-ticket-expedition vn-table div > vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(1) > vn-icon-button[icon="delete"]', + acceptDeleteRowButton: '.vn-confirm.shown button[response=accept]', + expeditionRow: 'vn-ticket-expedition vn-table vn-tbody > vn-tr' + }, + ticketPackages: { + packagesButton: 'vn-left-menu a[ui-sref="ticket.card.package"]', + firstPackageAutocomplete: 'vn-autocomplete[label="Package"]', + firstQuantityInput: 'vn-input-number[ng-model="package.quantity"] input', + firstRemovePackageButton: 'vn-icon-button[vn-tooltip="Remove package"]', + addPackageButton: 'vn-icon-button[vn-tooltip="Add package"]', + clearPackageAutocompleteButton: 'vn-autocomplete[label="Package"] .icons > vn-icon[icon=clear]', + savePackagesButton: `button[type=submit]` + }, + ticketSales: { + saleButton: 'vn-left-menu a[ui-sref="ticket.card.sale"]', + saleLine: 'vn-table div > vn-tbody > vn-tr', + saleDescriptorPopover: '.vn-popover.shown vn-item-descriptor', + saleDescriptorPopoverSummaryButton: '.vn-popover.shown vn-item-descriptor a[ui-sref="item.card.summary({id: $ctrl.item.id})"]', + descriptorItemDiaryButton: 'vn-item-descriptor .quicklinks.ng-scope > vn-horizontal > a > vn-icon > i', + newItemFromCatalogButton: 'vn-ticket-sale vn-float-button[icon="add"]', + newItemButton: 'vn-ticket-sale > vn-vertical > vn-card > vn-vertical > vn-one > vn-icon-button > button > vn-icon > i', + moreMenu: 'vn-ticket-sale vn-tool-bar > vn-button-menu[vn-id="more-button"] > div > button', + moreMenuCreateClaim: '.vn-drop-down.shown li[name="Add claim"]', + moreMenuReserve: '.vn-drop-down.shown li[name="Mark as reserved"]', + moreMenuUnmarkReseved: '.vn-drop-down.shown li[name="Unmark as reserved"]', + moreMenuUpdateDiscount: '.vn-drop-down.shown li[name="Update discount"]', + moreMenuUpdateDiscountInput: '.vn-dialog.shown form vn-ticket-sale-edit-discount vn-input-number[ng-model="$ctrl.newDiscount"] input', + transferQuantityInput: '.vn-popover.shown vn-table > div > vn-tbody > vn-tr > vn-td-editable > span > text', + transferQuantityCell: '.vn-popover.shown vn-table > div > vn-tbody > vn-tr > vn-td-editable', + firstSaleClaimIcon: 'vn-ticket-sale vn-table vn-tbody > vn-tr:nth-child(1) vn-icon[icon="icon-claims"]', + firstSaleDescriptorImage: '.vn-popover.shown vn-item-descriptor img', + firstSaleText: 'vn-table div > vn-tbody > vn-tr:nth-child(1)', + firstSaleThumbnailImage: 'vn-ticket-sale:nth-child(1) vn-tr:nth-child(1) vn-td:nth-child(3) > img', + firstSaleZoomedImage: 'body > div > div > img', + firstSaleQuantity: 'vn-input-number[ng-model="sale.quantity"]:nth-child(1) input', + firstSaleQuantityCell: 'vn-ticket-sale vn-tr:nth-child(1) > vn-td-editable:nth-child(5)', + firstSaleQuantityClearInput: 'vn-textfield[ng-model="sale.quantity"] div.suffix > i', + firstSaleIdAutocomplete: 'vn-ticket-sale vn-table vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(4) > vn-autocomplete', + idAutocompleteFirstResult: '.vn-drop-down.shown li', + firstSalePrice: 'vn-ticket-sale vn-table vn-tr:nth-child(1) > vn-td:nth-child(7) > span', + firstSalePriceInput: '.vn-popover.shown vn-input-number input', + firstSaleDiscount: 'vn-ticket-sale vn-table vn-tr:nth-child(1) > vn-td:nth-child(8) > span', + firstSaleDiscountInput: 'vn-ticket-sale:nth-child(1) vn-ticket-sale-edit-discount vn-input-number input', + firstSaleImport: 'vn-ticket-sale:nth-child(1) vn-td:nth-child(9)', + firstSaleReservedIcon: 'vn-ticket-sale vn-tr:nth-child(1) > vn-td:nth-child(2) > vn-icon:nth-child(3)', + firstSaleColour: 'vn-ticket-sale vn-tr:nth-child(1) vn-fetched-tags section', + firstSaleLength: 'vn-ticket-sale vn-tr:nth-child(1) vn-td-editable:nth-child(6) section:nth-child(3)', + firstSaleCheckbox: 'vn-ticket-sale vn-tr:nth-child(1) vn-check[ng-model="sale.checked"]', + secondSaleColour: 'vn-tr:nth-child(2) vn-fetched-tags section', + secondSalePrice: 'vn-ticket-sale vn-tr:nth-child(2) vn-td:nth-child(7) > span', + secondSaleDiscount: 'vn-ticket-sale vn-tr:nth-child(2) vn-td:nth-child(8)', + secondSaleImport: 'vn-ticket-sale vn-tr:nth-child(2) vn-td:nth-child(9)', + secondSaleText: 'vn-table div > vn-tbody > vn-tr:nth-child(2)', + secondSaleId: 'vn-ticket-sale:nth-child(2) vn-td-editable:nth-child(4) text > span', + secondSaleIdCell: 'vn-ticket-sale vn-tr:nth-child(2) > vn-td-editable:nth-child(4)', + secondSaleIdInput: 'vn-ticket-sale vn-table vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(4) > vn-autocomplete input', + secondSaleIdAutocomplete: 'vn-ticket-sale vn-table vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(4) > vn-autocomplete', + secondSaleQuantity: 'vn-ticket-sale vn-table vn-tr:nth-child(2) vn-input-number input', + secondSaleConceptCell: 'vn-ticket-sale vn-table vn-tbody > vn-tr:nth-child(2) > vn-td-editable:nth-child(6) > div', + secondSaleConceptInput: 'vn-ticket-sale vn-table vn-tr:nth-child(2) > vn-td-editable.ng-isolate-scope.selected vn-textfield input', + totalImport: 'vn-ticket-sale > vn-vertical > vn-card > vn-vertical > vn-horizontal > vn-one > p:nth-child(3) > strong', + selectAllSalesCheckbox: 'vn-ticket-sale vn-thead vn-check', + secondSaleCheckbox: 'vn-ticket-sale vn-tr:nth-child(2) vn-check[ng-model="sale.checked"]', + thirdSaleCheckbox: 'vn-ticket-sale vn-tr:nth-child(3) vn-check[ng-model="sale.checked"]', + deleteSaleButton: 'vn-ticket-sale vn-tool-bar > vn-button[icon="delete"]', + transferSaleButton: 'vn-ticket-sale vn-tool-bar > vn-button[icon="call_split"]', + moveToTicketInput: '.vn-popover.shown vn-textfield[ng-model="$ctrl.transfer.ticketId"] input', + moveToTicketInputClearButton: '.vn-popover.shown i[title="Clear"]', + moveToTicketButton: '.vn-popover.shown vn-icon[icon="arrow_forward_ios"]', + moveToNewTicketButton: '.vn-popover.shown vn-button[label="New ticket"]', + acceptDeleteLineButton: '.vn-confirm.shown button[response=accept]', + acceptDeleteTicketButton: '.vn-confirm.shown button[response=accept]', + stateMenuButton: 'vn-ticket-sale vn-tool-bar > vn-button-menu[label="State"]' + }, + ticketTracking: { + trackingButton: 'vn-left-menu a[ui-sref="ticket.card.tracking.index"]', + createStateButton: `vn-float-button`, + stateAutocomplete: 'vn-ticket-tracking-edit vn-autocomplete[ng-model="$ctrl.stateFk"]', + saveButton: `button[type=submit]`, + cancelButton: 'vn-ticket-tracking-edit vn-button[ui-sref="ticket.card.tracking.index"]' + }, + ticketBasicData: { + basicDataButton: 'vn-left-menu a[ui-sref="ticket.card.basicData.stepOne"]', + clientAutocomplete: 'vn-autocomplete[ng-model="$ctrl.clientFk"]', + addressAutocomplete: 'vn-autocomplete[ng-model="$ctrl.ticket.addressFk"]', + agencyAutocomplete: 'vn-autocomplete[ng-model="$ctrl.agencyModeId"]', + zoneAutocomplete: 'vn-autocomplete[ng-model="$ctrl.zoneId"]', + nextStepButton: 'vn-step-control .buttons > section:last-child vn-button', + finalizeButton: 'vn-step-control .buttons > section:last-child button[type=submit]', + stepTwoTotalPriceDif: 'vn-ticket-basic-data-step-two vn-tfoot > vn-tr > :nth-child(6)', + chargesReasonAutocomplete: 'vn-autocomplete[ng-model="$ctrl.ticket.option"]', + }, + ticketComponents: { + base: 'vn-ticket-components [name="base-sum"]' + }, + ticketRequests: { + addRequestButton: 'vn-ticket-request-index > a > vn-float-button > button', + request: 'vn-ticket-request-index vn-table vn-tr', + descriptionInput: 'vn-ticket-request-create > form > div > vn-card > vn-horizontal:nth-child(1) > vn-textfield input', + atenderAutocomplete: 'vn-ticket-request-create vn-autocomplete[ng-model="$ctrl.ticketRequest.attenderFk"]', + quantityInput: 'vn-ticket-request-create vn-input-number input[name=quantity]', + priceInput: 'vn-ticket-request-create vn-input-number input[name=price]', + firstRemoveRequestButton: 'vn-ticket-request-index vn-icon[icon="delete"]:nth-child(1)', + saveButton: 'vn-ticket-request-create button[type=submit]', + firstDescription: 'vn-ticket-request-index vn-table vn-tr:nth-child(1) > vn-td:nth-child(2)', + + }, + ticketLog: { + logButton: 'vn-left-menu a[ui-sref="ticket.card.log"]', + changedBy: 'vn-ticket-log > vn-log vn-tr:nth-child(1) > vn-td:nth-child(2) > span', + actionTaken: 'vn-ticket-log > vn-log vn-td:nth-child(1) > div > div:nth-child(3) > span.value', + id: 'vn-ticket-log > vn-log vn-td.before > vn-one:nth-child(1) > div > span.value' + }, + ticketService: { + addServiceButton: 'vn-ticket-service vn-icon-button[vn-tooltip="Add service"] > button', + firstAddServiceTypeButton: 'vn-ticket-service vn-icon-button[vn-tooltip="New service type"]', + firstServiceTypeAutocomplete: 'vn-ticket-service vn-autocomplete[ng-model="service.ticketServiceTypeFk"]', + firstQuantityInput: 'vn-ticket-service vn-input-number[label="Quantity"] input', + firstPriceInput: 'vn-ticket-service vn-input-number[label="Price"] input', + firstVatTypeAutocomplete: 'vn-ticket-service vn-autocomplete[label="Tax class"]', + fistDeleteServiceButton: 'vn-ticket-service form vn-horizontal:nth-child(1) vn-icon-button[icon="delete"]', + newServiceTypeNameInput: '.vn-dialog.shown vn-textfield[ng-model="$ctrl.newServiceType.name"] input', + newServiceTypeExpenseAutocomplete: '.vn-dialog.shown vn-autocomplete[ng-model="$ctrl.newServiceType.expenseFk"]', + serviceLine: 'vn-ticket-service > form > vn-card > vn-one:nth-child(2) > vn-horizontal', + saveServiceButton: `button[type=submit]`, + saveServiceTypeButton: '.vn-dialog.shown tpl-buttons > button' + }, + createStateView: { + stateAutocomplete: 'vn-autocomplete[ng-model="$ctrl.stateFk"]', + workerAutocomplete: 'vn-autocomplete[ng-model="$ctrl.workerFk"]', + clearStateInputButton: 'vn-autocomplete[ng-model="$ctrl.stateFk"] .icons > vn-icon[icon=clear]', + saveStateButton: `button[type=submit]` + }, + claimsIndex: { + searchClaimInput: `vn-searchbar input`, + searchResult: 'vn-claim-index vn-card > vn-table > div > vn-tbody > a', + searchButton: 'vn-searchbar vn-icon[icon="search"]' + }, + claimDescriptor: { + moreMenu: 'vn-claim-descriptor vn-icon-menu[icon=more_vert]', + moreMenuDeleteClaim: '.vn-drop-down.shown li[name="Delete claim"]', + acceptDeleteClaim: '.vn-confirm.shown button[response="accept"]' + }, + claimSummary: { + header: 'vn-claim-summary > vn-card > h5', + state: 'vn-claim-summary vn-label-value[label="State"] > section > span', + observation: 'vn-claim-summary vn-textarea[ng-model="$ctrl.summary.claim.observation"] textarea', + firstSaleItemId: 'vn-claim-summary vn-horizontal > vn-auto:nth-child(4) vn-table > div > vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(1) > span', + firstSaleDescriptorImage: '.vn-popover.shown vn-item-descriptor img', + itemDescriptorPopover: '.vn-popover.shown vn-item-descriptor', + itemDescriptorPopoverItemDiaryButton: '.vn-popover.shown vn-item-descriptor a[href="#!/item/2/diary"]', + firstDevelopmentWorker: 'vn-claim-summary vn-horizontal > vn-auto:nth-child(5) vn-table > div > vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(4) > span', + firstDevelopmentWorkerGoToClientButton: '.vn-popover.shown vn-worker-descriptor vn-quick-links > a[href="#!/client/21/summary"]', + firstActionTicketId: 'vn-claim-summary > vn-card > vn-horizontal > vn-auto:nth-child(6) vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(2) > span', + firstActionTicketDescriptor: '.vn-popover.shown vn-ticket-descriptor' + }, + claimBasicData: { + claimStateAutocomplete: 'vn-claim-basic-data vn-autocomplete[ng-model="$ctrl.claim.claimStateFk"]', + responsabilityInputRange: 'vn-range', + observationInput: 'vn-textarea[ng-model="$ctrl.claim.observation"] textarea', + saveButton: `button[type=submit]` + }, + claimDetail: { + secondItemDiscount: 'vn-claim-detail > vn-vertical > vn-card > vn-vertical > vn-table > div > vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(6) > span', + discountInput: '.vn-popover.shown vn-input-number[ng-model="$ctrl.newDiscount"] input', + discoutPopoverMana: '.vn-popover.shown .content > div > vn-horizontal > h5', + addItemButton: 'vn-claim-detail a vn-float-button', + firstClaimableSaleFromTicket: '.vn-dialog.shown vn-tbody > vn-tr', + claimDetailLine: 'vn-claim-detail > vn-vertical > vn-card > vn-vertical > vn-table > div > vn-tbody > vn-tr', + firstItemQuantityInput: 'vn-claim-detail vn-tr:nth-child(1) vn-input-number[ng-model="saleClaimed.quantity"] input', + totalClaimed: 'vn-claim-detail > vn-vertical > vn-card > vn-vertical > vn-horizontal > div > vn-label-value:nth-child(2) > section > span', + secondItemDeleteButton: 'vn-claim-detail > vn-vertical > vn-card > vn-vertical > vn-table > div > vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(8) > vn-icon-button > button > vn-icon > i' + }, + claimDevelopment: { + addDevelopmentButton: 'vn-claim-development > vn-vertical > vn-card > vn-vertical > vn-one > vn-icon-button > button > vn-icon', + firstDeleteDevelopmentButton: 'vn-claim-development > vn-vertical > vn-card > vn-vertical > form > vn-horizontal:nth-child(2) > vn-icon-button > button > vn-icon', + firstClaimReasonAutocomplete: 'vn-claim-development vn-horizontal:nth-child(1) vn-autocomplete[ng-model="claimDevelopment.claimReasonFk"]', + firstClaimResultAutocomplete: 'vn-claim-development vn-horizontal:nth-child(1) vn-autocomplete[ng-model="claimDevelopment.claimResultFk"]', + firstClaimResponsibleAutocomplete: 'vn-claim-development vn-horizontal:nth-child(1) vn-autocomplete[ng-model="claimDevelopment.claimResponsibleFk"]', + firstClaimWorkerAutocomplete: 'vn-claim-development vn-horizontal:nth-child(1) vn-autocomplete[ng-model="claimDevelopment.workerFk"]', + firstClaimRedeliveryAutocomplete: 'vn-claim-development vn-horizontal:nth-child(1) vn-autocomplete[ng-model="claimDevelopment.claimRedeliveryFk"]', + secondClaimReasonAutocomplete: 'vn-claim-development vn-horizontal:nth-child(2) vn-autocomplete[ng-model="claimDevelopment.claimReasonFk"]', + secondClaimResultAutocomplete: 'vn-claim-development vn-horizontal:nth-child(2) vn-autocomplete[ng-model="claimDevelopment.claimResultFk"]', + secondClaimResponsibleAutocomplete: 'vn-claim-development vn-horizontal:nth-child(2) vn-autocomplete[ng-model="claimDevelopment.claimResponsibleFk"]', + secondClaimWorkerAutocomplete: 'vn-claim-development vn-horizontal:nth-child(2) vn-autocomplete[ng-model="claimDevelopment.workerFk"]', + secondClaimRedeliveryAutocomplete: 'vn-claim-development vn-horizontal:nth-child(2) vn-autocomplete[ng-model="claimDevelopment.claimRedeliveryFk"]', + saveDevelopmentButton: `button[type=submit]` + }, + claimAction: { + importClaimButton: 'vn-claim-action vn-button[label="Import claim"]', + importTicketButton: 'vn-claim-action vn-button[label="Import ticket"]', + secondImportableTicket: '.vn-popover.shown .content > div > vn-table > div > vn-tbody > vn-tr:nth-child(2)', + firstLineDestination: 'vn-claim-action vn-tr:nth-child(1) vn-autocomplete[ng-model="saleClaimed.claimDestinationFk"]', + secondLineDestination: 'vn-claim-action vn-tr:nth-child(2) vn-autocomplete[ng-model="saleClaimed.claimDestinationFk"]', + firstDeleteLine: 'vn-claim-action vn-tr:nth-child(1) vn-icon-button[icon="delete"]', + isPaidWithManaCheckbox: 'vn-check[ng-model="$ctrl.claim.isChargedToMana"]' + }, + ordersIndex: { + searchResult: 'vn-order-index vn-card > vn-table > div > vn-tbody > a.vn-tr', + searchResultDate: 'vn-order-index vn-table vn-tbody > a:nth-child(1) > vn-td:nth-child(4)', + searchResultAddress: 'vn-order-index vn-table vn-tbody > a:nth-child(1) > vn-td:nth-child(6)', + searchOrderInput: `vn-order-index vn-textfield input`, + searchButton: 'vn-searchbar vn-icon[icon="search"]', + createOrderButton: `vn-float-button`, + }, + orderDescriptor: { + returnToModuleIndexButton: 'vn-order-descriptor a[ui-sref="order.index"]', + acceptNavigationButton: '.vn-confirm.shown button[response=accept]' + }, + createOrderView: { + clientAutocomplete: 'vn-autocomplete[label="Client"]', + addressAutocomplete: 'vn-autocomplete[label="Address"]', + agencyAutocomplete: 'vn-autocomplete[label="Agency"]', + landedDatePicker: 'vn-date-picker[label="Landed"]', + createButton: `button[type=submit]`, + cancelButton: 'vn-button[href="#!/client/index"]' + }, + orderCatalog: { + orderByAutocomplete: 'vn-autocomplete[label="Order by"]', + plantRealmButton: 'vn-order-catalog > vn-side-menu vn-icon[icon="icon-plant"]', + typeAutocomplete: 'vn-autocomplete[data="$ctrl.itemTypes"]', + itemIdInput: 'vn-catalog-filter vn-textfield[ng-model="$ctrl.itemFk"] input', + itemTagValueInput: 'vn-catalog-filter vn-textfield[ng-model="$ctrl.value"] input', + openTagSearch: 'vn-catalog-filter > div > vn-vertical > vn-textfield[ng-model="$ctrl.value"] .append i', + tagAutocomplete: 'vn-order-catalog-search-panel vn-autocomplete[ng-model="filter.tagFk"]', + tagValueInput: 'vn-order-catalog-search-panel vn-textfield[ng-model="filter.value"] input', + searchTagButton: 'vn-order-catalog-search-panel button[type=submit]', + thirdFilterRemoveButton: 'vn-catalog-filter .chips > vn-chip:nth-child(3) vn-icon[icon=cancel]', + fourthFilterRemoveButton: 'vn-catalog-filter .chips > vn-chip:nth-child(4) vn-icon[icon=cancel]', + }, + orderBasicData: { + clientAutocomplete: 'vn-autocomplete[label="Client"]', + addressAutocomplete: 'vn-autocomplete[label="Address"]', + agencyAutocomplete: 'vn-autocomplete[label="Agency"]', + observationInput: 'vn-textarea[label="Observation"] textarea', + saveButton: `button[type=submit]`, + acceptButton: '.vn-confirm.shown button[response="accept"]' + }, + orderLine: { + orderSubtotal: 'vn-order-line .header :first-child', + firstLineDeleteButton: 'vn-order-line vn-tbody > vn-tr:nth-child(1) vn-icon[icon="delete"]', + confirmOrder: 'vn-order-line vn-float-button', + confirmButton: '.vn-confirm.shown button[response="accept"]', + }, + routeIndex: { + addNewRouteButton: 'vn-route-index > a[ui-sref="route.create"]' + }, + createRouteView: { + workerAutocomplete: 'vn-route-create vn-autocomplete[ng-model="$ctrl.route.workerFk"]', + createdDatePicker: 'vn-route-create vn-date-picker[ng-model="$ctrl.route.created"]', + vehicleAutoComplete: 'vn-route-create vn-autocomplete[ng-model="$ctrl.route.vehicleFk"]', + agencyAutoComplete: 'vn-route-create vn-autocomplete[ng-model="$ctrl.route.agencyModeFk"]', + descriptionInput: 'vn-route-create vn-textfield[ng-model="$ctrl.route.description"] input', + submitButton: 'vn-route-create button[type=submit]' + }, + routeDescriptor: { + volume: 'vn-route-descriptor vn-label-value[label="Volume"] > section > span' + }, + routeSummary: { + routeId: 'vn-route-summary > vn-card > vn-horizontal > vn-one:nth-child(1) > vn-label-value:nth-child(1) > section > span' + }, + routeBasicData: { + workerAutoComplete: 'vn-route-basic-data vn-autocomplete[ng-model="$ctrl.route.workerFk"]', + vehicleAutoComplete: 'vn-route-basic-data vn-autocomplete[ng-model="$ctrl.route.vehicleFk"]', + agencyAutoComplete: 'vn-route-basic-data vn-autocomplete[ng-model="$ctrl.route.agencyModeFk"]', + kmStartInput: 'vn-route-basic-data vn-input-number[ng-model="$ctrl.route.kmStart"] input', + kmEndInput: 'vn-route-basic-data vn-input-number[ng-model="$ctrl.route.kmEnd"] input', + createdDateInput: 'vn-route-basic-data vn-date-picker[ng-model="$ctrl.route.created"]', + startedHourInput: 'vn-route-basic-data vn-input-time[ng-model="$ctrl.route.started"] input', + finishedHourInput: 'vn-route-basic-data vn-input-time[ng-model="$ctrl.route.finished"] input', + saveButton: 'vn-route-basic-data button[type=submit]' + }, + routeTickets: { + firstTicketPriority: 'vn-route-tickets vn-tr:nth-child(1) vn-textfield[ng-model="ticket.priority"] input', + secondTicketPriority: 'vn-route-tickets vn-tr:nth-child(2) vn-textfield[ng-model="ticket.priority"] input', + thirdTicketPriority: 'vn-route-tickets vn-tr:nth-child(3) vn-textfield[ng-model="ticket.priority"] input', + fourthTicketPriority: 'vn-route-tickets vn-tr:nth-child(4) vn-textfield[ng-model="ticket.priority"] input', + eleventhTicketPriority: 'vn-route-tickets vn-tr:nth-child(11) vn-textfield[ng-model="ticket.priority"] input', + firstTicketCheckbox: 'vn-route-tickets vn-tr:nth-child(1) vn-check', + buscamanButton: 'vn-route-tickets vn-button[icon="icon-buscaman"]', + firstTicketDeleteButton: 'vn-route-tickets vn-tr:nth-child(1) vn-icon[icon="delete"]', + confirmButton: '.vn-confirm.shown button[response="accept"]' + }, + workerPbx: { + extensionInput: 'vn-worker-pbx vn-textfield[ng-model="$ctrl.worker.sip.extension"] input', + saveButton: 'vn-worker-pbx button[type=submit]' + }, + workerTimeControl: { + timeDialogInput: '.vn-dialog.shown [ng-model="$ctrl.newTime"]', + mondayAddTimeButton: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(2) > vn-td:nth-child(1) > vn-icon-button', + tuesdayAddTimeButton: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(2) > vn-td:nth-child(2) > vn-icon-button', + wednesdayAddTimeButton: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(2) > vn-td:nth-child(3) > vn-icon-button', + thursdayAddTimeButton: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(2) > vn-td:nth-child(4) > vn-icon-button', + fridayAddTimeButton: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(2) > vn-td:nth-child(5) > vn-icon-button', + saturdayAddTimeButton: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(2) > vn-td:nth-child(6) > vn-icon-button', + sundayAddTimeButton: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(2) > vn-td:nth-child(7) > vn-icon-button', + confirmButton: '.vn-dialog.shown tpl-buttons > button', + firstEntryOfMonday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(1) > section:nth-child(1) > vn-chip > div', + firstEntryOfTuesday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(2) > section:nth-child(1) > vn-chip > div', + firstEntryOfWednesday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(3) > section:nth-child(1) > vn-chip > div', + firstEntryOfThursday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(4) > section:nth-child(1) > vn-chip > div', + firstEntryOfFriday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(5) > section:nth-child(1) > vn-chip > div', + firstEntryOfSaturday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(6) > section:nth-child(1) > vn-chip > div', + firstEntryOfSunday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(7) > section:nth-child(1) > vn-chip > div', + secondEntryOfMonday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(1) > section:nth-child(2) > vn-chip > div', + secondEntryOfTuesday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(2) > section:nth-child(2) > vn-chip > div', + secondEntryOfWednesday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(3) > section:nth-child(2) > vn-chip > div', + secondEntryOfThursday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(4) > section:nth-child(2) > vn-chip > div', + secondEntryOfFriday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(5) > section:nth-child(2) > vn-chip > div', + secondEntryOfSaturday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(6) > section:nth-child(2) > vn-chip > div', + secondEntryOfSunday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(7) > section:nth-child(2) > vn-chip > div', + thirdEntryOfMonday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(1) > section:nth-child(3) > vn-chip > div', + thirdEntryOfMondayDelete: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(1) > section:nth-child(3) > vn-chip > vn-icon[icon="cancel"]', + thirdEntryOfTuesday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(2) > section:nth-child(3) > vn-chip > div', + thirdEntryOfWednesday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(3) > section:nth-child(3) > vn-chip > div', + thirdEntryOfThursday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(4) > section:nth-child(3) > vn-chip > div', + thirdEntryOfFriday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(5) > section:nth-child(3) > vn-chip > div', + thirdEntryOfSaturday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(6) > section:nth-child(3) > vn-chip > div', + thirdEntryOfSunday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(7) > section:nth-child(3) > vn-chip > div', + fourthEntryOfMonday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(1) > section:nth-child(4) > vn-chip > div', + fourthEntryOfTuesday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(2) > section:nth-child(4) > vn-chip > div', + fourthEntryOfWednesday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(3) > section:nth-child(4) > vn-chip > div', + fourthEntryOfThursday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(4) > section:nth-child(4) > vn-chip > div', + fourthEntryOfFriday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(5) > section:nth-child(4) > vn-chip > div', + fourthEntryOfSaturday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(6) > section:nth-child(4) > vn-chip > div', + fourthEntryOfSunday: 'vn-worker-time-control vn-table > div > vn-tbody > vn-tr > vn-td:nth-child(7) > section:nth-child(4) > vn-chip > div', + mondayWorkedHours: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(1) > vn-td:nth-child(1)', + tuesdayWorkedHours: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(1) > vn-td:nth-child(2)', + wednesdayWorkedHours: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(1) > vn-td:nth-child(3)', + thursdayWorkedHours: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(1) > vn-td:nth-child(4)', + fridayWorkedHours: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(1) > vn-td:nth-child(5)', + saturdayWorkedHours: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(1) > vn-td:nth-child(6)', + sundayWorkedHours: 'vn-worker-time-control vn-table > div > vn-tfoot > vn-tr:nth-child(1) > vn-td:nth-child(7)', + weekWorkedHours: 'vn-worker-time-control vn-side-menu vn-label-value > section > span', + nextMonthButton: 'vn-worker-time-control vn-side-menu vn-calendar vn-button[icon=keyboard_arrow_right]', + secondWeekDay: 'vn-worker-time-control vn-side-menu vn-calendar .day:nth-child(8) > .day-number', + navigateBackToIndex: 'vn-worker-descriptor vn-icon[icon="chevron_left"]', + acceptDeleteDialog: '.vn-confirm.shown button[response="accept"]' + }, + invoiceOutIndex: { + searchInvoiceOutInput: `vn-searchbar input`, + searchButton: 'vn-searchbar vn-icon[icon="search"]', + searchResult: 'vn-invoice-out-index vn-card > vn-table > div > vn-tbody > a.vn-tr', + }, + invoiceOutDescriptor: { + moreMenu: 'vn-invoice-out-descriptor vn-icon-menu[icon=more_vert]', + moreMenuDeleteInvoiceOut: '.vn-drop-down.shown li[name="Delete Invoice"]', + moreMenuBookInvoiceOut: '.vn-drop-down.shown li[name="Book invoice"]', + moreMenuShowInvoiceOutPdf: '.vn-drop-down.shown li[name="Show invoice PDF"]', + acceptDeleteButton: '.vn-confirm.shown button[response="accept"]', + acceptBookingButton: '.vn-confirm.shown button[response="accept"]' + }, + invoiceOutSummary: { + bookedLabel: 'vn-invoice-out-summary > vn-card > vn-horizontal > vn-one > vn-label-value:nth-child(4) > section > span' } }; diff --git a/e2e/paths/01-login/01_login.spec.js b/e2e/paths/01-login/01_login.spec.js new file mode 100644 index 000000000..f612ad23c --- /dev/null +++ b/e2e/paths/01-login/01_login.spec.js @@ -0,0 +1,38 @@ +import createNightmare from '../../helpers/nightmare'; + +describe('Login path', () => { + const nightmare = createNightmare(); + + it('should receive an error when the username is incorrect', async() => { + const result = await nightmare + .doLogin('badUser', null) + .waitForLastSnackbar(); + + expect(result.length).toBeGreaterThan(0); + }); + + it('should receive an error when the username is blank', async() => { + const result = await nightmare + .doLogin('', null) + .waitForLastSnackbar(); + + expect(result.length).toBeGreaterThan(0); + }); + + it('should receive an error when the password is incorrect', async() => { + const result = await nightmare + .doLogin('employee', 'badPassword') + .waitForLastSnackbar(); + + expect(result.length).toBeGreaterThan(0); + }); + + it('should log in', async() => { + const url = await nightmare + .doLogin('employee', null) + .wait('#user') + .parsedUrl(); + + expect(url.hash).toEqual('#!/'); + }); +}); diff --git a/e2e/paths/02-client-module/01_create_client.spec.js b/e2e/paths/02-client-module/01_create_client.spec.js new file mode 100644 index 000000000..f2fe30464 --- /dev/null +++ b/e2e/paths/02-client-module/01_create_client.spec.js @@ -0,0 +1,125 @@ +import selectors from '../../helpers/selectors'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client create path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('employee', 'client'); + }); + + it(`should search for the user Carol Danvers to confirm it isn't created yet`, async() => { + const result = await nightmare + .write(selectors.clientsIndex.searchClientInput, 'Carol Danvers') + .waitToClick(selectors.clientsIndex.searchButton) + .waitForNumberOfElements(selectors.clientsIndex.searchResult, 0) + .countElement(selectors.clientsIndex.searchResult); + + expect(result).toEqual(0); + }); + + it('should now access to the create client view by clicking the create-client floating button', async() => { + const url = await nightmare + .waitToClick(selectors.clientsIndex.createClientButton) + .wait(selectors.createClientView.createButton) + .parsedUrl(); + + expect(url.hash).toEqual('#!/client/create'); + }); + + it('should receive an error when clicking the create button having all the form fields empty', async() => { + const result = await nightmare + .waitToClick(selectors.createClientView.createButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Some fields are invalid'); + }); + + it('should receive an error when clicking the create button having name and Business name fields empty', async() => { + const result = await nightmare + .write(selectors.createClientView.taxNumber, '74451390E') + .write(selectors.createClientView.userName, 'CaptainMarvel') + .write(selectors.createClientView.email, 'CarolDanvers@verdnatura.es') + .autocompleteSearch(selectors.createClientView.salesPersonAutocomplete, 'replenisher') + .waitToClick(selectors.createClientView.createButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Some fields are invalid'); + }); + + it(`should attempt to create a new user with all it's data but wrong email`, async() => { + const result = await nightmare + .write(selectors.createClientView.name, 'Carol Danvers') + .write(selectors.createClientView.socialName, 'AVG tax') + .write(selectors.createClientView.street, 'Many places') + .autocompleteSearch(selectors.createClientView.country, 'España') + .autocompleteSearch(selectors.createClientView.province, 'Province one') + .write(selectors.createClientView.city, 'Valencia') + .write(selectors.createClientView.postcode, '46000') + .clearInput(selectors.createClientView.email) + .write(selectors.createClientView.email, 'incorrect email format') + .waitToClick(selectors.createClientView.createButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Some fields are invalid'); + }); + + it(`should attempt to create a new user with all it's data but wrong postal code`, async() => { + const result = await nightmare + .clearInput(selectors.createClientView.email) + .write(selectors.createClientView.email, 'CarolDanvers@verdnatura.es') + .clearInput(selectors.createClientView.postcode) + .write(selectors.createClientView.postcode, '479999') + .waitToClick(selectors.createClientView.createButton) + .waitForLastSnackbar(); + + expect(result).toEqual(`The postcode doesn't exists. Ensure you put the correct format`); + }); + + it(`should check for autocompleted city, province and country`, async() => { + const clientCity = await nightmare + .waitToGetProperty(`${selectors.createClientView.city}`, 'value'); + + const clientProvince = await nightmare + .waitToGetProperty(`${selectors.createClientView.province} input`, 'value'); + + const clientCountry = await nightmare + .waitToGetProperty(`${selectors.createClientView.country} input`, 'value'); + + expect(clientCity).toEqual('Valencia'); + expect(clientProvince).toEqual('Province one'); + expect(clientCountry).toEqual('España'); + }); + + it(`should create a new user with all correct data`, async() => { + const result = await nightmare + .clearInput(selectors.createClientView.postcode) + .write(selectors.createClientView.postcode, '46000') + .waitToClick(selectors.createClientView.createButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should click on the Clients button of the top bar menu', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.clientsButton) + .wait(selectors.clientsIndex.createClientButton) + .parsedUrl(); + + expect(url.hash).toEqual('#!/client/index'); + }); + + it(`should search for the user Carol Danvers to confirm it exists`, async() => { + const result = await nightmare + .write(selectors.clientsIndex.searchClientInput, 'Carol Danvers') + .waitToClick(selectors.clientsIndex.searchButton) + .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) + .countElement(selectors.clientsIndex.searchResult); + + expect(result).toEqual(1); + }); +}); diff --git a/e2e/paths/02-client-module/02_edit_basic_data.spec.js b/e2e/paths/02-client-module/02_edit_basic_data.spec.js new file mode 100644 index 000000000..988ad82c8 --- /dev/null +++ b/e2e/paths/02-client-module/02_edit_basic_data.spec.js @@ -0,0 +1,175 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client Edit basicData path', () => { + const nightmare = createNightmare(); + describe('as employee', () => { + beforeAll(() => { + nightmare + .loginAndModule('employee', 'client') + .accessToSearchResult('Bruce Wayne') + .accessToSection('client.card.basicData'); + }); + + it('should not be able to change the salesPerson', async() => { + const result = await nightmare + .wait(selectors.clientBasicData.nameInput) + .evaluate(selector => { + return document.querySelector(selector).disabled; + }, `${selectors.clientBasicData.salesPersonAutocomplete} input`); + + expect(result).toBeTruthy(); + }); + + it('should edit the client basic data but leave salesPerson untainted', async() => { + const result = await nightmare + .clearInput(selectors.clientBasicData.nameInput) + .write(selectors.clientBasicData.nameInput, 'Ptonomy Wallace') + .clearInput(selectors.clientBasicData.contactInput) + .write(selectors.clientBasicData.contactInput, 'David Haller') + .clearInput(selectors.clientBasicData.phoneInput) + .write(selectors.clientBasicData.phoneInput, '987654321') + .clearInput(selectors.clientBasicData.mobileInput) + .write(selectors.clientBasicData.mobileInput, '123456789') + .clearInput(selectors.clientBasicData.emailInput) + .write(selectors.clientBasicData.emailInput, 'PWallace@verdnatura.es') + .autocompleteSearch(selectors.clientBasicData.channelAutocomplete, 'Rumors on the streets') + .waitToClick(selectors.clientBasicData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the name have been edited', async() => { + const result = await nightmare + .reloadSection('client.card.basicData') + .waitToGetProperty(selectors.clientBasicData.nameInput, 'value'); + + expect(result).toEqual('Ptonomy Wallace'); + }); + + it('should confirm the contact name have been edited', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientBasicData.contactInput, 'value'); + + expect(result).toEqual('David Haller'); + }); + + it('should confirm the landline phone number have been added', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientBasicData.phoneInput, 'value'); + + expect(result).toEqual('987654321'); + }); + + it('should confirm the mobile phone number have been added', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientBasicData.mobileInput, 'value'); + + expect(result).toEqual('123456789'); + }); + + it('should confirm the email have been edited', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientBasicData.emailInput, 'value'); + + expect(result).toEqual('PWallace@verdnatura.es'); + }); + + it('should confirm the channel have been selected', async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.clientBasicData.channelAutocomplete} input`, 'value'); + + expect(result).toEqual('Rumors on the streets'); + }); + }); + + describe('as salesAssistant', () => { + beforeAll(() => { + nightmare + .loginAndModule('salesASsistant', 'client') + .accessToSearchResult('Ptonomy Wallace') + .accessToSection('client.card.basicData'); + }); + + it('should be able to change the salesPerson', async() => { + const result = await nightmare + .wait(selectors.clientBasicData.nameInput) + .evaluate(selector => { + return document.querySelector(selector).disabled; + }, `${selectors.clientBasicData.salesPersonAutocomplete} input`); + + expect(result).toBeFalsy(); + }); + + it('should edit the client basic data including salesPerson', async() => { + const result = await nightmare + .clearInput(selectors.clientBasicData.nameInput) + .write(selectors.clientBasicData.nameInput, 'Ororo Munroe') + .clearInput(selectors.clientBasicData.contactInput) + .write(selectors.clientBasicData.contactInput, 'Black Panther') + .clearInput(selectors.clientBasicData.phoneInput) + .write(selectors.clientBasicData.phoneInput, '123456789') + .clearInput(selectors.clientBasicData.mobileInput) + .write(selectors.clientBasicData.mobileInput, '987654321') + .clearInput(selectors.clientBasicData.emailInput) + .write(selectors.clientBasicData.emailInput, 'Storm@verdnatura.es') + .autocompleteSearch(selectors.clientBasicData.salesPersonAutocomplete, 'replenisherNick') + .autocompleteSearch(selectors.clientBasicData.channelAutocomplete, 'Metropolis newspaper') + .waitToClick(selectors.clientBasicData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should now confirm the name have been edited', async() => { + const result = await nightmare + .reloadSection('client.card.basicData') + .waitToGetProperty(selectors.clientBasicData.nameInput, 'value'); + + expect(result).toEqual('Ororo Munroe'); + }); + + it('should now confirm the contact name have been edited', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientBasicData.contactInput, 'value'); + + expect(result).toEqual('Black Panther'); + }); + + it('should now confirm the landline phone number have been added', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientBasicData.phoneInput, 'value'); + + expect(result).toEqual('123456789'); + }); + + it('should now confirm the mobile phone number have been added', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientBasicData.mobileInput, 'value'); + + expect(result).toEqual('987654321'); + }); + + it('should now confirm the email have been edited', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientBasicData.emailInput, 'value'); + + expect(result).toEqual('Storm@verdnatura.es'); + }); + + it('should confirm the sales person have been selected', async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.clientBasicData.salesPersonAutocomplete} input`, 'value'); + + expect(result).toEqual('replenisherNick'); + }); + + it('should now confirm the channel have been selected', async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.clientBasicData.channelAutocomplete} input`, 'value'); + + expect(result).toEqual('Metropolis newspaper'); + }); + }); +}); diff --git a/e2e/paths/02-client-module/03_edit_fiscal_data.spec.js b/e2e/paths/02-client-module/03_edit_fiscal_data.spec.js new file mode 100644 index 000000000..9d41ed223 --- /dev/null +++ b/e2e/paths/02-client-module/03_edit_fiscal_data.spec.js @@ -0,0 +1,316 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client Edit fiscalData path', () => { + const nightmare = createNightmare(); + describe('as employee', () => { + beforeAll(() => { + nightmare + .loginAndModule('employee', 'client') + .accessToSearchResult('Bruce Banner') + .accessToSection('client.card.address.index'); + }); + + // Confirms all addresses have EQtax false for future propagation test step 1 + it(`should click on the 1st edit icon to check EQtax isnt checked`, async() => { + const result = await nightmare + .waitToClick(selectors.clientAddresses.firstEditAddress) + .checkboxState(selectors.clientAddresses.equalizationTaxCheckbox); + + expect(result).toBe('unchecked'); + }); + + // Confirms all addresses have EQtax false for future propagation test step 2 + it(`should go back to addresses then select the second one and confirm the EQtax isnt checked`, async() => { + const result = await nightmare + .waitToClick(selectors.clientAddresses.addressesButton) + .waitToClick(selectors.clientAddresses.secondEditAddress) + .checkboxState(selectors.clientAddresses.equalizationTaxCheckbox); + + expect(result).toBe('unchecked'); + }); + + it(`should click on the fiscal data button`, async() => { + const url = await nightmare + .waitToClick(selectors.clientFiscalData.fiscalDataButton) + .waitForURL('fiscal-data') + .parsedUrl(); + + expect(url.hash).toContain('fiscal-data'); + }); + + it('should not be able to edit the verified data checkbox', async() => { + const result = await nightmare + .wait(selectors.clientFiscalData.verifiedDataCheckbox) + .isDisabled(selectors.clientFiscalData.verifiedDataCheckbox); + + expect(result).toBeTruthy(); + }); + }); + + describe('as administrative', () => { + beforeAll(() => { + nightmare + .loginAndModule('administrative', 'client') + .accessToSearchResult('Bruce Banner') + .accessToSection('client.card.fiscalData'); + }); + + it(`should edit the fiscal data but fail as the fiscal id ain't valid`, async() => { + const result = await nightmare + .wait(selectors.clientFiscalData.socialNameInput) + .clearInput(selectors.clientFiscalData.socialNameInput) + .write(selectors.clientFiscalData.socialNameInput, 'SMASH') + .clearInput(selectors.clientFiscalData.fiscalIdInput) + .write(selectors.clientFiscalData.fiscalIdInput, 'INVALID!') + .clearInput(selectors.clientFiscalData.addressInput) + .write(selectors.clientFiscalData.addressInput, 'Somewhere edited') + .autocompleteSearch(selectors.clientFiscalData.countryAutocomplete, 'España') + .autocompleteSearch(selectors.clientFiscalData.provinceAutocomplete, 'Province one') + .clearInput(selectors.clientFiscalData.cityInput) + .write(selectors.clientFiscalData.cityInput, 'Valencia') + .clearInput(selectors.clientFiscalData.postcodeInput) + .write(selectors.clientFiscalData.postcodeInput, '46000') + .waitToClick(selectors.clientFiscalData.activeCheckbox) + .waitToClick(selectors.clientFiscalData.frozenCheckbox) + .waitToClick(selectors.clientFiscalData.hasToInvoiceCheckbox) + .waitToClick(selectors.clientFiscalData.viesCheckbox) + .waitToClick(selectors.clientFiscalData.invoiceByMailCheckbox) + .waitToClick(selectors.clientFiscalData.invoiceByAddressCheckbox) + .waitToClick(selectors.clientFiscalData.equalizationTaxCheckbox) + .waitToClick(selectors.clientFiscalData.verifiedDataCheckbox) + .waitToClick(selectors.clientFiscalData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Invalid Tax number'); + }); + + it(`should edit the fiscal this time with a valid fiscal id`, async() => { + const result = await nightmare + .clearInput(selectors.clientFiscalData.fiscalIdInput) + .write(selectors.clientFiscalData.fiscalIdInput, '94980061C') + .waitToClick(selectors.clientFiscalData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should propagate the Equalization tax', async() => { + const result = await nightmare + .waitToClick(selectors.clientFiscalData.acceptPropagationButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Equivalent tax spreaded'); + }); + + it('should receive an error if the fiscal id contains A or B at the beginning', async() => { + const result = await nightmare + .waitToClick(selectors.clientFiscalData.viesCheckbox) + .clearInput(selectors.clientFiscalData.fiscalIdInput) + .write(selectors.clientFiscalData.fiscalIdInput, 'A94980061C') + .waitToClick(selectors.clientFiscalData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Cannot check Equalization Tax in this NIF/CIF'); + }); + + it('should finally edit the fixcal data correctly as VIES isnt checked and fiscal id is valid for EQtax', async() => { + const result = await nightmare + .clearInput(selectors.clientFiscalData.fiscalIdInput) + .write(selectors.clientFiscalData.fiscalIdInput, '94980061C') + .waitToClick(selectors.clientFiscalData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + // confirm all addresses have now EQtax checked step 1 + it(`should click on the addresses button to access to the client's addresses`, async() => { + const url = await nightmare + .waitToClick(selectors.clientAddresses.addressesButton) + .waitForURL('/address/index') + .parsedUrl(); + + expect(url.hash).toContain('/address/index'); + }); + + // confirm all addresses have now EQtax checked step 2 + it(`should click on the 1st edit icon to confirm EQtax is checked`, async() => { + const result = await nightmare + .waitToClick(selectors.clientAddresses.firstEditAddress) + .waitForWatcherData(selectors.clientAddresses.watcher) + .checkboxState(selectors.clientAddresses.equalizationTaxCheckbox); + + expect(result).toBe('checked'); + }); + + // confirm all addresses have now EQtax checked step 3 + it(`should go back to addresses then select the second one and confirm the EQtax is checked`, async() => { + const result = await nightmare + .waitToClick(selectors.clientAddresses.addressesButton) + .waitToClick(selectors.clientAddresses.secondEditAddress) + .waitForWatcherData(selectors.clientAddresses.watcher) + .checkboxState(selectors.clientAddresses.equalizationTaxCheckbox); + + expect(result).toBe('checked'); + }); + + it('should navigate back to fiscal data and uncheck EQtax then check VIES', async() => { + const result = await nightmare + .waitToClick(selectors.clientFiscalData.fiscalDataButton) + .waitToClick(selectors.clientFiscalData.viesCheckbox) + .waitToClick(selectors.clientFiscalData.equalizationTaxCheckbox) + .waitToClick(selectors.clientFiscalData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should propagate the Equalization tax changes', async() => { + const result = await nightmare + .waitToClick(selectors.clientFiscalData.acceptPropagationButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Equivalent tax spreaded'); + }); + + it('should confirm its name have been edited', async() => { + const result = await nightmare + .waitToClick(selectors.clientFiscalData.fiscalDataButton) + .waitToGetProperty(selectors.clientFiscalData.socialNameInput, 'value'); + + expect(result).toEqual('SMASH'); + }); + + it('should confirm the fiscal id have been edited', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientFiscalData.fiscalIdInput, 'value'); + + expect(result).toEqual('94980061C'); + }); + + it('should confirm the address have been edited', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientFiscalData.addressInput, 'value'); + + expect(result).toEqual('Somewhere edited'); + }); + + it('should confirm the postcode have been edited', async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.clientFiscalData.postcodeInput}`, 'value'); + + expect(result).toContain('46000'); + }); + + it('should confirm the city have been autocompleted', async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.clientFiscalData.cityInput}`, 'value'); + + expect(result).toEqual('Valencia'); + }); + + + it(`should confirm the province have been autocompleted`, async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.clientFiscalData.provinceAutocomplete} input`, 'value'); + + expect(result).toEqual('Province one'); + }); + + it('should confirm the country have been autocompleted', async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.clientFiscalData.countryAutocomplete} input`, 'value'); + + expect(result).toEqual('España'); + }); + + it('should confirm active checkbox is unchecked', async() => { + const result = await nightmare + .checkboxState(selectors.clientFiscalData.activeCheckbox); + + expect(result).toBe('unchecked'); + }); + + it('should confirm frozen checkbox is checked', async() => { + const result = await nightmare + .checkboxState(selectors.clientFiscalData.frozenCheckbox); + + expect(result).toBe('checked'); + }); + + it('should confirm Has to invoice checkbox is unchecked', async() => { + const result = await nightmare + .checkboxState(selectors.clientFiscalData.hasToInvoiceCheckbox); + + expect(result).toBe('unchecked'); + }); + + it('should confirm Vies checkbox is checked', async() => { + const result = await nightmare + .checkboxState(selectors.clientFiscalData.viesCheckbox); + + expect(result).toBe('checked'); + }); + + it('should confirm Invoice by mail checkbox is unchecked', async() => { + const result = await nightmare + .checkboxState(selectors.clientFiscalData.invoiceByMailCheckbox); + + expect(result).toBe('unchecked'); + }); + + it('should confirm invoice by address checkbox is unchecked', async() => { + const result = await nightmare + .checkboxState(selectors.clientFiscalData.invoiceByAddressCheckbox); + + expect(result).toBe('unchecked'); + }); + + it('should confirm Equalization tax checkbox is unchecked', async() => { + const result = await nightmare + .checkboxState(selectors.clientFiscalData.equalizationTaxCheckbox); + + expect(result).toBe('unchecked'); + }); + + it('should confirm Verified data checkbox is checked', async() => { + const result = await nightmare + .checkboxState(selectors.clientFiscalData.verifiedDataCheckbox); + + expect(result).toBe('checked'); + }); + + // confirm invoice by address checkbox gets checked if the EQtax differs between addresses step 1 + it(`should click on the addresses button to access to the client's addresses`, async() => { + const url = await nightmare + .waitToClick(selectors.clientAddresses.addressesButton) + .waitForURL('/address/index') + .parsedUrl(); + + expect(url.hash).toContain('/address/index'); + }); + + // confirm invoice by address checkbox gets checked if the EQtax differs between addresses step 2 + it(`should click on the 1st edit icon to access the address details and uncheck EQtax checkbox`, async() => { + const result = await nightmare + .waitToClick(selectors.clientAddresses.firstEditAddress) + .waitForTextInInput(selectors.clientAddresses.cityInput, 'Silla') + .waitToClick(selectors.clientAddresses.equalizationTaxCheckbox) + .waitToClick(selectors.clientAddresses.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + // confirm invoice by address checkbox gets checked if the EQtax differs between addresses step 3 + it('should navigate back to fiscal data to confirm invoice by address is now checked', async() => { + const result = await nightmare + .waitToClick(selectors.clientFiscalData.fiscalDataButton) + .waitForWatcherData(selectors.clientFiscalData.watcher) + .checkboxState(selectors.clientFiscalData.invoiceByAddressCheckbox); + + expect(result).toBe('checked'); + }); + }); +}); diff --git a/e2e/paths/02-client-module/04_edit_billing_data.spec.js b/e2e/paths/02-client-module/04_edit_billing_data.spec.js new file mode 100644 index 000000000..ffea943f1 --- /dev/null +++ b/e2e/paths/02-client-module/04_edit_billing_data.spec.js @@ -0,0 +1,122 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client Edit billing data path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('administrative', 'client') + .accessToSearchResult('Bruce Banner') + .accessToSection('client.card.billingData'); + }); + + it(`should attempt to edit the billing data without an IBAN but fail`, async() => { + const snackbarMessage = await nightmare + .autocompleteSearch(selectors.clientBillingData.payMethodAutocomplete, 'PayMethod with IBAN') + .autocompleteSearch(selectors.clientBillingData.swiftBicAutocomplete, 'BBKKESMMMMM') + .clearInput(selectors.clientBillingData.dueDayInput) + .write(selectors.clientBillingData.dueDayInput, '60') + .waitForTextInInput(selectors.clientBillingData.dueDayInput, '60') + .waitToClick(selectors.clientBillingData.receivedCoreLCRCheckbox) + .waitToClick(selectors.clientBillingData.receivedCoreVNLCheckbox) + .waitToClick(selectors.clientBillingData.receivedB2BVNLCheckbox) + .waitToClick(selectors.clientBillingData.saveButton) + .waitForLastSnackbar(); + + expect(snackbarMessage).toEqual('That payment method requires an IBAN'); + }); + + it(`should add the IBAN but fail as it requires a BIC code`, async() => { + const snackbarMessage = await nightmare + .waitToClick(selectors.clientBillingData.clearswiftBicButton) + .clearInput(selectors.clientBillingData.IBANInput) + .write(selectors.clientBillingData.IBANInput, 'FR9121000418450200051332') + .waitForTextInInput(selectors.clientBillingData.IBANInput, 'FR9121000418450200051332') + .wait(1000) + .waitToClick(selectors.clientBillingData.saveButton) + .waitForLastSnackbar(); + + expect(snackbarMessage).toEqual('That payment method requires a BIC'); + }); + + it(`should create a new BIC code`, async() => { + const newcode = await nightmare + .waitToClick(selectors.clientBillingData.newBankEntityButton) + .write(selectors.clientBillingData.newBankEntityName, 'Gotham City Bank') + .write(selectors.clientBillingData.newBankEntityCode, 9999) + .write(selectors.clientBillingData.newBankEntityBIC, 'GTHMCT') + .waitToClick(selectors.clientBillingData.acceptBankEntityButton) + .waitToGetProperty(`${selectors.clientBillingData.swiftBicAutocomplete} input`, 'value'); + + expect(newcode).toEqual('GTHMCT Gotham City Bank'); + }); + + it(`should confirm the IBAN pay method is sucessfully saved`, async() => { + const payMethod = await nightmare + .waitToGetProperty(`${selectors.clientBillingData.payMethodAutocomplete} input`, 'value'); + + expect(payMethod).toEqual('PayMethod with IBAN'); + }); + + it(`should clear the BIC code field, update the IBAN to see how he BIC code autocompletes`, async() => { + const AutomaticCode = await nightmare + .clearInput(selectors.clientBillingData.IBANInput) + .write(selectors.clientBillingData.IBANInput, 'ES9121000418450200051332') + .waitForTextInInput(`${selectors.clientBillingData.swiftBicAutocomplete} input`, 'caixesbb') + .waitToGetProperty(`${selectors.clientBillingData.swiftBicAutocomplete} input`, 'value'); + + expect(AutomaticCode).toEqual('CAIXESBB Caixa Bank'); + }); + + it(`should save the form with all its new data`, async() => { + const snackbarMessages = await nightmare + .waitForWatcherData(selectors.clientBillingData.watcher) + .waitToClick(selectors.clientBillingData.saveButton) + .waitForSnackbar(); + + expect(snackbarMessages).toEqual(jasmine.arrayContaining(['Data saved!'])); + }); + + it('should confirm the due day have been edited', async() => { + const dueDate = await nightmare + .waitToGetProperty(selectors.clientBillingData.dueDayInput, 'value'); + + expect(dueDate).toEqual('60'); + }); + + it('should confirm the IBAN was saved', async() => { + const IBAN = await nightmare + .waitToGetProperty(selectors.clientBillingData.IBANInput, 'value'); + + expect(IBAN).toEqual('ES9121000418450200051332'); + }); + + it('should confirm the swift / BIC code was saved', async() => { + const code = await nightmare + .waitToGetProperty(`${selectors.clientBillingData.swiftBicAutocomplete} input`, 'value'); + + expect(code).toEqual('CAIXESBB Caixa Bank'); + }); + + it('should confirm Received LCR checkbox is checked', async() => { + const result = await nightmare + .checkboxState(selectors.clientBillingData.receivedCoreLCRCheckbox); + + expect(result).toBe('checked'); + }); + + it('should confirm Received core VNL checkbox is unchecked', async() => { + const result = await nightmare + .checkboxState(selectors.clientBillingData.receivedCoreVNLCheckbox); + + expect(result).toBe('unchecked'); + }); + + it('should confirm Received B2B VNL checkbox is unchecked', async() => { + const result = await nightmare + .checkboxState(selectors.clientBillingData.receivedB2BVNLCheckbox); + + expect(result).toBe('unchecked'); + }); +}); diff --git a/e2e/paths/02-client-module/05_add_address.spec.js b/e2e/paths/02-client-module/05_add_address.spec.js new file mode 100644 index 000000000..4502a9be1 --- /dev/null +++ b/e2e/paths/02-client-module/05_add_address.spec.js @@ -0,0 +1,120 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client Add address path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('employee', 'client') + .accessToSearchResult('Bruce Banner') + .accessToSection('client.card.address.index'); + }); + + it(`should click on the add new address button to access to the new address form`, async() => { + const url = await nightmare + .waitToClick(selectors.clientAddresses.createAddress) + .waitForURL('address/create') + .parsedUrl(); + + expect(url.hash).toContain('address/create'); + }); + + it('should receive an error after clicking save button as consignee, street and town fields are empty', async() => { + const result = await nightmare + .waitToClick(selectors.clientAddresses.defaultCheckboxInput) + .clearInput(selectors.clientAddresses.streetAddressInput) + .autocompleteSearch(selectors.clientAddresses.provinceAutocomplete, 'Province one') + .clearInput(selectors.clientAddresses.cityInput) + .write(selectors.clientAddresses.cityInput, 'Valencia') + .clearInput(selectors.clientAddresses.postcodeInput) + .write(selectors.clientAddresses.postcodeInput, '46000') + .autocompleteSearch(selectors.clientAddresses.agencyAutocomplete, 'Entanglement') + .write(selectors.clientAddresses.phoneInput, '999887744') + .write(selectors.clientAddresses.mobileInput, '999887744') + .waitToClick(selectors.clientFiscalData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Some fields are invalid'); + }); + + it('should confirm the postcode have been edited', async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.clientAddresses.postcodeInput}`, 'value'); + + expect(result).toContain('46000'); + }); + + it('should confirm the city have been autocompleted', async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.clientAddresses.cityInput}`, 'value'); + + expect(result).toEqual('Valencia'); + }); + + + it(`should confirm the province have been autocompleted`, async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.clientAddresses.provinceAutocomplete} input`, 'value'); + + expect(result).toEqual('Province one'); + }); + + it(`should create a new address with all it's data`, async() => { + const result = await nightmare + .write(selectors.clientAddresses.consigneeInput, 'Bruce Bunner') + .write(selectors.clientAddresses.streetAddressInput, '320 Park Avenue New York') + .waitToClick(selectors.clientAddresses.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should click on the addresses button confirm the new address exists and it's the default one`, async() => { + const result = await nightmare + // .waitToClick(selectors.clientAddresses.addressesButton) + .waitToGetProperty(selectors.clientAddresses.defaultAddress, 'innerText'); + + expect(result).toContain('320 Park Avenue New York'); + }); + + it(`should click on the make default icon of the second address then confirm it is the default one now`, async() => { + const result = await nightmare + .waitToClick(selectors.clientAddresses.secondMakeDefaultStar) + .waitForTextInElement(selectors.clientAddresses.defaultAddress, 'Somewhere in Thailand') + .waitToGetProperty(selectors.clientAddresses.defaultAddress, 'innerText'); + + expect(result).toContain('Somewhere in Thailand'); + }); + + it(`should click on the edit icon of the default address`, async() => { + const url = await nightmare + .waitForTextInElement(selectors.clientAddresses.defaultAddress, 'Somewhere in Thailand') + .waitToClick(selectors.clientAddresses.firstEditAddress) + .waitForURL('/edit') + .parsedUrl(); + + expect(url.hash).toContain('/edit'); + }); + + it(`should click on the active checkbox and receive an error to save it because it is the default address`, async() => { + const result = await nightmare + .waitForWatcherData(selectors.clientAddresses.watcher) + .waitToClick(selectors.clientAddresses.activeCheckbox) + .waitToClick(selectors.clientAddresses.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('The default consignee can not be unchecked'); + }); + + // this "it" should be removed if the watcher doesn't prevent the navigation upon state changes + it(`should go back to the addreses section by clicking the cancel button`, async() => { + const url = await nightmare + .waitToClick(selectors.clientAddresses.cancelEditAddressButton) + .waitToClick('.vn-confirm.shown button[response="accept"]') + .waitForURL('address/index') + .parsedUrl(); + + expect(url.hash).toContain('address/index'); + }); +}); diff --git a/e2e/paths/02-client-module/06_add_address_notes.spec.js b/e2e/paths/02-client-module/06_add_address_notes.spec.js new file mode 100644 index 000000000..a37fef529 --- /dev/null +++ b/e2e/paths/02-client-module/06_add_address_notes.spec.js @@ -0,0 +1,55 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client add address notes path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('employee', 'client') + .accessToSearchResult('Petter Parker') + .accessToSection('client.card.address.index'); + }); + + it(`should click on the edit icon of the default address`, async() => { + const url = await nightmare + .waitForTextInElement(selectors.clientAddresses.defaultAddress, '20 Ingram Street') + .waitToClick(selectors.clientAddresses.firstEditAddress) + .waitForURL('/edit') + .parsedUrl(); + + expect(url.hash).toContain('/edit'); + }); + + it('should not save a description without observation type', async() => { + const result = await nightmare + .waitToClick(selectors.clientAddresses.addObservationButton) + .write(selectors.clientAddresses.firstObservationDescriptionInput, 'first description') + .waitToClick(selectors.clientAddresses.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Some fields are invalid'); + }); + + it('should not save an observation type without description', async() => { + const result = await nightmare + .clearInput(selectors.clientAddresses.firstObservationDescriptionInput) + .autocompleteSearch(selectors.clientAddresses.firstObservationTypeAutocomplete, 'comercial') + .waitToClick(selectors.clientAddresses.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Some fields are invalid'); + }); + + it('should create two new observations', async() => { + const result = await nightmare + .write(selectors.clientAddresses.firstObservationDescriptionInput, 'first description') + .waitToClick(selectors.clientAddresses.addObservationButton) + .autocompleteSearch(selectors.clientAddresses.secondObservationTypeAutocomplete, 'observation one') + .write(selectors.clientAddresses.secondObservationDescriptionInput, 'second description') + .waitToClick(selectors.clientAddresses.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); +}); diff --git a/e2e/paths/02-client-module/07_edit_web_access.spec.js b/e2e/paths/02-client-module/07_edit_web_access.spec.js new file mode 100644 index 000000000..999b1c123 --- /dev/null +++ b/e2e/paths/02-client-module/07_edit_web_access.spec.js @@ -0,0 +1,42 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client Edit web access path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('employee', 'client') + .accessToSearchResult('Bruce Banner') + .accessToSection('client.card.webAccess'); + }); + + it(`should uncheck the Enable web access checkbox and update the name`, async() => { + const result = await nightmare + .waitToClick(selectors.clientWebAccess.enableWebAccessCheckbox) + .clearInput(selectors.clientWebAccess.userNameInput) + .write(selectors.clientWebAccess.userNameInput, 'Hulk') + .waitToClick(selectors.clientWebAccess.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm web access is now unchecked', async() => { + const result = await nightmare + .waitToClick(selectors.clientBasicData.basicDataButton) + .wait(selectors.clientBasicData.nameInput) + .waitToClick(selectors.clientsIndex.othersButton) + .waitToClick(selectors.clientWebAccess.webAccessButton) + .checkboxState(selectors.clientWebAccess.enableWebAccessCheckbox); + + expect(result).toBe('unchecked'); + }); + + it('should confirm web access name have been updated', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientWebAccess.userNameInput, 'value'); + + expect(result).toEqual('Hulk'); + }); +}); diff --git a/e2e/paths/02-client-module/08_add_notes.spec.js b/e2e/paths/02-client-module/08_add_notes.spec.js new file mode 100644 index 000000000..1528dd79b --- /dev/null +++ b/e2e/paths/02-client-module/08_add_notes.spec.js @@ -0,0 +1,38 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client Add notes path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('employee', 'client') + .accessToSearchResult('Bruce Banner') + .accessToSection('client.card.note.index'); + }); + + it(`should click on the add note button`, async() => { + const url = await nightmare + .waitToClick(selectors.clientNotes.addNoteFloatButton) + .waitForURL('/note/create') + .parsedUrl(); + + expect(url.hash).toContain('/note/create'); + }); + + it(`should create a note`, async() => { + const result = await nightmare + .write(selectors.clientNotes.noteInput, 'Meeting with Black Widow 21st 9am') + .waitToClick(selectors.clientNotes.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the note was created', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientNotes.firstNoteText, 'innerText'); + + expect(result).toEqual('Meeting with Black Widow 21st 9am'); + }); +}); diff --git a/e2e/paths/02-client-module/09_add_credit.spec.js b/e2e/paths/02-client-module/09_add_credit.spec.js new file mode 100644 index 000000000..60ff2d347 --- /dev/null +++ b/e2e/paths/02-client-module/09_add_credit.spec.js @@ -0,0 +1,40 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client Add credit path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('salesAssistant', 'client') + .accessToSearchResult('Hank Pym') + .accessToSection('client.card.credit.index'); + }); + + it(`should click on the add credit button`, async() => { + const url = await nightmare + .waitToClick(selectors.clientCredit.addCreditFloatButton) + .waitForURL('/credit/create') + .parsedUrl(); + + expect(url.hash).toContain('/credit/create'); + }); + + it(`should edit the credit`, async() => { + const result = await nightmare + .clearInput(selectors.clientCredit.creditInput) + .write(selectors.clientCredit.creditInput, 999) + .waitToClick(selectors.clientCredit.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the credit was updated', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientCredit.firstCreditText, 'innerText'); + + expect(result).toContain(999); + expect(result).toContain('salesAssistant'); + }); +}); diff --git a/e2e/paths/02-client-module/10_add_greuge.spec.js b/e2e/paths/02-client-module/10_add_greuge.spec.js new file mode 100644 index 000000000..46fdf65e3 --- /dev/null +++ b/e2e/paths/02-client-module/10_add_greuge.spec.js @@ -0,0 +1,51 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client Add greuge path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('salesAssistant', 'client') + .accessToSearchResult('Petter Parker') + .accessToSection('client.card.greuge.index'); + }); + + it(`should click on the add greuge button`, async() => { + const url = await nightmare + .waitToClick(selectors.clientGreuge.addGreugeFloatButton) + .waitForURL('greuge/create') + .parsedUrl(); + + expect(url.hash).toContain('greuge/create'); + }); + + it(`should receive an error if all fields are empty but date and type on submit`, async() => { + const result = await nightmare + .autocompleteSearch(selectors.clientGreuge.typeAutocomplete, 'Diff') + .waitToClick(selectors.clientGreuge.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Some fields are invalid'); + }); + + it(`should create a new greuge with all its data`, async() => { + const result = await nightmare + .write(selectors.clientGreuge.amountInput, 999) + .waitForTextInInput(selectors.clientGreuge.amountInput, '999') + .write(selectors.clientGreuge.descriptionInput, 'new armor for Batman!') + .waitToClick(selectors.clientGreuge.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the greuge was added to the list', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientGreuge.firstGreugeText, 'innerText'); + + expect(result).toContain(999); + expect(result).toContain('new armor for Batman!'); + expect(result).toContain('Diff'); + }); +}); diff --git a/e2e/paths/02-client-module/11_mandate.spec.js b/e2e/paths/02-client-module/11_mandate.spec.js new file mode 100644 index 000000000..4048ae8a2 --- /dev/null +++ b/e2e/paths/02-client-module/11_mandate.spec.js @@ -0,0 +1,22 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client mandate path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('salesPerson', 'client') + .accessToSearchResult('Petter Parker') + .accessToSection('client.card.mandate'); + }); + + it('should confirm the client has a mandate of the CORE type', async() => { + const result = await nightmare + .waitToGetProperty(selectors.clientMandate.firstMandateText, 'innerText'); + + expect(result).toContain('1'); + expect(result).toContain('VNL'); + expect(result).toContain('CORE'); + }); +}); diff --git a/e2e/paths/02-client-module/12_lock_of_verified_data.spec.js b/e2e/paths/02-client-module/12_lock_of_verified_data.spec.js new file mode 100644 index 000000000..398185ba5 --- /dev/null +++ b/e2e/paths/02-client-module/12_lock_of_verified_data.spec.js @@ -0,0 +1,182 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client lock verified data path', () => { + const nightmare = createNightmare(); + + describe('as salesPerson', () => { + beforeAll(() => { + nightmare + .loginAndModule('salesPerson', 'client') + .accessToSearchResult('Hank Pym') + .accessToSection('client.card.fiscalData'); + }); + + it('should confirm verified data button is disabled for salesPerson', async() => { + const result = await nightmare + .wait(200) + .wait(selectors.clientFiscalData.verifiedDataCheckbox) + .isDisabled(selectors.clientFiscalData.verifiedDataCheckbox); + + expect(result).toBeTruthy(); + }); + + it('should edit the social name', async() => { + const result = await nightmare + .wait(selectors.clientFiscalData.socialNameInput) + .clearInput(selectors.clientFiscalData.socialNameInput) + .write(selectors.clientFiscalData.socialNameInput, 'Captain America Civil War') + .waitToClick(selectors.clientFiscalData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the social name have been edited', async() => { + const result = await nightmare + .reloadSection('client.card.fiscalData') + .waitToGetProperty(selectors.clientFiscalData.socialNameInput, 'value'); + + expect(result).toEqual('Captain America Civil War'); + }); + }); + + describe('as administrative', () => { + beforeAll(() => { + nightmare + .loginAndModule('administrative', 'client') + .accessToSearchResult('Hank Pym') + .accessToSection('client.card.fiscalData'); + }); + + it('should confirm verified data button is enabled for administrative', async() => { + const result = await nightmare + .isDisabled(selectors.clientFiscalData.verifiedDataCheckbox); + + expect(result).toBeFalsy(); + }); + + it('should check the Verified data checkbox', async() => { + const result = await nightmare + .waitToClick(selectors.clientFiscalData.verifiedDataCheckbox) + .waitToClick(selectors.clientFiscalData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm Verified data checkbox is checked', async() => { + const isChecked = await nightmare + .reloadSection('client.card.fiscalData') + .checkboxState(selectors.clientFiscalData.verifiedDataCheckbox); + + expect(isChecked).toEqual('checked'); + }); + + it('should again edit the social name', async() => { + const result = await nightmare + .wait(selectors.clientFiscalData.socialNameInput) + .clearInput(selectors.clientFiscalData.socialNameInput) + .write(selectors.clientFiscalData.socialNameInput, 'Ant man and the Wasp') + .waitToClick(selectors.clientFiscalData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should again confirm the social name have been edited', async() => { + const result = await nightmare + .reloadSection('client.card.fiscalData') + .waitToGetProperty(selectors.clientFiscalData.socialNameInput, 'value'); + + expect(result).toEqual('Ant man and the Wasp'); + }); + }); + + describe('as salesPerson second run', () => { + beforeAll(() => { + nightmare + .loginAndModule('salesPerson', 'client') + .accessToSearchResult('Hank Pym') + .accessToSection('client.card.fiscalData'); + }); + + it('should confirm verified data button is disabled once again for salesPerson', async() => { + const isDisabled = await nightmare + .isDisabled(selectors.clientFiscalData.verifiedDataCheckbox); + + expect(isDisabled).toBeTruthy(); + }); + + it('should not be able to save change throwing a verified data error', async() => { + const result = await nightmare + .clearInput(selectors.clientFiscalData.socialNameInput) + .write(selectors.clientFiscalData.socialNameInput, 'This wont happen') + .waitToClick(selectors.clientFiscalData.saveButton) + .waitForSnackbar(); + + expect(result).toEqual(jasmine.arrayContaining([`You can't make changes on a client with verified data`])); + }); + }); + + describe('as salesAssistant', () => { + beforeAll(() => { + nightmare + .forceReloadSection('client.card.fiscalData') + .loginAndModule('salesAssistant', 'client') + .accessToSearchResult('Hank Pym') + .accessToSection('client.card.fiscalData'); + }); + + it('should confirm verified data button is enabled for salesAssistant', async() => { + const isDisabled = await nightmare + .isDisabled(selectors.clientFiscalData.verifiedDataCheckbox); + + expect(isDisabled).toBeFalsy(); + }); + + it('should now edit the social name', async() => { + const result = await nightmare + .clearInput(selectors.clientFiscalData.socialNameInput) + .write(selectors.clientFiscalData.socialNameInput, 'new social name edition') + .waitToClick(selectors.clientFiscalData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should now confirm the social name have been edited once and for all', async() => { + const result = await nightmare + .reloadSection('client.card.fiscalData') + .waitToGetProperty(selectors.clientFiscalData.socialNameInput, 'value'); + + expect(result).toEqual('new social name edition'); + }); + }); + + describe('as salesPerson third run', () => { + beforeAll(() => { + nightmare + .loginAndModule('salesPerson', 'client') + .accessToSearchResult('Hank Pym') + .accessToSection('client.card.fiscalData'); + }); + + it('should confirm verified data button is enabled once again', async() => { + const isDisabled = await nightmare + .isDisabled(selectors.clientFiscalData.verifiedDataCheckbox); + + expect(isDisabled).toBeTruthy(); + }); + + it('should confirm the form is enabled for salesPerson', async() => { + const result = await nightmare + .wait(selectors.clientFiscalData.socialNameInput) + .evaluate(selector => { + return document.querySelector(selector).disabled; + }, 'vn-textfield[ng-model="$ctrl.client.socialName"] > div'); + + expect(result).toBeFalsy(); + }); + }); +}); diff --git a/e2e/paths/02-client-module/13_log.spec.js b/e2e/paths/02-client-module/13_log.spec.js new file mode 100644 index 000000000..60ab6e7bc --- /dev/null +++ b/e2e/paths/02-client-module/13_log.spec.js @@ -0,0 +1,51 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client log path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('employee', 'client') + .accessToSearchResult('DavidCharlesHaller') + .accessToSection('client.card.basicData'); + }); + + it('should update the clients name', async() => { + let result = await nightmare + .clearInput(selectors.clientBasicData.nameInput) + .write(selectors.clientBasicData.nameInput, 'this is a test') + .waitToClick(selectors.clientBasicData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should navigate to the log section', async() => { + let url = await nightmare + .waitToClick(selectors.clientLog.logButton) + .waitForURL('log') + .parsedUrl(); + + expect(url.hash).toContain('log'); + }); + + it('should check the previous value of the last logged change', async() => { + let lastModificationPreviousValue = await nightmare + .waitToGetProperty(selectors.clientLog.lastModificationPreviousValue, 'innerText'); + + expect(lastModificationPreviousValue).toContain('DavidCharlesHaller'); + }); + + it('should check the current value of the last logged change', async() => { + let lastModificationPreviousValue = await nightmare + .waitToGetProperty(selectors.clientLog.lastModificationPreviousValue, 'innerText'); + + let lastModificationCurrentValue = await nightmare + .waitToGetProperty(selectors.clientLog.lastModificationCurrentValue, 'innerText'); + + + expect(lastModificationPreviousValue).toEqual('name: DavidCharlesHaller'); + expect(lastModificationCurrentValue).toEqual('name: this is a test'); + }); +}); diff --git a/e2e/paths/02-client-module/14_balance.spec.js b/e2e/paths/02-client-module/14_balance.spec.js new file mode 100644 index 000000000..56e1336c8 --- /dev/null +++ b/e2e/paths/02-client-module/14_balance.spec.js @@ -0,0 +1,162 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client balance path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('administrative', 'client') + .accessToSearchResult('Petter Parker'); + }); + + it('should now edit the local user config data', async() => { + let result = await nightmare + .waitToClick(selectors.globalItems.userMenuButton) + .autocompleteSearch(selectors.globalItems.userLocalCompany, 'CCs') + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should access to the balance section to check the data shown matches the local settings', async() => { + let result = await nightmare + .accessToSection('client.card.balance.index') + .waitToGetProperty(`${selectors.clientBalance.companyAutocomplete} input`, 'value'); + + expect(result).toEqual('CCs'); + }); + + it('should now clear the user local settings', async() => { + let result = await nightmare + .waitToClick(selectors.globalItems.userMenuButton) + .waitToClick(selectors.globalItems.userConfigThirdAutocompleteClear) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should click the new payment button', async() => { + let url = await nightmare + .reloadSection('client.card.balance.index') + .waitToClick(selectors.clientBalance.newPaymentButton) + .waitForURL('/balance') + .parsedUrl(); + + expect(url.hash).toContain('/balance'); + }); + + it('should create a new payment that clears the debt', async() => { + let result = await nightmare + .autocompleteSearch(selectors.clientBalance.newPaymentBank, 'Pay on receipt') + .waitToClick(selectors.clientBalance.saveButton) + .waitForLastSnackbar(); + + expect(result).toContain('Data saved!'); + }); + + it('should check balance is now 0 and the company is now VNL becouse the user local settings were removed', async() => { + let company = await nightmare + .waitForSpinnerLoad() + .waitToGetProperty(`${selectors.clientBalance.companyAutocomplete} input`, 'value'); + + let firstBalanceLine = await nightmare + .waitToGetProperty(selectors.clientBalance.firstBalanceLine, 'innerText'); + + + expect(company).toEqual('VNL'); + expect(firstBalanceLine).toContain('0.00'); + }); + + it('should now click the new payment button', async() => { + let url = await nightmare + .waitToClick(selectors.clientBalance.newPaymentButton) + .waitForURL('/balance') + .parsedUrl(); + + expect(url.hash).toContain('/balance'); + }); + + it('should create a new payment that sets the balance to positive value', async() => { + let result = await nightmare + .clearInput(selectors.clientBalance.newPaymentAmountInput) + .write(selectors.clientBalance.newPaymentAmountInput, '100') + .waitToClick(selectors.clientBalance.saveButton) + .waitForLastSnackbar(); + + expect(result).toContain('Data saved!'); + }); + + it('should check balance is now -100', async() => { + let result = await nightmare + .waitToGetProperty(selectors.clientBalance.firstBalanceLine, 'innerText'); + + expect(result).toContain('-€100.00'); + }); + + it('should again click the new payment button', async() => { + let url = await nightmare + .waitToClick(selectors.clientBalance.newPaymentButton) + .waitForURL('/balance') + .parsedUrl(); + + expect(url.hash).toContain('/balance'); + }); + + it('should create a new payment that sets the balance back to the original negative value', async() => { + let result = await nightmare + .clearInput(selectors.clientBalance.newPaymentAmountInput) + .write(selectors.clientBalance.newPaymentAmountInput, '-150') + .waitToClick(selectors.clientBalance.saveButton) + .waitForLastSnackbar(); + + expect(result).toContain('Data saved!'); + }); + + it('should check balance is now 50', async() => { + let result = await nightmare + .waitToGetProperty(selectors.clientBalance.firstBalanceLine, 'innerText'); + + expect(result).toEqual('€50.00'); + }); + + it('should now click on the Clients button of the top bar menu', async() => { + let url = await nightmare + .waitForLogin('employee') + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.clientsButton) + .wait(selectors.clientsIndex.createClientButton) + .parsedUrl(); + + expect(url.hash).toEqual('#!/client/index'); + }); + + it('should now search for the user Petter Parker', async() => { + let resultCount = await nightmare + .write(selectors.clientsIndex.searchClientInput, 'Petter Parker') + .waitToClick(selectors.clientsIndex.searchButton) + .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) + .countElement(selectors.clientsIndex.searchResult); + + expect(resultCount).toEqual(1); + }); + + it(`should click on the search result to access to the client's balance`, async() => { + let url = await nightmare + .waitForTextInElement(selectors.clientsIndex.searchResult, 'Petter Parker') + .waitToClick(selectors.clientsIndex.searchResult) + .waitToClick(selectors.clientBalance.balanceButton) + .waitForURL('/balance') + .parsedUrl(); + + expect(url.hash).toContain('/balance'); + }); + + it('should not be able to click the new payment button as it isnt present', async() => { + let result = await nightmare + .exists(selectors.clientBalance.newPaymentButton); + + expect(result).toBeFalsy(); + }); +}); diff --git a/e2e/paths/02-client-module/15_user_config.spec.js b/e2e/paths/02-client-module/15_user_config.spec.js new file mode 100644 index 000000000..d47e4a447 --- /dev/null +++ b/e2e/paths/02-client-module/15_user_config.spec.js @@ -0,0 +1,120 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('User config', () => { + const nightmare = createNightmare(); + + describe('as salesPerson', () => { + beforeAll(() => { + nightmare + .waitForLogin('salesPerson'); + }); + + it('should now open the user config form to check the settings', async() => { + let userLocalWarehouse = await nightmare + .waitToClick(selectors.globalItems.userMenuButton) + .getProperty(`${selectors.globalItems.userLocalWarehouse} input`, 'value'); + + let userLocalBank = await nightmare + .getProperty(`${selectors.globalItems.userLocalBank} input`, 'value'); + + let userLocalCompany = await nightmare + .getProperty(`${selectors.globalItems.userLocalCompany} input`, 'value'); + + let userWarehouse = await nightmare + .waitToGetProperty(`${selectors.globalItems.userWarehouse} input`, 'value'); + + let userCompany = await nightmare + .waitToGetProperty(`${selectors.globalItems.userCompany} input`, 'value'); + + expect(userLocalWarehouse).toEqual(''); + expect(userLocalBank).toEqual(''); + expect(userLocalCompany).toEqual(''); + expect(userWarehouse).toEqual('Warehouse Three'); + expect(userCompany).toEqual('VNH'); + }); + }); + + describe('as employee', () => { + beforeAll(() => { + nightmare + .waitForLogin('employee'); + }); + + it('should open the user config form to check the settings', async() => { + let userLocalWarehouse = await nightmare + .waitToClick(selectors.globalItems.userMenuButton) + .getProperty(`${selectors.globalItems.userLocalWarehouse} input`, 'value'); + + let userLocalBank = await nightmare + .getProperty(`${selectors.globalItems.userLocalBank} input`, 'value'); + + let userLocalCompany = await nightmare + .getProperty(`${selectors.globalItems.userLocalCompany} input`, 'value'); + + let userWarehouse = await nightmare + .waitToGetProperty(`${selectors.globalItems.userWarehouse} input`, 'value'); + + let userCompany = await nightmare + .waitToGetProperty(`${selectors.globalItems.userCompany} input`, 'value'); + + expect(userLocalWarehouse).toEqual(''); + expect(userLocalBank).toEqual(''); + expect(userLocalCompany).toEqual(''); + expect(userWarehouse).toEqual('Warehouse Two'); + expect(userCompany).toEqual('CCs'); + }); + + it('should now edit the user config data', async() => { + let result = await nightmare + .autocompleteSearch(selectors.globalItems.userLocalWarehouse, 'Warehouse Four') + .autocompleteSearch(selectors.globalItems.userLocalBank, 'Pay on receipt') + .autocompleteSearch(selectors.globalItems.userLocalCompany, 'VNL') + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + }); + + describe('as salesPerson 2nd run', () => { + beforeAll(() => { + nightmare + .waitForLogin('salesPerson'); + }); + + it('should again open the user config form to check the local settings', async() => { + let userLocalWarehouse = await nightmare + .waitToClick(selectors.globalItems.userMenuButton) + .waitToGetProperty(`${selectors.globalItems.userLocalWarehouse} input`, 'value'); + + let userLocalBank = await nightmare + .waitToGetProperty(`${selectors.globalItems.userLocalBank} input`, 'value'); + + let userLocalCompany = await nightmare + .waitToGetProperty(`${selectors.globalItems.userLocalCompany} input`, 'value'); + + let userWarehouse = await nightmare + .waitToGetProperty(`${selectors.globalItems.userWarehouse} input`, 'value'); + + let userCompany = await nightmare + .waitToGetProperty(`${selectors.globalItems.userCompany} input`, 'value'); + + expect(userLocalWarehouse).toContain('Warehouse Four'); + expect(userLocalBank).toContain('Pay on receipt'); + expect(userLocalCompany).toContain('VNL'); + expect(userWarehouse).toEqual('Warehouse Three'); + expect(userCompany).toEqual('VNH'); + }); + + it('should now clear the local settings', async() => { + let result = await nightmare + .waitToClick(selectors.globalItems.userMenuButton) + .waitToClick(selectors.globalItems.userConfigFirstAutocompleteClear) + .waitToClick(selectors.globalItems.userConfigSecondAutocompleteClear) + .waitToClick(selectors.globalItems.userConfigThirdAutocompleteClear) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + }); +}); diff --git a/e2e/paths/02-client-module/16_web_payment.spec.js b/e2e/paths/02-client-module/16_web_payment.spec.js new file mode 100644 index 000000000..3e9a26b75 --- /dev/null +++ b/e2e/paths/02-client-module/16_web_payment.spec.js @@ -0,0 +1,40 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client web Payment', () => { + const nightmare = createNightmare(); + + describe('as employee', () => { + beforeAll(() => { + nightmare + .loginAndModule('employee', 'client') + .accessToSearchResult('Tony Stark') + .accessToSection('client.card.webPayment'); + }); + + it('should not be able to confirm payments', async() => { + let exists = await nightmare + .exists(selectors.webPayment.confirmFirstPaymentButton); + + expect(exists).toBeFalsy(); + }); + }); + + describe('as administrative', () => { + beforeAll(() => { + nightmare + .loginAndModule('administrative', 'client') + .accessToSearchResult('Tony Stark') + .accessToSection('client.card.webPayment'); + }); + + it('should be able to confirm payments', async() => { + let exists = await nightmare + .waitToClick(selectors.webPayment.confirmFirstPaymentButton) + .wait(selectors.webPayment.firstPaymentConfirmed) + .exists(selectors.webPayment.firstPaymentConfirmed); + + expect(exists).toBeTruthy(); + }); + }); +}); diff --git a/e2e/paths/02-client-module/17_dms.spec.js b/e2e/paths/02-client-module/17_dms.spec.js new file mode 100644 index 000000000..236401cf4 --- /dev/null +++ b/e2e/paths/02-client-module/17_dms.spec.js @@ -0,0 +1,33 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Client DMS', () => { + const nightmare = createNightmare(); + + describe('as salesPerson', () => { + beforeAll(() => { + nightmare + .loginAndModule('salesPerson', 'client') + .accessToSearchResult('Tony Stark') + .accessToSection('client.card.dms.index'); + }); + + it('should delete de first file', async() => { + let result = await nightmare + .waitToClick(selectors.dms.deleteFileButton) + .waitToClick(selectors.dms.acceptDeleteButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should click on the first document line worker name making the descriptor visible`, async() => { + const visible = await nightmare + .waitToClick(selectors.dms.firstDocWorker) + .wait(selectors.dms.firstDocWorkerDescriptor) + .isVisible(selectors.dms.firstDocWorkerDescriptor); + + expect(visible).toBeTruthy(); + }); + }); +}); diff --git a/e2e/paths/03-worker-module/01_pbx.spec.js b/e2e/paths/03-worker-module/01_pbx.spec.js new file mode 100644 index 000000000..49d4db133 --- /dev/null +++ b/e2e/paths/03-worker-module/01_pbx.spec.js @@ -0,0 +1,33 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Worker pbx path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('hr', 'worker') + .accessToSearchResult('employee') + .accessToSection('worker.card.pbx'); + }); + + it('should receive an error when the extension exceeds 4 characters', async() => { + const result = await nightmare + .write(selectors.workerPbx.extensionInput, 55555) + + .waitToClick(selectors.workerPbx.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Extension format is invalid'); + }); + + it('should sucessfully save the changes', async() => { + const result = await nightmare + .clearInput(selectors.workerPbx.extensionInput) + .write(selectors.workerPbx.extensionInput, 4444) + .waitToClick(selectors.workerPbx.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved! User must access web'); + }); +}); diff --git a/e2e/paths/03-worker-module/02_time_control.spec.js b/e2e/paths/03-worker-module/02_time_control.spec.js new file mode 100644 index 000000000..706fc2a74 --- /dev/null +++ b/e2e/paths/03-worker-module/02_time_control.spec.js @@ -0,0 +1,425 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Worker time control path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('hr', 'worker') + .accessToSearchResult('HankPym') + .accessToSection('worker.card.timeControl'); + }); + + describe('as HHRR', () => { + describe('on Monday', () => { + it('should scan in Hank Pym', async() => { + const scanTime = '07:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.mondayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.firstEntryOfMonday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should scan out Hank Pym for break`, async() => { + const scanTime = '10:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.mondayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.secondEntryOfMonday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should scan in Hank Pym for a wrong hour and forget to scan in from the break`, async() => { + const scanTime = '18:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.mondayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.thirdEntryOfMonday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should delete the wrong entry for Hank Pym`, async() => { + const wrongScanTime = '18:00'; + const result = await nightmare + .waitForTextInElement(selectors.workerTimeControl.thirdEntryOfMonday, wrongScanTime) + .waitToClick(selectors.workerTimeControl.thirdEntryOfMondayDelete) + .waitToClick(selectors.workerTimeControl.acceptDeleteDialog) + .waitForLastSnackbar(); + + expect(result).toEqual('Entry removed'); + }); + + it(`should scan out Hank Pym to leave early`, async() => { + const scanTime = '14:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.mondayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.thirdEntryOfMonday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should add the break's scan in for Hank Pym and be in the right order`, async() => { + const scanTime = '10:20'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.mondayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.fourthEntryOfMonday, 'innerText'); + + expect(result).toEqual('14:00'); + }); + + it(`should the third entry be the scan in from break`, async() => { + const scanTime = '10:20'; + const result = await nightmare + .waitToGetProperty(selectors.workerTimeControl.thirdEntryOfMonday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should check Hank Pym worked 8 hours`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.workerTimeControl.mondayWorkedHours, '07:00 h.') + .waitToGetProperty(selectors.workerTimeControl.mondayWorkedHours, 'innerText'); + + expect(result).toEqual('07:00 h.'); + }); + }); + + describe('on Tuesday', () => { + it('should happily scan in Hank Pym', async() => { + const scanTime = '08:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.tuesdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.firstEntryOfTuesday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should happily scan out Hank Pym for break`, async() => { + const scanTime = '10:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.tuesdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.secondEntryOfTuesday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should happily scan in Hank Pym from the break`, async() => { + const scanTime = '10:20'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.tuesdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.thirdEntryOfTuesday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should happily scan out Hank Pym for the day`, async() => { + const scanTime = '16:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.tuesdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.fourthEntryOfTuesday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should check Hank Pym worked 8 happy hours`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.workerTimeControl.tuesdayWorkedHours, '08:00 h.') + .waitToGetProperty(selectors.workerTimeControl.tuesdayWorkedHours, 'innerText'); + + expect(result).toEqual('08:00 h.'); + }); + }); + + describe('on Wednesday', () => { + it('should cheerfully scan in Hank Pym', async() => { + const scanTime = '09:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.wednesdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.firstEntryOfWednesday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should cheerfully scan out Hank Pym for break`, async() => { + const scanTime = '10:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.wednesdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.secondEntryOfWednesday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should cheerfully scan in Hank Pym from the break`, async() => { + const scanTime = '10:20'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.wednesdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.thirdEntryOfWednesday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should cheerfully scan out Hank Pym for the day`, async() => { + const scanTime = '17:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.wednesdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.fourthEntryOfWednesday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should check Hank Pym worked 8 cheerfull hours`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.workerTimeControl.wednesdayWorkedHours, '08:00 h.') + .waitToGetProperty(selectors.workerTimeControl.wednesdayWorkedHours, 'innerText'); + + expect(result).toEqual('08:00 h.'); + }); + }); + + describe('on Thursday', () => { + it('should joyfully scan in Hank Pym', async() => { + const scanTime = '09:59'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.thursdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.firstEntryOfThursday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should joyfully scan out Hank Pym for break`, async() => { + const scanTime = '10:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.thursdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.secondEntryOfThursday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should joyfully scan in Hank Pym from the break`, async() => { + const scanTime = '10:20'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.thursdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.thirdEntryOfThursday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should joyfully scan out Hank Pym for the day`, async() => { + const scanTime = '17:59'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.thursdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.fourthEntryOfThursday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should check Hank Pym worked 8 joyfull hours`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.workerTimeControl.thursdayWorkedHours, '08:00 h.') + .waitToGetProperty(selectors.workerTimeControl.thursdayWorkedHours, 'innerText'); + + expect(result).toEqual('08:00 h.'); + }); + }); + + describe('on Friday', () => { + it('should smilingly scan in Hank Pym', async() => { + const scanTime = '07:30'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.fridayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.firstEntryOfFriday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should smilingly scan out Hank Pym for break`, async() => { + const scanTime = '10:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.fridayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.secondEntryOfFriday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should smilingly scan in Hank Pym from the break`, async() => { + const scanTime = '10:20'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.fridayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.thirdEntryOfFriday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should smilingly scan out Hank Pym for the day`, async() => { + const scanTime = '15:30'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.fridayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.fourthEntryOfFriday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should check Hank Pym worked 8 hours with a smile on his face`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.workerTimeControl.fridayWorkedHours, '08:00 h.') + .waitToGetProperty(selectors.workerTimeControl.fridayWorkedHours, 'innerText'); + + expect(result).toEqual('08:00 h.'); + }); + }); + }); + + describe('as hr', () => { + describe('on Saturday', () => { + beforeAll(() => { + nightmare + .loginAndModule('hr', 'worker') + .accessToSearchResult('HankPym') + .accessToSection('worker.card.timeControl'); + }); + + it('should lovingly scan in Hank Pym', async() => { + const scanTime = '06:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.saturdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.firstEntryOfSaturday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should lovingly scan out Hank Pym for the day with no break to leave a bit early`, async() => { + const scanTime = '13:40'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.saturdayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.secondEntryOfSaturday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should check Hank Pym worked 8 hours with all his will`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.workerTimeControl.saturdayWorkedHours, '08:00 h.') + .waitToGetProperty(selectors.workerTimeControl.saturdayWorkedHours, 'innerText'); + + expect(result).toEqual('08:00 h.'); + }); + }); + + describe('on Sunday', () => { + it('should gladly scan in Hank Pym', async() => { + const scanTime = '05:00'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.sundayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.firstEntryOfSunday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should gladly scan out Hank Pym for the day with no break to leave a bit early`, async() => { + const scanTime = '12:40'; + const result = await nightmare + .waitToClick(selectors.workerTimeControl.sundayAddTimeButton) + .pickTime(selectors.workerTimeControl.timeDialogInput, scanTime) + .waitToClick(selectors.workerTimeControl.confirmButton) + .waitToGetProperty(selectors.workerTimeControl.secondEntryOfSunday, 'innerText'); + + expect(result).toEqual(scanTime); + }); + + it(`should check Hank Pym worked 8 glad hours`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.workerTimeControl.sundayWorkedHours, '08:00 h.') + .waitToGetProperty(selectors.workerTimeControl.sundayWorkedHours, 'innerText'); + + expect(result).toEqual('08:00 h.'); + }); + + it(`should check Hank Pym doesn't have hours set on the next months first week`, async() => { + const wholeWeekHours = await nightmare + .waitToClick(selectors.workerTimeControl.nextMonthButton) + .waitToClick(selectors.workerTimeControl.secondWeekDay) + .waitForTextInElement(selectors.workerTimeControl.weekWorkedHours, '00:00 h.') + .waitToGetProperty(selectors.workerTimeControl.weekWorkedHours, 'innerText'); + + expect(wholeWeekHours).toEqual('00:00 h.'); + }); + + it(`should check he didn't scan in this week yet`, async() => { + const wholeWeekHours = await nightmare + .waitToClick(selectors.workerTimeControl.navigateBackToIndex) + .accessToSearchResult('salesBoss') + .accessToSection('worker.card.timeControl') + .waitToGetProperty(selectors.workerTimeControl.weekWorkedHours, 'innerText'); + + expect(wholeWeekHours).toEqual('00:00 h.'); + }); + }); + }); + + describe('after all this amazing week', () => { + beforeAll(() => { + nightmare + .loginAndModule('HankPym', 'worker') + .accessToSearchResult('HankPym') + .accessToSection('worker.card.timeControl'); + }); + + it('should Hank Pym check his hours are alright', async() => { + const wholeWeekHours = await nightmare + .waitForTextInElement(selectors.workerTimeControl.weekWorkedHours, '55:00 h.') + .waitToGetProperty(selectors.workerTimeControl.weekWorkedHours, 'innerText'); + + expect(wholeWeekHours).toEqual('55:00 h.'); + }); + }); +}); diff --git a/e2e/paths/04-item-module/01_summary.spec.js b/e2e/paths/04-item-module/01_summary.spec.js new file mode 100644 index 000000000..8f493bfac --- /dev/null +++ b/e2e/paths/04-item-module/01_summary.spec.js @@ -0,0 +1,203 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Item summary path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('employee', 'item'); + }); + + it('should search for an item', async() => { + const result = await nightmare + .clearInput(selectors.itemsIndex.searchItemInput) + .write(selectors.itemsIndex.searchItemInput, 'Ranged weapon longbow 2m') + .waitToClick(selectors.itemsIndex.searchButton) + .waitForNumberOfElements(selectors.itemsIndex.searchResult, 1) + .countElement(selectors.itemsIndex.searchResult); + + expect(result).toEqual(1); + }); + + it(`should click on the search result summary button to open the item summary popup`, async() => { + const isVisible = await nightmare + .waitForTextInElement(selectors.itemsIndex.searchResult, 'Ranged weapon longbow 2m') + .waitToClick(selectors.itemsIndex.searchResultPreviewButton) + .isVisible(selectors.itemSummary.basicData); + + expect(isVisible).toBeTruthy(); + }); + + it(`should check the item summary preview shows fields from basic data`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.itemSummary.basicData, 'Ranged weapon longbow 2m') + .waitToGetProperty(selectors.itemSummary.basicData, 'innerText'); + + expect(result).toContain('Ranged weapon longbow 2m'); + }); + + it(`should check the item summary preview shows fields from tags`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.itemSummary.tags, 'Brown') + .waitToGetProperty(selectors.itemSummary.tags, 'innerText'); + + expect(result).toContain('Brown'); + }); + + it(`should check the item summary preview shows fields from niche`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.itemSummary.niche, 'A1') + .waitToGetProperty(selectors.itemSummary.niche, 'innerText'); + + expect(result).toContain('A1'); + }); + + it(`should check the item summary preview shows fields from botanical`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.itemSummary.botanical, 'Hedera helix') + .waitToGetProperty(selectors.itemSummary.botanical, 'innerText'); + + expect(result).toContain('Hedera helix'); + }); + + it(`should check the item summary preview shows fields from barcode`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.itemSummary.barcode, '1') + .waitToGetProperty(selectors.itemSummary.barcode, 'innerText'); + + expect(result).toContain('1'); + }); + + it(`should close the summary popup`, async() => { + const result = await nightmare + .mousedown(selectors.itemsIndex.closeItemSummaryPreview) + .waitUntilNotPresent(selectors.itemSummary.basicData) + .visible(selectors.itemSummary.basicData); + + expect(result).toBeFalsy(); + }); + + it('should search for other item', async() => { + const result = await nightmare + .clearInput('vn-searchbar input') + .waitToClick(selectors.itemsIndex.searchButton) + .write(selectors.itemsIndex.searchItemInput, 'Melee weapon combat fist 15cm') + .waitToClick(selectors.itemsIndex.searchButton) + .waitForNumberOfElements(selectors.itemsIndex.searchResult, 1) + .countElement(selectors.itemsIndex.searchResult); + + expect(result).toEqual(1); + }); + + it(`should now click on the search result summary button to open the item summary popup`, async() => { + const isVisible = await nightmare + .waitForTextInElement(selectors.itemsIndex.searchResult, 'Melee weapon combat fist 15cm') + .waitToClick(selectors.itemsIndex.searchResultPreviewButton) + .isVisible(selectors.itemSummary.basicData); + + + expect(isVisible).toBeTruthy(); + }); + + it(`should now check the item summary preview shows fields from basic data`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.itemSummary.basicData, 'Melee weapon combat fist 15cm') + .waitToGetProperty(selectors.itemSummary.basicData, 'innerText'); + + expect(result).toContain('Melee weapon combat fist 15cm'); + }); + + it(`should now check the item summary preview shows fields from tags`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.itemSummary.tags, 'Silver') + .waitToGetProperty(selectors.itemSummary.tags, 'innerText'); + + expect(result).toContain('Silver'); + }); + + it(`should now check the item summary preview shows fields from niche`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.itemSummary.niche, 'A4') + .waitToGetProperty(selectors.itemSummary.niche, 'innerText'); + + expect(result).toContain('A4'); + }); + + it(`should now check the item summary preview shows fields from botanical`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.itemSummary.botanical, '-') + .waitToGetProperty(selectors.itemSummary.botanical, 'innerText'); + + expect(result).toContain('-'); + }); + + it(`should now check the item summary preview shows fields from barcode`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.itemSummary.barcode, '4') + .waitToGetProperty(selectors.itemSummary.barcode, 'innerText'); + + expect(result).toContain('4'); + }); + + it(`should now close the summary popup`, async() => { + const result = await nightmare + .mousedown(selectors.itemsIndex.closeItemSummaryPreview) + .waitUntilNotPresent(selectors.itemSummary.basicData) + .visible(selectors.itemSummary.basicData); + + expect(result).toBeFalsy(); + }); + + it(`should navigate to the one of the items detailed section`, async() => { + const url = await nightmare + .waitToClick(selectors.itemsIndex.searchResult) + .waitForURL('summary') + .parsedUrl(); + + expect(url.hash).toContain('summary'); + }); + + it(`should check the descritor edit button is not visible for employee`, async() => { + const visibleButton = await nightmare + .isVisible(selectors.itemDescriptor.editButton); + + expect(visibleButton).toBeFalsy(); + }); + + it(`should check the item summary shows fields from basic data section`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.itemSummary.basicData, 'Melee weapon combat fist 15cm') + .waitToGetProperty(selectors.itemSummary.basicData, 'innerText'); + + expect(result).toContain('Melee weapon combat fist 15cm'); + }); + + it(`should check the item summary shows fields from tags section`, async() => { + const result = await nightmare + .waitToGetProperty(selectors.itemSummary.tags, 'innerText'); + + expect(result).toContain('Silver'); + }); + + it(`should check the item summary shows fields from niches section`, async() => { + const result = await nightmare + .waitToGetProperty(selectors.itemSummary.niche, 'innerText'); + + expect(result).toContain('One A4'); + }); + + it(`should check the item summary shows fields from botanical section`, async() => { + const result = await nightmare + .waitToGetProperty(selectors.itemSummary.botanical, 'innerText'); + + expect(result).toContain('-'); + }); + + it(`should check the item summary shows fields from barcodes section`, async() => { + const result = await nightmare + .waitToGetProperty(selectors.itemSummary.barcode, 'innerText'); + + expect(result).toContain('4'); + }); +}); diff --git a/e2e/paths/04-item-module/02_basic_data.spec.js b/e2e/paths/04-item-module/02_basic_data.spec.js new file mode 100644 index 000000000..02f09b626 --- /dev/null +++ b/e2e/paths/04-item-module/02_basic_data.spec.js @@ -0,0 +1,104 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Item Edit basic data path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('buyer', 'item') + .accessToSearchResult('Melee weapon combat fist 15cm') + .accessToSection('item.card.basicData'); + }); + + it(`should check the descritor edit button is visible for buyer`, async() => { + const visibleButton = await nightmare + .isVisible(selectors.itemDescriptor.editButton); + + expect(visibleButton).toBeTruthy(); + }); + + it(`should edit the item basic data`, async() => { + const result = await nightmare + .clearInput(selectors.itemBasicData.nameInput) + .write(selectors.itemBasicData.nameInput, 'Rose of Purity') + .autocompleteSearch(selectors.itemBasicData.typeAutocomplete, 'Anthurium') + .autocompleteSearch(selectors.itemBasicData.intrastatAutocomplete, 'Coral y materiales similares') + .clearInput(selectors.itemBasicData.relevancyInput) + .write(selectors.itemBasicData.relevancyInput, '1') + .autocompleteSearch(selectors.itemBasicData.originAutocomplete, 'Spain') + .autocompleteSearch(selectors.itemBasicData.expenseAutocomplete, 'Alquiler VNH') + .clearInput(selectors.itemBasicData.longNameInput) + .write(selectors.itemBasicData.longNameInput, 'RS Rose of Purity') + .waitToClick(selectors.itemBasicData.isActiveCheckbox) + .waitToClick(selectors.itemBasicData.priceInKgCheckbox) + .waitToClick(selectors.itemBasicData.submitBasicDataButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }, 15000); + + it(`should confirm the item name was edited`, async() => { + const result = await nightmare + .reloadSection('item.card.basicData') + .waitToGetProperty(selectors.itemBasicData.nameInput, 'value'); + + expect(result).toEqual('Rose of Purity'); + }); + + it(`should confirm the item type was edited`, async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.itemBasicData.typeAutocomplete} input`, 'value'); + + expect(result).toEqual('Anthurium'); + }); + + it(`should confirm the item intrastad was edited`, async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.itemBasicData.intrastatAutocomplete} input`, 'value'); + + expect(result).toEqual('5080000 Coral y materiales similares'); + }); + + it(`should confirm the item relevancy was edited`, async() => { + const result = await nightmare + .waitToGetProperty(selectors.itemBasicData.relevancyInput, 'value'); + + expect(result).toEqual('1'); + }); + + it(`should confirm the item origin was edited`, async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.itemBasicData.originAutocomplete} input`, 'value'); + + expect(result).toEqual('Spain'); + }); + + it(`should confirm the item expence was edited`, async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.itemBasicData.expenseAutocomplete} input`, 'value'); + + expect(result).toEqual('Alquiler VNH'); + }); + + it(`should confirm the item long name was edited`, async() => { + const result = await nightmare + .waitToGetProperty(selectors.itemBasicData.longNameInput, 'value'); + + expect(result).toEqual('RS Rose of Purity'); + }); + + it('should confirm isActive checkbox is unchecked', async() => { + const result = await nightmare + .checkboxState(selectors.itemBasicData.isActiveCheckbox); + + expect(result).toBe('unchecked'); + }); + + it('should confirm the priceInKg checkbox is checked', async() => { + const result = await nightmare + .checkboxState(selectors.itemBasicData.priceInKgCheckbox); + + expect(result).toBe('checked'); + }); +}); diff --git a/e2e/paths/04-item-module/03_tax.spec.js b/e2e/paths/04-item-module/03_tax.spec.js new file mode 100644 index 000000000..903d05f10 --- /dev/null +++ b/e2e/paths/04-item-module/03_tax.spec.js @@ -0,0 +1,62 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Item edit tax path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('buyer', 'item') + .accessToSearchResult('Ranged weapon longbow 2m') + .accessToSection('item.card.tax'); + }); + + it(`should add the item tax to all countries`, async() => { + const result = await nightmare + .autocompleteSearch(selectors.itemTax.firstClassAutocomplete, 'General VAT') + .autocompleteSearch(selectors.itemTax.secondClassAutocomplete, 'General VAT') + .autocompleteSearch(selectors.itemTax.thirdClassAutocomplete, 'General VAT') + .waitToClick(selectors.itemTax.submitTaxButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should confirm the first item tax class was edited`, async() => { + const firstVatType = await nightmare + .reloadSection('item.card.tax') + .waitToGetProperty(`${selectors.itemTax.firstClassAutocomplete} input`, 'value'); + + expect(firstVatType).toEqual('General VAT'); + }); + + it(`should confirm the second item tax class was edited`, async() => { + const secondVatType = await nightmare + .waitToGetProperty(`${selectors.itemTax.secondClassAutocomplete} input`, 'value'); + + expect(secondVatType).toEqual('General VAT'); + }); + + it(`should confirm the third item tax class was edited`, async() => { + const thirdVatType = await nightmare + .waitToGetProperty(`${selectors.itemTax.thirdClassAutocomplete} input`, 'value'); + + expect(thirdVatType).toEqual('General VAT'); + }); + + it(`should edit the first class without saving the form`, async() => { + const firstVatType = await nightmare + .autocompleteSearch(selectors.itemTax.firstClassAutocomplete, 'Reduced VAT') + .waitToGetProperty(`${selectors.itemTax.firstClassAutocomplete} input`, 'value'); + + expect(firstVatType).toEqual('Reduced VAT'); + }); + + it(`should now click the undo changes button and see the changes works`, async() => { + const firstVatType = await nightmare + .waitToClick(selectors.itemTax.undoChangesButton) + .waitToGetProperty(`${selectors.itemTax.firstClassAutocomplete} input`, 'value'); + + expect(firstVatType).toEqual('General VAT'); + }); +}); diff --git a/e2e/paths/04-item-module/04_tags.spec.js b/e2e/paths/04-item-module/04_tags.spec.js new file mode 100644 index 000000000..8c9c9bb94 --- /dev/null +++ b/e2e/paths/04-item-module/04_tags.spec.js @@ -0,0 +1,76 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Item create tags path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('buyer', 'item') + .accessToSearchResult('Ranged weapon longbow 2m') + .accessToSection('item.card.tags'); + }); + + it(`should create a new tag and delete a former one`, async() => { + const result = await nightmare + .waitToClick(selectors.itemTags.fourthRemoveTagButton) + .waitToClick(selectors.itemTags.addItemTagButton) + .autocompleteSearch(selectors.itemTags.seventhTagAutocomplete, 'Ancho de la base') + .write(selectors.itemTags.seventhValueInput, '50') + .clearInput(selectors.itemTags.seventhRelevancyInput) + .write(selectors.itemTags.seventhRelevancyInput, '4') + .waitToClick(selectors.itemTags.submitItemTagsButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should confirm the fourth row data is the expected one`, async() => { + let result = await nightmare + .reloadSection('item.card.tags') + .wait('vn-item-tags') + .waitToGetProperty(`${selectors.itemTags.fourthTagAutocomplete} input`, 'value'); + + expect(result).toEqual('Ancho de la base'); + + result = await nightmare + .waitToGetProperty(selectors.itemTags.fourthValueInput, 'value'); + + expect(result).toEqual('50'); + + result = await nightmare + .waitToGetProperty(selectors.itemTags.fourthRelevancyInput, 'value'); + + expect(result).toEqual('4'); + }); + + it(`should confirm the fifth row data is the expected one`, async() => { + let tag = await nightmare + .waitToGetProperty(`${selectors.itemTags.fifthTagAutocomplete} input`, 'value'); + + let value = await nightmare + .waitToGetProperty(selectors.itemTags.fifthValueInput, 'value'); + + let relevancy = await nightmare + .waitToGetProperty(selectors.itemTags.fifthRelevancyInput, 'value'); + + expect(tag).toEqual('Color'); + expect(value).toEqual('Brown'); + expect(relevancy).toEqual('5'); + }); + + it(`should confirm the sixth row data is the expected one`, async() => { + let tag = await nightmare + .waitToGetProperty(`${selectors.itemTags.sixthTagAutocomplete} input`, 'value'); + + let value = await nightmare + .waitToGetProperty(selectors.itemTags.sixthValueInput, 'value'); + + let relevancy = await nightmare + .waitToGetProperty(selectors.itemTags.sixthRelevancyInput, 'value'); + + expect(tag).toEqual('Categoria'); + expect(value).toEqual('+1 precission'); + expect(relevancy).toEqual('6'); + }); +}); diff --git a/e2e/paths/04-item-module/05_niche.spec.js b/e2e/paths/04-item-module/05_niche.spec.js new file mode 100644 index 000000000..042b28638 --- /dev/null +++ b/e2e/paths/04-item-module/05_niche.spec.js @@ -0,0 +1,62 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Item create niche path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('buyer', 'item') + .accessToSearchResult('Ranged weapon longbow 2m') + .accessToSection('item.card.niche'); + }); + + it(`should click create a new niche and delete a former one`, async() => { + const result = await nightmare + .waitForTextInInput(`${selectors.itemNiches.firstWarehouseAutocomplete} input`, 'Warehouse One') + .waitToClick(selectors.itemNiches.addNicheButton) + .waitToClick(selectors.itemNiches.secondNicheRemoveButton) + .autocompleteSearch(selectors.itemNiches.thirdWarehouseAutocomplete, 'Warehouse Two') + .write(selectors.itemNiches.thirdCodeInput, 'A4') + .waitToClick(selectors.itemNiches.submitNichesButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should confirm the first niche is the expected one`, async() => { + let result = await nightmare + .reloadSection('item.card.niche') + .waitForTextInInput(`${selectors.itemNiches.firstWarehouseAutocomplete} input`, 'Warehouse One') + .waitToGetProperty(`${selectors.itemNiches.firstWarehouseAutocomplete} input`, 'value'); + + expect(result).toEqual('Warehouse One'); + result = await nightmare + .waitToGetProperty(selectors.itemNiches.firstCodeInput, 'value'); + + expect(result).toEqual('A1'); + }); + + it(`should confirm the second niche is the expected one`, async() => { + let result = await nightmare + .waitToGetProperty(`${selectors.itemNiches.secondWarehouseAutocomplete} input`, 'value'); + + expect(result).toEqual('Warehouse Three'); + result = await nightmare + .waitToGetProperty(selectors.itemNiches.secondCodeInput, 'value'); + + + expect(result).toEqual('A3'); + }); + + it(`should confirm the third niche is the expected one`, async() => { + let result = await nightmare + .waitToGetProperty(`${selectors.itemNiches.thirdWarehouseAutocomplete} input`, 'value'); + + expect(result).toEqual('Warehouse Two'); + result = await nightmare + .waitToGetProperty(selectors.itemNiches.thirdCodeInput, 'value'); + + expect(result).toEqual('A4'); + }); +}); diff --git a/e2e/paths/04-item-module/06_botanical.spec.js b/e2e/paths/04-item-module/06_botanical.spec.js new file mode 100644 index 000000000..864705056 --- /dev/null +++ b/e2e/paths/04-item-module/06_botanical.spec.js @@ -0,0 +1,84 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Item Create botanical path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('buyer', 'item') + .accessToSearchResult('Ranged weapon pistol 9mm') + .accessToSection('item.card.botanical'); + }); + + it(`should create a new botanical for the item`, async() => { + const result = await nightmare + .write(selectors.itemBotanical.botanicalInput, 'Cicuta maculata') + .autocompleteSearch(selectors.itemBotanical.genusAutocomplete, 'Abelia') + .autocompleteSearch(selectors.itemBotanical.speciesAutocomplete, 'dealbata') + .waitToClick(selectors.itemBotanical.submitBotanicalButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should confirm the botanical for the item was created`, async() => { + const result = await nightmare + .reloadSection('item.card.botanical') + .waitForTextInInput(selectors.itemBotanical.botanicalInput, 'Cicuta maculata') + .waitToGetProperty(selectors.itemBotanical.botanicalInput, 'value'); + + expect(result).toEqual('Cicuta maculata'); + }); + + it(`should confirm the Genus for the item was created`, async() => { + const result = await nightmare + .waitForTextInInput(`${selectors.itemBotanical.genusAutocomplete} input`, 'Abelia') + .waitToGetProperty(`${selectors.itemBotanical.genusAutocomplete} input`, 'value'); + + expect(result).toEqual('Abelia'); + }); + + it(`should confirm the Species for the item was created`, async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.itemBotanical.speciesAutocomplete} input`, 'value'); + + expect(result).toEqual('dealbata'); + }); + + it(`should edit botanical for the item`, async() => { + const result = await nightmare + .clearInput(selectors.itemBotanical.botanicalInput) + .write(selectors.itemBotanical.botanicalInput, 'Herp Derp') + .autocompleteSearch(selectors.itemBotanical.genusAutocomplete, 'Abies') + .autocompleteSearch(selectors.itemBotanical.speciesAutocomplete, 'decurrens') + .waitToClick(selectors.itemBotanical.submitBotanicalButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should confirm the botanical for the item was edited`, async() => { + const result = await nightmare + .reloadSection('item.card.botanical') + .waitForTextInInput(selectors.itemBotanical.botanicalInput, 'Herp Derp') + .waitToGetProperty(selectors.itemBotanical.botanicalInput, 'value'); + + expect(result).toEqual('Herp Derp'); + }); + + it(`should confirm the Genus for the item was edited`, async() => { + const result = await nightmare + .waitForTextInInput(`${selectors.itemBotanical.genusAutocomplete} input`, 'Abies') + .waitToGetProperty(`${selectors.itemBotanical.genusAutocomplete} input`, 'value'); + + expect(result).toEqual('Abies'); + }); + + it(`should confirm the Species for the item was edited`, async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.itemBotanical.speciesAutocomplete} input`, 'value'); + + expect(result).toEqual('decurrens'); + }); +}); diff --git a/e2e/paths/04-item-module/07_barcode.spec.js b/e2e/paths/04-item-module/07_barcode.spec.js new file mode 100644 index 000000000..db588cfe6 --- /dev/null +++ b/e2e/paths/04-item-module/07_barcode.spec.js @@ -0,0 +1,33 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Item Create barcodes path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('buyer', 'item') + .accessToSearchResult('Ranged weapon longbow 2m') + .accessToSection('item.card.itemBarcode'); + }); + + it(`should click create a new code and delete a former one`, async() => { + const result = await nightmare + .waitToClick(selectors.itemBarcodes.firstCodeRemoveButton) + .waitToClick(selectors.itemBarcodes.addBarcodeButton) + .write(selectors.itemBarcodes.thirdCodeInput, '5') + .waitToClick(selectors.itemBarcodes.submitBarcodesButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should confirm the barcode 5 is created and it is now the third barcode as the first was deleted`, async() => { + const result = await nightmare + .reloadSection('item.card.itemBarcode') + .waitForTextInInput(selectors.itemBarcodes.thirdCodeInput, '5') + .waitToGetProperty(selectors.itemBarcodes.thirdCodeInput, 'value'); + + expect(result).toEqual('5'); + }); +}); diff --git a/e2e/paths/04-item-module/08_create_and_clone.spec.js b/e2e/paths/04-item-module/08_create_and_clone.spec.js new file mode 100644 index 000000000..8f4952fb1 --- /dev/null +++ b/e2e/paths/04-item-module/08_create_and_clone.spec.js @@ -0,0 +1,131 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Item Create/Clone path', () => { + const nightmare = createNightmare(); + describe('create', () => { + beforeAll(() => { + nightmare + .loginAndModule('buyer', 'item'); + }); + + it(`should search for the item Infinity Gauntlet to confirm it isn't created yet`, async() => { + const result = await nightmare + .clearInput(selectors.itemsIndex.searchItemInput) + .write(selectors.itemsIndex.searchItemInput, 'Infinity Gauntlet') + .waitToClick(selectors.itemsIndex.searchButton) + .waitForNumberOfElements(selectors.itemsIndex.searchResult, 0) + .countElement(selectors.itemsIndex.searchResult); + + expect(result).toEqual(0); + }); + + it('should access to the create item view by clicking the create floating button', async() => { + const url = await nightmare + .waitToClick(selectors.itemsIndex.createItemButton) + .wait(selectors.itemCreateView.createButton) + .parsedUrl(); + + expect(url.hash).toEqual('#!/item/create'); + }); + + it('should return to the item index by clickig the cancel button', async() => { + const url = await nightmare + .waitToClick(selectors.itemCreateView.cancelButton) + .wait(selectors.itemsIndex.createItemButton) + .parsedUrl(); + + expect(url.hash).toEqual('#!/item/index'); + }); + + it('should now access to the create item view by clicking the create floating button', async() => { + const url = await nightmare + .waitToClick(selectors.itemsIndex.createItemButton) + .wait(selectors.itemCreateView.createButton) + .parsedUrl(); + + expect(url.hash).toEqual('#!/item/create'); + }); + + it('should create the Infinity Gauntlet item', async() => { + const result = await nightmare + .write(selectors.itemCreateView.temporalName, 'Infinity Gauntlet') + .autocompleteSearch(selectors.itemCreateView.typeAutocomplete, 'Crisantemo') + .autocompleteSearch(selectors.itemCreateView.intrastatAutocomplete, 'Coral y materiales similares') + .autocompleteSearch(selectors.itemCreateView.originAutocomplete, 'Holand') + .waitToClick(selectors.itemCreateView.createButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm Infinity Gauntlet item was created', async() => { + let result = await nightmare + .waitToGetProperty(selectors.itemBasicData.nameInput, 'value'); + + expect(result).toEqual('Infinity Gauntlet'); + + + result = await nightmare + .waitToGetProperty(`${selectors.itemBasicData.typeAutocomplete} input`, 'value'); + + expect(result).toEqual('Crisantemo'); + + result = await nightmare + .waitToGetProperty(`${selectors.itemBasicData.intrastatAutocomplete} input`, 'value'); + + expect(result).toEqual('5080000 Coral y materiales similares'); + + result = await nightmare + .waitToGetProperty(`${selectors.itemBasicData.originAutocomplete} input`, 'value'); + + expect(result).toEqual('Holand'); + }); + }); + + describe('clone', () => { + it('should return to the items index by clicking the return to items button', async() => { + const url = await nightmare + .waitToClick(selectors.itemBasicData.goToItemIndexButton) + .wait(selectors.itemsIndex.createItemButton) + .waitForURL('#!/item/index') + .parsedUrl(); + + expect(url.hash).toContain('#!/item/index'); + }); + + it(`should search for the item Infinity Gauntlet`, async() => { + const result = await nightmare + .clearInput(selectors.itemsIndex.searchItemInput) + .write(selectors.itemsIndex.searchItemInput, 'Infinity Gauntlet') + .waitToClick(selectors.itemsIndex.searchButton) + .waitForNumberOfElements(selectors.itemsIndex.searchResult, 1) + .countElement(selectors.itemsIndex.searchResult); + + expect(result).toEqual(1); + }); + + it(`should clone the Infinity Gauntlet`, async() => { + const url = await nightmare + .waitForTextInElement(selectors.itemsIndex.searchResult, 'Infinity Gauntlet') + .waitToClick(selectors.itemsIndex.searchResultCloneButton) + .waitToClick(selectors.itemsIndex.acceptClonationAlertButton) + .waitForURL('tags') + .parsedUrl(); + + expect(url.hash).toContain('tags'); + }); + + it('should search for the item Infinity Gauntlet and find two', async() => { + const result = await nightmare + .waitToClick(selectors.itemTags.goToItemIndexButton) + .clearInput(selectors.itemsIndex.searchItemInput) + .write(selectors.itemsIndex.searchItemInput, 'Infinity Gauntlet') + .waitToClick(selectors.itemsIndex.searchButton) + .waitForNumberOfElements(selectors.itemsIndex.searchResult, 2) + .countElement(selectors.itemsIndex.searchResult); + + expect(result).toEqual(2); + }); + }); +}); diff --git a/e2e/paths/04-item-module/09_regularize.spec.js b/e2e/paths/04-item-module/09_regularize.spec.js new file mode 100644 index 000000000..a83b9ef7f --- /dev/null +++ b/e2e/paths/04-item-module/09_regularize.spec.js @@ -0,0 +1,207 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Item regularize path', () => { + const nightmare = createNightmare(); + beforeAll(() => { + nightmare + .loginAndModule('employee', 'item'); + }); + + + it('should edit the user local warehouse', async() => { + let result = await nightmare + .waitForSpinnerLoad() + .waitToClick(selectors.globalItems.userMenuButton) + .autocompleteSearch(selectors.globalItems.userLocalWarehouse, 'Warehouse Four') + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should open the user config form to check the local settings', async() => { + let userLocalWarehouse = await nightmare + .waitToClick(selectors.globalItems.userMenuButton) + .waitToGetProperty(`${selectors.globalItems.userLocalWarehouse} input`, 'value'); + + expect(userLocalWarehouse).toContain('Warehouse Four'); + }); + + it('should search for an item', async() => { + const resultCount = await nightmare + .clearInput(selectors.itemsIndex.searchItemInput) + .write(selectors.itemsIndex.searchItemInput, 'Ranged weapon pistol 9mm') + .waitToClick(selectors.itemsIndex.searchButton) + .waitForNumberOfElements(selectors.itemsIndex.searchResult, 1) + .countElement(selectors.itemsIndex.searchResult); + + expect(resultCount).toEqual(1); + }); + + it(`should click on the search result to access to the item tax`, async() => { + const url = await nightmare + .waitForTextInElement(selectors.itemsIndex.searchResult, 'Ranged weapon pistol 9mm') + .waitToClick(selectors.itemsIndex.searchResult) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it('should open the regularize dialog and check the warehouse matches the local user settings', async() => { + const result = await nightmare + .waitToClick(selectors.itemDescriptor.moreMenu) + .waitToClick(selectors.itemDescriptor.moreMenuRegularizeButton) + .waitToGetProperty(`${selectors.itemDescriptor.regularizeWarehouseAutocomplete} input`, 'value'); + + expect(result).toEqual('Warehouse Four'); + }); + + it('should regularize the item', async() => { + const result = await nightmare + .write(selectors.itemDescriptor.regularizeQuantityInput, 100) + .autocompleteSearch(selectors.itemDescriptor.regularizeWarehouseAutocomplete, 'Warehouse One') + .waitToClick(selectors.itemDescriptor.regularizeSaveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should click on the Tickets button of the top bar menu', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.ticketsButton) + .wait(selectors.ticketsIndex.searchTicketInput) + .parsedUrl(); + + expect(url.hash).toEqual('#!/ticket/index'); + }); + + it('should now clear the user local settings', async() => { + let result = await nightmare + .waitToClick(selectors.globalItems.userMenuButton) + .waitToClick(selectors.globalItems.userConfigFirstAutocompleteClear) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should search for the ticket with alias missing', async() => { + const result = await nightmare + .write(selectors.ticketsIndex.searchTicketInput, 'missing') + .waitToClick(selectors.ticketsIndex.searchButton) + .waitForNumberOfElements(selectors.ticketsIndex.searchResult, 1) + .countElement(selectors.ticketsIndex.searchResult); + + expect(result).toEqual(1); + }); + + it(`should click on the search result to access to the ticket summary`, async() => { + const url = await nightmare + .waitForTextInElement(selectors.ticketsIndex.searchResult, 'Missing') + .waitToClick(selectors.ticketsIndex.searchResult) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it(`should check the ticket sale quantity is showing a negative value`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.ticketSummary.firstSaleQuantity, '-100') + .waitToGetProperty(selectors.ticketSummary.firstSaleQuantity, 'innerText'); + + expect(result).toContain('-100'); + }); + + it(`should check the ticket sale discount is 100%`, async() => { + const result = await nightmare + .waitToGetProperty(selectors.ticketSummary.firstSaleDiscount, 'innerText'); + + expect(result).toContain('100 %'); + }); + + it('should now click on the Items button of the top bar menu', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.itemsButton) + .wait(selectors.itemsIndex.searchItemInput) + .parsedUrl(); + + expect(url.hash).toEqual('#!/item/index'); + }); + + it('should search for the item once again', async() => { + const resultCount = await nightmare + .clearInput(selectors.itemsIndex.searchItemInput) + .write(selectors.itemsIndex.searchItemInput, 'Ranged weapon pistol 9mm') + .waitToClick(selectors.itemsIndex.searchButton) + .waitForNumberOfElements(selectors.itemsIndex.searchResult, 1) + .countElement(selectors.itemsIndex.searchResult); + + expect(resultCount).toEqual(1); + }); + + it(`should click on the search result to access to the item tax`, async() => { + const url = await nightmare + .waitForTextInElement(selectors.itemsIndex.searchResult, 'Ranged weapon pistol 9mm') + .waitToClick(selectors.itemsIndex.searchResult) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it('should regularize the item once more', async() => { + const result = await nightmare + .waitToClick(selectors.itemDescriptor.moreMenu) + .waitToClick(selectors.itemDescriptor.moreMenuRegularizeButton) + .write(selectors.itemDescriptor.regularizeQuantityInput, 100) + .autocompleteSearch(selectors.itemDescriptor.regularizeWarehouseAutocomplete, 'Warehouse One') + .waitToClick(selectors.itemDescriptor.regularizeSaveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should again click on the Tickets button of the top bar menu', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.ticketsButton) + .wait(selectors.ticketsIndex.searchTicketInput) + .parsedUrl(); + + expect(url.hash).toEqual('#!/ticket/index'); + }); + + it('should search for the ticket with id 25 once again', async() => { + const result = await nightmare + .write(selectors.ticketsIndex.searchTicketInput, 25) + .waitToClick(selectors.ticketsIndex.searchButton) + .waitForNumberOfElements(selectors.ticketsIndex.searchResult, 1) + .countElement(selectors.ticketsIndex.searchResult); + + expect(result).toEqual(1); + }); + + it(`should now click on the search result to access to the ticket summary`, async() => { + const url = await nightmare + .waitForTextInElement(selectors.ticketsIndex.searchResult, '25') + .waitToClick(selectors.ticketsIndex.searchResult) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it(`should check the ticket contains now two sales`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.ticketSummary.firstSaleQuantity, '-100') + .countElement(selectors.ticketSummary.sale); + + expect(result).toEqual(2); + }); +}); diff --git a/e2e/paths/04-item-module/10_item_index.spec.js b/e2e/paths/04-item-module/10_item_index.spec.js new file mode 100644 index 000000000..32a6effda --- /dev/null +++ b/e2e/paths/04-item-module/10_item_index.spec.js @@ -0,0 +1,87 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Item index path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('salesPerson', 'item') + .waitToClick(selectors.itemsIndex.searchIcon); + }); + + it('should click on the fields to show button to open the list of columns to show', async() => { + const visible = await nightmare + .waitToClick(selectors.itemsIndex.fieldsToShowButton) + .isVisible(selectors.itemsIndex.fieldsToShowForm); + + expect(visible).toBeTruthy(); + }); + + it('should unmark all checkboxes except the first and the last ones', async() => { + const result = await nightmare + .waitToClick(selectors.itemsIndex.idCheckbox) + .waitToClick(selectors.itemsIndex.stemsCheckbox) + .waitToClick(selectors.itemsIndex.sizeCheckbox) + .waitToClick(selectors.itemsIndex.nicheCheckbox) + .waitToClick(selectors.itemsIndex.typeCheckbox) + .waitToClick(selectors.itemsIndex.categoryCheckbox) + .waitToClick(selectors.itemsIndex.intrastadCheckbox) + .waitToClick(selectors.itemsIndex.originCheckbox) + .waitToClick(selectors.itemsIndex.buyerCheckbox) + .waitToClick(selectors.itemsIndex.destinyCheckbox) + .waitToClick(selectors.itemsIndex.saveFieldsButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should navigate forth and back to see the images column is still visible', async() => { + const imageVisible = await nightmare + .waitToClick(selectors.itemsIndex.searchResult) + .waitToClick(selectors.itemDescriptor.goBackToModuleIndexButton) + .waitToClick(selectors.itemsIndex.searchIcon) + .wait(selectors.itemsIndex.searchResult) + .waitImgLoad(selectors.itemsIndex.firstItemImage) + .isVisible(selectors.itemsIndex.firstItemImageTd); + + expect(imageVisible).toBeTruthy(); + }); + + it('should check the ids column is not visible', async() => { + const idVisible = await nightmare + .isVisible(selectors.itemsIndex.firstItemId); + + expect(idVisible).toBeFalsy(); + }); + + it('should mark all unchecked boxes to leave the index as it was', async() => { + const result = await nightmare + .waitToClick(selectors.itemsIndex.fieldsToShowButton) + .waitToClick(selectors.itemsIndex.idCheckbox) + .waitToClick(selectors.itemsIndex.stemsCheckbox) + .waitToClick(selectors.itemsIndex.sizeCheckbox) + .waitToClick(selectors.itemsIndex.nicheCheckbox) + .waitToClick(selectors.itemsIndex.typeCheckbox) + .waitToClick(selectors.itemsIndex.categoryCheckbox) + .waitToClick(selectors.itemsIndex.intrastadCheckbox) + .waitToClick(selectors.itemsIndex.originCheckbox) + .waitToClick(selectors.itemsIndex.buyerCheckbox) + .waitToClick(selectors.itemsIndex.destinyCheckbox) + .waitToClick(selectors.itemsIndex.saveFieldsButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should now navigate forth and back to see the ids column is now visible', async() => { + const idVisible = await nightmare + .waitToClick(selectors.itemsIndex.searchResult) + .waitToClick(selectors.itemDescriptor.goBackToModuleIndexButton) + .waitToClick(selectors.itemsIndex.searchIcon) + .wait(selectors.itemsIndex.searchResult) + .isVisible(selectors.itemsIndex.firstItemId); + + expect(idVisible).toBeTruthy(); + }); +}); diff --git a/e2e/paths/04-item-module/11_item_log.spec.js b/e2e/paths/04-item-module/11_item_log.spec.js new file mode 100644 index 000000000..cf3beb528 --- /dev/null +++ b/e2e/paths/04-item-module/11_item_log.spec.js @@ -0,0 +1,76 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Item log path', () => { + const nightmare = createNightmare(); + beforeAll(() => { + nightmare + .loginAndModule('developer', 'item'); + }); + + it(`should search for the Knowledge artifact to confirm it isn't created yet`, async() => { + const result = await nightmare + .write(selectors.itemsIndex.searchItemInput, 'Knowledge artifact') + .waitToClick(selectors.itemsIndex.searchButton) + .waitForNumberOfElements(selectors.itemsIndex.searchResult, 0) + .countElement(selectors.itemsIndex.searchResult); + + expect(result).toEqual(0); + }); + + it('should access to the create item view by clicking the create floating button', async() => { + const url = await nightmare + .waitToClick(selectors.itemsIndex.createItemButton) + .wait(selectors.itemCreateView.createButton) + .parsedUrl(); + + expect(url.hash).toEqual('#!/item/create'); + }); + + it('should create the Knowledge artifact item', async() => { + const result = await nightmare + .write(selectors.itemCreateView.temporalName, 'Knowledge artifact') + .autocompleteSearch(selectors.itemCreateView.typeAutocomplete, 'Crisantemo') + .autocompleteSearch(selectors.itemCreateView.intrastatAutocomplete, 'Coral y materiales similares') + .autocompleteSearch(selectors.itemCreateView.originAutocomplete, 'Holand') + .waitToClick(selectors.itemCreateView.createButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should return to the items index by clicking the return to items button', async() => { + const url = await nightmare + .waitToClick(selectors.itemBasicData.goToItemIndexButton) + .wait(selectors.itemsIndex.createItemButton) + .waitForURL('#!/item/index') + .parsedUrl(); + + expect(url.hash).toContain('#!/item/index'); + }); + + it(`should search for the created item and navigate to it's log section`, async() => { + const url = await nightmare + .accessToSearchResult('Knowledge artifact') + .accessToSection('item.card.log') + .waitForURL('/log') + .parsedUrl(); + + expect(url.hash).toContain('/log'); + }); + + it(`should confirm the log is showing 5 entries`, async() => { + const anyLineCreatedCount = await nightmare + .wait(selectors.itemLog.anyLineCreated) + .countElement(selectors.itemLog.anyLineCreated); + + expect(anyLineCreatedCount).toEqual(5); + }); + + it(`should confirm the log is showing the intrastat for the created item`, async() => { + const fifthLineCreatedProperty = await nightmare + .waitToGetProperty(selectors.itemLog.fifthLineCreatedProperty, 'innerText'); + + expect(fifthLineCreatedProperty).toEqual('Coral y materiales similares'); + }); +}); diff --git a/e2e/paths/04-item-module/12_descriptor.spec.js b/e2e/paths/04-item-module/12_descriptor.spec.js new file mode 100644 index 000000000..d008d0d4e --- /dev/null +++ b/e2e/paths/04-item-module/12_descriptor.spec.js @@ -0,0 +1,48 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Item descriptor path', () => { + const nightmare = createNightmare(); + beforeAll(() => { + nightmare + .loginAndModule('buyer', 'item') + .accessToSearchResult(1) + .accessToSection('item.card.basicData'); + }); + + it('should check the descriptor inactive icon is dark as the item is active', async() => { + let darkIcon = await nightmare + .wait(selectors.itemDescriptor.inactiveIcon) + .waitForClassNotPresent(selectors.itemDescriptor.inactiveIcon, 'bright') + .isVisible(selectors.itemDescriptor.inactiveIcon); + + expect(darkIcon).toBeTruthy(); + }); + + it('should set the item to inactive', async() => { + let result = await nightmare + .waitToClick(selectors.itemBasicData.isActiveCheckbox) + .waitToClick(selectors.itemBasicData.submitBasicDataButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should reload the section and check the inactive icon is bright', async() => { + let brightIcon = await nightmare + .reloadSection('item.card.basicData') + .waitForClassPresent(selectors.itemDescriptor.inactiveIcon, 'bright') + .isVisible(selectors.itemDescriptor.inactiveIcon); + + expect(brightIcon).toBeTruthy(); + }); + + it('should set the item back to active', async() => { + let result = await nightmare + .waitToClick(selectors.itemBasicData.isActiveCheckbox) + .waitToClick(selectors.itemBasicData.submitBasicDataButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); +}); diff --git a/e2e/paths/05-ticket-module/01-sale/01_list_sales.spec.js b/e2e/paths/05-ticket-module/01-sale/01_list_sales.spec.js new file mode 100644 index 000000000..a755cd940 --- /dev/null +++ b/e2e/paths/05-ticket-module/01-sale/01_list_sales.spec.js @@ -0,0 +1,95 @@ +import selectors from '../../../helpers/selectors.js'; +import createNightmare from '../../../helpers/nightmare'; + +describe('Ticket List sale path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + return nightmare + .loginAndModule('employee', 'ticket') + .accessToSearchResult(13) + .accessToSection('ticket.card.sale'); + }); + + it('should confirm the first ticket sale contains the colour', async() => { + const value = await nightmare + .waitToGetProperty(selectors.ticketSales.firstSaleColour, 'innerText'); + + expect(value).toContain('Black'); + }); + + it('should confirm the first sale contains the price', async() => { + const value = await nightmare + .waitToGetProperty(selectors.ticketSales.firstSalePrice, 'innerText'); + + expect(value).toContain('1.72'); + }); + + it('should confirm the first sale contains the discount', async() => { + const value = await nightmare + .waitToGetProperty(selectors.ticketSales.firstSaleDiscount, 'innerText'); + + expect(value).toContain('0.00%'); + }); + + it('should confirm the first sale contains the total import', async() => { + const value = await nightmare + .waitToGetProperty(selectors.ticketSales.firstSaleImport, 'innerText'); + + expect(value).toContain('34.40'); + }); + + it('should add an empty item to the sale list', async() => { + const sales = await nightmare + .waitToClick(selectors.ticketSales.newItemButton) + .countElement(selectors.ticketSales.saleLine); + + expect(sales).toEqual(2); + }); + + it('should select a valid item to be added as the second item in the sales list', async() => { + const result = await nightmare + .waitToClick(selectors.ticketSales.secondSaleIdInput) + .write(selectors.ticketSales.secondSaleIdAutocomplete, 'Melee weapon heavy shield 1x0.5m') + .waitToClick(selectors.ticketSales.idAutocompleteFirstResult) + .write(selectors.ticketSales.secondSaleQuantity, '1\u000d') + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + // #1865 + xit('should update the description of the new sale', async() => { + const result = await nightmare + .focusElement(selectors.ticketSales.secondSaleConceptCell) + .write(selectors.ticketSales.secondSaleConceptInput, 'Aegis of Valor\u000d') + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should add a third empty item to the sale list', async() => { + const sales = await nightmare + .waitToClick(selectors.ticketSales.newItemButton) + .countElement(selectors.ticketSales.saleLine); + + expect(sales).toEqual(3); + }); + + it('should select the 2nd and 3th item and delete both', async() => { + const result = await nightmare + .waitToClick(selectors.ticketSales.secondSaleCheckbox) + .waitToClick(selectors.ticketSales.thirdSaleCheckbox) + .waitToClick(selectors.ticketSales.deleteSaleButton) + .waitToClick(selectors.ticketSales.acceptDeleteLineButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should verify there's only 1 single line remaining`, async() => { + const sales = await nightmare + .countElement(selectors.ticketSales.saleLine); + + expect(sales).toEqual(1); + }); +}); diff --git a/e2e/paths/05-ticket-module/01-sale/02_edit_sale.spec.js b/e2e/paths/05-ticket-module/01-sale/02_edit_sale.spec.js new file mode 100644 index 000000000..898a1fe53 --- /dev/null +++ b/e2e/paths/05-ticket-module/01-sale/02_edit_sale.spec.js @@ -0,0 +1,519 @@ +import selectors from '../../../helpers/selectors.js'; +import createNightmare from '../../../helpers/nightmare'; + +// #1632 [e2e] ticket.sale - Transferir líneas +xdescribe('Ticket Edit sale path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('salesPerson', 'ticket') + .accessToSearchResult(16) + .accessToSection('ticket.card.sale'); + }); + + it(`should click on the first sale claim icon to navigate over there`, async() => { + const url = await nightmare + .waitToClick(selectors.ticketSales.firstSaleClaimIcon) + .wait(selectors.claimBasicData.claimStateAutocomplete) + .parsedUrl(); + + expect(url.hash).toEqual('#!/claim/2/basic-data'); + }); + + it('should navigate to the tickets index', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.ticketsButton) + .wait(selectors.ticketsIndex.searchTicketInput) + .parsedUrl(); + + expect(url.hash).toEqual('#!/ticket/index'); + }); + + it(`should search for a ticket and then navigate to it's sales`, async() => { + const url = await nightmare + .accessToSearchResult(16) + .accessToSection('ticket.card.sale') + .waitForURL('/sale') + .parsedUrl(); + + expect(url.hash).toContain('/sale'); + }); + + it(`should check the zoomed image isn't present`, async() => { + const result = await nightmare + .countElement(selectors.ticketSales.firstSaleZoomedImage); + + expect(result).toEqual(0); + }); + + it(`should click on the thumbnail image of the 1st sale and see the zoomed image`, async() => { + const result = await nightmare + .clickIfVisible(selectors.ticketSales.firstSaleThumbnailImage) + .countElement(selectors.ticketSales.firstSaleZoomedImage); + + expect(result).toEqual(1); + }); + + it(`should click on the zoomed image to close it`, async() => { + const result = await nightmare + .wait(100) + .clickIfVisible(selectors.ticketSales.firstSaleZoomedImage) + .countElement(selectors.ticketSales.firstSaleZoomedImage); + + expect(result).toEqual(0); + }); + + it(`should confirm the item descriptor insnt visible yet`, async() => { + const visible = await nightmare + .isVisible(selectors.ticketSales.saleDescriptorPopover); + + expect(visible).toBeFalsy(); + }); + + it(`should click on the first sale ID making the item descriptor visible`, async() => { + const visible = await nightmare + .waitToClick(selectors.ticketSales.firstSaleId) + .waitImgLoad(selectors.ticketSales.firstSaleDescriptorImage) + .isVisible(selectors.ticketSales.saleDescriptorPopover); + + expect(visible).toBeTruthy(); + }); + + it(`should click on the descriptor image of the 1st sale and see the zoomed image`, async() => { + const result = await nightmare + .clickIfVisible('vn-item-descriptor img') + .countElement(selectors.ticketSales.firstSaleZoomedImage); + + expect(result).toEqual(1); + }); + + it(`should now click on the zoomed image to close it`, async() => { + const result = await nightmare + .clickIfVisible(selectors.ticketSales.firstSaleZoomedImage) + .countElement(selectors.ticketSales.firstSaleZoomedImage); + + expect(result).toEqual(0); + }); + + it(`should click on the summary icon of the item-descriptor to access to the item summary`, async() => { + const url = await nightmare + .waitToClick(selectors.ticketSales.saleDescriptorPopoverSummaryButton) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it('should return to ticket sales section', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.ticketsButton) + .accessToSearchResult(16) + .accessToSection('ticket.card.sale') + .waitForURL('/sale') + .parsedUrl(); + + expect(url.hash).toContain('/sale'); + }); + + it('should try to add a higher quantity value and then receive an error', async() => { + const result = await nightmare + .focusElement(selectors.ticketSales.firstSaleQuantityCell) + .write(selectors.ticketSales.firstSaleQuantity, '11\u000d') + .waitForLastSnackbar(); + + expect(result).toEqual('The new quantity should be smaller than the old one'); + }); + + it('should remove 1 from the first sale quantity', async() => { + const result = await nightmare + .focusElement(selectors.ticketSales.firstSaleQuantityCell) + .write(selectors.ticketSales.firstSaleQuantity, '9\u000d') + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should update the price', async() => { + const result = await nightmare + .waitToClick(`${selectors.ticketSales.firstSalePrice} > span`) + .write(selectors.ticketSales.firstSalePriceInput, '5\u000d') + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the price have been updated', async() => { + const result = await nightmare + .wait(1999) + .waitToGetProperty(`${selectors.ticketSales.firstSalePrice} span`, 'innerText'); + + expect(result).toContain('5.00'); + }); + + it('should confirm the total price for that item have been updated', async() => { + const result = await nightmare + .waitToGetProperty(selectors.ticketSales.firstSaleImport, 'innerText'); + + expect(result).toContain('45.00'); + }); + + it('should update the discount', async() => { + const result = await nightmare + .waitToClick(`${selectors.ticketSales.firstSaleDiscount} > span`) + .write(selectors.ticketSales.firstSaleDiscountInput, '50\u000d') + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the discount have been updated', async() => { + const result = await nightmare + .waitForTextInElement(`${selectors.ticketSales.firstSaleDiscount} > span`, '50.00%') + .waitToGetProperty(`${selectors.ticketSales.firstSaleDiscount} > span`, 'innerText'); + + expect(result).toContain('50.00%'); + }); + + it('should confirm the total import for that item have been updated', async() => { + const result = await nightmare + .waitForTextInElement(selectors.ticketSales.firstSaleImport, '22.50') + .waitToGetProperty(selectors.ticketSales.firstSaleImport, 'innerText'); + + expect(result).toContain('22.50'); + }); + + it('should select the third sale and create a claim of it', async() => { + const url = await nightmare + .waitToClick(selectors.ticketSales.thirdSaleCheckbox) + .waitToClick(selectors.ticketSales.moreMenu) + .waitToClick(selectors.ticketSales.moreMenuCreateClaim) + .wait(selectors.claimBasicData.claimStateAutocomplete) + .parsedUrl(); + + expect(url.hash).toContain('basic-data'); + }); + + it('should click on the Claims button of the top bar menu', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.claimsButton) + .wait(selectors.claimsIndex.searchClaimInput) + .parsedUrl(); + + expect(url.hash).toEqual('#!/claim/index'); + }); + + it('should search for the claim with id 4', async() => { + const result = await nightmare + .write(selectors.claimsIndex.searchClaimInput, 4) + .waitToClick(selectors.claimsIndex.searchButton) + .waitForNumberOfElements(selectors.claimsIndex.searchResult, 1) + .countElement(selectors.claimsIndex.searchResult); + + expect(result).toEqual(1); + }); + + it('should click the Tickets button of the top bar menu', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.ticketsButton) + .wait(selectors.ticketsIndex.searchTicketInput) + .parsedUrl(); + + expect(url.hash).toEqual('#!/ticket/index'); + }); + + it('should search for a ticket then access to the sales section', async() => { + const url = await nightmare + .accessToSearchResult(16) + .accessToSection('ticket.card.sale') + .waitForURL('/sale') + .parsedUrl(); + + expect(url.hash).toContain('/sale'); + }); + + it('should select the third sale and delete it', async() => { + const result = await nightmare + .waitToClick(selectors.ticketSales.thirdSaleCheckbox) + .waitToClick(selectors.ticketSales.deleteSaleButton) + .waitToClick(selectors.ticketSales.acceptDeleteLineButton) + .waitForSpinnerLoad() + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should confirm the third sale was deleted`, async() => { + const result = await nightmare + .countElement(selectors.ticketSales.saleLine); + + expect(result).toEqual(3); + }); + + it('should select the second sale and transfer it to a valid ticket', async() => { + const targetTicketId = 12; + + const result = await nightmare + .waitToClick(selectors.ticketSales.secondSaleCheckbox) + .waitToClick(selectors.ticketSales.transferSaleButton) + .focusElement(selectors.ticketSales.transferQuantityCell) + .write(selectors.ticketSales.transferQuantityInput, '10\u000d') + .write(selectors.ticketSales.moveToTicketInput, targetTicketId) + .waitToClick(selectors.ticketSales.moveToTicketButton) + .waitForURL(`ticket/${targetTicketId}/sale`) + .parsedUrl(); + + expect(result.hash).toContain(`ticket/${targetTicketId}/sale`); + }); + + it('should confirm the transfered line is the correct one', async() => { + const result = await nightmare + .wait(selectors.ticketSales.secondSaleText) + .waitToGetProperty(selectors.ticketSales.secondSaleText, 'innerText'); + + expect(result).toContain(`Melee weapon heavy shield`); + }); + + it('should confirm the transfered quantity is the correct one', async() => { + const result = await nightmare + .waitToGetProperty(selectors.ticketSales.secondSaleQuantityCell, 'innerText'); + + expect(result).toContain('10'); + }); + + it('should go back to the original ticket sales section', async() => { + const url = await nightmare + .waitToClick(selectors.ticketDescriptor.goBackToModuleIndexButton) + .accessToSearchResult(16) + .accessToSection('ticket.card.sale') + .waitForURL('/sale') + .parsedUrl(); + + expect(url.hash).toContain('/sale'); + }); + + it(`should confirm the original ticket has still three lines`, async() => { + const result = await nightmare + .wait(selectors.ticketSales.saleLine) + .countElement(selectors.ticketSales.saleLine); + + expect(result).toEqual(3); + }); + + it(`should confirm the second sale quantity is now half of it's original value after the transfer`, async() => { + const result = await nightmare + .waitToGetProperty(selectors.ticketSales.secondSaleQuantityCell, 'innerText'); + + expect(result).toContain('10'); + }); + + it('should go back to the receiver ticket sales section', async() => { + const url = await nightmare + .waitToClick(selectors.ticketDescriptor.goBackToModuleIndexButton) + .accessToSearchResult(12) + .accessToSection('ticket.card.sale') + .waitForURL('/sale') + .parsedUrl(); + + expect(url.hash).toContain('/sale'); + }); + + it('should transfer the sale back to the original ticket', async() => { + const targetTicketId = 16; + + const result = await nightmare + .waitToClick(selectors.ticketSales.secondSaleCheckbox) + .waitToClick(selectors.ticketSales.transferSaleButton) + .write(selectors.ticketSales.moveToTicketInput, targetTicketId) + .waitToClick(selectors.ticketSales.moveToTicketButton) + .waitForURL(`ticket/${targetTicketId}/sale`) + .parsedUrl(); + + expect(result.hash).toContain(`ticket/${targetTicketId}/sale`); + }); + + it('should confirm the original ticket received the line', async() => { + const expectedLines = 4; + const result = await nightmare + .waitForNumberOfElements(selectors.ticketSales.saleLine, expectedLines) + .countElement(selectors.ticketSales.saleLine); + + expect(result).toEqual(expectedLines); + }); + + it(`should throw an error when attempting to create a ticket for an inactive client`, async() => { + const result = await nightmare + .waitToClick(selectors.ticketSales.firstSaleCheckbox) + .waitToClick(selectors.ticketSales.transferSaleButton) + .waitToClick(selectors.ticketSales.moveToNewTicketButton) + .waitToClick(selectors.ticketSales.acceptDeleteTicketButton) + .waitForLastSnackbar(); + + expect(result).toEqual(`You can't create a ticket for a inactive client`); + }); + + it('should go now to the ticket sales section of an active, not frozen client', async() => { + const url = await nightmare + .waitToClick(selectors.ticketDescriptor.goBackToModuleIndexButton) + .accessToSearchResult(13) + .accessToSection('ticket.card.sale') + .waitForURL('/sale') + .parsedUrl(); + + expect(url.hash).toContain('/sale'); + }); + + it(`should select all sales, tranfer them to a new ticket and delete the sender ticket as it would've been left empty`, async() => { + const senderTicketId = 13; + + const url = await nightmare + .waitToClick(selectors.ticketSales.selectAllSalesCheckbox) + .waitToClick(selectors.ticketSales.transferSaleButton) + .waitToClick(selectors.ticketSales.moveToNewTicketButton) + .waitToClick(selectors.ticketSales.acceptDeleteTicketButton) + .wait((selector, ticketId) => { + return document.querySelector(selector).innerText.toLowerCase().indexOf(`${ticketId}`) == -1; + }, selectors.ticketDescriptor.idLabelValue, senderTicketId) + .parsedUrl(); + + expect(url.hash).toContain('/sale'); + }); + + it('should confirm the new ticket received the line', async() => { + const result = await nightmare + .countElement(selectors.ticketSales.saleLine); + + expect(result).toEqual(1); + }); + + it('should check the first sale reserved icon isnt visible', async() => { + const result = await nightmare + .isVisible(selectors.ticketSales.firstSaleReservedIcon); + + expect(result).toBeFalsy(); + }); + + it('should mark the first sale as reserved', async() => { + const result = await nightmare + .waitToClick(selectors.ticketSales.firstSaleCheckbox) + .waitToClick(selectors.ticketSales.moreMenu) + .waitToClick(selectors.ticketSales.moreMenuReserve) + .waitForClassNotPresent(selectors.ticketSales.firstSaleReservedIcon, 'ng-hide') + .isVisible(selectors.ticketSales.firstSaleReservedIcon); + + expect(result).toBeTruthy(); + }); + + it('should unmark the first sale as reserved', async() => { + const result = await nightmare + .waitToClick(selectors.ticketSales.moreMenu) + .waitToClick(selectors.ticketSales.moreMenuUnmarkReseved) + .waitForClassPresent(selectors.ticketSales.firstSaleReservedIcon, 'ng-hide') + .isVisible(selectors.ticketSales.firstSaleReservedIcon); + + expect(result).toBeFalsy(); + }); + + it('should update all sales discount', async() => { + const result = await nightmare + .waitToClick(selectors.ticketSales.moreMenu) + .waitToClick(selectors.ticketSales.moreMenuUpdateDiscount) + .write(selectors.ticketSales.moreMenuUpdateDiscountInput, 100) + .write('body', '\u000d') + .waitForTextInElement(selectors.ticketSales.totalImport, '0.00') + .waitToGetProperty(selectors.ticketSales.totalImport, 'innerText'); + + expect(result).toContain('0.00'); + }); + + it('should log in as Production role and go to a target ticket summary', async() => { + const url = await nightmare + .loginAndModule('production', 'ticket') + .accessToSearchResult(13) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it(`should check it's state is deleted`, async() => { + const result = await nightmare + .waitToGetProperty(selectors.ticketDescriptor.stateLabelValue, 'innerText'); + + expect(result).toEqual('State Eliminado'); + }); + + describe('when state is preparation and loged as Production', () => { + it(`should not be able to edit the sale price`, async() => { + const result = await nightmare + .waitToClick(selectors.ticketDescriptor.goBackToModuleIndexButton) + .accessToSearchResult(8) + .accessToSection('ticket.card.sale') + .waitToClick(selectors.ticketSales.firstSalePrice) + .exists(selectors.ticketSales.firstSalePriceInput); + + expect(result).toBeFalsy(); + }); + + it(`should not be able to edit the sale discount`, async() => { + const result = await nightmare + .waitToClick(selectors.ticketSales.firstSaleDiscount) + .exists(selectors.ticketSales.firstSaleDiscountInput); + + expect(result).toBeFalsy(); + }); + + it(`should not be able to edit the sale state`, async() => { + const result = await nightmare + .waitToClick(selectors.ticketSales.stateMenuButton) + .exists(selectors.ticketSales.stateMenuOptions); + + expect(result).toBeFalsy(); + }); + + it('should log in as salesPerson then go to the sales of a target ticket', async() => { + const url = await nightmare + .loginAndModule('salesPerson', 'ticket') + .accessToSearchResult(8) + .accessToSection('ticket.card.sale') + .waitForURL('/sale') + .parsedUrl(); + + expect(url.hash).toContain('/sale'); + }); + }); + + describe('when state is preparation and loged as salesPerson', () => { + it(`shouldn't be able to edit the sale price`, async() => { + const result = await nightmare + .waitToClick(selectors.ticketSales.firstSalePrice) + .exists(selectors.ticketSales.firstSalePriceInput); + + expect(result).toBeFalsy(); + }); + + it(`should be able to edit the sale discount`, async() => { + const result = await nightmare + .waitToClick(selectors.ticketSales.firstSaleDiscount) + .exists(selectors.ticketSales.firstSaleDiscountInput); + + expect(result).toBeFalsy(); + }); + + it(`should not be able to edit the sale state`, async() => { + const result = await nightmare + .waitToClick(selectors.ticketSales.stateMenuButton) + .exists(selectors.ticketSales.stateMenuOptions); + + expect(result).toBeFalsy(); + }); + }); +}); diff --git a/e2e/paths/05-ticket-module/01_observations.spec.js b/e2e/paths/05-ticket-module/01_observations.spec.js new file mode 100644 index 000000000..42193ea57 --- /dev/null +++ b/e2e/paths/05-ticket-module/01_observations.spec.js @@ -0,0 +1,46 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket Create notes path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + return nightmare + .loginAndModule('employee', 'ticket') + .accessToSearchResult(1) + .accessToSection('ticket.card.observation'); + }); + + it('should create a new note', async() => { + let result = await nightmare + .waitToClick(selectors.ticketNotes.addNoteButton) + .autocompleteSearch(selectors.ticketNotes.firstNoteTypeAutocomplete, 'observation one') + .write(selectors.ticketNotes.firstDescriptionInput, 'description') + .waitToClick(selectors.ticketNotes.submitNotesButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the note is the expected one', async() => { + let result = await nightmare + .reloadSection('ticket.card.observation') + .waitToGetProperty(`${selectors.ticketNotes.firstNoteTypeAutocomplete} input`, 'value'); + + expect(result).toEqual('observation one'); + + let firstDescription = await nightmare + .waitToGetProperty(selectors.ticketNotes.firstDescriptionInput, 'value'); + + expect(firstDescription).toEqual('description'); + }); + + it('should delete the note', async() => { + let result = await nightmare + .waitToClick(selectors.ticketNotes.firstNoteRemoveButton) + .waitToClick(selectors.ticketNotes.submitNotesButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); +}); diff --git a/e2e/paths/05-ticket-module/02_expeditions_and_log.spec.js b/e2e/paths/05-ticket-module/02_expeditions_and_log.spec.js new file mode 100644 index 000000000..ec9b16fa4 --- /dev/null +++ b/e2e/paths/05-ticket-module/02_expeditions_and_log.spec.js @@ -0,0 +1,40 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket expeditions and log path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + return nightmare + .loginAndModule('production', 'ticket') + .accessToSearchResult('1') + .accessToSection('ticket.card.expedition'); + }); + + it(`should delete a former expedition and confirm the remaining expedition are the expected ones`, async() => { + const result = await nightmare + .waitToClick(selectors.ticketExpedition.secondExpeditionRemoveButton) + .waitToClick(selectors.ticketExpedition.acceptDeleteRowButton) + .waitToClick(selectors.ticketPackages.packagesButton) + .wait(selectors.ticketPackages.firstPackageAutocomplete) + .waitToClick(selectors.ticketExpedition.expeditionButton) + .wait(selectors.ticketExpedition.expeditionRow) + .countElement(selectors.ticketExpedition.expeditionRow); + + expect(result).toEqual(3); + }); + + it(`should confirm the expedition deleted is shown now in the ticket log`, async() => { + const changedBy = await nightmare + .waitToClick(selectors.ticketLog.logButton) + .waitToGetProperty(selectors.ticketLog.changedBy, 'innerText'); + const actionTaken = await nightmare + .waitToGetProperty(selectors.ticketLog.actionTaken, 'innerText'); + const id = await nightmare + .waitToGetProperty(selectors.ticketLog.id, 'innerText'); + + expect(changedBy).toEqual('production'); + expect(actionTaken).toEqual('Deletes'); + expect(id).toEqual('2'); + }); +}); diff --git a/e2e/paths/05-ticket-module/04_packages.spec.js b/e2e/paths/05-ticket-module/04_packages.spec.js new file mode 100644 index 000000000..b51bb8b95 --- /dev/null +++ b/e2e/paths/05-ticket-module/04_packages.spec.js @@ -0,0 +1,70 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket Create packages path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + return nightmare + .loginAndModule('employee', 'ticket') + .accessToSearchResult('1') + .accessToSection('ticket.card.package'); + }); + + it(`should attempt create a new package but receive an error if package is blank`, async() => { + const result = await nightmare + .waitToClick(selectors.ticketPackages.firstRemovePackageButton) + .waitToClick(selectors.ticketPackages.addPackageButton) + .write(selectors.ticketPackages.firstQuantityInput, 99) + .waitToClick(selectors.ticketPackages.savePackagesButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Package cannot be blank'); + }); + + it(`should delete the first package and receive and error to save a new one with blank quantity`, async() => { + const result = await nightmare + .clearInput(selectors.ticketPackages.firstQuantityInput) + .autocompleteSearch(selectors.ticketPackages.firstPackageAutocomplete, 'Container medical box 1m') + .waitToClick(selectors.ticketPackages.savePackagesButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Some fields are invalid'); + }); + + it(`should confirm the quantity input isn't invalid yet`, async() => { + const result = await nightmare + .evaluate(selector => { + return document.querySelector(selector).checkValidity(); + }, selectors.ticketPackages.firstQuantityInput); + + expect(result).toBeTruthy(); + }); + + it(`should create a new package with correct data`, async() => { + const result = await nightmare + .clearInput(selectors.ticketPackages.firstQuantityInput) + .write(selectors.ticketPackages.firstQuantityInput, -99) + .waitToClick(selectors.ticketPackages.savePackagesButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should confirm the first select is the expected one`, async() => { + const result = await nightmare + .reloadSection('ticket.card.package') + .waitForTextInInput(`${selectors.ticketPackages.firstPackageAutocomplete} input`, 'Container medical box 1m') + .waitToGetProperty(`${selectors.ticketPackages.firstPackageAutocomplete} input`, 'value'); + + expect(result).toEqual('7 : Container medical box 1m'); + }); + + it(`should confirm the first quantity is just a number and the string part was ignored by the imput number`, async() => { + const result = await nightmare + .waitForTextInInput(selectors.ticketPackages.firstQuantityInput, '-99') + .waitToGetProperty(selectors.ticketPackages.firstQuantityInput, 'value'); + + expect(result).toEqual('-99'); + }); +}); diff --git a/e2e/paths/05-ticket-module/05_tracking_state.spec.js b/e2e/paths/05-ticket-module/05_tracking_state.spec.js new file mode 100644 index 000000000..7c319f1c9 --- /dev/null +++ b/e2e/paths/05-ticket-module/05_tracking_state.spec.js @@ -0,0 +1,85 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket Create new tracking state path', () => { + const nightmare = createNightmare(); + + describe('as production', () => { + beforeAll(() => { + return nightmare + .loginAndModule('production', 'ticket') + .accessToSearchResult('1') + .accessToSection('ticket.card.tracking.index'); + }); + + it('should access to the create state view by clicking the create floating button', async() => { + let url = await nightmare + .clickIfVisible(selectors.ticketTracking.createStateButton) + .wait(selectors.createStateView.stateAutocomplete) + .parsedUrl(); + + + expect(url.hash).toContain('tracking/edit'); + }); + + it(`should attempt create a new state but receive an error if state is empty`, async() => { + let result = await nightmare + .waitToClick(selectors.createStateView.saveStateButton) + .waitForLastSnackbar(); + + expect(result).toEqual('State cannot be blank'); + }); + + it(`should create a new state`, async() => { + let result = await nightmare + .autocompleteSearch(selectors.createStateView.stateAutocomplete, '¿Fecha?') + .waitToClick(selectors.createStateView.saveStateButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + }); + + describe('as salesPerson', () => { + beforeAll(() => { + return nightmare + .loginAndModule('salesPerson', 'ticket') + .accessToSearchResult('1') + .accessToSection('ticket.card.tracking.index'); + }); + + it('should now access to the create state view by clicking the create floating button', async() => { + let url = await nightmare + .waitToClick(selectors.ticketTracking.createStateButton) + .wait(selectors.createStateView.stateAutocomplete) + .parsedUrl(); + + expect(url.hash).toContain('tracking/edit'); + }); + + it(`should attemp to create an state for which salesPerson doesn't have permissions`, async() => { + let result = await nightmare + .autocompleteSearch(selectors.createStateView.stateAutocomplete, 'Encajado') + .waitToClick(selectors.createStateView.saveStateButton) + .waitForLastSnackbar(); + + expect(result).toEqual(`You don't have enough privileges`); + }); + + it(`should make sure the worker gets autocomplete uppon selecting the assigned state`, async() => { + let result = await nightmare + .autocompleteSearch(selectors.createStateView.stateAutocomplete, 'asignado') + .waitToGetProperty(`${selectors.createStateView.workerAutocomplete} input`, 'value'); + + expect(result).toEqual('salesPersonNick'); + }); + + it(`should succesfully create a valid state`, async() => { + let result = await nightmare + .waitToClick(selectors.createStateView.saveStateButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + }); +}); diff --git a/e2e/paths/05-ticket-module/06_basic_data_steps.spec.js b/e2e/paths/05-ticket-module/06_basic_data_steps.spec.js new file mode 100644 index 000000000..3dcac0765 --- /dev/null +++ b/e2e/paths/05-ticket-module/06_basic_data_steps.spec.js @@ -0,0 +1,99 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket Edit basic data path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + return nightmare + .loginAndModule('employee', 'ticket') + .accessToSearchResult(11) + .accessToSection('ticket.card.basicData.stepOne'); + }); + + it(`should confirm the zone autocomplete is disabled unless your role is productionBoss`, async() => { + const disabled = await nightmare + .wait(selectors.ticketBasicData.zoneAutocomplete) + .evaluate(selector => { + return document.querySelector(selector).disabled; + }, `${selectors.ticketBasicData.zoneAutocomplete} input`); + + expect(disabled).toBeTruthy(); + }); + + it(`should now log as productionBoss to perform the rest of the tests`, async() => { + await nightmare + .loginAndModule('productionBoss', 'ticket') + .accessToSearchResult(11) + .accessToSection('ticket.card.basicData.stepOne'); + }); + + it(`should confirm the zone autocomplete is enabled for the role productionBoss`, async() => { + const disabled = await nightmare + .waitForSpinnerLoad() + .wait(selectors.ticketBasicData.zoneAutocomplete) + .evaluate(selector => { + return document.querySelector(selector).disabled; + }, `${selectors.ticketBasicData.zoneAutocomplete} input`); + + expect(disabled).toBeFalsy(); + }); + + it(`should check the zone is for Silla247`, async() => { + let zone = await nightmare + .waitToGetProperty(`${selectors.ticketBasicData.zoneAutocomplete} input`, 'value'); + + expect(zone).toContain('Zone 247 A'); + }); + + it(`should edit the ticket agency then check there are no zones for it`, async() => { + let zone = await nightmare + .autocompleteSearch(selectors.ticketBasicData.agencyAutocomplete, 'Entanglement') + .getProperty(`${selectors.ticketBasicData.zoneAutocomplete} input`, 'value'); + + expect(zone.length).toEqual(0); + }); + + it(`should edit the ticket zone then check the agency is for the new zone`, async() => { + let zone = await nightmare + .autocompleteSearch(selectors.ticketBasicData.zoneAutocomplete, 'Zone expensive A') + .waitToGetProperty(`${selectors.ticketBasicData.agencyAutocomplete} input`, 'value'); + + expect(zone).toContain('Silla247Expensive'); + }); + + it(`should click next`, async() => { + let url = await nightmare + .waitToClick(selectors.ticketBasicData.nextStepButton) + .waitForURL('data/step-two') + .parsedUrl(); + + expect(url.hash).toContain('data/step-two'); + }); + + it(`should have a price diference`, async() => { + const result = await nightmare + .waitToGetProperty(selectors.ticketBasicData.stepTwoTotalPriceDif, 'innerText'); + + expect(result).toContain('-€248.00'); + }); + + it(`should then click next to move on to step three`, async() => { + let url = await nightmare + .waitToClick(selectors.ticketBasicData.nextStepButton) + .waitForURL('data/step-three') + .parsedUrl(); + + expect(url.hash).toContain('data/step-three'); + }); + + it(`should select a new reason for the changes made then click on finalize`, async() => { + let url = await nightmare + .autocompleteSearch(selectors.ticketBasicData.chargesReasonAutocomplete, 'Cambiar los precios en el ticket') + .waitToClick(selectors.ticketBasicData.finalizeButton) + .waitForURL('summary') + .parsedUrl(); + + expect(url.hash).toContain('summary'); + }); +}); diff --git a/e2e/paths/05-ticket-module/08_components.spec.js b/e2e/paths/05-ticket-module/08_components.spec.js new file mode 100644 index 000000000..501c2eaad --- /dev/null +++ b/e2e/paths/05-ticket-module/08_components.spec.js @@ -0,0 +1,26 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket List components path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + return nightmare + .loginAndModule('employee', 'ticket') + .accessToSearchResult('1') + .accessToSection('ticket.card.components'); + }); + + it('should confirm the total base is correct', async() => { + const name = 'Base €'; + const minLength = name.length; + + const base = await nightmare + .waitPropertyLength(selectors.ticketComponents.base, 'innerText', minLength) + .waitToGetProperty(selectors.ticketComponents.base, 'innerText'); + + + expect(base).toContain('Base'); + expect(base.length).toBeGreaterThan(minLength); + }); +}); diff --git a/e2e/paths/05-ticket-module/09_weekly.spec.js b/e2e/paths/05-ticket-module/09_weekly.spec.js new file mode 100644 index 000000000..ad8a8020c --- /dev/null +++ b/e2e/paths/05-ticket-module/09_weekly.spec.js @@ -0,0 +1,167 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket descriptor path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('employee', 'ticket'); + }); + + it('should count the amount of tickets in the turns section', async() => { + const result = await nightmare + .waitToClick(selectors.ticketsIndex.menuWeeklyTickets) + .wait(selectors.ticketsIndex.weeklyTicket) + .countElement(selectors.ticketsIndex.weeklyTicket); + + expect(result).toEqual(5); + }); + + it('should now click on the Tickets button of the top bar menu', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.ticketsButton) + .wait(selectors.ticketsIndex.searchTicketInput) + .parsedUrl(); + + expect(url.hash).toEqual('#!/ticket/index'); + }); + + it('should search for the ticket 11', async() => { + const result = await nightmare + .write(selectors.ticketsIndex.searchTicketInput, 11) + .waitToClick(selectors.ticketsIndex.searchButton) + .waitForNumberOfElements(selectors.ticketsIndex.searchResult, 1) + .countElement(selectors.ticketsIndex.searchResult); + + expect(result).toEqual(1); + }); + + it(`should click on the search result to access to the ticket`, async() => { + const url = await nightmare + .waitToClick(selectors.ticketsIndex.searchResult) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it('should add the ticket to thursday turn using the descriptor more menu', async() => { + const result = await nightmare + .waitToClick(selectors.ticketDescriptor.moreMenu) + .waitToClick(selectors.ticketDescriptor.moreMenuAddToTurn) + .waitToClick(selectors.ticketDescriptor.thursdayButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should again click on the Tickets button of the top bar menu', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.ticketsButton) + .wait(selectors.ticketsIndex.searchTicketInput) + .parsedUrl(); + + expect(url.hash).toEqual('#!/ticket/index'); + }); + + it('should confirm the ticket 11 was added on thursday', async() => { + const result = await nightmare + .waitToClick(selectors.ticketsIndex.menuWeeklyTickets) + .waitToGetProperty(selectors.ticketsIndex.sixthWeeklyTicket, 'value'); + + expect(result).toEqual('Thursday'); + }); + + it('should click on the Tickets button of the top bar menu once more', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.ticketsButton) + .wait(selectors.ticketsIndex.searchTicketInput) + .parsedUrl(); + + expect(url.hash).toEqual('#!/ticket/index'); + }); + + it('should now search for the ticket 11', async() => { + const result = await nightmare + .write(selectors.ticketsIndex.searchTicketInput, 11) + .waitToClick(selectors.ticketsIndex.searchButton) + .waitForNumberOfElements(selectors.ticketsIndex.searchResult, 1) + .countElement(selectors.ticketsIndex.searchResult); + + expect(result).toEqual(1); + }); + + it(`should click on the search result to access to the ticket`, async() => { + const url = await nightmare + .waitToClick(selectors.ticketsIndex.searchResult) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it('should add the ticket to saturday turn using the descriptor more menu', async() => { + const result = await nightmare + .waitToClick(selectors.ticketDescriptor.moreMenu) + .waitToClick(selectors.ticketDescriptor.moreMenuAddToTurn) + .waitToClick(selectors.ticketDescriptor.saturdayButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should click on the Tickets button of the top bar menu once again', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.ticketsButton) + .wait(selectors.ticketsIndex.searchTicketInput) + .parsedUrl(); + + expect(url.hash).toEqual('#!/ticket/index'); + }); + + it('should confirm the ticket 11 was added on saturday', async() => { + const result = await nightmare + .waitToClick(selectors.ticketsIndex.menuWeeklyTickets) + .waitToGetProperty(selectors.ticketsIndex.sixthWeeklyTicket, 'value'); + + expect(result).toEqual('Saturday'); + }); + + it('should now search for the weekly ticket 11', async() => { + const result = await nightmare + .write(selectors.ticketsIndex.searchWeeklyTicketInput, 11) + .waitToClick(selectors.ticketsIndex.searchWeeklyButton) + .waitForNumberOfElements(selectors.ticketsIndex.searchWeeklyResult, 1) + .countElement(selectors.ticketsIndex.searchWeeklyResult); + + expect(result).toEqual(1); + }); + + it('should delete the weekly ticket 11', async() => { + const result = await nightmare + .waitToClick(selectors.ticketsIndex.firstWeeklyTicketDeleteIcon) + .waitToClick(selectors.ticketsIndex.acceptDeleteTurn) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the sixth weekly ticket was deleted', async() => { + const result = await nightmare + .waitToClick('vn-searchbar vn-icon[icon=clear]') + .waitToClick(selectors.ticketsIndex.searchWeeklyButton) + .waitForNumberOfElements(selectors.ticketsIndex.searchWeeklyResult, 5) + .countElement(selectors.ticketsIndex.searchWeeklyResult); + + expect(result).toEqual(5); + }); +}); diff --git a/e2e/paths/05-ticket-module/10_request.spec.js b/e2e/paths/05-ticket-module/10_request.spec.js new file mode 100644 index 000000000..44dc3e1af --- /dev/null +++ b/e2e/paths/05-ticket-module/10_request.spec.js @@ -0,0 +1,59 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket purchase request path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('salesPerson', 'ticket') + .accessToSearchResult('16') + .accessToSection('ticket.card.request.index'); + }); + + it(`should add a new request`, async() => { + const result = await nightmare + .waitToClick(selectors.ticketRequests.addRequestButton) + .write(selectors.ticketRequests.descriptionInput, 'New stuff') + .write(selectors.ticketRequests.quantityInput, 99) + .autocompleteSearch(selectors.ticketRequests.atenderAutocomplete, 'buyerNick') + .write(selectors.ticketRequests.priceInput, 999) + .waitToClick(selectors.ticketRequests.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should have been redirected to the request index`, async() => { + const url = await nightmare + .waitForURL('/request') + .parsedUrl(); + + expect(url.hash).toContain('/request'); + }); + + it(`should confirm the new request was added`, async() => { + const result = await nightmare + .reloadSection('ticket.card.request.index') + .waitToGetProperty(selectors.ticketRequests.firstDescription, 'innerText'); + + expect(result).toEqual('New stuff'); + }); + + it(`should delete the added request`, async() => { + const result = await nightmare + .waitToClick(selectors.ticketRequests.firstRemoveRequestButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should confirm the request was deleted`, async() => { + const result = await nightmare + .reloadSection('ticket.card.request.index') + .wait(selectors.ticketRequests.addRequestButton) + .exists(selectors.ticketRequests.request); + + expect(result).toBeFalsy(); + }); +}); diff --git a/e2e/paths/05-ticket-module/11_diary.spec.js b/e2e/paths/05-ticket-module/11_diary.spec.js new file mode 100644 index 000000000..1f053d29f --- /dev/null +++ b/e2e/paths/05-ticket-module/11_diary.spec.js @@ -0,0 +1,63 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket diary path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('employee', 'ticket'); + }); + + it('should search for a specific ticket', async() => { + const result = await nightmare + .write(selectors.ticketsIndex.searchTicketInput, 1) + .waitToClick(selectors.ticketsIndex.searchButton) + .waitForNumberOfElements(selectors.ticketsIndex.searchResult, 1) + .countElement(selectors.ticketsIndex.searchResult); + + expect(result).toEqual(1); + }); + + it(`should click on the search result to access to the ticket summary`, async() => { + const url = await nightmare + .waitForTextInElement(selectors.ticketsIndex.searchResult, 'Bat cave') + .waitToClick(selectors.ticketsIndex.searchResult) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it(`should navigate to the item diary from the 1st sale item id descriptor popover`, async() => { + const url = await nightmare + .waitToClick(selectors.ticketSummary.firstSaleItemId) + .waitToClick(selectors.ticketSummary.popoverDiaryButton) + .waitForURL('/diary') + .parsedUrl(); + + expect(url.hash).toContain('/diary'); + }); + + it(`should check the second line id is marked as message`, async() => { + const result = await nightmare + .waitToGetProperty(selectors.itemDiary.secondTicketId, 'className'); + + expect(result).toContain('message'); + }); + + it(`should check the third line balance is marked as message`, async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.itemDiary.fourthBalance} > span`, 'className'); + + expect(result).toContain('message'); + }); + + it(`should change to the warehouse two and check there are sales marked as negative balance`, async() => { + const result = await nightmare + .autocompleteSearch(selectors.itemDiary.warehouseAutocomplete, 'Warehouse Two') + .waitToGetProperty(selectors.itemDiary.firstBalance, 'className'); + + expect(result).toContain('balance'); + }); +}); diff --git a/e2e/paths/05-ticket-module/12_descriptor.spec.js b/e2e/paths/05-ticket-module/12_descriptor.spec.js new file mode 100644 index 000000000..9442f1be0 --- /dev/null +++ b/e2e/paths/05-ticket-module/12_descriptor.spec.js @@ -0,0 +1,196 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket descriptor path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('salesperson', 'ticket'); + }); + + describe('Delete ticket', () => { + it('should search for an specific ticket', async() => { + const result = await nightmare + .write(selectors.ticketsIndex.searchTicketInput, 18) + .waitToClick(selectors.ticketsIndex.searchButton) + .waitForNumberOfElements(selectors.ticketsIndex.searchResult, 1) + .countElement(selectors.ticketsIndex.searchResult); + + expect(result).toEqual(1); + }); + + it(`should click on the search result to access to the ticket summary`, async() => { + const url = await nightmare + .waitForTextInElement(selectors.ticketsIndex.searchResult, 'Cerebro') + .waitToClick(selectors.ticketsIndex.searchResult) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it(`should update the shipped hour using the descriptor menu`, async() => { + const result = await nightmare + .waitToClick(selectors.ticketDescriptor.moreMenu) + .waitToClick(selectors.ticketDescriptor.moreMenuChangeShippedHour) + .pickTime(selectors.ticketDescriptor.changeShippedHourInput, '08:15') + .waitToClick(selectors.ticketDescriptor.acceptChangeHourButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Shipped hour updated'); + }); + + it(`should confirm the ticket descriptor shows the correct shipping hour`, async() => { + const result = await nightmare + .waitToGetProperty(selectors.ticketDescriptor.descriptorDeliveryDate, 'innerText'); + + expect(result).toContain('08:15'); + }); + + it('should delete the ticket using the descriptor more menu', async() => { + const result = await nightmare + .waitToClick(selectors.ticketDescriptor.moreMenu) + .waitToClick(selectors.ticketDescriptor.moreMenuDeleteTicket) + .waitToClick(selectors.ticketDescriptor.acceptDeleteButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Ticket deleted'); + }); + + it('should have been relocated to the ticket index', async() => { + const url = await nightmare + .parsedUrl(); + + expect(url.hash).toEqual('#!/ticket/index'); + }); + + it(`should search for the deleted ticket and check it's date`, async() => { + const result = await nightmare + .write(selectors.ticketsIndex.searchTicketInput, 18) + .waitToClick(selectors.ticketsIndex.searchButton) + .waitForNumberOfElements(selectors.ticketsIndex.searchResult, 1) + .wait(selectors.ticketsIndex.searchResultDate) + .waitToGetProperty(selectors.ticketsIndex.searchResultDate, 'innerText'); + + expect(result).toContain(2000); + }); + }); + + describe('add stowaway', () => { + it('should search for a ticket', async() => { + const result = await nightmare + .clearInput(selectors.ticketsIndex.searchTicketInput) + .write(selectors.ticketsIndex.searchTicketInput, 16) + .waitToClick(selectors.ticketsIndex.searchButton) + .waitForNumberOfElements(selectors.ticketsIndex.searchResult, 1) + .countElement(selectors.ticketsIndex.searchResult); + + expect(result).toEqual(1); + }); + + it(`should now click on the search result to access to the ticket summary`, async() => { + const url = await nightmare + .waitForTextInElement(selectors.ticketsIndex.searchResult, 'Many Places') + .waitToClick(selectors.ticketsIndex.searchResult) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it('should open the add stowaway dialog', async() => { + const isVisible = await nightmare + .wait(() => { + let element = document.querySelector('vn-ticket-descriptor'); + return element.$ctrl.canShowStowaway === true; + }) + .waitToClick(selectors.ticketDescriptor.moreMenu) + .waitToClick(selectors.ticketDescriptor.moreMenuAddStowaway) + .wait(selectors.ticketDescriptor.addStowawayDialogFirstTicket) + .visible(selectors.ticketDescriptor.addStowawayDialogFirstTicket); + + expect(isVisible).toBeTruthy(); + }); + + it('should add a ticket as stowaway', async() => { + const result = await nightmare + .waitToClick(selectors.ticketDescriptor.addStowawayDialogFirstTicket) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should check the state of the stowaway ticket is embarked`, async() => { + const state = await nightmare + .waitToGetProperty(selectors.ticketDescriptor.stateLabelValue, 'innerText'); + + expect(state).toEqual('State Embarcando'); + }); + + it(`should navigate back to the added ticket using the descriptors ship button`, async() => { + const url = await nightmare + .waitToClick(selectors.ticketDescriptor.shipButton) + .waitForURL('#!/ticket/17/summary') + .parsedUrl(); + + expect(url.hash).toContain('#!/ticket/17/summary'); + }); + + it('should delete the stowaway', async() => { + const result = await nightmare + .waitToClick(selectors.ticketDescriptor.moreMenu) + .waitToClick(selectors.ticketDescriptor.moreMenuDeleteStowawayButton) + .waitToClick(selectors.ticketDescriptor.acceptDeleteStowawayButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should confirm the ship buton doesn't exisist any more`, async() => { + const exists = await nightmare + .exists(selectors.ticketDescriptor.shipButton); + + expect(exists).toBeFalsy(); + }); + }); + + describe('Make invoice', () => { + it('should login as adminBoss role then search for a ticket', async() => { + const invoiceableTicketId = 14; + + const url = await nightmare + .loginAndModule('adminBoss', 'ticket') + .accessToSearchResult(invoiceableTicketId) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain(`ticket/${invoiceableTicketId}/summary`); + }); + + it(`should make sure the ticket doesn't have an invoiceOutFk yet`, async() => { + const result = await nightmare + .waitToGetProperty(selectors.ticketSummary.invoiceOutRef, 'innerText'); + + expect(result).toEqual('-'); + }); + + it('should invoice the ticket using the descriptor more menu', async() => { + const result = await nightmare + .waitToClick(selectors.ticketDescriptor.moreMenu) + .waitToClick(selectors.ticketDescriptor.moreMenuMakeInvoice) + .waitToClick(selectors.ticketDescriptor.acceptInvoiceOutButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Ticket invoiced'); + }); + + it(`should make sure the ticket summary have an invoiceOutFk`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.ticketSummary.invoiceOutRef, 'T4444445') + .waitToGetProperty(selectors.ticketSummary.invoiceOutRef, 'innerText'); + + expect(result).toEqual('T4444445'); + }); + }); +}); diff --git a/e2e/paths/05-ticket-module/13_services.spec.js b/e2e/paths/05-ticket-module/13_services.spec.js new file mode 100644 index 000000000..472e23315 --- /dev/null +++ b/e2e/paths/05-ticket-module/13_services.spec.js @@ -0,0 +1,143 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket services path', () => { + const nightmare = createNightmare(); + const invoicedTicketId = 1; + + describe('as employee', () => { + beforeAll(() => { + nightmare + .loginAndModule('employee', 'ticket') + .accessToSearchResult(invoicedTicketId) + .accessToSection('ticket.card.service'); + }); + + it('should find the add descripton button disabled for this user role', async() => { + const result = await nightmare + .waitForClassPresent(selectors.ticketService.firstAddServiceTypeButton, 'disabled') + .waitToClick(selectors.ticketService.addServiceButton) + .wait(selectors.ticketService.firstAddServiceTypeButton) + .isDisabled(selectors.ticketService.firstAddServiceTypeButton); + + expect(result).toBeTruthy(); + }, 100000); + + it('should receive an error if you attempt to save a service without access rights', async() => { + const result = await nightmare + .clearInput(selectors.ticketService.firstPriceInput) + .write(selectors.ticketService.firstPriceInput, 999) + .waitToClick(selectors.ticketService.saveServiceButton) + .waitForLastSnackbar(); + + expect(result).toEqual(`The current ticket can't be modified`); + }); + }); + + describe('as administrative', () => { + let editableTicketId = 16; + it('should navigate to the services of a target ticket', async() => { + const url = await nightmare + .loginAndModule('administrative', 'ticket') + .accessToSearchResult(editableTicketId) + .accessToSection('ticket.card.service') + .waitForURL('/service') + .parsedUrl(); + + expect(url.hash).toContain('/service'); + }); + + it('should click on the add button to prepare the form to create a new service', async() => { + const result = await nightmare + .waitToClick(selectors.ticketService.addServiceButton) + .isVisible(selectors.ticketService.firstServiceTypeAutocomplete); + + expect(result).toBeTruthy(); + }); + + it('should receive an error if you attempt to save it with empty fields', async() => { + const result = await nightmare + .waitToClick(selectors.ticketService.saveServiceButton) + .waitForLastSnackbar(); + + expect(result).toEqual(`can't be blank`); + }); + + it('should click on the add new service type to open the dialog', async() => { + const result = await nightmare + .waitToClick(selectors.ticketService.firstAddServiceTypeButton) + .wait('.vn-dialog.shown') + .isVisible(selectors.ticketService.newServiceTypeNameInput); + + expect(result).toBeTruthy(); + }); + + it('should receive an error if service type is empty on submit', async() => { + const result = await nightmare + .waitToClick(selectors.ticketService.saveServiceTypeButton) + .waitForLastSnackbar(); + + expect(result).toEqual(`Name can't be empty`); + }); + + it('should create a new service type then add price then create the service', async() => { + const result = await nightmare + .write(selectors.ticketService.newServiceTypeNameInput, 'Documentos') + .autocompleteSearch(selectors.ticketService.newServiceTypeExpenseAutocomplete, 'Retencion') + .waitToClick(selectors.ticketService.saveServiceTypeButton) + .write(selectors.ticketService.firstPriceInput, 999) + .waitToClick(selectors.ticketService.saveServiceButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the service description was created correctly', async() => { + const result = await nightmare + .reloadSection('ticket.card.service') + .waitToGetProperty(`${selectors.ticketService.firstServiceTypeAutocomplete} input`, 'value'); + + expect(result).toEqual('Documentos'); + }); + + it('should confirm the service quantity was created correctly', async() => { + const result = await nightmare + .waitToGetProperty(selectors.ticketService.firstQuantityInput, 'value'); + + expect(result).toEqual('1'); + }); + + it('should confirm the service price was created correctly', async() => { + const result = await nightmare + .waitToGetProperty(selectors.ticketService.firstPriceInput, 'value'); + + expect(result).toEqual('999'); + }); + + it('should confirm the service VAT was created correctly', async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.ticketService.firstVatTypeAutocomplete} input`, 'value'); + + expect(result).toEqual('General VAT'); + }); + + it('should delete the service', async() => { + const result = await nightmare + .waitToClick(selectors.ticketService.fistDeleteServiceButton) + .waitForNumberOfElements(selectors.ticketService.serviceLine, 0) + .waitToClick(selectors.ticketService.saveServiceButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should confirm the service was removed`, async() => { + const result = await nightmare + .reloadSection('ticket.card.service') + .waitForNumberOfElements(selectors.ticketService.serviceLine, 0) + .countElement(selectors.ticketService.serviceLine); + + expect(result).toEqual(0); + }); + }); +}); diff --git a/e2e/paths/05-ticket-module/14_create_ticket.spec.js b/e2e/paths/05-ticket-module/14_create_ticket.spec.js new file mode 100644 index 000000000..773ea3602 --- /dev/null +++ b/e2e/paths/05-ticket-module/14_create_ticket.spec.js @@ -0,0 +1,41 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket create path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('employee', 'ticket'); + }); + + it('should open the new ticket form', async() => { + const url = await nightmare + .waitToClick(selectors.ticketsIndex.newTicketButton) + .wait(selectors.createTicketView.clientAutocomplete) + .parsedUrl(); + + expect(url.hash).toEqual('#!/ticket/create'); + }); + + it('should succeed to create a ticket', async() => { + const result = await nightmare + .autocompleteSearch(selectors.createTicketView.clientAutocomplete, 'Tony Stark') + .autocompleteSearch(selectors.createTicketView.addressAutocomplete, 'Tony Stark') + .datePicker(selectors.createTicketView.deliveryDateInput, 1, null) + .autocompleteSearch(selectors.createTicketView.warehouseAutocomplete, 'Warehouse One') + .autocompleteSearch(selectors.createTicketView.agencyAutocomplete, 'Silla247') + .waitToClick(selectors.createTicketView.createButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should check the url is now the summary of the ticket', async() => { + const url = await nightmare + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); +}); diff --git a/e2e/paths/05-ticket-module/15_create_ticket_from_client.spec.js b/e2e/paths/05-ticket-module/15_create_ticket_from_client.spec.js new file mode 100644 index 000000000..30eac6f04 --- /dev/null +++ b/e2e/paths/05-ticket-module/15_create_ticket_from_client.spec.js @@ -0,0 +1,34 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket create from client path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('employee', 'client') + .accessToSearchResult('Petter Parker'); + }); + + it('should click the create simple ticket on the descriptor menu', async() => { + const url = await nightmare + .waitToClick(selectors.clientDescriptor.moreMenu) + .waitToClick(selectors.clientDescriptor.simpleTicketButton) + .waitForURL('#!/ticket/create?clientFk=102') + .parsedUrl(); + + expect(url.hash).toContain('clientFk=102'); + }); + + it('should check if the client details are the expected ones', async() => { + const client = await nightmare + .waitToGetProperty(`${selectors.createTicketView.clientAutocomplete} input`, 'value'); + + const address = await nightmare + .waitToGetProperty(`${selectors.createTicketView.addressAutocomplete} input`, 'value'); + + + expect(client).toContain('Petter Parker'); + expect(address).toContain('20 Ingram Street'); + }); +}); diff --git a/e2e/paths/05-ticket-module/16_summary.spec.js b/e2e/paths/05-ticket-module/16_summary.spec.js new file mode 100644 index 000000000..2832da428 --- /dev/null +++ b/e2e/paths/05-ticket-module/16_summary.spec.js @@ -0,0 +1,97 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Ticket Summary path', () => { + const nightmare = createNightmare(); + const ticketId = 20; + + it('should navigate to the target ticket summary section', async() => { + let url = await nightmare + .loginAndModule('employee', 'ticket') + .accessToSearchResult(ticketId) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it(`should display details from the ticket and it's client on the top of the header`, async() => { + let result = await nightmare + .waitForTextInElement(selectors.ticketSummary.header, 'Bruce Banner') + .waitToGetProperty(selectors.ticketSummary.header, 'innerText'); + + expect(result).toContain(`Ticket #${ticketId}`); + expect(result).toContain('Bruce Banner (109)'); + expect(result).toContain('Somewhere in Thailand'); + }); + + it('should display ticket details', async() => { + let result = await nightmare + .waitToGetProperty(selectors.ticketSummary.state, 'innerText'); + + expect(result).toContain('Arreglar'); + }); + + it('should display delivery details', async() => { + let result = await nightmare + .waitToGetProperty(selectors.ticketSummary.route, 'innerText'); + + expect(result).toContain('3'); + }); + + it('should display the ticket total', async() => { + let result = await nightmare + .waitToGetProperty(selectors.ticketSummary.total, 'innerText'); + + expect(result).toContain('€155.54'); + }); + + it('should display the ticket line(s)', async() => { + let result = await nightmare + .waitToGetProperty(selectors.ticketSummary.firstSaleItemId, 'innerText'); + + expect(result).toContain('000002'); + }); + + it(`should click on the first sale ID making the item descriptor visible`, async() => { + const visible = await nightmare + .waitToClick(selectors.ticketSummary.firstSaleItemId) + .waitImgLoad(selectors.ticketSummary.firstSaleDescriptorImage) + .isVisible(selectors.ticketSummary.itemDescriptorPopover); + + expect(visible).toBeTruthy(); + }); + + it(`should check the url for the item diary link of the descriptor is for the right item id`, async() => { + const exists = await nightmare + .exists(selectors.ticketSummary.itemDescriptorPopoverItemDiaryButton); + + expect(exists).toBeTruthy(); + }); + + it('should log in as production then navigate to the summary of the same ticket', async() => { + let url = await nightmare + .loginAndModule('production', 'ticket') + .accessToSearchResult(ticketId) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it('should click on the SET OK button', async() => { + let result = await nightmare + .waitToClick(selectors.ticketSummary.setOk) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the ticket state was updated', async() => { + let result = await nightmare + .waitForSpinnerLoad() + .waitToGetProperty(selectors.ticketSummary.state, 'innerText'); + + expect(result).toContain('OK'); + }); +}); diff --git a/e2e/paths/06-claim-module/01_basic_data.spec.js b/e2e/paths/06-claim-module/01_basic_data.spec.js new file mode 100644 index 000000000..2df37a147 --- /dev/null +++ b/e2e/paths/06-claim-module/01_basic_data.spec.js @@ -0,0 +1,59 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Claim edit basic data path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('salesAssistant', 'claim') + .accessToSearchResult('1') + .accessToSection('claim.card.basicData'); + }); + + it(`should edit claim state and observation fields`, async() => { + const result = await nightmare + .autocompleteSearch(selectors.claimBasicData.claimStateAutocomplete, 'Gestionado') + .clearTextarea(selectors.claimBasicData.observationInput) + .write(selectors.claimBasicData.observationInput, 'edited observation') + .waitToClick(selectors.claimBasicData.saveButton) + .waitForSnackbar(); + + expect(result).toEqual(jasmine.arrayContaining(['Data saved!'])); + }); + + it(`should have been redirected to the next section of claims as the role is salesAssistant`, async() => { + const url = await nightmare + .waitForURL('/detail') + .parsedUrl(); + + expect(url.hash).toContain('/detail'); + }); + + it('should confirm the claim state was edited', async() => { + const result = await nightmare + .reloadSection('claim.card.basicData') + .wait(selectors.claimBasicData.claimStateAutocomplete) + .waitToGetProperty(`${selectors.claimBasicData.claimStateAutocomplete} input`, 'value'); + + expect(result).toEqual('Gestionado'); + }); + + it('should confirm the claim observation was edited', async() => { + const result = await nightmare + .waitToGetProperty(selectors.claimBasicData.observationInput, 'value'); + + expect(result).toEqual('edited observation'); + }); + + it(`should edit the claim to leave it untainted`, async() => { + const result = await nightmare + .autocompleteSearch(selectors.claimBasicData.claimStateAutocomplete, 'Pendiente') + .clearTextarea(selectors.claimBasicData.observationInput) + .write(selectors.claimBasicData.observationInput, 'Observation one') + .waitToClick(selectors.claimBasicData.saveButton) + .waitForSnackbar(); + + expect(result).toEqual(jasmine.arrayContaining(['Data saved!'])); + }); +}); diff --git a/e2e/paths/06-claim-module/02_development.spec.js b/e2e/paths/06-claim-module/02_development.spec.js new file mode 100644 index 000000000..640eff636 --- /dev/null +++ b/e2e/paths/06-claim-module/02_development.spec.js @@ -0,0 +1,97 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Claim development', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('salesAssistant', 'claim') + .accessToSearchResult('1') + .accessToSection('claim.card.development'); + }); + + it('should delete a development and create a new one', async() => { + const result = await nightmare + .waitToClick(selectors.claimDevelopment.firstDeleteDevelopmentButton) + .waitToClick(selectors.claimDevelopment.addDevelopmentButton) + .autocompleteSearch(selectors.claimDevelopment.secondClaimReasonAutocomplete, 'Baja calidad') + .autocompleteSearch(selectors.claimDevelopment.secondClaimResultAutocomplete, 'Deshidratacion') + .autocompleteSearch(selectors.claimDevelopment.secondClaimResponsibleAutocomplete, 'Calidad general') + .autocompleteSearch(selectors.claimDevelopment.secondClaimWorkerAutocomplete, 'deliveryNick') + .autocompleteSearch(selectors.claimDevelopment.secondClaimRedeliveryAutocomplete, 'Reparto') + .waitToClick(selectors.claimDevelopment.saveDevelopmentButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }, 15000); + + it(`should redirect to the next section of claims as the role is salesAssistant`, async() => { + const url = await nightmare + .waitForURL('/action') + .parsedUrl(); + + expect(url.hash).toContain('/action'); + }); + + it('should edit a development', async() => { + const result = await nightmare + .reloadSection('claim.card.development') + .autocompleteSearch(selectors.claimDevelopment.firstClaimReasonAutocomplete, 'Calor') + .autocompleteSearch(selectors.claimDevelopment.firstClaimResultAutocomplete, 'Cocido') + .autocompleteSearch(selectors.claimDevelopment.firstClaimResponsibleAutocomplete, 'Calidad general') + .autocompleteSearch(selectors.claimDevelopment.firstClaimWorkerAutocomplete, 'adminAssistantNick') + .autocompleteSearch(selectors.claimDevelopment.firstClaimRedeliveryAutocomplete, 'Cliente') + .waitToClick(selectors.claimDevelopment.saveDevelopmentButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the first development is the expected one', async() => { + const reason = await nightmare + .reloadSection('claim.card.development') + .waitToGetProperty(`${selectors.claimDevelopment.firstClaimReasonAutocomplete} input`, 'value'); + + const result = await nightmare + .waitToGetProperty(`${selectors.claimDevelopment.firstClaimResultAutocomplete} input`, 'value'); + + const responsible = await nightmare + .waitToGetProperty(`${selectors.claimDevelopment.firstClaimResponsibleAutocomplete} input`, 'value'); + + const worker = await nightmare + .waitToGetProperty(`${selectors.claimDevelopment.firstClaimWorkerAutocomplete} input`, 'value'); + + const redelivery = await nightmare + .waitToGetProperty(`${selectors.claimDevelopment.firstClaimRedeliveryAutocomplete} input`, 'value'); + + expect(reason).toEqual('Calor'); + expect(result).toEqual('Cocido'); + expect(responsible).toEqual('Calidad general'); + expect(worker).toEqual('adminAssistantNick'); + expect(redelivery).toEqual('Cliente'); + }); + + it('should confirm the second development is the expected one', async() => { + const reason = await nightmare + .waitToGetProperty(`${selectors.claimDevelopment.secondClaimReasonAutocomplete} input`, 'value'); + + const result = await nightmare + .waitToGetProperty(`${selectors.claimDevelopment.secondClaimResultAutocomplete} input`, 'value'); + + const responsible = await nightmare + .waitToGetProperty(`${selectors.claimDevelopment.secondClaimResponsibleAutocomplete} input`, 'value'); + + const worker = await nightmare + .waitToGetProperty(`${selectors.claimDevelopment.secondClaimWorkerAutocomplete} input`, 'value'); + + const redelivery = await nightmare + .waitToGetProperty(`${selectors.claimDevelopment.secondClaimRedeliveryAutocomplete} input`, 'value'); + + expect(reason).toEqual('Baja calidad'); + expect(result).toEqual('Deshidratacion'); + expect(responsible).toEqual('Calidad general'); + expect(worker).toEqual('deliveryNick'); + expect(redelivery).toEqual('Reparto'); + }); +}); diff --git a/e2e/paths/06-claim-module/03_detail.spec.js b/e2e/paths/06-claim-module/03_detail.spec.js new file mode 100644 index 000000000..43d291bb3 --- /dev/null +++ b/e2e/paths/06-claim-module/03_detail.spec.js @@ -0,0 +1,121 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +// #1528 e2e claim/detail +xdescribe('Claim detail', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('salesPerson', 'claim') + .accessToSearchResult(1) + .accessToSection('claim.card.detail'); + }); + + it('should add the first claimable item from ticket to the claim', async() => { + const result = await nightmare + .waitToClick(selectors.claimDetail.addItemButton) + .waitToClick(selectors.claimDetail.firstClaimableSaleFromTicket) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the claim contains now two items', async() => { + const result = await nightmare + .countElement(selectors.claimDetail.claimDetailLine); + + expect(result).toEqual(2); + }); + + it('should edit de first item claimed quantity', async() => { + const result = await nightmare + .clearInput(selectors.claimDetail.firstItemQuantityInput) + .write(selectors.claimDetail.firstItemQuantityInput, 4) + .write('body', '\u000d') // simulates enter + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the first item quantity, and the claimed total were correctly edited', async() => { + const claimedQuantity = await nightmare + .waitToGetProperty(selectors.claimDetail.firstItemQuantityInput, 'value'); + + const totalClaimed = await nightmare + .waitToGetProperty(selectors.claimDetail.totalClaimed, 'innerText'); + + expect(claimedQuantity).toEqual('4'); + expect(totalClaimed).toContain('€47.62'); + }); + + it('should login as salesAssistant and navigate to the claim.detail section', async() => { + const url = await nightmare + .loginAndModule('salesAssistant', 'claim') + .accessToSearchResult(1) + .accessToSection('claim.card.detail') + .waitForURL('/detail') + .parsedUrl(); + + expect(url.hash).toContain('/detail'); + }); + + it('should edit de second item claimed discount', async() => { + const result = await nightmare + .waitToClick(selectors.claimDetail.secondItemDiscount) + .write(selectors.claimDetail.discountInput, 100) + .write('body', '\u000d') // simulates enter + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should check the mana is the expected one', async() => { + const result = await nightmare + .waitToClick(selectors.claimDetail.secondItemDiscount) + .waitToGetProperty(selectors.claimDetail.discoutPopoverMana, 'innerText'); + + expect(result).toContain('MANÁ: €106'); + }); + + it('should delete the second item from the claim', async() => { + const result = await nightmare + .waitToClick(selectors.claimDetail.secondItemDeleteButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the claim contains now one item', async() => { + const result = await nightmare + .countElement(selectors.claimDetail.claimDetailLine); + + expect(result).toEqual(1); + }); + + it('should add the deleted ticket from to the claim', async() => { + const result = await nightmare + .waitToClick(selectors.claimDetail.addItemButton) + .waitToClick(selectors.claimDetail.firstClaimableSaleFromTicket) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should have been redirected to the next section in claims`, async() => { + const url = await nightmare + .waitForURL('/development') + .parsedUrl(); + + expect(url.hash).toContain('development'); + }); + + it('should navigate back to claim.detail to confirm the claim contains now two items', async() => { + const result = await nightmare + .accessToSection('claim.card.detail') + .wait(selectors.claimDetail.claimDetailLine) + .countElement(selectors.claimDetail.claimDetailLine); + + expect(result).toEqual(2); + }); +}); diff --git a/e2e/paths/06-claim-module/04_claim_action.spec.js b/e2e/paths/06-claim-module/04_claim_action.spec.js new file mode 100644 index 000000000..5bf6ed3d2 --- /dev/null +++ b/e2e/paths/06-claim-module/04_claim_action.spec.js @@ -0,0 +1,78 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Claim action path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('administrative', 'claim') + .accessToSearchResult(2) + .accessToSection('claim.card.action'); + }); + + it('should import the claim', async() => { + const result = await nightmare + .waitToClick(selectors.claimAction.importClaimButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should import the second importable ticket', async() => { + const result = await nightmare + .waitToClick(selectors.claimAction.importTicketButton) + .waitToClick(selectors.claimAction.secondImportableTicket) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should edit the second line destination field', async() => { + const result = await nightmare + .autocompleteSearch(selectors.claimAction.secondLineDestination, 'Bueno') + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should delete the first line', async() => { + const result = await nightmare + .waitToClick(selectors.claimAction.firstDeleteLine) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should refresh the view to check the remaining line is the expected one', async() => { + const result = await nightmare + .reloadSection('claim.card.action') + .waitToGetProperty(`${selectors.claimAction.firstLineDestination} input`, 'value'); + + expect(result).toEqual('Bueno'); + }); + + it('should delete the current first line', async() => { + const result = await nightmare + .waitToClick(selectors.claimAction.firstDeleteLine) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should check the "is paid with mana" checkbox', async() => { + const result = await nightmare + .waitToClick(selectors.claimAction.isPaidWithManaCheckbox) + .waitForSnackbar(); + + expect(result).toEqual(jasmine.arrayContaining(['Data saved!'])); + }); + + it('should confirm the "is paid with mana" checkbox is checked', async() => { + const result = await nightmare + .reloadSection('claim.card.action') + .checkboxState(selectors.claimAction.isPaidWithManaCheckbox); + + expect(result).toBe('checked'); + }); +}); diff --git a/e2e/paths/06-claim-module/05_summary.spec.js b/e2e/paths/06-claim-module/05_summary.spec.js new file mode 100644 index 000000000..b6d16cb6b --- /dev/null +++ b/e2e/paths/06-claim-module/05_summary.spec.js @@ -0,0 +1,97 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('claim Summary path', () => { + const nightmare = createNightmare(); + const claimId = 4; + + it('should navigate to the target claim summary section', async() => { + let url = await nightmare + .loginAndModule('employee', 'claim') + .accessToSearchResult(claimId) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it(`should display details from the claim and it's client on the top of the header`, async() => { + let result = await nightmare + .waitForTextInElement(selectors.claimSummary.header, 'Tony Stark') + .waitToGetProperty(selectors.claimSummary.header, 'innerText'); + + expect(result).toContain('4 -'); + expect(result).toContain('Tony Stark'); + }); + + it('should display the claim state', async() => { + let result = await nightmare + .waitToGetProperty(selectors.claimSummary.state, 'innerText'); + + expect(result).toContain('Resuelto'); + }); + + it('should display the observation', async() => { + let result = await nightmare + .waitToGetProperty(selectors.claimSummary.observation, 'value'); + + expect(result).toContain('observation four'); + }); + + it('should display the claimed line(s)', async() => { + let result = await nightmare + .waitToGetProperty(selectors.claimSummary.firstSaleItemId, 'innerText'); + + expect(result).toContain('000002'); + }); + + it(`should click on the first sale ID making the item descriptor visible`, async() => { + const visible = await nightmare + .waitToClick(selectors.claimSummary.firstSaleItemId) + .waitImgLoad(selectors.claimSummary.firstSaleDescriptorImage) + .isVisible(selectors.claimSummary.itemDescriptorPopover); + + expect(visible).toBeTruthy(); + }); + + it(`should check the url for the item diary link of the descriptor is for the right item id`, async() => { + const exists = await nightmare + .exists(selectors.claimSummary.itemDescriptorPopoverItemDiaryButton); + + expect(exists).toBeTruthy(); + await nightmare.mousedown('.vn-popover.shown'); + }); + + it('should display the claim development details', async() => { + let result = await nightmare + .waitToGetProperty(selectors.claimSummary.firstDevelopmentWorker, 'innerText'); + + expect(result).toContain('salesAssistantNick'); + }); + + it(`should click on the first development worker making the worker descriptor visible`, async() => { + const visible = await nightmare + .waitToClick(selectors.claimSummary.firstDevelopmentWorker) + .wait(selectors.claimSummary.firstDevelopmentWorkerGoToClientButton) + .isVisible(selectors.claimSummary.firstDevelopmentWorkerGoToClientButton); + + expect(visible).toBeTruthy(); + }); + + it(`should check the url for the go to clientlink of the descriptor is for the right client id`, async() => { + const exists = await nightmare + .exists(selectors.claimSummary.firstDevelopmentWorkerGoToClientButton); + + expect(exists).toBeTruthy(); + await nightmare.mousedown('.vn-popover.shown'); + }); + + it(`should click on the first action ticket ID making the ticket descriptor visible`, async() => { + const visible = await nightmare + .waitToClick(selectors.claimSummary.firstActionTicketId) + .wait(selectors.claimSummary.firstActionTicketDescriptor) + .isVisible(selectors.claimSummary.firstActionTicketDescriptor); + + expect(visible).toBeTruthy(); + }); +}); diff --git a/e2e/paths/06-claim-module/06_descriptor.spec.js b/e2e/paths/06-claim-module/06_descriptor.spec.js new file mode 100644 index 000000000..67faaa224 --- /dev/null +++ b/e2e/paths/06-claim-module/06_descriptor.spec.js @@ -0,0 +1,71 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('claim Descriptor path', () => { + const nightmare = createNightmare(); + const claimId = 1; + + it('should navigate to the target claim summary section', async() => { + let url = await nightmare + .loginAndModule('employee', 'claim') + .accessToSearchResult(claimId) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it(`should not be able to see the delete claim button of the descriptor more menu`, async() => { + let exists = await nightmare + .waitToClick(selectors.claimDescriptor.moreMenu) + .exists(selectors.claimDescriptor.moreMenuDeleteClaim); + + expect(exists).toBeFalsy(); + }); + + it(`should log in as salesAssistant and navigate to the target claim`, async() => { + let url = await nightmare + .loginAndModule('salesAssistant', 'claim') + .accessToSearchResult(claimId) + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it(`should be able to see the delete claim button of the descriptor more menu`, async() => { + let exists = await nightmare + .waitToClick(selectors.claimDescriptor.moreMenu) + .wait(selectors.claimDescriptor.moreMenuDeleteClaim) + .exists(selectors.claimDescriptor.moreMenuDeleteClaim); + + expect(exists).toBeTruthy(); + }); + + it(`should delete the claim`, async() => { + let result = await nightmare + .waitToClick(selectors.claimDescriptor.moreMenuDeleteClaim) + .waitToClick(selectors.claimDescriptor.acceptDeleteClaim) + .waitForLastSnackbar(); + + expect(result).toEqual('Claim deleted!'); + }); + + it(`should have been relocated to the claim index`, async() => { + let url = await nightmare + .waitForURL('/claim/index') + .parsedUrl(); + + expect(url.hash).toContain('/claim/index'); + }); + + it(`should search for the deleted claim to find no results`, async() => { + const result = await nightmare + .write(selectors.claimsIndex.searchClaimInput, claimId) + .waitToClick(selectors.claimsIndex.searchButton) + .waitForNumberOfElements(selectors.claimsIndex.searchResult, 0) + .countElement(selectors.claimsIndex.searchResult); + + expect(result).toEqual(0); + }); +}); diff --git a/e2e/paths/07-order-module/01_edit_basic_data.spec.js b/e2e/paths/07-order-module/01_edit_basic_data.spec.js new file mode 100644 index 000000000..4cc04bfa0 --- /dev/null +++ b/e2e/paths/07-order-module/01_edit_basic_data.spec.js @@ -0,0 +1,119 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Order edit basic data path', () => { + const nightmare = createNightmare(); + const today = new Date().getDate(); + + describe('when confirmed order', () => { + beforeAll(() => { + nightmare + .loginAndModule('employee', 'order') + .accessToSearchResult(1) + .accessToSection('order.card.basicData'); + }); + + it('should not be able to change the client', async() => { + const result = await nightmare + .autocompleteSearch(selectors.orderBasicData.clientAutocomplete, 'Tony Stark') + .autocompleteSearch(selectors.orderBasicData.addressAutocomplete, 'Tony Stark') + .waitToClick(selectors.orderBasicData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual(`You can't make changes on the basic data of an confirmed order or with rows`); + }, 15000); + }); + + describe('when order with rows', () => { + it('should now navigate to order index', async() => { + const orderId = 16; + const url = await nightmare + .waitToClick(selectors.orderDescriptor.returnToModuleIndexButton) + .waitToClick(selectors.orderDescriptor.acceptNavigationButton) + .wait(selectors.ordersIndex.createOrderButton) + .accessToSearchResult(orderId) + .accessToSection('order.card.basicData') + .wait(selectors.orderBasicData.observationInput) + .parsedUrl(); + + expect(url.hash).toEqual(`#!/order/${orderId}/basic-data`); + }); + + it('should not be able to change anything', async() => { + const result = await nightmare + .write(selectors.orderBasicData.observationInput, 'observation') + .waitToClick(selectors.orderBasicData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual(`You can't make changes on the basic data of an confirmed order or with rows`); + }); + }); + + describe('when new order', () => { + it('should navigate to the order index and click the new order button', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.returnToModuleIndexButton) + .waitToClick(selectors.orderBasicData.acceptButton) + .waitToClick(selectors.ordersIndex.createOrderButton) + .waitForURL('#!/order/create') + .parsedUrl(); + + expect(url.hash).toContain('#!/order/create'); + }); + + it('should now create a new one', async() => { + const url = await nightmare + .autocompleteSearch(selectors.createOrderView.clientAutocomplete, 'Jessica Jones') + .datePicker(selectors.createOrderView.landedDatePicker, 0, today) + .autocompleteSearch(selectors.createOrderView.agencyAutocomplete, 'inhouse pickup') + .waitToClick(selectors.createOrderView.createButton) + .waitForURL('/catalog') + .parsedUrl(); + + expect(url.hash).toContain('/catalog'); + }); + + it('should navigate to the basic data section of the new order', async() => { + const url = await nightmare + .accessToSection('order.card.basicData') + .wait(selectors.orderBasicData.observationInput) + .parsedUrl(); + + expect(url.hash).toContain('/basic-data'); + }); + + it('should be able to modify all the properties', async() => { + const result = await nightmare + .autocompleteSearch(selectors.orderBasicData.clientAutocomplete, 'Tony Stark') + .autocompleteSearch(selectors.orderBasicData.addressAutocomplete, 'Tony Stark') + .autocompleteSearch(selectors.orderBasicData.agencyAutocomplete, 'Silla247') + .write(selectors.orderBasicData.observationInput, 'my observation') + .waitToClick(selectors.orderBasicData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should now confirm the client have been edited', async() => { + const result = await nightmare + .reloadSection('order.card.basicData') + .waitToGetProperty(`${selectors.orderBasicData.clientAutocomplete} input`, 'value'); + + expect(result).toEqual('104: Tony Stark'); + }); + + it('should now confirm the agency have been edited', async() => { + const result = await nightmare + .waitToGetProperty(`${selectors.orderBasicData.agencyAutocomplete} input`, 'value'); + + expect(result).toEqual('7: Silla247'); + }); + + it('should now confirm the observations have been edited', async() => { + const result = await nightmare + .waitToGetProperty(selectors.orderBasicData.observationInput, 'value'); + + expect(result).toEqual('my observation'); + }); + }); +}); diff --git a/e2e/paths/07-order-module/02_catalog.spec.js b/e2e/paths/07-order-module/02_catalog.spec.js new file mode 100644 index 000000000..cad95741e --- /dev/null +++ b/e2e/paths/07-order-module/02_catalog.spec.js @@ -0,0 +1,83 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Order catalog', () => { + const nightmare = createNightmare(); + beforeAll(() => { + nightmare + .loginAndModule('employee', 'order'); + }); + + it('should open the create new order form', async() => { + const url = await nightmare + .waitToClick(selectors.ordersIndex.createOrderButton) + .waitForURL('order/create') + .parsedUrl(); + + expect(url.hash).toContain('order/create'); + }); + + it('should create a new order', async() => { + let today = new Date().getDate(); + const url = await nightmare + .autocompleteSearch(selectors.createOrderView.clientAutocomplete, 'Tony Stark') + .datePicker(selectors.createOrderView.landedDatePicker, 0, today) + .autocompleteSearch(selectors.createOrderView.agencyAutocomplete, 'inhouse pickup') + .waitToClick(selectors.createOrderView.createButton) + .waitForURL('/catalog') + .parsedUrl(); + + + expect(url.hash).toContain('/catalog'); + }); + + it('should add the realm and type filters and obtain results', async() => { + const result = await nightmare + .waitToClick(selectors.orderCatalog.plantRealmButton) + .autocompleteSearch(selectors.orderCatalog.typeAutocomplete, 'Anthurium') + .waitForNumberOfElements('section.product', 4) + .countElement('section.product'); + + expect(result).toEqual(4); + }); + + it('should search for the item tag value +1 and find two results', async() => { + const result = await nightmare + .write(selectors.orderCatalog.itemTagValueInput, '+1\u000d') + .waitForNumberOfElements('section.product', 2) + .countElement('section.product'); + + expect(result).toEqual(2); + }); + + it('should search for the item tag categoria +1 and find two results', async() => { + const result = await nightmare + .waitToClick(selectors.orderCatalog.openTagSearch) + .autocompleteSearch(selectors.orderCatalog.tagAutocomplete, 'categoria') + .write(selectors.orderCatalog.tagValueInput, '+1') + .waitToClick(selectors.orderCatalog.searchTagButton) + .waitForNumberOfElements('section.product', 1) + .countElement('section.product'); + + expect(result).toEqual(1); + }); + + it('should remove the tag filters and have 4 results', async() => { + const result = await nightmare + .waitToClick(selectors.orderCatalog.fourthFilterRemoveButton) + .waitToClick(selectors.orderCatalog.thirdFilterRemoveButton) + .waitForNumberOfElements('.product', 4) + .countElement('section.product'); + + expect(result).toEqual(4); + }); + + it('should search for the item id 1 and have only 1 result', async() => { + const result = await nightmare + .write(selectors.orderCatalog.itemIdInput, '2\u000d') + .waitForNumberOfElements('section.product', 1) + .countElement('section.product'); + + expect(result).toEqual(1); + }); +}); diff --git a/e2e/paths/07-order-module/03_lines.spec.js b/e2e/paths/07-order-module/03_lines.spec.js new file mode 100644 index 000000000..8128fdc07 --- /dev/null +++ b/e2e/paths/07-order-module/03_lines.spec.js @@ -0,0 +1,45 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Order lines', () => { + const nightmare = createNightmare(); + beforeAll(() => { + nightmare + .loginAndModule('employee', 'order') + .accessToSearchResult(16) + .accessToSection('order.card.line'); + }); + + it('should check the order subtotal', async() => { + const result = await nightmare + .waitToGetProperty(selectors.orderLine.orderSubtotal, 'innerText'); + + expect(result).toContain('135.60'); + }); + + it('should delete the first line in the order', async() => { + const result = await nightmare + .waitToClick(selectors.orderLine.firstLineDeleteButton) + .waitToClick(selectors.orderLine.confirmButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the order subtotal has changed', async() => { + const result = await nightmare + .waitToGetProperty(selectors.orderLine.orderSubtotal, 'innerText'); + + expect(result).toContain('90.10'); + }); + + it('should confirm the whole order and redirect to ticket index filtered by clientFk', async() => { + const url = await nightmare + .waitToClick(selectors.orderLine.confirmOrder) + .waitForURL('ticket/index') + .parsedUrl(); + + expect(url.hash).toContain('ticket/index'); + expect(url.hash).toContain('clientFk'); + }); +}); diff --git a/e2e/paths/08-route-module/01_create.spec.js b/e2e/paths/08-route-module/01_create.spec.js new file mode 100644 index 000000000..1282eabd9 --- /dev/null +++ b/e2e/paths/08-route-module/01_create.spec.js @@ -0,0 +1,69 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Route create path', () => { + const nightmare = createNightmare(); + describe('as employee', () => { + beforeAll(() => { + nightmare + .loginAndModule('employee', 'route'); + }); + + it('should click on the add new route button and open the creation form', async() => { + const url = await nightmare + .waitToClick(selectors.routeIndex.addNewRouteButton) + .wait(selectors.createRouteView.workerAutocomplete) + .parsedUrl(); + + expect(url.hash).toEqual('#!/route/create'); + }); + + it(`should attempt to create a new route but fail since employee has no access rights`, async() => { + const result = await nightmare + .write(selectors.createRouteView.descriptionInput, 'faster faster!!') + .waitToClick(selectors.createRouteView.submitButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Access denied'); + }); + }); + + describe('as delivery', () => { + beforeAll(() => { + nightmare + .login('delivery') + .selectModule('route') + .changeLanguageToEnglish(); + }); + + it('should again click on the add new route button and open the creation form', async() => { + const url = await nightmare + .waitToClick(selectors.routeIndex.addNewRouteButton) + .wait(selectors.createRouteView.workerAutocomplete) + .parsedUrl(); + + expect(url.hash).toEqual('#!/route/create'); + }); + + it(`should create a new route`, async() => { + const result = await nightmare + .autocompleteSearch(selectors.createRouteView.workerAutocomplete, 'teamManagerNick') + .datePicker(selectors.createRouteView.createdDatePicker, 0, null) + .autocompleteSearch(selectors.createRouteView.vehicleAutoComplete, '4444-IMK') + .autocompleteSearch(selectors.createRouteView.agencyAutoComplete, 'Teleportation device') + .write(selectors.createRouteView.descriptionInput, 'faster faster!!') + .waitToClick(selectors.createRouteView.submitButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it(`should confirm the redirection to the created route summary`, async() => { + const url = await nightmare + .wait(selectors.routeSummary.routeId) + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + }); +}); diff --git a/e2e/paths/08-route-module/02_basic_data.spec.js b/e2e/paths/08-route-module/02_basic_data.spec.js new file mode 100644 index 000000000..63ed673d9 --- /dev/null +++ b/e2e/paths/08-route-module/02_basic_data.spec.js @@ -0,0 +1,63 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('Route basic Data path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('delivery', 'route') + .accessToSearchResult(1) + .accessToSection('route.card.basicData'); + }); + + it('should edit the route basic data', async() => { + const result = await nightmare + .autocompleteSearch(selectors.routeBasicData.workerAutoComplete, 'adminBossNick') + .autocompleteSearch(selectors.routeBasicData.vehicleAutoComplete, '1111-IMK') + .datePicker(selectors.routeBasicData.createdDateInput, 1, null) + .clearInput(selectors.routeBasicData.kmStartInput) + .write(selectors.routeBasicData.kmStartInput, 1) + .clearInput(selectors.routeBasicData.kmEndInput) + .write(selectors.routeBasicData.kmEndInput, 2) + .write(selectors.routeBasicData.startedHourInput, '0800') + .write(selectors.routeBasicData.finishedHourInput, '1230') + .waitToClick(selectors.routeBasicData.saveButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }, 15000); + + it('should confirm the worker was edited', async() => { + const worker = await nightmare + .reloadSection('route.card.basicData') + .waitToGetProperty(`${selectors.routeBasicData.workerAutoComplete} input`, 'value'); + + + expect(worker).toEqual('adminBossNick'); + }); + + it('should confirm the vehicle was edited', async() => { + const vehicle = await nightmare + .waitToGetProperty(`${selectors.routeBasicData.vehicleAutoComplete} input`, 'value'); + + + expect(vehicle).toEqual('1111-IMK'); + }); + + it('should confirm the km start was edited', async() => { + const kmStart = await nightmare + .waitToGetProperty(selectors.routeBasicData.kmStartInput, 'value'); + + + expect(kmStart).toEqual('1'); + }); + + it('should confirm the km end was edited', async() => { + const kmEnd = await nightmare + .waitToGetProperty(selectors.routeBasicData.kmEndInput, 'value'); + + + expect(kmEnd).toEqual('2'); + }); +}); diff --git a/e2e/paths/08-route-module/03_tickets.spec.js b/e2e/paths/08-route-module/03_tickets.spec.js new file mode 100644 index 000000000..24a3ebbcf --- /dev/null +++ b/e2e/paths/08-route-module/03_tickets.spec.js @@ -0,0 +1,88 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +// #1528 e2e claim/detail +xdescribe('Route basic Data path', () => { + const nightmare = createNightmare(); + + beforeAll(() => { + nightmare + .loginAndModule('delivery', 'route') + .accessToSearchResult(3) + .accessToSection('route.card.tickets'); + }); + + it('should modify the first ticket priority', async() => { + const result = await nightmare + .write(selectors.routeTickets.firstTicketPriority, 2) + .write('body', '\u000d') // simulates enter + .waitForLastSnackbar(); + + expect(result).toEqual('Data saved!'); + }); + + it('should confirm the buscamanButton is disabled', async() => { + const result = await nightmare + .evaluate(selector => { + return document.querySelector(selector); + }, `${selectors.routeTickets.buscamanButton} :disabled`); + + expect(result).toBeTruthy(); + }); + + it('should check the first ticket checkbox and confirm the buscamanButton button is no longer disabled', async() => { + const result = await nightmare + .waitToClick(selectors.routeTickets.firstTicketCheckbox) + .evaluate(selector => { + return document.querySelector(selector); + }, `${selectors.routeTickets.buscamanButton} :disabled`); + + expect(result).toBeFalsy(); + }); + + it('should check the route volume on the descriptor', async() => { + const result = await nightmare + .waitToGetProperty(selectors.routeDescriptor.volume, 'innerText'); + + expect(result).toEqual('1.1 / 18 m³'); + }); + + it('should count how many tickets are in route', async() => { + const result = await nightmare + .countElement('vn-route-tickets vn-textfield[ng-model="ticket.priority"]'); + + expect(result).toEqual(11); + }); + + it('should delete the first ticket in route', async() => { + const result = await nightmare + .waitToClick(selectors.routeTickets.firstTicketDeleteButton) + .waitToClick(selectors.routeTickets.confirmButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Ticket removed from route'); + }); + + it('should again delete the first ticket in route', async() => { + const result = await nightmare + .waitToClick(selectors.routeTickets.firstTicketDeleteButton) + .waitToClick(selectors.routeTickets.confirmButton) + .waitForLastSnackbar(); + + expect(result).toEqual('Ticket removed from route'); + }); + + it('should now count how many tickets are in route to find one less', async() => { + const result = await nightmare + .countElement('vn-route-tickets vn-textfield[ng-model="ticket.priority"]'); + + expect(result).toEqual(9); + }); + + it('should confirm the route volume on the descriptor has been updated by the changes made', async() => { + const result = await nightmare + .waitToGetProperty(selectors.routeDescriptor.volume, 'innerText'); + + expect(result).toEqual('0.9 / 18 m³'); + }); +}); diff --git a/e2e/paths/09-invoice-out-module/01_descriptor.spec.js b/e2e/paths/09-invoice-out-module/01_descriptor.spec.js new file mode 100644 index 000000000..9701d2238 --- /dev/null +++ b/e2e/paths/09-invoice-out-module/01_descriptor.spec.js @@ -0,0 +1,182 @@ +import selectors from '../../helpers/selectors.js'; +import createNightmare from '../../helpers/nightmare'; + +describe('InvoiceOut descriptor path', () => { + const nightmare = createNightmare(); + + describe('as Administrative', () => { + beforeAll(() => { + nightmare + .loginAndModule('administrative', 'ticket'); + }); + + it('should search for tickets with an specific invoiceOut', async() => { + const result = await nightmare + .waitToClick(selectors.ticketsIndex.openAdvancedSearchButton) + .write(selectors.ticketsIndex.advancedSearchInvoiceOut, 'T2222222') + .waitToClick(selectors.ticketsIndex.advancedSearchButton) + .waitForNumberOfElements(selectors.ticketsIndex.searchResult, 1) + .countElement(selectors.ticketsIndex.searchResult); + + expect(result).toEqual(1); + }); + + it('should navigate to the invoiceOut index', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.invoiceOutButton) + .wait(selectors.invoiceOutIndex.searchInvoiceOutInput) + .parsedUrl(); + + expect(url.hash).toEqual('#!/invoice-out/index'); + }); + + it('should search for the target invoiceOut', async() => { + const result = await nightmare + .write(selectors.invoiceOutIndex.searchInvoiceOutInput, 'T2222222') + .waitToClick(selectors.invoiceOutIndex.searchButton) + .waitForNumberOfElements(selectors.invoiceOutIndex.searchResult, 1) + .countElement(selectors.invoiceOutIndex.searchResult); + + expect(result).toEqual(1); + }); + + it(`should click on the search result to access to the invoiceOut summary`, async() => { + const url = await nightmare + .accessToSearchResult('T2222222') + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it('should delete the invoiceOut using the descriptor more menu', async() => { + const result = await nightmare + .waitToClick(selectors.invoiceOutDescriptor.moreMenu) + .waitToClick(selectors.invoiceOutDescriptor.moreMenuDeleteInvoiceOut) + .waitToClick(selectors.invoiceOutDescriptor.acceptDeleteButton) + .waitForLastSnackbar(); + + expect(result).toEqual('InvoiceOut deleted'); + }); + + it('should have been relocated to the invoiceOut index', async() => { + const url = await nightmare + .parsedUrl(); + + expect(url.hash).toEqual('#!/invoice-out/index'); + }); + + it(`should search for the deleted invouceOut to find no results`, async() => { + const result = await nightmare + .write(selectors.invoiceOutIndex.searchInvoiceOutInput, 'T2222222') + .waitToClick(selectors.invoiceOutIndex.searchButton) + .waitForNumberOfElements(selectors.invoiceOutIndex.searchResult, 0) + .countElement(selectors.invoiceOutIndex.searchResult); + + expect(result).toEqual(0); + }); + + it('should navigate to the ticket index', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.ticketsButton) + .wait(selectors.ticketsIndex.searchTicketInput) + .parsedUrl(); + + expect(url.hash).toEqual('#!/ticket/index'); + }); + + it('should search for tickets with an specific invoiceOut to find no results', async() => { + const result = await nightmare + .waitToClick(selectors.ticketsIndex.openAdvancedSearchButton) + .write(selectors.ticketsIndex.advancedSearchInvoiceOut, 'T2222222') + .waitToClick(selectors.ticketsIndex.advancedSearchButton) + .waitForNumberOfElements(selectors.ticketsIndex.searchResult, 0) + .countElement(selectors.ticketsIndex.searchResult); + + expect(result).toEqual(0); + }); + + it('should now navigate to the invoiceOut index', async() => { + const url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .wait(selectors.globalItems.applicationsMenuVisible) + .waitToClick(selectors.globalItems.invoiceOutButton) + .wait(selectors.invoiceOutIndex.searchInvoiceOutInput) + .parsedUrl(); + + expect(url.hash).toEqual('#!/invoice-out/index'); + }); + + it(`should search and access to the invoiceOut summary`, async() => { + const url = await nightmare + .accessToSearchResult('T1111111') + .waitForURL('/summary') + .parsedUrl(); + + expect(url.hash).toContain('/summary'); + }); + + it(`should check the invoiceOut is booked in the summary data`, async() => { + const result = await nightmare + .waitForTextInElement(selectors.invoiceOutSummary.bookedLabel, '/') + .waitToGetProperty(selectors.invoiceOutSummary.bookedLabel, 'innerText'); + + expect(result.length).toBeGreaterThan(1); + }); + + it('should re-book the invoiceOut using the descriptor more menu', async() => { + const result = await nightmare + .waitToClick(selectors.invoiceOutDescriptor.moreMenu) + .waitToClick(selectors.invoiceOutDescriptor.moreMenuBookInvoiceOut) + .waitToClick(selectors.invoiceOutDescriptor.acceptBookingButton) + .waitForLastSnackbar(); + + expect(result).toEqual('InvoiceOut booked'); + }); + + it(`should check the invoiceOut booked in the summary data`, async() => { + let today = new Date(); + + let day = today.getDate(); + if (day < 10) day = `0${day}`; + + let month = (today.getMonth() + 1); + if (month < 10) month = `0${month}`; + + let expectedDate = `${day}/${month}/${today.getFullYear()}`; + + const result = await nightmare + .waitToGetProperty(selectors.invoiceOutSummary.bookedLabel, 'innerText'); + + expect(result).toEqual(expectedDate); + }); + }); + + describe('as salesPerson', () => { + beforeAll(() => { + nightmare + .loginAndModule('salesPerson', 'invoiceOut') + .accessToSearchResult('A1111111'); + }); + + it(`should check the salesPerson role doens't see the book option in the more menu`, async() => { + const result = await nightmare + .waitToClick(selectors.invoiceOutDescriptor.moreMenu) + .wait(selectors.invoiceOutDescriptor.moreMenuShowInvoiceOutPdf) + .exists(selectors.invoiceOutDescriptor.moreMenuBookInvoiceOut); + + expect(result).toBeFalsy(); + }); + + it(`should check the salesPerson role doens't see the delete option in the more menu`, async() => { + const result = await nightmare + .exists(selectors.invoiceOutDescriptor.moreMenuDeleteInvoiceOut); + + expect(result).toBeFalsy(); + }); + }); +}); diff --git a/e2e/paths/client-module/01_create_client.spec.js b/e2e/paths/client-module/01_create_client.spec.js deleted file mode 100644 index 4b7df7464..000000000 --- a/e2e/paths/client-module/01_create_client.spec.js +++ /dev/null @@ -1,114 +0,0 @@ -import selectors from '../../helpers/selectors'; -import createNightmare from '../../helpers/helpers'; - -describe('create client path', () => { - let nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should access to the clients index by clicking the clients button', () => { - return nightmare - .click(selectors.moduleAccessView.clientsSectionButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it(`should search for the user Carol Danvers to confirm it isn't created yet`, () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Carol Danvers') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 0) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(0); - }); - }); - - it('should access to the create client view by clicking the create-client floating button', () => { - return nightmare - .click(selectors.clientsIndex.createClientButton) - .wait(selectors.createClientView.createButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/create'); - }); - }); - - it('should receive an error when clicking the create button having all the form fields empty', () => { - return nightmare - .click(selectors.createClientView.createButton) - .waitForSnackbar() - .then(result => { - expect(result).toEqual('Some fields are invalid'); - }); - }); - - it('should receive an error when clicking the create button having name and Business name fields empty', () => { - return nightmare - .type(selectors.createClientView.taxNumber, '16195279J') - .type(selectors.createClientView.userName, 'CaptainMarvel') - .type(selectors.createClientView.email, 'CarolDanvers@verdnatura.es') - .waitToClick(selectors.createClientView.salesPersonInput) - .waitToClick(selectors.createClientView.salesBruceBannerOption) - .click(selectors.createClientView.createButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Some fields are invalid'); - }); - }); - - it(`should attempt to create a new user with all it's data but wrong email`, () => { - return nightmare - .type(selectors.createClientView.name, 'Carol Danvers') - .type(selectors.createClientView.socialName, 'AVG tax') - .clearInput(selectors.createClientView.email) - .type(selectors.createClientView.email, 'incorrect email format') - .click(selectors.createClientView.createButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Some fields are invalid'); - }); - }); - - it(`should create a new user with all correct data`, () => { - return nightmare - .clearInput(selectors.createClientView.email) - .type(selectors.createClientView.email, 'caroldanvers@verdnatura.es') - .click(selectors.createClientView.createButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Data saved!'); - }); - }); - - it('should click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it(`should search for the user Carol Danvers to confirm it exists`, () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Carol Danvers') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); -}); diff --git a/e2e/paths/client-module/02_edit_basic_data.spec.js b/e2e/paths/client-module/02_edit_basic_data.spec.js deleted file mode 100644 index ea58176cf..000000000 --- a/e2e/paths/client-module/02_edit_basic_data.spec.js +++ /dev/null @@ -1,130 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('Edit basicData path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should search for the user Bruce Wayne', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Bruce Wayne') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it('should click on the search result to access to the clients basic data', () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Bruce Wayne') - .waitToClick(selectors.clientsIndex.searchResult) - .waitForURL('basic-data') - .url() - .then(url => { - expect(url).toContain('basic-data'); - }); - }); - - it('should edit the client basic data', () => { - return nightmare - .wait(selectors.clientBasicData.nameInput) - .clearInput(selectors.clientBasicData.nameInput) - .type(selectors.clientBasicData.nameInput, 'Ororo Munroe') - .clearInput(selectors.clientBasicData.contactInput) - .type(selectors.clientBasicData.contactInput, 'Black Panther') - .clearInput(selectors.clientBasicData.phoneInput) - .type(selectors.clientBasicData.phoneInput, '123456789') - .clearInput(selectors.clientBasicData.mobileInput) - .type(selectors.clientBasicData.mobileInput, '987654321') - .clearInput(selectors.clientBasicData.emailInput) - .type(selectors.clientBasicData.emailInput, 'Storm@verdnatura.es') - .waitToClick(selectors.clientBasicData.salesPersonInput) - .waitToClick(selectors.clientBasicData.salesPersonOptionOne) - .waitToClick(selectors.clientBasicData.channelInput) - .waitToClick(selectors.clientBasicData.channelMetropolisOption) - .click(selectors.clientBasicData.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toEqual('Data saved!'); - }); - }); - - it('should confirm the name have been edited', () => { - return nightmare - .click(selectors.clientFiscalData.fiscalDataButton) - .wait(selectors.clientFiscalData.addressInput) - .click(selectors.clientBasicData.basicDataButton) - .wait(selectors.clientBasicData.nameInput) - .getInputValue(selectors.clientBasicData.nameInput) - .then(result => { - expect(result).toEqual('Ororo Munroe'); - }); - }); - - it('should confirm the contact name have been edited', () => { - return nightmare - .getInputValue(selectors.clientBasicData.contactInput) - .then(result => { - expect(result).toEqual('Black Panther'); - }); - }); - - it('should confirm the landline phone number have been added', () => { - return nightmare - .getInputValue(selectors.clientBasicData.phoneInput) - .then(result => { - expect(result).toEqual('123456789'); - }); - }); - - it('should confirm the mobile phone number have been added', () => { - return nightmare - .getInputValue(selectors.clientBasicData.mobileInput) - .then(result => { - expect(result).toEqual('987654321'); - }); - }); - - it('should confirm the email have been edited', () => { - return nightmare - .getInputValue(selectors.clientBasicData.emailInput) - .then(result => { - expect(result).toEqual('Storm@verdnatura.es'); - }); - }); - - it('should confirm the sales person have been selected', () => { - return nightmare - .getInputValue(selectors.clientBasicData.salesPersonInput) - .then(result => { - expect(result).toEqual('accessory accessory'); - }); - }); - - it('should confirm the channel have been selected', () => { - return nightmare - .getInputValue(selectors.clientBasicData.channelInput) - .then(result => { - expect(result).toEqual('Metropolis newspaper'); - }); - }); -}); diff --git a/e2e/paths/client-module/03_edit_fiscal_data.spec.js b/e2e/paths/client-module/03_edit_fiscal_data.spec.js deleted file mode 100644 index 099c422ab..000000000 --- a/e2e/paths/client-module/03_edit_fiscal_data.spec.js +++ /dev/null @@ -1,279 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('Edit fiscalData path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should search for the user Bruce Banner', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Bruce Banner') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - describe('Confirm all addresses have EQtax false for future propagation test', () => { - it(`should click on the search result to access to the client's addresses`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Bruce Banner') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientAddresses.addressesButton) - .waitForURL('/addresses/list') - .url() - .then(url => { - expect(url).toContain('/addresses/list'); - }); - }); - - it(`should click on the 1st edit icon to check EQtax is checked`, () => { - return nightmare - .waitToClick(selectors.clientAddresses.firstEditButton) - .wait(selectors.clientAddresses.equalizationTaxCheckboxLabel) - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientAddresses.equalizationTaxCheckboxLabel) - .then(value => { - expect(value).toBeFalsy(); - }); - }); - - it(`should go back to addresses then select the second one and confirm the EQtax is checked`, () => { - return nightmare - .waitToClick(selectors.clientAddresses.addressesButton) - .waitToClick(selectors.clientAddresses.secondEditButton) - .wait(selectors.clientAddresses.equalizationTaxCheckboxLabel) - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientAddresses.equalizationTaxCheckboxLabel) - .then(value => { - expect(value).toBeFalsy(); - }); - }); - }); - - it(`should click on the fiscal data button to start editing`, () => { - return nightmare - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .waitForURL('fiscal-data') - .url() - .then(url => { - expect(url).toContain('fiscal-data'); - }); - }); - - it('should edit the clients fiscal data', () => { - return nightmare - .wait(selectors.clientFiscalData.socialNameInput) - .clearInput(selectors.clientFiscalData.socialNameInput) - .type(selectors.clientFiscalData.socialNameInput, 'SMASH!') - .clearInput(selectors.clientFiscalData.fiscalIdInput) - .type(selectors.clientFiscalData.fiscalIdInput, '94980061C') - .waitToClick(selectors.clientFiscalData.equalizationTaxCheckboxLabel) - .clearInput(selectors.clientFiscalData.addressInput) - .type(selectors.clientFiscalData.addressInput, 'Somewhere edited') - .clearInput(selectors.clientFiscalData.cityInput) - .type(selectors.clientFiscalData.cityInput, 'N/A') - .clearInput(selectors.clientFiscalData.postcodeInput) - .type(selectors.clientFiscalData.postcodeInput, '12345') - .waitToClick(selectors.clientFiscalData.provinceInput) - .waitToClick(selectors.clientFiscalData.provinceFifthOption) - .waitToClick(selectors.clientFiscalData.activeCheckboxLabel) - .waitToClick(selectors.clientFiscalData.invoiceByAddressCheckboxInput) - .waitToClick(selectors.clientFiscalData.verifiedDataCheckboxInput) - .waitToClick(selectors.clientFiscalData.hasToInvoiceCheckboxLabel) - .waitToClick(selectors.clientFiscalData.invoiceByMailCheckboxLabel) - .waitToClick(selectors.clientFiscalData.viesCheckboxInput) - .click(selectors.clientFiscalData.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toEqual('Data saved!'); - }); - }); - - it('should propagate the Equalization tax', () => { - return nightmare - .waitToClick(selectors.clientFiscalData.acceptPropagationButton) - .waitForSnackbar() - .then(result => { - expect(result).toEqual('Equivalent tax spreaded'); - }); - }); - - describe('confirm all addresses have now EQtax checked', () => { - it(`should click on the addresses button to access to the client's addresses`, () => { - return nightmare - .waitToClick(selectors.clientAddresses.addressesButton) - .waitForURL('/addresses/list') - .url() - .then(url => { - expect(url).toContain('/addresses/list'); - }); - }); - - it(`should click on the 1st edit icon to confirm EQtax is checked`, () => { - return nightmare - .waitToClick(selectors.clientAddresses.firstEditButton) - .wait(selectors.clientAddresses.equalizationTaxCheckboxLabel) - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientAddresses.equalizationTaxCheckboxLabel) - .then(value => { - expect(value).toBeTruthy(); - }); - }); - - it(`should go back to addresses then select the second one and confirm the EQtax is checked`, () => { - return nightmare - .waitToClick(selectors.clientAddresses.addressesButton) - .waitToClick(selectors.clientAddresses.secondEditButton) - .wait(selectors.clientAddresses.equalizationTaxCheckboxLabel) - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientAddresses.equalizationTaxCheckboxLabel) - .then(value => { - expect(value).toBeTruthy(); - }); - }); - }); - - it('should navigate back to fiscal data to confirm it have been edited', () => { - return nightmare - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .wait(selectors.clientFiscalData.socialNameInput) - .getInputValue(selectors.clientFiscalData.socialNameInput) - .then(result => { - expect(result).toEqual('SMASH!'); - }); - }); - - it('should confirm the fiscal id have been edited', () => { - return nightmare - .getInputValue(selectors.clientFiscalData.fiscalIdInput) - .then(result => { - expect(result).toEqual('94980061C'); - }); - }); - - it('should confirm Equalization tax checkbox is checked', () => { - return nightmare - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientFiscalData.equalizationTaxCheckboxLabel) - .then(value => { - expect(value).toBeTruthy(); - }); - }); - - it('should confirm the address have been edited', () => { - return nightmare - .getInputValue(selectors.clientFiscalData.addressInput) - .then(result => { - expect(result).toEqual('Somewhere edited'); - }); - }); - - it('should confirm the city have been edited', () => { - return nightmare - .getInputValue(selectors.clientFiscalData.cityInput) - .then(result => { - expect(result).toEqual('N/A'); - }); - }); - - it('should confirm the postcode have been edited', () => { - return nightmare - .getInputValue(selectors.clientFiscalData.postcodeInput) - .then(result => { - expect(result).toEqual('12345'); - }); - }); - - it(`should confirm the province have been selected`, () => { - return nightmare - .getInputValue(selectors.clientFiscalData.provinceInput) - .then(result => { - expect(result).toEqual('Province two'); - }); - }); - - it('should confirm active checkbox is unchecked', () => { - return nightmare - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientFiscalData.activeCheckboxLabel) - .then(value => { - expect(value).toBeFalsy(); - }); - }); - - it('should confirm invoice by address checkbox is unchecked', () => { - return nightmare - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientFiscalData.invoiceByAddressCheckboxInput) - .then(value => { - expect(value).toBeFalsy(); - }); - }); - - it('should confirm Verified data checkbox is checked', () => { - return nightmare - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientFiscalData.verifiedDataCheckboxInput) - .then(value => { - expect(value).toBeTruthy(); - }); - }); - - it('should confirm Has to invoice checkbox is unchecked', () => { - return nightmare - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientFiscalData.hasToInvoiceCheckboxLabel) - .then(value => { - expect(value).toBeFalsy(); - }); - }); - - it('should confirm Invoice by mail checkbox is unchecked', () => { - return nightmare - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientFiscalData.invoiceByMailCheckboxLabel) - .then(value => { - expect(value).toBeFalsy(); - }); - }); - - it('should confirm Vies checkbox is checked', () => { - return nightmare - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientFiscalData.viesCheckboxInput) - .then(value => { - expect(value).toBeTruthy(); - }); - }); -}); diff --git a/e2e/paths/client-module/04_edit_pay_method.spec.js b/e2e/paths/client-module/04_edit_pay_method.spec.js deleted file mode 100644 index 108a5494e..000000000 --- a/e2e/paths/client-module/04_edit_pay_method.spec.js +++ /dev/null @@ -1,122 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('Edit pay method path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should search for the user Bruce Banner', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Bruce Banner') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the client's pay method`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Bruce Banner') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientPayMethod.payMethodButton) - .waitForURL('billing-data') - .url() - .then(url => { - expect(url).toContain('billing-data'); - }); - }); - - it(`should attempt to edit the Pay method without an IBAN but fail`, () => { - return nightmare - .waitToClick(selectors.clientPayMethod.payMethodInput) - .waitToClick(selectors.clientPayMethod.payMethodIBANOption) - .clearInput(selectors.clientPayMethod.dueDayInput) - .type(selectors.clientPayMethod.dueDayInput, '60') - .waitToClick(selectors.clientPayMethod.receivedCoreVNHCheckbox) - .waitToClick(selectors.clientPayMethod.receivedCoreVNLCheckbox) - .waitToClick(selectors.clientPayMethod.receivedB2BVNLCheckbox) - .waitToClick(selectors.clientPayMethod.saveButton) - .waitToClick(selectors.clientPayMethod.cancelNotificationButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Error'); - }); - }); - - it(`should add the IBAN`, () => { - return nightmare - .clearInput(selectors.clientPayMethod.IBANInput) - .type(selectors.clientPayMethod.IBANInput, 'ES91 2100 0418 4502 0005 1332') - .waitToClick(selectors.clientPayMethod.saveButton) - .waitToClick(selectors.clientPayMethod.cancelNotificationButton) - .waitForSnackbar() - .then(result => { - expect(result).toEqual('Data saved!'); - }); - }); - - it(`should confirm the IBAN pay method is sucessfully saved`, () => { - return nightmare - .getInputValue(selectors.clientPayMethod.payMethodInput) - .then(result => { - expect(result).toEqual('PayMethod with IBAN'); - }); - }); - - it('should confirm the due day have been edited', () => { - return nightmare - .getInputValue(selectors.clientPayMethod.dueDayInput) - .then(result => { - expect(result).toEqual('60'); - }); - }); - - it('should confirm Received core VNH checkbox is unchecked', () => { - return nightmare - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientPayMethod.receivedCoreVNHCheckbox) - .then(value => { - expect(value).toBeFalsy(); - }); - }); - - it('should confirm Received core VNL checkbox is unchecked', () => { - return nightmare - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientPayMethod.receivedCoreVNLCheckbox) - .then(value => { - expect(value).toBeFalsy(); - }); - }); - - it('should confirm Received B2B VNL checkbox is unchecked', () => { - return nightmare - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientPayMethod.receivedB2BVNLCheckbox) - .then(value => { - expect(value).toBeFalsy(); - }); - }); -}); diff --git a/e2e/paths/client-module/05_add_address.spec.js b/e2e/paths/client-module/05_add_address.spec.js deleted file mode 100644 index e765aea72..000000000 --- a/e2e/paths/client-module/05_add_address.spec.js +++ /dev/null @@ -1,128 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('Add address path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should search for the user Bruce Banner', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Bruce Banner') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the client addresses`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Bruce Banner') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientAddresses.addressesButton) - .waitForURL('addresses/list') - .url() - .then(url => { - expect(url).toContain('addresses/list'); - }); - }); - - it(`should click on the add new address button to access to the new address form`, () => { - return nightmare - .waitToClick(selectors.clientAddresses.createAddress) - .waitForURL('addresses/create') - .url() - .then(url => { - expect(url).toContain('addresses/create'); - }); - }); - - it('should receive an error after clicking save button as consignee, street and town fields are empty', () => { - return nightmare - .waitToClick(selectors.clientAddresses.defaultCheckboxInput) - .clearInput(selectors.clientAddresses.streetAddressInput) - .type(selectors.clientAddresses.postcodeInput, '10022') - .waitToClick(selectors.clientAddresses.provinceInput) - .waitToClick(selectors.clientAddresses.provinceSecondOption) - .waitToClick(selectors.clientAddresses.agencyInput) - .waitToClick(selectors.clientAddresses.agenctySecondOption) - .type(selectors.clientAddresses.phoneInput, '999887744') - .type(selectors.clientAddresses.mobileInput, '999887744') - .waitToClick(selectors.clientFiscalData.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Some fields are invalid'); - }); - }); - - it(`should create a new address with all it's data`, () => { - return nightmare - .type(selectors.clientAddresses.consigneeInput, 'Bruce Bunner') - .type(selectors.clientAddresses.streetAddressInput, '320 Park Avenue New York') - .type(selectors.clientAddresses.cityInput, 'New York') - .click(selectors.clientAddresses.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Data saved!'); - }); - }); - - it(`should click on the addresses button confirm the new address exists and it's the default one`, () => { - return nightmare - .waitToClick(selectors.clientAddresses.addressesButton) - .wait(selectors.clientAddresses.defaultAddress) - .getInnerText(selectors.clientAddresses.defaultAddress) - .then(result => { - expect(result).toContain('320 Park Avenue New York'); - }); - }); - - it(`should click on the make default icon of the second address then confirm it is the default one now`, () => { - return nightmare - .waitToClick(selectors.clientAddresses.secondMakeDefaultStar) - .waitForTextInElement(selectors.clientAddresses.defaultAddress, 'Somewhere in Thailand') - .getInnerText(selectors.clientAddresses.defaultAddress) - .then(result => { - expect(result).toContain('Somewhere in Thailand'); - }); - }); - - it(`should click on the edit icon of the default address`, () => { - return nightmare - .waitForTextInElement(selectors.clientAddresses.defaultAddress, 'Somewhere in Thailand') - .waitToClick(selectors.clientAddresses.firstEditButton) - .waitForURL('/edit') - .url() - .then(result => { - expect(result).toContain('/edit'); - }); - }); - - it(`should click on the active checkbox and receive an error to save it becouse it is the default address`, () => { - return nightmare - .waitToClick(selectors.clientAddresses.activeCheckbox) - .waitToClick(selectors.clientAddresses.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Error:'); - }); - }); -}); diff --git a/e2e/paths/client-module/06_add_address_notes.spec.js b/e2e/paths/client-module/06_add_address_notes.spec.js deleted file mode 100644 index 0c2008bd0..000000000 --- a/e2e/paths/client-module/06_add_address_notes.spec.js +++ /dev/null @@ -1,97 +0,0 @@ -// import selectors from '../../helpers/selectors.js'; -// import createNightmare from '../../helpers/helpers'; - -// describe('Add address notes path', () => { -// const nightmare = createNightmare(); - -// beforeAll(() => { -// return nightmare -// .waitForLogin('developer'); -// }); - -// it('should click on the Clients button of the top bar menu', () => { -// return nightmare -// .waitToClick(selectors.globalItems.applicationsMenuButton) -// .wait(selectors.globalItems.applicationsMenuVisible) -// .waitToClick(selectors.globalItems.clientsButton) -// .wait(selectors.clientsIndex.createClientButton) -// .parsedUrl() -// .then(url => { -// expect(url.hash).toEqual('#!/clients'); -// }); -// }); - -// it('should search for the user Petter Parker', () => { -// return nightmare -// .wait(selectors.clientsIndex.searchResult) -// .type(selectors.clientsIndex.searchClientInput, 'Petter Parker') -// .click(selectors.clientsIndex.searchButton) -// .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) -// .countSearchResults(selectors.clientsIndex.searchResult) -// .then(result => { -// expect(result).toEqual(1); -// }); -// }); - -// it(`should click on the search result to access to the client addresses`, () => { -// return nightmare -// .waitForTextInElement(selectors.clientsIndex.searchResult, 'Petter Parker') -// .waitToClick(selectors.clientsIndex.searchResult) -// .waitToClick(selectors.clientAddresses.addressesButton) -// .waitForURL('addresses/list') -// .url() -// .then(url => { -// expect(url).toContain('addresses/list'); -// }); -// }); - -// it(`should click on the edit icon of the default address`, () => { -// return nightmare -// .waitForTextInElement(selectors.clientAddresses.defaultAddress, '20 Ingram Street') -// .waitToClick(selectors.clientAddresses.firstEditButton) -// .waitForURL('/edit') -// .url() -// .then(result => { -// expect(result).toContain('/edit'); -// }); -// }); - -// it('should not save a description without observation type', () => { -// return nightmare -// .waitToClick(selectors.clientAddresses.addObservationButton) -// .wait(selectors.clientAddresses.firstObservationDescriptionInput) -// .type(selectors.clientAddresses.firstObservationDescriptionInput, 'first description') -// .waitToClick(selectors.clientAddresses.saveButton) -// .waitForSnackbar() -// .then(result => { -// expect(result).toContain('Some fields are invalid'); -// }); -// }); - -// it('should not save an observation type without description', () => { -// return nightmare -// .clearInput(selectors.clientAddresses.firstObservationDescriptionInput) -// .waitToClick(selectors.clientAddresses.firstObservationTypeSelect) -// .waitToClick(selectors.clientAddresses.firstObservationTypeSelectOptionOne) -// .waitToClick(selectors.clientAddresses.saveButton) -// .waitForSnackbar() -// .then(result => { -// expect(result).toContain('Some fields are invalid'); -// }); -// }); - -// it('should create two new observations', () => { -// return nightmare -// .type(selectors.clientAddresses.firstObservationDescriptionInput, 'first description') -// .waitToClick(selectors.clientAddresses.addObservationButton) -// .waitToClick(selectors.clientAddresses.secondObservationTypeSelect) -// .waitToClick(selectors.clientAddresses.secondObservationTypeSelectOptionTwo) -// .type(selectors.clientAddresses.secondObservationDescriptionInput, 'second description') -// .waitToClick(selectors.clientAddresses.saveButton) -// .waitForSnackbar() -// .then(result => { -// expect(result).toContain('pepinillos saved!'); -// }); -// }); -// }); - diff --git a/e2e/paths/client-module/07_edit_web_access.spec.js b/e2e/paths/client-module/07_edit_web_access.spec.js deleted file mode 100644 index bb0c29304..000000000 --- a/e2e/paths/client-module/07_edit_web_access.spec.js +++ /dev/null @@ -1,78 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('Edit web access path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should search for the user Bruce Banner', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Bruce Banner') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the client's web access`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Bruce Banner') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientWebAccess.webAccessButton) - .waitForURL('web-access') - .url() - .then(url => { - expect(url).toContain('web-access'); - }); - }); - - it(`should uncheck the Enable web access checkbox and update the name`, () => { - return nightmare - .waitToClick(selectors.clientWebAccess.enableWebAccessCheckbox) - .clearInput(selectors.clientWebAccess.userNameInput) - .type(selectors.clientWebAccess.userNameInput, 'Hulk') - .waitToClick(selectors.clientWebAccess.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain(`Data saved!`); - }); - }); - - it('should confirm web access is unchecked and name updated', () => { - return nightmare - .waitToClick(selectors.clientBasicData.basicDataButton) - .wait(selectors.clientBasicData.nameInput) - .waitToClick(selectors.clientWebAccess.webAccessButton) - .wait(selectors.clientWebAccess.enableWebAccessCheckbox) - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientWebAccess.enableWebAccessCheckbox) - .then(value => { - expect(value).toBeFalsy(); - return nightmare - .getInputValue(selectors.clientWebAccess.userNameInput); - }) - .then(result => { - expect(result).toEqual('Hulk'); - }); - }); -}); diff --git a/e2e/paths/client-module/08_add_notes.spec.js b/e2e/paths/client-module/08_add_notes.spec.js deleted file mode 100644 index 5193ee7d4..000000000 --- a/e2e/paths/client-module/08_add_notes.spec.js +++ /dev/null @@ -1,76 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('Add notes path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should search for the user Bruce Banner', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Bruce Banner') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the client's notes`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Bruce Banner') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientNotes.notesButton) - .waitForURL('notes/list') - .url() - .then(url => { - expect(url).toContain('notes/list'); - }); - }); - - it(`should click on the add note button`, () => { - return nightmare - .waitToClick(selectors.clientNotes.addNoteFloatButton) - .waitForURL('/notes/create') - .url() - .then(url => { - expect(url).toContain('/notes/create'); - }); - }); - - it(`should create a note`, () => { - return nightmare - .type(selectors.clientNotes.noteInput, 'Meeting with Black Widow 21st 9am') - .click(selectors.clientNotes.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toEqual('Data saved!'); - }); - }); - - it('should confirm the note was created', () => { - return nightmare - .wait(selectors.clientNotes.firstNoteText) - .getInnerText(selectors.clientNotes.firstNoteText) - .then(value => { - expect(value).toEqual('Meeting with Black Widow 21st 9am'); - }); - }); -}); diff --git a/e2e/paths/client-module/09_add_credit.spec.js b/e2e/paths/client-module/09_add_credit.spec.js deleted file mode 100644 index c5ad8088d..000000000 --- a/e2e/paths/client-module/09_add_credit.spec.js +++ /dev/null @@ -1,78 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('Add credit path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should search for the user Petter Parker', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Petter Parker') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the client's credit`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Petter Parker') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientCredit.creditButton) - .waitForURL('credit/list') - .url() - .then(url => { - expect(url).toContain('credit/list'); - }); - }); - - it(`should click on the add credit button`, () => { - return nightmare - .waitToClick(selectors.clientCredit.addCreditFloatButton) - .waitForURL('/credit/create') - .url() - .then(url => { - expect(url).toContain('/credit/create'); - }); - }); - - it(`should edit the credit`, () => { - return nightmare - .clearInput(selectors.clientCredit.creditInput) - .type(selectors.clientCredit.creditInput, 999) - .click(selectors.clientCredit.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toEqual('Data saved!'); - }); - }); - - it('should confirm the credit was updated', () => { - return nightmare - .wait(selectors.clientCredit.firstCreditText) - .getInnerText(selectors.clientCredit.firstCreditText) - .then(value => { - expect(value).toContain(999); - expect(value).toContain('developer'); - }); - }); -}); diff --git a/e2e/paths/client-module/10_add_greuge.spec.js b/e2e/paths/client-module/10_add_greuge.spec.js deleted file mode 100644 index 9f8f93771..000000000 --- a/e2e/paths/client-module/10_add_greuge.spec.js +++ /dev/null @@ -1,90 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('Add greuge path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should search for the user Petter Parker', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Petter Parker') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the client's greuge`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Petter Parker') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientGreuge.greugeButton) - .waitForURL('greuge/list') - .url() - .then(url => { - expect(url).toContain('greuge/list'); - }); - }); - - it(`should click on the add greuge button`, () => { - return nightmare - .waitToClick(selectors.clientGreuge.addGreugeFloatButton) - .waitForURL('greuge/create') - .url() - .then(url => { - expect(url).toContain('greuge/create'); - }); - }); - - it(`should receive an error if all fields are empty but date and type on submit`, () => { - return nightmare - .waitToClick(selectors.clientGreuge.typeInput) - .waitToClick(selectors.clientGreuge.typeSecondOption) - .click(selectors.clientGreuge.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Some fields are invalid'); - }); - }); - - it(`should create a new greuge with all its data`, () => { - return nightmare - .type(selectors.clientGreuge.amountInput, 999) - .type(selectors.clientGreuge.descriptionInput, 'new armor for Batman!') - .click(selectors.clientGreuge.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Data saved!'); - }); - }); - - it('should confirm the greuge was added to the list', () => { - return nightmare - .wait(selectors.clientGreuge.firstGreugeText) - .getInnerText(selectors.clientGreuge.firstGreugeText) - .then(value => { - expect(value).toContain(999); - expect(value).toContain('new armor for Batman!'); - expect(value).toContain('Diff'); - }); - }); -}); diff --git a/e2e/paths/client-module/11_mandate.spec.js b/e2e/paths/client-module/11_mandate.spec.js deleted file mode 100644 index 9728afa02..000000000 --- a/e2e/paths/client-module/11_mandate.spec.js +++ /dev/null @@ -1,58 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('mandate path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should search for the user Petter Parker', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Petter Parker') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the client's mandate`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Petter') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientMandate.mandateButton) - .waitForURL('mandate') - .url() - .then(url => { - expect(url).toContain('mandate'); - }); - }); - - it('should confirm the client has a mandate of the CORE type', () => { - return nightmare - .wait(selectors.clientMandate.firstMandateText) - .getInnerText(selectors.clientMandate.firstMandateText) - .then(value => { - expect(value).toContain('1'); - expect(value).toContain('WAY'); - expect(value).toContain('CORE'); - }); - }); -}); diff --git a/e2e/paths/client-module/12_lock_of_verified_data.spec.js b/e2e/paths/client-module/12_lock_of_verified_data.spec.js deleted file mode 100644 index 764476e62..000000000 --- a/e2e/paths/client-module/12_lock_of_verified_data.spec.js +++ /dev/null @@ -1,472 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('lock verified data path', () => { - const nightmare = createNightmare(); - - describe('as salesPerson', () => { - beforeAll(() => { - return nightmare - .waitForLogin('salesPerson'); - }); - - it('should click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should search for the user Petter Parker', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Petter Parker') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the client's fiscal data`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Petter Parker') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .waitForURL('fiscal-data') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('fiscal-data'); - }); - }); - - it(`should click on the fiscal data button to start editing`, () => { - return nightmare - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .waitForURL('fiscal-data') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('fiscal-data'); - }); - }); - - it('should confirm verified data button is disabled for salesPerson', () => { - return nightmare - .wait(selectors.clientFiscalData.verifiedDataCheckboxInput) - .evaluate(selector => { - return document.querySelector(selector).className; - }, 'body > vn-app > vn-vertical > vn-vertical > vn-client-card > vn-main-block > vn-horizontal > vn-one > vn-vertical > vn-client-fiscal-data > form > vn-card > div > vn-horizontal:nth-child(5) > vn-check:nth-child(3) > label') - .then(result => { - expect(result).toContain('is-disabled'); - }); - }); - - it('should edit the social name', () => { - return nightmare - .wait(selectors.clientFiscalData.socialNameInput) - .clearInput(selectors.clientFiscalData.socialNameInput) - .type(selectors.clientFiscalData.socialNameInput, 'salesPerson was here') - .click(selectors.clientFiscalData.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toEqual('Data saved!'); - }); - }); - - it('should confirm the social name have been edited', () => { - return nightmare - .waitToClick(selectors.clientBasicData.basicDataButton) - .wait(selectors.clientBasicData.nameInput) - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .wait(selectors.clientFiscalData.socialNameInput) - .getInputValue(selectors.clientFiscalData.socialNameInput) - .then(result => { - expect(result).toEqual('salesPerson was here'); - }); - }); - }); - - describe('as administrative', () => { - beforeAll(() => { - return nightmare - .waitToClick(selectors.globalItems.logOutButton) - .waitForLogin('administrative'); - }); - - it('should navigate to clients index', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should search again for the user Petter Parker', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Petter Parker') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the Petter Parkers fiscal data`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Petter Parker') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .waitForURL('fiscal-data') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('fiscal-data'); - }); - }); - - it(`should click on the fiscal data button`, () => { - return nightmare - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .waitForURL('fiscal-data') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('fiscal-data'); - }); - }); - - it('should confirm verified data button is enabled for administrative', () => { - return nightmare - .wait(selectors.clientFiscalData.verifiedDataCheckboxInput) - .evaluate(selector => { - return document.querySelector(selector).className; - }, 'body > vn-app > vn-vertical > vn-vertical > vn-client-card > vn-main-block > vn-horizontal > vn-one > vn-vertical > vn-client-fiscal-data > form > vn-card > div > vn-horizontal:nth-child(5) > vn-check:nth-child(3) > label') - .then(result => { - expect(result).not.toContain('is-disabled'); - }); - }); - - it('should check the Verified data checkbox', () => { - return nightmare - .waitToClick(selectors.clientFiscalData.verifiedDataCheckboxInput) - .waitToClick(selectors.clientFiscalData.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toEqual('Data saved!'); - }); - }); - - it('should confirm Verified data checkbox is checked', () => { - return nightmare - .waitToClick(selectors.clientBasicData.basicDataButton) - .wait(selectors.clientBasicData.nameInput) - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .wait(selectors.clientFiscalData.verifiedDataCheckboxInput) - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientFiscalData.verifiedDataCheckboxInput) - .then(value => { - expect(value).toBeTruthy(); - }); - }); - - it('should again edit the social name', () => { - return nightmare - .wait(selectors.clientFiscalData.socialNameInput) - .clearInput(selectors.clientFiscalData.socialNameInput) - .type(selectors.clientFiscalData.socialNameInput, 'administrative was here') - .click(selectors.clientFiscalData.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toEqual('Data saved!'); - }); - }); - - it('should confirm the social name have been edited once and for all', () => { - return nightmare - .waitToClick(selectors.clientBasicData.basicDataButton) - .wait(selectors.clientBasicData.nameInput) - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .wait(selectors.clientFiscalData.socialNameInput) - .getInputValue(selectors.clientFiscalData.socialNameInput) - .then(result => { - expect(result).toEqual('administrative was here'); - }); - }); - }); - - describe('as salesPerson second run', () => { - beforeAll(() => { - return nightmare - .waitToClick(selectors.globalItems.logOutButton) - .waitForLogin('salesPerson'); - }); - - it('should again click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should again search for the user Petter Parker', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Petter Parker') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the client's fiscal data`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Petter Parker') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .waitForURL('fiscal-data') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('fiscal-data'); - }); - }); - - it(`should click on the fiscal data button to start editing`, () => { - return nightmare - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .waitForURL('fiscal-data') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('fiscal-data'); - }); - }); - - it('should confirm verified data button is disabled once again for salesPerson', () => { - return nightmare - .wait(selectors.clientFiscalData.verifiedDataCheckboxInput) - .evaluate(selector => { - return document.querySelector(selector).className; - }, 'body > vn-app > vn-vertical > vn-vertical > vn-client-card > vn-main-block > vn-horizontal > vn-one > vn-vertical > vn-client-fiscal-data > form > vn-card > div > vn-horizontal:nth-child(5) > vn-check:nth-child(3) > label') - .then(result => { - expect(result).toContain('is-disabled'); - }); - }); - - it('should confirm the form have been disabled for salesPerson', () => { - return nightmare - .wait(selectors.clientFiscalData.socialNameInput) - .evaluate(selector => { - return document.querySelector(selector).className; - }, 'vn-textfield[field="$ctrl.client.socialName"] > div') - .then(result => { - expect(result).toContain('is-disabled'); - }); - }); - }); - - describe('as salesAssistant', () => { - beforeAll(() => { - return nightmare - .waitToClick(selectors.globalItems.logOutButton) - .waitForLogin('salesAssistant'); - }); - - it('should navigate to clients index', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should search again for the user Petter Parker', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Petter Parker') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the Petter Parkers fiscal data`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Petter Parker') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .waitForURL('fiscal-data') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('fiscal-data'); - }); - }); - - it(`should click on the fiscal data button`, () => { - return nightmare - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .waitForURL('fiscal-data') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('fiscal-data'); - }); - }); - - it('should confirm verified data button is enabled for salesAssistant', () => { - return nightmare - .wait(selectors.clientFiscalData.verifiedDataCheckboxInput) - .evaluate(selector => { - return document.querySelector(selector).className; - }, 'body > vn-app > vn-vertical > vn-vertical > vn-client-card > vn-main-block > vn-horizontal > vn-one > vn-vertical > vn-client-fiscal-data > form > vn-card > div > vn-horizontal:nth-child(5) > vn-check:nth-child(3) > label') - .then(result => { - expect(result).not.toContain('is-disabled'); - }); - }); - - it('should uncheck the Verified data checkbox', () => { - return nightmare - .waitToClick(selectors.clientFiscalData.verifiedDataCheckboxInput) - .waitToClick(selectors.clientFiscalData.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toEqual('Data saved!'); - }); - }); - - it('should confirm Verified data checkbox is unchecked', () => { - return nightmare - .waitToClick(selectors.clientBasicData.basicDataButton) - .wait(selectors.clientBasicData.nameInput) - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .wait(selectors.clientFiscalData.verifiedDataCheckboxInput) - .evaluate(selector => { - return document.querySelector(selector).checked; - }, selectors.clientFiscalData.verifiedDataCheckboxInput) - .then(value => { - expect(value).toBeFalsy(); - }); - }); - - it('should again edit the social name', () => { - return nightmare - .wait(selectors.clientFiscalData.socialNameInput) - .clearInput(selectors.clientFiscalData.socialNameInput) - .type(selectors.clientFiscalData.socialNameInput, 'salesAssistant was here') - .click(selectors.clientFiscalData.saveButton) - .waitForSnackbar() - .then(result => { - expect(result).toEqual('Data saved!'); - }); - }); - - it('should confirm the social name have been edited once and for all', () => { - return nightmare - .waitToClick(selectors.clientBasicData.basicDataButton) - .wait(selectors.clientBasicData.nameInput) - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .wait(selectors.clientFiscalData.socialNameInput) - .getInputValue(selectors.clientFiscalData.socialNameInput) - .then(result => { - expect(result).toEqual('salesAssistant was here'); - }); - }); - }); - - describe('as salesPerson third run', () => { - beforeAll(() => { - return nightmare - .waitToClick(selectors.globalItems.logOutButton) - .waitForLogin('salesPerson'); - }); - - it('should again click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should once again search for the user Petter Parker', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Petter Parker') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the client's fiscal data`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Petter Parker') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .waitForURL('fiscal-data') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('fiscal-data'); - }); - }); - - it(`should click on the fiscal data button to start editing`, () => { - return nightmare - .waitToClick(selectors.clientFiscalData.fiscalDataButton) - .waitForURL('fiscal-data') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('fiscal-data'); - }); - }); - - it('should confirm verified data button is enabled once again', () => { - return nightmare - .wait(selectors.clientFiscalData.verifiedDataCheckboxInput) - .evaluate(selector => { - return document.querySelector(selector).className; - }, 'body > vn-app > vn-vertical > vn-vertical > vn-client-card > vn-main-block > vn-horizontal > vn-one > vn-vertical > vn-client-fiscal-data > form > vn-card > div > vn-horizontal:nth-child(5) > vn-check:nth-child(3) > label') - .then(result => { - expect(result).toContain('is-disabled'); - }); - }); - - it('should confirm the form is enabled for salesPerson', () => { - return nightmare - .wait(selectors.clientFiscalData.socialNameInput) - .evaluate(selector => { - return document.querySelector(selector).className; - }, 'vn-textfield[field="$ctrl.client.socialName"] > div') - .then(result => { - expect(result).not.toContain('is-disabled'); - }); - }); - }); -}); diff --git a/e2e/paths/client-module/13_invoices.spec.js b/e2e/paths/client-module/13_invoices.spec.js deleted file mode 100644 index 1bc5bec99..000000000 --- a/e2e/paths/client-module/13_invoices.spec.js +++ /dev/null @@ -1,57 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('invoice path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should click on the Clients button of the top bar menu', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .wait(selectors.globalItems.applicationsMenuVisible) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); - }); - - it('should search for the user Petter Parker', () => { - return nightmare - .wait(selectors.clientsIndex.searchResult) - .type(selectors.clientsIndex.searchClientInput, 'Petter Parker') - .click(selectors.clientsIndex.searchButton) - .waitForNumberOfElements(selectors.clientsIndex.searchResult, 1) - .countSearchResults(selectors.clientsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the client invoices`, () => { - return nightmare - .waitForTextInElement(selectors.clientsIndex.searchResult, 'Petter') - .waitToClick(selectors.clientsIndex.searchResult) - .waitToClick(selectors.clientInvoices.invoicesButton) - .waitForURL('invoices') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('invoices'); - }); - }); - - it('should confirm the client has an invoice', () => { - return nightmare - .wait(selectors.clientInvoices.firstInvoiceText) - .getInnerText(selectors.clientInvoices.firstInvoiceText) - .then(value => { - expect(value).toContain('V1800001'); - expect(value).toContain('350.50'); - }); - }); -}); diff --git a/e2e/paths/item-module/01_item_summary.spec.js b/e2e/paths/item-module/01_item_summary.spec.js deleted file mode 100644 index 5100a84c5..000000000 --- a/e2e/paths/item-module/01_item_summary.spec.js +++ /dev/null @@ -1,141 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('Item summary path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should access to the items index by clicking the items button', () => { - return nightmare - .click(selectors.moduleAccessView.itemsSectionButton) - .wait(selectors.itemsIndex.createItemButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/item/list'); - }); - }); - - it('should search for the item Gem of Time', () => { - return nightmare - .wait(selectors.itemsIndex.searchResult) - .type(selectors.itemsIndex.searchItemInput, 'Gem of Time') - .click(selectors.itemsIndex.searchButton) - .waitForNumberOfElements(selectors.itemsIndex.searchResult, 1) - .countSearchResults(selectors.itemsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result summary button to open the item summary popup`, () => { - return nightmare - .waitForTextInElement(selectors.itemsIndex.searchResult, 'Gem of Time') - .isVisible(selectors.itemSummary.basicData) - .then(result => { - expect(result).toBeFalsy(); - return nightmare - .waitToClick(selectors.itemsIndex.searchResultPreviewButton) - .isVisible(selectors.itemSummary.basicData); - }) - .then(result => { - expect(result).toBeTruthy(); - }); - }); - - it(`should check the item summary preview shows fields from basic data`, () => { - return nightmare - .waitForTextInElement(selectors.itemSummary.basicData, 'Name: Gem of Time') - .getInnerText(selectors.itemSummary.basicData) - .then(result => { - expect(result).toContain('Name: Gem of Time'); - }); - }); - - it(`should check the item summary preview shows fields from tags`, () => { - return nightmare - .waitForTextInElement(selectors.itemSummary.tags, 'Color: Yellow') - .getInnerText(selectors.itemSummary.tags) - .then(result => { - expect(result).toContain('Color: Yellow'); - }); - }); - - it(`should check the item summary preview shows fields from niche`, () => { - return nightmare - .waitForTextInElement(selectors.itemSummary.niche, 'Warehouse One: A1') - .getInnerText(selectors.itemSummary.niche) - .then(result => { - expect(result).toContain('Warehouse One: A1'); - }); - }); - - it(`should check the item summary preview shows fields from botanical`, () => { - return nightmare - .waitForTextInElement(selectors.itemSummary.botanical, 'Botanical: Hedera helix') - .getInnerText(selectors.itemSummary.botanical) - .then(result => { - expect(result).toContain('Botanical: Hedera helix'); - }); - }); - - it(`should check the item summary preview shows fields from barcode`, () => { - return nightmare - .waitForTextInElement(selectors.itemSummary.barcode, '1') - .getInnerText(selectors.itemSummary.barcode) - .then(result => { - expect(result).toContain('1'); - }); - }); - - it(`should close the summary popup`, () => { - return nightmare - .waitToClick(selectors.itemsIndex.closeItemSummaryPreview) - .isVisible(selectors.itemSummary.basicData) - .then(result => { - expect(result).toBeFalsy(); - }); - }); - - it(`should navigate to the one of the items detailed section`, () => { - return nightmare - .waitToClick(selectors.itemsIndex.searchResult) - .waitForURL('summary') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('summary'); - }); - }); - - it(`should check the item summary shows fields from all its sections`, () => { - return nightmare - .waitForTextInElement(selectors.itemSummary.basicData, 'Name: Gem of Time') - .getInnerText(selectors.itemSummary.basicData) - .then(result => { - expect(result).toContain('Name: Gem of Time'); - return nightmare - .getInnerText(selectors.itemSummary.tags); - }) - .then(result => { - expect(result).toContain('Color: Yellow'); - return nightmare - .getInnerText(selectors.itemSummary.niche); - }) - .then(result => { - expect(result).toContain('Warehouse One: A1'); - return nightmare - .getInnerText(selectors.itemSummary.botanical); - }) - .then(result => { - expect(result).toContain('Botanical: Hedera helix'); - return nightmare - .getInnerText(selectors.itemSummary.barcode); - }) - .then(result => { - expect(result).toContain('1'); - }); - }); -}); diff --git a/e2e/paths/item-module/02_edit_item_basic_data.spec.js b/e2e/paths/item-module/02_edit_item_basic_data.spec.js deleted file mode 100644 index c2de03c06..000000000 --- a/e2e/paths/item-module/02_edit_item_basic_data.spec.js +++ /dev/null @@ -1,117 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('edit item basic data path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should access to the items index by clicking the items button', () => { - return nightmare - .click(selectors.moduleAccessView.itemsSectionButton) - .wait(selectors.itemsIndex.createItemButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/item/list'); - }); - }); - - it('should search for the item Gem of Mind', () => { - return nightmare - .wait(selectors.itemsIndex.searchResult) - .type(selectors.itemsIndex.searchItemInput, 'Gem of Mind') - .click(selectors.itemsIndex.searchButton) - .waitForNumberOfElements(selectors.itemsIndex.searchResult, 1) - .countSearchResults(selectors.itemsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the item basic data`, () => { - return nightmare - .waitForTextInElement(selectors.itemsIndex.searchResult, 'Gem of Mind') - .waitToClick(selectors.itemsIndex.searchResult) - .waitToClick(selectors.itemBasicData.basicDataButton) - .waitForURL('data') - .url() - .then(url => { - expect(url).toContain('data'); - }); - }); - - it(`should edit the item basic data`, () => { - return nightmare - .clearInput(selectors.itemBasicData.nameInput) - .type(selectors.itemBasicData.nameInput, 'Rose of Purity') - .waitToClick(selectors.itemBasicData.typeSelect) - .waitToClick(selectors.itemBasicData.typeSelectOptionTwo) - .waitToClick(selectors.itemBasicData.intrastatSelect) - .waitToClick(selectors.itemBasicData.intrastatSelectOptionOne) - .clearInput(selectors.itemBasicData.relevancyInput) - .type(selectors.itemBasicData.relevancyInput, '1') - .waitToClick(selectors.itemBasicData.originSelect) - .waitToClick(selectors.itemBasicData.originSelectOptionTwo) - .waitToClick(selectors.itemBasicData.expenceSelect) - .waitToClick(selectors.itemBasicData.expenceSelectOptionTwo) - .click(selectors.itemBasicData.submitBasicDataButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Data saved!'); - }); - }); - - it(`should confirm the item name was edited`, () => { - return nightmare - .click(selectors.itemNiches.firstCodeInput) - .wait(selectors.itemNiches.firstCodeInput) - .waitToClick(selectors.itemBasicData.basicDataButton) - .getInputValue(selectors.itemBasicData.nameInput) - .then(result => { - expect(result).toEqual('Rose of Purity'); - }); - }); - - it(`should confirm the item type was edited`, () => { - return nightmare - .getInputValue(selectors.itemBasicData.typeSelect) - .then(result => { - expect(result).toEqual('Crisantemo'); - }); - }); - - it(`should confirm the item intrastad was edited`, () => { - return nightmare - .getInputValue(selectors.itemBasicData.intrastatSelect) - .then(result => { - expect(result).toEqual('Coral y materiales similares'); - }); - }); - - it(`should confirm the item relevancy was edited`, () => { - return nightmare - .getInputValue(selectors.itemBasicData.relevancyInput) - .then(result => { - expect(result).toEqual('1'); - }); - }); - - it(`should confirm the item origin was edited`, () => { - return nightmare - .getInputValue(selectors.itemBasicData.originSelect) - .then(result => { - expect(result).toEqual('Spain'); - }); - }); - - it(`should confirm the item expence was edited`, () => { - return nightmare - .getInputValue(selectors.itemBasicData.expenceSelect) - .then(result => { - expect(result).toEqual('loan'); - }); - }); -}); diff --git a/e2e/paths/item-module/03_edit_item_tax.spec.js b/e2e/paths/item-module/03_edit_item_tax.spec.js deleted file mode 100644 index 07bb75414..000000000 --- a/e2e/paths/item-module/03_edit_item_tax.spec.js +++ /dev/null @@ -1,82 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('add item tax path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should access to the items index by clicking the items button', () => { - return nightmare - .click(selectors.moduleAccessView.itemsSectionButton) - .wait(selectors.itemsIndex.createItemButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/item/list'); - }); - }); - - it('should search for the item Gem of Time', () => { - return nightmare - .wait(selectors.itemsIndex.searchResult) - .type(selectors.itemsIndex.searchItemInput, 'Gem of Time') - .click(selectors.itemsIndex.searchButton) - .waitForNumberOfElements(selectors.itemsIndex.searchResult, 1) - .countSearchResults(selectors.itemsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the item tax`, () => { - return nightmare - .waitForTextInElement(selectors.itemsIndex.searchResult, 'Gem of Time') - .waitToClick(selectors.itemsIndex.searchResult) - .waitToClick(selectors.itemTax.taxButton) - .waitForURL('tax') - .url() - .then(url => { - expect(url).toContain('tax'); - }); - }); - - it(`should add the item tax to all countries`, () => { - return nightmare - .waitToClick(selectors.itemTax.firstClassSelect) - .waitToClick(selectors.itemTax.firstClassSelectOptionTwo) - .waitToClick(selectors.itemTax.secondClassSelect) - .waitToClick(selectors.itemTax.secondClassSelectOptionOne) - .waitToClick(selectors.itemTax.thirdClassSelect) - .waitToClick(selectors.itemTax.thirdClassSelectOptionTwo) - .click(selectors.itemTax.submitTaxButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Data saved!'); - }); - }); - - it(`should confirm the item tax class was edited`, () => { - return nightmare - .click(selectors.itemTags.tagsButton) - .wait(selectors.itemTags.firstTagSelect) - .waitToClick(selectors.itemTax.taxButton) - .waitForTextInInput(selectors.itemTax.firstClassSelect, 'general') - .getInputValue(selectors.itemTax.firstClassSelect) - .then(result => { - expect(result).toEqual('General VAT'); - return nightmare - .getInputValue(selectors.itemTax.secondClassSelect); - }) - .then(result => { - expect(result).toEqual('Reduced VAT'); - return nightmare - .getInputValue(selectors.itemTax.thirdClassSelect); - }) - .then(result => { - expect(result).toEqual('General VAT'); - }); - }); -}); diff --git a/e2e/paths/item-module/04_create_item_tags.spec.js b/e2e/paths/item-module/04_create_item_tags.spec.js deleted file mode 100644 index 19d9ef26a..000000000 --- a/e2e/paths/item-module/04_create_item_tags.spec.js +++ /dev/null @@ -1,206 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('create item tags path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should access to the items index by clicking the items button', () => { - return nightmare - .click(selectors.moduleAccessView.itemsSectionButton) - .wait(selectors.itemsIndex.createItemButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/item/list'); - }); - }); - - it('should search for the item Gem of Time', () => { - return nightmare - .wait(selectors.itemsIndex.searchResult) - .type(selectors.itemsIndex.searchItemInput, 'Gem of Time') - .click(selectors.itemsIndex.searchButton) - .waitForNumberOfElements(selectors.itemsIndex.searchResult, 1) - .countSearchResults(selectors.itemsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the item tags`, () => { - return nightmare - .waitForTextInElement(selectors.itemsIndex.searchResult, 'Gem of Time') - .waitToClick(selectors.itemsIndex.searchResult) - .waitToClick(selectors.itemTags.tagsButton) - .waitForURL('tags') - .url() - .then(url => { - expect(url).toContain('tags'); - }); - }); - - it(`should create a new tag, edit another and delete a former one`, () => { - return nightmare - .waitToClick(selectors.itemTags.firstTagSelect) - .waitToClick(selectors.itemTags.firstTagSelectOptionOne) - .clearInput(selectors.itemTags.firstValueInput) - .type(selectors.itemTags.firstValueInput, 'Dark Blue') - .clearInput(selectors.itemTags.firstRelevancyInput) - .type(selectors.itemTags.firstRelevancyInput, '2') - .waitToClick(selectors.itemTags.fifthRemoveTagButton) - .waitToClick(selectors.itemTags.addItemTagButton) - .waitToClick(selectors.itemTags.fifthTagSelect) - .waitToClick(selectors.itemTags.fifthTagSelectOptionFive) - .type(selectors.itemTags.fifthValueInput, 'Thanos') - .type(selectors.itemTags.fifthRelevancyInput, '1') - .clearInput(selectors.itemTags.secondRelevancyInput) - .type(selectors.itemTags.secondRelevancyInput, '5') - .click(selectors.itemTags.submitItemTagsButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Data saved!'); - }); - }); - - it(`should confirm the first select is the expected one`, () => { - return nightmare - .click(selectors.itemBasicData.basicDataButton) - .wait(selectors.itemBasicData.nameInput) - .click(selectors.itemTags.tagsButton) - .waitForTextInInput(selectors.itemTags.firstTagSelect, 'Owner') - .getInputValue(selectors.itemTags.firstTagSelect) - .then(result => { - expect(result).toEqual('Owner'); - }); - }); - - it(`should confirm the first value is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.firstValueInput, 'Thanos') - .getInputValue(selectors.itemTags.firstValueInput) - .then(result => { - expect(result).toEqual('Thanos'); - }); - }); - - it(`should confirm the first relevancy is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.firstRelevancyInput, '1') - .getInputValue(selectors.itemTags.firstRelevancyInput) - .then(result => { - expect(result).toEqual('1'); - }); - }); - - it(`should confirm the second select is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.secondTagSelect, 'Color') - .getInputValue(selectors.itemTags.secondTagSelect) - .then(result => { - expect(result).toEqual('Color'); - }); - }); - - it(`should confirm the second value is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.secondValueInput, 'Dark Blue') - .getInputValue(selectors.itemTags.secondValueInput) - .then(result => { - expect(result).toEqual('Dark Blue'); - }); - }); - - it(`should confirm the second relevancy is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.secondRelevancyInput, '2') - .getInputValue(selectors.itemTags.secondRelevancyInput) - .then(result => { - expect(result).toEqual('2'); - }); - }); - - it(`should confirm the third select is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.thirdTagSelect, 'Shape') - .getInputValue(selectors.itemTags.thirdTagSelect) - .then(result => { - expect(result).toEqual('Shape'); - }); - }); - - it(`should confirm the third value is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.thirdValueInput, 'round') - .getInputValue(selectors.itemTags.thirdValueInput) - .then(result => { - expect(result).toEqual('round'); - }); - }); - - it(`should confirm the third relevancy is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.thirdRelevancyInput, '3') - .getInputValue(selectors.itemTags.thirdRelevancyInput) - .then(result => { - expect(result).toEqual('3'); - }); - }); - - it(`should confirm the fourth select is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.fourthTagSelect, 'Power') - .getInputValue(selectors.itemTags.fourthTagSelect) - .then(result => { - expect(result).toEqual('Power'); - }); - }); - - it(`should confirm the fourth value is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.fourthValueInput, 'Manipulates time') - .getInputValue(selectors.itemTags.fourthValueInput) - .then(result => { - expect(result).toEqual('Manipulates time'); - }); - }); - - it(`should confirm the fourth relevancy is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.fourthRelevancyInput, '4') - .getInputValue(selectors.itemTags.fourthRelevancyInput) - .then(result => { - expect(result).toEqual('4'); - }); - }); - - it(`should confirm the fifth select is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.fifthTagSelect, 'Location') - .getInputValue(selectors.itemTags.fifthTagSelect) - .then(result => { - expect(result).toEqual('Location'); - }); - }); - - it(`should confirm the fifth value is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.fifthValueInput, 'Gamoras hideout') - .getInputValue(selectors.itemTags.fifthValueInput) - .then(result => { - expect(result).toEqual('Gamoras hideout'); - }); - }); - - it(`should confirm the fifth relevancy is the expected one`, () => { - return nightmare - .waitForTextInInput(selectors.itemTags.fifthRelevancyInput, '5') - .getInputValue(selectors.itemTags.fifthRelevancyInput) - .then(result => { - expect(result).toEqual('5'); - }); - }); -}); diff --git a/e2e/paths/item-module/05_create_item_niche.spec.js b/e2e/paths/item-module/05_create_item_niche.spec.js deleted file mode 100644 index 588dad678..000000000 --- a/e2e/paths/item-module/05_create_item_niche.spec.js +++ /dev/null @@ -1,106 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('create item niche path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should access to the items index by clicking the items button', () => { - return nightmare - .click(selectors.moduleAccessView.itemsSectionButton) - .wait(selectors.itemsIndex.createItemButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/item/list'); - }); - }); - - it('should search for the item Gem of Time', () => { - return nightmare - .wait(selectors.itemsIndex.searchResult) - .type(selectors.itemsIndex.searchItemInput, 'Gem of Time') - .click(selectors.itemsIndex.searchButton) - .waitForNumberOfElements(selectors.itemsIndex.searchResult, 1) - .countSearchResults(selectors.itemsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the item niches`, () => { - return nightmare - .waitForTextInElement(selectors.itemsIndex.searchResult, 'Gem of Time') - .waitToClick(selectors.itemsIndex.searchResult) - .waitToClick(selectors.itemNiches.nicheButton) - .waitForURL('niche') - .url() - .then(url => { - expect(url).toContain('niche'); - }); - }); - - it(`should click create a new niche, edit another and delete a former one`, () => { - return nightmare - .waitToClick(selectors.itemNiches.addNicheButton) - .waitToClick(selectors.itemNiches.firstWarehouseSelect) - .waitToClick(selectors.itemNiches.firstWarehouseSelectSecondOption) - .clearInput(selectors.itemNiches.firstCodeInput) - .type(selectors.itemNiches.firstCodeInput, 'A2') - .waitToClick(selectors.itemNiches.secondNicheRemoveButton) - .waitToClick(selectors.itemNiches.thirdWarehouseSelect) - .waitToClick(selectors.itemNiches.thirdWarehouseSelectFourthOption) - .type(selectors.itemNiches.thirdCodeInput, 'A4') - .click(selectors.itemNiches.submitNichesButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Data saved!'); - }); - }); - - it(`should confirm the first niche is the expected one`, () => { - return nightmare - .click(selectors.itemBasicData.basicDataButton) - .wait(selectors.itemBasicData.nameInput) - .click(selectors.itemNiches.nicheButton) - .waitForTextInInput(selectors.itemNiches.firstWarehouseSelect, 'Warehouse Two') - .getInputValue(selectors.itemNiches.firstWarehouseSelect) - .then(result => { - expect(result).toEqual('Warehouse Two'); - return nightmare - .getInputValue(selectors.itemNiches.firstCodeInput); - }) - .then(result => { - expect(result).toEqual('A2'); - }); - }); - - it(`should confirm the second niche is the expected one`, () => { - return nightmare - .getInputValue(selectors.itemNiches.secondWarehouseSelect) - .then(result => { - expect(result).toEqual('Warehouse Three'); - return nightmare - .getInputValue(selectors.itemNiches.secondCodeInput); - }) - .then(result => { - expect(result).toEqual('A3'); - }); - }); - - it(`should confirm the third niche is the expected one`, () => { - return nightmare - .getInputValue(selectors.itemNiches.thirdWarehouseSelect) - .then(result => { - expect(result).toEqual('Warehouse Four'); - return nightmare - .getInputValue(selectors.itemNiches.thirdCodeInput); - }) - .then(result => { - expect(result).toEqual('A4'); - }); - }); -}); diff --git a/e2e/paths/item-module/06_create_item_botanical.spec.js b/e2e/paths/item-module/06_create_item_botanical.spec.js deleted file mode 100644 index 18462c2a6..000000000 --- a/e2e/paths/item-module/06_create_item_botanical.spec.js +++ /dev/null @@ -1,132 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('create item botanical path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should access to the items index by clicking the items button', () => { - return nightmare - .click(selectors.moduleAccessView.itemsSectionButton) - .wait(selectors.itemsIndex.createItemButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/item/list'); - }); - }); - - it('should search for the item Gem of Time', () => { - return nightmare - .wait(selectors.itemsIndex.searchResult) - .type(selectors.itemsIndex.searchItemInput, 'Mjolnir') - .click(selectors.itemsIndex.searchButton) - .waitForNumberOfElements(selectors.itemsIndex.searchResult, 1) - .countSearchResults(selectors.itemsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the item botanical`, () => { - return nightmare - .waitForTextInElement(selectors.itemsIndex.searchResult, 'Mjolnir') - .waitToClick(selectors.itemsIndex.searchResult) - .waitToClick(selectors.itemBotanical.botanicalButton) - .waitForURL('botanical') - .url() - .then(url => { - expect(url).toContain('botanical'); - }); - }); - - it(`should create a new botanical for the item with id Mjolnir`, () => { - return nightmare - .type(selectors.itemBotanical.botanicalInput, 'Cicuta maculata') - .waitToClick(selectors.itemBotanical.genusSelect) - .waitToClick(selectors.itemBotanical.genusSelectOptionOne) - .waitToClick(selectors.itemBotanical.speciesSelect) - .waitToClick(selectors.itemBotanical.speciesSelectOptionOne) - .waitToClick(selectors.itemBotanical.submitBotanicalButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Data saved!'); - }); - }); - - it(`should confirm the botanical for item Mjolnir was created`, () => { - return nightmare - .click(selectors.itemBasicData.basicDataButton) - .wait(selectors.itemBasicData.nameInput) - .click(selectors.itemBotanical.botanicalButton) - .waitForTextInInput(selectors.itemBotanical.botanicalInput, 'Cicuta maculata') - .getInputValue(selectors.itemBotanical.botanicalInput) - .then(result => { - expect(result).toEqual('Cicuta maculata'); - }); - }); - - it(`should confirm the Genus for item Mjolnir was created`, () => { - return nightmare - .waitForTextInInput(selectors.itemBotanical.genusSelect, 'Abelia') - .getInputValue(selectors.itemBotanical.genusSelect) - .then(result => { - expect(result).toEqual('Abelia'); - }); - }); - - it(`should confirm the Species for item Mjolnir was created`, () => { - return nightmare - .getInputValue(selectors.itemBotanical.speciesSelect) - .then(result => { - expect(result).toEqual('dealbata'); - }); - }); - - it(`should edit botanical for the item Mjolnir`, () => { - return nightmare - .clearInput(selectors.itemBotanical.botanicalInput) - .type(selectors.itemBotanical.botanicalInput, 'Herp Derp') - .waitToClick(selectors.itemBotanical.genusSelect) - .waitToClick(selectors.itemBotanical.genusSelectOptionTwo) - .waitToClick(selectors.itemBotanical.speciesSelect) - .waitToClick(selectors.itemBotanical.speciesSelectOptionTwo) - .waitToClick(selectors.itemBotanical.submitBotanicalButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Data saved!'); - }); - }); - - it(`should confirm the botanical for item Mjolnir was edited`, () => { - return nightmare - .click(selectors.itemBasicData.basicDataButton) - .wait(selectors.itemBasicData.nameInput) - .click(selectors.itemBotanical.botanicalButton) - .waitForTextInInput(selectors.itemBotanical.botanicalInput, 'Herp Derp') - .getInputValue(selectors.itemBotanical.botanicalInput) - .then(result => { - expect(result).toEqual('Herp Derp'); - }); - }); - - it(`should confirm the Genus for item Mjolnir was edited`, () => { - return nightmare - .waitForTextInInput(selectors.itemBotanical.genusSelect, 'Abies') - .getInputValue(selectors.itemBotanical.genusSelect) - .then(result => { - expect(result).toEqual('Abies'); - }); - }); - - it(`should confirm the Species for item Mjolnir was edited`, () => { - return nightmare - .getInputValue(selectors.itemBotanical.speciesSelect) - .then(result => { - expect(result).toEqual('decurrens'); - }); - }); -}); diff --git a/e2e/paths/item-module/07_create_item_barcode.spec.js b/e2e/paths/item-module/07_create_item_barcode.spec.js deleted file mode 100644 index f2900988a..000000000 --- a/e2e/paths/item-module/07_create_item_barcode.spec.js +++ /dev/null @@ -1,70 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('create item barcodes path', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - it('should access to the items index by clicking the items button', () => { - return nightmare - .click(selectors.moduleAccessView.itemsSectionButton) - .wait(selectors.itemsIndex.createItemButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/item/list'); - }); - }); - - it('should search for the item Gem of Time', () => { - return nightmare - .wait(selectors.itemsIndex.searchResult) - .type(selectors.itemsIndex.searchItemInput, 'Gem of Time') - .click(selectors.itemsIndex.searchButton) - .waitForNumberOfElements(selectors.itemsIndex.searchResult, 1) - .countSearchResults(selectors.itemsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should click on the search result to access to the item barcodes`, () => { - return nightmare - .waitForTextInElement(selectors.itemsIndex.searchResult, 'Gem of Time') - .waitToClick(selectors.itemsIndex.searchResult) - .waitToClick(selectors.itemBarcodes.barcodeButton) - .waitForURL('barcode') - .url() - .then(url => { - expect(url).toContain('barcode'); - }); - }); - - it(`should click create a new code and delete a former one`, () => { - return nightmare - .waitToClick(selectors.itemBarcodes.firstCodeRemoveButton) - .waitToClick(selectors.itemBarcodes.addBarcodeButton) - .wait(selectors.itemBarcodes.thirdCodeInput) - .type(selectors.itemBarcodes.thirdCodeInput, '5') - .waitToClick(selectors.itemBarcodes.submitBarcodesButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Data saved!'); - }); - }); - - it(`should confirm the barcode 5 is created and it is now the third barcode as the first was deleted`, () => { - return nightmare - .click(selectors.itemBasicData.basicDataButton) - .wait(selectors.itemBasicData.nameInput) - .click(selectors.itemBarcodes.barcodeButton) - .waitForTextInInput(selectors.itemBarcodes.thirdCodeInput, '5') - .getInputValue(selectors.itemBarcodes.thirdCodeInput) - .then(result => { - expect(result).toEqual('5'); - }); - }); -}); diff --git a/e2e/paths/item-module/08_item_create_and_clone.spec.js b/e2e/paths/item-module/08_item_create_and_clone.spec.js deleted file mode 100644 index a4a54263a..000000000 --- a/e2e/paths/item-module/08_item_create_and_clone.spec.js +++ /dev/null @@ -1,142 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import createNightmare from '../../helpers/helpers'; - -describe('Item', () => { - const nightmare = createNightmare(); - - beforeAll(() => { - return nightmare - .waitForLogin('developer'); - }); - - describe('create path', () => { - it('should access to the items index by clicking the items button', () => { - return nightmare - .click(selectors.moduleAccessView.itemsSectionButton) - .wait(selectors.itemsIndex.createItemButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/item/list'); - }); - }); - - it(`should search for the item Infinity Gauntlet to confirm it isn't created yet`, () => { - return nightmare - .wait(selectors.itemsIndex.searchResult) - .type(selectors.itemsIndex.searchItemInput, 'Infinity Gauntlet') - .click(selectors.itemsIndex.searchButton) - .waitForNumberOfElements(selectors.itemsIndex.searchResult, 0) - .countSearchResults(selectors.itemsIndex.searchResult) - .then(result => { - expect(result).toEqual(0); - }); - }); - - it('should access to the create item view by clicking the create floating button', () => { - return nightmare - .click(selectors.itemsIndex.createItemButton) - .wait(selectors.itemCreateView.createButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/item/create'); - }); - }); - - it('should create the Infinity Gauntlet item', () => { - return nightmare - .type(selectors.itemCreateView.name, 'Infinity Gauntlet') - .waitToClick(selectors.itemCreateView.typeSelect) - .waitToClick(selectors.itemCreateView.typeSelectOptionOne) - .waitToClick(selectors.itemCreateView.intrastatSelect) - .waitToClick(selectors.itemCreateView.intrastatSelectOptionOne) - .waitToClick(selectors.itemCreateView.originSelect) - .waitToClick(selectors.itemCreateView.originSelectOptionOne) - .waitToClick(selectors.itemCreateView.expenceSelect) - .waitToClick(selectors.itemCreateView.expenceSelectOptionOne) - .click(selectors.itemCreateView.createButton) - .waitForSnackbar() - .then(result => { - expect(result).toContain('Data saved!'); - }); - }); - - it('should confirm Infinity Gauntlet item was created', () => { - return nightmare - .wait(selectors.itemBasicData.nameInput) - .getInputValue(selectors.itemBasicData.nameInput) - .then(result => { - expect(result).toBe('Infinity Gauntlet'); - return nightmare - .getInputValue(selectors.itemBasicData.typeSelect); - }) - .then(result => { - expect(result).toBe('Crisantemo'); - return nightmare - .getInputValue(selectors.itemBasicData.intrastatSelect); - }) - .then(result => { - expect(result).toBe('Plantas vivas: Esqueje/injerto, Vid'); - return nightmare - .getInputValue(selectors.itemBasicData.originSelect); - }) - .then(result => { - expect(result).toBe('Spain'); - return nightmare - .getInputValue(selectors.itemBasicData.expenceSelect); - }) - .then(result => { - expect(result).toBe('loan'); - }); - }); - }); - - describe('clone path', () => { - it('should return to the items index by clicking the return to items button', () => { - return nightmare - .click(selectors.itemBasicData.goToItemIndexButton) - .wait(selectors.itemsIndex.createItemButton) - .waitForURL('#!/item/list') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('#!/item/list'); - }); - }); - - it(`should search for the item Infinity Gauntlet`, () => { - return nightmare - .wait(selectors.itemsIndex.searchResult) - .type(selectors.itemsIndex.searchItemInput, 'Infinity Gauntlet') - .click(selectors.itemsIndex.searchButton) - .waitForNumberOfElements(selectors.itemsIndex.searchResult, 1) - .countSearchResults(selectors.itemsIndex.searchResult) - .then(result => { - expect(result).toEqual(1); - }); - }); - - it(`should clone the Infinity Gauntlet`, () => { - return nightmare - .waitForTextInElement(selectors.itemsIndex.searchResult, 'Infinity Gauntlet') - .click(selectors.itemsIndex.searchResultCloneButton) - .waitToClick(selectors.itemsIndex.acceptClonationAlertButton) - .waitForURL('tags') - .parsedUrl() - .then(url => { - expect(url.hash).toContain('tags'); - }); - }); - - it('should search for the item Infinity Gauntlet and find two', () => { - return nightmare - .waitToClick(selectors.itemTags.goToItemIndexButton) - .wait(selectors.itemsIndex.searchResult) - .type(selectors.itemsIndex.searchItemInput, 'Infinity Gauntlet') - .click(selectors.itemsIndex.searchButton) - .waitForNumberOfElements(selectors.itemsIndex.searchResult, 2) - .countSearchResults(selectors.itemsIndex.searchResult) - .then(result => { - expect(result).toEqual(2); - }); - }); - }); -}); diff --git a/e2e/smokes-tests.js b/e2e/smokes-tests.js new file mode 100644 index 000000000..7b4e16edf --- /dev/null +++ b/e2e/smokes-tests.js @@ -0,0 +1,35 @@ +require('babel-core/register')({presets: ['es2015']}); + +process.on('warning', warning => { + console.log(warning.name); + console.log(warning.message); + console.log(warning.stack); +}); + +let verbose = false; + +if (process.argv[2] === '--v') + verbose = true; + +let Jasmine = require('jasmine'); +let jasmine = new Jasmine(); +let SpecReporter = require('jasmine-spec-reporter').SpecReporter; + +jasmine.loadConfig({ + spec_files: [ + `${__dirname}/smokes/**/*[sS]pec.js`, + `${__dirname}/helpers/extensions.js` + ], + helpers: [] +}); + +jasmine.addReporter(new SpecReporter({ + spec: { + // displayStacktrace: 'summary', + displaySuccessful: verbose, + displayFailedSpec: true, + displaySpecDuration: true + } +})); + +jasmine.execute(); diff --git a/e2e/smokes/01_client_path.spec.js b/e2e/smokes/01_client_path.spec.js index f441d4f7b..2c70ae959 100644 --- a/e2e/smokes/01_client_path.spec.js +++ b/e2e/smokes/01_client_path.spec.js @@ -1,42 +1,30 @@ import selectors from '../helpers/selectors'; -import createNightmare from '../helpers/helpers'; +import createNightmare from '../helpers/nightmare'; describe('create client path', () => { let nightmare = createNightmare(); beforeAll(() => { return nightmare - .waitForLogin('developer'); + .loginAndModule('employee', 'client'); }); - it('should access to the clients index by clicking the clients button', () => { - return nightmare - .click(selectors.moduleAccessView.clientsSectionButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); + it('should access to the create client view by clicking the create-client floating button', async() => { + let url = await nightmare + .waitToClick(selectors.clientsIndex.createClientButton) + .wait(selectors.createClientView.createButton) + .parsedUrl(); + + expect(url.hash).toEqual('#!/client/create'); }); - it('should access to the create client view by clicking the create-client floating button', () => { - return nightmare - .click(selectors.clientsIndex.createClientButton) - .wait(selectors.createClientView.createButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/create'); - }); - }); + it('should cancel the client creation to go back to clients index', async() => { + let url = await nightmare + .waitToClick(selectors.globalItems.applicationsMenuButton) + .waitToClick(selectors.globalItems.clientsButton) + .wait(selectors.clientsIndex.createClientButton) + .parsedUrl(); - it('should cancel the client creation to go back to clients index', () => { - return nightmare - .waitToClick(selectors.globalItems.applicationsMenuButton) - .waitToClick(selectors.globalItems.clientsButton) - .wait(selectors.clientsIndex.createClientButton) - .parsedUrl() - .then(url => { - expect(url.hash).toEqual('#!/clients'); - }); + expect(url.hash).toEqual('#!/client/index'); }); }); diff --git a/e2e_tests.js b/e2e_tests.js deleted file mode 100644 index dd1d7a079..000000000 --- a/e2e_tests.js +++ /dev/null @@ -1,38 +0,0 @@ -require('babel-core/register')({presets: ['es2015']}); - -process.on('warning', warning => { - console.log(warning.name); - console.log(warning.message); - console.log(warning.stack); -}); - -var verbose = false; - -if (process.argv[2] === '--v') { - verbose = true; -} - -var Jasmine = require('jasmine'); -var jasmine = new Jasmine(); -var SpecReporter = require('jasmine-spec-reporter').SpecReporter; - -jasmine.loadConfig({ - spec_files: [ - './e2e/**/*[sS]pec.js', - './e2e/helpers/extensions.js' - ], - helpers: [ - '/services/utils/jasmineHelpers.js' - ] -}); - -jasmine.addReporter(new SpecReporter({ - spec: { - // displayStacktrace: 'summary', - displaySuccessful: verbose, - displayFailedSpec: true, - displaySpecDuration: true - } -})); - -jasmine.execute(); diff --git a/fileMock.js b/fileMock.js new file mode 100644 index 000000000..9dc5fc1e4 --- /dev/null +++ b/fileMock.js @@ -0,0 +1 @@ +module.exports = ''; diff --git a/front/Dockerfile b/front/Dockerfile new file mode 100644 index 000000000..098ee161e --- /dev/null +++ b/front/Dockerfile @@ -0,0 +1,18 @@ +FROM debian:stretch-slim +EXPOSE 80 +ENV TZ Europe/Madrid + +ARG DEBIAN_FRONTEND=noninteractive +RUN apt-get update \ + && apt-get install -y --no-install-recommends nginx \ + && rm -rf /var/lib/apt/lists/* \ + && ln -sf /dev/stdout /var/log/nginx/access.log \ + && ln -sf /dev/stderr /var/log/nginx/error.log + +WORKDIR /etc/nginx +COPY front/nginx.conf sites-available/salix +RUN rm sites-enabled/default && ln -s ../sites-available/salix sites-enabled/salix + +COPY dist /salix/dist + +CMD ["nginx", "-g", "daemon off;"] diff --git a/front/core/components/array-model/array-model.js b/front/core/components/array-model/array-model.js new file mode 100644 index 000000000..5b0b94cdc --- /dev/null +++ b/front/core/components/array-model/array-model.js @@ -0,0 +1,228 @@ +import ngModule from '../../module'; +import ModelProxy from '../model-proxy/model-proxy'; + +/** + * Model that uses an array as datasource. + */ +export default class ArrayModel extends ModelProxy { + constructor($q, $filter, $element, $scope) { + super($element, $scope); + this.$q = $q; + this.$filter = $filter; + this.autoLoad = true; + this.limit = 0; + this.userFilter = []; + + this.clear(); + } + + $onInit() { + this.autoRefresh(); + } + + get isLoading() { + return false; + } + + autoRefresh() { + if (this.autoLoad) + return this.refresh(); + return this.$q.resolve(); + } + + refresh() { + this.data = this.proccessData(0); + return this.$q.resolve(); + } + + proccessData(skip) { + if (!this.proxiedData) return null; + let data = this.proxiedData.slice(); + + let filter = { + order: this.order, + limit: this.limit + }; + + if (this.where) + filter.where = [this.where]; + + filter = this.mergeFilters(this.userFilter, filter); + + let where = filter.where; + + if (where) { + if (!Array.isArray(where)) + where = [where]; + + for (let subWhere of where) + data = this.$filter('filter')(data, subWhere); + } + + let order = filter.order; + + if (typeof order === 'string') + order = order.split(/\s*,\s*/); + + if (Array.isArray(order)) { + let orderComp = []; + + for (let field of order) { + let split = field.split(/\s+/); + orderComp.push({ + field: split[0], + way: split[1] === 'DESC' ? -1 : 1 + }); + } + + data = data.sort((a, b) => this.sortFunc(a, b, orderComp)); + } else if (typeof order === 'function') + data = data.sort(order); + + this.skip = skip; + + if (filter.limit) { + let end = skip + filter.limit; + this.moreRows = end < data.length; + data = data.slice(this.skip, end); + } else + this.moreRows = false; + + this.currentFilter = filter; + return data; + } + + applyFilter(user, params) { + this.userFilter = user; + this.userParams = params; + return this.refresh(); + } + + addFilter(user, params) { + this.userFilter = this.mergeFilters(user, this.userFilter); + this.userParams = Object.assign({}, this.userParams, params); + return this.refresh(); + } + + removeFilter() { + return applyFilter(null, null); + } + + loadMore() { + if (!this.moreRows) + return this.$q.resolve(); + + let data = this.proccessData(this.skip + this.currentFilter.limit); + this.data = this.data.concat(data); + return this.$q.resolve(); + } + + clear() { + this.data = null; + this.userFilter = null; + this.moreRows = false; + this.skip = 0; + } + + /** + * Saves current changes on the server. + * + * @return {Promise} The save request promise + */ + save() { + if (this.getChanges()) + this.orgData = this.data; + + super.save(); + + return this.$q.resolve(); + } + + sortFunc(a, b, order) { + for (let i of order) { + let compRes = this.compareFunc(a[i.field], b[i.field]) * i.way; + if (compRes !== 0) + return compRes; + } + + return 0; + } + + compareFunc(a, b) { + if (a === b) + return 0; + + let aType = typeof a; + + if (aType === typeof b) { + switch (aType) { + case 'string': + return a.localeCompare(b); + case 'number': + return a - b; + case 'boolean': + return a ? 1 : -1; + case 'object': + if (a instanceof Date && b instanceof Date) + return a.getTime() - b.getTime(); + } + } + + if (a === undefined) + return -1; + if (b === undefined) + return 1; + if (a === null) + return -1; + if (b === null) + return 1; + + return a > b ? 1 : -1; + } + + mergeFilters(src, dst) { + let mergedWhere = []; + let wheres = [dst.where, src.where]; + + for (let where of wheres) { + if (Array.isArray(where)) + mergedWhere = mergedWhere.concat(where); + else if (where) + mergedWhere.push(where); + } + + switch (mergedWhere.length) { + case 0: + mergedWhere = undefined; + break; + case 1: + mergedWhere = mergedWhere[0]; + break; + } + + return { + where: mergedWhere, + order: src.order || dst.order, + limit: src.limit || dst.limit + }; + } + + undoChanges() { + super.undoChanges(); + this.refresh(); + } +} +ArrayModel.$inject = ['$q', '$filter', '$element', '$scope']; + +ngModule.component('vnArrayModel', { + controller: ArrayModel, + bindings: { + orgData: ' +
    +
    +
    +
    +
    + + +
    +
    + +
    +
    + + + + +
    +
    +
    +
    + + +
    +
    +
    + +
    + + \ No newline at end of file diff --git a/front/core/components/autocomplete/index.js b/front/core/components/autocomplete/index.js new file mode 100755 index 000000000..38c85db57 --- /dev/null +++ b/front/core/components/autocomplete/index.js @@ -0,0 +1,298 @@ +import ngModule from '../../module'; +import Field from '../field'; +import assignProps from '../../lib/assign-props'; +import {mergeWhere} from 'vn-loopback/util/filter'; +import './style.scss'; + +/** + * Input with option selector. + * + * @property {String} showFiled The data field name that should be shown + * @property {String} valueField The data field name that should be used as value + * @property {Array} data Static data for the autocomplete + * @property {Object} intialData An initial data to avoid the server request used to get the selection + * @property {Boolean} multiple Wether to allow multiple selection + * @property {Object} selection Current object selected + * + * @event change Thrown when value is changed + */ +export default class Autocomplete extends Field { + constructor($element, $, $compile, $transclude) { + super($element, $, $compile); + this.$transclude = $transclude; + + this._selection = null; + this.input = this.element.querySelector('input'); + } + + $postLink() { + super.$postLink(); + this.assignDropdownProps(); + this.showField = this.$.dropDown.showField; + this.valueField = this.$.dropDown.valueField; + this.refreshSelection(); + } + + /** + * @type {any} The autocomplete value. + */ + get field() { + return super.field; + } + + set field(value) { + super.field = value; + this.refreshSelection(); + } + + get model() { + return this._model; + } + + set model(value) { + this.dropDownAssign({model: value}); + } + + get data() { + return this._data; + } + + set data(value) { + this.dropDownAssign({data: value}); + } + + get url() { + return this._url; + } + + set url(value) { + this.dropDownAssign({url: value}); + } + + dropDownAssign(props) { + for (let prop in props) + this[`_${prop}`] = props[prop]; + if (this.$.dropDown) + Object.assign(this.$.dropDown, props); + } + + /** + * @type {Object} The selected data object, you can use this property + * to prevent requests to display the initial value. + */ + get selection() { + return this._selection; + } + + set selection(value) { + this._selection = value; + this.refreshDisplayed(); + } + + get initialData() { + return this._initialData; + } + + set initialData(value) { + this._initialData = value; + this.refreshSelection(); + } + + selectionIsValid(selection) { + return selection + && selection[this.valueField] == this._field + && selection[this.showField] != null; + } + + refreshSelection() { + if (this._field == null) { + this.selection = null; + return; + } + + if (!(this.valueField && this.showField) + || this.selectionIsValid(this._selection)) + return; + + const selection = this.fetchSelection(); + this.selection = selection; + } + + fetchSelection() { + if (this.selectionIsValid(this.initialData)) + return this.initialData; + + if (!this.$.dropDown) + return null; + + let data; + if (this.$.dropDown.model) + data = this.$.dropDown.model.orgData; + + if (data) { + let selection = data.find(i => this.selectionIsValid(i)); + if (selection) return selection; + } + + if (this.url) { + let where = {}; + + if (this.multiple) + where[this.valueField] = {inq: this.field}; + else + where[this.valueField] = this._field; + + where = mergeWhere(where, this.fetchFunction); + + let filter = { + fields: this.$.dropDown.getFields(), + where: where + }; + + let json = encodeURIComponent(JSON.stringify(filter)); + this.$http.get(`${this.url}?filter=${json}`).then( + json => this.onSelectionRequest(json.data), + () => this.onSelectionRequest() + ); + } + + return null; + } + + onSelectionRequest(data) { + if (data && data.length > 0) { + if (this.multiple) + this.selection = data; + else + this.selection = data[0]; + } else + this.selection = null; + } + + refreshDisplayed() { + let display = ''; + let hasTemplate = this.$transclude && this.$transclude.isSlotFilled('tplItem'); + + if (this._selection && this.showField) { + if (this.multiple && Array.isArray(this._selection)) { + for (let item of this._selection) { + if (display.length > 0) display += ', '; + display += item[this.showField]; + } + } else { + display = this._selection[this.showField]; + if (hasTemplate) { + let template = this.$transclude(() => {}, null, 'tplItem').text(); + display = this.$interpolate(template)(this._selection); + } + } + } + + this.input.value = display; + + if (this.translateFields) { + if (this.translateFields.indexOf(this.showField) > -1) + this.input.value = this.$translate.instant(display); + } + } + + onDropDownSelect(item) { + const value = item[this.valueField]; + this.selection = item; + this.change(value); + } + + onDropDownClose() { + setTimeout(() => this.focus()); + } + + onContainerKeyDown(event) { + if (event.defaultPrevented) return; + switch (event.key) { + case 'ArrowUp': + case 'ArrowDown': + this.showDropDown(); + break; + default: + if (event.key.length == 1) + this.showDropDown(event.key); + else + return; + } + } + + onContainerClick(event) { + if (event.defaultPrevented) return; + this.showDropDown(); + } + + onDataReady() { + this.refreshSelection(); + } + + assignDropdownProps() { + if (!this.$.dropDown) return; + this.$.dropDown.copySlot('tplItem', this.$transclude); + + assignProps(this, this.$.dropDown, [ + 'valueField', + 'showField', + 'showFilter', + 'multiple', + 'translateFields', + 'model', + 'data', + 'url', + 'fields', + 'include', + 'where', + 'order', + 'limit', + 'searchFunction' + ]); + } + + showDropDown(search) { + if (!this.editable) return; + this.assignDropdownProps(); + this.$.dropDown.show(this.container, search); + } + + get fetchFunction() { + return this._fetchFunction; + } + + set fetchFunction(value) { + this._fetchFunction = value; + + if (value) + this.refreshSelection(); + } +} +Autocomplete.$inject = ['$element', '$scope', '$compile', '$transclude']; + +ngModule.vnComponent('vnAutocomplete', { + template: require('./index.html'), + controller: Autocomplete, + bindings: { + showField: '@?', + valueField: '@?', + initialData: ' { + let $element; + let controller; + let data = {id: 1, name: 'Bruce Wayne'}; + + beforeEach(ngModule('vnCore')); + + beforeEach(inject(($compile, $rootScope) => { + $element = $compile(``)($rootScope); + controller = $element.controller('vnAutocomplete'); + })); + + afterEach(() => { + $element.remove(); + }); + + describe('url() setter', () => { + it(`should set the url property`, () => { + controller.url = '/TestModels'; + + expect(controller.url).toEqual('/TestModels'); + }); + }); + + describe('field() setter/getter', () => { + it(`should set the field property`, () => { + controller.field = 'id'; + + expect(controller.field).toEqual('id'); + }); + }); + + describe('selection property', () => { + beforeEach(() => { + controller.field = data.id; + }); + + it(`should set selection finding an existing item in the initialData property`, () => { + controller.initialData = data; + + expect(controller.selection).toEqual(data); + }); + + it(`should set selection finding an existing item in the data property`, () => { + controller.data = [data]; + + expect(controller.selection).toEqual(data); + }); + + it(`should set selection to null when can't find an existing item in the data property`, () => { + expect(controller.selection).toEqual(null); + }); + }); +}); diff --git a/front/core/components/autocomplete/style.scss b/front/core/components/autocomplete/style.scss new file mode 100755 index 000000000..19e8362d5 --- /dev/null +++ b/front/core/components/autocomplete/style.scss @@ -0,0 +1,26 @@ +@import "effects"; + +.vn-autocomplete { + overflow: hidden; + + & > .container { + cursor: pointer; + + & > .infix > .control { + overflow: hidden; + + & > input { + cursor: pointer; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + text-align: left; + padding-left: 0; + padding-right: 0; + } + } + } + &.readonly > .container > .icons.post { + display: none; + } +} diff --git a/front/core/components/button-menu/index.html b/front/core/components/button-menu/index.html new file mode 100644 index 000000000..01bcdce10 --- /dev/null +++ b/front/core/components/button-menu/index.html @@ -0,0 +1,19 @@ + + + \ No newline at end of file diff --git a/front/core/components/button-menu/index.js b/front/core/components/button-menu/index.js new file mode 100644 index 000000000..c19962b08 --- /dev/null +++ b/front/core/components/button-menu/index.js @@ -0,0 +1,104 @@ +import ngModule from '../../module'; +import Button from '../button'; +import assignProps from '../../lib/assign-props'; +import './style.scss'; + +export default class ButtonMenu extends Button { + constructor($element, $scope, $transclude) { + super($element, $scope); + this.$transclude = $transclude; + $element.on('click', e => this.onButtonClick(e)); + } + + get model() { + return this._model; + } + + set model(value) { + this.dropDownAssign({model: value}); + } + + get data() { + return this._data; + } + + set data(value) { + this.dropDownAssign({data: value}); + } + + get url() { + return this._url; + } + + set url(value) { + this.dropDownAssign({url: value}); + } + + dropDownAssign(props) { + for (let prop in props) + this[`_${prop}`] = props[prop]; + if (this.$.dropDown) + Object.assign(this.$.dropDown, props); + } + + onButtonClick(event) { + if (event.defaultPrevented) return; + this.emit('open'); + this.showDropDown(); + } + + onDropDownSelect(item) { + const value = item[this.valueField]; + this.field = value; + this.emit('change', {value}); + } + + showDropDown() { + this.$.dropDown.copySlot('tplItem', this.$transclude); + + assignProps(this, this.$.dropDown, [ + 'valueField', + 'showField', + 'showFilter', + 'multiple', + 'translateFields', + 'model', + 'data', + 'url', + 'fields', + 'include', + 'where', + 'order', + 'limit', + 'searchFunction' + ]); + this.$.dropDown.show(this.element); + } +} +ButtonMenu.$inject = ['$element', '$scope', '$transclude']; + +ngModule.vnComponent('vnButtonMenu', { + template: require('./index.html'), + controller: ButtonMenu, + bindings: { + showField: '@?', + selection: ' { + let controller; + let $element; + + beforeEach(ngModule('vnCore')); + + beforeEach(inject(($compile, $rootScope) => { + $element = $compile(``)($rootScope); + controller = $element.controller('vnIconMenu'); + controller.valueField = 'name'; + })); + + afterEach(() => { + $element.remove(); + }); + + describe('onButtonClick(event)', () => { + it(`should emit the open event`, () => { + spyOn(controller, 'emit'); + + let event = new MouseEvent('click', { + view: controller.element.window, + bubbles: true, + cancelable: true + }); + controller.onButtonClick(event); + + expect(controller.emit).toHaveBeenCalledWith('open'); + }); + }); + + describe('onDropDownSelect(value)', () => { + it(`should set field to the given value and emit the change event`, () => { + spyOn(controller, 'emit'); + controller.onDropDownSelect({name: 'Item name'}); + + expect(controller.field).toBe('Item name'); + expect(controller.emit).toHaveBeenCalledWith('change', {value: 'Item name'}); + }); + }); +}); diff --git a/front/core/components/button-menu/style.scss b/front/core/components/button-menu/style.scss new file mode 100644 index 000000000..cbb6129bd --- /dev/null +++ b/front/core/components/button-menu/style.scss @@ -0,0 +1,3 @@ +.vn-button-menu { + position: relative; +} \ No newline at end of file diff --git a/front/core/components/button/index.html b/front/core/components/button/index.html new file mode 100644 index 000000000..e8c3f6bc5 --- /dev/null +++ b/front/core/components/button/index.html @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/front/core/components/button/index.js b/front/core/components/button/index.js new file mode 100644 index 000000000..17710967a --- /dev/null +++ b/front/core/components/button/index.js @@ -0,0 +1,43 @@ +import ngModule from '../../module'; +import FormInput from '../form-input'; +import './style.scss'; + +export default class Button extends FormInput { + constructor($element, $scope) { + super($element, $scope); + this.design = 'colored'; + this.initTabIndex(); + this.element.addEventListener('keyup', e => this.onKeyup(e)); + this.element.addEventListener('click', e => this.onClick(e)); + } + + $onInit() { + this.element.classList.add(this.design); + if (!this.type) this.type = 'button'; + } + + onKeyup(event) { + if (event.defaultPrevented) return; + switch (event.key) { + case ' ': + case 'Enter': + return this.element.click(); + } + } + + onClick(event) { + if (this.disabled) + event.stopImmediatePropagation(); + } +} +Button.$inject = ['$element', '$scope']; + +ngModule.vnComponent('vnButton', { + controller: Button, + template: require('./index.html'), + bindings: { + icon: '@?', + type: '@?' + } +}); + diff --git a/front/core/components/button/style.scss b/front/core/components/button/style.scss new file mode 100644 index 000000000..032c88cbb --- /dev/null +++ b/front/core/components/button/style.scss @@ -0,0 +1,83 @@ +@import "variables"; + +.vn-button { + display: inline-flex; + align-items: center; + justify-content: center; + height: 36px; + border: none; + border-radius: .1em; + font-family: vn-font-bold; + text-transform: uppercase; + font-size: 14px; + cursor: pointer; + box-sizing: border-box; + outline: none; + + & > button { + width: 100%; + padding: 0 12px; + box-sizing: border-box; + background-color: transparent; + border: none; + height: inherit; + color: inherit; + font: inherit; + display: block; + text-transform: inherit; + cursor: inherit; + outline: none; + display: flex; + align-items: center; + justify-content: center; + + & > vn-icon { + vertical-align: middle; + color: inherit; + font-size: 1.7em; + } + } + &.colored { + color: white; + background-color: $color-button; + box-shadow: 0 .15em .15em 0 rgba(0, 0, 0, .3); + transition: background 200ms ease-in-out; + + &:not(.disabled) { + &:hover, + &:focus { + background-color: lighten($color-button, 10%); + } + } + } + &.flat { + color: $color-button; + background-color: transparent; + box-shadow: none; + transition: background 200ms ease-in-out; + + &:not(.disabled) { + &:hover, + &:focus { + background-color: $color-hover-cd; + } + } + } + &:hover, + &:focus { + outline: none; + } + &.round { + border-radius: 50%; + height: 3.8em; + width: 3.8em; + + & > button > span { + display: none; + } + } + &.disabled { + opacity: .7; + cursor: initial; + } +} diff --git a/front/core/components/calendar/index.html b/front/core/components/calendar/index.html new file mode 100644 index 000000000..0efff2492 --- /dev/null +++ b/front/core/components/calendar/index.html @@ -0,0 +1,46 @@ +
    +
    + + +
    + {{$ctrl.defaultDate | date: 'MMMM'}} + {{$ctrl.defaultDate | date: 'yyyy'}} +
    + + +
    +
    +
    + {{::day.localeChar}} +
    +
    +
    +
    +
    + {{::day | date: 'd'}} +
    +
    +
    +
    \ No newline at end of file diff --git a/front/core/components/calendar/index.js b/front/core/components/calendar/index.js new file mode 100644 index 000000000..4afec0a9a --- /dev/null +++ b/front/core/components/calendar/index.js @@ -0,0 +1,193 @@ +import ngModule from '../../module'; +import FormInput from '../form-input'; +import './style.scss'; + +/** + * Flat calendar. + * + * @property {Array} defaultDate Array of events + * @property {Function} hasEvents Determines if an events exists for a day + * @property {Function} getClass Class to apply to specific day + * @event selection Emitted when day or weekday is selected + * @event move Emitted when month changes + */ +export default class Calendar extends FormInput { + constructor($element, $scope, vnWeekDays) { + super($element, $scope); + this.weekDays = vnWeekDays.locales; + this.defaultDate = new Date(); + this.displayControls = true; + } + + /** + * The initial date + * + * @return {Date} - Default date + */ + get defaultDate() { + return this._defaultDate; + } + + set defaultDate(value) { + if (value) { + value = new Date(value); + value.setHours(0, 0, 0, 0); + value.setDate(1); + } + + this._defaultDate = value; + this.month = value.getMonth(); + this.repaint(); + } + + /** + * Returns first day of month from a given date + * + * @param {Date} date - Origin date + * @return {Integer} + */ + firstDay(date) { + return new Date( + date.getFullYear(), + date.getMonth(), + 1 + ); + } + + /** + * Repaints the calendar. + */ + repaint() { + const firstWeekday = this.firstDay(this.defaultDate).getDay() - 1; + let weekdayOffset = firstWeekday >= 0 ? firstWeekday : 6; + + let dayIndex = new Date(this.defaultDate.getTime()); + dayIndex.setDate(1 - weekdayOffset); + + this.days = []; + + for (let i = 1; i <= 42; i++) { + this.days.push(new Date(dayIndex.getTime())); + dayIndex.setDate(dayIndex.getDate() + 1); + } + } + + /** + * Gets CSS classes to apply to the specified day. + * + * @param {Date} day The day + * @return {Object} The CSS classes to apply + */ + getDayClasses(day) { + let wday = day.getDay(); + let month = day.getMonth(); + + let classes = { + weekend: wday === 6 || wday === 0, + previous: month < this.month, + current: month == this.month, + next: month > this.month, + event: this.hasEvents({$day: day}) + }; + + let userClass = this.getClass({$day: day}); + if (userClass) classes[userClass] = true; + + return classes; + } + + /** + * Moves to next month(s) + */ + moveNext() { + this.move(1); + } + + /** + * Moves to previous month(s) + */ + movePrevious() { + this.move(-1); + } + + /** + * Moves @direction months backwards/forwards. + * + * @param {Number} direction Negative to move backwards, positive forwards + */ + move(direction) { + let date = new Date(this.defaultDate.getTime()); + date.setMonth(date.getMonth() + direction); + this.defaultDate = date; + + this.repaint(); + this.emit('move', {$date: date}); + } + + /* + * Day selection event + */ + select(day) { + if (!this.editable) return; + this.change(day); + this.emit('selection', { + $days: [day], + $type: 'day' + }); + this.repaint(); + } + + /* + * WeekDay selection event + */ + selectWeekDay(weekday) { + if (!this.editable) return; + let days = []; + for (let day of this.days) { + if (day.getDay() === weekday && day.getMonth() == this.month) + days.push(day); + } + this.field = days[0]; + this.emit('selection', { + $days: days, + $type: 'weekday', + $weekday: weekday + }); + this.repaint(); + } + + hasEvents() { + return false; + } + + getClass() { + return ''; + } + + repeatLast() { + if (!this.formatDay) return; + + let days = this.element.querySelectorAll('.days > .day'); + for (let i = 0; i < days.length; i++) { + this.formatDay({ + $day: this.days[i], + $element: days[i] + }); + } + } +} +Calendar.$inject = ['$element', '$scope', 'vnWeekDays']; + +ngModule.vnComponent('vnCalendar', { + template: require('./index.html'), + controller: Calendar, + bindings: { + defaultDate: '=?', + hasEvents: '&?', + getClass: '&?', + formatDay: '&?', + displayControls: ' { + let controller; + let $element; + + let date = new Date(); + date.setHours(0, 0, 0, 0); + date.setDate(1); + + beforeEach(ngModule('vnCore')); + + beforeEach(inject(($compile, $rootScope) => { + $element = $compile(` { + $element.remove(); + }); + + describe('moveNext()', () => { + it(`should shift to the next month, then emit a 'move' event`, () => { + spyOn(controller, 'emit'); + let nextMonth = new Date(date.getTime()); + nextMonth.setMonth(nextMonth.getMonth() + 1); + + controller.moveNext(); + + expect(controller.month).toEqual(nextMonth.getMonth()); + expect(controller.emit).toHaveBeenCalledWith('move', {$date: nextMonth}); + }); + }); + + describe('movePrevious()', () => { + it(`should shift to the previous month, then emit a 'move' event`, () => { + spyOn(controller, 'emit'); + let previousMonth = new Date(date.getTime()); + previousMonth.setMonth(previousMonth.getMonth() - 1); + + controller.movePrevious(); + + expect(controller.month).toEqual(previousMonth.getMonth()); + expect(controller.emit).toHaveBeenCalledWith('move', {$date: previousMonth}); + }); + }); + + describe('select()', () => { + it(`should return the selected element, then emit a 'selection' event`, () => { + spyOn(controller, 'emit'); + + const day = new Date(); + day.setHours(0, 0, 0, 0); + controller.select(day); + + let res = { + $days: [day], + $type: 'day' + }; + + expect(controller.field).toEqual(day); + expect(controller.emit).toHaveBeenCalledWith('selection', res); + }); + }); +}); + diff --git a/front/core/components/calendar/style.scss b/front/core/components/calendar/style.scss new file mode 100644 index 000000000..8492d09f1 --- /dev/null +++ b/front/core/components/calendar/style.scss @@ -0,0 +1,97 @@ +@import "variables"; + +.vn-calendar { + display: block; + + & > div { + & > .header { + display: flex; + margin-bottom: 0.5em; + align-items: center; + height: 2.4em; + + & > .title { + flex: 1; + text-align: center; + padding: 0.2em 0; + } + & > .vn-button { + color: inherit; + } + } + & > .weekdays { + display: flex; + color: $color-font-secondary; + margin-bottom: 0.5em; + padding: 0.5em 0; + font-weight: bold; + font-size: 0.8em; + text-align: center; + + & > section { + width: 14.28%; + cursor: pointer; + } + } + & > .days { + display: flex; + justify-content: center; + align-items: center; + flex-wrap: wrap; + + & > .day { + width: 14.28%; + height: 40px; + display: flex; + justify-content: center; + align-items: center; + + &.weekend { + color: $color-font-secondary; + } + &.previous, + &.next { + opacity: .5; + } + &.event .day-number { + background-color: $color-main; + color: $color-font-dark; + } + & > .day-number { + display: flex; + justify-content: center; + align-items: center; + border-radius: 50%; + font-size: 14px; + width: 2.2em; + height: 2.2em; + cursor: pointer; + outline: 0; + transition: background-color 300ms ease-in-out; + + &:hover { + background-color: lighten($color-font-secondary, 20%); + opacity: .8 + } + } + } + &.hide-contiguous > .day { + &.previous, + &.next { + visibility: hidden; + } + } + } + } + &.disabled, + &.readonly { + & > div { + & > .weekdays > section { + cursor: initial; + } + & > .days > .day > .day-number { + cursor: initial; + } + } + } +} diff --git a/front/core/components/card/card.js b/front/core/components/card/card.js new file mode 100644 index 000000000..c0be1e3d3 --- /dev/null +++ b/front/core/components/card/card.js @@ -0,0 +1,17 @@ +import ngModule from '../../module'; +require('./style.scss'); + +export default function directive() { + return { + restrict: 'E', + transclude: true, + link: function($scope, $element, $attrs, $ctrl, $transclude) { + $element[0].classList.add('vn-shadow', 'bg-panel'); + + $transclude($scope, function(clone) { + $element.append(clone); + }); + } + }; +} +ngModule.directive('vnCard', directive); diff --git a/front/core/components/card/style.scss b/front/core/components/card/style.scss new file mode 100644 index 000000000..a459879df --- /dev/null +++ b/front/core/components/card/style.scss @@ -0,0 +1,4 @@ +vn-card { + display: block; + box-sizing: border-box; +} \ No newline at end of file diff --git a/front/core/components/check/index.html b/front/core/components/check/index.html new file mode 100644 index 000000000..8c8171410 --- /dev/null +++ b/front/core/components/check/index.html @@ -0,0 +1,12 @@ +
    +
    +
    +
    + + {{::$ctrl.label}} + + + \ No newline at end of file diff --git a/front/core/components/check/index.js b/front/core/components/check/index.js new file mode 100644 index 000000000..78b1807a5 --- /dev/null +++ b/front/core/components/check/index.js @@ -0,0 +1,76 @@ +import ngModule from '../../module'; +import Toggle from '../toggle'; +import './style.scss'; + +/** + * Basic element for user input. You can use this to supply a way for the user + * to toggle an option. + * + * @property {Boolean} tripleState Switch between three states when clicked + * @property {Boolean} indeterminate Sets the element into indeterminate state + * @property {String} info Shows a text information tooltip to the user + */ +export default class Check extends Toggle { + set field(value) { + super.field = value; + this.element.classList.toggle('checked', Boolean(value)); + this.indeterminate = Boolean(value == null && this.tripleState); + } + + get field() { + return super.field; + } + + set checked(value) { + this.field = Boolean(value); + } + + get checked() { + return Boolean(this.field); + } + + set indeterminate(value) { + this._indeterminate = value; + this.element.classList.toggle('indeterminate', Boolean(value)); + } + + get indeterminate() { + return this._indeterminate; + } + + set tripleState(value) { + this._tripleState = value; + this.field = this.field; + } + + get tripleState() { + return this._tripleState; + } + + onClick(event) { + if (super.onClick(event)) return; + let value; + + if (this.tripleState) { + if (this.field == null) + value = true; + else if (this.field) + value = false; + else + value = null; + } else + value = !this.field; + + this.change(value); + } +} + +ngModule.vnComponent('vnCheck', { + template: require('./index.html'), + controller: Check, + bindings: { + tripleState: ' { + let $element; + let controller; + let element; + + beforeEach(ngModule('vnCore')); + + beforeEach(inject(($compile, $rootScope) => { + $element = $compile(``)($rootScope); + controller = $element.controller('vnCheck'); + element = $element[0]; + })); + + afterEach(() => { + $element.remove(); + }); + + describe('field() setter', () => { + it(`should set model value`, () => { + controller.field = true; + + expect(controller.field).toEqual(true); + }); + + it(`should uncheck value and change to true when clicked`, () => { + controller.field = false; + element.click(); + + expect(controller.field).toEqual(true); + }); + + it(`should check value and change to false when clicked`, () => { + controller.field = true; + element.click(); + + expect(controller.field).toEqual(false); + }); + + it(`should check value and change to false when clicked`, () => { + controller.field = true; + controller.tripleState = true; + element.click(); + + expect(controller.field).toEqual(false); + }); + + it(`should set value to null and change to true when clicked`, () => { + controller.field = null; + controller.tripleState = true; + element.click(); + + expect(controller.field).toEqual(true); + }); + + it(`should cast value to boolean when clicked`, () => { + controller.field = 0; + element.click(); + + expect(controller.field).toEqual(true); + }); + }); +}); diff --git a/front/core/components/check/style.scss b/front/core/components/check/style.scss new file mode 100644 index 000000000..b84b61ce5 --- /dev/null +++ b/front/core/components/check/style.scss @@ -0,0 +1,46 @@ +@import "variables"; + +.vn-check { + & > .btn { + border-radius: 2px; + transition: background 250ms; + + & > .mark { + box-sizing: border-box; + position: absolute; + display: block; + border-width: 0; + } + } + & > vn-icon { + margin-left: 5px; + color: $color-font-secondary; + vertical-align: middle; + } + &.checked > .btn { + border-color: transparent; + background-color: $color-button; + + & > .mark { + top: 0; + left: 4px; + transform: rotate(45deg); + width: 7px; + height: 13px; + border: 2px solid $color-font-dark; + border-top: 0; + border-left: 0; + } + } + &.indeterminate > .btn > .mark { + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 12px; + height: 2px; + border-bottom: 2px solid #666; + } + &.disabled.checked > .btn { + background-color: $color-font-secondary; + } +} diff --git a/front/core/components/chip/index.html b/front/core/components/chip/index.html new file mode 100644 index 000000000..38a56923d --- /dev/null +++ b/front/core/components/chip/index.html @@ -0,0 +1,7 @@ +
    + + \ No newline at end of file diff --git a/front/core/components/chip/index.js b/front/core/components/chip/index.js new file mode 100644 index 000000000..6cffecc2b --- /dev/null +++ b/front/core/components/chip/index.js @@ -0,0 +1,20 @@ +import ngModule from '../../module'; +import Component from '../../lib/component'; +import './style.scss'; + +export default class Chip extends Component { + onRemove() { + if (!this.disabled) this.emit('remove'); + } +} +Chip.$inject = ['$element', '$scope', '$transclude']; + +ngModule.vnComponent('vnChip', { + template: require('./index.html'), + controller: Chip, + transclude: true, + bindings: { + disabled: ' { + let $element; + let $scope; + let controller; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject(($componentController, $rootScope) => { + $scope = $rootScope.$new(); + $element = angular.element(`
    ${template}
    `); + controller = $componentController('vnChip', {$element, $scope, $transclude: () => {}}); + })); + + describe('onRemove()', () => { + it(`should emit remove event`, () => { + controller.emit = () => {}; + spyOn(controller, 'emit'); + controller.onRemove(); + + expect(controller.emit).toHaveBeenCalledWith('remove'); + }); + }); +}); diff --git a/front/core/components/chip/style.scss b/front/core/components/chip/style.scss new file mode 100644 index 000000000..3778c62b9 --- /dev/null +++ b/front/core/components/chip/style.scss @@ -0,0 +1,72 @@ +@import "variables"; + +vn-chip { + border-radius: 1em; + background-color: $color-bg; + color: $color-font; + font-size: .9rem; + margin: .25em; + display: inline-flex; + align-items: center; + height: 2em; + max-width: 100%; + box-sizing: border-box; + + &.colored { + background-color: $color-main; + color: $color-font-bg; + } + &.notice { + background-color: $color-notice-medium + } + &.success { + background-color: $color-success-medium; + } + &.warning { + background-color: $color-main-medium; + } + &.alert { + background-color: $color-alert-medium; + } + &.message { + color: $color-font-dark; + background-color: $color-bg-dark + } + + & > div { + display: flex; + align-items: center; + height: 100%; + padding: 0 .7em; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + + & > vn-avatar { + margin-left: -0.7em; + margin-right: .3em; + vertical-align: middle; + height: 2em; + width: 2em; + } + } + & > vn-icon { + margin-right: .12em; + margin-left: -.12em; + vertical-align: middle; + opacity: .6; + cursor: pointer; + transition: opacity 250ms ease-out; + + &:hover, + &:focus { + opacity: 1; + } + } +} + +vn-avatar { + display: inline-block; + min-width: 2em; + border-radius: 50%; +} \ No newline at end of file diff --git a/front/core/components/confirm/confirm.html b/front/core/components/confirm/confirm.html new file mode 100644 index 000000000..5ef8fde75 --- /dev/null +++ b/front/core/components/confirm/confirm.html @@ -0,0 +1,10 @@ +
    + +
    {{::$ctrl.message}}
    + {{::$ctrl.question}} +
    + + + + +
    \ No newline at end of file diff --git a/front/core/components/confirm/confirm.js b/front/core/components/confirm/confirm.js new file mode 100644 index 000000000..f187a3cb4 --- /dev/null +++ b/front/core/components/confirm/confirm.js @@ -0,0 +1,23 @@ +import ngModule from '../../module'; +import Dialog from '../dialog'; +import template from './confirm.html'; +import './style.scss'; + +export default class Confirm extends Dialog { + constructor($element, $, $transclude) { + super($element, $, $transclude); + + let $template = angular.element(template); + this.fillSlot('body', $template.find('tpl-body')); + this.fillSlot('buttons', $template.find('tpl-buttons')); + } +} + +ngModule.vnComponent('vnConfirm', { + controller: Confirm, + transclude: true, + bindings: { + question: '@', + message: '@?' + } +}); diff --git a/front/core/components/confirm/style.scss b/front/core/components/confirm/style.scss new file mode 100644 index 000000000..d3cea6cb1 --- /dev/null +++ b/front/core/components/confirm/style.scss @@ -0,0 +1,3 @@ +.vn-confirm .window { + max-width: 30em +} \ No newline at end of file diff --git a/front/core/components/crud-model/crud-model.js b/front/core/components/crud-model/crud-model.js new file mode 100644 index 000000000..9a260a690 --- /dev/null +++ b/front/core/components/crud-model/crud-model.js @@ -0,0 +1,290 @@ +import ngModule from '../../module'; +import ModelProxy from '../model-proxy/model-proxy'; +import {mergeWhere, mergeFilters} from 'vn-loopback/util/filter'; + +/** + * Model that uses remote loopback model as datasource. + * + * @property {Array} fields the list of fields to fetch + */ +export default class CrudModel extends ModelProxy { + constructor($q, $http, $element, $scope) { + super($element, $scope); + this.$http = $http; + this.$q = $q; + this.primaryKey = 'id'; + this.autoLoad = false; + } + + $onInit() { + this.initialized = true; + this.autoRefresh(); + } + + get isLoading() { + return this.canceler != null; + } + + /** + * @type {String} The remote model URL + */ + get url() { + return this._url; + } + + set url(url) { + if (this._url === url) return; + this._url = url; + this.clear(); + + if (this.initialized) + this.autoRefresh(); + } + + autoRefresh() { + if (this.autoLoad) + return this.refresh(); + return this.$q.resolve(); + } + + buildFilter() { + let order = this.order; + + if (typeof order === 'string') + order = this.order.split(/\s*,\s*/); + + let myFilter = { + fields: this.fields, + where: mergeWhere(this.link, this.where), + include: this.include, + order: order, + limit: this.limit + }; + + let filter = this.filter; + filter = mergeFilters(myFilter, filter); + filter = mergeFilters(this.userFilter, filter); + return filter; + } + + refresh() { + if (!this._url) + return this.$q.resolve(); + return this.sendRequest(this.buildFilter()); + } + + /** + * Applies a new filter to the model. + * + * @param {Object} filter The Loopback filter + * @param {Object} params Custom parameters + * @return {Promise} The request promise + */ + applyFilter(filter, params) { + this.userFilter = filter; + this.userParams = params; + return this.refresh(); + } + + /** + * Adds a filter to the model. + * + * @param {Object} filter The Loopback filter + * @param {Object} params Custom parameters + * @return {Promise} The request promise + */ + addFilter(filter, params) { + this.userFilter = mergeFilters(filter, this.userFilter); + this.userParams = Object.assign({}, this.userParams, params); + return this.refresh(); + } + + removeFilter() { + return applyFilter(null, null); + } + + /** + * Cancels the current request, if any. + */ + cancelRequest() { + if (this.canceler) { + this.canceler.resolve(); + this.canceler = null; + } + } + + loadMore() { + if (!this.moreRows) + return this.$q.resolve(); + + let filter = Object.assign({}, this.currentFilter); + filter.skip = this.orgData ? this.orgData.length : 0; + return this.sendRequest(filter, true); + } + + clear() { + this.orgData = null; + this.moreRows = null; + } + + /** + * Returns an object with the unsaved changes made to the model. + * + * @return {Object} The current changes + */ + getChanges() { + if (!this.isChanged) + return null; + + let deletes = []; + let updates = []; + let creates = []; + + let pk = this.primaryKey; + + for (let row of this.removed) + deletes.push(row.$orgRow[pk]); + + for (let row of this._data) { + if (row.$isNew) { + let data = {}; + for (let prop in row) { + if (prop.charAt(0) !== '$') + data[prop] = row[prop]; + } + creates.push(data); + } else if (row.$oldData) { + let data = {}; + for (let prop in row.$oldData) + data[prop] = row[prop]; + updates.push({ + data, + where: {[pk]: row.$orgRow[pk]} + }); + } + } + + let changes = {deletes, updates, creates}; + + for (let prop in changes) { + if (changes[prop].length === 0) + changes[prop] = undefined; + } + + return changes; + } + + /** + * Saves current changes on the server. + * + * @return {Promise} The save request promise + */ + save() { + let changes = this.getChanges(); + + if (!changes) + return this.$q.resolve(); + + let url = this.saveUrl ? this.saveUrl : `${this._url}/crud`; + return this.$http.post(url, changes) + .then(() => { + this.applyChanges(); + super.save(); + }); + } + + buildParams() { + let params = {}; + + if (this.params instanceof Object) + Object.assign(params, this.params); + if (this.userParams instanceof Object) + Object.assign(params, this.userParams); + + return params; + } + + sendRequest(filter, append) { + this.cancelRequest(); + this.canceler = this.$q.defer(); + this.isPaging = append; + + if (!append && this.status != 'ready') + this.status = 'loading'; + + let params = Object.assign( + {filter}, + this.buildParams() + ); + let options = { + timeout: this.canceler.promise, + params: params + }; + + return this.$http.get(this._url, options).then( + json => this.onRemoteDone(json, filter, append), + json => this.onRemoteError(json, append) + ).finally(() => { + this.isPaging = false; + }); + } + + onRemoteDone(json, filter, append) { + let data = json.data; + + if (append) + this.orgData = this.orgData.concat(data); + else { + this.orgData = data; + this.currentFilter = filter; + } + + this.data = this.proxiedData.slice(); + this.moreRows = filter.limit && data.length == filter.limit; + this.onRequestEnd(); + } + + onRemoteError(err, append) { + if (!append) { + this.clear(); + this.status = 'error'; + } + + this.onRequestEnd(); + throw err; + } + + onRequestEnd() { + this.canceler = null; + } + + undoChanges() { + super.undoChanges(); + this.data = this.proxiedData.slice(); + } +} +CrudModel.$inject = ['$q', '$http', '$element', '$scope']; + +ngModule.component('vnCrudModel', { + controller: CrudModel, + bindings: { + orgData: ' +
    + + + +
    + + + + Enter a new search + + + Ups! It seems there was an error + + + No results + +
    \ No newline at end of file diff --git a/front/core/components/data-viewer/index.js b/front/core/components/data-viewer/index.js new file mode 100644 index 000000000..1f967d94b --- /dev/null +++ b/front/core/components/data-viewer/index.js @@ -0,0 +1,33 @@ +import ngModule from '../../module'; +import './style.scss'; + +export default class DataViewer { + get isReady() { + return this.status == 'ready'; + } + + get status() { + if (this.model) + return this.model.status; + + if (this.isLoading) + return 'loading'; + if (!this.data) + return 'clear'; + if (this.data.length) + return 'ready'; + else + return 'empty'; + } +} + +ngModule.component('vnDataViewer', { + template: require('./index.html'), + transclude: true, + controller: DataViewer, + bindings: { + model: ' .empty-rows { + display: block; + text-align: center; + padding: 1.5em; + box-sizing: border-box; + color: $color-font-secondary; + font-size: 1.4em; + } +} \ No newline at end of file diff --git a/front/core/components/date-picker/index.js b/front/core/components/date-picker/index.js new file mode 100644 index 000000000..24f8cf90f --- /dev/null +++ b/front/core/components/date-picker/index.js @@ -0,0 +1,55 @@ +import ngModule from '../../module'; +import Field from '../field'; + +class DatePicker extends Field { + constructor($element, $scope, $compile) { + super($element, $scope, $compile); + + this.input = $compile(``)($scope)[0]; + this.input.addEventListener('change', () => this.onValueUpdate()); + } + + onValueUpdate() { + let date = null; + let value = this.input.value; + + if (value) { + let ymd = value.split('-') + .map(e => parseInt(e)); + date = new Date(ymd[0], ymd[1] - 1, ymd[2]); + + if (this.field) { + let orgDate = this.field instanceof Date + ? this.field + : new Date(this.field); + + date.setHours( + orgDate.getHours(), + orgDate.getMinutes(), + orgDate.getSeconds(), + orgDate.getMilliseconds() + ); + } + } + + super.field = date; + this.$.$applyAsync(); + } + + get field() { + return super.field; + } + + set field(value) { + super.field = value; + this.input.value = this.$filter('date')(value, 'yyyy-MM-dd'); + } +} +DatePicker.$inject = ['$element', '$scope', '$compile']; + +ngModule.vnComponent('vnDatePicker', { + controller: DatePicker, + bindings: { + options: ' { + let $filter; + let $element; + let $ctrl; + + let today; + today = new Date(); + today.setHours(0, 0, 0, 0); + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject(($compile, $rootScope, _$filter_) => { + $filter = _$filter_; + + $element = $compile(``)($rootScope); + $ctrl = $element.controller('vnDatePicker'); + })); + + afterEach(() => { + $element.remove(); + }); + + describe('field() setter', () => { + it(`should display the formated the date`, () => { + $ctrl.field = today; + let displayed = $filter('date')(today, 'yyyy-MM-dd'); + + expect($ctrl.value).toEqual(displayed); + }); + }); + + describe('onValueUpdate()', () => { + it(`should change the picker value to selected date`, () => { + $ctrl.value = $filter('date')(today, 'yyyy-MM-dd'); + $ctrl.input.dispatchEvent(new Event('change')); + + expect($ctrl.field).toEqual(today); + }); + }); +}); diff --git a/front/core/components/debug-info/index.html b/front/core/components/debug-info/index.html new file mode 100644 index 000000000..1ce9e6b08 --- /dev/null +++ b/front/core/components/debug-info/index.html @@ -0,0 +1,9 @@ +
    Debug info
    +
      +
    • + {{$ctrl.env}} +
    • +
    • + {{$root.$$watchersCount}} watchers +
    • +
    \ No newline at end of file diff --git a/front/core/components/debug-info/index.js b/front/core/components/debug-info/index.js new file mode 100644 index 000000000..5e3d2e1ea --- /dev/null +++ b/front/core/components/debug-info/index.js @@ -0,0 +1,27 @@ +import ngModule from '../../module'; +import './style.scss'; + +/** + * Floating box displaying debugging information. + * Enabled only in development environment. + */ +export default class Controller { + constructor($element, $) { + this.env = process.env.NODE_ENV || 'development'; + + if (this.env == 'development') + this.interval = setInterval(() => $.$digest(), 2000); + else + $element[0].style.display = 'none'; + } + + $onDestroy() { + clearInterval(this.interval); + } +} +Controller.$inject = ['$element', '$scope']; + +ngModule.component('vnDebugInfo', { + template: require('./index.html'), + controller: Controller +}); diff --git a/front/core/components/debug-info/style.scss b/front/core/components/debug-info/style.scss new file mode 100644 index 000000000..95c024a6d --- /dev/null +++ b/front/core/components/debug-info/style.scss @@ -0,0 +1,44 @@ +@import "variables"; + +vn-debug-info { + position: fixed; + bottom: 1em; + left: 1em; + padding: 1em; + min-width: 8em; + background-color: #3f51b5; + color: $color-font-dark; + border-radius: 4px; + z-index: 999; + box-shadow: $shadow; + transition: opacity 400ms ease-in-out; + + &:hover { + opacity: .5; + } + & > h6 { + font-weight: normal; + color: rgba(255, 255, 255, .5); + font-size: 1em; + } + ul { + list-style-type: none; + padding: 0; + margin: 0; + + & > li { + margin-top: .2em; + font-size: .95em; + + & > span { + padding: .05em .2em; + border-radius: 4px; + transition: background-color 200ms ease-in-out; + + &.alert { + background-color: $color-alert; + } + } + } + } +} \ No newline at end of file diff --git a/front/core/components/dialog/index.html b/front/core/components/dialog/index.html new file mode 100644 index 000000000..c213042e1 --- /dev/null +++ b/front/core/components/dialog/index.html @@ -0,0 +1,22 @@ +
    + +
    + + +
    +
    +
    +
    +
    +
    \ No newline at end of file diff --git a/front/core/components/dialog/index.js b/front/core/components/dialog/index.js new file mode 100644 index 000000000..7a7cb5f9f --- /dev/null +++ b/front/core/components/dialog/index.js @@ -0,0 +1,140 @@ +import ngModule from '../../module'; +import Popup from '../popup'; +import template from './index.html'; +import './style.scss'; + +/** + * Dialog component that allows to register function handlers for responses. If + * any of the handlers returns false or a promise that resolves to false, + * the dialog closing is cancelled. Also, if promise is returned, the dialog + * will wait until it is resolved by locking itself and displaying a loading + * animation. + * + * @property {Function} onResponse Handler for dialog response + * @property {Function} onAccept Shortcut handler for accept response + * @slot body The dialog HTML body + * @slot buttons The dialog HTML buttons + */ +export default class Dialog extends Popup { + constructor($element, $, $transclude) { + super($element, $, $transclude); + this.fillDefaultSlot(template); + } + + /** + * Shows the dialog and optionally registers a handler for the response. + * + * @param {*} data Optional user data to pass to response handler + * @param {Function} responseHandler An optional response handler + * @return {Promise} A promise that will be resolved with response when dialog is closed + */ + show(data, responseHandler) { + if (this.shown) + return this.$q.reject(new Error('Dialog already shown')); + super.show(); + + if (typeof data == 'function') { + responseHandler = data; + data = null; + } + + this.data = data; + this.showHandler = responseHandler; + return this.$q(resolve => { + this.resolve = resolve; + }); + } + + /** + * Hides the dialog resolving the promise returned by show(). + * + * @param {String} response The response + */ + hide(response) { + if (!this.shown) return; + super.hide(); + + this.showHandler = null; + if (this.resolve) + this.resolve(response); + } + + /** + * Calls the response handlers. + * + * @param {String} response The response code + * @return {Boolean} The response handler return + */ + respond(response) { + if (!this.shown) + return this.$q.resolve(); + + let handlerArgs = { + $response: response, + $data: this.data + }; + let cancellers = []; + + if (this.onResponse) + cancellers.push(this.onResponse(handlerArgs)); + if (response == 'accept' && this.onAccept) + cancellers.push(this.onAccept(handlerArgs)); + if (this.showHandler) + cancellers.push(this.showHandler(response, this.data)); + + let promises = []; + let resolvedCancellers = []; + + for (let canceller of cancellers) { + if (canceller instanceof Object && canceller.then) + promises.push(canceller); + else + resolvedCancellers.push(canceller); + } + + let close = () => { + if (resolvedCancellers.indexOf(false) == -1) + this.hide(response); + else + return false; + }; + + if (promises.length) { + this.loading = true; + + return this.$q.all(promises) + .then(res => { + resolvedCancellers = resolvedCancellers.concat(res); + return close(); + }) + .finally(() => { + this.loading = false; + }); + } else + return this.$q.resolve(close()); + } + + onButtonClick(event) { + let buttons = this.popup.querySelector('.buttons'); + let tplButtons = buttons.querySelector('tpl-buttons'); + let node = event.target; + while (node.parentNode != tplButtons) { + if (node == buttons) return; + node = node.parentNode; + } + + this.respond(node.getAttribute('response')); + } +} + +ngModule.vnComponent('vnDialog', { + controller: Dialog, + transclude: { + body: 'tplBody', + buttons: '?tplButtons' + }, + bindings: { + onResponse: '&?', + onAccept: '&?' + } +}); diff --git a/front/core/components/dialog/index.spec.js b/front/core/components/dialog/index.spec.js new file mode 100644 index 000000000..8c41bc060 --- /dev/null +++ b/front/core/components/dialog/index.spec.js @@ -0,0 +1,99 @@ +describe('Component vnDialog', () => { + let $element; + let $scope; + let controller; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject(($rootScope, $compile) => { + $scope = $rootScope.$new(); + $element = $compile('Body')($scope); + controller = $element.controller('vnDialog'); + controller.emit = jasmine.createSpy('emit'); + })); + + afterEach(() => { + $scope.$destroy(); + $element.remove(); + }); + + describe('show()', () => { + it(`should call the show handler when response is given`, () => { + let called; + let showHandler = () => called = true; + + controller.show(showHandler); + controller.respond(); + + expect(called).toBeTruthy(); + }); + + it(`should not hide the dialog when false is returned from response handler`, () => { + controller.show(() => false); + spyOn(controller, 'hide'); + controller.respond('answer'); + + expect(controller.hide).not.toHaveBeenCalled(); + }); + }); + + describe('hide()', () => { + it(`should resolve the promise returned by show`, () => { + let resolved = true; + controller.show().then(() => resolved = true); + controller.hide(); + $scope.$apply(); + + expect(resolved).toBeTruthy(); + }); + }); + + describe('respond()', () => { + it(`should do nothing if dialog is already hidden`, () => { + controller.onResponse = () => {}; + spyOn(controller, 'onResponse'); + controller.respond(); + + expect(controller.onResponse).not.toHaveBeenCalledWith(); + }); + + it(`should call onResponse() if it's defined`, () => { + controller.onResponse = () => {}; + spyOn(controller, 'onResponse'); + + controller.show(); + controller.respond(); + + expect(controller.onResponse).toHaveBeenCalledWith(jasmine.any(Object)); + }); + + it(`should call onResponse() with the response`, () => { + controller.onResponse = () => {}; + spyOn(controller, 'onResponse'); + + controller.show(); + controller.respond('response'); + + expect(controller.onResponse).toHaveBeenCalledWith({$response: 'response'}); + }); + + it(`should call onAccept() when accept response is given`, () => { + controller.onAccept = () => {}; + spyOn(controller, 'onAccept'); + + controller.show(); + controller.respond('accept'); + + expect(controller.onAccept).toHaveBeenCalledWith({$response: 'accept'}); + }); + + it(`should resolve the promise returned by show() with response`, () => { + let response; + controller.show().then(res => response = res); + controller.respond('response'); + $scope.$apply(); + + expect(response).toEqual('response'); + }); + }); +}); diff --git a/front/core/components/dialog/style.scss b/front/core/components/dialog/style.scss new file mode 100644 index 000000000..2f3d9a028 --- /dev/null +++ b/front/core/components/dialog/style.scss @@ -0,0 +1,63 @@ +@import "effects"; + +.vn-dialog > .window { + position: relative; + + & > .close { + @extend %clickable; + text-transform: uppercase; + background-color: transparent; + border: none; + border-radius: .1em; + position: absolute; + top: 0; + right: 0; + padding: .3em; + color: #666; + } + & > form { + padding: $spacing-lg; + + & > .body > tpl-body { + display: block; + min-width: 16em; + } + & > .buttons > tpl-buttons { + display: block; + margin-top: 1.5em; + text-align: right; + + button, + input[type="button"], + input[type="submit"], + input[type="reset"] { + @extend %clickable; + text-transform: uppercase; + background-color: transparent; + border: none; + border-radius: .1em; + color: $color-button; + font-family: vn-font-bold; + padding: .7em; + margin: -0.7em; + margin-left: .7em; + } + } + } + & > .loading-overlap { + position: absolute; + width: 100%; + height: 100%; + background-color: rgba(0, 0, 0, .2); + display: flex; + align-items: center; + justify-content: center; + z-index: 1; + opacity: 0; + transition: opacity 200ms ease-in-out; + + &.shown { + opacity: 1; + } + } +} diff --git a/front/core/components/drop-down/index.html b/front/core/components/drop-down/index.html new file mode 100644 index 000000000..5366d9d90 --- /dev/null +++ b/front/core/components/drop-down/index.html @@ -0,0 +1,21 @@ +
    + + +
    +
    + +
    + {{$ctrl.statusText}} +
    +
    \ No newline at end of file diff --git a/front/core/components/drop-down/index.js b/front/core/components/drop-down/index.js new file mode 100644 index 000000000..9f2dfe424 --- /dev/null +++ b/front/core/components/drop-down/index.js @@ -0,0 +1,475 @@ +import './style.scss'; +import ngModule from '../../module'; +import Popover from '../popover'; +import template from './index.html'; +import ArrayModel from '../array-model/array-model'; +import CrudModel from '../crud-model/crud-model'; +import {mergeWhere} from 'vn-loopback/util/filter'; +import focus from '../../lib/focus'; + +/** + * @event select Thrown when model item is selected + * @event change Thrown when model data is ready + */ +export default class DropDown extends Popover { + constructor($element, $, $transclude) { + super($element, $, $transclude); + this.valueField = 'id'; + this.showField = 'name'; + this._search = undefined; + this._activeOption = -1; + this.showLoadMore = true; + this.showFilter = true; + this.searchDelay = 300; + this.fillDefaultSlot(template); + } + + get search() { + return this._search; + } + + set search(value) { + let oldValue = this._search; + this._search = value; + + if (!this.shown) return; + + value = value == '' || value == null ? null : value; + oldValue = oldValue == '' || oldValue == null ? null : oldValue; + if (value === oldValue && this.modelData != null) return; + + if (value != null) + this._activeOption = 0; + + this.$timeout.cancel(this.searchTimeout); + + if (this.model) { + this.model.clear(); + if (!this.data) { + this.searchTimeout = this.$timeout(() => { + this.refreshModel(); + this.searchTimeout = null; + }, value != null ? this.searchDelay : 0); + } else + this.refreshModel(); + } + + this.buildList(); + } + + get statusText() { + let model = this.model; + let data = this.modelData; + + if (!model) + return 'No data'; + if (model.isLoading || this.searchTimeout) + return 'Loading...'; + if (data == null) + return 'No data'; + if (model.moreRows) + return 'Load More'; + if (data.length === 0) + return 'No results found'; + + return null; + } + + get activeOption() { + return this._activeOption; + } + + /** + * Shows the drop-down. If a parent is specified it is shown in a visible + * relative position to it. + * + * @param {HTMLElement} parent The parent element to show drop down relative to + * @param {String} search The initial search term or %null + */ + show(parent, search) { + if (this.shown) return; + super.show(parent); + + this._activeOption = -1; + + this.list = this.popup.querySelector('.list'); + this.ul = this.popup.querySelector('ul'); + + this.docKeyDownHandler = e => this.onDocKeyDown(e); + this.document.addEventListener('keydown', this.docKeyDownHandler); + + this.listScrollHandler = e => this.onScroll(e); + this.list.addEventListener('scroll', this.listScrollHandler); + this.list.scrollTop = 0; + + this.search = search; + this.buildList(); + + focus(this.popup.querySelector('input')); + } + + hide() { + if (!this.shown) return; + super.hide(); + + this.document.removeEventListener('keydown', this.docKeyDownHandler); + this.docKeyDownHandler = null; + + this.list.removeEventListener('scroll', this.listScrollHandler); + this.listScrollHandler = null; + } + + onClose() { + this.destroyList(); + this.list = null; + this.ul = null; + + super.onClose(); + } + + /** + * Activates an option and scrolls the drop-down to that option. + * + * @param {Number} option The option index + */ + moveToOption(option) { + this.activateOption(option); + + let list = this.list; + let li = this.activeLi; + if (!li) return; + + let liRect = li.getBoundingClientRect(); + let listRect = list.getBoundingClientRect(); + + if (liRect.bottom > listRect.bottom) + list.scrollTop += liRect.bottom - listRect.bottom; + else if (liRect.top < listRect.top) + list.scrollTop -= listRect.top - liRect.top; + } + + /** + * Activates an option. + * + * @param {Number} option The option index + */ + activateOption(option) { + this._activeOption = option; + + if (this.activeLi) + this.activeLi.className = ''; + + let data = this.modelData; + + if (option >= 0 && data && option < data.length) { + this.activeLi = this.ul.children[option]; + this.activeLi.className = 'active'; + } + } + + /** + * Selects an option. + * + * @param {Number} option The option index + */ + selectOption(option) { + let data = this.modelData; + let item = option != -1 && data ? data[option] : null; + + if (item) { + let value = item[this.valueField]; + + if (this.multiple) { + if (!Array.isArray(this.selection)) { + this.selection = []; + this.field = []; + } + + this.selection.push(item); + this.field.push(value); + } else { + this.selection = item; + this.field = value; + } + + this.emit('select', {item}); + } + + if (!this.multiple) + this.hide(); + } + + onClearClick() { + this.search = null; + } + + onScroll() { + let list = this.list; + let shouldLoad = + list.scrollTop + list.clientHeight >= (list.scrollHeight - 40) + && !this.model.isLoading; + + if (shouldLoad) + this.model.loadMore(); + } + + onLoadMoreClick(event) { + if (event.defaultPrevented) return; + this.model.loadMore(); + } + + onContainerClick(event) { + if (event.defaultPrevented) return; + let index = getPosition(this.ul, event); + if (index != -1) this.selectOption(index); + } + + onDocKeyDown(event) { + if (event.defaultPrevented) return; + + let data = this.modelData; + let option = this.activeOption; + let nOpts = data ? data.length - 1 : 0; + + switch (event.key) { + case 'Tab': + this.selectOption(option); + return; + case 'Enter': + this.selectOption(option); + break; + case 'ArrowUp': + this.moveToOption(option <= 0 ? nOpts : option - 1); + break; + case 'ArrowDown': + this.moveToOption(option >= nOpts ? 0 : option + 1); + break; + case 'End': + this.moveToOption(nOpts); + break; + case 'Home': + this.moveToOption(0); + break; + default: + return; + } + + event.preventDefault(); + this.$.$applyAsync(); + } + + buildList() { + if (!this.shown) return; + this.destroyList(); + + let hasTemplate = this.$transclude && this.$transclude.isSlotFilled('tplItem'); + let fragment = this.document.createDocumentFragment(); + let data = this.modelData; + + if (data) { + for (let i = 0; i < data.length; i++) { + let option = data[i]; + option.orgShowField = option[this.showField]; + + if (this.translateFields) { + option = Object.assign({}, option); + for (let field of this.translateFields) + option[field] = this.$translate.instant(option[field]); + } + + let li = this.document.createElement('li'); + + li.setAttribute('name', option.orgShowField); + fragment.appendChild(li); + + if (this.multiple) { + let check = this.document.createElement('input'); + check.type = 'checkbox'; + li.appendChild(check); + + if (this.field && this.field.indexOf(option[this.valueField]) != -1) + check.checked = true; + } + + if (hasTemplate) { + this.$transclude((clone, scope) => { + Object.assign(scope, option); + li.appendChild(clone[0]); + this.scopes[i] = scope; + }, null, 'tplItem'); + } else { + let text = this.document.createTextNode(option[this.showField]); + li.appendChild(text); + } + } + } + + this.ul.appendChild(fragment); + this.activateOption(this._activeOption); + this.$.$applyAsync(() => this.relocate()); + } + + destroyList() { + if (this.ul) + this.ul.innerHTML = ''; + + if (this.scopes) { + for (let scope of this.scopes) + scope.$destroy(); + } + + this.scopes = []; + } + + getFields() { + let fields = []; + fields.push(this.valueField); + fields.push(this.showField); + + if (this.fields) { + for (let field of this.fields) + fields.push(field); + } + + return fields; + } + + // Model related code + + onDataChange() { + if (this.model.orgData) + this.emit('dataReady'); + this.buildList(); + } + + get modelData() { + return this._model ? this._model.data : null; + } + + get model() { + return this._model; + } + + set model(value) { + this.linkEvents({_model: value}, {dataChange: this.onDataChange}); + this.onDataChange(); + } + + get url() { + return this._url; + } + + set url(value) { + this._url = value; + if (value) { + this.model = new CrudModel(this.$q, this.$http); + this.model.autoLoad = false; + this.model.url = value; + this.model.$onInit(); + } + } + + get data() { + return this._data; + } + + set data(value) { + this._data = value; + if (value) { + this.model = new ArrayModel(this.$q, this.$filter); + this.model.autoLoad = false; + this.model.orgData = value; + this.model.$onInit(); + } + } + + refreshModel() { + let model = this.model; + + let order; + if (this.order) + order = this.order; + else if (this.showField) + order = `${this.showField} ASC`; + + let filter = { + order, + limit: this.limit || 30 + }; + + if (model instanceof CrudModel) { + let searchExpr = this._search == null + ? null + : this.searchFunction({$search: this._search}); + + Object.assign(filter, { + fields: this.getFields(), + include: this.include, + where: mergeWhere(this.where, searchExpr) + }); + } else if (model instanceof ArrayModel) { + if (this._search != null) + filter.where = this.searchFunction({$search: this._search}); + } + + return this.model.applyFilter(filter); + } + + searchFunction(scope) { + if (this.model instanceof CrudModel) + return {[this.showField]: {like: `%${scope.$search}%`}}; + if (this.model instanceof ArrayModel) + return {[this.showField]: scope.$search}; + } +} + +/** + * Gets the position of an event element relative to a parent. + * + * @param {HTMLElement} parent The parent element + * @param {Event} event The event object + * @return {Number} The element index + */ +function getPosition(parent, event) { + let target = event.target; + let children = parent.children; + + if (target === parent) + return -1; + + while (target.parentNode !== parent) + target = target.parentNode; + + for (let i = 0; i < children.length; i++) { + if (children[i] === target) + return i; + } + + return -1; +} + +ngModule.vnComponent('vnDropDown', { + controller: DropDown, + transclude: { + tplItem: '?tplItem' + }, + bindings: { + field: '=?', + selection: '=?', + search: ' { + let $element; + let controller; + + beforeEach(ngModule('vnCore')); + + beforeEach(inject(($compile, $rootScope, $document) => { + $element = $compile(``)($rootScope); + $document.find('body').append($element); + controller = $element.controller('vnDropDown'); + })); + + afterEach(() => { + $element.remove(); + }); + + describe('show() method', () => { + it(`should enable the show property`, () => { + controller.show(); + + expect(controller.shown).toEqual(true); + }); + }); + + describe('hide() method', () => { + it(`should disable the show property`, () => { + controller.hide(); + + expect(controller.shown).toEqual(false); + }); + }); +}); diff --git a/front/core/components/drop-down/style.scss b/front/core/components/drop-down/style.scss new file mode 100755 index 000000000..fb346135f --- /dev/null +++ b/front/core/components/drop-down/style.scss @@ -0,0 +1,66 @@ +@import "effects"; +@import "variables"; + +.vn-drop-down > .window > .content { + display: flex; + flex-direction: column; + height: inherit; + + & > .filter { + position: relative; + + & > .search { + display: block; + width: 100%; + box-sizing: border-box; + padding: $spacing-sm; + } + & > vn-icon[icon=clear] { + display: none; + cursor: pointer; + position: absolute; + right: .5em; + top: .6em; + height: 1em; + color: #888; + border-radius: 50%; + background-color: rgba(255, 255, 255, .8); + font-size: 18px; + + &:hover { + color: $color-font; + } + } + &:hover > vn-icon[icon=clear] { + display: block; + } + } + & > .list { + max-height: 20em; + overflow: auto; + + ul { + padding: 0; + margin: 0; + list-style-type: none; + } + li, .status { + @extend %clickable; + padding: .6em; + white-space: nowrap; + display: flex; + + & > input[type=checkbox] { + margin: 0; + margin-right: .6em; + } + &.active { + @extend %active; + } + } + .status { + color: $color-main; + font-weight: bold; + } + } +} diff --git a/front/core/components/fetched-tags/index.html b/front/core/components/fetched-tags/index.html new file mode 100644 index 000000000..a1816d6f0 --- /dev/null +++ b/front/core/components/fetched-tags/index.html @@ -0,0 +1,15 @@ + + + {{::$ctrl.title}} + + +
    + {{::fetchedTag.value}} +
    +
    +
    \ No newline at end of file diff --git a/front/core/components/field/index.html b/front/core/components/field/index.html new file mode 100644 index 000000000..d614d157f --- /dev/null +++ b/front/core/components/field/index.html @@ -0,0 +1,35 @@ +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + + +
    +
    +
    +
    +
    +
    +
    +
    diff --git a/front/core/components/field/index.js b/front/core/components/field/index.js new file mode 100644 index 000000000..481ccce91 --- /dev/null +++ b/front/core/components/field/index.js @@ -0,0 +1,223 @@ +import ngModule from '../../module'; +import FormInput from '../form-input'; +import './style.scss'; + +export default class Field extends FormInput { + constructor($element, $scope) { + super($element, $scope); + + this.prefix = null; + this.suffix = null; + + this.control = this.element.querySelector('.control'); + this.element.addEventListener('click', e => this.onClick(e)); + + this.container = this.element.querySelector('.container'); + this.container.addEventListener('mousedown', e => this.onMouseDown(e)); + } + + $onInit() { + super.$onInit(); + + if (this.info) this.classList.add('has-icons'); + + this.input.addEventListener('focus', () => this.onFocus(true)); + this.input.addEventListener('blur', () => this.onFocus(false)); + this.input.addEventListener('change', () => this.onChange()); + } + + set field(value) { + if (value === this.field) return; + super.field = value; + this.classList.toggle('not-empty', value != null && value !== ''); + this.validateValue(); + } + + get field() { + return super.field; + } + + set input(value) { + if (this.input) + this.control.removeChild(this.input); + this._input = value; + if (value) + this.control.appendChild(value); + } + + get input() { + return this._input; + } + + set value(value) { + this.input.value = value; + } + + get value() { + return this.input.value; + } + + set type(value) { + this.input.type = value; + } + + get type() { + return this.input.type; + } + + set name(value) { + this.input.name = value; + } + + get name() { + return this.input.name; + } + + set placeholder(value) { + this.input.placeholder = value; + } + + get placeholder() { + return this.input.placeholder; + } + + set required(value) { + this._required = value; + let required = this.element.querySelector('.required'); + display(required, this._required); + } + + get required() { + return this._required; + } + + set prefix(value) { + this._prefix = value; + this.refreshFix('.prefix', value); + } + + get prefix() { + return this._prefix; + } + + set suffix(value) { + this._suffix = value; + this.refreshFix('.suffix', value); + } + + get suffix() { + return this._suffix; + } + + set hint(value) { + this._hint = value; + this.refreshHint(); + } + + get hint() { + return this._hint; + } + + set error(value) { + if (value === this.error) return; + this._error = value; + this.refreshHint(); + } + + get error() { + return this._error; + } + + get shownError() { + return this.error || this.inputError || null; + } + + refreshHint() { + let error = this.shownError; + let hint = error || this.hint; + + let hintEl = this.element.querySelector('.hint'); + hintEl.innerText = hint || ''; + hintEl.classList.toggle('filled', Boolean(hint)); + + this.classList.toggle('invalid', Boolean(error)); + } + + refreshFix(selector, text) { + let fix = this.element.querySelector(selector); + display(fix, text); + fix.innerText = text || ''; + } + + onClick() { + // if (event.defaultPrevented) return; + + if (this.input !== document.activeElement) + this.focus(); + } + + onMouseDown(event) { + if (event.target == this.input) return; + event.preventDefault(); + this.focus(); + } + + onFocus(hasFocus) { + this.classList.toggle('focused', hasFocus); + } + + onClear(event) { + if (event.defaultPrevented) return; + event.preventDefault(); + this.field = null; + this.input.dispatchEvent(new Event('change')); + } + + buildInput(type) { + let template = ``; + this.input = this.$compile(template)(this.$)[0]; + } + + /** + * If input value is invalid, sets the error message as hint. + */ + validateValue() { + let error = this.input.checkValidity() + ? null + : this.input.validationMessage; + + if (error === this.inputError) return; + this.inputError = error; + this.refreshHint(); + } + + onChange() { + this.emit('change', {value: this.field}); + } +} +Field.$inject = ['$element', '$scope']; + +ngModule.vnComponent('vnField', { + template: require('./index.html'), + transclude: { + prepend: '?prepend', + append: '?append' + }, + controller: Field, + bindings: { + type: '@?', + placeholder: '@?', + value: '=?', + info: '@?', + required: ' .container { + display: flex; + align-items: stretch; + position: relative; + + & > .infix { + position: relative; + display: flex; + flex: auto; + width: 100%; + min-width: 0; + + & > label { + position: absolute; + left: 0; + top: 18px; + line-height: 20px; + pointer-events: none; + color: $color-font-bg-marginal; + transition-property: top, color, font-size; + transition-duration: 400ms; + transition-timing-function: cubic-bezier(.4, 0, .2, 1); + + & > .required { + display: none; + color: $color-alert + } + } + & > .fix { + padding-top: 24px; + line-height: 24px; + font-size: 1rem; + opacity: 0; + transition: opacity 200ms ease-in-out; + + &.prefix { + padding-right: 5px; + } + &.suffix { + padding-left: 5px; + } + } + & > .control { + height: 100%; + flex: auto; + + & > * { + padding-top: 24px; + padding-bottom: 8px; + height: inherit; + outline: none; + border: none; + font-family: Arial, sans-serif; + display: block; + font-size: 1rem; + width: 100%; + background: 0; + color: inherit; + box-sizing: border-box; + min-height: 56px; + } + & > input { + position: relative; + color: $color-font; + + &::placeholder { + color: $color-font-bg; + } + &[type=time], + &[type=date], + &[type=password] { + opacity: 0; + transition: opacity 200ms ease-in-out; + cursor: pointer; + } + &[type=time], + &[type=date] { + clip-path: inset(0 20px 0 0); + + &::-webkit-inner-spin-button, + &::-webkit-clear-button { + display: none; + -webkit-appearance: none; + } + &::-webkit-calendar-picker-indicator { + position: absolute; + height: 100%; + width: 100%; + opacity: 0; + cursor: pointer; + } + } + &[type=number] { + -moz-appearance: textfield; + + &::-webkit-outer-spin-button, + &::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; + } + } + &:invalid { + box-shadow: none; + } + &:-internal-autofill-selected { + &, + &:hover, + &:focus, + &:active, + &:valid { + box-shadow: 0 0 0 40px $color-bg-panel inset; + } + } + } + } + } + & > .prepend, + & > .append, + & > .icons { + display: flex; + align-items: center; + color: $color-font-bg-marginal; + } + & > .prepend > prepend, + & > .append > append, + & > .icons { + display: flex; + align-items: center; + + & > vn-icon { + font-size: 24px; + } + } + & > .prepend > prepend { + padding-right: 12px; + } + & > .icons { + &.pre { + padding-left: 12px; + } + & > vn-icon { + cursor: pointer; + } + & > vn-icon[icon=clear] { + display: none; + } + } + & > .underline { + position: absolute; + bottom: 0; + content: ' '; + pointer-events: none; + width: 100%; + + &.blur { + border-bottom: 1px solid $color-input-underline; + transition: border-color 200ms ease-in-out; + } + &.focus { + height: 2px; + background-color: $color-primary; + left: 50%; + width: 0; + transition-property: width, left, background-color; + transition-duration: 300ms; + transition-timing-function: cubic-bezier(.4, 0, .2, 1); + } + } + } + &.dense { + & > .hint { + display: none; + } + & > .container > .infix { + & > label { + top: 8px; + } + & > .control > * { + padding-top: 8px; + min-height: 40px; + } + } + &.not-empty, + &.focused, + &.invalid { + & > .container > .infix > label { + top: 0; + line-height: 8px; + } + } + } + &.standout { + border-radius: .1em; + background-color: rgba(255, 255, 255, .1); + padding: 0 12px; + transition-property: background-color, color; + transition-duration: 200ms; + transition-timing-function: ease-in-out; + + & > .container { + & > .underline { + display: none; + } + & > .infix > .control > * { + color: $color-font-dark; + + &::placeholder { + color: $color-font-bg-dark; + } + } + & > .prepend, + & > .append, + & > .icons { + color: $color-font-bg-dark-marginal; + } + } + &.focused { + background-color: $color-bg-panel; + + & > .container { + & > .infix > .control > * { + color: $color-font; + + &::placeholder { + color: $color-font-bg; + } + } + & > .prepend, + & > .append, + & > .icons { + color: $color-font-bg-marginal; + } + } + } + } + &.not-empty, + &.focused, + &.invalid { + & > .container > .infix { + & > label { + top: 5px; + color: $color-primary; + padding: 0; + font-size: 12px; + } + & > .control > * { + &[type=time], + &[type=date], + &[type=password] { + opacity: 1; + } + } + } + } + &.has-icons, + &.not-empty:hover, + &.not-empty.focused { + & > .container { + & > .append > append { + padding-left: 0; + } + & > .icons.pre { + padding-left: 12px; + } + } + } + &:not(.disabled):not(.readonly) { + &.focused > .container > .underline.focus { + left: 0; + width: 100%; + } + & > .container:hover > .underline.blur { + border-color: $color-input-underline-hover; + } + &.not-empty:hover, + &.not-empty.focused { + & > .container > .icons > vn-icon[icon=clear] { + display: initial; + } + } + } + &.readonly > .container { + & > .infix > .control > * { + caret-color: transparent; + } + & > .underline.blur { + border-bottom-style: dashed; + } + } + & > .hint { + padding: 4px 0; + height: 12px; + color: rgba(0, 0, 0, .4); + font-size: 12px; + transform: translateY(-12px); + transition-property: opacity, transform, color; + transition-duration: 200ms; + transition-timing-function: ease-in-out; + opacity: 0; + visibility: hidden; + + &.filled { + opacity: 1; + transform: translateY(0); + visibility: visible; + } + } + &.invalid { + & > .container { + & > .infix > label { + color: $color-alert; + } + & > .underline.focus { + background-color: $color-alert; + } + & > .underline.blur { + border-bottom-color: $color-alert; + opacity: 1; + } + } + & > .hint { + color: $color-alert; + } + } +} diff --git a/front/core/components/float-button/index.js b/front/core/components/float-button/index.js new file mode 100644 index 000000000..32ada7437 --- /dev/null +++ b/front/core/components/float-button/index.js @@ -0,0 +1,13 @@ +import ngModule from '../../module'; +import Button from '../button'; + +export default class FloatButton extends Button { + constructor($element, $scope) { + super($element, $scope); + this.element.classList.add('round'); + } +} + +ngModule.vnComponent('vnFloatButton', { + controller: FloatButton +}); diff --git a/front/core/components/form-input/index.js b/front/core/components/form-input/index.js new file mode 100644 index 000000000..0395922c7 --- /dev/null +++ b/front/core/components/form-input/index.js @@ -0,0 +1,133 @@ +import ngModule from '../../module'; +import Component from '../../lib/component'; + +/** + * Base component for form inputs. + * + * @property {String} label Label to display along the component + * @property {any} field The value with which the element is linked + * @property {Boolean} disabled Put component in disabled mode + */ +export default class FormInput extends Component { + constructor($element, $scope) { + super($element, $scope); + this.classList = this.element.classList; + this.classList.add(...this.constructor.$classNames); + } + + $onInit() { + // XXX: Compatibility with old inputs + let attrs = this.$element[0].attributes; + if (!this.name && attrs['ng-model']) { + let split = attrs['ng-model'].nodeValue.split('.'); + this.name = split[split.length - 1]; + } + + if (!this.ngModel) return; + this.ngModel.$render = () => { + this.field = this.ngModel.$viewValue; + }; + } + + set field(value) { + this._field = value; + + if (this.ngModel) + this.ngModel.$setViewValue(value); + } + + get field() { + return this._field; + } + + set name(value) { + this.element.setAttribute('name', value); + } + + get name() { + return this.element.getAttribute('name'); + } + + set disabled(value) { + this._disabled = boolTag(value); + this.classList.toggle('disabled', this._disabled); + if (this.input) + this.input.disabled = this._disabled; + this.refreshTabIndex(); + } + + get disabled() { + return this._disabled; + } + + set readonly(value) { + this._readonly = boolTag(value); + this.classList.toggle('readonly', this._readonly); + if (this.input) + this.input.readOnly = this._readonly; + } + + get readonly() { + return this._readonly; + } + + set tabIndex(value) { + this._tabIndex = value; + this.refreshTabIndex(); + } + + get tabIndex() { + return this._tabIndex; + } + + get inputEl() { + return this.input || this.element; + } + + get editable() { + return !(this.readonly || this.disabled); + } + + select() { + if (this.inputEl.select) + this.inputEl.select(); + } + + focus() { + this.inputEl.focus(); + } + + initTabIndex() { + if (!this.element.hasAttribute('tabindex')) + this.element.tabIndex = 0; + } + + refreshTabIndex() { + this.inputEl.tabIndex = this.disabled ? -1 : this.tabIndex; + } + + change(value) { + this.field = value; + this.element.dispatchEvent(new Event('change')); + this.emit('change', {value: this.field}); + } +} + +ngModule.vnComponent('vnFormInput', { + controller: FormInput, + bindings: { + label: '@?', + field: '=?', + name: '@?', + disabled: ' button { + padding: .2em !important; + } + &:focus { + opacity: .6; + } +} diff --git a/front/core/components/icon-menu/index.html b/front/core/components/icon-menu/index.html new file mode 100644 index 000000000..0d59b3779 --- /dev/null +++ b/front/core/components/icon-menu/index.html @@ -0,0 +1,11 @@ + + + \ No newline at end of file diff --git a/front/core/components/icon-menu/index.js b/front/core/components/icon-menu/index.js new file mode 100644 index 000000000..6dd3d683a --- /dev/null +++ b/front/core/components/icon-menu/index.js @@ -0,0 +1,14 @@ +import ngModule from '../../module'; +import ButtonMenu from '../button-menu'; + +export default class IconMenu extends ButtonMenu { + constructor($element, $scope, $transclude) { + super($element, $scope, $transclude); + this.element.classList.add('flat'); + } +} + +ngModule.vnComponent('vnIconMenu', { + template: require('./index.html'), + controller: IconMenu +}); diff --git a/client/core/src/components/icon/icon.js b/front/core/components/icon/icon.js similarity index 88% rename from client/core/src/components/icon/icon.js rename to front/core/components/icon/icon.js index 01087b0c7..1b78f4693 100644 --- a/client/core/src/components/icon/icon.js +++ b/front/core/components/icon/icon.js @@ -26,7 +26,7 @@ class Icon { Icon.$inject = ['$attrs']; ngModule.component('vnIcon', { - template: '{{::$ctrl.iconContent}}', + template: '{{::$ctrl.iconContent}}', controller: Icon, bindings: { icon: '@' diff --git a/front/core/components/icon/style.scss b/front/core/components/icon/style.scss new file mode 100644 index 000000000..07a1584e3 --- /dev/null +++ b/front/core/components/icon/style.scss @@ -0,0 +1,12 @@ +vn-icon { + display: inline-block; + font-size: 18pt; + text-align: center; + outline: 0; + + & > i, + & > i.material-icons { + display: block; + font-size: inherit; + } +} diff --git a/front/core/components/index.js b/front/core/components/index.js new file mode 100644 index 000000000..0ebd03420 --- /dev/null +++ b/front/core/components/index.js @@ -0,0 +1,51 @@ +import './model-proxy/model-proxy'; +import './crud-model/crud-model'; +import './watcher/watcher'; +import './textfield/textfield'; +import './icon/icon'; +import './confirm/confirm'; +import './title/title'; +import './subtitle/subtitle'; +import './spinner/spinner'; +import './snackbar/snackbar'; +import './tooltip/tooltip'; +import './menu/menu'; +import './multi-check/multi-check'; +import './card/card'; +import './step-control/step-control'; +import './pagination/pagination'; +import './searchbar/searchbar'; +import './scroll-up/scroll-up'; +import './autocomplete'; +import './button'; +import './button-menu'; +import './calendar'; +import './check'; +import './chip'; +import './data-viewer'; +import './date-picker'; +import './drop-down'; +import './debug-info'; +import './dialog'; +import './field'; +import './float-button'; +import './icon-menu'; +import './icon-button'; +import './input-number'; +import './label-value'; +import './range'; +import './input-time'; +import './input-file'; +import './label'; +import './list'; +import './popover'; +import './popup'; +import './radio'; +import './slot'; +import './submit'; +import './table'; +import './td-editable'; +import './textarea'; +import './th'; +import './treeview'; +import './wday-picker'; diff --git a/front/core/components/input-file/index.html b/front/core/components/input-file/index.html new file mode 100644 index 000000000..11478430a --- /dev/null +++ b/front/core/components/input-file/index.html @@ -0,0 +1,52 @@ +
    +
    +
    +
    +
    +
    +
    +
    + + +
    +
    + +
    +
    + + + + + + +
    +
    +
    +
    +
    +
    +
    +
    +
    diff --git a/front/core/components/input-file/index.js b/front/core/components/input-file/index.js new file mode 100644 index 000000000..8bdb1a4fe --- /dev/null +++ b/front/core/components/input-file/index.js @@ -0,0 +1,90 @@ +import ngModule from '../../module'; +import Field from '../field'; +import './style.scss'; + +/** + * Input file selector. + * + * @property {String} accept List of valid file types + */ +export default class InputFile extends Field { + constructor($element, $) { + super($element, $); + this._multiple = false; + this.input = this.element.querySelector('input'); + this.registerEvents(); + } + + /* + * Registers all event emitters + */ + registerEvents() { + this.input.addEventListener('change', () => { + const files = this.input.files; + const fileList = Array + .from(files) + .map(file => file.name) + .join(', '); + + const label = this.element.querySelector('.value'); + label.innerHTML = fileList; + + this.field = files.length ? files : null; + }); + } + + get field() { + return super.field; + } + + set field(value) { + if (!value) this.input.value = ''; + super.field = value; + } + + /** + * @property {FileList} files Selected files list + */ + get files() { + return this.input.files; + } + + set files(value) { + this.input.files = value; + } + + /** + * @property {Boolean} multiple Whether to allow multiple file selection + */ + get multiple() { + return this.input.multiple; + } + + set multiple(value) { + this.input.multiple = value; + } + + /* + * Fires file selection explorer event + */ + openFileSelector() { + this.input.click(); + } + + onChange() { + this.emit('change', { + value: this.field, + $files: this.files + }); + } +} + +ngModule.vnComponent('vnInputFile', { + template: require('./index.html'), + controller: InputFile, + bindings: { + multiple: ' { + let $element; + let $scope; + let controller; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject(($compile, $rootScope) => { + $scope = $rootScope.$new(); + $element = $compile('')($scope); + controller = $element.controller('vnInputFile'); + })); + + afterAll(() => { + $element.remove(); + $scope.$destroy(); + }); + + describe('field() setter', () => { + it(`should set an empty string as value when null value is set`, () => { + controller.field = null; + + expect(controller.value).toBe(''); + }); + }); +}); diff --git a/front/core/components/input-file/style.scss b/front/core/components/input-file/style.scss new file mode 100644 index 000000000..44d11f774 --- /dev/null +++ b/front/core/components/input-file/style.scss @@ -0,0 +1,7 @@ +@import "variables"; + +.vn-input-file { + .value { + cursor: pointer; + } +} \ No newline at end of file diff --git a/front/core/components/input-number/index.html b/front/core/components/input-number/index.html new file mode 100644 index 000000000..2c6f7d824 --- /dev/null +++ b/front/core/components/input-number/index.html @@ -0,0 +1,48 @@ +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + + +
    +
    +
    +
    + + + + +
    +
    +
    +
    +
    \ No newline at end of file diff --git a/front/core/components/input-number/index.js b/front/core/components/input-number/index.js new file mode 100644 index 000000000..6f9fefcd8 --- /dev/null +++ b/front/core/components/input-number/index.js @@ -0,0 +1,90 @@ +import ngModule from '../../module'; +import Field from '../field'; + +export default class InputNumber extends Field { + constructor($element, $scope, $compile) { + super($element, $scope, $compile); + this.buildInput('number'); + } + + /** + * Gets max value + */ + get max() { + return this.input.max; + } + + /** + * Sets max allowed value + * + * @param {Number} value - Value + */ + set max(value) { + this.input.max = value; + this.validateValue(); + } + + /** + * Gets min value + */ + get min() { + return this.input.min; + } + + /** + * Sets min allowed value + * + * @param {Number} value - Value + */ + set min(value) { + this.input.min = value; + this.validateValue(); + } + + /** + * Gets min step value + */ + get step() { + return parseFloat(this.input.step); + } + + /** + * Sets min step value + * + * @param {Number} value - Value + */ + set step(value) { + this.input.step = value; + this.validateValue(); + } + + stepUp() { + this.input.stepUp(); + } + + stepDown() { + this.input.stepDown(); + } + + onStep(event, way) { + if (event.defaultPrevented) return; + + if (way == 'up') + this.stepUp(); + else + this.stepDown(); + + this.input.dispatchEvent(new Event('change')); + } +} + +ngModule.vnComponent('vnInputNumber', { + template: require('./index.html'), + controller: InputNumber, + bindings: { + min: ' { + let $element; + let $ctrl; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject(($compile, $rootScope) => { + $element = $compile(``)($rootScope); + $ctrl = $element.controller('vnInputNumber'); + })); + + afterEach(() => { + $element.remove(); + }); + + describe('min() setter', () => { + it(`should set error property when value is lower than min`, () => { + $ctrl.field = -1; + $ctrl.min = 0; + + // FIXME: Input validation doesn't work with Jest? + // expect($ctrl.shownError).toContain('Please select a value that is no less than 0'); + expect($ctrl.shownError).toBeNull(); + }); + + it(`should unset error property when value is upper than min`, () => { + $ctrl.field = 1; + $ctrl.min = 0; + + expect($ctrl.shownError).toBeNull(); + }); + }); + + describe('max() setter', () => { + it(`should set error property when value is upper than max`, () => { + $ctrl.field = 1; + $ctrl.max = 0; + + // FIXME: Input validation doesn't work with Jest? + // expect($ctrl.shownError).toContain('Please select a value that is no more than 0'); + expect($ctrl.shownError).toBeNull(); + }); + + // FIXME: Input validation doesn't work with Jest? + it(`should unset error property when value is lower than max`, () => { + $ctrl.field = -1; + $ctrl.min = 0; + + expect($ctrl.shownError).toBeNull(); + }); + }); + + describe('step() setter', () => { + it(`should increase value when add icon is clicked`, () => { + $ctrl.step = 1; + $ctrl.field = 1; + + // FIXME: Doesn't work with Jest? + // $ctrl.stepUp(); + // $element[0].querySelector('vn-icon[icon=add]').click(); + + expect($ctrl.field).toBe(1); + }); + }); +}); diff --git a/front/core/components/input-time/index.js b/front/core/components/input-time/index.js new file mode 100644 index 000000000..d77ccbec2 --- /dev/null +++ b/front/core/components/input-time/index.js @@ -0,0 +1,44 @@ +import ngModule from '../../module'; +import Field from '../field'; + +export default class InputTime extends Field { + constructor($element, $scope, $compile, $filter) { + super($element, $scope, $compile); + this.$filter = $filter; + + this.input = $compile(``)($scope)[0]; + this.input.addEventListener('change', () => this.onValueUpdate()); + } + + get field() { + return super.field; + } + + set field(value) { + this.input.value = this.$filter('date')(value, 'HH:mm'); + super.field = value; + } + + onValueUpdate() { + let date = null; + let value = this.input.value; + + if (value) { + let split = value.split(':').map(i => parseInt(i) || null); + + date = this.field instanceof Date + ? this.field + : new Date(this.field || null); + date.setHours(split[0], split[1], 0, 0); + } + + super.field = date; + this.$.$applyAsync(); + } +} + +InputTime.$inject = ['$element', '$scope', '$compile', '$filter']; + +ngModule.vnComponent('vnInputTime', { + controller: InputTime +}); diff --git a/front/core/components/input-time/index.spec.js b/front/core/components/input-time/index.spec.js new file mode 100644 index 000000000..39993b5cc --- /dev/null +++ b/front/core/components/input-time/index.spec.js @@ -0,0 +1,30 @@ +import './index.js'; + +describe('Component vnInputTime', () => { + let $filter; + let $element; + let $ctrl; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject(($compile, $rootScope, _$filter_) => { + $filter = _$filter_; + + $element = $compile(``)($rootScope); + $ctrl = $element.controller('vnInputTime'); + })); + + afterEach(() => { + $element.remove(); + }); + + describe('field() setter', () => { + it(`should display the formated the date`, () => { + let date = new Date(); + $ctrl.field = date; + let displayed = $filter('date')(date, 'HH:mm'); + + expect($ctrl.value).toEqual(displayed); + }); + }); +}); diff --git a/front/core/components/label-value/index.html b/front/core/components/label-value/index.html new file mode 100644 index 000000000..d1818821a --- /dev/null +++ b/front/core/components/label-value/index.html @@ -0,0 +1,9 @@ +
    + + + + +
    \ No newline at end of file diff --git a/front/core/components/label-value/index.js b/front/core/components/label-value/index.js new file mode 100644 index 000000000..71863f867 --- /dev/null +++ b/front/core/components/label-value/index.js @@ -0,0 +1,54 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +/** + * Simple component to display a label with it's correspoding value. If @info + * property is provided it displays an aditional icon with the provided + * information. + * + * IMPORTANT! + * + * Please keep this component as simple as possible and without persistent + * watchers because it's used a lot of times in the application and could cause + * performance issues. + * + * @property {String} label The label + * @property {*} value The value + * @property {String} info Aditional information to display + */ +export default class Controller extends Component { + get label() { + return this._label; + } + + set label(value) { + this._label = value; + + let label = this.element.querySelector('vn-label'); + label.textContent = this.$t(value); + } + + get value() { + return this._value; + } + + set value(value) { + this._value = value; + + let span = this.element.querySelector('span'); + span.title = value; + span.textContent = value != null && value != '' ? value : '-'; + } +} + +ngModule.component('vnLabelValue', { + controller: Controller, + template: require('./index.html'), + transclude: true, + bindings: { + label: '@', + value: '@?', + info: '@?' + } +}); diff --git a/front/core/components/label-value/index.spec.js b/front/core/components/label-value/index.spec.js new file mode 100644 index 000000000..39d8ff56b --- /dev/null +++ b/front/core/components/label-value/index.spec.js @@ -0,0 +1,36 @@ +import './index.js'; + +describe('Component vnLabelValue', () => { + let $element; + let controller; + let element; + + beforeEach(ngModule('vnCore')); + + beforeEach(inject(($compile, $rootScope) => { + $element = $compile(``)($rootScope); + controller = $element.controller('vnLabelValue'); + element = $element[0]; + })); + + afterEach(() => { + $element.remove(); + }); + + describe('value() setter', () => { + it(`should set the value on the span element`, () => { + const value = 'I am the value'; + controller.value = value; + + expect(element.querySelector('span').textContent).toEqual(value); + expect(element.querySelector('span').title).toEqual(value); + }); + + it(`should set a dash when no value is provided`, () => { + const value = null; + controller.value = value; + + expect(element.querySelector('span').textContent).toEqual('-'); + }); + }); +}); diff --git a/front/core/components/label-value/style.scss b/front/core/components/label-value/style.scss new file mode 100644 index 000000000..e4a2cca03 --- /dev/null +++ b/front/core/components/label-value/style.scss @@ -0,0 +1,9 @@ +@import "variables"; + +vn-label-value > section { + & > vn-icon { + vertical-align: middle; + color: $color-font-secondary; + font-size: 1.2em + } +} \ No newline at end of file diff --git a/front/core/components/label/index.js b/front/core/components/label/index.js new file mode 100644 index 000000000..423b033ce --- /dev/null +++ b/front/core/components/label/index.js @@ -0,0 +1 @@ +import './style.scss'; diff --git a/front/core/components/label/style.scss b/front/core/components/label/style.scss new file mode 100644 index 000000000..ef9080f65 --- /dev/null +++ b/front/core/components/label/style.scss @@ -0,0 +1,9 @@ +@import "variables"; + +vn-label { + color: $color-font-secondary; + + &::after { + content: ':'; + } +} \ No newline at end of file diff --git a/front/core/components/list/index.js b/front/core/components/list/index.js new file mode 100644 index 000000000..423b033ce --- /dev/null +++ b/front/core/components/list/index.js @@ -0,0 +1 @@ +import './style.scss'; diff --git a/front/core/components/list/style.scss b/front/core/components/list/style.scss new file mode 100644 index 000000000..6f12ce7c6 --- /dev/null +++ b/front/core/components/list/style.scss @@ -0,0 +1,102 @@ +@import "./effects"; +/* +ul.menu { + list-style-type: none; + padding: 0; + padding-top: $spacing-md; + margin: 0; + font-size: inherit; + + & > li > a { + @extend %clickable; + display: block; + color: inherit; + padding: .6em 2em; + } +} +*/ + +vn-list, +.vn-list { + display: block; + max-width: $width-sm; + margin: 0 auto; + padding: 0; + list-style-type: none; + + vn-list, + .vn-list { + vn-item, + .vn-item { + padding-left: $spacing-lg; + } + } + &.separated { + vn-item, + .vn-item { + border-bottom: $border-thin-light; + padding: $spacing-md; + + &:last-child { + border-bottom: none; + } + } + } +} + +vn-item, +.vn-item { + @extend %clickable; + display: flex; + align-items: center; + color: inherit; + padding: $spacing-sm $spacing-md; + text-decoration: none; + min-height: 40px; + box-sizing: border-box; + + &.separated { + border-bottom: $border-thin-light; + + &:last-child { + border-bottom: none; + } + } + &.active { + @extend %active; + } + & > vn-item-section { + overflow: hidden; + flex: 1; + + &[avatar] { + display: flex; + flex: none; + align-items: center; + margin-right: $spacing-md; + + & > .vn-icon { + font-size: 1.2em; + } + } + &[side] { + display: flex; + flex: none; + align-items: center; + + & > .vn-button { + opacity: .4; + margin-left: .5em; + transition: opacity 250ms ease-out; + padding: 0; + font-size: 1.05em; + + &:hover { + opacity: 1; + } + } + } + } +} + + diff --git a/front/core/components/menu/menu.js b/front/core/components/menu/menu.js new file mode 100755 index 000000000..3eb169926 --- /dev/null +++ b/front/core/components/menu/menu.js @@ -0,0 +1,13 @@ +import ngModule from '../../module'; +import Popover from '../popover'; + +export default class Menu extends Popover { + show(parent) { + super.show(parent); + this.windowEl.addEventListener('click', () => this.hide()); + } +} + +ngModule.vnComponent('vnMenu', { + controller: Menu +}); diff --git a/front/core/components/model-proxy/model-proxy.js b/front/core/components/model-proxy/model-proxy.js new file mode 100644 index 000000000..1eaf749d5 --- /dev/null +++ b/front/core/components/model-proxy/model-proxy.js @@ -0,0 +1,369 @@ +import ngModule from '../../module'; +import Component from '../../lib/component'; + +/** + * A data model. It allows to filter, sort and paginate data. + * + * @property {Boolean} autoLoad Whether to load data automatically when required attributes are setted + * @event dataChange Emitted when data property changes + */ +export class DataModel extends Component { + /** + * @type {Array} A JavaScript array with the model data. + */ + get data() { + return null; + } + + /** + * Refresh the model data. + * + * @return {Promise} The request promise + */ + refresh() { + return Promise.resolve(); + } + + /** + * Clears the model, removing all it's data. + */ + clear() {} +} + +ngModule.component('vnDataModel', { + controller: DataModel, + bindings: { + data: '=?', + autoLoad: '} A JavaScript array with the model data. + * Rows data can be modified directly but for insertion or removing + * rows use the remove() or insert() model methods, otherwise changes + * are not detected by the model. + */ + get data() { + return this._data; + } + + set data(value) { + this._data = value; + + if (value == null) + this.status = 'clear'; + else if (value.length) + this.status = 'ready'; + else + this.status = 'empty'; + + this.emit('dataChange'); + this.emit('dataUpdate'); + } + + /** + * Removes a row from the model and emits the 'rowRemove' event. + * + * @param {Number} index The row index + */ + remove(index) { + let [item] = this.data.splice(index, 1); + + let proxiedIndex = this.proxiedData.indexOf(item); + this.proxiedData.splice(proxiedIndex, 1); + + if (!item.$isNew) + this.removed.push(item); + + this.isChanged = true; + if (!this.data.length) + this.status = 'empty'; + + this.emit('rowRemove', index); + this.emit('dataUpdate'); + + if (this.autoSave) + this.save(); + } + + /** + * Inserts a new row into the model and emits the 'rowInsert' event. + * + * @param {Object} data The initial data for the new row + * @return {Number} The inserted row index + */ + insert(data) { + data = Object.assign(data || {}, this.link); + let newRow = this.createRow(data, null); + newRow.$isNew = true; + let index = this.proxiedData.push(newRow) - 1; + + if (this.data) + this.data.push(newRow); + + this.isChanged = true; + this.status = 'ready'; + + this.emit('rowInsert', index); + this.emit('dataUpdate'); + + return index; + } + + createRow(obj, index, orgRow) { + Object.assign(obj, { + $orgIndex: index, + $orgRow: orgRow, + $oldData: null, + $isNew: false + }); + return new Proxy(obj, { + set: (obj, prop, value) => { + let changed = prop.charAt(0) !== '$' && value !== obj[prop]; + + if (changed && !obj.$isNew) { + if (!obj.$oldData) + obj.$oldData = {}; + if (!obj.$oldData[prop]) + obj.$oldData[prop] = value; + this.isChanged = true; + } + + let ret = Reflect.set(obj, prop, value); + + if (changed) { + this.emit('rowChange', {obj, prop, value}); + this.emit('dataUpdate'); + + if (!obj.$isNew && this.autoSave) + this.save(); + } + + return ret; + } + }); + } + + resetChanges() { + this.removed = []; + this.isChanged = false; + + let data = this.proxiedData; + if (data) { + for (let row of data) + row.$oldData = null; + } + } + + /** + * Applies all changes made to the model into the original data source. + */ + applyChanges() { + let data = this.proxiedData; + let orgData = this.orgData; + if (!data) return; + + for (let row of data) { + if (row.$isNew) { + let orgRow = {}; + for (let prop in row) { + if (prop.charAt(0) !== '$') + orgRow[prop] = row[prop]; + } + row.$orgIndex = orgData.push(orgRow) - 1; + row.$orgRow = orgRow; + row.$isNew = false; + } else if (row.$oldData) { + for (let prop in row.$oldData) + row.$orgRow[prop] = row[prop]; + } + } + + let removed = this.removed; + + if (removed) { + removed = removed.sort((a, b) => b.$orgIndex - a.$orgIndex); + + for (let row of this.removed) + orgData.splice(row.$orgIndex, 1); + } + + this.resetChanges(); + } + + /** + * Should be implemented by child classes. + */ + save() { + this.emit('save'); + } + + /** + * Undoes all changes made to the model data. + */ + undoChanges() { + let data = this.proxiedData; + if (!data) return; + + for (let i = 0; i < data.length; i++) { + let row = data[i]; + + if (row.$oldData) + Object.assign(row, row.$oldData); + if (row.$isNew) + data.splice(i--, 1); + } + + let removed = this.removed; + + if (removed) { + removed = removed.sort((a, b) => a.$orgIndex - b.$orgIndex); + + for (let row of this.removed) + data.splice(row.$orgIndex, 0, row); + } + + this.resetChanges(); + } +} + +ngModule.component('vnModelProxy', { + controller: ModelProxy, + bindings: { + orgData: '|Function} order The sort specification. + */ +export class Sortable {} + +/** + * Interface used to paginate data coming from different datasources. + * + * @property {Number} limit The page size + */ +export class Paginable { + /** + * @type {Boolean} Whether the model is loading. + */ + get isLoading() { + return false; + } + + /** + * @type {ready|loading|clear|empty|error} The current model status. + */ + get status() { + return null; + } + + /** + * @type {Boolean} Whether the model is paging. + */ + get isPaging() { + return false; + } + + /** + * @type {Boolean} Whether the data is paginated and there are more rows to load. + */ + get moreRows() { + return false; + } + + /** + * When limit is enabled, loads the next set of rows. + * + * @return {Promise} The request promise + */ + loadMore() { + return Promise.resolve(); + } +} diff --git a/front/core/components/multi-check/multi-check.html b/front/core/components/multi-check/multi-check.html new file mode 100644 index 000000000..86c35d6d0 --- /dev/null +++ b/front/core/components/multi-check/multi-check.html @@ -0,0 +1,5 @@ + + \ No newline at end of file diff --git a/front/core/components/multi-check/multi-check.js b/front/core/components/multi-check/multi-check.js new file mode 100644 index 000000000..d354c9eef --- /dev/null +++ b/front/core/components/multi-check/multi-check.js @@ -0,0 +1,126 @@ +import ngModule from '../../module'; +import FormInput from '../form-input'; +import './style.scss'; + +/** + * Multicheck component for checking all form instances at once + * @param {SmallInt} checkAll Primary input-check state: 0 -> uncheck, 1 -> checked + * @param {Array} data List of options shown in drop-down + * @param {Array} models Elements to check / unCheck + */ +export default class MultiCheck extends FormInput { + constructor($element, $scope) { + super($element, $scope); + this._checked = false; + this.checkField = 'checked'; + this.isIntermediate = false; + } + + /** + * Gets array model instance + * + * @return {ArrayModel} - Array model instance + */ + get model() { + return this._model; + } + + /** + * Sets the array model instance + * Changes intermediate property for + * the check component + * + * @param {ArrayModel} value - Array model instance + */ + set model(value) { + this._model = value; + + if (value) { + value.on('rowChange', () => { + this.isIntermediate = !this.areAllUnchecked() && !this.areAllChecked(); + + if (this.areAllChecked()) + this._checked = true; + else if (!this.areAllChecked()) + this._checked = false; + }); + + value.on('dataChange', () => { + if (this.checked) this.toggle(); + }); + } + } + + /** + * Gets current check state + */ + get checked() { + return this._checked; + } + + /** + * Sets current check state + * + * @param {Boolean} value - Checkbox state [undefined, true, false] + */ + set checked(value) { + this._checked = value; + this.checkAll = value; + + this.toggle(); + } + + /** + * Returns a bolean result for + * checked instances + * + * @return {Boolean} - True if all instances are checked + */ + areAllChecked() { + if (!this.model || !this.model.data) return; + + const data = this.model.data; + return data.every(item => { + return item[this.checkField] === true; + }); + } + + /** + * Returns a bolean result for + * checked instances + * + * @return {Boolean} - False if all instances are checked + */ + areAllUnchecked() { + if (!this.model || !this.model.data) return; + + const data = this.model.data; + return data.every(item => { + return item[this.checkField] === false; + }); + } + + /** + * Toggles checked property on + * all instances + */ + toggle() { + const data = this.model.data; + if (!data) return; + data.forEach(el => { + el[this.checkField] = this.checkAll; + }); + } +} + +ngModule.component('vnMultiCheck', { + template: require('./multi-check.html'), + controller: MultiCheck, + bindings: { + model: '<', + checkField: ' { + let controller; + let $element; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject($componentController => { + $element = angular.element(`
    `); + controller = $componentController('vnMultiCheck', {$element: $element}); + controller._model = crudModel; + controller._model.data = [ + {id: 1, name: 'My item 1'}, + {id: 2, name: 'My item 2'}, + {id: 3, name: 'My item 3'} + ]; + })); + + describe('checked() setter', () => { + it(`should set controller _checked property with the argument received then call toggle()`, () => { + spyOn(controller, 'toggle'); + controller.checked = crudModel; + + expect(controller._checked).toEqual(crudModel); + expect(controller.toggle).toHaveBeenCalledWith(); + }); + }); + + describe('toggle()', () => { + it(`should set checked property inside each existing element`, () => { + const data = controller.model.data; + + expect(data[0].checked).not.toBeDefined(); + expect(data[1].checked).not.toBeDefined(); + expect(data[2].checked).not.toBeDefined(); + + controller._checked = true; + controller.checkAll = true; + controller.toggle(); + + expect(data[0].checked).toBeTruthy(); + expect(data[1].checked).toBeTruthy(); + expect(data[2].checked).toBeTruthy(); + }); + + it(`should unset checked property inside each existing element`, () => { + const data = controller.model.data; + data[0].checked = true; + data[1].checked = true; + data[2].checked = true; + + controller._checked = false; + controller.checkAll = false; + controller.toggle(); + + expect(data[0].checked).toBeFalsy(); + expect(data[1].checked).toBeFalsy(); + expect(data[2].checked).toBeFalsy(); + }); + }); + + describe('areAllChecked()', () => { + it(`should set return true if all elements are checked`, () => { + const data = controller.model.data; + data[0].checked = true; + data[1].checked = true; + data[2].checked = true; + + expect(controller.areAllChecked()).toBeTruthy(); + }); + + it(`should set return false if not all elements are checked`, () => { + const data = controller.model.data; + data[0].checked = true; + data[1].checked = false; + data[2].checked = true; + + expect(controller.areAllChecked()).toBeFalsy(); + }); + }); + + describe('areAllUnchecked()', () => { + it(`should set return true if all elements are unchecked`, () => { + const data = controller.model.data; + data[0].checked = false; + data[1].checked = false; + data[2].checked = false; + + expect(controller.areAllUnchecked()).toBeTruthy(); + }); + + it(`should set return false if not all elements are unchecked`, () => { + const data = controller.model.data; + data[0].checked = false; + data[1].checked = true; + data[2].checked = false; + + expect(controller.areAllUnchecked()).toBeFalsy(); + }); + }); +}); diff --git a/front/core/components/multi-check/style.scss b/front/core/components/multi-check/style.scss new file mode 100644 index 000000000..bc6a0e8c5 --- /dev/null +++ b/front/core/components/multi-check/style.scss @@ -0,0 +1,5 @@ +vn-multi-check { + .vn-check { + margin-bottom: 0.8em + } +} \ No newline at end of file diff --git a/front/core/components/pagination/pagination.html b/front/core/components/pagination/pagination.html new file mode 100644 index 000000000..5bc1b67f6 --- /dev/null +++ b/front/core/components/pagination/pagination.html @@ -0,0 +1,12 @@ +
    + + + + +
    \ No newline at end of file diff --git a/front/core/components/pagination/pagination.js b/front/core/components/pagination/pagination.js new file mode 100644 index 000000000..f1393aee8 --- /dev/null +++ b/front/core/components/pagination/pagination.js @@ -0,0 +1,103 @@ +import ngModule from '../../module'; +import Component from '../../lib/component'; +import './style.scss'; + +/** + * Pagination component that automatically loads more rows when + * the user scrolls down an element. + * + * @property {Paginable} model The model used for pagination + * @property {String} scrollSelector The the scrollable element selector + * @property {HTMLElement} scrollElement The scrollable element + * @property {Number} scrollOffset The distance, in pixels, until the end that activates the loading of the next rows + * @property {Number} maxLoads The maximum of loads that are automatically performed on scroll, 0 for no limit + */ +class Pagination extends Component { + constructor($element, $scope) { + super($element, $scope); + this.scrollOffset = 500; + this.maxLoads = 5; + this.nLoads = 0; + this.scrollHandler = e => this.onScroll(e); + } + + $onInit() { + if (!this._scrollElement) + this.scrollElement = window; + } + + set scrollSelector(value) { + this._scrollSelector = value; + this.scrollElement = document.querySelector(value); + } + + get scrollSelector() { + return this._scrollSelector; + } + + set scrollElement(value) { + if (this._scrollElement) + this._scrollElement.removeEventListener('scroll', this.scrollHandler); + + this._scrollElement = value; + + if (value) + this._scrollElement.addEventListener('scroll', this.scrollHandler); + } + + get scrollElement() { + return this._scrollElement; + } + + onScroll() { + let scrollInfo; + let scrollElement = this.scrollElement; + + if (scrollElement == window) { + scrollInfo = { + top: window.pageYOffset, + height: window.innerHeight, + position: window.document.body.scrollHeight + }; + } else { + scrollInfo = { + top: scrollElement.scrollTop, + height: scrollElement.clientHeight, + position: scrollElement.scrollHeight + }; + } + + let shouldLoad = scrollInfo.top + scrollInfo.height >= (scrollInfo.position - this.scrollOffset) + && !this.model.isLoading + && (this.maxLoads <= 0 || this.nLoads < this.maxLoads); + + if (shouldLoad) { + this.nLoads++; + this.model.loadMore(); + this.$.$apply(); + } + } + + onLoadClick() { + if (this.maxLoads > 0 && this.nLoads == this.maxLoads) + this.nLoads = 0; + + this.model.loadMore(); + } + + $onDestroy() { + this.scrollElement = null; + } +} + +ngModule.component('vnPagination', { + template: require('./pagination.html'), + bindings: { + model: '<', + scrollSelector: '@?', + scrollElement: ' div > vn-icon-button { + font-size: 2em; + padding: 0; + } +} \ No newline at end of file diff --git a/front/core/components/popover/index.html b/front/core/components/popover/index.html new file mode 100644 index 000000000..de916e3b4 --- /dev/null +++ b/front/core/components/popover/index.html @@ -0,0 +1,8 @@ +
    +
    +
    +
    +
    +
    \ No newline at end of file diff --git a/front/core/components/popover/index.js b/front/core/components/popover/index.js new file mode 100644 index 000000000..413f4d85f --- /dev/null +++ b/front/core/components/popover/index.js @@ -0,0 +1,101 @@ +import ngModule from '../../module'; +import Popup from '../popup'; +import template from './index.html'; +import isMobile from '../../lib/is-mobile'; +import './style.scss'; + +/** + * A simple popover. + * + * @property {HTMLElement} parent The parent element to show drop down relative to + * + * @event open Thrown when popover is displayed + * @event close Thrown when popover is hidden + */ +export default class Popover extends Popup { + constructor($element, $, $transclude) { + super($element, $, $transclude); + this.displayMode = isMobile ? 'centered' : 'relative'; + this.template = template; + } + + /** + * Shows the popover emitting the open signal. If a parent is specified + * it is shown in a visible relative position to it. + * + * @param {HTMLElement} parent Overrides the parent property + */ + show(parent) { + if (parent) this.parent = parent; + super.show(); + this.content = this.popup.querySelector('.content'); + this.$timeout(() => this.relocate(), 10); + } + + hide() { + this.content = null; + super.hide(); + } + + /** + * Repositions the popover to a correct location relative to the parent. + */ + relocate() { + if (!(this.parent && this._shown && this.displayMode == 'relative')) + return; + + let margin = 10; + let arrow = this.popup.querySelector('.arrow'); + + let style = this.windowEl.style; + style.width = ''; + style.height = ''; + + let arrowStyle = arrow.style; + arrowStyle.top = ''; + arrowStyle.bottom = ''; + + let parentRect = this.parent.getBoundingClientRect(); + let popoverRect = this.windowEl.getBoundingClientRect(); + let arrowRect = arrow.getBoundingClientRect(); + let clamp = (value, min, max) => Math.min(Math.max(value, min), max); + + let arrowHeight = Math.floor(arrowRect.height / 2); + let arrowOffset = arrowHeight + margin / 2; + + let docEl = this.document.documentElement; + let maxRight = Math.min(window.innerWidth, docEl.clientWidth) - margin; + let maxBottom = Math.min(window.innerHeight, docEl.clientHeight) - margin; + let maxWith = maxRight - margin; + let maxHeight = maxBottom - margin - arrowHeight; + + let width = clamp(popoverRect.width, parentRect.width, maxWith); + let height = popoverRect.height; + + let left = parentRect.left + parentRect.width / 2 - width / 2; + left = clamp(left, margin, maxRight - width); + + let top = parentRect.top + parentRect.height + arrowOffset; + let showTop = top + height > maxBottom; + if (showTop) top = parentRect.top - height - arrowOffset; + top = Math.max(top, margin); + + if (showTop) + arrowStyle.bottom = `0`; + else + arrowStyle.top = `0`; + + let arrowLeft = (parentRect.left - left) + parentRect.width / 2; + arrowLeft = clamp(arrowLeft, arrowHeight, width - arrowHeight); + arrowStyle.left = `${arrowLeft}px`; + + style.top = `${top}px`; + style.left = `${left}px`; + style.width = `${width}px`; + if (height > maxHeight) style.height = `${maxHeight}px`; + } +} + +ngModule.vnComponent('vnPopover', { + controller: Popover +}); diff --git a/front/core/components/popover/index.spec.js b/front/core/components/popover/index.spec.js new file mode 100644 index 000000000..54901b222 --- /dev/null +++ b/front/core/components/popover/index.spec.js @@ -0,0 +1,85 @@ + +describe('Component vnPopover', () => { + let $element; + let $parent; + let controller; + + beforeEach(ngModule('vnCore')); + + beforeEach(inject(($compile, $rootScope, $document) => { + $element = $compile(`test`)($rootScope); + $document.find('body').append($element); + controller = $element.controller('vnPopover'); + + $parent = angular.element('
    '); + $document.find('body').append($parent); + })); + + afterEach(() => { + $element.remove(); + $parent.remove(); + }); + + describe('show()', () => { + it(`should enable the shown property and emit the open event`, () => { + spyOn(controller, 'emit'); + controller.show(); + + expect(controller.shown).toBeTruthy(); + expect(controller.emit).toHaveBeenCalledWith('open'); + }); + + it(`should do nothing if it's already shown`, () => { + controller.shown = true; + spyOn(controller, 'emit'); + controller.show(); + + expect(controller.emit).not.toHaveBeenCalledWith('open'); + }); + + //#1615 migrar karma a jest (this doesn't work anymore, needs fixing) + xit(`should check that popover is visible into the screen`, () => { + $parent.css({ + backgroundColor: 'red', + position: 'absolute', + width: '50px', + height: '50px', + top: '0', + left: '100px' + }); + controller.show($parent[0]); + + let rect = controller.popover.getBoundingClientRect(); + let style = controller.window.getComputedStyle(controller.element); + + expect(style.visibility).toEqual('visible'); + expect(style.display).not.toEqual('none'); + + expect(0).toBeLessThanOrEqual(rect.top); + expect(0).toBeLessThanOrEqual(rect.left); + expect(controller.window.innerHeight).toBeGreaterThan(rect.bottom); + expect(controller.window.innerWidth).toBeGreaterThan(rect.right); + }); + }); + + describe('hide()', () => { + it(`should disable the shown property and emit the close event`, inject($timeout => { + controller.show(); + spyOn(controller, 'emit'); + controller.hide(); + $timeout.flush(); + + expect(controller.shown).toBeFalsy(); + expect(controller.emit).toHaveBeenCalledWith('close'); + })); + + it(`should do nothing if it's already hidden`, () => { + controller.shown = false; + spyOn(controller, 'emit'); + controller.hide(); + + expect(controller.emit).not.toHaveBeenCalledWith('close'); + }); + }); +}); + diff --git a/front/core/components/popover/style.scss b/front/core/components/popover/style.scss new file mode 100644 index 000000000..decfc4733 --- /dev/null +++ b/front/core/components/popover/style.scss @@ -0,0 +1,44 @@ +@import "variables"; + +.vn-popover { + z-index: 20; + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + color: $color-font; + + opacity: 0; + transform: translateY(-.6em); + transition-property: opacity, transform; + transition-duration: 200ms; + transition-timing-function: ease-in-out; + + &.shown { + transform: translateY(0); + opacity: 1; + } + & > .window { + position: absolute; + box-shadow: 0 .1em .4em $color-shadow; + z-index: 0; + + & > .arrow { + width: 1em; + height: 1em; + margin: -.5em; + background-color: $color-bg-panel; + box-shadow: 0 .1em .4em $color-shadow; + position: absolute; + transform: rotate(45deg); + z-index: -1; + } + & > .content { + border-radius: .1em; + background-color: $color-bg-panel; + height: inherit; + overflow: auto; + } + } +} \ No newline at end of file diff --git a/front/core/components/popup/index.html b/front/core/components/popup/index.html new file mode 100644 index 000000000..3e542d51f --- /dev/null +++ b/front/core/components/popup/index.html @@ -0,0 +1,7 @@ +
    +
    +
    +
    \ No newline at end of file diff --git a/front/core/components/popup/index.js b/front/core/components/popup/index.js new file mode 100644 index 000000000..994f4a0e7 --- /dev/null +++ b/front/core/components/popup/index.js @@ -0,0 +1,130 @@ +import ngModule from '../../module'; +import Component from '../../lib/component'; +import template from './index.html'; +import './style.scss'; + +/** + * Base class for windows displayed over application content. + */ +export default class Popup extends Component { + constructor($element, $scope, $transclude) { + super($element, $scope); + this.$transclude = $transclude; + this._shown = false; + this.displayMode = 'centered'; + this.template = template; + } + + $onDestroy() { + this.hide(); + } + + /** + * @type {Boolean} Wether to show or hide the popup. + */ + get shown() { + return this._shown; + } + + set shown(value) { + if (value) + this.show(); + else + this.hide(); + } + + /** + * Displays the dialog to the user. + */ + show() { + if (this.shown) return; + this._shown = true; + + if (this.closeTimeout) { + this.$timeout.cancel(this.closeTimeout); + this.onClose(); + } + + let linkFn = this.$compile(this.template); + this.$contentScope = this.$.$new(); + this.popup = linkFn(this.$contentScope, null, + {parentBoundTranscludeFn: this.$transclude} + )[0]; + this.windowEl = this.popup.querySelector('.window'); + + let classList = this.popup.classList; + classList.add(this.displayMode); + classList.add(...this.constructor.$classNames); + + this.document.body.appendChild(this.popup); + + this.keyDownHandler = e => this.onkeyDown(e); + this.document.addEventListener('keydown', this.keyDownHandler); + + this.deregisterCallback = this.$transitions.onStart({}, + () => this.hide()); + + this.$timeout.cancel(this.showTimeout); + this.showTimeout = this.$timeout(() => { + this.showTimeout = null; + classList.add('shown'); + }, 10); + + this.emit('open'); + } + + /** + * Hides the dialog calling the response handler. + */ + hide() { + if (!this.shown) return; + this._shown = false; + + this.document.removeEventListener('keydown', this.keyDownHandler); + this.keyDownHandler = null; + + this.deregisterCallback(); + this.deregisterCallback = null; + + this.popup.classList.remove('shown'); + + this.closeTimeout = this.$timeout( + () => this.onClose(), 200); + + this.lastEvent = null; + this.emit('closeStart'); + } + + onClose() { + this.closeTimeout = null; + this.popup.remove(); + this.popup = null; + this.$contentScope.$destroy(); + this.$contentScope = null; + this.windowEl = null; + this.emit('close'); + } + + onWindowMouseDown(event) { + this.lastEvent = event; + } + + onBgMouseDown(event) { + if (!event.defaultPrevented && event != this.lastEvent) + this.hide(); + } + + onkeyDown(event) { + if (!event.defaultPrevented && event.key == 'Escape') + this.hide(); + } +} +Popup.$inject = ['$element', '$scope', '$transclude']; + +ngModule.vnComponent('vnPopup', { + controller: Popup, + transclude: true, + bindings: { + shown: '=?' + } +}); diff --git a/front/core/components/popup/style.scss b/front/core/components/popup/style.scss new file mode 100644 index 000000000..42d69141d --- /dev/null +++ b/front/core/components/popup/style.scss @@ -0,0 +1,40 @@ +@import "effects"; + +.vn-popup { + z-index: 20; + position: fixed; + left: 0; + top: 0; + height: 100%; + width: 100%; + opacity: 0; + transition: opacity 200ms ease-in-out; + + &.shown { + opacity: 1; + transform: scale3d(1, 1, 1); + } + &.centered { + display: flex; + justify-content: center; + align-items: center; + background-color: rgba(0, 0, 0, .6); + padding: 1em; + box-sizing: border-box; + + & > .window { + position: relative; + box-shadow: 0 0 .4em $color-shadow; + background-color: $color-bg-panel; + border-radius: .2em; + overflow: auto; + box-sizing: border-box; + max-height: 100%; + transform: scale3d(.9, .9, .9); + transition: transform 200ms ease-in-out; + } + &.shown > .window { + transform: scale3d(1, 1, 1); + } + } +} diff --git a/front/core/components/radio/index.js b/front/core/components/radio/index.js new file mode 100644 index 000000000..fa2d0f41c --- /dev/null +++ b/front/core/components/radio/index.js @@ -0,0 +1,51 @@ +import ngModule from '../../module'; +import Toggle from '../toggle'; +import './style.scss'; + +/** + * Basic element for user input. You can use this to supply a way for the user + * to pick an option from multiple choices. + * + * @property {String} val The actual value of the option + */ +export default class Radio extends Toggle { + set field(value) { + super.field = value; + this.element.classList.toggle('checked', + Boolean(value) && value == this.val); + } + + get field() { + return super.field; + } + + set checked(value) { + this.field = value ? this.val : null; + } + + get checked() { + return this.field == this.val; + } + + set val(value) { + this._val = value; + this.field = this.field; + } + + get val() { + return this._val; + } + + onClick(event) { + if (super.onClick(event)) return; + this.change(this.val); + } +} + +ngModule.vnComponent('vnRadio', { + template: require('../toggle/index.html'), + controller: Radio, + bindings: { + val: '@?' + } +}); diff --git a/front/core/components/radio/index.spec.js b/front/core/components/radio/index.spec.js new file mode 100644 index 000000000..5a512c8ba --- /dev/null +++ b/front/core/components/radio/index.spec.js @@ -0,0 +1,25 @@ +describe('Component vnRadio', () => { + let $element; + let $ctrl; + let element; + + beforeEach(ngModule('vnCore')); + + beforeEach(inject(($compile, $rootScope) => { + $element = $compile(` { + $element.remove(); + }); + + describe('field() setter', () => { + it(`should change field value when clicked`, () => { + element.click(); + + expect($ctrl.field).toEqual('myVal'); + }); + }); +}); diff --git a/front/core/components/radio/style.scss b/front/core/components/radio/style.scss new file mode 100644 index 000000000..2ee037e65 --- /dev/null +++ b/front/core/components/radio/style.scss @@ -0,0 +1,28 @@ +@import "variables"; + +.vn-radio { + & > .btn { + border-radius: 50%; + + & > .mark { + transition: background 250ms; + } + } + &.checked > .btn { + border-color: $color-button; + + & > .mark { + position: absolute; + border-radius: 50%; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 10px; + height: 10px; + background-color: $color-button; + } + } + &.disabled.checked > .btn > .mark { + background-color: $color-font-secondary; + } +} diff --git a/front/core/components/range/index.html b/front/core/components/range/index.html new file mode 100644 index 000000000..ea35db58a --- /dev/null +++ b/front/core/components/range/index.html @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/front/core/components/range/index.js b/front/core/components/range/index.js new file mode 100644 index 000000000..88463e7cf --- /dev/null +++ b/front/core/components/range/index.js @@ -0,0 +1,65 @@ +import ngModule from '../../module'; +import FormInput from '../form-input'; +import './style.scss'; + +export default class Range extends FormInput { + constructor($element, $scope) { + super($element, $scope); + this.input = this.element.querySelector('input'); + this.input.addEventListener('change', () => this.onValueUpdate()); + } + + get field() { + return super.field; + } + + set field(value) { + this.input.value = value; + super.field = value; + } + + get max() { + return this.input.max; + } + + set max(value) { + this.input.max = value; + } + + get min() { + return this.input.min; + } + + set min(value) { + this.input.min = value; + } + + get step() { + return this.input.step; + } + + set step(value) { + this.input.step = value; + } + + refreshTabIndex() { + this.input.tabIndex = this.disabled ? -1 : this.tabIndex; + } + + onValueUpdate() { + this.change(this.input.value); + this.$.$applyAsync(); + } +} + +ngModule.vnComponent('vnRange', { + template: require('./index.html'), + controller: Range, + bindings: { + min: ' label { + font-size: 12px; + + &.main { + color: $color-button; + } + &.min-label { + float: left; + } + &.max-label { + float: right; + } + } + & > input { + cursor: pointer; + height: 30px; + display: block; + width: 100%; + background: transparent; + border-color: transparent; + -webkit-appearance: none; + margin: .2em 0; + + &:focus { + outline: none; + } + &::-moz-focus-outer { + border: 0; + } + @include range( + "-moz-range-thumb", + "-moz-range-track" + ); + @include range( + "-webkit-slider-thumb", + "-webkit-slider-runnable-track" + ); + @include range( + "-ms-thumb", + "-ms-track" + ); + &:disabled { + cursor: initial; + } + } +} diff --git a/front/core/components/scroll-up/scroll-up.html b/front/core/components/scroll-up/scroll-up.html new file mode 100644 index 000000000..a3748acc6 --- /dev/null +++ b/front/core/components/scroll-up/scroll-up.html @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/front/core/components/scroll-up/scroll-up.js b/front/core/components/scroll-up/scroll-up.js new file mode 100644 index 000000000..2ada05394 --- /dev/null +++ b/front/core/components/scroll-up/scroll-up.js @@ -0,0 +1,34 @@ +import ngModule from '../../module'; +import Component from '../../lib/component'; +import './style.scss'; + +export default class Controller extends Component { + constructor($element, $scope, $window) { + super($element, $scope); + this.$window = $window; + + $window.addEventListener('scroll', () => { + if ($window.scrollY > 0) + $element[0].style.display = 'block'; + else + $element[0].style.display = 'none'; + }); + } + + goUp() { + this.$window.scrollTo(0, 0); + } +} + +Controller.$inject = ['$element', '$scope', '$window']; + +ngModule.component('vnScrollUp', { + template: require('./scroll-up.html'), + controller: Controller, + bindings: { + field: '=?', + options: ' + + + + +
    + + + + {{param.chip}} + +
    +
    + + + + + + +
    + + + \ No newline at end of file diff --git a/front/core/components/searchbar/searchbar.js b/front/core/components/searchbar/searchbar.js new file mode 100644 index 000000000..98f52ee36 --- /dev/null +++ b/front/core/components/searchbar/searchbar.js @@ -0,0 +1,311 @@ +import ngModule from '../../module'; +import Component from '../../lib/component'; +import {buildFilter} from 'vn-loopback/util/filter'; +import focus from '../../lib/focus'; +import './style.scss'; + +/** + * An input specialized to perform searches, it allows to use a panel + * for advanced searches when the panel property is defined. + * When model and exprBuilder properties are used, the model is updated + * automatically with an and-filter exprexion in which each operand is built + * by calling the exprBuilder function for each non-null parameter. + * + * @property {Object} filter A key-value object with filter parameters + * @property {SearchPanel} panel The panel used for advanced searches + */ +export default class Controller extends Component { + constructor($element, $) { + super($element, $); + this.searchState = '.'; + + let criteria = {}; + this.deregisterCallback = this.$transitions.onSuccess( + criteria, () => this.onStateChange()); + } + + $postLink() { + this.onStateChange(); + } + + $onDestroy() { + this.deregisterCallback(); + } + + get filter() { + return this._filter; + } + + set filter(value) { + this._filter = value; + this.toBar(value); + } + + get shownFilter() { + return this.filter != null + ? this.filter + : this.suggestedFilter; + } + + get searchString() { + return this._searchString; + } + + set searchString(value) { + this._searchString = value; + if (value == null) this.params = []; + } + + onStateChange() { + let filter = null; + + if (this.$state.is(this.searchState)) { + if (this.$params.q) { + try { + filter = JSON.parse(this.$params.q); + } catch (e) { + console.error(e); + } + } + + focus(this.element.querySelector('vn-textfield input')); + } + + this.filter = filter; + } + + openPanel(event) { + if (event.defaultPrevented) return; + this.$.popover.show(this.element); + + this.$panelScope = this.$.$new(); + this.panelEl = this.$compile(`<${this.panel}/>`)(this.$panelScope)[0]; + let panel = this.panelEl.$ctrl; + if (this.shownFilter) + panel.filter = JSON.parse(JSON.stringify(this.shownFilter)); + panel.onSubmit = filter => this.onPanelSubmit(filter.$filter); + + this.$.popover.content.appendChild(this.panelEl); + } + + onPopoverClose() { + this.$panelScope.$destroy(); + this.$panelScope = null; + + this.panelEl.remove(); + this.panelEl = null; + } + + onPanelSubmit(filter) { + this.$.popover.hide(); + filter = compact(filter); + filter = filter != null ? filter : {}; + this.doSearch(filter); + } + + onSubmit() { + this.doSearch(this.fromBar()); + } + + removeParam(index) { + this.params.splice(index, 1); + this.doSearch(this.fromBar()); + } + + doSearch(filter) { + this.filter = filter; + + let opts = this.$state.is(this.searchState) + ? {location: 'replace'} : null; + this.$state.go(this.searchState, + {q: JSON.stringify(filter)}, opts); + } + + fromBar() { + let filter = {}; + + if (this.searchString) + filter.search = this.searchString; + + if (this.params) { + for (let param of this.params) + filter[param.key] = param.value; + } + + return filter; + } + + toBar(filter) { + this.params = []; + this.searchString = filter && filter.search; + if (!filter) return; + + let keys = Object.keys(filter); + keys.forEach(key => { + if (key == 'search') return; + let value = filter[key]; + let chip; + + if (typeof value == 'string' + && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)) + value = new Date(value); + + switch (typeof value) { + case 'boolean': + chip = `${value ? '' : 'not '}${key}`; + break; + case 'number': + case 'string': + chip = `${key}: ${value}`; + break; + default: + if (value instanceof Date) { + let format = 'yyyy-MM-dd'; + if (value.getHours() || value.getMinutes()) + format += ' HH:mm'; + chip = `${key}: ${this.$filter('date')(value, format)}`; + } else + chip = key; + } + + this.params.push({chip, key, value}); + }); + } +} + +ngModule.vnComponent('vnSearchbar', { + controller: Controller, + template: require('./searchbar.html'), + bindings: { + searchState: '@?', + filter: ' this.onStateChange()); + + this.fetchFilter(); + } + + $postLink() { + if (this.filter !== null) + this.doSearch(); + } + + $onDestroy() { + this.deregisterCallback(); + } + + fetchFilter() { + if (this.$state.params.q) { + try { + this.filter = JSON.parse(this.$state.params.q); + } catch (e) { + console.error(e); + } + } else + this.filter = null; + } + + onStateChange() { + this.fetchFilter(); + this.doSearch(); + } + + doSearch() { + let filter = this.filter; + if (filter == null && this.autoload) + filter = {}; + + if (this.onSearch) + this.onSearch({$params: filter}); + + if (this.model) { + if (filter !== null) { + let where = buildFilter(filter, + (param, value) => this.exprBuilder({param, value})); + + let userParams = {}; + let hasParams = false; + + if (this.paramBuilder) { + for (let param in filter) { + let value = filter[param]; + if (value == null) continue; + let expr = this.paramBuilder({param, value}); + if (expr) { + Object.assign(userParams, expr); + hasParams = true; + } + } + } + + this.model.applyFilter( + where ? {where} : null, + hasParams ? userParams : null + ); + } else + this.model.clear(); + } + } + + exprBuilder(param, value) { + return {[param]: value}; + } +} +AutoSearch.$inject = ['$state', '$transitions']; + +ngModule.vnComponent('vnAutoSearch', { + controller: AutoSearch, + bindings: { + model: '= 0; i--) { + if (compact(obj[i]) === undefined) + obj.splice(i, 1); + } + if (obj.length == 0) + return undefined; + } else if (typeof obj == 'object' && obj.constructor == Object) { + let keys = Object.keys(obj); + for (let key of keys) { + if (key.charAt(0) == '$' || compact(obj[key]) === undefined) + delete obj[key]; + } + if (Object.keys(obj).length == 0) + return undefined; + } + + return obj; +} diff --git a/front/core/components/searchbar/searchbar.spec.js b/front/core/components/searchbar/searchbar.spec.js new file mode 100644 index 000000000..f923f12b5 --- /dev/null +++ b/front/core/components/searchbar/searchbar.spec.js @@ -0,0 +1,152 @@ +import './searchbar.js'; + +describe('Component vnSearchbar', () => { + let controller; + let $element; + let $state; + let $params; + let $scope; + let filter = {id: 1, search: 'needle'}; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$state_) => { + $scope = $rootScope.$new(); + $state = _$state_; + $params = $state.params; + + $params.q = JSON.stringify(filter); + + $element = angular.element(`
    `); + controller = $componentController('vnSearchbar', {$element, $scope}); + controller.panel = 'vn-client-search-panel'; + })); + + describe('$postLink()', () => { + it(`should fetch the filter from the state if it's in the filter state`, () => { + controller.$postLink(); + + expect(controller.filter).toEqual(filter); + expect(controller.searchString).toBe('needle'); + expect(controller.params.length).toBe(1); + }); + + it(`should not fetch the filter from the state if not in the filter state`, () => { + controller.searchState = 'other.state'; + controller.$postLink(); + + expect(controller.filter).toBeNull(); + expect(controller.searchString).toBeNull(); + expect(controller.params.length).toBe(0); + }); + }); + + describe('filter() setter', () => { + it(`should update the bar params and search`, () => { + let withoutHours = new Date(2000, 1, 1); + let withHours = new Date(withoutHours.getTime()); + withHours.setHours(12, 30, 15, 10); + + controller.filter = { + search: 'needle', + withHours: withHours.toJSON(), + withoutHours: withoutHours.toJSON(), + boolean: true, + negated: false, + myObjectProp: {myProp: 1} + }; + + let chips = {}; + for (let param of controller.params || []) + chips[param.key] = param.chip; + + expect(controller.searchString).toBe('needle'); + expect(chips.withHours).toBe('withHours: 2000-02-01 12:30'); + expect(chips.withoutHours).toBe('withoutHours: 2000-02-01'); + expect(chips.boolean).toBe('boolean'); + expect(chips.negated).toBe('not negated'); + expect(chips.myObjectProp).toBe('myObjectProp'); + }); + }); + + describe('shownFilter() getter', () => { + it(`should return the _filter if not null`, () => { + controller.filter = filter; + controller.suggestedFilter = {sugestedParam: 'suggestedValue'}; + + expect(controller.shownFilter).toEqual(filter); + }); + + it(`should return the suggested filter if filter is null`, () => { + controller.filter = null; + controller.suggestedFilter = {sugestedParam: 'suggestedValue'}; + + expect(controller.shownFilter).toEqual(controller.suggestedFilter); + }); + }); + + describe('searchString() setter', () => { + it(`should clear the whole filter when it's null`, () => { + controller.filter = filter; + controller.searchString = null; + + expect(controller.searchString).toBeNull(); + expect(controller.params.length).toBe(0); + }); + }); + + describe('onPanelSubmit()', () => { + it(`should compact and define the filter`, () => { + controller.$.popover = {hide: jasmine.createSpy('hide')}; + + const filter = { + id: 1, + thisKeyShouldBePurged: null, + alsoThis: [], + andThis: {emptyProp: undefined, nullProp: null}, + dontForgetThis: [null, undefined], + myObject: {keepThis: true, butNotThis: null}, + myArray: [null, undefined, true] + }; + controller.onPanelSubmit(filter); + + expect(controller.filter).toEqual({ + id: 1, + myObject: {keepThis: true}, + myArray: [true] + }); + }); + }); + + describe('onSubmit()', () => { + it(`should define the filter`, () => { + controller.filter = filter; + controller.searchString = 'mySearch'; + controller.onSubmit(); + + expect(controller.filter).toEqual({id: 1, search: 'mySearch'}); + }); + }); + + describe('removeParam()', () => { + it(`should remove the parameter from the filter`, () => { + controller.filter = filter; + controller.removeParam(0); + + expect(controller.filter).toEqual({search: 'needle'}); + }); + }); + + describe('doSearch()', () => { + it(`should go to the search state and pass the filter as query param`, () => { + spyOn($state, 'go'); + controller.searchState = 'search.state'; + controller.doSearch(filter); + + let queryParams = {q: JSON.stringify(filter)}; + + expect($state.go).toHaveBeenCalledWith('search.state', queryParams, null); + expect(controller.filter).toEqual(filter); + }); + }); +}); diff --git a/front/core/components/searchbar/style.scss b/front/core/components/searchbar/style.scss new file mode 100644 index 000000000..31907792c --- /dev/null +++ b/front/core/components/searchbar/style.scss @@ -0,0 +1,47 @@ +@import "variables"; + +vn-searchbar { + display: block; + max-width: 35em; + margin: 0 auto; + + .search-params { + flex: 1; + margin: .05em 0; + overflow: visible; + display: flex; + max-width: 24em; + + & > .search-param { + color: rgba(0, 0, 0, .6); + background-color: rgba(0, 0, 0, .1); + padding: .1em .4em; + margin-left: .2em; + display: inline-block; + border-radius: .8em; + max-width: 12em; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + + & > vn-icon { + font-size: inherit; + vertical-align: middle; + cursor: pointer; + border-radius: 50%; + + &:hover { + color: rgba(0, 0, 0, .8); + } + } + } + } +} + +.search-panel { + max-height: 48em; + + & > form { + padding: $spacing-lg; + } +} \ No newline at end of file diff --git a/front/core/components/slot/index.js b/front/core/components/slot/index.js new file mode 100644 index 000000000..1747ed93f --- /dev/null +++ b/front/core/components/slot/index.js @@ -0,0 +1,81 @@ +import ngModule from '../../module'; +import './portal'; +import './style.scss'; + +export class Slot { + constructor($element, vnSlotService) { + this.$element = $element; + this.vnSlotService = vnSlotService; + this.$content = null; + } + + $onDestroy() { + this.unregister(); + } + + set name(value) { + this.unregister(); + this._name = value; + this.vnSlotService.slots[value] = this; + } + + get name() { + return this._name; + } + + unregister() { + if (this.name) + this.vnSlotService.slots[this.name] = undefined; + } + + setContent($content) { + if (this.$content) { + this.$content.detach(); + this.$content = null; + } + + this.$content = $content; + if (this.$content) this.$element.append($content); + this.$element[0].style.display = $content ? 'block' : 'none'; + } +} +Slot.$inject = ['$element', 'vnSlotService']; + +ngModule.vnComponent('vnSlot', { + controller: Slot, + bindings: { + name: '@?' + } +}); + +export class SlotService { + constructor() { + this.stacks = {}; + this.slots = {}; + } + + push(slot, $transclude) { + if (!this.stacks[slot]) this.stacks[slot] = []; + this.stacks[slot].unshift($transclude); + this.refreshContent(slot); + } + + pop(slot) { + let $content = this.stacks[slot].shift(); + this.refreshContent(slot); + if ($content && typeof $content == 'object') + $content.remove(); + } + + refreshContent(slot) { + if (!this.slots[slot]) return; + let $content = this.stacks[slot][0]; + if (typeof $content == 'function') { + $content(clone => { + $content = this.stacks[slot][0] = clone; + }); + } + this.slots[slot].setContent($content); + } +} +ngModule.service('vnSlotService', SlotService); diff --git a/front/core/components/slot/portal.js b/front/core/components/slot/portal.js new file mode 100644 index 000000000..f4dbecb09 --- /dev/null +++ b/front/core/components/slot/portal.js @@ -0,0 +1,28 @@ +import ngModule from '../../module'; + +/** + * Component used to fill slots with content. + */ +export default class Portal { + constructor($transclude, vnSlotService) { + this.$transclude = $transclude; + this.vnSlotService = vnSlotService; + } + + $postLink() { + this.vnSlotService.push(this.slot, this.$transclude); + } + + $onDestroy() { + this.vnSlotService.pop(this.slot); + } +} +Portal.$inject = ['$transclude', 'vnSlotService']; + +ngModule.component('vnPortal', { + controller: Portal, + transclude: true, + bindings: { + slot: '@' + } +}); diff --git a/front/core/components/slot/style.scss b/front/core/components/slot/style.scss new file mode 100644 index 000000000..825aad085 --- /dev/null +++ b/front/core/components/slot/style.scss @@ -0,0 +1,3 @@ +vn-slot { + display: block; +} \ No newline at end of file diff --git a/front/core/components/snackbar/snackbar.html b/front/core/components/snackbar/snackbar.html new file mode 100644 index 000000000..8ef5891bc --- /dev/null +++ b/front/core/components/snackbar/snackbar.html @@ -0,0 +1 @@ +
    \ No newline at end of file diff --git a/front/core/components/snackbar/snackbar.js b/front/core/components/snackbar/snackbar.js new file mode 100644 index 000000000..4106ffedd --- /dev/null +++ b/front/core/components/snackbar/snackbar.js @@ -0,0 +1,123 @@ +import ngModule from '../../module'; +import Component from '../../lib/component'; +import './style.scss'; + +/** + * A simple component to show non-obstructive notifications to the user. + */ +export default class Controller extends Component { + constructor($element, $translate) { + super($element); + this.$translate = $translate; + this.snackbar = $element[0].firstChild; + this.$snackbar = angular.element(this.snackbar); + } + + /** + * It creates a new snackbar notification + * @param {Object} data Snackbar data + * @return {Object} Created snackbar shape + */ + createShape(data) { + let shape = document.createElement('div'); + shape.className = 'shape'; + + let button = document.createElement('button'); + + let buttonText = data.actionText || this.$translate.instant('Hide'); + buttonText = document.createTextNode(buttonText); + button.appendChild(buttonText); + + button.addEventListener('click', () => { + this.onButtonClick(shape); + }); + + shape.appendChild(button); + + let shapeText = document.createElement('div'); + shapeText.setAttribute('class', 'text'); + shape.appendChild(shapeText); + + let text = document.createTextNode(data.message); + shapeText.appendChild(text); + + if (data.shapeType) + shape.classList.add(data.shapeType); + + let parent = this.snackbar.querySelectorAll('.shape')[0]; + + if (parent) { + this.snackbar.insertBefore(shape, parent); + } else { + this.snackbar.appendChild(shape); + } + + return shape; + } + + /** + * Shows a notification. + * + * @param {Object} data The message data + */ + show(data) { + this.actionHandler = data.actionHandler; + + let shape = this.createShape(data); + + setTimeout(() => + this.hide(shape), data.timeout || 3000); + + setTimeout(() => + shape.classList.add('shown'), 30); + } + + /** + * Shows an error. + * + * @param {Object} data The message data + */ + showError(data) { + data.shapeType = 'error'; + + this.show(data); + } + + /** + * Shows a success. + * + * @param {Object} data The message data + */ + showSuccess(data) { + data.shapeType = 'success'; + + this.show(data); + } + + /** + * Hides the snackbar. + * @param {Object} shape Snackbar element + */ + hide(shape) { + setTimeout(() => shape.classList.remove('shown'), 30); + setTimeout(() => shape.remove(), 250); + } + + onSnackbarClick(event) { + this.event = event; + } + + onButtonClick(shape) { + if (this.actionHandler) { + this.actionHandler(); + } else { + this.hide(shape); + } + } +} +Controller.$inject = ['$element', '$translate']; + +ngModule.component('vnSnackbar', { + template: require('./snackbar.html'), + controller: Controller +}); diff --git a/front/core/components/snackbar/style.scss b/front/core/components/snackbar/style.scss new file mode 100644 index 000000000..e7c073b0c --- /dev/null +++ b/front/core/components/snackbar/style.scss @@ -0,0 +1,61 @@ +@import "variables"; + +vn-snackbar #shapes { + max-height: 20.625em; + margin-left: -12.5em; + position: fixed; + z-index: 100; + width: 25em; + left: 50%; + bottom: 0 +} + +vn-snackbar .shape { + background-color: rgba(0, 0, 0, 0.8); + box-shadow: 0 0 .4em $color-shadow; + transition: transform 300ms ease-in-out; + transform: translateY(20em); + box-sizing: border-box; + border-radius: .2em; + margin-bottom: 15px; + color: white; + padding: 1em; + + &.text { + text-align: center + } + + &.shown { + transform: translateY(0); + } + + &.success { + background-color: rgba(163, 209, 49, 0.8); + color: #445911; + + & > button { + color: rgba(1, 1, 1, 0.6); + } + } + + &.error { + background-color: rgba(198, 40, 40, 0.8); + + & > button { + color: rgba(1, 1, 1, 0.6); + } + } + + & > button { + background-color: transparent; + text-transform: uppercase; + margin-left: .5em; + font-weight: bold; + cursor: pointer; + color: $color-main; + float: right; + border: none; + padding: .5em; + margin: -.5em + } +} \ No newline at end of file diff --git a/front/core/components/spinner/spinner.html b/front/core/components/spinner/spinner.html new file mode 100644 index 000000000..440e47445 --- /dev/null +++ b/front/core/components/spinner/spinner.html @@ -0,0 +1,13 @@ +
    + + + + +
    \ No newline at end of file diff --git a/client/core/src/components/spinner/spinner.js b/front/core/components/spinner/spinner.js similarity index 82% rename from client/core/src/components/spinner/spinner.js rename to front/core/components/spinner/spinner.js index ca87323d5..aee973aa6 100644 --- a/client/core/src/components/spinner/spinner.js +++ b/front/core/components/spinner/spinner.js @@ -1,19 +1,18 @@ import ngModule from '../../module'; import Component from '../../lib/component'; -import './style.css'; +import './style.scss'; /** * A spinner to inform the user about loading process. */ export default class Spinner extends Component { constructor($element, $scope) { - super($element); + super($element, $scope); this._enable = false; this.spinner = $element[0].firstChild; - componentHandler.upgradeElement(this.spinner); } /** - * Enables/disables the spinner. + * Activates/deactivates the spinner. * * @param {Boolean} value %true to enable, %false to disable */ @@ -35,14 +34,14 @@ export default class Spinner extends Component { * Activates the spinner. */ start() { - this.spinner.MaterialSpinner.start(); + this.spinner.style.display = 'block'; this._enable = true; } /** * Deactivates the spinner. */ stop() { - this.spinner.MaterialSpinner.stop(); + this.spinner.style.display = 'none'; this._enable = false; } } diff --git a/front/core/components/spinner/spinner.spec.js b/front/core/components/spinner/spinner.spec.js new file mode 100644 index 000000000..dbcdb0acd --- /dev/null +++ b/front/core/components/spinner/spinner.spec.js @@ -0,0 +1,49 @@ +import './spinner.js'; + +describe('Component vnSpinner', () => { + let $element; + let controller; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject(($compile, $rootScope) => { + $element = $compile(``)($rootScope); + controller = $element.controller('vnSpinner'); + })); + + afterEach(() => { + $element.remove(); + }); + + describe('enable()', () => { + it(`should call start() when enable is set to true`, () => { + spyOn(controller, 'start'); + controller.enable = true; + + expect(controller.start).toHaveBeenCalledWith(); + }); + + it(`should call stop() when enable is set to false`, () => { + spyOn(controller, 'stop'); + controller.enable = false; + + expect(controller.stop).toHaveBeenCalledWith(); + }); + }); + + describe('start()', () => { + it(`should set enable to true`, () => { + controller.start(); + + expect(controller.enable).toBeTruthy(); + }); + }); + + describe('stop()', () => { + it(`should set enable to false`, () => { + controller.stop(); + + expect(controller.enable).toBeFalsy(); + }); + }); +}); diff --git a/front/core/components/spinner/style.scss b/front/core/components/spinner/style.scss new file mode 100644 index 000000000..eb39f64e8 --- /dev/null +++ b/front/core/components/spinner/style.scss @@ -0,0 +1,60 @@ +@import "variables"; + +vn-spinner { + display: inline-block; + min-height: 28px; + min-width: 28px; + color: $color-main; + + & > .loader { + position: relative; + margin: 0 auto; + width: 100%; + height: 100%; + + &:before { + content: ''; + display: block; + padding-top: 100%; + } + & > .circular { + animation: rotate 2s linear infinite; + transform-origin: center center; + height: 100%; + width: 100%; + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + margin: auto; + + & > .path { + stroke-dasharray: 1, 200; + stroke-dashoffset: 0; + stroke-linecap: square; + stroke-width: 6px; + animation: dash 1.5s ease-in-out infinite; + } + } + } + @keyframes rotate { + 100% { + transform: rotate(360deg); + } + } + @keyframes dash { + 0% { + stroke-dasharray: 1, 200; + stroke-dashoffset: 0; + } + 50% { + stroke-dasharray: 89, 200; + stroke-dashoffset: -35px; + } + 100% { + stroke-dasharray: 89, 200; + stroke-dashoffset: -124px; + } + } +} \ No newline at end of file diff --git a/front/core/components/step-control/step-control.html b/front/core/components/step-control/step-control.html new file mode 100644 index 000000000..0ca358676 --- /dev/null +++ b/front/core/components/step-control/step-control.html @@ -0,0 +1,32 @@ +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +
    +
    + + + + +
    +
    +
    \ No newline at end of file diff --git a/front/core/components/step-control/step-control.js b/front/core/components/step-control/step-control.js new file mode 100644 index 000000000..0ca1f0c46 --- /dev/null +++ b/front/core/components/step-control/step-control.js @@ -0,0 +1,85 @@ +import ngModule from '../../module'; +import './style.scss'; + +export default class StepControl { + constructor($state) { + this.$state = $state; + } + + set steps(steps) { + if (!steps) return; + + this._steps = steps; + + if (this.currentStepIndex > 0) + this.$state.go(this._steps[0].state); + } + + set currentState(state) { + if (!this.onStepChange) + return this.$state.go(state); + + let change = this.onStepChange({state}); + + if (typeof change === 'object' && change.then) { + return change.then(isAllowed => { + if (isAllowed) + this.$state.go(state); + }); + } + + if (change) + this.$state.go(state); + } + + get totalSteps() { + return this._steps.length; + } + + get currentState() { + return this.$state.current.name; + } + + get currentStepIndex() { + for (let i = 0; i < this._steps.length; i++) { + if (this._steps[i].state == this.$state.current.name) + return i; + } + } + + onPreviousClick() { + let state = this._steps[this.currentStepIndex - 1].state; + + this.currentState = state; + } + + onNextClick() { + let state = this._steps[this.currentStepIndex + 1].state; + + this.currentState = state; + } + + canMovePrevious() { + return this.currentStepIndex > 0; + } + + canFinalize() { + return this.currentStepIndex === this.totalSteps - 1; + } + + canMoveNext() { + return this.currentStepIndex < this.totalSteps - 1; + } +} + +StepControl.$inject = ['$state']; + +ngModule.component('vnStepControl', { + template: require('./step-control.html'), + controller: StepControl, + bindings: { + steps: '<', + onStepChange: '&?', + onStepEnd: '&?' + } +}); diff --git a/front/core/components/step-control/step-control.spec.js b/front/core/components/step-control/step-control.spec.js new file mode 100644 index 000000000..944457cfe --- /dev/null +++ b/front/core/components/step-control/step-control.spec.js @@ -0,0 +1,68 @@ +import './step-control.js'; + +describe('Component vnStepControl', () => { + let controller; + let $state; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject(($componentController, _$state_) => { + $state = _$state_; + spyOn($state, 'go'); + controller = $componentController('vnStepControl', {$state: $state}); + })); + + describe('steps()', () => { + it(`should do nothing if called without args`, () => { + controller.steps = undefined; + + expect(controller._steps).not.toEqual(null); + }); + + it(`should set _steps property in the controller and call state.go()`, () => { + controller.$state.current.name = 'test'; + controller.steps = [{state: 'nothing'}, {state: 'test'}]; + + expect(controller._steps).toEqual([{state: 'nothing'}, {state: 'test'}]); + expect(controller.currentStepIndex).toEqual(1); + expect(controller.$state.go).toHaveBeenCalledWith('nothing'); + }); + }); + + describe('currentState()', () => { + it(`should call the go method if the's no onStepChange`, () => { + controller.currentState = 'hello state!'; + + expect(controller.$state.go).toHaveBeenCalledWith('hello state!'); + }); + + it(`should call the onStepChange method then return false and never call the go method`, () => { + controller.onStepChange = jasmine.createSpy(controller, 'onStepChange').and.returnValue(false); + + controller.currentState = 'something'; + + expect(controller.onStepChange).toHaveBeenCalledWith({state: 'something'}); + expect(controller.$state.go).not.toHaveBeenCalledWith('something'); + }); + + it(`should call the onStepChange method then return true and finally call the go method`, () => { + controller.onStepChange = jasmine.createSpy(controller, 'onStepChange').and.returnValue(true); + + controller.currentState = 'something'; + + expect(controller.onStepChange).toHaveBeenCalledWith({state: 'something'}); + expect(controller.$state.go).toHaveBeenCalledWith('something'); + }); + }); + + describe('currentStepIndex()', () => { + it('should get the current state index from an Array of states', () => { + controller.$state.current.name = 'iam_a_current_state'; + controller.steps = [{state: 'iam_not_current_state'}, {state: 'iam_a_current_state'}]; + + let result = controller.currentStepIndex; + + expect(result).toEqual(1); + }); + }); +}); diff --git a/front/core/components/step-control/style.scss b/front/core/components/step-control/style.scss new file mode 100644 index 000000000..9acc1f314 --- /dev/null +++ b/front/core/components/step-control/style.scss @@ -0,0 +1,45 @@ +@import "variables"; + +vn-step-control { + display: flex; + justify-content: center; + + .step-control { + border-top: 2px solid $color-main; + margin-bottom: 15px; + + & > .steps { + display: flex; + flex-direction: row + } + & > .steps > .step { + justify-content: center; + min-width: 125px; + display: flex; + flex: auto + } + & > .steps > .step .circle { + border: 2px solid $color-main; + background-color: white; + align-content: center; + margin-top: -9.5px; + border-radius: 50%; + cursor: pointer; + height: 15px; + width: 15px + } + & > .steps > .step .circle.active { + background-color: $color-main; + } + & > .buttons { + display: flex; + flex: auto; + flex-direction: row; + justify-content: space-between; + margin-top: 10px + } + & > .buttons > .step { + display: flex + } + } +} \ No newline at end of file diff --git a/front/core/components/submit/index.js b/front/core/components/submit/index.js new file mode 100644 index 000000000..ced73f0ba --- /dev/null +++ b/front/core/components/submit/index.js @@ -0,0 +1,13 @@ +import ngModule from '../../module'; +import Button from '../button'; + +export default class Controller extends Button { + constructor($element, $scope) { + super($element, $scope); + this.type = 'submit'; + } +} + +ngModule.vnComponent('vnSubmit', { + controller: Controller +}); diff --git a/front/core/components/subtitle/subtitle.html b/front/core/components/subtitle/subtitle.html new file mode 100644 index 000000000..40c244006 --- /dev/null +++ b/front/core/components/subtitle/subtitle.html @@ -0,0 +1,2 @@ +
    +
    \ No newline at end of file diff --git a/client/core/src/components/subtitle/subtitle.js b/front/core/components/subtitle/subtitle.js similarity index 100% rename from client/core/src/components/subtitle/subtitle.js rename to front/core/components/subtitle/subtitle.js diff --git a/front/core/components/table/index.html b/front/core/components/table/index.html new file mode 100644 index 000000000..5c36dd6a0 --- /dev/null +++ b/front/core/components/table/index.html @@ -0,0 +1,2 @@ +
    +
    \ No newline at end of file diff --git a/front/core/components/table/index.js b/front/core/components/table/index.js new file mode 100644 index 000000000..0b9236c84 --- /dev/null +++ b/front/core/components/table/index.js @@ -0,0 +1,56 @@ +import ngModule from '../../module'; +import './style.scss'; + +export default class Table { + constructor($scope, $element, $transclude) { + this.$scope = $scope; + this.table = $element[0]; + this.field = null; + this.order = null; + this.autoLoad = true; + } + + setOrder(field, order) { + this.field = field; + this.order = order; + } + + applyOrder(field = this.field, order = this.order) { + if (field && order) { + this.model.order = `${field} ${order}`; + this.setActiveArrow(); + } + + this.model.refresh(); + } + + $onChanges() { + // FIXME: The autoload property should be removed from vnTable + // because it's already implemented at vnModel + if (this.autoLoad && this.model && !this.model.data) + this.applyOrder(); + } + + setActiveArrow() { + let columns = this.table.querySelectorAll('vn-thead vn-th'); + columns.forEach(column => { + column.classList.remove('active'); + }); + + let selector = `vn-thead vn-th[field="${this.field}"]`; + let activeColumn = this.table.querySelector(selector); + activeColumn.classList.add('active'); + } +} + +Table.$inject = ['$scope', '$element', '$transclude']; + +ngModule.component('vnTable', { + template: require('./index.html'), + transclude: true, + controller: Table, + bindings: { + model: ' { + let $scope; + let $element; + let controller; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject(($componentController, $rootScope) => { + $scope = $rootScope.$new(); + $element = angular.element(` + + + + + + + + + `); + controller = $componentController('vnTable', {$scope, $element, $transclude: () => {}}); + })); + + describe('setActiveArrow()', () => { + it(`should remove the active class from all table headers and then add it to the one in field`, () => { + controller.field = 'id'; + + controller.setActiveArrow(); + + expect($element[0].getElementsByClassName('active')[0].getAttribute('field')).toEqual('id'); + expect($element[0].getElementsByClassName('active').length).toEqual(1); + }); + }); +}); diff --git a/front/core/components/table/style.scss b/front/core/components/table/style.scss new file mode 100644 index 000000000..41d1f6db8 --- /dev/null +++ b/front/core/components/table/style.scss @@ -0,0 +1,179 @@ +@import "effects"; +@import "variables"; + +vn-table { + display: block; + width: 100%; + overflow: auto; +} +.vn-table { + width: 100%; + display: table; + border-collapse: collapse; + + & > vn-thead, + & > thead { + display: table-header-group; + border-bottom: .15em solid $color-spacer; + + & > * > th { + font-weight: normal; + } + & > * > vn-th[field] { + position: relative; + overflow: visible; + cursor: pointer; + + &.active > :after { + color: $color-font; + opacity: 1; + } + &.desc > :after { + content: 'arrow_drop_down'; + } + &.asc > :after { + content: 'arrow_drop_up'; + } + & > :after { + font-family: 'Material Icons'; + content: 'arrow_drop_down'; + position: absolute; + color: $color-spacer; + opacity: 0; + } + &:hover > :after { + opacity: 1; + } + } + } + & > vn-tbody, + & > tbody { + display: table-row-group; + } + & > vn-tfoot, + & > tfoot { + border-top: .15em solid $color-spacer; + display: table-footer-group + } + & > * > vn-tr, + & > * > a.vn-tr, + & > * > tr { + display: table-row; + height: 3em; + } + vn-thead, vn-tbody, vn-tfoot, + thead, tbody, tfoot { + & > * { + display: table-row; + + & > vn-th, + & > th { + color: $color-font-light; + padding-top: 1em; + padding-bottom: .8em; + } + & > vn-th, + & > vn-td, + & > th, + & > td { + overflow: hidden; + } + & > vn-th, + & > vn-td, + & > vn-td-editable, + & > th, + & > td { + vertical-align: middle; + display: table-cell; + text-align: left; + padding: .6em .5em; + white-space: nowrap; + text-overflow: ellipsis; + max-width: 5em; + + &[number] { + text-align: right; + width: 6em; + } + &[center] { + text-align: center; + } + &[shrink] { + width: 1px; + text-align: center; + } + &[expand] { + max-width: 25em; + min-width: 0; + } + vn-icon.bright, i.bright { + color: #f7931e; + } + } + & > :last-child { + padding-right: 1.4em; + } + & > :first-child { + padding-left: 1.4em; + } + } + & > a.vn-tr { + color: inherit; + } + } + vn-tbody > *, + tbody > * { + border-bottom: .1em solid $color-spacer-light; + + &:last-child { + border-bottom: none; + } + &.clickable { + @extend %clickable; + } + & > vn-td, + & > td { + .chip { + padding: .3em; + border-radius: .3em; + color: $color-font-bg; + + &.notice { + background-color: $color-notice-medium + } + &.success { + background-color: $color-success-medium; + } + &.warning { + background-color: $color-main-medium; + } + &.alert { + background-color: $color-alert-medium; + } + &.message { + color: $color-font-dark; + background-color: $color-bg-dark + } + } + vn-icon-menu { + display: inline-block; + color: $color-main; + padding: .25em + } + } + & > [actions] { + width: 1px; + + & > * { + vertical-align: middle; + } + } + } + .vn-textfield { + float: right; + margin: 0!important; + } + .vn-check { + margin: 0; + } +} \ No newline at end of file diff --git a/front/core/components/td-editable/index.html b/front/core/components/td-editable/index.html new file mode 100644 index 000000000..8a1e33fe8 --- /dev/null +++ b/front/core/components/td-editable/index.html @@ -0,0 +1,2 @@ +
    + \ No newline at end of file diff --git a/front/core/components/td-editable/index.js b/front/core/components/td-editable/index.js new file mode 100644 index 000000000..844e7501e --- /dev/null +++ b/front/core/components/td-editable/index.js @@ -0,0 +1,107 @@ +import ngModule from '../../module'; +import Component from '../../lib/component'; +import FormInput from '../form-input'; +import './style.scss'; + +export default class Controller extends Component { + constructor($element, $scope, $transclude, $timeout) { + super($element, $scope); + this.$timeout = $timeout; + this.element.tabIndex = 0; + + this.element.addEventListener('focus', () => { + if (this.field || this.disabled) return; + $transclude((tClone, tScope) => { + this.field = tClone; + this.tScope = tScope; + this.element.querySelector('.field').appendChild(this.field[0]); + this.element.tabIndex = -1; + }, null, 'field'); + this.element.classList.add('selected'); + }); + + this.element.addEventListener('focusout', event => this.hideField(event)); + + this.element.addEventListener('keyup', event => { + if (event.key === 'Enter') + this.hideField(event); + }); + + this.element.addEventListener('click', event => { + if (this.disabled) return; + + let target = event.target; + while (target) { + if (target == this.field[0]) return; + target = target.parentNode; + } + + let inputCtrl = this.field[0].firstElementChild.$ctrl; + if (inputCtrl instanceof FormInput) { + let evt = new MouseEvent('click', { + bubbles: true, + cancelable: true, + view: window + }); + inputCtrl.input.dispatchEvent(evt); + } + }); + } + + hideField(event) { + if (!this.field || !this.tScope) return; + + this.lastEvent = event; + let target = event.relatedTarget; + while (target && target != this.element) + target = target.parentNode; + + if (!target) { + this.tScope.$destroy(); + this.tScope = null; + this.field.remove(); + this.field = null; + this.element.classList.remove('selected'); + this.element.tabIndex = 0; + } + } + + destroyTimer() { + if (this.timer) { + this.$timeout.cancel(this.timer); + this.timer = null; + } + } + + $onDestroy() { + this.destroyTimer(); + } + + get disabled() { + return this._disabled; + } + + set disabled(value) { + this._disabled = value; + + const classList = this.element.classList; + + if (value) + classList.add('disabled'); + else + classList.remove('disabled'); + } +} +Controller.$inject = ['$element', '$scope', '$transclude', '$timeout']; + +ngModule.component('vnTdEditable', { + template: require('./index.html'), + controller: Controller, + bindings: { + disabled: ' .text { + visibility: hidden; + } + & > .field { + display: none; + width: 100%; + height: 100%; + position: absolute; + z-index:10; + top: 0; + left: 0; + box-sizing: border-box; + align-items: center; + padding: .6em; + overflow: visible; + + & > field { + flex: 1; + background-color: $color-bg-panel; + padding: .5em; + box-shadow: 0 0 .4em rgba(0, 0, 0, .2); + border-radius: .1em; + min-width: 6em; + + & > * { + width: 100%; + max-width: initial; + } + } + } + &.selected > .field { + display: flex; + } +} + +vn-td-editable.disabled { + cursor: initial; +} +vn-td-editable.disabled text { + border: none; +} \ No newline at end of file diff --git a/front/core/components/textarea/index.js b/front/core/components/textarea/index.js new file mode 100644 index 000000000..8fcae7b0f --- /dev/null +++ b/front/core/components/textarea/index.js @@ -0,0 +1,26 @@ +import ngModule from '../../module'; +import Field from '../field'; + +export default class Textarea extends Field { + constructor($element, $scope, $compile) { + super($element, $scope, $compile); + + let html = ``; + this.input = this.$compile(html)($scope)[0]; + } + + set rows(value) { + this.input.rows = typeof value == 'number' && value > 0 ? value : 3; + } + + get rows() { + return this.input.rows; + } +} + +ngModule.vnComponent('vnTextarea', { + controller: Textarea, + bindings: { + rows: ' { + let $element; + let $ctrl; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject(($compile, $rootScope) => { + $element = $compile(``)($rootScope); + $ctrl = $element.controller('vnTextarea'); + })); + + afterEach(() => { + $element.remove(); + }); + + describe('rows() setter', () => { + it(`should set rows property of the element to the given value if it's a valid number`, () => { + $ctrl.rows = 27; + + expect($ctrl.rows).toEqual(27); + }); + + it(`should set rows property of the element to 3 if the given value if it's null`, () => { + $ctrl.rows = null; + + expect($ctrl.rows).toEqual(3); + }); + + it(`should set rows property of the element to 3 if the given value if it's not a valid number`, () => { + $ctrl.rows = 'a'; + + expect($ctrl.rows).toEqual(3); + }); + }); +}); diff --git a/front/core/components/textfield/textfield.js b/front/core/components/textfield/textfield.js new file mode 100644 index 000000000..f166dae1c --- /dev/null +++ b/front/core/components/textfield/textfield.js @@ -0,0 +1,13 @@ +import ngModule from '../../module'; +import Field from '../field'; + +export default class Textfield extends Field { + constructor($element, $scope, $compile) { + super($element, $scope, $compile); + this.buildInput('text'); + } +} + +ngModule.vnComponent('vnTextfield', { + controller: Textfield +}); diff --git a/front/core/components/th/index.html b/front/core/components/th/index.html new file mode 100644 index 000000000..28d80695d --- /dev/null +++ b/front/core/components/th/index.html @@ -0,0 +1,3 @@ +
    + +
    \ No newline at end of file diff --git a/front/core/components/th/index.js b/front/core/components/th/index.js new file mode 100644 index 000000000..682fb4eb1 --- /dev/null +++ b/front/core/components/th/index.js @@ -0,0 +1,88 @@ +import ngModule from '../../module'; + +export default class Th { + constructor($element) { + this._order = 'ASC'; + this.column = $element[0]; + $element.on('click', () => this.onToggleOrder()); + } + + /** + * Changes the order if the cell has a field and defaultOrder property + */ + $onInit() { + if (!this.field) return; + + if (this.defaultOrder) + this.order = this.defaultOrder; + + this.updateArrow(); + } + + set order(order) { + this._order = order; + this.table.setOrder(this.field, order); + } + + get order() { + return this._order; + } + + get field() { + return this.column.getAttribute('field'); + } + + /** + * Toggle order ASC/DESC + */ + toggleOrder() { + if (this.order === 'ASC') + this.order = 'DESC'; + else + this.order = 'ASC'; + } + + /** + * Applies a new filter order to the model and + * updates the cell arrow + */ + onToggleOrder() { + if (!this.field) return; + + if (this.table.field == this.field) + this.toggleOrder(); + else + this.table.setOrder(this.field, this.order); + + + this.updateArrow(); + + this.table.applyOrder(this.field, this.order); + } + + /** + * Set cell class to asc/desc + */ + updateArrow() { + this.column.classList.remove('asc', 'desc'); + + if (this.order === 'DESC') + this.column.classList.add('desc'); + else + this.column.classList.add('asc'); + } +} + +Th.$inject = ['$element']; + +ngModule.component('vnTh', { + template: require('./index.html'), + transclude: true, + controller: Th, + bindings: { + defaultOrder: '@?' + }, + require: { + table: '^^vnTable' + } +}); diff --git a/front/core/components/th/index.spec.js b/front/core/components/th/index.spec.js new file mode 100644 index 000000000..dc9e43672 --- /dev/null +++ b/front/core/components/th/index.spec.js @@ -0,0 +1,106 @@ +import './index.js'; +import template from './index.html'; + +describe('Component vnTh', () => { + let controller; + let $element; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject($componentController => { + $element = angular.element(`
    ${template}
    `); + controller = $componentController('vnTh', {$element: $element}); + controller.table = { + setOrder: () => {}, + applyOrder: () => {} + }; + controller.column.setAttribute('field', 'MyField'); + })); + + describe('onInit()', () => { + it(`should define controllers order as per defaultOrder then call setOrder()`, () => { + controller.defaultOrder = 'DESC'; + spyOn(controller.table, 'setOrder'); + controller.$onInit(); + + expect(controller.order).toEqual('DESC'); + expect(controller.table.setOrder).toHaveBeenCalledWith('MyField', 'DESC'); + }); + }); + + describe('toggleOrder()', () => { + it(`should change the ordenation to DESC (descendant) if it was ASC (ascendant)`, () => { + controller.order = 'ASC'; + controller.toggleOrder(); + + expect(controller.order).toEqual('DESC'); + }); + + it(`should change the ordenation to ASC (ascendant) if it wasnt ASC`, () => { + controller.order = 'DESC or any other value that might occur'; + controller.toggleOrder(); + + expect(controller.order).toEqual('ASC'); + }); + + it(`should call the setOrder() function after changing a value`, () => { + spyOn(controller.table, 'setOrder'); + controller.order = 'Change me!'; + + expect(controller.table.setOrder).toHaveBeenCalledWith('MyField', 'Change me!'); + }); + }); + + describe('onToggleOrder()', () => { + it(`should not call updateArrow() method if field property isn't defined`, () => { + controller.column.setAttribute('field', ''); + spyOn(controller, 'updateArrow'); + + controller.onToggleOrder(); + + expect(controller.updateArrow).not.toHaveBeenCalledWith(); + }); + + it(`should call toggleOrder() method if field property and + table field property equals and then call updateArrow()`, () => { + controller.table.field = 'MyField'; + spyOn(controller, 'toggleOrder'); + spyOn(controller, 'updateArrow'); + + controller.onToggleOrder(); + + expect(controller.toggleOrder).toHaveBeenCalledWith(); + expect(controller.updateArrow).toHaveBeenCalledWith(); + }); + + it(`should call setOrder() method if field property and + table field property doesn't equals and then call updateArrow()`, () => { + controller.table.field = 'MyField2'; + spyOn(controller.table, 'setOrder'); + spyOn(controller, 'updateArrow'); + + controller.onToggleOrder(); + + expect(controller.table.setOrder).toHaveBeenCalledWith('MyField', 'ASC'); + expect(controller.updateArrow).toHaveBeenCalledWith(); + }); + }); + + describe('updateArrow()', () => { + it(`should remove 'asc' class and add 'desc' class if order property is descendant`, () => { + controller.column.classList.add('asc'); + controller.order = 'DESC'; + controller.updateArrow(); + + expect(controller.column.classList[0]).toEqual('desc'); + }); + + it(`should remove 'asc' class and add it again if order property is ascendant`, () => { + controller.column.classList.add('asc'); + controller.order = 'ASC'; + controller.updateArrow(); + + expect(controller.column.classList[0]).toEqual('asc'); + }); + }); +}); diff --git a/front/core/components/title/title.html b/front/core/components/title/title.html new file mode 100644 index 000000000..cfdad746f --- /dev/null +++ b/front/core/components/title/title.html @@ -0,0 +1,3 @@ +

    + +

    \ No newline at end of file diff --git a/client/core/src/components/title/title.js b/front/core/components/title/title.js similarity index 100% rename from client/core/src/components/title/title.js rename to front/core/components/title/title.js diff --git a/front/core/components/toggle/index.html b/front/core/components/toggle/index.html new file mode 100644 index 000000000..3ec11242e --- /dev/null +++ b/front/core/components/toggle/index.html @@ -0,0 +1,7 @@ +
    +
    +
    +
    + + {{::$ctrl.label}} + \ No newline at end of file diff --git a/front/core/components/toggle/index.js b/front/core/components/toggle/index.js new file mode 100644 index 000000000..bc3851bbc --- /dev/null +++ b/front/core/components/toggle/index.js @@ -0,0 +1,39 @@ +import ngModule from '../../module'; +import FormInput from '../form-input'; +import './style.scss'; + +/** + * Base component with common logic and styles for checkbox and radio button. + * + * @property {Boolean} checked Whether the checkbox is checked + */ +export default class Toggle extends FormInput { + constructor($element, $) { + super($element, $); + this.initTabIndex(); + this.element.addEventListener('click', e => this.onClick(e)); + this.element.addEventListener('keydown', e => this.onKeydown(e)); + } + + onKeydown(event) { + if (!event.defaultPrevented && event.key == ' ') + this.element.click(); + } + + onClick(event) { + if (!this.editable || event.defaultPrevented) + return true; + } + + change(value) { + this.$.$applyAsync(); + super.change(value); + } +} + +ngModule.vnComponent('vnToggle', { + controller: Toggle, + bindings: { + checked: ' span { + font-size: 1rem; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + } + & > .btn { + position: relative; + box-sizing: border-box; + display: inline-block; + vertical-align: middle; + width: 20px; + height: 20px; + min-width: 20px; + margin: 6px 0; + margin-right: .6em; + border: 2px solid #666; + } + & > .btn > .focus-mark { + position: absolute; + top: 50%; + left: 50%; + height: 38px; + width: 38px; + margin-top: -19px; + margin-left: -19px; + border-radius: 50%; + transform: scale3d(0, 0, 0); + transition: background 250ms; + transition: transform 250ms; + background-color: rgba(0, 0, 0, .1); + } + &.checked > .btn { + border-color: $color-button; + + & > .focus-mark { + background-color: rgba($color-button, .15); + } + } + &.disabled { + cursor: inherit; + + &.checked > .btn { + border-color: $color-font-secondary; + } + } + &.readonly { + cursor: inherit; + } + &:focus:not(.disabled) > .btn > .focus-mark { + transform: scale3d(1, 1, 1); + } +} diff --git a/front/core/components/tooltip/style.scss b/front/core/components/tooltip/style.scss new file mode 100644 index 000000000..926142582 --- /dev/null +++ b/front/core/components/tooltip/style.scss @@ -0,0 +1,25 @@ +@import "variables"; + +.vn-tooltip { + display: none; + position: fixed; + z-index: 150; + background-color: $color-bg-dark; + color: $color-active-font; + border-radius: .2em; + + &.show { + display: inherit; + } + &.text { + max-width: 320px; + padding: 15px; + } + & > .arrow { + position: absolute; + width: 0; + height: 0; + border-style: solid; + border-color: transparent; + } +} diff --git a/front/core/components/tooltip/tooltip.html b/front/core/components/tooltip/tooltip.html new file mode 100644 index 000000000..e2c9e19ce --- /dev/null +++ b/front/core/components/tooltip/tooltip.html @@ -0,0 +1,3 @@ +
    +
    +
    \ No newline at end of file diff --git a/front/core/components/tooltip/tooltip.js b/front/core/components/tooltip/tooltip.js new file mode 100644 index 000000000..7ec188653 --- /dev/null +++ b/front/core/components/tooltip/tooltip.js @@ -0,0 +1,254 @@ +import ngModule from '../../module'; +import Component from '../../lib/component'; +import './style.scss'; + +let positions = ['left', 'right', 'up', 'down']; + +/** + * A simple tooltip. + * + * @property {String} position The relative position to the parent + */ +export default class Tooltip extends Component { + constructor($element, $scope, $timeout) { + super($element, $scope); + this.$timeout = $timeout; + $element.addClass('vn-tooltip vn-shadow'); + this.position = 'down'; + this.margin = 10; + } + + /** + * Shows the tooltip. + * + * @param {HTMLElement} parent The parent element + */ + show(parent) { + this.parent = parent; + this.$element.addClass('show'); + this.relocate(); + this.cancelTimeout(); + this.relocateTimeout = this.$timeout(() => this.relocate(), 50); + } + + /** + * Hides the tooltip. + */ + hide() { + this.$element.removeClass('show'); + this.cancelTimeout(); + } + + cancelTimeout() { + if (this.relocateTimeout) { + this.$timeout.cancel(this.relocateTimeout); + this.relocateTimeout = null; + } + } + + /** + * Repositions the tooltip acording to it's own size and parent location. + */ + relocate() { + let axis; + let position = this.position; + + if (positions.indexOf(position) == -1) + position = 'down'; + + switch (position) { + case 'right': + case 'left': + axis = 'x'; + break; + default: + axis = 'y'; + } + + let arrowSize = this.margin; + let tipMargin = this.margin; + let rect = this.parent.getBoundingClientRect(); + let tipRect = this.element.getBoundingClientRect(); + + let tipComputed = this.window.getComputedStyle(this.element, null); + let bgColor = tipComputed.getPropertyValue('background-color'); + + let min = tipMargin; + let maxTop = this.window.innerHeight - tipRect.height - tipMargin; + let maxLeft = this.window.innerWidth - tipRect.width - tipMargin; + + // Coordinates + + let top; + let left; + + function calcCoords() { + top = rect.top; + left = rect.left; + + if (axis == 'x') + top += rect.height / 2 - tipRect.height / 2; + else + left += rect.width / 2 - tipRect.width / 2; + + switch (position) { + case 'right': + left += arrowSize + rect.width; + break; + case 'left': + left -= arrowSize + tipRect.width; + break; + case 'up': + top -= arrowSize + tipRect.height; + break; + default: + top += arrowSize + rect.height; + } + } + calcCoords(); + + // Overflow + + let axisOverflow = + axis == 'x' && (left < min || left > maxLeft) || + axis == 'y' && (top < min || top > maxTop); + + function switchPosition(position) { + switch (position) { + case 'right': + return 'left'; + case 'left': + return 'right'; + case 'up': + return 'down'; + default: + return 'up'; + } + } + + if (axisOverflow) { + position = switchPosition(position); + calcCoords(); + } + + function range(coord, min, max) { + return Math.min(Math.max(coord, min), max); + } + + if (axis == 'x') + top = range(top, min, maxTop); + else + left = range(left, min, maxLeft); + + let style = this.element.style; + style.top = `${top}px`; + style.left = `${left}px`; + + // Arrow position + + if (this.arrow) + this.element.removeChild(this.arrow); + + let arrow = document.createElement('div'); + arrow.className = 'arrow'; + arrow.style.borderWidth = `${arrowSize}px`; + + let arrowStyle = arrow.style; + + if (axis == 'x') { + let arrowTop = (rect.top + rect.height / 2) - top - arrowSize; + arrowStyle.top = `${arrowTop}px`; + } else { + let arrowLeft = (rect.left + rect.width / 2) - left - arrowSize; + arrowStyle.left = `${arrowLeft}px`; + } + + let arrowCoord = `${-tipMargin}px`; + + switch (position) { + case 'right': + arrowStyle.left = arrowCoord; + arrowStyle.borderRightColor = bgColor; + arrowStyle.borderLeftWidth = 0; + break; + case 'left': + arrowStyle.right = arrowCoord; + arrowStyle.borderLeftColor = bgColor; + arrowStyle.borderRightWidth = 0; + break; + case 'up': + arrowStyle.bottom = arrowCoord; + arrowStyle.borderTopColor = bgColor; + arrowStyle.borderBottomWidth = 0; + break; + default: + arrowStyle.top = arrowCoord; + arrowStyle.borderBottomColor = bgColor; + arrowStyle.borderTopWidth = 0; + } + + this.element.appendChild(arrow); + this.arrow = arrow; + } + + $onDestroy() { + this.hide(); + } +} +Tooltip.$inject = ['$element', '$scope', '$timeout']; + +ngModule.component('vnTooltip', { + template: require('./tooltip.html'), + controller: Tooltip, + transclude: true, + bindings: { + position: '@?' + } +}); + +directive.$inject = ['$document', '$compile', '$templateRequest']; +export function directive($document, $compile, $templateRequest) { + return { + restrict: 'A', + link: function($scope, $element, $attrs) { + let tooltip; + let $tooltip; + let $tooltipScope; + + if ($attrs.tooltipId) { + let tooltipKey = kebabToCamel($attrs.tooltipId); + tooltip = $scope[tooltipKey]; + if (!(tooltip instanceof Tooltip)) + throw new Error(`vnTooltip id should reference a tooltip instance`); + } else { + $tooltipScope = $scope.$new(); + $tooltipScope.text = $attrs.vnTooltip; + let template = `{{::text}}`; + $tooltip = $compile(template)($tooltipScope); + $document.find('body').append($tooltip); + tooltip = $tooltip[0].$ctrl; + } + + if ($attrs.tooltipPosition) + tooltip.position = $attrs.tooltipPosition; + + $element[0].title = ''; + $element.on('mouseover', function(event) { + if (event.defaultPrevented) return; + tooltip.show($element[0]); + }); + $element.on('mouseout', function() { + tooltip.hide(); + }); + $element.on('$destroy', function() { + tooltip.hide(); + + if ($tooltip) { + $tooltip.remove(); + $tooltipScope.$destroy(); + } + }); + } + }; +} +ngModule.directive('vnTooltip', directive); diff --git a/front/core/components/tooltip/tooltip.spec.js b/front/core/components/tooltip/tooltip.spec.js new file mode 100644 index 000000000..74cb410ff --- /dev/null +++ b/front/core/components/tooltip/tooltip.spec.js @@ -0,0 +1,120 @@ +import './tooltip'; + +describe('Component vnTooltip', () => { + let $element; + let controller; + let $parent; + let element; + let window; + + beforeEach(ngModule('vnCore')); + + beforeEach(inject(($componentController, $compile, $templateRequest, $document) => { + $element = angular.element(`test`); + $document.find('body').append($element); + controller = $componentController('vnTooltip', {$document, $compile, $templateRequest, $element}); + element = $element[0]; + window = controller.window; + + $parent = angular.element('
    '); + $parent.css({ + backgroundColor: 'red', + position: 'absolute', + width: '100px', + height: '100px', + top: '0', + left: '0' + }); + $document.find('body').append($parent); + })); + + afterEach(() => { + $element.remove(); + $parent.remove(); + }); + + describe('show()', () => { + it(`should check that tooltip is visible into the screen`, () => { + expect(element.classList).not.toContain('show'); + + controller.show($parent[0]); + + let rect = element.getBoundingClientRect(); + + expect(element.classList).toContain('show'); + + expect(0).toBeLessThanOrEqual(rect.top); + expect(0).toBeLessThanOrEqual(rect.left); + expect(window.innerHeight).toBeGreaterThan(rect.bottom); + expect(window.innerWidth).toBeGreaterThan(rect.right); + }); + }); + + describe('hide()', () => { + it(`should check that tooltip is not visible`, () => { + controller.show($parent[0]); + + expect(element.classList).toContain('show'); + controller.hide(); + + expect(element.classList).not.toContain('show'); + }); + }); + + // #1892 reparar unitarios front tooltip.js + xdescribe('relocate()', () => { + it(`should reallocate tooltip on top-left`, () => { + controller.show($parent[0]); + let rect = element.getBoundingClientRect(); + + expect(controller.margin).toBeLessThan(rect.top); + expect(controller.margin).toEqual(rect.left); + }); + + it(`should reallocate tooltip on bottom-left`, () => { + $parent.css({ + top: `${window.innerHeight}px` + }); + controller.show($parent[0]); + let rect = element.getBoundingClientRect(); + + expect(window.innerHeight).toBeGreaterThan(rect.top); + expect(controller.margin).toEqual(rect.left); + }); + + it(`should reallocate tooltip on bottom-right`, () => { + $parent.css({ + top: `${window.innerHeight}px`, + left: `${window.innerWidth}px` + }); + controller.show($parent[0]); + let rect = element.getBoundingClientRect(); + + expect(window.innerWidth).toBeGreaterThan(rect.left); + expect(window.innerWidth - controller.margin).toEqual(rect.right); + }); + + it(`should reallocate tooltip on top-right`, () => { + $parent.css({ + left: `${window.innerWidth}px` + }); + controller.show($parent[0]); + let rect = element.getBoundingClientRect(); + + expect(controller.margin).toBeLessThan(rect.top); + expect(window.innerWidth - controller.margin).toEqual(rect.right); + }); + + it(`should reallocate tooltip on center`, () => { + $parent.css({ + top: `${window.window.innerHeight / 2}px`, + left: `${window.window.innerWidth / 2}px` + }); + controller.show($parent[0]); + let rect = element.getBoundingClientRect(); + + expect(window.innerHeight / 2).toBeLessThan(rect.top); + expect(window.innerWidth / 2).toBeGreaterThan(rect.left); + }); + }); +}); diff --git a/front/core/components/treeview/child.html b/front/core/components/treeview/child.html new file mode 100644 index 000000000..25e5f965b --- /dev/null +++ b/front/core/components/treeview/child.html @@ -0,0 +1,20 @@ +
    + + +
    +
    + + + + +
    +
    diff --git a/front/core/components/treeview/child.js b/front/core/components/treeview/child.js new file mode 100644 index 000000000..9e4edef35 --- /dev/null +++ b/front/core/components/treeview/child.js @@ -0,0 +1,61 @@ +import ngModule from '../../module'; + +class Controller { + constructor($element, $scope, $compile) { + this.$scope = $scope; + this.$compile = $compile; + this.element = $element[0]; + + this.element.$ctrl = this; + this.element.droppable = true; + this.dropCount = 0; + this.element.classList.add('vn-droppable'); + } + + $onInit() { + const transcludeElement = this.element.querySelector('.content'); + const content = angular.element(transcludeElement); + + if (this.item.parent) { + this.treeview.$transclude(($clone, $scope) => { + this.$contentScope = $scope; + $scope.item = this.item; + content.append($clone); + }); + + this.element.draggable = true; + this.element.classList.add('vn-draggable'); + } else { + let template = `{{$ctrl.treeview.rootLabel}}`; + let $clone = this.$compile(template)(this.$scope); + content.append($clone); + } + } + + $onDestroy() { + if (this.$contentScope) + this.$contentScope.$destroy(); + } + + dragEnter() { + this.dropCount++; + + if (element != this.dropping) { + this.undrop(); + if (element) element.classList.add('dropping'); + this.dropping = element; + } + } +} +Controller.$inject = ['$element', '$scope', '$compile']; + +ngModule.component('vnTreeviewChild', { + template: require('./child.html'), + controller: Controller, + bindings: { + item: '<' + }, + require: { + treeview: '^vnTreeview' + } +}); diff --git a/front/core/components/treeview/childs.html b/front/core/components/treeview/childs.html new file mode 100644 index 000000000..39d14c134 --- /dev/null +++ b/front/core/components/treeview/childs.html @@ -0,0 +1,11 @@ + +
      +
    • + + + + +
    • +
    \ No newline at end of file diff --git a/front/core/components/treeview/childs.js b/front/core/components/treeview/childs.js new file mode 100644 index 000000000..03ae30233 --- /dev/null +++ b/front/core/components/treeview/childs.js @@ -0,0 +1,15 @@ +import ngModule from '../../module'; + +class Controller {} + +ngModule.component('vnTreeviewChilds', { + template: require('./childs.html'), + controller: Controller, + bindings: { + items: '<', + parent: ' + diff --git a/front/core/components/treeview/index.js b/front/core/components/treeview/index.js new file mode 100644 index 000000000..b39ff7b46 --- /dev/null +++ b/front/core/components/treeview/index.js @@ -0,0 +1,265 @@ +import ngModule from '../../module'; +import Component from '../../lib/component'; +import './style.scss'; +import './childs'; +import './child'; + +/** + * Treeview + */ +export default class Treeview extends Component { + constructor($element, $scope, $transclude, $window) { + super($element, $scope); + this.$transclude = $transclude; + this.$window = $window; + this.readOnly = true; + + this.element.addEventListener('dragstart', + event => this.dragStart(event)); + this.element.addEventListener('dragend', + event => this.dragEnd(event)); + + this.element.addEventListener('dragover', + event => this.dragOver(event)); + this.element.addEventListener('drop', + event => this.drop(event)); + this.element.addEventListener('dragenter', + event => this.dragEnter(event)); + this.element.addEventListener('dragleave', + event => this.dragLeave(event)); + + this.dropCount = 0; + } + + undrop() { + if (!this.dropping) return; + this.dropping.classList.remove('dropping'); + this.dropping = null; + } + + findDroppable(event) { + let element = event.target; + while (element != this.element && !element.droppable) + element = element.parentNode; + if (element == this.element) + return null; + return element; + } + + dragOver(event) { + this.dragClientY = event.clientY; + + // Prevents page reload + event.preventDefault(); + } + + onDragInterval() { + if (this.dragClientY > 0 && this.dragClientY < 75) + this.$window.scrollTo(0, this.$window.scrollY - 25); + } + + dragStart(event) { + event.target.classList.add('dragging'); + event.dataTransfer.setData('text', event.target.id); + + const element = this.findDroppable(event); + this.dragging = element; + + this.interval = setInterval(() => this.onDragInterval(), 100); + } + + dragEnd(event) { + event.target.classList.remove('dragging'); + this.undrop(); + this.dropCount = 0; + this.dragging = null; + clearInterval(this.interval); + } + + dragEnter(event) { + let element = this.findDroppable(event); + if (element) this.dropCount++; + + if (element != this.dropping) { + this.undrop(); + if (element) element.classList.add('dropping'); + this.dropping = element; + } + } + + dragLeave(event) { + let element = this.findDroppable(event); + + if (element) { + this.dropCount--; + if (this.dropCount == 0) this.undrop(); + } + } + + drop(event) { + event.preventDefault(); + this.element.classList.remove('dropping'); + + const $dropped = this.dropping.$ctrl.item; + const $dragged = this.dragging.$ctrl.item; + + if ($dropped != $dragged.parent) + this.emit('drop', {$dropped, $dragged}); + } + + get data() { + return this._data; + } + + set data(value) { + this._data = value; + + const sons = value.length; + const rootElement = [{ + childs: value, + active: true, + sons: sons + }]; + + this.setParent(rootElement[0], value); + + this.items = rootElement; + } + + fetch() { + return this.fetchFunc().then(res => + this.data = res + ); + } + + setParent(parent, childs) { + childs.forEach(child => { + child.parent = parent; + + if (child.childs) + this.setParent(parent, child.childs); + }); + } + + onToggle(event, item) { + let ignoreEvent = event.defaultPrevented + || event == this.lastActionEvent + || !item.sons; + if (ignoreEvent) return; + + if (item.active) + this.fold(item); + else + this.unfold(item); + } + + fold(item) { + item.childs = undefined; + item.active = false; + } + + unfold(item) { + return this.fetchFunc({$item: item}).then(newData => { + this.setParent(item, newData); + + const childs = item.childs; + if (childs) { + childs.forEach(child => { + let index = newData.findIndex(newChild => { + return newChild.id == child.id; + }); + newData[index] = child; + }); + } + + if (this.sortFunc) { + item.childs = newData.sort((a, b) => + this.sortFunc({$a: a, $b: b}) + ); + } + }).then(() => item.active = true); + } + + onRemove(event, item) { + this.lastActionEvent = event; + if (this.removeFunc) + this.removeFunc({$item: item}); + } + + remove(item) { + const parent = item.parent; + let childs = parent.childs; + + if (!childs) childs = []; + + let index = childs.indexOf(item); + childs.splice(index, 1); + if (parent) parent.sons--; + } + + onCreate(event, parent) { + this.lastActionEvent = event; + if (this.createFunc) + this.createFunc({$parent: parent}); + } + + create(item) { + const parent = item.parent; + let childs = parent.childs; + if (!childs) childs = []; + + if (!parent.active) + this.unfold(parent); + else + childs.push(item); + + if (this.sortFunc) { + childs = childs.sort((a, b) => + this.sortFunc({$a: a, $b: b}) + ); + } + + if (parent) parent.sons++; + } + + move(item, newParent) { + if (newParent == item) return; + + if (item.parent) { + const parent = item.parent; + const childs = parent.childs; + const index = childs.indexOf(item); + parent.sons--; + + childs.splice(index, 1); + } + + item.parent = newParent; + + if (!newParent.active) { + this.unfold(newParent).then(() => { + item.parent.sons++; + }); + } else + this.create(item); + } +} + +Treeview.$inject = ['$element', '$scope', '$transclude', '$window']; + +ngModule.component('vnTreeview', { + template: require('./index.html'), + controller: Treeview, + bindings: { + rootLabel: '@', + data: ' { + let controller; + let $element; + + beforeEach(ngModule('vnCore')); + + beforeEach(inject(($compile, $rootScope) => { + $element = $compile(``)($rootScope); + controller = $element.controller('vnTreeview'); + + const promise = new Promise(() => { + return {name: 'My item'}; + }); + + controller.fetchFunc = () => { + return promise; + }; + + controller.createFunc = () => { + return promise; + }; + + controller.removeFunc = () => { + return promise; + }; + + controller.sortFunc = () => { + return promise; + }; + })); + + afterEach(() => { + $element.remove(); + }); + + // See how to test DOM element in Jest + xdescribe('undrop()', () => { + it(`should reset all drop events and properties`, () => { + controller.dropping = angular.element(``); + spyOn(controller.dropping.classList, 'remove'); + + controller.undrop(); + + expect(controller.dropping).toBeNull(); + }); + }); + + describe('dragOver()', () => { + it(`should set the dragClientY property`, () => { + const event = new Event('dragover'); + event.clientY = 100; + + controller.dragOver(event); + + expect(controller.dragClientY).toEqual(100); + }); + }); + + describe('data() setter', () => { + it(`should set the items property nested into a root element`, () => { + const items = [{name: 'Item1'}, {name: 'Item2'}]; + controller.data = items; + + const rootItem = controller.items[0]; + + expect(rootItem.childs).toEqual(items); + }); + }); + + describe('fetch()', () => { + it(`should call the fetchFunc() method`, () => { + spyOn(controller, 'fetchFunc').and.returnValue( + new Promise(resolve => resolve([{name: 'My item'}])) + ); + controller.fetch().then(() => { + expect(controller.data).toBeDefined(); + }); + + expect(controller.fetchFunc).toHaveBeenCalledWith(); + }); + }); + + describe('setParent()', () => { + it(`should set the parent property recursively to each element of an item list`, () => { + spyOn(controller, 'setParent').and.callThrough(); + const items = [{name: 'Item1'}, {name: 'Item2', childs: [ + {name: 'Item3'} + ]}]; + const rootItem = {name: 'Nested tree', sons: items}; + controller.setParent(rootItem, items); + + expect(items[0].parent).toEqual(rootItem); + expect(items[1].parent).toEqual(rootItem); + expect(controller.setParent).toHaveBeenCalledWith(rootItem, items[1].childs); + }); + }); + + describe('onToggle()', () => { + it(`should call the fold() or unfold() methods`, () => { + spyOn(controller, 'fold'); + spyOn(controller, 'unfold'); + + let event = new MouseEvent('click', { + bubbles: true, + cancelable: true, + view: window + }); + const item = {name: 'My item', sons: 1}; + + controller.onToggle(event, item); + item.active = true; + controller.onToggle(event, item); + + expect(controller.unfold).toHaveBeenCalledWith(item); + expect(controller.fold).toHaveBeenCalledWith(item); + }); + }); + + describe('fold()', () => { + it(`should remove the childs and set the active property to false`, () => { + const item = {name: 'My item', childs: [{name: 'Item 1'}], active: true}; + + controller.fold(item); + + expect(item.childs).toBeUndefined(); + expect(item.active).toBeFalsy(); + }); + }); + + describe('unfold()', () => { + it(`should unfold a parent item`, () => { + const expectedResponse = [{name: 'Item 1'}, {name: 'Item 2'}]; + spyOn(controller, 'fetchFunc').and.returnValue( + new Promise(resolve => resolve(expectedResponse)) + ); + spyOn(controller, 'setParent'); + spyOn(controller, 'sortFunc'); + const parent = {name: 'My item', sons: 1}; + const child = {name: 'Item 1'}; + child.parent = parent; + parent.childs = [child]; + + controller.unfold(parent).then(() => { + expect(controller.fetchFunc).toHaveBeenCalledWith({$item: parent}); + expect(controller.setParent).toHaveBeenCalledWith(parent, expectedResponse); + expect(controller.sortFunc).toHaveBeenCalledWith(jasmine.any(Object)); + expect(parent.active).toBeTruthy(); + }); + }); + }); + + describe('onRemove()', () => { + it(`should call the removeFunc() method`, () => { + let event = new MouseEvent('click', { + bubbles: true, + cancelable: true, + view: window + }); + + spyOn(controller, 'removeFunc'); + const item = {name: 'My item'}; + controller.onRemove(event, item); + + expect(controller.removeFunc).toHaveBeenCalledWith({$item: item}); + }); + }); + + describe('remove()', () => { + it(`should remove a child element`, () => { + const parent = {name: 'My item', sons: 1}; + const child = {name: 'Item 1'}; + child.parent = parent; + parent.childs = [child]; + + controller.remove(child); + + expect(parent.childs).toEqual([]); + expect(parent.sons).toEqual(0); + }); + }); + + describe('onCreate()', () => { + it(`should call the createFunc() method`, () => { + let event = new MouseEvent('click', { + bubbles: true, + cancelable: true, + view: window + }); + + spyOn(controller, 'createFunc'); + const parent = {name: 'My item'}; + controller.onCreate(event, parent); + + expect(controller.createFunc).toHaveBeenCalledWith({$parent: parent}); + }); + }); + + describe('create()', () => { + it(`should unfold an inactive parent and then create a child`, () => { + spyOn(controller, 'unfold'); + spyOn(controller, 'sortFunc'); + const parent = {name: 'My item', sons: 2, childs: [ + {name: 'Item 1'}, + {name: 'Item 2'} + ]}; + const child = {name: 'Item 3'}; + child.parent = parent; + parent.childs.push(child); + + controller.create(child); + + expect(parent.sons).toEqual(3); + expect(controller.unfold).toHaveBeenCalledWith(parent); + expect(controller.sortFunc).toHaveBeenCalledWith(jasmine.any(Object)); + expect(controller.sortFunc).toHaveBeenCalledTimes(2); + }); + + it(`should create a child on an active parent`, () => { + spyOn(controller, 'unfold'); + spyOn(controller, 'sortFunc'); + const parent = {name: 'My item', sons: 2, childs: [ + {name: 'Item 1'}, + {name: 'Item 2'} + ], active: true}; + const child = {name: 'Item 3'}; + child.parent = parent; + + controller.create(child); + + expect(parent.sons).toEqual(3); + expect(controller.unfold).not.toHaveBeenCalledWith(parent); + expect(controller.sortFunc).toHaveBeenCalledWith(jasmine.any(Object)); + expect(controller.sortFunc).toHaveBeenCalledTimes(2); + }); + }); + + describe('move()', () => { + it(`should move an item to anocher parent and then unfold the parent`, () => { + spyOn(controller, 'unfold').and.returnValue( + new Promise(resolve => resolve()) + ); + const newParent = {name: 'My item 2', sons: 0}; + const parent = {name: 'My item', sons: 3, childs: [ + {name: 'Item 1'}, + {name: 'Item 2'} + ]}; + const child = {name: 'Item 3'}; + child.parent = parent; + parent.childs.push(child); + + controller.move(child, newParent); + + expect(parent.sons).toEqual(2); + expect(controller.unfold).toHaveBeenCalledWith(newParent); + }); + + it(`should move an item to anocher parent`, () => { + spyOn(controller, 'unfold'); + spyOn(controller, 'create'); + const newParent = {name: 'My item 2', sons: 0, active: true}; + const parent = {name: 'My item', sons: 3, childs: [ + {name: 'Item 1'}, + {name: 'Item 2'} + ]}; + const child = {name: 'Item 3'}; + child.parent = parent; + parent.childs.push(child); + + controller.move(child, newParent); + + expect(parent.sons).toEqual(2); + expect(controller.unfold).not.toHaveBeenCalledWith(newParent); + }); + }); +}); diff --git a/front/core/components/treeview/style.scss b/front/core/components/treeview/style.scss new file mode 100644 index 000000000..7cd8c8bea --- /dev/null +++ b/front/core/components/treeview/style.scss @@ -0,0 +1,57 @@ +@import "effects"; + +vn-treeview-childs { + display: block; + + ul { + padding: 0; + margin: 0; + + li { + list-style: none; + + ul { + padding-left: 2.2em; + } + } + } + + vn-icon-button { + display: table-cell; + vertical-align: middle; + padding: 0; + } + + .node > .buttons { + display: none + } + + .node:hover > .buttons { + display: block + } + + .content { + flex-grow: 1 + } +} + +vn-treeview-child { + line-height: 38px; + font-size: 16px; + display: block; + + .node { + @extend %clickable; + display: flex; + padding: 2px; + align-items: center; + } + & > div > .arrow { + min-width: 24px; + margin-right: 10px; + transition: transform 200ms; + } + &.expanded > div > .arrow { + transform: rotate(180deg); + } +} \ No newline at end of file diff --git a/client/core/src/components/watcher/locale/es.yml b/front/core/components/watcher/locale/es.yml similarity index 100% rename from client/core/src/components/watcher/locale/es.yml rename to front/core/components/watcher/locale/es.yml diff --git a/front/core/components/watcher/watcher.html b/front/core/components/watcher/watcher.html new file mode 100644 index 000000000..c3c54a65d --- /dev/null +++ b/front/core/components/watcher/watcher.html @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/front/core/components/watcher/watcher.js b/front/core/components/watcher/watcher.js new file mode 100644 index 000000000..ddef745fd --- /dev/null +++ b/front/core/components/watcher/watcher.js @@ -0,0 +1,265 @@ +import ngModule from '../../module'; +import Component from '../../lib/component'; +import getModifiedData from '../../lib/modified'; +import copyObject from '../../lib/copy'; +import isEqual from '../../lib/equals'; +import isFullEmpty from '../../lib/full-empty'; +import UserError from '../../lib/user-error'; + +/** + * Component that checks for changes on a specific model property and + * asks the user to save or discard it when the state changes. + * Also it can save the data to the server when the @url and @idField + * properties are provided. + */ +export default class Watcher extends Component { + constructor($element, $, $state, $stateParams, $transitions, $http, vnApp, $translate, $attrs, $q) { + super($element); + Object.assign(this, { + $, + $state, + $stateParams, + $http, + _: $translate, + $attrs, + vnApp, + $q + }); + + this.state = null; + this.deregisterCallback = $transitions.onStart({}, + transition => this.callback(transition)); + this.updateOriginalData(); + } + + $onInit() { + if (this.get && this.url) + this.fetchData(); + else if (this.get && !this.url) + throw new Error('URL parameter ommitted'); + } + + $onChanges() { + if (this.data) + this.updateOriginalData(); + } + + $onDestroy() { + this.deregisterCallback(); + } + + get dirty() { + return this.form && this.form.$dirty || this.dataChanged(); + } + + dataChanged() { + let data = this.copyInNewObject(this.data); + return !isEqual(data, this.orgData); + } + + fetchData() { + let id = this.data[this.idField]; + return this.$http.get(`${this.url}/${id}`).then( + json => { + this.data = copyObject(json.data); + this.updateOriginalData(); + } + ); + } + + /** + * Submits the data and goes back in the history. + * + * @return {Promise} The request promise + */ + submitBack() { + return this.submit().then(res => { + this.window.history.back(); + return res; + }); + } + + /** + * Submits the data and goes another state. + * + * @param {String} state The state name + * @param {Object} params The request params + * @return {Promise} The request promise + */ + submitGo(state, params) { + return this.submit().then(res => { + this.$state.go(state, params || {}); + return res; + }); + } + + /** + * Submits the data to the server. + * + * @return {Promise} The http request promise + */ + submit() { + try { + this.check(); + } catch (err) { + return this.$q.reject(err); + } + + return this.realSubmit().then(res => { + this.notifySaved(); + return res; + }); + } + + /** + * Submits the data without checking data validity or changes. + * + * @return {Promise} The http request promise + */ + realSubmit() { + if (this.form) + this.form.$setSubmitted(); + + if (!this.dataChanged()) { + this.updateOriginalData(); + return this.$q.resolve(); + } + + let isPost = (this.$attrs.save && this.$attrs.save.toLowerCase() === 'post'); + let changedData = isPost + ? this.data + : getModifiedData(this.data, this.orgData); + + let id = this.idField ? this.orgData[this.idField] : null; + + // If watcher is associated to mgCrud + + if (this.save && this.save.accept) { + if (id) + changedData[this.idField] = id; + + this.save.model = changedData; + return this.$q((resolve, reject) => { + this.save.accept().then( + json => this.writeData({data: json}, resolve), + reject + ); + }); + } + + // When mgCrud is not used + + if (id) { + return this.$q((resolve, reject) => { + this.$http.patch(`${this.url}/${id}`, changedData).then( + json => this.writeData(json, resolve), + reject + ); + }); + } + + + return this.$q((resolve, reject) => { + this.$http.post(this.url, changedData).then( + json => this.writeData(json, resolve), + reject + ); + }); + } + + /** + * Checks if data is ready to send. + */ + check() { + if (this.form && this.form.$invalid) + throw new UserError('Some fields are invalid'); + if (!this.dirty) + throw new UserError('No changes to save'); + } + + /** + * Notifies the user that the data has been saved. + */ + notifySaved() { + this.vnApp.showSuccess(this.$t('Data saved!')); + } + + setPristine() { + if (this.form) this.form.$setPristine(); + } + + setDirty() { + if (this.form) this.form.$setDirty(); + } + + callback(transition) { + if (!this.state && this.dirty) { + this.state = transition.to().name; + this.$.confirm.show(); + return false; + } + + return true; + } + + onConfirmResponse(response) { + if (response === 'accept') { + if (this.data) + Object.assign(this.data, this.orgData); + this.$state.go(this.state); + } else + this.state = null; + } + + writeData(json, resolve) { + Object.assign(this.data, json.data); + this.updateOriginalData(); + resolve(json); + } + + updateOriginalData() { + this.orgData = this.copyInNewObject(this.data); + this.setPristine(); + } + + loadOriginalData() { + const orgData = JSON.parse(JSON.stringify(this.orgData)); + this.data = Object.assign(this.data, orgData); + this.setPristine(); + } + + copyInNewObject(data) { + let newCopy = {}; + if (data && typeof data === 'object') { + Object.keys(data).forEach( + key => { + let value = data[key]; + if (value instanceof Date) + newCopy[key] = new Date(value.getTime()); + else if (!isFullEmpty(value)) { + if (typeof value === 'object') + newCopy[key] = this.copyInNewObject(value); + else + newCopy[key] = value; + } + } + ); + } + + return newCopy; + } +} +Watcher.$inject = ['$element', '$scope', '$state', '$stateParams', '$transitions', '$http', 'vnApp', '$translate', '$attrs', '$q']; + +ngModule.component('vnWatcher', { + template: require('./watcher.html'), + bindings: { + url: '@?', + idField: '@?', + data: '<', + form: '<', + save: '<', + get: ' { + let $scope; + let $element; + let $state; + let $httpBackend; + let controller; + let $attrs; + let $q; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_, _$state_, _$q_) => { + $scope = $rootScope.$new(); + $element = angular.element('
    '); + $state = _$state_; + $q = _$q_; + $httpBackend = _$httpBackend_; + $attrs = { + save: 'patch' + }; + controller = $componentController('vnWatcher', {$scope, $element, $state, $httpBackend, $attrs, $q}); + })); + + describe('$onInit()', () => { + it(`should call fetchData() if controllers get and url properties are defined`, () => { + controller.get = () => {}; + controller.url = 'test.com'; + spyOn(controller, 'fetchData'); + controller.$onInit(); + + expect(controller.fetchData).toHaveBeenCalledWith(); + }); + + it(`should throw an error if $onInit is called without url defined`, () => { + controller.get = () => {}; + + expect(function() { + controller.$onInit(); + }).toThrowError(/parameter/); + }); + }); + + describe('fetchData()', () => { + it(`should perform a query then store the received data into controller.data and call updateOriginalData()`, () => { + spyOn(controller, 'updateOriginalData'); + let json = {data: 'some data'}; + controller.data = [1]; + controller.idField = 0; + controller.url = 'test.com'; + $httpBackend.whenGET('test.com/1').respond(json); + $httpBackend.expectGET('test.com/1'); + controller.fetchData(); + $httpBackend.flush(); + + expect(controller.data).toEqual({data: 'some data'}); + expect(controller.updateOriginalData).toHaveBeenCalledWith(); + }); + }); + + describe('submitBack()', () => { + it(`should call controller.window.history.back() function after calling controllers submit() function`, done => { + spyOn(controller, 'submit').and.returnValue(Promise.resolve()); + spyOn(controller.window.history, 'back'); + controller.submitBack() + .then(() => { + expect(controller.submit).toHaveBeenCalledWith(); + expect(controller.window.history.back).toHaveBeenCalledWith(); + done(); + }).catch(done.fail); + }); + }); + + describe('submitGo()', () => { + it(`should call controller.$state.go() function after calling controllers submit() function`, done => { + spyOn(controller, 'submit').and.returnValue(Promise.resolve()); + spyOn(controller.$state, 'go'); + let state = 'the.State'; + controller.submitGo(state) + .then(() => { + expect(controller.submit).toHaveBeenCalledWith(); + expect(controller.$state.go).toHaveBeenCalledWith(state, {}); + done(); + }).catch(done.fail); + }); + }); + + describe('check()', () => { + it(`should throw error if controller.form is invalid`, () => { + controller.form = {$invalid: true}; + + expect(function() { + controller.check(); + }).toThrowError(); + }); + + it(`should throw error if controller.dirty is true`, () => { + controller.form = {$invalid: true}; + + expect(function() { + controller.check(); + }).toThrowError(); + }); + }); + + describe('realSubmit()', () => { + describe('when controller.form', () => { + it(`should call controller.form.setSubmited if controller.form is defined`, () => { + controller.form = { + $setSubmitted: () => {}, + $setPristine: () => {} + }; + spyOn(controller.form, '$setSubmitted'); + controller.realSubmit(); + + expect(controller.form.$setSubmitted).toHaveBeenCalledWith(); + }); + }); + + describe('when controller.save()', () => { + it(`should set controller.save.model property`, () => { + controller.save = {accept: () => $q.resolve()}; + controller.data = {originalInfo: 'original data', info: 'new data'}; + controller.orgData = {originalInfo: 'original data'}; + controller.realSubmit(); + + expect(controller.save.model).toEqual({info: 'new data'}); + }); + }); + + describe('when id is defined', () => { + it(`should perform a query then call controller.writeData()`, done => { + controller.dataChanged = () => { + return true; + }; + controller.data = {id: 2}; + controller.orgData = {id: 1}; + let changedData = getModifiedData(controller.data, controller.orgData); + controller.idField = 'id'; + controller.url = 'test.com'; + let json = {data: 'some data'}; + spyOn(controller, 'writeData').and.callThrough(); + $httpBackend.whenPATCH(`${controller.url}/1`, changedData).respond(json); + $httpBackend.expectPATCH(`${controller.url}/1`); + controller.realSubmit() + .then(() => { + expect(controller.writeData).toHaveBeenCalledWith(jasmine.any(Object), jasmine.any(Function)); + done(); + }).catch(done.fail); + $httpBackend.flush(); + }); + }); + + it(`should perform a POST query then call controller.writeData()`, done => { + controller.dataChanged = () => { + return true; + }; + controller.data = {id: 2}; + controller.orgData = {id: 1}; + controller.url = 'test.com'; + let json = {data: 'some data'}; + spyOn(controller, 'writeData').and.callThrough(); + $httpBackend.whenPOST(`${controller.url}`, controller.data).respond(json); + $httpBackend.expectPOST(`${controller.url}`, controller.data); + controller.realSubmit() + .then(() => { + expect(controller.writeData).toHaveBeenCalledWith(jasmine.any(Object), jasmine.any(Function)); + done(); + }).catch(done.fail); + $httpBackend.flush(); + }); + }); + + describe('writeData()', () => { + it(`should call Object.asssign() function over controllers.data with json.data, then call updateOriginalData function and finally call resolve() function`, () => { + spyOn(controller, 'updateOriginalData'); + controller.data = {}; + let json = {data: 'some data'}; + let resolve = jasmine.createSpy('resolve'); + controller.writeData(json, resolve); + + expect(controller.updateOriginalData).toHaveBeenCalledWith(); + expect(resolve).toHaveBeenCalledWith(json); + }); + }); + + describe('callback()', () => { + describe(`when dataChanged() returns true and there's no state in the controller`, () => { + it(`should define controller.state, call controller.$.confirm.show() and return false`, () => { + $scope.confirm = {show: jasmine.createSpy('show')}; + controller.dataChanged = () => { + return true; + }; + controller.state = undefined; + let transition = {to: () => { + return {name: 'Batman'}; + }}; + let result = controller.callback(transition); + + expect(controller.state).toEqual('Batman'); + expect(controller.$.confirm.show).toHaveBeenCalledWith(); + expect(result).toBeFalsy(); + }); + }); + + describe(`when dataChanged() returns false and/or there's a state in the controller`, () => { + it(`should return true`, () => { + $scope.confirm = {show: jasmine.createSpy('show')}; + controller.dataChanged = () => { + return false; + }; + controller.state = 'the state'; + let transition = {to: () => { + return {name: 'Batman'}; + }}; + let result = controller.callback(transition); + + expect(result).toBeTruthy(); + }); + }); + }); + + describe(`onConfirmResponse()`, () => { + describe(`when response is accept`, () => { + it(`should call Object.assing on controlle.data with controller.orgData then call go() on state`, () => { + let response = 'accept'; + controller.data = {}; + controller.orgData = {name: 'Batman'}; + controller.$state = {go: jasmine.createSpy('go')}; + controller.state = 'Batman'; + controller.onConfirmResponse(response); + + expect(controller.data).toEqual(controller.orgData); + expect(controller.$state.go).toHaveBeenCalledWith(controller.state); + }); + }); + + describe(`when response is not accept`, () => { + it(`should set controller.state to null`, () => { + let response = 'anything but accept'; + controller.state = 'Batman'; + controller.onConfirmResponse(response); + + expect(controller.state).toBeFalsy(); + }); + }); + }); + + describe(`loadOriginalData()`, () => { + it(`should iterate over the current data object, delete all properties then assign the ones from original data`, () => { + controller.data = {name: 'Bruce'}; + controller.orgData = {name: 'Batman'}; + controller.loadOriginalData(); + + expect(controller.data).toEqual(controller.orgData); + }); + }); +}); diff --git a/front/core/components/wday-picker/index.html b/front/core/components/wday-picker/index.html new file mode 100644 index 000000000..4262431e6 --- /dev/null +++ b/front/core/components/wday-picker/index.html @@ -0,0 +1,8 @@ + + + {{day.localeChar}} + \ No newline at end of file diff --git a/front/core/components/wday-picker/index.js b/front/core/components/wday-picker/index.js new file mode 100644 index 000000000..94a6d424c --- /dev/null +++ b/front/core/components/wday-picker/index.js @@ -0,0 +1,24 @@ +import ngModule from '../../module'; +import FormInput from '../form-input'; +import './style.scss'; + +export default class WdayPicker extends FormInput { + constructor($element, $scope, vnWeekDays) { + super($element, $scope); + this.days = vnWeekDays.locales; + this.initTabIndex(); + } + + toggleDay(index) { + let field = this.field; + if (!field) field = []; + field[index] = !field[index]; + this.change(field); + } +} +WdayPicker.$inject = ['$element', '$scope', 'vnWeekDays']; + +ngModule.vnComponent('vnWdayPicker', { + template: require('./index.html'), + controller: WdayPicker +}); diff --git a/front/core/components/wday-picker/style.scss b/front/core/components/wday-picker/style.scss new file mode 100644 index 000000000..be610c733 --- /dev/null +++ b/front/core/components/wday-picker/style.scss @@ -0,0 +1,27 @@ +@import "effects"; + +.vn-wday-picker { + text-align: center; + + &:focus { + outline: solid 1px rgba(0, 0, 0, .1); + } + & > span { + @extend %clickable; + border-radius: 50%; + padding: .4em; + margin: .2em; + display: inline-flex; + width: 1.5em; + height: 1.5em; + justify-content: center; + align-items: center; + outline: none; + background-color: rgba(0, 0, 0, .05); + + &.marked { + background: $color-button; + color: $color-font-dark; + } + } +} \ No newline at end of file diff --git a/front/core/directives/acl.js b/front/core/directives/acl.js new file mode 100644 index 000000000..1cebddd42 --- /dev/null +++ b/front/core/directives/acl.js @@ -0,0 +1,41 @@ +import ngModule from '../module'; +import FormInput from '../components/form-input'; + +function vnAcl(aclService) { + let acls = []; + + return { + restrict: 'A', + priority: -1, + link: function(_, $element, $attrs) { + acls = $attrs.vnAcl.split(',').map(i => i.trim()); + + if (acls[0] == '') return; + + let action = $attrs.vnAclAction || 'disable'; + + if (aclService.hasAny(acls)) return; + + if (action === 'disable') { + let element = $element[0]; + let elementToDisable = element.$ctrl; + + if (!(elementToDisable instanceof FormInput)) { + let selector = 'input, textarea, button, submit'; + + if (!element.matches(selector)) + element = element.querySelector(selector); + + elementToDisable = element; + } + + if (elementToDisable) + elementToDisable.disabled = true; + } else + $element.remove(); + } + }; +} +vnAcl.$inject = ['aclService']; + +ngModule.directive('vnAcl', vnAcl); diff --git a/front/core/directives/bind.js b/front/core/directives/bind.js new file mode 100644 index 000000000..409c78f32 --- /dev/null +++ b/front/core/directives/bind.js @@ -0,0 +1,60 @@ +import ngModule from '../module'; + +directive.$inject = ['$document']; +export function directive($document) { + let modifiers = ['alt', 'ctrl', 'meta', 'shift']; + + function checkAttributes($attrs) { + let shortcut = $attrs.vnBind.split(' '); + let keys = {}; + + if (shortcut[0] == '') + throw new Error('vnBind: Binding keys not defined'); + + if (shortcut.length == 1) { + keys.altKey = true; + keys.ctrlKey = true; + } else { + let mods = shortcut.splice(0, shortcut.length - 1); + for (let mod of mods) { + if (modifiers.indexOf(mod) == -1) + throw new Error('vnBind: Invalid modifier key in binding'); + + keys[`${mod}Key`] = true; + } + } + + keys.key = shortcut[0]; + if (keys.key == 'space') keys.key = ' '; + + return keys; + } + + return { + restrict: 'A', + link: function($scope, $element, $attrs) { + let shortcut = checkAttributes($attrs); + + function onKeyUp(event) { + if (event.defaultPrevented) return; + let correctShortcut = true; + + for (const key in shortcut) { + correctShortcut = correctShortcut + && shortcut[key] == event[key]; + } + if (correctShortcut) { + event.preventDefault(); + $element.triggerHandler('click'); + } + } + + $document.on('keyup', onKeyUp); + $element.on('$destroy', function() { + $document.off('keyup', onKeyUp); + }); + } + }; +} +ngModule.directive('vnBind', directive); + diff --git a/front/core/directives/dialog.js b/front/core/directives/dialog.js new file mode 100644 index 000000000..167bd04e7 --- /dev/null +++ b/front/core/directives/dialog.js @@ -0,0 +1,25 @@ +import ngModule from '../module'; +import Dialog from '../components/dialog'; +import {kebabToCamel} from '../lib/string'; + +/** + * Registers a click handler on the element that opens the dialog id + * specified as value. + * + * @return {Object} The directive + */ +export default function directive() { + return { + restrict: 'A', + link: function($scope, $element, $attrs) { + $element.on('click', function(event) { + if (event.defaultPrevented) return; + let dialogKey = kebabToCamel($attrs.vnDialog); + let dialog = $scope[dialogKey]; + if (dialog instanceof Dialog) + dialog.show(); + }); + } + }; +} +ngModule.directive('vnDialog', directive); diff --git a/front/core/directives/droppable.js b/front/core/directives/droppable.js new file mode 100644 index 000000000..929b64be7 --- /dev/null +++ b/front/core/directives/droppable.js @@ -0,0 +1,43 @@ +import ngModule from '../module'; +import './droppable.scss'; + +class Controller { + constructor($element, $, $attrs) { + this.element = $element[0]; + this.$ = $; + this.$attrs = $attrs; + + this.element.addEventListener('dragover', + event => event.preventDefault()); // Prevents page reload + this.element.addEventListener('drop', + event => this.drop(event)); + this.element.addEventListener('dragenter', + event => this.dragEnter(event)); + this.element.addEventListener('dragleave', + event => this.dragLeave(event)); + } + + dragEnter(event) { + this.droppedElement = event.target; + this.element.classList.add('dropping'); + } + + dragLeave(event) { + if (this.droppedElement === event.target) + this.element.classList.remove('dropping'); + } + + drop(event) { + if (event.defaultPrevented) return; + event.preventDefault(); + this.element.classList.remove('dropping'); + this.$.$eval(this.$attrs.vnDroppable, {$event: event}); + } +} +Controller.$inject = ['$element', '$scope', '$attrs']; + +ngModule.directive('vnDroppable', () => { + return { + controller: Controller + }; +}); diff --git a/front/core/directives/droppable.scss b/front/core/directives/droppable.scss new file mode 100644 index 000000000..97e6f8a19 --- /dev/null +++ b/front/core/directives/droppable.scss @@ -0,0 +1,25 @@ +@import "./variables"; + + +.vn-droppable, +.vn-draggable, +[vn-droppable] { + border: 2px dashed transparent; + border-radius: 0.5em; + transition: all 0.5s; +} + +.vn-droppable, +[vn-droppable] { + display: block; + + &.dropping { + background-color: $color-hover-cd; + border-color: $color-bg-dark; + } +} + +.vn-draggable.dragging { + background-color: $color-main-light; + border-color: $color-main; +} \ No newline at end of file diff --git a/front/core/directives/focus.js b/front/core/directives/focus.js new file mode 100644 index 000000000..869e9a7f0 --- /dev/null +++ b/front/core/directives/focus.js @@ -0,0 +1,45 @@ +import ngModule from '../module'; +import isMobile from '../lib/is-mobile'; + +export function focus($scope, input) { + if (isMobile) return; + + const element = input; + let selector = 'input, textarea, button, submit'; + + if (!input.matches(selector)) + input = input.querySelector(selector); + + if (!input) { + const focusEvent = new MouseEvent('focus', { + bubbles: true, + cancelable: true, + view: window + }); + element.dispatchEvent(focusEvent); + return; + } + + input.focus(); + + if (input.select) { + $scope.$applyAsync(() => { + input.select(); + }); + } +} + +/** + * Sets the focus and selects the text on the input. + * + * @return {Object} The directive + */ +export function directive() { + return { + restrict: 'A', + link: function($scope, $element) { + $scope.$watch('', () => focus($scope, $element[0])); + } + }; +} +ngModule.directive('vnFocus', directive); diff --git a/front/core/directives/http-click.js b/front/core/directives/http-click.js new file mode 100644 index 000000000..5e69d81d1 --- /dev/null +++ b/front/core/directives/http-click.js @@ -0,0 +1,29 @@ +import ngModule from '../module'; + +/** + * Disables a clicked element while request is being processed + * Enables again when promise ends + * + * @param {Object} $parse + * @return {Object} The directive + */ +export function directive($parse) { + return { + restrict: 'A', + link: function($scope, $element, $attrs) { + const cb = $parse($attrs.vnHttpClick); + const element = $element[0]; + $element.on('click', () => { + element.$ctrl.disabled = true; + + cb($scope).finally(() => { + element.$ctrl.disabled = false; + }); + }); + } + }; +} + +directive.$inject = ['$parse']; + +ngModule.directive('vnHttpClick', directive); diff --git a/front/core/directives/http-submit.js b/front/core/directives/http-submit.js new file mode 100644 index 000000000..0cf17866e --- /dev/null +++ b/front/core/directives/http-submit.js @@ -0,0 +1,37 @@ +import ngModule from '../module'; + +/** + * Disables a submitted form while request is being processed + * Enables again when promise ends + * + * @param {Object} $parse + * @return {Object} The directive + */ +export function directive($parse) { + return { + restrict: 'A', + link: function($scope, $element, $attrs) { + const cb = $parse($attrs.vnHttpSubmit); + const element = $element[0]; + $element.on('submit', () => { + const selector = 'vn-textfield, vn-autocomplete, vn-submit'; + const elements = element.querySelectorAll(selector); + const fields = angular.element(elements); + + angular.forEach(fields, field => { + field.$ctrl.disabled = true; + }); + + cb($scope).finally(() => { + angular.forEach(fields, field => { + field.$ctrl.disabled = false; + }); + }); + }); + } + }; +} + +directive.$inject = ['$parse']; + +ngModule.directive('vnHttpSubmit', directive); diff --git a/front/core/directives/id.js b/front/core/directives/id.js new file mode 100644 index 000000000..8230527d6 --- /dev/null +++ b/front/core/directives/id.js @@ -0,0 +1,35 @@ +import ngModule from '../module'; +import {kebabToCamel} from '../lib/string'; + +/** + * Registers the element controller into the scope as a property whose name is + * the directive value transformed to lowerCamelCase. + * + * @return {Object} The directive + */ +export function directive() { + return { + restrict: 'A', + link: function($scope, $element, $attrs) { + let id = kebabToCamel($attrs.vnId); + + if (!id) + throw new Error(`vnId: Attribute can't be null`); + + let $ctrl = $element[0].$ctrl + ? $element[0].$ctrl + : $element.controller($element[0].tagName.toLowerCase()); + let ctrl = $ctrl || $element[0]; + + $scope[id] = ctrl; + + if (!$scope.hasOwnProperty('$ctrl')) { + while ($scope && !$scope.hasOwnProperty('$ctrl')) + $scope = Object.getPrototypeOf($scope); + + if ($scope) $scope[id] = ctrl; + } + } + }; +} +ngModule.directive('vnId', directive); diff --git a/front/core/directives/index.js b/front/core/directives/index.js new file mode 100644 index 000000000..185046a3c --- /dev/null +++ b/front/core/directives/index.js @@ -0,0 +1,16 @@ +import './id'; +import './focus'; +import './dialog'; +import './popover'; +import './rule'; +import './acl'; +import './on-error-src'; +import './zoom-image'; +import './visible-by'; +import './bind'; +import './repeat-last'; +import './title'; +import './uvc'; +import './droppable'; +import './http-click'; +import './http-submit'; diff --git a/services/nginx/static/images/no-image200x200.png b/front/core/directives/no-image.png similarity index 100% rename from services/nginx/static/images/no-image200x200.png rename to front/core/directives/no-image.png diff --git a/front/core/directives/on-error-src.js b/front/core/directives/on-error-src.js new file mode 100644 index 000000000..094064aad --- /dev/null +++ b/front/core/directives/on-error-src.js @@ -0,0 +1,22 @@ +import ngModule from '../module'; +import noImage from './no-image.png'; + +/** + * Sets a default image when there is an error loading + * the original image. + * + * @return {Object} The directive + */ +export default function onErrorSrc() { + return { + restrict: 'A', + link: (scope, element, attrs) => { + let imgError = noImage; + element.bind('error', function() { + if (attrs.src != imgError) + attrs.$set('src', imgError); + }); + } + }; +} +ngModule.directive('onErrorSrc', onErrorSrc); diff --git a/front/core/directives/popover.js b/front/core/directives/popover.js new file mode 100644 index 000000000..5d86665ba --- /dev/null +++ b/front/core/directives/popover.js @@ -0,0 +1,24 @@ +import ngModule from '../module'; +import Popover from '../components/popover'; +import {kebabToCamel} from '../lib/string'; + +/** + * Directive used to open a popover. + * + * @return {Object} The directive + */ +export function directive() { + return { + restrict: 'A', + link: function($scope, $element, $attrs) { + $element.on('click', function(event) { + if (event.defaultPrevented) return; + let popoverKey = kebabToCamel($attrs.vnPopover); + let popover = $scope[popoverKey]; + if (popover instanceof Popover) + popover.show($element[0]); + }); + } + }; +} +ngModule.directive('vnPopover', directive); diff --git a/front/core/directives/repeat-last.js b/front/core/directives/repeat-last.js new file mode 100644 index 000000000..504fa5253 --- /dev/null +++ b/front/core/directives/repeat-last.js @@ -0,0 +1,23 @@ +import ngModule from '../module'; + +/** + * Calls a passed function if is the last element from an ng-repeat. + * + * @attribute {String} onLast - Callback function + * @return {Object} The directive + */ +directive.$inject = ['$parse']; +export function directive($parse) { + return { + restrict: 'A', + link: function($scope, $element, $attrs) { + if ($scope.$last && $attrs.onLast) { + let fn = $parse($attrs.onLast); + setTimeout(() => { + fn($scope); + }); + } + } + }; +} +ngModule.directive('vnRepeatLast', directive); diff --git a/front/core/directives/rule.js b/front/core/directives/rule.js new file mode 100644 index 000000000..85b6041f8 --- /dev/null +++ b/front/core/directives/rule.js @@ -0,0 +1,72 @@ +import ngModule from '../module'; +import {validateAll} from '../lib/validator'; +import {firstUpper} from '../lib/string'; + +directive.$inject = ['$translate', '$window']; +export function directive($translate, $window) { + return { + restrict: 'A', + link: link, + require: { + ngModel: 'ngModel', + form: '^^?form' + } + }; + + function link($scope, $element, $attrs, $ctrl) { + let vnValidations = $window.validations; + if (!vnValidations) return; + + if (!/^([A-Z]\w+(\.[a-z]\w*)?)?$/.test($attrs.rule)) + throw new Error(`rule: Attribute must have this syntax: [ModelName[.fieldName]]`); + + let rule = $attrs.rule.split('.'); + let modelName = rule.shift(); + let fieldName = rule.shift(); + + let split = $attrs.ngModel.split('.'); + if (!fieldName) fieldName = split.pop() || null; + if (!modelName) modelName = firstUpper(split.pop() || ''); + + if (!modelName || !fieldName) + throw new Error(`rule: Cannot retrieve model or field attribute`); + + let modelValidations = vnValidations[modelName]; + + if (!modelValidations) + throw new Error(`rule: Model '${modelName}' doesn't exist`); + + let validations = modelValidations.validations[fieldName]; + if (!validations || validations.length == 0) + return; + + let ngModel = $ctrl.ngModel; + let form = $ctrl.form; + let field = $element[0].$ctrl; + let error; + + function refreshError() { + if (!field) return; + let canShow = ngModel.$dirty || (form && form.$submitted); + field.error = error && canShow ? error.message : null; + } + + ngModel.$options.$$options.allowInvalid = true; + ngModel.$validators.entity = value => { + try { + error = null; + validateAll($translate, value, validations); + } catch (e) { + error = e; + } + + refreshError(); + return error == null; + }; + + if (form) + $scope.$watch(form.$submitted, refreshError); + } +} +ngModule.directive('rule', directive); + diff --git a/front/core/directives/specs/acl.spec.js b/front/core/directives/specs/acl.spec.js new file mode 100644 index 000000000..94000d543 --- /dev/null +++ b/front/core/directives/specs/acl.spec.js @@ -0,0 +1,95 @@ +describe('Directive acl', () => { + let $scope; + let $element; + let element; + let compile; + + beforeEach(ngModule('vnCore')); + + beforeEach(inject(($httpBackend, aclService) => { + $httpBackend.whenGET('Accounts/acl') + .respond({ + user: {id: 1, name: 'myUser'}, + roles: [ + {role: {name: 'myRole'}}, + {role: {name: 'myOtherRole'}} + ] + }); + aclService.load(); + $httpBackend.flush(); + })); + + afterEach(() => { + $element.remove(); + $scope.$destroy(); + }); + + compile = html => { + inject(($compile, $rootScope) => { + $scope = $rootScope.$new(); + $element = $compile(html)($scope); + $scope.$digest(); + element = $element[0]; + }); + }; + + it('should not disable the input element as the user owns the role', () => { + let html = ` +
    + +
    + `; + compile(html); + let input = element.querySelector('input'); + + expect(input.disabled).toBeFalsy(); + }); + + it('should disable the element as the action is to disable and the user does not own the role', () => { + let html = ` +
    + +
    + `; + compile(html); + let input = element.querySelector('input'); + + expect(input.disabled).toBeTruthy(); + }); + + it('should keep the element as the action is to remove and the user owns the role', () => { + let html = ` +
    +
    + +
    +
    + `; + compile(html); + let div = element.querySelector('div'); + + expect(div).not.toBeNull(); + }); + + it('should delete the element as the action is to remove and the user does not own the role', () => { + let html = ` +
    +
    + +
    +
    + `; + compile(html); + let div = element.querySelector('div'); + + expect(div).toBeNull(); + }); +}); diff --git a/front/core/directives/specs/bind.spec.js b/front/core/directives/specs/bind.spec.js new file mode 100644 index 000000000..d8d2cb359 --- /dev/null +++ b/front/core/directives/specs/bind.spec.js @@ -0,0 +1,29 @@ +describe('Directive bind', () => { + let compile; + + beforeEach(ngModule('vnCore')); + + compile = html => { + inject(($compile, $rootScope) => { + let $element = $compile(html)($rootScope); + $rootScope.$digest(); + $element.remove(); + }); + }; + + it('should throw an error when the directive atribute is not set', () => { + let html = `
    `; + + expect(() => { + compile(html); + }).toThrow(Error(`vnBind: Binding keys not defined`)); + }); + + it('should throw an error when the command modifier is not valid', () => { + let html = `
    `; + + expect(() => { + compile(html); + }).toThrow(new Error(`vnBind: Invalid modifier key in binding`)); + }); +}); diff --git a/front/core/directives/specs/dialog.spec.js b/front/core/directives/specs/dialog.spec.js new file mode 100644 index 000000000..4d5a02e31 --- /dev/null +++ b/front/core/directives/specs/dialog.spec.js @@ -0,0 +1,33 @@ +describe('Directive dialog', () => { + let $scope; + let $element; + let element; + let compile; + let controller; + + beforeEach(ngModule('vnCore')); + + compile = _element => { + inject(($compile, $rootScope) => { + $scope = $rootScope.$new(); + $scope.myDialog = controller; + element = angular.element(_element); + $compile(element)($scope); + $scope.$digest(); + }); + }; + + beforeEach(angular.mock.inject(($rootScope, $compile) => { + $element = $compile('')($rootScope); + controller = $element.controller('vnDialog'); + })); + + it('should call show() function if dialog is a instance of vnDialog', () => { + let html = `
    `; + spyOn(controller, 'show'); + compile(html); + element[0].click(); + + expect(controller.show).toHaveBeenCalledWith(); + }); +}); diff --git a/front/core/directives/specs/focus.spec.js b/front/core/directives/specs/focus.spec.js new file mode 100644 index 000000000..82cd7d84d --- /dev/null +++ b/front/core/directives/specs/focus.spec.js @@ -0,0 +1,45 @@ +describe('Directive focus', () => { + let $scope; + let $element; + let compile; + + beforeEach(ngModule('vnCore')); + + compile = (_element, _childElement) => { + inject(($compile, $rootScope) => { + $scope = $rootScope.$new(); + $element = angular.element(_element); + if (_childElement) + $element[0].firstChild.focus = jasmine.createSpy(focus); + + $element[0].focus = jasmine.createSpy('focus'); + $element[0].select = jasmine.createSpy('select'); + $compile($element)($scope); + $scope.$digest(); + }); + }; + + it('should call the querySelector function upon the input to redefine it with the expected selector then call focus', () => { + let html = `
    `; + let childHtml = ''; + compile(html, childHtml); + + expect($element[0].firstChild.focus).toHaveBeenCalledWith(); + }); + + + it('should call focus function on the element', () => { + let html = ``; + compile(html); + + expect($element[0].focus).toHaveBeenCalledWith(); + }); + + it('should call select function on the element', () => { + let html = ``; + compile(html); + $scope.$apply(); + + expect($element[0].select).toHaveBeenCalledWith(); + }); +}); diff --git a/front/core/directives/specs/id.spec.js b/front/core/directives/specs/id.spec.js new file mode 100644 index 000000000..9d400701a --- /dev/null +++ b/front/core/directives/specs/id.spec.js @@ -0,0 +1,35 @@ + +describe('Directive vnId', () => { + let $scope; + let $element; + let compile; + + beforeEach(ngModule('vnCore')); + + compile = _element => { + inject(($compile, $rootScope) => { + $scope = $rootScope.$new(); + $element = angular.element(_element); + $compile($element)($scope); + $scope.$digest(); + }); + }; + + it(`should throw an error when there's no id defined`, () => { + let html = `
    `; + + expect(() => { + compile(html); + }).toThrow(new Error(`vnId: Attribute can't be null`)); + }); + + // FIXME: Sometimes fails with '$scope is undefined' + xit(`should set the controller into the $scope as there are no errors being thrown`, () => { + let html = `
    `; + + expect($scope['1']).not.toBeDefined(); + compile(html); + + expect($scope['1']).toBeDefined(); + }); +}); diff --git a/front/core/directives/specs/rule.spec.js b/front/core/directives/specs/rule.spec.js new file mode 100644 index 000000000..522ca5637 --- /dev/null +++ b/front/core/directives/specs/rule.spec.js @@ -0,0 +1,113 @@ +describe('Directive rule', () => { + let $scope; + let $element; + let element; + + beforeEach(ngModule('vnCore')); + + function compile(html, value) { + inject(($compile, $rootScope, $window) => { + $window.validations = {Model: + {validations: {field: [{validation: 'absence'}]}} + }; + + $scope = $rootScope.$new(); + + $element = angular.element(html); + $compile($element)($scope); + element = $element[0]; + + $scope.model = {field: value}; + $scope.$digest(); + }); + } + + afterEach(() => { + $scope.$destroy(); + $element.remove(); + }); + + describe('Errors', () => { + it(`should throw an error if the rule doesn't have the right syntax`, () => { + expect(() => { + compile(` +
    + + +
    + `); + }).toThrow(new Error(`rule: Attribute must have this syntax: [ModelName[.fieldName]]`)); + }); + + it('should throw an error if cannot retrieve model or field', () => { + expect(() => { + compile(` +
    + + +
    + `); + }).toThrow(new Error(`rule: Cannot retrieve model or field attribute`)); + }); + + it('should throw an error if the model is not defined', () => { + expect(() => { + compile(` +
    + + +
    + `); + }).toThrow(new Error(`rule: Model 'NonExistentModel' doesn't exist`)); + }); + }); + + describe('Validator extended', () => { + let html = ` +
    + + +
    + `; + + it('should not validate the entity as it has a wrong value', () => { + compile(html, 'invalidValue'); + + expect(element.classList).toContain('ng-invalid'); + }); + + it('should validate the entity as it has a valid value', () => { + compile(html, ''); + + expect(element.classList).toContain('ng-valid'); + }); + }); + + describe('Validator minimal', () => { + let html = ` + + + `; + + it('should validate with empty rule and without specifying a parent form', () => { + compile(html, 'invalidValue'); + + expect(element.classList).toContain('ng-invalid'); + }); + }); +}); diff --git a/client/core/src/directives/specs/zoom-image.spec.js b/front/core/directives/specs/zoom-image.spec.js similarity index 94% rename from client/core/src/directives/specs/zoom-image.spec.js rename to front/core/directives/specs/zoom-image.spec.js index 1891f738a..f9d9c1801 100644 --- a/client/core/src/directives/specs/zoom-image.spec.js +++ b/front/core/directives/specs/zoom-image.spec.js @@ -5,9 +5,7 @@ describe('Directive zoomImage', () => { let srcZoom = 'http://zoom.img.jpg/'; let findContainer; - beforeEach(() => { - angular.mock.module('client'); - }); + beforeEach(ngModule('vnCore')); beforeEach(angular.mock.inject(($compile, $rootScope) => { compile = $compile; @@ -23,7 +21,7 @@ describe('Directive zoomImage', () => { function getCompiledImage(imgHtml) { let element = angular.element(imgHtml); - var compiledElement = compile(element)(scope); + let compiledElement = compile(element)(scope); scope.$digest(); return compiledElement; } diff --git a/front/core/directives/title.js b/front/core/directives/title.js new file mode 100644 index 000000000..17d445c68 --- /dev/null +++ b/front/core/directives/title.js @@ -0,0 +1,37 @@ +import ngModule from '../module'; + +/** + * Watch for a state transition to change the page title + * + * @return {Object} The directive + */ + +directive.$inject = ['$transitions', '$translate', '$state']; + +export default function directive($transitions, $translate, $state) { + return { + restrict: 'A', + link: function($scope, $element, $attrs) { + $transitions.onSuccess({}, transition => { + let currentState = transition.targetState(); + let currentRoute = currentState._definition.self; + let parentRoute = currentState._definition.path[1].self; + let moduleName; + + moduleName = $translate.instant(parentRoute.description); + moduleName = moduleName ? `${moduleName} :` : ''; + + if (currentRoute == parentRoute) + moduleName = ''; + + let pageName = $translate.instant(currentRoute.description); + let paramId = $state.params.id ? `${$state.params.id} -` : ''; + + let title = `${moduleName} ${paramId} ${pageName}`; + + $element.html(title); + }); + } + }; +} +ngModule.directive('vnTitle', directive); diff --git a/front/core/directives/uvc.html b/front/core/directives/uvc.html new file mode 100644 index 000000000..49b59b406 --- /dev/null +++ b/front/core/directives/uvc.html @@ -0,0 +1,31 @@ +
    +
    + + + + + +
    Fields to show
    +
    +
    + + + + + + + + +
    +
    +
    +
    +
    diff --git a/front/core/directives/uvc.js b/front/core/directives/uvc.js new file mode 100644 index 000000000..e464a93ab --- /dev/null +++ b/front/core/directives/uvc.js @@ -0,0 +1,113 @@ +import ngModule from '../module'; +import template from './uvc.html'; +import './uvc.scss'; + +directive.$inject = ['$http', '$compile', 'vnApp', '$translate']; +export function directive($http, $compile, vnApp, $translate) { + function getHeaderList($element, $scope) { + let allHeaders = $element[0].querySelectorAll(`vn-th[field], vn-th[th-id]`); + let headerList = Array.from(allHeaders); + let ids = []; + let titles = {}; + + headerList.forEach(header => { + let id = header.getAttribute('th-id') || header.getAttribute('field'); + ids.push(id); + titles[id] = header.innerText || id.charAt(0).toUpperCase() + id.slice(1); + }); + + $scope.fields = ids; + $scope.titles = titles; + + return headerList; + } + + function getTableConfig(tableCode) { + return $http.get(`UserConfigViews/getConfig?tableCode=${tableCode}`); + } + + function createViewConfig(config, fields) { + fields.forEach(field => { + if (config.configuration[field] == null) + config.configuration[field] = true; + }); + } + + function addHideClass($scope, headerList, userConfig) { + let selectors = []; + Object.keys(userConfig.configuration).forEach(key => { + let index; + if (userConfig.configuration[key] === false) { + index = headerList.findIndex(el => { + return (el.getAttribute('th-id') == key || el.getAttribute('field') == key); + }); + + let baseSelector = `vn-table[vn-uvc=${userConfig.tableCode}] > div`; + selectors.push(`${baseSelector} vn-thead > vn-tr > vn-th:nth-child(${index + 1})`); + selectors.push(`${baseSelector} vn-tbody > vn-tr > vn-td:nth-child(${index + 1})`); + selectors.push(`${baseSelector} vn-tbody > .vn-tr > vn-td:nth-child(${index + 1})`); + } + }); + + + if (document.querySelector('style[id="uvc"]')) { + let child = document.querySelector('style[id="uvc"]'); + child.parentNode.removeChild(child); + } + + if (selectors.length) { + let rule = selectors.join(', ') + '{display: none;}'; + $scope.css = document.createElement('style'); + $scope.css.setAttribute('id', 'uvc'); + document.head.appendChild($scope.css); + $scope.css.appendChild(document.createTextNode(rule)); + } + + $scope.$on('$destroy', () => { + if ($scope.css && document.querySelector('style[id="uvc"]')) { + let child = document.querySelector('style[id="uvc"]'); + child.parentNode.removeChild(child); + } + }); + } + + function saveConfiguration(tableConfiguration) { + tableConfiguration.configuration = JSON.parse(JSON.stringify(tableConfiguration.configuration)); + return $http.post(`UserConfigViews/save`, tableConfiguration); + } + + return { + restrict: 'A', + link: async function($scope, $element, $attrs) { + let cTemplate = $compile(template)($scope)[0]; + $scope.$ctrl.showUvc = event => { + event.preventDefault(); + event.stopImmediatePropagation(); + $scope.uvc.show(); + }; + + let tableCode = $attrs.vnUvc.trim(); + let headerList = getHeaderList($element, $scope); + + let defaultConfigView = {tableCode: tableCode, configuration: {}}; + let userView = await getTableConfig(tableCode); + let config = userView.data || defaultConfigView; + + $scope.tableConfiguration = config; + createViewConfig(config, $scope.fields); + + addHideClass($scope, headerList, config); + + let table = document.querySelector(`vn-table[vn-uvc=${tableCode}]`); + + table.insertBefore(cTemplate, table.firstChild); + $scope.$ctrl.saveConfiguration = async tableConfiguration => { + let newConfig = await saveConfiguration(tableConfiguration); + vnApp.showSuccess($translate.instant('Data saved!')); + addHideClass($scope, headerList, newConfig.data); + $scope.uvc.hide(); + }; + } + }; +} +ngModule.directive('vnUvc', directive); diff --git a/front/core/directives/uvc.scss b/front/core/directives/uvc.scss new file mode 100644 index 000000000..5221b8bdd --- /dev/null +++ b/front/core/directives/uvc.scss @@ -0,0 +1,11 @@ +vn-table vn-dialog[vn-id="uvc"]{ + & > div { + min-width: 18em; + align-items: center; + + } + + vn-button[label="Save"] { + margin: 0 auto; + } +} \ No newline at end of file diff --git a/front/core/directives/visible-by.js b/front/core/directives/visible-by.js new file mode 100644 index 000000000..9a02d88e9 --- /dev/null +++ b/front/core/directives/visible-by.js @@ -0,0 +1,18 @@ +import ngModule from '../module'; + +function vnVisibleBy(aclService) { + return { + restrict: 'A', + priority: -1, + link: function($scope, $element, $attrs) { + let acls = $attrs.vnVisibleBy.replace(/\s/g, ''); + acls = acls.split(','); + + if (!aclService.hasAny(acls)) + $element[0].style.visibility = 'hidden'; + } + }; +} +vnVisibleBy.$inject = ['aclService']; + +ngModule.directive('vnVisibleBy', vnVisibleBy); diff --git a/client/core/src/directives/zoom-image.js b/front/core/directives/zoom-image.js similarity index 90% rename from client/core/src/directives/zoom-image.js rename to front/core/directives/zoom-image.js index db7de27be..607dbe337 100644 --- a/client/core/src/directives/zoom-image.js +++ b/front/core/directives/zoom-image.js @@ -1,4 +1,5 @@ import ngModule from '../module'; +import './zoom-image.scss'; export function directive($timeout) { let container; @@ -24,9 +25,8 @@ export function directive($timeout) { } function onKeyDown(event) { - if (event.keyCode === 27) { + if (event.key === 'Escape') destroyContainers(); - } } function destroyContainers() { @@ -44,12 +44,12 @@ export function directive($timeout) { restrict: 'A', link: function($scope, $element, $attrs) { $element.on('click', function(event) { - event.preventDefault(); + if (event.defaultPrevented) return; let src = $attrs.zoomImage || $attrs.src; - if (src) { + if (src) createContainers(src); - } else + else throw new Error('No image source detected'); }); } diff --git a/client/core/src/styles/zoom-image.scss b/front/core/directives/zoom-image.scss similarity index 96% rename from client/core/src/styles/zoom-image.scss rename to front/core/directives/zoom-image.scss index cc0212006..e075ff3a1 100644 --- a/client/core/src/styles/zoom-image.scss +++ b/front/core/directives/zoom-image.scss @@ -1,13 +1,10 @@ -img[zoom-image]{ - cursor: zoom-in; -} .vn-zoom-image { width: 100%; height: 100%; position: fixed; top: 0; - z-index: 11; + z-index: 25; background-color: rgba(1, 1, 1, 0.6); & > div { @@ -27,3 +24,6 @@ img[zoom-image]{ } } } +img[zoom-image]{ + cursor: zoom-in; +} diff --git a/front/core/filters/currency.js b/front/core/filters/currency.js new file mode 100644 index 000000000..d44457813 --- /dev/null +++ b/front/core/filters/currency.js @@ -0,0 +1,33 @@ +import ngModule from '../module'; + +/** + * Override angular currency formatting a number, adding symbol after value. + * + * @return {String} The formated number + */ + +export default function currency($translate) { + function currency(input, symbol = 'EUR', fractionSize = 2) { + let options = { + style: 'currency', + currency: symbol, + minimumFractionDigits: fractionSize, + maximumFractionDigits: fractionSize + }; + + if (typeof input == 'number') { + return new Intl.NumberFormat($translate.use(), options) + .format(input); + } + + return undefined; + } + + currency.$stateful = true; + + return currency; +} + +currency.$inject = ['$translate']; + +ngModule.filter('currency', currency); diff --git a/front/core/filters/dash-if-empty.js b/front/core/filters/dash-if-empty.js new file mode 100644 index 000000000..3e40c976b --- /dev/null +++ b/front/core/filters/dash-if-empty.js @@ -0,0 +1,15 @@ +import ngModule from '../module'; + +/** + * Returns dash when value is empty, otherwise returns the same string. + * + * @return {String} The string result + */ +export default function dashIfEmpty() { + return function(input) { + if (input == null || input === '') + return '-'; + return input; + }; +} +ngModule.filter('dashIfEmpty', dashIfEmpty); diff --git a/front/core/filters/index.js b/front/core/filters/index.js new file mode 100644 index 000000000..cc4dff823 --- /dev/null +++ b/front/core/filters/index.js @@ -0,0 +1,6 @@ +import './phone'; +import './ucwords'; +import './dash-if-empty'; +import './percentage'; +import './currency'; +import './zero-fill'; diff --git a/front/core/filters/percentage.js b/front/core/filters/percentage.js new file mode 100644 index 000000000..41e3f8288 --- /dev/null +++ b/front/core/filters/percentage.js @@ -0,0 +1,22 @@ +import ngModule from '../module'; + +export default function percentage($translate) { + function percentage(input, fractionSize = 2) { + if (input == null || input === '') + return null; + + return new Intl.NumberFormat($translate.use(), { + style: 'percent', + minimumFractionDigits: fractionSize, + maximumFractionDigits: fractionSize + }).format(parseFloat(input)); + } + + percentage.$stateful = true; + + return percentage; +} + +percentage.$inject = ['$translate']; + +ngModule.filter('percentage', percentage); diff --git a/client/core/src/filters/phone.js b/front/core/filters/phone.js similarity index 100% rename from client/core/src/filters/phone.js rename to front/core/filters/phone.js diff --git a/front/core/filters/specs/currency.spec.js b/front/core/filters/specs/currency.spec.js new file mode 100644 index 000000000..28a4a3640 --- /dev/null +++ b/front/core/filters/specs/currency.spec.js @@ -0,0 +1,41 @@ +describe('Currency filter', () => { + let compile; + let $element; + + beforeEach(ngModule('vnCore')); + + compile = html => { + inject(($compile, $rootScope) => { + $element = $compile(html)($rootScope); + $rootScope.$digest(); + }); + }; + + it('should return a ONE decimal number as per the argument', () => { + let html = `
    {{200 | currency: 'EUR': 1}}
    `; + compile(html); + + expect($element[0].innerHTML).toContain('200.0'); + }); + + it('should return a TWO decimals number as per the argument', () => { + let html = `
    {{200 | currency: 'EUR': 2}}
    `; + compile(html); + + expect($element[0].innerHTML).toContain('200.00'); + }); + + it('should return a TEN decimals number as per the argument', () => { + let html = `
    {{200 | currency: 'EUR': 10}}
    `; + compile(html); + + expect($element[0].innerHTML).toContain('200.0000000000'); + }); + + it('sould return nothing when the value is not set', () => { + let html = `
    {{null | currency: 'EUR': 2}}
    `; + compile(html); + + expect($element[0].innerHTML).toEqual(''); + }); +}); diff --git a/client/core/src/filters/ucwords.js b/front/core/filters/ucwords.js similarity index 100% rename from client/core/src/filters/ucwords.js rename to front/core/filters/ucwords.js diff --git a/front/core/filters/zero-fill.js b/front/core/filters/zero-fill.js new file mode 100644 index 000000000..c4d76b96f --- /dev/null +++ b/front/core/filters/zero-fill.js @@ -0,0 +1,17 @@ +import ngModule from '../module'; + +/** + * Pads a number with zeros. + * + * @param {Number} input The number to pad + * @param {Number} padLength The resulting number of digits + * @return {String} The zero-filled number + */ +export default function zeroFill() { + return function(input, padLength) { + if (input == null) return input; + let sign = Math.sign(input) === -1 ? '-' : ''; + return sign + new Array(padLength).concat([Math.abs(input)]).join('0').slice(-padLength); + }; +} +ngModule.filter('zeroFill', zeroFill); diff --git a/front/core/index.js b/front/core/index.js new file mode 100644 index 000000000..fdcfaff05 --- /dev/null +++ b/front/core/index.js @@ -0,0 +1,8 @@ +import './styles'; + +export * from './module'; +export * from './directives'; +export * from './filters'; +export * from './lib'; +export * from './services'; +export * from './components'; diff --git a/front/core/lib/assign-props.js b/front/core/lib/assign-props.js new file mode 100644 index 000000000..efc313e7e --- /dev/null +++ b/front/core/lib/assign-props.js @@ -0,0 +1,6 @@ + +export default function(srcObject, dstObject, props) { + for (let prop of props) + if (srcObject[prop] !== undefined) + dstObject[prop] = srcObject[prop]; +} diff --git a/front/core/lib/component.js b/front/core/lib/component.js new file mode 100644 index 000000000..b9f04dba6 --- /dev/null +++ b/front/core/lib/component.js @@ -0,0 +1,142 @@ +import ngModule from '../module'; +import EventEmitter from './event-emitter'; +import {kebabToCamel} from './string'; + +/** + * Base class for component controllers. + */ +export default class Component extends EventEmitter { + /** + * Contructor. + * + * @param {HTMLElement} $element The main component element + * @param {$rootScope.Scope} $scope The element scope + */ + constructor($element, $scope) { + super(); + if (!$element) return; + this.element = $element[0]; + this.element.$ctrl = this; + this.$element = $element; + this.$ = $scope; + } + + $postLink() { + if (!this.$element) return; + let attrs = this.$element[0].attributes; + let $scope = this.$; + for (let attr of attrs) { + if (attr.name.substr(0, 2) !== 'on') continue; + let eventName = kebabToCamel(attr.name.substr(3)); + let callback = locals => $scope.$parent.$eval(attr.nodeValue, locals); + this.on(eventName, callback); + } + } + + /** + * The component owner window. + */ + get window() { + return this.document.defaultView; + } + + /** + * The component owner document. + */ + get document() { + return this.element.ownerDocument; + } + + /** + * Translates an string. + * + * @param {String} string String to translate + * @param {Array} params Translate parameters + * @return {String} The translated string + */ + $t(string, params) { + return this.$translate.instant(string, params); + } + + createBoundTranscludeFn(linkFn) { + let scope = this.$; + let previousBoundTranscludeFn = this.$transclude.$$boundTransclude; + + function vnBoundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) { + if (!transcludedScope) { + transcludedScope = scope.$new(false, containingScope); + transcludedScope.$$transcluded = true; + } + return linkFn(transcludedScope, cloneFn, { + parentBoundTranscludeFn: previousBoundTranscludeFn, + transcludeControllers: controllers, + futureParentElement: futureParentElement + }); + } + vnBoundTranscludeFn.$$slots = previousBoundTranscludeFn.$$slots; + + return vnBoundTranscludeFn; + } + + fillDefaultSlot(template) { + let linkFn = this.$compile(template); + this.$transclude.$$boundTransclude = this.createBoundTranscludeFn(linkFn); + } + + fillSlot(slot, template) { + let slots = this.$transclude.$$boundTransclude.$$slots; + let linkFn = this.$compile(template); + slots[slot] = this.createBoundTranscludeFn(linkFn); + } + + copySlot(slot, $transclude) { + this.$transclude.$$boundTransclude.$$slots[slot] = + $transclude.$$boundTransclude.$$slots[slot]; + } +} +Component.$inject = ['$element', '$scope']; + +function runFn( + $translate, + $q, + $http, + $state, + $stateParams, + $timeout, + $transitions, + $compile, + $filter, + $interpolate, + $window, + vnApp) { + Object.assign(Component.prototype, { + $translate, + $q, + $http, + $state, + $params: $stateParams, + $timeout, + $transitions, + $compile, + $filter, + $interpolate, + $window, + vnApp + }); +} +runFn.$inject = [ + '$translate', + '$q', + '$http', + '$state', + '$stateParams', + '$timeout', + '$transitions', + '$compile', + '$filter', + '$interpolate', + '$window', + 'vnApp' +]; + +ngModule.run(runFn); diff --git a/client/core/src/lib/copy.js b/front/core/lib/copy.js similarity index 100% rename from client/core/src/lib/copy.js rename to front/core/lib/copy.js diff --git a/client/core/src/lib/crud.js b/front/core/lib/crud.js similarity index 100% rename from client/core/src/lib/crud.js rename to front/core/lib/crud.js diff --git a/front/core/lib/date.js b/front/core/lib/date.js new file mode 100644 index 000000000..2acfd6e55 --- /dev/null +++ b/front/core/lib/date.js @@ -0,0 +1,21 @@ +/** + * Transforms a UTC date to JSON date without datetime. + * + * @param {date} date Date to format + * @return {String} Formatted date string + */ +export function toJsonDate(date) { + date = new Date(date); + + let day = date.getDate(); + let month = date.getMonth() + 1; + let year = date.getFullYear(); + + if (day < 10) + day = `0${day}`; + + if (month < 10) + month = `0${month}`; + + return new Date(`${year}-${month}-${day}`); +} diff --git a/client/core/src/lib/equals.js b/front/core/lib/equals.js similarity index 100% rename from client/core/src/lib/equals.js rename to front/core/lib/equals.js diff --git a/front/core/lib/event-emitter.js b/front/core/lib/event-emitter.js new file mode 100644 index 000000000..83e361253 --- /dev/null +++ b/front/core/lib/event-emitter.js @@ -0,0 +1,86 @@ +/** + * Implemented by all those classes that emit events. + */ +export default class EventEmitter { + /** + * Connects to an object event. + * + * @param {String} eventName The event name + * @param {Function} callback The callback function + * @param {Object} thisArg The scope for the callback or %null + */ + on(eventName, callback, thisArg) { + if (!this.$events) + this.$events = {}; + if (!this.$events[eventName]) + this.$events[eventName] = []; + this.$events[eventName].push({callback, thisArg}); + } + + /** + * Disconnects all handlers for callback. + * + * @param {Function} callback The callback function + */ + off(callback) { + if (!this.$events) return; + for (let event in this.$events) { + for (let i = 0; i < event.length; i++) { + if (event[i].callback === callback) + event.splice(i--, 1); + } + } + } + + /** + * Disconnects all instance callbacks. + * + * @param {Object} thisArg The callbacks instance + */ + disconnect(thisArg) { + if (!this.$events) return; + for (let event in this.$events) { + for (let i = 0; i < event.length; i++) { + if (event[i].thisArg === thisArg) + event.splice(i--, 1); + } + } + } + + /** + * Emits an event. + * + * @param {String} eventName The event name + * @param {Object} args Arguments to pass to the callbacks + */ + emit(eventName, args) { + if (!this.$events || !this.$events[eventName]) + return; + + args = Object.assign({$this: this}, args); + + let callbacks = this.$events[eventName]; + for (let callback of callbacks) + callback.callback.call(callback.thisArg, args); + } + + /** + * Links the object with another object events. + * + * @param {Object} propValue The property and the new value + * @param {Object} handlers The event handlers + */ + linkEvents(propValue, handlers) { + for (let prop in propValue) { + let value = propValue[prop]; + if (this[prop]) + this[prop].disconnect(this); + this[prop] = value; + if (value) { + for (let event in handlers) + value.on(event, handlers[event], this); + } + } + } +} +EventEmitter.$inject = ['$element', '$scope']; diff --git a/front/core/lib/focus.js b/front/core/lib/focus.js new file mode 100644 index 000000000..8b997d920 --- /dev/null +++ b/front/core/lib/focus.js @@ -0,0 +1,16 @@ + +import isMobile from './is-mobile'; + +export default function focus(element) { + if (isMobile) return; + setTimeout(() => element.focus(), 10); +} + +export function select(element) { + if (isMobile) return; + setTimeout(() => { + element.focus(); + if (element.select) + element.select(); + }, 10); +} diff --git a/client/core/src/lib/full-empty.js b/front/core/lib/full-empty.js similarity index 100% rename from client/core/src/lib/full-empty.js rename to front/core/lib/full-empty.js diff --git a/front/core/lib/get-main-route.js b/front/core/lib/get-main-route.js new file mode 100644 index 000000000..52a86ada1 --- /dev/null +++ b/front/core/lib/get-main-route.js @@ -0,0 +1,8 @@ + +export default function getMainRoute(routes) { + for (let route of routes) { + if (!route.abstract) + return route; + } + return null; +} diff --git a/front/core/lib/http-error.js b/front/core/lib/http-error.js new file mode 100644 index 000000000..91ccc8905 --- /dev/null +++ b/front/core/lib/http-error.js @@ -0,0 +1,12 @@ +/** + * Wraps $http error responses. This class is mainly used to + * avoid the default AngularJS behaviour, that is, stringifying all + * unhandled rejections that aren't @Error objects. More info at: + * - https://github.com/angular/angular.js/issues/14631 + */ +export default class HttpError extends Error { + constructor(message, fileName, lineNumber) { + super(message, fileName, lineNumber); + this.name = 'HttpError'; + } +} diff --git a/front/core/lib/index.js b/front/core/lib/index.js new file mode 100644 index 000000000..4d562ca05 --- /dev/null +++ b/front/core/lib/index.js @@ -0,0 +1,10 @@ +import './module-loader'; +import './crud'; +import './copy'; +import './equals'; +import './focus'; +import './get-main-route'; +import './modified'; +import './key-codes'; +import './http-error'; +import './user-error'; diff --git a/front/core/lib/is-mobile.js b/front/core/lib/is-mobile.js new file mode 100644 index 000000000..5fae749df --- /dev/null +++ b/front/core/lib/is-mobile.js @@ -0,0 +1,4 @@ + +const regex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i; +const isMobile = regex.test(navigator.userAgent); +export default isMobile; diff --git a/client/core/src/lib/key-codes.js b/front/core/lib/key-codes.js similarity index 100% rename from client/core/src/lib/key-codes.js rename to front/core/lib/key-codes.js diff --git a/front/core/lib/modified.js b/front/core/lib/modified.js new file mode 100644 index 000000000..620dc75b3 --- /dev/null +++ b/front/core/lib/modified.js @@ -0,0 +1,23 @@ +import isEqual from './equals'; + +export default function getModifiedData(object, objectOld) { + let newObject = {}; + if (objectOld === null) + return object; + + for (let k in object) { + let val = object[k]; + let valOld = objectOld[k] === undefined ? null : objectOld[k]; + + if (!isEqual(val, valOld)) { + if (val instanceof Date) + newObject[k] = new Date(val.getTime()); + else if (val instanceof Object) + newObject[k] = getModifiedData(val, valOld); + else + newObject[k] = val; + } + } + + return Object.keys(newObject).length ? newObject : undefined; +} diff --git a/front/core/lib/module-loader.js b/front/core/lib/module-loader.js new file mode 100644 index 000000000..18f0a3ea3 --- /dev/null +++ b/front/core/lib/module-loader.js @@ -0,0 +1,109 @@ +import ngModule from '../module'; +import moduleImport from 'module-import'; + +factory.$inject = ['$http', '$window', '$ocLazyLoad', '$translatePartialLoader', '$translate', '$q']; +export function factory($http, $window, $ocLazyLoad, $translatePartialLoader, $translate, $q) { + /** + * Used to load application modules lazily. + */ + class ModuleLoader { + constructor() { + this.loaded = {}; + this.imports = {}; + this.moduleImport = moduleImport; + this.modelInfo = $http.get(`modelInfo`) + .then(json => { + this.onModelInfoReady(json); + this.modelInfo = true; + }); + } + + /** + * Loads the passed module and it's dependencies. Loading a module + * implies load the webpack chunk, translations, recursively load + * module dependencies and finally register all of them into Angular. + * + * @param {String} mod The module name to load + * @return {Promise} Will be resolved when loaded, when module is + * already loaded it returns a resolved promise + */ + load(mod) { + let mods = []; + return this.loadRec(mod, mods); + } + + loadRec(mod, mods) { + let loaded = this.loaded[mod]; + + if (loaded === true || mods.indexOf(mod) != -1) + return $q.resolve(true); + if (loaded instanceof $q) + return loaded; + + let moduleConf = $window.routes.find(i => i && i.module == mod); + if (!moduleConf) + return $q.reject(new Error(`Module not found: ${mod}`)); + + let promises = []; + + if (this.modelInfo instanceof $q) + promises.push(this.modelInfo); + + $translatePartialLoader.addPart(mod); + promises.push($translate.refresh()); + + let modImport = this.imports[mod]; + + if (!modImport) { + modImport = this.imports[mod] = this.moduleImport(mod) + .then(() => this.imports[mod] = true); + } + if (modImport && modImport.then) + promises.push(modImport); + + let deps = moduleConf.dependencies; + + if (deps) { + mods.push(mod); + for (let dep of deps) + promises.push(this.loadRec(dep, mods)); + mods.pop(); + } + + this.loaded[mod] = $q.all(promises) + .then(() => $ocLazyLoad.load({name: mod})) + .then(() => this.loaded[mod] = true); + return this.loaded[mod]; + } + + onModelInfoReady(json) { + let entities = json.data; + for (let entity in entities) { + let fields = entities[entity].validations; + for (let field in fields) { + let validations = fields[field]; + for (let validation of validations) + this.parseValidation(validation); + } + } + + Object.assign($window.validations, json.data); + } + + parseValidation(val) { + switch (val.validation) { + case 'custom': + // TODO: Don't use eval() because it's "evil". + // How to do the same without eval? + val.bindedFunction = eval(`(${val.bindedFunction})`); + break; + case 'format': + val.with = new RegExp(val.with); + break; + } + } + } + + return new ModuleLoader(); +} +ngModule.factory('vnModuleLoader', factory); diff --git a/front/core/lib/specs/acl-service.spec.js b/front/core/lib/specs/acl-service.spec.js new file mode 100644 index 000000000..3a1460241 --- /dev/null +++ b/front/core/lib/specs/acl-service.spec.js @@ -0,0 +1,56 @@ +describe('Service acl', () => { + let aclService; + + beforeEach(ngModule('vnCore')); + + beforeEach(inject((_aclService_, $httpBackend) => { + $httpBackend.when('GET', `Accounts/acl`).respond({ + roles: [ + {role: {name: 'foo'}}, + {role: {name: 'bar'}}, + {role: {name: 'baz'}} + ] + }); + aclService = _aclService_; + aclService.load(); + $httpBackend.flush(); + })); + + describe('load()', () => { + it('should load roles from backend', () => { + expect(aclService.roles).toEqual({ + foo: true, + bar: true, + baz: true + }); + }); + }); + + describe('hasAny()', () => { + it('should return true when user has any of the passed roles', () => { + let hasAny = aclService.hasAny(['foo', 'nonExistent']); + + expect(hasAny).toBeTruthy(); + }); + + it('should return true when user has all the passed roles', () => { + let hasAny = aclService.hasAny(['bar', 'baz']); + + expect(hasAny).toBeTruthy(); + }); + + it('should return false when user has not any of the passed roles', () => { + let hasAny = aclService.hasAny(['inventedRole', 'nonExistent']); + + expect(hasAny).toBeFalsy(); + }); + }); + + describe('reset()', () => { + it('should reset the roles', () => { + aclService.reset(); + + expect(aclService.roles).toBeNull(); + }); + }); +}); diff --git a/front/core/lib/specs/module-loader.spec.js b/front/core/lib/specs/module-loader.spec.js new file mode 100644 index 000000000..2f756f7be --- /dev/null +++ b/front/core/lib/specs/module-loader.spec.js @@ -0,0 +1,108 @@ +describe('factory vnModuleLoader', () => { + let vnModuleLoader; + let $rootScope; + let $window; + + beforeEach(ngModule('vnCore')); + + beforeEach(angular.mock.inject((_vnModuleLoader_, _$rootScope_, $httpBackend, _$window_, $q) => { + vnModuleLoader = _vnModuleLoader_; + $rootScope = _$rootScope_; + $window = _$window_; + + $window.validations = {}; + $window.routes = [ + { + module: 'myModule', + dependencies: ['fooModule', 'barModule'] + }, { + module: 'fooModule', + dependencies: ['myModule'] + }, { + module: 'barModule' + } + ]; + + $httpBackend.whenGET('modelInfo') + .respond({ + FooModel: { + properties: { + id: {type: 'Number'}, + email: {type: 'String'}, + field: {type: 'Boolean'} + }, + validations: { + id: [{ + validation: 'presence' + }], + email: [{ + validation: 'format', + with: '/@/' + }], + field: [{ + validation: 'custom', + bindedFunction: '() => true' + }] + } + } + }); + $httpBackend.flush(); + + vnModuleLoader.moduleImport = () => $q.resolve(); + })); + + describe('load()', () => { + it('should throw error if module does not exist', async() => { + let errorThrown; + + vnModuleLoader.load('unexistentModule') + .catch(() => errorThrown = true); + $rootScope.$apply(); + + expect(errorThrown).toBeTruthy(); + }); + + it('should set module loaded to true when it is loaded', async() => { + vnModuleLoader.load('barModule'); + $rootScope.$apply(); + + expect(vnModuleLoader.loaded['barModule']).toBeTruthy(); + }); + + it('should resolve returned promise when module is loaded', async() => { + let loaded; + + vnModuleLoader.load('barModule') + .then(() => loaded = true); + $rootScope.$apply(); + + expect(loaded).toBeTruthy(); + }); + + it('should load dependencies', async() => { + vnModuleLoader.load('fooModule'); + $rootScope.$apply(); + + expect(vnModuleLoader.loaded['barModule']).toBeTruthy(); + }); + + it('should work with circular dependencies', async() => { + vnModuleLoader.load('myModule'); + $rootScope.$apply(); + + expect(vnModuleLoader.loaded['fooModule']).toBeTruthy(); + }); + + it('should load models information and parse validations', async() => { + vnModuleLoader.load('barModule'); + + let FooModel = $window.validations.FooModel; + let validations = FooModel && FooModel.validations; + + expect(FooModel).toBeDefined(); + expect(validations).toBeDefined(); + expect(validations.email[0].with).toBeInstanceOf(RegExp); + expect(validations.field[0].bindedFunction).toBeInstanceOf(Function); + }); + }); +}); diff --git a/front/core/lib/specs/validator.spec.js b/front/core/lib/specs/validator.spec.js new file mode 100644 index 000000000..dd8fc985d --- /dev/null +++ b/front/core/lib/specs/validator.spec.js @@ -0,0 +1,184 @@ +import {validate} from '../validator.js'; + +describe('Validator', () => { + let $translate; + + beforeEach(ngModule('vnCore')); + + beforeEach(inject(_$translate_ => { + $translate = _$translate_; + })); + + describe('presence', () => { + let conf = {validation: 'presence'}; + + it('should not validate the value as it should be defined', () => { + expect(() => { + validate($translate, '', conf); + }).toThrowError(); + }); + + it('should validate the value as it should be defined', () => { + expect(() => { + validate($translate, 'aDefinedValue', conf); + }).not.toThrowError(); + }); + }); + + describe('absence', () => { + let conf = {validation: 'absence'}; + + it('should not validate the value as it should be undefined', () => { + expect(() => { + validate($translate, 'aDefinedValue', conf); + }).toThrowError(); + }); + + it('should validate the value as it should be undefined', () => { + expect(() => { + validate($translate, '', conf); + }).not.toThrowError(); + }); + }); + + describe('length', () => { + it('should not validate the value as it should have an specific valid length', () => { + let conf = { + validation: 'length', + is: 25 + }; + + expect(() => { + validate($translate, 'invalidSpecificLengthString', conf); + }).toThrowError(); + }); + + it('should validate the value as it should have an specific valid length', () => { + let conf = { + validation: 'length', + is: 25 + }; + + expect(() => { + validate($translate, 'validSpecificLengthString', conf); + }).not.toThrowError(); + }); + + it('should not validate the value as it should have a min length', () => { + let conf = { + validation: 'length', + min: 10 + }; + + expect(() => { + validate($translate, 'shortName', conf); + }).toThrowError(); + }); + + it('should validate the value as it should have a min length', () => { + let conf = { + validation: 'length', + min: 10 + }; + + expect(() => { + validate($translate, 'veryLongName', conf); + }).not.toThrowError(); + }); + + it('should not validate the value as it should be smaller than the maximum', () => { + let conf = { + validation: 'length', + max: 20 + }; + + expect(() => { + validate($translate, 'chainThatExceedsMaxLength', conf); + }).toThrowError(); + }); + + it('should validate the value as it should be smaller than the maximum', () => { + let conf = { + validation: 'length', + max: 20 + }; + + expect(() => { + validate($translate, 'shortString', conf); + }).not.toThrowError(); + }); + }); + + describe('numericality', () => { + let conf = {validation: 'numericality'}; + + it('should not validate the value as it should be an integer', () => { + expect(() => { + validate($translate, 'notANumber', conf); + }).toThrowError(); + }); + + it('should validate the value as it should be an integer', () => { + expect(() => { + validate($translate, '123456789', conf); + }).not.toThrowError(); + }); + }); + + describe('inclusion', () => { + let conf = { + validation: 'inclusion', + in: ['firstValue', 'seekValue', 'lastValue'] + }; + + it('should not validate the value as it should be in array', () => { + expect(() => { + validate($translate, 'notIncludedValue', conf); + }).toThrowError(); + }); + + it('should validate the value as it should be in array', () => { + expect(() => { + validate($translate, 'seekValue', conf); + }).not.toThrowError(); + }); + }); + + describe('exclusion', () => { + let conf = { + validation: 'exclusion', + in: ['firstValue', 'seekValue', 'lastValue'] + }; + + it('should not validate the value as it should not be in array', () => { + expect(() => { + validate($translate, 'seekValue', conf); + }).toThrowError(); + }); + + it('should validate the value as it should not be in array', () => { + expect(() => { + validate($translate, 'notIncludedValue', conf); + }).not.toThrowError(); + }); + }); + + describe('format', () => { + let conf = { + validation: 'format', + with: /[a-z-]+@[a-z-]+\.[a-z]+/ + }; + + it('should not validate the value as it should match regexp', () => { + expect(() => { + validate($translate, 'wrongValue', conf); + }).toThrowError(); + }); + + it('should validate the value as it should match regexp', () => { + expect(() => { + validate($translate, 'valid-value@domain.com', conf); + }).not.toThrowError(); + }); + }); +}); diff --git a/front/core/lib/string.js b/front/core/lib/string.js new file mode 100644 index 000000000..50bee9873 --- /dev/null +++ b/front/core/lib/string.js @@ -0,0 +1,32 @@ +/** + * Transforms a kebab-case string to camelCase. A kebab-case string + * is a string with hyphen character as word separator. + * + * @param {String} str The hyphenized string + * @return {String} The camelized string + */ +export function kebabToCamel(str) { + return str.replace(/-([a-z])/g, g => g[1].toUpperCase()); +} + +/** + * Transforms a camelCase to kebab-case. + * + * @param {String} str The camelized string + * @return {String} The hyphenized string + */ +export function camelToKebab(str) { + let kebabCased = str.substr(1) + .replace(/[A-Z]/g, g => `-${g[0]}`); + return `${str.charAt(0)}${kebabCased}`.toLowerCase(); +} + +/** + * Transforms the first letter of a string to uppercase. + * + * @param {String} str The input string + * @return {String} The transformed string + */ +export function firstUpper(str) { + return str.charAt(0).toUpperCase() + str.substr(1); +} diff --git a/front/core/lib/user-error.js b/front/core/lib/user-error.js new file mode 100644 index 000000000..597656c74 --- /dev/null +++ b/front/core/lib/user-error.js @@ -0,0 +1,10 @@ +/** + * Errors that can be visible and understood by the end user. + * Used mainly in the global error handler. + */ +export default class UserError extends Error { + constructor(message, fileName, lineNumber) { + super(message, fileName, lineNumber); + this.name = 'UserError'; + } +} diff --git a/front/core/lib/validator.js b/front/core/lib/validator.js new file mode 100644 index 000000000..b0b8f7389 --- /dev/null +++ b/front/core/lib/validator.js @@ -0,0 +1,112 @@ +import {validator} from '../vendor'; + +export const validators = { + presence: ($translate, value) => { + if (validator.isEmpty(value ? String(value) : '')) + throw new Error(_($translate, `Value can't be empty`)); + }, + absence: ($translate, value) => { + if (!validator.isEmpty(value)) + throw new Error(_($translate, `Value should be empty`)); + }, + length: ($translate, value, conf) => { + let options = { + min: conf.min || conf.is, + max: conf.max || conf.is + }; + let val = value ? String(value) : ''; + if (!validator.isLength(val, options)) { + if (conf.is) { + throw new Error(_($translate, + `Value should be %s characters long`, [conf.is])); + } else if (conf.min && conf.max) { + throw new Error(_($translate, + `Value should have a length between %s and %s`, [conf.min, conf.max])); + } else if (conf.min) { + throw new Error(_($translate, + `Value should have at least %s characters`, [conf.min])); + } else { + throw new Error(_($translate, + `Value should have at most %s characters`, [conf.max])); + } + } + }, + numericality: ($translate, value, conf) => { + if (conf.int) { + if (!validator.isInt(value)) + throw new Error(_($translate, `Value should be integer`)); + } else if (!validator.isNumeric(value)) + throw new Error(_($translate, `Value should be a number`)); + }, + inclusion: ($translate, value, conf) => { + if (!validator.isIn(value, conf.in)) + throw new Error(_($translate, `Invalid value`)); + }, + exclusion: ($translate, value, conf) => { + if (validator.isIn(value, conf.in)) + throw new Error(_($translate, `Invalid value`)); + }, + format: ($translate, value, conf) => { + if (!validator.matches(value, conf.with)) + throw new Error(_($translate, `Invalid value`)); + }, + custom: ($translate, value, conf) => { + if (!conf.bindedFunction(value)) + throw new Error(_($translate, `Invalid value`)); + } +}; + +/** + * Checks if value satisfies a set of validations. + * + * @param {*} value The value + * @param {Array} validations Array with validations + */ +export function validateAll($translate, value, validations) { + for (let conf of validations) + validate($translate, value, conf); +} + +/** + * Checks if value satisfies a validation. + * + * @param {*} value The value + * @param {Object} conf The validation configuration + */ +export function validate($translate, value, conf) { + let validator = validators[conf.validation]; + try { + let isEmpty = value == null || value === ''; + + if (isEmpty) + checkNull($translate, value, conf); + if (validator && (!isEmpty || conf.validation == 'presence')) + validator($translate, value, conf); + } catch (e) { + let message = conf.message ? conf.message : e.message; + throw new Error(_($translate, message)); + } +} + +/** + * Checks if value satisfies a blank or not null validation. + * + * @param {*} value The value + * @param {Object} conf The validation configuration + */ +export function checkNull($translate, value, conf) { + if (conf.allowBlank === false && value === '') + throw new Error(_($translate, `Value can't be blank`)); + else if (conf.allowNull === false && value == null) + throw new Error(_($translate, `Value can't be null`)); +} + +export function _($translate, text, params = []) { + text = $translate.instant(text); + + for (let i = 0; i < params.length; i++) { + text = text.replace('%s', params[i]); + } + + return text; +} diff --git a/front/core/locale/en.yml b/front/core/locale/en.yml new file mode 100644 index 000000000..99a9b8049 --- /dev/null +++ b/front/core/locale/en.yml @@ -0,0 +1,16 @@ +Accept: Accept +Cancel: Cancel +Close: Close +Clear: Clear +Save: Save +Add: Add +Search: Search +Show More: Show More +No more results: No more results +Hide: Hide +Next: Next +Finalize: Finalize +Previous: Back +Load more: Load more +Auto-scroll interrupted, please adjust the search: Auto-scroll interrupted, please adjust the search +General search: General search \ No newline at end of file diff --git a/front/core/locale/es.yml b/front/core/locale/es.yml new file mode 100644 index 000000000..1e1e4da4c --- /dev/null +++ b/front/core/locale/es.yml @@ -0,0 +1,65 @@ +Accept: Aceptar +Cancel: Cancelar +Close: Cerrar +Clear: Borrar +Save: Guardar +Add: Añadir +Search: Buscar +Show More: Ver más +No more results: No hay más resultados +Hide: Ocultar +Next: Siguiente +Finalize: Finalizar +Previous: Anterior +Auto-scroll interrupted, please adjust the search: Auto-scroll interrumpido, por favor ajusta la búsqueda +Value can't be empty: El valor no puede estar vacío +Value should be empty: El valor debe estar vacío +Value should be integer: El valor debe ser entero +Value should be a number: El valor debe ser numérico +Invalid value: Valor incorrecto +Value can't be blank: El valor no puede estar en blanco +Value can't be null: El valor no puede ser nulo +Value should be %s characters long: El valor debe ser de %s carácteres de longitud +Value should have a length between %s and %s: El valor debe tener una longitud de entre %s y %s +Value should have at least %s characters: El valor debe tener al menos %s carácteres +Value should have at most %s characters: El valor debe tener un máximo de %s carácteres +Enter a new search: Introduce una nueva búsqueda +No results: Sin resultados +Ups! It seems there was an error: ¡Vaya! Parece que ha habido un error +General search: Busqueda general +January: Enero +February: Febrero +March: Marzo +April: Abril +May: Mayo +June: Junio +July: Julio +August: Agosto +September: Septiembre +October: Octubre +November: Noviembre +December: Diciembre +Monday: Lunes +Tuesday: Martes +Wednesday: Miércoles +Thursday: Jueves +Friday: Viernes +Saturday: Sábado +Sunday: Domingo +Has delivery: Hay reparto +Loading: Cargando +Fields to show: Campos a mostrar +Create new one: Crear nuevo +Toggle: Desplegar/Plegar +Check all: Seleccionar todo +Select a file: Selecciona un fichero +Edit: Editar +Edit item: Editar elemento +No records found: No se han encontrado elementos +Day: Día +Days: Días +Go up: Ir arriba +Loading...: Cargando... +No results found: Sin resultados +No data: Sin datos +Load more: Cargar más \ No newline at end of file diff --git a/front/core/mocks/crud-model.js b/front/core/mocks/crud-model.js new file mode 100644 index 000000000..af6406eec --- /dev/null +++ b/front/core/mocks/crud-model.js @@ -0,0 +1,37 @@ +module.exports = { + data: [], + filter: {}, + order: {}, + + insert: () => { + return { + then: callback => { + callback({data: {id: 1234}}); + } + }; + }, + remove: () => { + return { + then: callback => { + callback({data: {id: 1234}}); + } + }; + }, + save: () => { + return { + then: callback => { + callback({data: {id: 1234}}); + } + }; + }, + on: () => { + return { + then: callback => { + callback({data: {id: 1234}}); + } + }; + }, + refresh: () => {}, + addFilter: () => {}, + applyFilter: () => {}, +}; diff --git a/front/core/mocks/watcher.js b/front/core/mocks/watcher.js new file mode 100644 index 000000000..05022bf88 --- /dev/null +++ b/front/core/mocks/watcher.js @@ -0,0 +1,21 @@ +module.exports = { + submit: () => { + return { + then: callback => { + callback({data: {id: 1234}}); + } + }; + }, + realSubmit: () => { + return { + then: callback => { + callback({data: {id: 1234}}); + } + }; + }, + check: () => {}, + notifySaved: () => {}, + setDirty: () => {}, + setPristine: () => {}, + updateOriginalData: () => {} +}; diff --git a/front/core/module.js b/front/core/module.js new file mode 100644 index 000000000..0c52fd565 --- /dev/null +++ b/front/core/module.js @@ -0,0 +1,106 @@ +import {ng, ngDeps} from './vendor'; +import {camelToKebab} from './lib/string'; + +/** + * Acts like native Module.component() function but merging component options + * with parent component options. This method establishes the $options property + * to the component controller class with the merged component options. To + * retrieve parent options, it reads the same property of the parent class, so + * for the parent options to be copied, it must have been declared using this + * same function. If any of the options (template, transclude, bindings...) is + * redeclared in the child component, the last has preference. + * + * @param {String} name Coponent name in camelCase + * @param {Object} options The component options + * @return {angularModule} The same angular module + */ +function vnComponent(name, options) { + let controller = options.controller; + let parent = Object.getPrototypeOf(controller); + let parentOptions = parent.$options || {}; + + let parentTransclude = parentOptions.transclude; + let transclude = parentTransclude instanceof Object + ? Object.assign({}, parentTransclude) + : parentTransclude; + + if (options.transclude instanceof Object) { + if (transclude instanceof Object) + Object.assign(transclude, options.transclude); + else + transclude = options.transclude; + } else if (options.transclude !== undefined) + transclude = options.transclude; + + let mergedOptions = Object.assign({}, + parentOptions, + options, + { + transclude, + bindings: Object.assign({}, + parentOptions.bindings, + options.bindings + ), + require: Object.assign({}, + parentOptions.require, + options.require + ) + } + ); + controller.$options = mergedOptions; + + let classNames = [camelToKebab(name)]; + if (parent.$classNames) classNames = classNames.concat(parent.$classNames); + controller.$classNames = classNames; + + return this.component(name, mergedOptions); +} + +const ngModuleFn = ng.module; + +ng.module = function(...args) { + let ngModule = ngModuleFn.apply(this, args); + ngModule.vnComponent = vnComponent; + return ngModule; +}; + +const ngModule = ng.module('vnCore', ngDeps); +export default ngModule; + +config.$inject = ['$translateProvider', '$translatePartialLoaderProvider', '$animateProvider']; +export function config($translateProvider, $translatePartialLoaderProvider, $animateProvider) { + // For CSS browser targeting + document.documentElement.setAttribute('data-browser', navigator.userAgent); + + $translatePartialLoaderProvider.addPart('core'); + + let conf = {urlTemplate: '/locale/{part}/{lang}.json'}; + + let fallbackLang = 'es'; + let langs = ['en', 'es']; + let langAliases = { + en_US: 'en', + en_UK: 'en', + es_ES: 'es', + es_AR: 'es' + }; + + $translateProvider + .useSanitizeValueStrategy('escape') + .useLoader('$translatePartialLoader', conf) + .registerAvailableLanguageKeys(langs, langAliases) + // FIXME: Circular dependency due to vnInterceptor + // .fallbackLanguage(fallbackLang) + .determinePreferredLanguage(() => { + let locale = $translateProvider.resolveClientLocale(); + if (langs.indexOf(locale) !== -1) + return locale; + if (langAliases[locale]) + return langAliases[locale]; + return fallbackLang; + }); + + $animateProvider.customFilter( + node => node.tagName == 'UI-VIEW'); +} +ngModule.config(config); diff --git a/front/core/services/acl-service.js b/front/core/services/acl-service.js new file mode 100644 index 000000000..ee4404d34 --- /dev/null +++ b/front/core/services/acl-service.js @@ -0,0 +1,37 @@ +import ngModule from '../module'; + +class AclService { + constructor($http) { + this.$http = $http; + } + + reset() { + this.user = null; + this.roles = null; + } + + load() { + return this.$http.get('Accounts/acl').then(res => { + this.user = res.data.user; + this.roles = {}; + + for (let role of res.data.roles) { + if (role.role) + this.roles[role.role.name] = true; + } + }); + } + + hasAny(roles) { + if (this.roles) { + for (let role of roles) { + if (this.roles[role]) + return true; + } + } + return false; + } +} +AclService.$inject = ['$http']; + +ngModule.service('aclService', AclService); diff --git a/front/core/services/app.js b/front/core/services/app.js new file mode 100644 index 000000000..6b2cd1d2a --- /dev/null +++ b/front/core/services/app.js @@ -0,0 +1,43 @@ +import ngModule from '../module'; + +/** + * The main application class. + * + * @property {String} name The application name. + * @property {Snackbar} snackbar The main object to show messages. + */ +export default class App { + constructor() { + this.loaderStatus = 0; + this.loading = false; + } + + showMessage(message) { + if (this.logger) + this.logger.showMessage(message); + } + + showSuccess(message) { + if (this.logger) + this.logger.showSuccess(message); + } + + showError(message) { + if (this.logger) + this.logger.showError(message); + } + + pushLoader() { + this.loaderStatus++; + if (this.loaderStatus === 1) + this.loading = true; + } + + popLoader() { + this.loaderStatus--; + if (this.loaderStatus === 0) + this.loading = false; + } +} + +ngModule.service('vnApp', App); diff --git a/front/core/services/auth.js b/front/core/services/auth.js new file mode 100644 index 000000000..f59c4c0dd --- /dev/null +++ b/front/core/services/auth.js @@ -0,0 +1,100 @@ +import ngModule from '../module'; +import UserError from 'core/lib/user-error'; + +/** + * Authentication service. + * + * @property {Boolean} loggedIn Whether the user is currently logged + */ +export default class Auth { + constructor($http, $q, $state, $transitions, $window, vnToken, vnModules, aclService) { + Object.assign(this, { + $http, + $q, + $state, + $transitions, + $window, + vnToken, + vnModules, + aclService, + loggedIn: false + }); + } + + initialize() { + let criteria = { + to: state => state.name != 'login' + }; + this.$transitions.onStart(criteria, transition => { + if (this.loggedIn) + return true; + + let redirectToLogin = () => { + return transition.router.stateService.target('login', { + continue: this.$window.location.hash + }); + }; + + if (this.vnToken.token) { + return this.loadAcls() + .then(() => true) + .catch(redirectToLogin); + } else + return redirectToLogin(); + }); + } + + login(user, password, remember) { + if (!user) + return this.$q.reject(new UserError('Please enter your username')); + + let params = { + user, + password: password || undefined + }; + + return this.$http.post('Accounts/login', params).then( + json => this.onLoginOk(json, remember)); + } + + onLoginOk(json, remember) { + this.vnToken.set(json.data.token, remember); + + return this.loadAcls().then(() => { + let continueHash = this.$state.params.continue; + if (continueHash) + this.$window.location = continueHash; + else + this.$state.go('home'); + }); + } + + logout() { + let promise = this.$http.post('Accounts/logout', null, { + headers: {Authorization: this.vnToken.token} + }).catch(() => {}); + + this.vnToken.unset(); + this.loggedIn = false; + this.vnModules.reset(); + this.aclService.reset(); + this.$state.go('login'); + + return promise; + } + + loadAcls() { + return this.aclService.load() + .then(() => { + this.loggedIn = true; + this.vnModules.reset(); + }) + .catch(err => { + this.vnToken.unset(); + throw err; + }); + } +} +Auth.$inject = ['$http', '$q', '$state', '$transitions', '$window', 'vnToken', 'vnModules', 'aclService']; + +ngModule.service('vnAuth', Auth); diff --git a/front/core/services/config.js b/front/core/services/config.js new file mode 100644 index 000000000..8fa07e85c --- /dev/null +++ b/front/core/services/config.js @@ -0,0 +1,79 @@ +import ngModule from '../module'; + +/** + * Saves and loads the application configuration. + */ +export default class Config { + constructor($http, vnApp, $translate, $window) { + Object.assign(this, { + $http, + vnApp, + $translate, + storage: $window.localStorage, + user: {}, + local: {} + }); + + this.params = [ + 'warehouseFk', + 'companyFk', + 'bankFk' + ]; + } + + initialize() { + for (let param of this.params) + this.local[param] = this.getItem(param); + + return this.$http.get('UserConfigs/getUserConfig') + .then(res => { + for (let param of this.params) + this.user[param] = res.data[param]; + }) + .finally(() => this.mergeParams()); + } + + mergeParams() { + for (let param of this.params) { + let local = this.local[param]; + this[param] = local != null && local != '' + ? local + : this.user[param]; + } + } + + setUser(param, value) { + this.user[param] = value; + this.mergeParams(); + + let params = {[param]: value}; + return this.$http.post('UserConfigs/setUserConfig', params) + .then(() => this.showSaved()); + } + + setLocal(param, value) { + this.setItem(param, value); + this.local[param] = value; + this.mergeParams(); + this.showSaved(); + } + + showSaved() { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + } + + getItem(key) { + let value = this.storage[key]; + return value !== undefined ? JSON.parse(value) : value; + } + + setItem(key, value) { + if (value == null) + this.storage.removeItem(key); + else + this.storage[key] = JSON.stringify(value); + } +} +Config.$inject = ['$http', 'vnApp', '$translate', '$window']; + +ngModule.service('vnConfig', Config); diff --git a/front/core/services/index.js b/front/core/services/index.js new file mode 100644 index 000000000..4573ab5c9 --- /dev/null +++ b/front/core/services/index.js @@ -0,0 +1,9 @@ + +import './acl-service'; +import './app'; +import './auth'; +import './token'; +import './modules'; +import './interceptor'; +import './config'; +import './week-days'; diff --git a/front/core/services/interceptor.js b/front/core/services/interceptor.js new file mode 100644 index 000000000..b7cf3a0ec --- /dev/null +++ b/front/core/services/interceptor.js @@ -0,0 +1,43 @@ +import ngModule from '../module'; +import HttpError from 'core/lib/http-error'; + +interceptor.$inject = ['$q', 'vnApp', 'vnToken', '$translate']; +function interceptor($q, vnApp, vnToken, $translate) { + let apiPath = 'api/'; + + return { + setApiPath(path) { + apiPath = path; + }, + request(config) { + vnApp.pushLoader(); + + if (config.url.charAt(0) !== '/' && apiPath) + config.url = `${apiPath}${config.url}`; + if (vnToken.token) + config.headers.Authorization = vnToken.token; + if ($translate.use()) + config.headers['Accept-Language'] = $translate.use(); + if (config.filter) { + if (!config.params) config.params = {}; + config.params.filter = config.filter; + } + + return config; + }, + requestError(rejection) { + return $q.reject(rejection); + }, + response(response) { + vnApp.popLoader(); + return response; + }, + responseError(rejection) { + vnApp.popLoader(); + let err = new HttpError(rejection.statusText); + Object.assign(err, rejection); + return $q.reject(err); + } + }; +} +ngModule.factory('vnInterceptor', interceptor); diff --git a/front/core/services/locale/en.yml b/front/core/services/locale/en.yml new file mode 100644 index 000000000..2be73e696 --- /dev/null +++ b/front/core/services/locale/en.yml @@ -0,0 +1,6 @@ +Invalid login: Invalid login, remember that distinction is made between uppercase and lowercase +Could not contact the server: Could not contact the server, make sure you have a connection to the network +Please enter your username: Please enter your username +It seems that the server has fall down: It seems that the server has fall down, wait a few minutes and try again +Session has expired: Your session has expired, please login again +Access denied: Access denied \ No newline at end of file diff --git a/front/core/services/locale/es.yml b/front/core/services/locale/es.yml new file mode 100644 index 000000000..cf8801b52 --- /dev/null +++ b/front/core/services/locale/es.yml @@ -0,0 +1,6 @@ +Invalid login: Usuario o contraseña incorrectos, recuerda que se hace distinción entre mayúsculas y minúsculas +Could not contact the server: No se ha podido contactar con el servidor, asegurate de que dispones de conexión con la red +Please enter your username: Por favor introduce tu nombre de usuario +It seems that the server has fall down: Parece que el servidor se ha caído, espera unos minutos e inténtalo de nuevo +Session has expired: Tu sesión ha expirado, por favor vuelve a iniciar sesión +Access denied: Acción no permitida \ No newline at end of file diff --git a/front/core/services/modules.js b/front/core/services/modules.js new file mode 100644 index 000000000..1021bc4fa --- /dev/null +++ b/front/core/services/modules.js @@ -0,0 +1,47 @@ +import ngModule from '../module'; +import getMainRoute from '../lib/get-main-route'; + +export default class Modules { + constructor(aclService, $window) { + Object.assign(this, { + aclService, + $window + }); + } + + reset() { + this.modules = null; + } + + get() { + if (this.modules) + return this.modules; + + this.modules = []; + for (let mod of this.$window.routes) { + if (!mod || !mod.routes) continue; + + let route = getMainRoute(mod.routes); + if (!route || (route.acl && !this.aclService.hasAny(route.acl))) + continue; + + let keyBind; + if (mod.keybindings) { + let res = mod.keybindings.find(i => i.state == route.state); + if (res) keyBind = res.key.toUpperCase(); + } + + this.modules.push({ + name: mod.name || mod.module, + icon: mod.icon || null, + route, + keyBind + }); + } + + return this.modules; + } +} +Modules.$inject = ['aclService', '$window']; + +ngModule.service('vnModules', Modules); diff --git a/front/core/services/token.js b/front/core/services/token.js new file mode 100644 index 000000000..126fbb604 --- /dev/null +++ b/front/core/services/token.js @@ -0,0 +1,34 @@ +import ngModule from '../module'; + +/** + * Saves and loads the token for the current logged in user. + * + * @property {String} token The current login token or %null + */ +export default class Token { + constructor() { + try { + this.token = sessionStorage.getItem('vnToken'); + if (!this.token) + this.token = localStorage.getItem('vnToken'); + } catch (e) {} + } + set(value, remember) { + this.unset(); + try { + if (remember) + localStorage.setItem('vnToken', value); + else + sessionStorage.setItem('vnToken', value); + } catch (e) {} + + this.token = value; + } + unset() { + localStorage.removeItem('vnToken'); + sessionStorage.removeItem('vnToken'); + this.token = null; + } +} + +ngModule.service('vnToken', Token); diff --git a/front/core/services/week-days.js b/front/core/services/week-days.js new file mode 100644 index 000000000..698d6df2c --- /dev/null +++ b/front/core/services/week-days.js @@ -0,0 +1,116 @@ +import ngModule from '../module'; + +/** + * @property {Array} days Weekdays data array with the same indexes as Date.getDay() + * @property {Object} map Weekdays data map using weekday codes as key + * @property {Array} localeCodes Locale weekday codes indexes depend on current locale + * @property {Array} locale Weekday data array with indexes depending on current locale + * + * Weekday properties: + * + * @property {Number} index The weekday index acording to Date.getDay() + * @property {String} code The weekday code + * @property {String} name The weekday name + * @property {String} char The first weekday letter + * @property {String} abr The abreviated 3 letters weekday name + * @property {String} locale The weekday name in current locale + * @property {String} localeChar The first weekday letter in current locale + * @property {String} localeAbr The abreviated 3 letters weekday name in current locale + */ +class WeekDays { + constructor($translate) { + this.$translate = $translate; + + this.days = [ + { + code: 'sun', + name: 'Sunday' + }, { + code: 'mon', + name: 'Monday' + }, { + code: 'tue', + name: 'Tuesday' + }, { + code: 'wed', + name: 'Wednesday' + }, { + code: 'thu', + name: 'Thursday' + }, { + code: 'fri', + name: 'Friday' + }, { + code: 'sat', + name: 'Saturday' + } + ]; + + this.map = {}; + for (let i = 0; i < this.days.length; i++) { + let day = this.days[i]; + day.index = i; + day.char = day.name.substr(0, 1); + day.abr = day.name.substr(0, 3); + this.map[day.code] = day; + } + + this.getLocales(); + } + + getLocales() { + for (let day of this.days) { + let locale = this.$translate.instant(day.name); + Object.assign(day, { + locale, + localeChar: locale.substr(0, 1), + localeAbr: locale.substr(0, 3) + }); + } + + this.localeCodes = [ + 'mon', + 'tue', + 'wed', + 'thu', + 'fri', + 'sat', + 'sun' + ]; + + this.locales = []; + for (let code of this.localeCodes) + this.locales.push(this.map[code]); + } + + fromSet(weekDays) { + let wdays = []; + + if (weekDays) { + let codes = weekDays.split(','); + for (let code of codes) { + let data = this.map[code]; + if (data) wdays[data.index] = true; + } + } + + return wdays; + } + + toSet(wdays) { + let weekDays = []; + + if (wdays) { + for (let i = 0; i < wdays.length; i++) { + if (!wdays[i]) continue; + let data = this.days[i]; + if (data) weekDays.push(data.code); + } + } + + return weekDays.join(','); + } +} +WeekDays.$inject = ['$translate']; + +ngModule.service('vnWeekDays', WeekDays); diff --git a/front/core/styles/animations.scss b/front/core/styles/animations.scss new file mode 100644 index 000000000..039f79c77 --- /dev/null +++ b/front/core/styles/animations.scss @@ -0,0 +1,30 @@ + +@keyframes nothing {} +@keyframes slideIn { + from { + transform: translate3d(-2em, 0, 0); + opacity: 0; + } + to { + transform: translate3d(0, 0, 0); + opacity: 1; + } +} +@keyframes amplify { + from { + opacity: 0; + transform: scale3d(0, 0, 0); + } + to { + opacity: 1; + transform: scale3d(1, 1, 1); + } +} +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} \ No newline at end of file diff --git a/front/core/styles/background.scss b/front/core/styles/background.scss new file mode 100644 index 000000000..0b96250b5 --- /dev/null +++ b/front/core/styles/background.scss @@ -0,0 +1,17 @@ +@import "./variables"; + +.bg-panel { + background-color: $color-bg-panel; +} +.item-hightlight { + background-color: $color-hightlight; +} +.item-disabled { + opacity: $color-disabled; +} +.vn-shadow { + box-shadow: $shadow; +} +.invisible { + visibility: hidden; +} diff --git a/front/core/styles/border.scss b/front/core/styles/border.scss new file mode 100644 index 000000000..7450b5857 --- /dev/null +++ b/front/core/styles/border.scss @@ -0,0 +1,23 @@ +@import "./variables"; + +.border-solid { + border: $border-thin-light; +} +.border-solid-top { + border-top: $border-thin-light; +} +.border-solid-left { + border-left: $border-thin-light; +} +.border-solid-right { + border-right: $border-thin-light; +} +.border-solid-bottom { + border-bottom: $border-thin-light; +} + +/* Border Radius */ + +.border-radius { + border-radius: .3em; +} \ No newline at end of file diff --git a/front/core/styles/effects.scss b/front/core/styles/effects.scss new file mode 100644 index 000000000..205a23bd2 --- /dev/null +++ b/front/core/styles/effects.scss @@ -0,0 +1,28 @@ +@import "./variables"; + +%clickable { + cursor: pointer; + transition: background-color 250ms ease-out; + + &:hover, + &:focus { + background-color: $color-hover-cd; + outline: none; + } +} + +%clickable-light { + cursor: pointer; + transition: opacity 250ms ease-out; + + &:hover, + &:focus { + opacity: $color-hover-dc; + outline: none; + } +} + +%active { + background-color: $color-active; + color: $color-active-font; +} diff --git a/front/core/styles/font-family.scss b/front/core/styles/font-family.scss new file mode 100644 index 000000000..b461917ce --- /dev/null +++ b/front/core/styles/font-family.scss @@ -0,0 +1,41 @@ +@font-face { + font-family: vn-font-medium; + src: url(./fonts/Roboto-Medium.ttf); +} +@font-face { + font-family: vn-font; + src: url(./fonts/Roboto-Regular.ttf); +} +@font-face { + font-family: vn-font-bold; + src: url(./fonts/Roboto-Bold.ttf); +} +@font-face { + font-family: 'Material Icons'; + font-style: normal; + font-weight: 400; + src: url('./icons/Material-Design-Icons.woff2') format('woff2'); +} + +.material-icons { + font-family: 'Material Icons'; + font-weight: normal; + font-style: normal; + font-size: 24px; /* Preferred icon size */ + display: inline-block; + line-height: 1; + text-transform: none; + letter-spacing: normal; + word-wrap: normal; + white-space: nowrap; + direction: ltr; + + /* Support for all WebKit browsers. */ + -webkit-font-smoothing: antialiased; + /* Support for Safari and Chrome. */ + text-rendering: optimizeLegibility; + /* Support for Firefox. */ + -moz-osx-font-smoothing: grayscale; + /* Support for IE. */ + font-feature-settings: 'liga'; +} diff --git a/client/salix/src/styles/fonts/Roboto-Bold.ttf b/front/core/styles/fonts/Roboto-Bold.ttf similarity index 100% rename from client/salix/src/styles/fonts/Roboto-Bold.ttf rename to front/core/styles/fonts/Roboto-Bold.ttf diff --git a/client/salix/src/styles/fonts/Roboto-Medium.ttf b/front/core/styles/fonts/Roboto-Medium.ttf similarity index 100% rename from client/salix/src/styles/fonts/Roboto-Medium.ttf rename to front/core/styles/fonts/Roboto-Medium.ttf diff --git a/client/salix/src/styles/fonts/Roboto-Regular.ttf b/front/core/styles/fonts/Roboto-Regular.ttf similarity index 100% rename from client/salix/src/styles/fonts/Roboto-Regular.ttf rename to front/core/styles/fonts/Roboto-Regular.ttf diff --git a/front/core/styles/global.scss b/front/core/styles/global.scss new file mode 100644 index 000000000..8b3d465f1 --- /dev/null +++ b/front/core/styles/global.scss @@ -0,0 +1,47 @@ +@import "variables"; + +html { + background-color: $color-bg; + overflow: auto; + height: 100%; +} +body { + height: 100%; + font-family: vn-font; + color: $color-font; + font-size: $font-size; + margin: 0; + padding: 0; +} +a:focus { + outline: 1px solid $color-spacer-light; +} +input, +button { + &:focus { + outline: none; + } +} +button, +input { + &::-moz-focus-inner { + border: none; + } +} +input[type=submit], +input[type=button], +button { + cursor: pointer; + + &:disabled { + opacity: .7; + } +} +a { + color: $color-font-link; + text-decoration: none; +} +.ng-leave, +.ng-enter { + transition: none; +} \ No newline at end of file diff --git a/client/core/src/styles/Material-Design-Icons.woff2 b/front/core/styles/icons/Material-Design-Icons.woff2 similarity index 100% rename from client/core/src/styles/Material-Design-Icons.woff2 rename to front/core/styles/icons/Material-Design-Icons.woff2 diff --git a/front/core/styles/icons/salixfont.css b/front/core/styles/icons/salixfont.css new file mode 100644 index 000000000..e3bdda503 --- /dev/null +++ b/front/core/styles/icons/salixfont.css @@ -0,0 +1,292 @@ +@font-face { + font-family: 'salixfont'; + src: + url('./salixfont.ttf?wtrl3') format('truetype'), + url('./salixfont.woff?wtrl3') format('woff'), + url('./salixfont.svg?wtrl3#salixfont') format('svg'); + font-weight: normal; + font-style: normal; +} + +[class^="icon-"], [class*=" icon-"] { + /* use !important to prevent issues with browser extensions that change fonts */ + font-family: 'salixfont' !important; + speak: none; + font-style: normal; + font-weight: normal; + font-variant: normal; + text-transform: none; + line-height: 1; + + /* Better Font Rendering =========== */ + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +.icon-fruit:before { + content: "\e957"; +} +.icon-deliveryprices:before { + content: "\e956"; +} +.icon-basketadd:before { + content: "\e955"; +} +.icon-catalog:before { + content: "\e952"; +} +.icon-agency:before { + content: "\e910"; +} +.icon-delivery:before { + content: "\e94a"; +} +.icon-wand:before { + content: "\e954"; +} +.icon-unavailable:before { + content: "\e953"; +} +.icon-buscaman:before { + content: "\e951"; +} +.icon-pbx:before { + content: "\e950"; +} +.icon-calendar:before { + content: "\e94f"; +} +.icon-linesplit:before { + content: "\e945"; +} +.icon-invoices:before { + content: "\e91c"; +} +.icon-pets:before { + content: "\e94e"; +} +.icon-100:before { + content: "\e940"; +} +.icon-accessory:before { + content: "\e90a"; +} +.icon-actions:before { + content: "\e900"; +} +.icon-addperson:before { + content: "\e901"; +} +.icon-albaran:before { + content: "\e902"; +} +.icon-apps:before { + content: "\e948"; +} +.icon-artificial:before { + content: "\e903"; +} +.icon-barcode:before { + content: "\e904"; +} +.icon-basket:before { + content: "\e942"; +} +.icon-bin:before { + content: "\e905"; +} +.icon-botanical:before { + content: "\e906"; +} +.icon-bucket:before { + content: "\e907"; +} +.icon-claims:before { + content: "\e908"; +} +.icon-clone:before { + content: "\e909"; +} +.icon-columnadd:before { + content: "\e944"; +} +.icon-columndelete:before { + content: "\e90f"; +} +.icon-components:before { + content: "\e90b"; +} +.icon-consignatarios:before { + content: "\e90d"; +} +.icon-control:before { + content: "\e93f"; +} +.icon-credit:before { + content: "\e90e"; +} +.icon-details:before { + content: "\e911"; +} +.icon-disabled:before { + content: "\e91b"; +} +.icon-doc:before { + content: "\e913"; +} +.icon-entry:before { + content: "\e914"; +} +.icon-exit:before { + content: "\e947"; +} +.icon-eye:before { + content: "\e915"; +} +.icon-fiscal:before { + content: "\e912"; +} +.icon-flower:before { + content: "\e916"; +} +.icon-frozen:before { + content: "\e917"; +} +.icon-greenery:before { + content: "\e93c"; +} +.icon-greuge:before { + content: "\e918"; +} +.icon-grid:before { + content: "\e919"; +} +.icon-handmade:before { + content: "\e90c"; +} +.icon-history:before { + content: "\e91a"; +} +.icon-info:before { + content: "\e949"; +} +.icon-item:before { + content: "\e941"; +} +.icon-languaje:before { + content: "\e91d"; +} +.icon-linedelete:before { + content: "\e946"; +} +.icon-lines:before { + content: "\e91e"; +} +.icon-linesprepaired:before { + content: "\e94b"; +} +.icon-logout:before { + content: "\e91f"; +} +.icon-mana:before { + content: "\e920"; +} +.icon-mandatory:before { + content: "\e921"; +} +.icon-niche:before { + content: "\e922"; +} +.icon-no036:before { + content: "\e923"; +} +.icon-notes:before { + content: "\e924"; +} +.icon-noweb:before { + content: "\e925"; +} +.icon-onlinepayment:before { + content: "\e926"; +} +.icon-package:before { + content: "\e927"; +} +.icon-payment:before { + content: "\e928"; +} +.icon-person:before { + content: "\e929"; +} +.icon-photo:before { + content: "\e92a"; +} +.icon-plant:before { + content: "\e92b"; +} +.icon-recovery:before { + content: "\e92d"; +} +.icon-regentry:before { + content: "\e92e"; +} +.icon-reserve:before { + content: "\e92f"; +} +.icon-revision:before { + content: "\e94c"; +} +.icon-risk:before { + content: "\e930"; +} +.icon-services:before { + content: "\e94d"; +} +.icon-settings:before { + content: "\e931"; +} +.icon-sms:before { + content: "\e932"; +} +.icon-solclaim:before { + content: "\e933"; +} +.icon-solunion:before { + content: "\e934"; +} +.icon-splur:before { + content: "\e935"; +} +.icon-stowaway:before { + content: "\e92c"; +} +.icon-supplier:before { + content: "\e936"; +} +.icon-tags:before { + content: "\e937"; +} +.icon-tax:before { + content: "\e938"; +} +.icon-ticket:before { + content: "\e939"; +} +.icon-traceability:before { + content: "\e93a"; +} +.icon-transaction:before { + content: "\e93b"; +} +.icon-volume:before { + content: "\e93d"; +} +.icon-web:before { + content: "\e93e"; +} +.icon-worker:before { + content: "\e943"; +} +.icon-deletedTicket:before { + content: "\e958"; +} diff --git a/front/core/styles/icons/salixfont.svg b/front/core/styles/icons/salixfont.svg new file mode 100644 index 000000000..26b1a31e9 --- /dev/null +++ b/front/core/styles/icons/salixfont.svg @@ -0,0 +1,99 @@ + + + +Generated by IcoMoon + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/front/core/styles/icons/salixfont.ttf b/front/core/styles/icons/salixfont.ttf new file mode 100644 index 000000000..3242d75be Binary files /dev/null and b/front/core/styles/icons/salixfont.ttf differ diff --git a/front/core/styles/icons/salixfont.woff b/front/core/styles/icons/salixfont.woff new file mode 100644 index 000000000..e2f312391 Binary files /dev/null and b/front/core/styles/icons/salixfont.woff differ diff --git a/front/core/styles/index.js b/front/core/styles/index.js new file mode 100644 index 000000000..dd35b7bfd --- /dev/null +++ b/front/core/styles/index.js @@ -0,0 +1,11 @@ +import './animations.scss'; +import './background.scss'; +import './border.scss'; +import './font-family.scss'; +import './global.scss'; +import './icons/salixfont.css'; +import './layout.scss'; +import './responsive.scss'; +import './spacing.scss'; +import './text.scss'; +import './width.scss'; diff --git a/client/salix/src/styles/layout.scss b/front/core/styles/layout.scss similarity index 80% rename from client/salix/src/styles/layout.scss rename to front/core/styles/layout.scss index c952abe37..925526dca 100644 --- a/client/salix/src/styles/layout.scss +++ b/front/core/styles/layout.scss @@ -1,17 +1,4 @@ -html, body { - height: 100%; - margin: 0px; - padding: 0px; -} - -html [full-height], .full-height { - height: 100%; -} -html [self-scroll], .self-scroll { - overflow: auto; -} - /* Horizontal & vertical */ html [vn-horizontal], vn-horizontal, .vn-horizontal, @@ -36,11 +23,6 @@ html [wrap] { html [wrap-reverse] { flex-wrap: wrap-reverse; } -html [scrollable] { - min-height: 1px; - flex: 1; - flex-basis: 0.000000001px; -} /* Horizontal & vertical childs */ @@ -64,7 +46,6 @@ html [vn-auto], vn-auto, .vn-auto { flex-basis: auto; } html [vn-none], vn-none, .vn-none { - flex: 1; flex: none; } html [vn-one], vn-one, .vn-one { diff --git a/front/core/styles/responsive.scss b/front/core/styles/responsive.scss new file mode 100644 index 000000000..9cc58dd12 --- /dev/null +++ b/front/core/styles/responsive.scss @@ -0,0 +1,55 @@ +@import "variables"; + +/* Desktop - Laptop 1360x768 */ +@media (max-resolution: 119dpi) and (min-device-width: 1340px) and (max-device-width: 1899px) +{ + body { font-size: 10pt; } +} + +/* Mobile - Low DPI */ +@media + (min-resolution: 120dpi), + (-webkit-min-device-pixel-ratio: 1.5) +{ + body { font-size: 9pt; } +} +@media + (min-resolution: 144dpi), + (-webkit-min-device-pixel-ratio: 1.5) +{ + body { font-size: 11pt; } +} + +/* Mobile - Normal DPI */ +@media + (max-device-width: 383px) and (min-resolution: 192dpi), + (max-device-width: 383px) and (-webkit-min-device-pixel-ratio: 2) +{ + body { font-size: 10pt; } +} +@media + (min-device-width: 384px) and (min-resolution: 192dpi), + (min-device-width: 384px) and (-webkit-min-device-pixel-ratio: 2) +{ + body { font-size: 11pt; } +} + +/* Mobile - High DPI */ +@media + (max-device-width: 411px) and (min-resolution: 249dpi), + (max-device-width: 411px) and (-webkit-min-device-pixel-ratio: 3) +{ + body { font-size: 10pt; } +} +@media + (min-device-width: 412px) and (min-resolution: 249dpi), + (min-device-width: 412px) and (-webkit-min-device-pixel-ratio: 3) +{ + body { font-size: 11pt; } +} + +.vn-hide-narrow { + @media (max-width: $mobile-width) { + display: none; + } +} diff --git a/front/core/styles/spacing.scss b/front/core/styles/spacing.scss new file mode 100644 index 000000000..35e3fa10d --- /dev/null +++ b/front/core/styles/spacing.scss @@ -0,0 +1,355 @@ +/** + * CSS spacing classes + * + * vn-[p|m][t|r|b|l|a|x|y]-[none|auto|xs|sm|md|lg|xl] + * T D S + * + * T - type + * - values: p (padding), m (margin) + * + * D - direction + * - values: + * t (top), r (right), b (bottom), l (left), + * a (all), x (both left & right), y (both top & bottom) + * + * S - size + * - values: + * none, + * auto (ONLY for specific margins: vn-ml-*, vn-mr-*, vn-mx-*), + * xs (extra small), + * sm (small), + * md (medium), + * lg (large), + * xl (extra large) + */ + + @import "./variables"; + +//++++++++++++++++++++++++++++++++++++++++++++++++ Padding + +// None + +.vn-pa-none { + padding: 0; +} +.vn-pl-none { + padding-left: 0; +} +.vn-pr-none { + padding-right: 0; +} +.vn-pt-none { + padding-top: 0; +} +.vn-pb-none { + padding-bottom: 0; +} +.vn-py-none { + padding-top: 0; + padding-bottom: 0; +} +.vn-px-none { + padding-left: 0; + padding-right: 0; +} + +// Extra small + +.vn-pa-xs { + padding: $spacing-xs; +} +.vn-pl-xs { + padding-left: $spacing-xs; +} +.vn-pr-xs { + padding-right: $spacing-xs; +} +.vn-pt-xs { + padding-top: $spacing-xs; +} +.vn-pb-xs { + padding-bottom: $spacing-xs; +} +.vn-py-xs { + padding-top: $spacing-xs; + padding-bottom: $spacing-xs; +} +.vn-px-xs { + padding-left: $spacing-xs; + padding-right: $spacing-xs; +} + +// Small + +.vn-pa-sm { + padding: $spacing-sm; +} +.vn-pl-sm { + padding-left: $spacing-sm; +} +.vn-pr-sm { + padding-right: $spacing-sm; +} +.vn-pt-sm { + padding-top: $spacing-sm; +} +.vn-pb-sm { + padding-bottom: $spacing-sm; +} +.vn-py-sm { + padding-top: $spacing-sm; + padding-bottom: $spacing-sm; +} +.vn-px-sm { + padding-left: $spacing-sm; + padding-right: $spacing-sm; +} + +// Medium + +.vn-pa-md { + padding: $spacing-md; +} +.vn-pl-md { + padding-left: $spacing-md; +} +.vn-pr-md { + padding-right: $spacing-md; +} +.vn-pt-md { + padding-top: $spacing-md; +} +.vn-pb-md { + padding-bottom: $spacing-md; +} +.vn-py-md { + padding-top: $spacing-md; + padding-bottom: $spacing-md; +} +.vn-px-md { + padding-left: $spacing-md; + padding-right: $spacing-md; +} + +// Large + +.vn-pa-lg { + padding: $spacing-lg; +} +.vn-pl-lg { + padding-left: $spacing-lg; +} +.vn-pr-lg { + padding-right: $spacing-lg; +} +.vn-pt-lg { + padding-top: $spacing-lg; +} +.vn-pb-lg { + padding-bottom: $spacing-lg; +} +.vn-py-lg { + padding-top: $spacing-lg; + padding-bottom: $spacing-lg; +} +.vn-px-lg { + padding-left: $spacing-lg; + padding-right: $spacing-lg; +} + +// Extra large + +.vn-pa-xl { + padding: $spacing-xl; +} +.vn-pl-xl { + padding-left: $spacing-xl; +} +.vn-pr-xl { + padding-right: $spacing-xl; +} +.vn-pt-xl { + padding-top: $spacing-xl; +} +.vn-pb-xl { + padding-bottom: $spacing-xl; +} +.vn-py-xl { + padding-top: $spacing-xl; + padding-bottom: $spacing-xl; +} +.vn-px-xl { + padding-left: $spacing-xl; + padding-right: $spacing-xl; +} + +//++++++++++++++++++++++++++++++++++++++++++++++++ Margin + +// None + +.vn-ma-none { + padding: 0; +} +.vn-ml-none { + padding-left: 0; +} +.vn-mr-none { + padding-right: 0; +} +.vn-mt-none { + padding-top: 0; +} +.vn-mb-none { + padding-bottom: 0; +} +.vn-my-none { + padding-top: 0; + padding-bottom: 0; +} +.vn-mx-none { + padding-left: 0; + padding-right: 0; +} + +// Auto + +.vn-ml-none { + padding-left: auto; +} +.vn-mr-none { + padding-right: auto; +} +.vn-mx-none { + padding-left: auto; + padding-right: auto; +} + +// Extra small + +.vn-ma-xs { + margin: $spacing-xs; +} +.vn-mt-xs { + margin-top: $spacing-xs; +} +.vn-ml-xs { + margin-left: $spacing-xs; +} +.vn-mr-xs { + margin-right: $spacing-xs; +} +.vn-mb-xs { + margin-bottom: $spacing-xs; +} +.vn-my-xs { + margin-top: $spacing-xs; + margin-bottom: $spacing-xs; +} +.vn-mx-xs { + margin-left: $spacing-xs; + margin-right: $spacing-xs; +} + +// Small + +.vn-ma-sm { + margin: $spacing-sm; +} +.vn-mt-sm { + margin-top: $spacing-sm; +} +.vn-ml-sm { + margin-left: $spacing-sm; +} +.vn-mr-sm { + margin-right: $spacing-sm; +} +.vn-mb-sm { + margin-bottom: $spacing-sm; +} +.vn-my-sm { + margin-top: $spacing-sm; + margin-bottom: $spacing-sm; +} +.vn-mx-sm { + margin-left: $spacing-sm; + margin-right: $spacing-sm; +} + +// Medium + +.vn-ma-md { + margin: $spacing-md; +} +.vn-mt-md { + margin-top: $spacing-md; +} +.vn-ml-md { + margin-left: $spacing-md; +} +.vn-mr-md { + margin-right: $spacing-md; +} +.vn-mb-md { + margin-bottom: $spacing-md; +} +.vn-my-md { + margin-top: $spacing-md; + margin-bottom: $spacing-md; +} +.vn-mx-md { + margin-left: $spacing-md; + margin-right: $spacing-md; +} + +// Large + +.vn-ma-lg { + margin: $spacing-lg; +} +.vn-mt-lg { + margin-top: $spacing-lg; +} +.vn-ml-lg { + margin-left: $spacing-lg; +} +.vn-mr-lg { + margin-right: $spacing-lg; +} +.vn-mb-lg { + margin-bottom: $spacing-lg; +} +.vn-my-lg { + margin-top: $spacing-lg; + margin-bottom: $spacing-lg; +} +.vn-mx-lg { + margin-left: $spacing-lg; + margin-right: $spacing-lg; +} + +/* Extra large */ + +.vn-ma-xl { + margin: $spacing-xl; +} +.vn-mt-xl { + margin-top: $spacing-xl; +} +.vn-ml-xl { + margin-left: $spacing-xl; +} +.vn-mr-xl { + margin-right: $spacing-xl; +} +.vn-mb-xl { + margin-bottom: $spacing-xl; +} +.vn-my-xl { + margin-top: $spacing-xl; + margin-bottom: $spacing-xl; +} +.vn-mx-xl { + margin-left: $spacing-xl; + margin-right: $spacing-xl; +} diff --git a/front/core/styles/text.scss b/front/core/styles/text.scss new file mode 100644 index 000000000..b1624cd26 --- /dev/null +++ b/front/core/styles/text.scss @@ -0,0 +1,70 @@ +@import "./variables"; + +/* Headings */ + +.text-h1, h1 { + font-size: 32pt; +} +.text-h2, h2 { + font-size: 28pt; +} +.text-h3, h3 { + font-size: 24pt; +} +.text-h4, h4 { + font-size: 20pt; +} +.text-h5, h5 { + font-size: 16pt; +} +.text-h6, h6 { + font-size: 14pt; +} +.text-subtitle1 { + font-size: 13pt; +} +.text-subtitle2 { + font-size: 12pt; +} +.text-body1 { + font-size: 11pt; +} +.text-body2 { + font-size: 11pt; +} +.text-caption { + font-size: 11pt; +} +.text-overline { + font-size: 10pt; +} + +h1, h2, h3, h4, h5, h6 { + padding: 0; + margin-top: 0; + margin-bottom: .3em; +} + +/* Colors */ + +.text-primary { + color: $color-main; +} +.text-secondary { + color: $color-font-secondary; +} + +/* Helpers */ + +.text-uppercase { + text-transform: uppercase; +} +.text-center { + text-align: center; +} +.text-right { + text-align: right; +} +.text-left { + text-align: left; +} diff --git a/front/core/styles/util.scss b/front/core/styles/util.scss new file mode 100644 index 000000000..95a523ff4 --- /dev/null +++ b/front/core/styles/util.scss @@ -0,0 +1,6 @@ + +@mixin browser($browser) { + html[data-browser*="#{$browser}"] & { + @content; + } +} diff --git a/front/core/styles/variables.scss b/front/core/styles/variables.scss new file mode 100644 index 000000000..89e487ad7 --- /dev/null +++ b/front/core/styles/variables.scss @@ -0,0 +1,120 @@ +@import "./util"; + +$menu-width: 16em; +$topbar-height: 4em; +$mobile-width: 800px; +$font-size: 16px; + +// Width + +$width-xs: 25em; +$width-sm: 34em; +$width-md: 50em; +$width-lg: 80em; +$width-xl: 100em; + +// Spacing + +$spacing-xs: 4px; +$spacing-sm: 8px; +$spacing-md: 16px; +$spacing-lg: 32px; +$spacing-xl: 70px; + +// Light theme + +$color-primary: #f7931e; +$color-secondary: $color-primary; + +$color-font: #222; +$color-font-light: #555; +$color-font-secondary: #9b9b9b; +$color-font-dark: white; +$color-font-link: #005a9a; +$color-font-bg: rgba(0, 0, 0, .7); +$color-font-bg-marginal: rgba(0, 0, 0, .4); +$color-font-bg-dark: rgba(255, 255, 255, .7); +$color-font-bg-dark-marginal: rgba(255, 255, 255, .4); + +$color-header: #3d3d3d; +$color-menu-header: #3d3d3d; +$color-bg: #e5e5e5; +$color-bg-dark: #3d3d3d; +$color-active: #3d3d3d; +$color-active-font: $color-font-dark; +$color-bg-panel: white; +$color-main: $color-primary; +$color-marginal: #ccc; +$color-success: #a3d131; +$color-notice: #32b1ce; +$color-alert: #f42121; +$color-button: $color-secondary; + +$color-spacer: rgba(0, 0, 0, .3); +$color-spacer-light: rgba(0, 0, 0, .12); +$color-input-underline: rgba(0, 0, 0, .12); +$color-input-underline-hover: rgba(0, 0, 0, .6); +$color-shadow: rgba(0, 0, 0, .2); +$color-hightlight: rgba(0, 0, 0, .05); +$color-hover-cd: rgba(0, 0, 0, .1); +$color-hover-dc: .7; +$color-disabled: .6; + +$color-font-link-medium: lighten($color-font-link, 20%); +$color-font-link-light: lighten($color-font-link, 35%); +$color-main-medium: lighten($color-main, 20%); +$color-main-light: lighten($color-main, 35%); +$color-success-medium: lighten($color-success, 20%); +$color-success-light: lighten($color-success, 35%); +$color-notice-medium: lighten($color-notice, 20%); +$color-notice-light: lighten($color-notice, 35%); +$color-alert-medium: lighten($color-alert, 20%); +$color-alert-light: lighten($color-alert, 35%); +/**/ + +// Dark theme +/* +$color-header: #3d3d3d; +$color-bg: #222; +$color-bg-dark: #222; +$color-font: #eee; +$color-font-light: #aaa; +$color-font-secondary: #777; +$color-font-dark: white; +$color-font-bg: rgba(0, 0, 0, .8); +$color-font-link: #005a9a; +$color-active: #666; +$color-active-font: white; +$color-bg-panel: #3c3b3b; +$color-main: #f7931e; +$color-marginal: #ccc; +$color-success: #a3d131; +$color-notice: #32b1ce; +$color-alert: #f42121; + +$color-spacer: rgba(255, 255, 255, .3); +$color-spacer-light: rgba(255, 255, 255, .12); +$color-input-underline: rgba(255, 255, 255, .12); +$color-input-underline-hover: rgba(255, 255, 255, .6); +$color-shadow: rgba(0, 0, 0, .2); +$color-hightlight: rgba(255, 255, 255, .15); +$color-hover-cd: rgba(255, 255, 255, .1); +$color-hover-dc: .7; +$color-disabled: .6; + +$color-font-link: lighten($color-main, 10%); +$color-main-medium: darken($color-main, 20%); +$color-main-light: darken($color-main, 35%); +$color-success-medium: darken($color-success, 20%); +$color-success-light: darken($color-success, 35%); +$color-notice-medium: darken($color-notice, 20%); +$color-notice-light: darken($color-notice, 35%); +$color-alert-medium: darken($color-alert, 20%); +$color-alert-light: darken($color-alert, 35%); +/**/ + +// Border + +$border-thin: .05em solid $color-spacer; +$border-thin-light: .05em solid $color-spacer-light; +$shadow: 0 .15em .15em 0 rgba(0, 0, 0, .3); diff --git a/front/core/styles/width.scss b/front/core/styles/width.scss new file mode 100644 index 000000000..e017de3ea --- /dev/null +++ b/front/core/styles/width.scss @@ -0,0 +1,26 @@ +@import "./variables"; + +%margin-auto { + margin-left: auto; + margin-right: auto; +} +.vn-w-xs { + @extend %margin-auto; + max-width: $width-xs; +} +.vn-w-sm { + @extend %margin-auto; + max-width: $width-sm; +} +.vn-w-md { + @extend %margin-auto; + max-width: $width-md; +} +.vn-w-lg { + @extend %margin-auto; + max-width: $width-lg; +} +.vn-w-xl { + @extend %margin-auto; + max-width: $width-xl; +} diff --git a/front/core/vendor.js b/front/core/vendor.js new file mode 100644 index 000000000..8cec57f4f --- /dev/null +++ b/front/core/vendor.js @@ -0,0 +1,21 @@ +import '@babel/polyfill'; +import * as ng from 'angular'; +export {ng}; + +import 'angular-animate'; +import 'angular-translate'; +import 'angular-translate-loader-partial'; +import '@uirouter/angularjs'; +import 'mg-crud'; +import 'oclazyload'; + +export const ngDeps = [ + 'ngAnimate', + 'pascalprecht.translate', + 'ui.router', + 'mgCrud', + 'oc.lazyLoad' +]; + +import * as validator from 'validator'; +export {validator}; diff --git a/front/module-import.js b/front/module-import.js new file mode 100755 index 000000000..21d468931 --- /dev/null +++ b/front/module-import.js @@ -0,0 +1,21 @@ + +export default function moduleImport(moduleName) { + // TODO: Webpack watches module backend files when using dynamic import + //return import( + // /* webpackInclude: /modules\/[a-z0-9-]+\/front\/index.js$/ */ + // '../modules/'+ moduleName +'/front/index.js' + //); + + switch(moduleName) { + case 'client' : return import('client/front'); + case 'item' : return import('item/front'); + case 'ticket' : return import('ticket/front'); + case 'order' : return import('order/front'); + case 'claim' : return import('claim/front'); + case 'agency' : return import('agency/front'); + case 'travel' : return import('travel/front'); + case 'worker' : return import('worker/front'); + case 'invoiceOut' : return import('invoiceOut/front'); + case 'route' : return import('route/front'); + } +} diff --git a/front/nginx.conf b/front/nginx.conf new file mode 100644 index 000000000..22bce2283 --- /dev/null +++ b/front/nginx.conf @@ -0,0 +1,14 @@ + +server { + listen 80 default_server; + listen [::]:80 default_server; + server_name _; + autoindex off; + client_max_body_size 250M; + + root /salix/dist; + + location / { + autoindex on; + } +} diff --git a/front/package-lock.json b/front/package-lock.json new file mode 100644 index 000000000..f546f6c65 --- /dev/null +++ b/front/package-lock.json @@ -0,0 +1,3179 @@ +{ + "name": "salix-front", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@babel/polyfill": { + "version": "7.2.5", + "resolved": "https://registry.npmjs.org/@babel/polyfill/-/polyfill-7.2.5.tgz", + "integrity": "sha512-8Y/t3MWThtMLYr0YNC/Q76tqN1w30+b0uQMeFUYauG2UGTR19zyUtFrAzT23zNtBxPp+LbE5E/nwV/q/r3y6ug==", + "requires": { + "core-js": "^2.5.7", + "regenerator-runtime": "^0.12.0" + } + }, + "@uirouter/angularjs": { + "version": "1.0.20", + "resolved": "https://registry.npmjs.org/@uirouter/angularjs/-/angularjs-1.0.20.tgz", + "integrity": "sha512-fY6bsesTL/tg8gyFHXaIjD1r5b7Ac+SYupodO9OzT4/gKI0YC+uGzLpQESAiXlT3fsxdEPVBzdtAbzXDwCKdEA==", + "requires": { + "@uirouter/core": "5.0.21" + } + }, + "@uirouter/core": { + "version": "5.0.21", + "resolved": "https://registry.npmjs.org/@uirouter/core/-/core-5.0.21.tgz", + "integrity": "sha512-QWHc0wT00qtYNkT0BXZaFNLLHZyux0qJjF8c2WklW5/Q0Z866NoJjJErEMWjQb/AR+olkR2NlfEEi8KTQU2OpA==" + }, + "angular": { + "version": "1.7.5", + "resolved": "https://registry.npmjs.org/angular/-/angular-1.7.5.tgz", + "integrity": "sha512-760183yxtGzni740IBTieNuWLtPNAoMqvmC0Z62UoU0I3nqk+VJuO3JbQAXOyvo3Oy/ZsdNQwrSTh/B0OQZjNw==" + }, + "angular-animate": { + "version": "1.7.8", + "resolved": "https://registry.npmjs.org/angular-animate/-/angular-animate-1.7.8.tgz", + "integrity": "sha512-bINtzizq7TbJzfVrDpwLfTxVl0Qd7fRNWFb5jKYI1vaFZobQNX/QONXlLow6ySsDbZ6eLECycB7mvWtfh1YYaw==" + }, + "angular-translate": { + "version": "2.18.1", + "resolved": "https://registry.npmjs.org/angular-translate/-/angular-translate-2.18.1.tgz", + "integrity": "sha512-Mw0kFBqsv5j8ItL9IhRZunIlVmIRW6iFsiTmRs9wGr2QTt8z4rehYlWyHos8qnXc/kyOYJiW50iH50CSNHGB9A==", + "requires": { + "angular": ">=1.2.26 <=1.7" + } + }, + "angular-translate-loader-partial": { + "version": "2.18.1", + "resolved": "https://registry.npmjs.org/angular-translate-loader-partial/-/angular-translate-loader-partial-2.18.1.tgz", + "integrity": "sha512-+bPzY3+F2I1tb+X5bscvZq0OGoVEVkHwPGZvaY4nhbktpshArYpvIEV+RQFUa/QNj8vQc3iQ/pruJDb8w3zIdw==", + "requires": { + "angular-translate": "~2.18.1" + } + }, + "argparse": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.9.tgz", + "integrity": "sha1-c9g7wmP4bpf4zE9rrhsOkKfSLIY=", + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "core-js": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.1.tgz", + "integrity": "sha512-L72mmmEayPJBejKIWe2pYtGis5r0tQ5NaJekdhyXgeMQTpJoBsH0NL4ElY2LfSoV15xeQWKQ+XTTOZdyero5Xg==" + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" + }, + "js-yaml": { + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "mg-crud": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/mg-crud/-/mg-crud-1.1.2.tgz", + "integrity": "sha1-p6AWGzWSPK7/8ZpIBpS2V1vDggw=", + "requires": { + "angular": "^1.6.1" + } + }, + "npm": { + "version": "6.11.3", + "resolved": "https://registry.npmjs.org/npm/-/npm-6.11.3.tgz", + "integrity": "sha512-K2h+MPzZiY39Xf6eHEdECe/LKoJXam4UCflz5kIxoskN3LQFeYs5fqBGT5i4TtM/aBk+86Mcf+jgXs/WuWAutQ==", + "requires": { + "JSONStream": "^1.3.5", + "abbrev": "~1.1.1", + "ansicolors": "~0.3.2", + "ansistyles": "~0.1.3", + "aproba": "^2.0.0", + "archy": "~1.0.0", + "bin-links": "^1.1.3", + "bluebird": "^3.5.5", + "byte-size": "^5.0.1", + "cacache": "^12.0.3", + "call-limit": "^1.1.1", + "chownr": "^1.1.2", + "ci-info": "^2.0.0", + "cli-columns": "^3.1.2", + "cli-table3": "^0.5.1", + "cmd-shim": "^3.0.3", + "columnify": "~1.5.4", + "config-chain": "^1.1.12", + "debuglog": "*", + "detect-indent": "~5.0.0", + "detect-newline": "^2.1.0", + "dezalgo": "~1.0.3", + "editor": "~1.0.0", + "figgy-pudding": "^3.5.1", + "find-npm-prefix": "^1.0.2", + "fs-vacuum": "~1.2.10", + "fs-write-stream-atomic": "~1.0.10", + "gentle-fs": "^2.2.1", + "glob": "^7.1.4", + "graceful-fs": "^4.2.2", + "has-unicode": "~2.0.1", + "hosted-git-info": "^2.8.2", + "iferr": "^1.0.2", + "imurmurhash": "*", + "infer-owner": "^1.0.4", + "inflight": "~1.0.6", + "inherits": "^2.0.4", + "ini": "^1.3.5", + "init-package-json": "^1.10.3", + "is-cidr": "^3.0.0", + "json-parse-better-errors": "^1.0.2", + "lazy-property": "~1.0.0", + "libcipm": "^4.0.3", + "libnpm": "^3.0.1", + "libnpmaccess": "^3.0.2", + "libnpmhook": "^5.0.3", + "libnpmorg": "^1.0.1", + "libnpmsearch": "^2.0.2", + "libnpmteam": "^1.0.2", + "libnpx": "^10.2.0", + "lock-verify": "^2.1.0", + "lockfile": "^1.0.4", + "lodash._baseindexof": "*", + "lodash._baseuniq": "~4.6.0", + "lodash._bindcallback": "*", + "lodash._cacheindexof": "*", + "lodash._createcache": "*", + "lodash._getnative": "*", + "lodash.clonedeep": "~4.5.0", + "lodash.restparam": "*", + "lodash.union": "~4.6.0", + "lodash.uniq": "~4.5.0", + "lodash.without": "~4.4.0", + "lru-cache": "^5.1.1", + "meant": "~1.0.1", + "mississippi": "^3.0.0", + "mkdirp": "~0.5.1", + "move-concurrently": "^1.0.1", + "node-gyp": "^5.0.3", + "nopt": "~4.0.1", + "normalize-package-data": "^2.5.0", + "npm-audit-report": "^1.3.2", + "npm-cache-filename": "~1.0.2", + "npm-install-checks": "~3.0.0", + "npm-lifecycle": "^3.1.3", + "npm-package-arg": "^6.1.1", + "npm-packlist": "^1.4.4", + "npm-pick-manifest": "^3.0.2", + "npm-profile": "^4.0.2", + "npm-registry-fetch": "^4.0.0", + "npm-user-validate": "~1.0.0", + "npmlog": "~4.1.2", + "once": "~1.4.0", + "opener": "^1.5.1", + "osenv": "^0.1.5", + "pacote": "^9.5.8", + "path-is-inside": "~1.0.2", + "promise-inflight": "~1.0.1", + "qrcode-terminal": "^0.12.0", + "query-string": "^6.8.2", + "qw": "~1.0.1", + "read": "~1.0.7", + "read-cmd-shim": "^1.0.4", + "read-installed": "~4.0.3", + "read-package-json": "^2.1.0", + "read-package-tree": "^5.3.1", + "readable-stream": "^3.4.0", + "readdir-scoped-modules": "^1.1.0", + "request": "^2.88.0", + "retry": "^0.12.0", + "rimraf": "^2.6.3", + "safe-buffer": "^5.1.2", + "semver": "^5.7.1", + "sha": "^3.0.0", + "slide": "~1.1.6", + "sorted-object": "~2.0.1", + "sorted-union-stream": "~2.1.3", + "ssri": "^6.0.1", + "stringify-package": "^1.0.0", + "tar": "^4.4.10", + "text-table": "~0.2.0", + "tiny-relative-date": "^1.3.0", + "uid-number": "0.0.6", + "umask": "~1.1.0", + "unique-filename": "^1.1.1", + "unpipe": "~1.0.0", + "update-notifier": "^2.5.0", + "uuid": "^3.3.2", + "validate-npm-package-license": "^3.0.4", + "validate-npm-package-name": "~3.0.0", + "which": "^1.3.1", + "worker-farm": "^1.7.0", + "write-file-atomic": "^2.4.3" + }, + "dependencies": { + "JSONStream": { + "version": "1.3.5", + "bundled": true, + "requires": { + "jsonparse": "^1.2.0", + "through": ">=2.2.7 <3" + } + }, + "abbrev": { + "version": "1.1.1", + "bundled": true + }, + "agent-base": { + "version": "4.3.0", + "bundled": true, + "requires": { + "es6-promisify": "^5.0.0" + } + }, + "agentkeepalive": { + "version": "3.5.2", + "bundled": true, + "requires": { + "humanize-ms": "^1.2.1" + } + }, + "ajv": { + "version": "5.5.2", + "bundled": true, + "requires": { + "co": "^4.6.0", + "fast-deep-equal": "^1.0.0", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.3.0" + } + }, + "ansi-align": { + "version": "2.0.0", + "bundled": true, + "requires": { + "string-width": "^2.0.0" + } + }, + "ansi-regex": { + "version": "2.1.1", + "bundled": true + }, + "ansi-styles": { + "version": "3.2.1", + "bundled": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "ansicolors": { + "version": "0.3.2", + "bundled": true + }, + "ansistyles": { + "version": "0.1.3", + "bundled": true + }, + "aproba": { + "version": "2.0.0", + "bundled": true + }, + "archy": { + "version": "1.0.0", + "bundled": true + }, + "are-we-there-yet": { + "version": "1.1.4", + "bundled": true, + "requires": { + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "asap": { + "version": "2.0.6", + "bundled": true + }, + "asn1": { + "version": "0.2.4", + "bundled": true, + "requires": { + "safer-buffer": "~2.1.0" + } + }, + "assert-plus": { + "version": "1.0.0", + "bundled": true + }, + "asynckit": { + "version": "0.4.0", + "bundled": true + }, + "aws-sign2": { + "version": "0.7.0", + "bundled": true + }, + "aws4": { + "version": "1.8.0", + "bundled": true + }, + "balanced-match": { + "version": "1.0.0", + "bundled": true + }, + "bcrypt-pbkdf": { + "version": "1.0.2", + "bundled": true, + "optional": true, + "requires": { + "tweetnacl": "^0.14.3" + } + }, + "bin-links": { + "version": "1.1.3", + "bundled": true, + "requires": { + "bluebird": "^3.5.3", + "cmd-shim": "^3.0.0", + "gentle-fs": "^2.0.1", + "graceful-fs": "^4.1.15", + "write-file-atomic": "^2.3.0" + } + }, + "bluebird": { + "version": "3.5.5", + "bundled": true + }, + "boxen": { + "version": "1.3.0", + "bundled": true, + "requires": { + "ansi-align": "^2.0.0", + "camelcase": "^4.0.0", + "chalk": "^2.0.1", + "cli-boxes": "^1.0.0", + "string-width": "^2.0.0", + "term-size": "^1.2.0", + "widest-line": "^2.0.0" + } + }, + "brace-expansion": { + "version": "1.1.11", + "bundled": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "buffer-from": { + "version": "1.0.0", + "bundled": true + }, + "builtins": { + "version": "1.0.3", + "bundled": true + }, + "byline": { + "version": "5.0.0", + "bundled": true + }, + "byte-size": { + "version": "5.0.1", + "bundled": true + }, + "cacache": { + "version": "12.0.3", + "bundled": true, + "requires": { + "bluebird": "^3.5.5", + "chownr": "^1.1.1", + "figgy-pudding": "^3.5.1", + "glob": "^7.1.4", + "graceful-fs": "^4.1.15", + "infer-owner": "^1.0.3", + "lru-cache": "^5.1.1", + "mississippi": "^3.0.0", + "mkdirp": "^0.5.1", + "move-concurrently": "^1.0.1", + "promise-inflight": "^1.0.1", + "rimraf": "^2.6.3", + "ssri": "^6.0.1", + "unique-filename": "^1.1.1", + "y18n": "^4.0.0" + } + }, + "call-limit": { + "version": "1.1.1", + "bundled": true + }, + "camelcase": { + "version": "4.1.0", + "bundled": true + }, + "capture-stack-trace": { + "version": "1.0.0", + "bundled": true + }, + "caseless": { + "version": "0.12.0", + "bundled": true + }, + "chalk": { + "version": "2.4.1", + "bundled": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "chownr": { + "version": "1.1.2", + "bundled": true + }, + "ci-info": { + "version": "2.0.0", + "bundled": true + }, + "cidr-regex": { + "version": "2.0.10", + "bundled": true, + "requires": { + "ip-regex": "^2.1.0" + } + }, + "cli-boxes": { + "version": "1.0.0", + "bundled": true + }, + "cli-columns": { + "version": "3.1.2", + "bundled": true, + "requires": { + "string-width": "^2.0.0", + "strip-ansi": "^3.0.1" + } + }, + "cli-table3": { + "version": "0.5.1", + "bundled": true, + "requires": { + "colors": "^1.1.2", + "object-assign": "^4.1.0", + "string-width": "^2.1.1" + } + }, + "cliui": { + "version": "4.1.0", + "bundled": true, + "requires": { + "string-width": "^2.1.1", + "strip-ansi": "^4.0.0", + "wrap-ansi": "^2.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "bundled": true + }, + "strip-ansi": { + "version": "4.0.0", + "bundled": true, + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "clone": { + "version": "1.0.4", + "bundled": true + }, + "cmd-shim": { + "version": "3.0.3", + "bundled": true, + "requires": { + "graceful-fs": "^4.1.2", + "mkdirp": "~0.5.0" + } + }, + "co": { + "version": "4.6.0", + "bundled": true + }, + "code-point-at": { + "version": "1.1.0", + "bundled": true + }, + "color-convert": { + "version": "1.9.1", + "bundled": true, + "requires": { + "color-name": "^1.1.1" + } + }, + "color-name": { + "version": "1.1.3", + "bundled": true + }, + "colors": { + "version": "1.3.3", + "bundled": true, + "optional": true + }, + "columnify": { + "version": "1.5.4", + "bundled": true, + "requires": { + "strip-ansi": "^3.0.0", + "wcwidth": "^1.0.0" + } + }, + "combined-stream": { + "version": "1.0.6", + "bundled": true, + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "concat-map": { + "version": "0.0.1", + "bundled": true + }, + "concat-stream": { + "version": "1.6.2", + "bundled": true, + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "config-chain": { + "version": "1.1.12", + "bundled": true, + "requires": { + "ini": "^1.3.4", + "proto-list": "~1.2.1" + } + }, + "configstore": { + "version": "3.1.2", + "bundled": true, + "requires": { + "dot-prop": "^4.1.0", + "graceful-fs": "^4.1.2", + "make-dir": "^1.0.0", + "unique-string": "^1.0.0", + "write-file-atomic": "^2.0.0", + "xdg-basedir": "^3.0.0" + } + }, + "console-control-strings": { + "version": "1.1.0", + "bundled": true + }, + "copy-concurrently": { + "version": "1.0.5", + "bundled": true, + "requires": { + "aproba": "^1.1.1", + "fs-write-stream-atomic": "^1.0.8", + "iferr": "^0.1.5", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.0" + }, + "dependencies": { + "aproba": { + "version": "1.2.0", + "bundled": true + }, + "iferr": { + "version": "0.1.5", + "bundled": true + } + } + }, + "core-util-is": { + "version": "1.0.2", + "bundled": true + }, + "create-error-class": { + "version": "3.0.2", + "bundled": true, + "requires": { + "capture-stack-trace": "^1.0.0" + } + }, + "cross-spawn": { + "version": "5.1.0", + "bundled": true, + "requires": { + "lru-cache": "^4.0.1", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + }, + "dependencies": { + "lru-cache": { + "version": "4.1.5", + "bundled": true, + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "yallist": { + "version": "2.1.2", + "bundled": true + } + } + }, + "crypto-random-string": { + "version": "1.0.0", + "bundled": true + }, + "cyclist": { + "version": "0.2.2", + "bundled": true + }, + "dashdash": { + "version": "1.14.1", + "bundled": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "debug": { + "version": "3.1.0", + "bundled": true, + "requires": { + "ms": "2.0.0" + }, + "dependencies": { + "ms": { + "version": "2.0.0", + "bundled": true + } + } + }, + "debuglog": { + "version": "1.0.1", + "bundled": true + }, + "decamelize": { + "version": "1.2.0", + "bundled": true + }, + "decode-uri-component": { + "version": "0.2.0", + "bundled": true + }, + "deep-extend": { + "version": "0.5.1", + "bundled": true + }, + "defaults": { + "version": "1.0.3", + "bundled": true, + "requires": { + "clone": "^1.0.2" + } + }, + "define-properties": { + "version": "1.1.3", + "bundled": true, + "requires": { + "object-keys": "^1.0.12" + } + }, + "delayed-stream": { + "version": "1.0.0", + "bundled": true + }, + "delegates": { + "version": "1.0.0", + "bundled": true + }, + "detect-indent": { + "version": "5.0.0", + "bundled": true + }, + "detect-newline": { + "version": "2.1.0", + "bundled": true + }, + "dezalgo": { + "version": "1.0.3", + "bundled": true, + "requires": { + "asap": "^2.0.0", + "wrappy": "1" + } + }, + "dot-prop": { + "version": "4.2.0", + "bundled": true, + "requires": { + "is-obj": "^1.0.0" + } + }, + "dotenv": { + "version": "5.0.1", + "bundled": true + }, + "duplexer3": { + "version": "0.1.4", + "bundled": true + }, + "duplexify": { + "version": "3.6.0", + "bundled": true, + "requires": { + "end-of-stream": "^1.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.0.0", + "stream-shift": "^1.0.0" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "ecc-jsbn": { + "version": "0.1.2", + "bundled": true, + "optional": true, + "requires": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "editor": { + "version": "1.0.0", + "bundled": true + }, + "encoding": { + "version": "0.1.12", + "bundled": true, + "requires": { + "iconv-lite": "~0.4.13" + } + }, + "end-of-stream": { + "version": "1.4.1", + "bundled": true, + "requires": { + "once": "^1.4.0" + } + }, + "env-paths": { + "version": "1.0.0", + "bundled": true + }, + "err-code": { + "version": "1.1.2", + "bundled": true + }, + "errno": { + "version": "0.1.7", + "bundled": true, + "requires": { + "prr": "~1.0.1" + } + }, + "es-abstract": { + "version": "1.12.0", + "bundled": true, + "requires": { + "es-to-primitive": "^1.1.1", + "function-bind": "^1.1.1", + "has": "^1.0.1", + "is-callable": "^1.1.3", + "is-regex": "^1.0.4" + } + }, + "es-to-primitive": { + "version": "1.2.0", + "bundled": true, + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } + }, + "es6-promise": { + "version": "4.2.8", + "bundled": true + }, + "es6-promisify": { + "version": "5.0.0", + "bundled": true, + "requires": { + "es6-promise": "^4.0.3" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "bundled": true + }, + "execa": { + "version": "0.7.0", + "bundled": true, + "requires": { + "cross-spawn": "^5.0.1", + "get-stream": "^3.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + }, + "dependencies": { + "get-stream": { + "version": "3.0.0", + "bundled": true + } + } + }, + "extend": { + "version": "3.0.2", + "bundled": true + }, + "extsprintf": { + "version": "1.3.0", + "bundled": true + }, + "fast-deep-equal": { + "version": "1.1.0", + "bundled": true + }, + "fast-json-stable-stringify": { + "version": "2.0.0", + "bundled": true + }, + "figgy-pudding": { + "version": "3.5.1", + "bundled": true + }, + "find-npm-prefix": { + "version": "1.0.2", + "bundled": true + }, + "find-up": { + "version": "2.1.0", + "bundled": true, + "requires": { + "locate-path": "^2.0.0" + } + }, + "flush-write-stream": { + "version": "1.0.3", + "bundled": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.4" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "forever-agent": { + "version": "0.6.1", + "bundled": true + }, + "form-data": { + "version": "2.3.2", + "bundled": true, + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "1.0.6", + "mime-types": "^2.1.12" + } + }, + "from2": { + "version": "2.3.0", + "bundled": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.0" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "fs-minipass": { + "version": "1.2.6", + "bundled": true, + "requires": { + "minipass": "^2.2.1" + } + }, + "fs-vacuum": { + "version": "1.2.10", + "bundled": true, + "requires": { + "graceful-fs": "^4.1.2", + "path-is-inside": "^1.0.1", + "rimraf": "^2.5.2" + } + }, + "fs-write-stream-atomic": { + "version": "1.0.10", + "bundled": true, + "requires": { + "graceful-fs": "^4.1.2", + "iferr": "^0.1.5", + "imurmurhash": "^0.1.4", + "readable-stream": "1 || 2" + }, + "dependencies": { + "iferr": { + "version": "0.1.5", + "bundled": true + }, + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "fs.realpath": { + "version": "1.0.0", + "bundled": true + }, + "function-bind": { + "version": "1.1.1", + "bundled": true + }, + "gauge": { + "version": "2.7.4", + "bundled": true, + "requires": { + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" + }, + "dependencies": { + "aproba": { + "version": "1.2.0", + "bundled": true + }, + "string-width": { + "version": "1.0.2", + "bundled": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + } + } + }, + "genfun": { + "version": "5.0.0", + "bundled": true + }, + "gentle-fs": { + "version": "2.2.1", + "bundled": true, + "requires": { + "aproba": "^1.1.2", + "chownr": "^1.1.2", + "fs-vacuum": "^1.2.10", + "graceful-fs": "^4.1.11", + "iferr": "^0.1.5", + "infer-owner": "^1.0.4", + "mkdirp": "^0.5.1", + "path-is-inside": "^1.0.2", + "read-cmd-shim": "^1.0.1", + "slide": "^1.1.6" + }, + "dependencies": { + "aproba": { + "version": "1.2.0", + "bundled": true + }, + "iferr": { + "version": "0.1.5", + "bundled": true + } + } + }, + "get-caller-file": { + "version": "1.0.2", + "bundled": true + }, + "get-stream": { + "version": "4.1.0", + "bundled": true, + "requires": { + "pump": "^3.0.0" + } + }, + "getpass": { + "version": "0.1.7", + "bundled": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "glob": { + "version": "7.1.4", + "bundled": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "global-dirs": { + "version": "0.1.1", + "bundled": true, + "requires": { + "ini": "^1.3.4" + } + }, + "got": { + "version": "6.7.1", + "bundled": true, + "requires": { + "create-error-class": "^3.0.0", + "duplexer3": "^0.1.4", + "get-stream": "^3.0.0", + "is-redirect": "^1.0.0", + "is-retry-allowed": "^1.0.0", + "is-stream": "^1.0.0", + "lowercase-keys": "^1.0.0", + "safe-buffer": "^5.0.1", + "timed-out": "^4.0.0", + "unzip-response": "^2.0.1", + "url-parse-lax": "^1.0.0" + }, + "dependencies": { + "get-stream": { + "version": "3.0.0", + "bundled": true + } + } + }, + "graceful-fs": { + "version": "4.2.2", + "bundled": true + }, + "har-schema": { + "version": "2.0.0", + "bundled": true + }, + "har-validator": { + "version": "5.1.0", + "bundled": true, + "requires": { + "ajv": "^5.3.0", + "har-schema": "^2.0.0" + } + }, + "has": { + "version": "1.0.3", + "bundled": true, + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-flag": { + "version": "3.0.0", + "bundled": true + }, + "has-symbols": { + "version": "1.0.0", + "bundled": true + }, + "has-unicode": { + "version": "2.0.1", + "bundled": true + }, + "hosted-git-info": { + "version": "2.8.2", + "bundled": true, + "requires": { + "lru-cache": "^5.1.1" + } + }, + "http-cache-semantics": { + "version": "3.8.1", + "bundled": true + }, + "http-proxy-agent": { + "version": "2.1.0", + "bundled": true, + "requires": { + "agent-base": "4", + "debug": "3.1.0" + } + }, + "http-signature": { + "version": "1.2.0", + "bundled": true, + "requires": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + } + }, + "https-proxy-agent": { + "version": "2.2.2", + "bundled": true, + "requires": { + "agent-base": "^4.3.0", + "debug": "^3.1.0" + } + }, + "humanize-ms": { + "version": "1.2.1", + "bundled": true, + "requires": { + "ms": "^2.0.0" + } + }, + "iconv-lite": { + "version": "0.4.23", + "bundled": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "iferr": { + "version": "1.0.2", + "bundled": true + }, + "ignore-walk": { + "version": "3.0.1", + "bundled": true, + "requires": { + "minimatch": "^3.0.4" + } + }, + "import-lazy": { + "version": "2.1.0", + "bundled": true + }, + "imurmurhash": { + "version": "0.1.4", + "bundled": true + }, + "infer-owner": { + "version": "1.0.4", + "bundled": true + }, + "inflight": { + "version": "1.0.6", + "bundled": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "bundled": true + }, + "ini": { + "version": "1.3.5", + "bundled": true + }, + "init-package-json": { + "version": "1.10.3", + "bundled": true, + "requires": { + "glob": "^7.1.1", + "npm-package-arg": "^4.0.0 || ^5.0.0 || ^6.0.0", + "promzard": "^0.3.0", + "read": "~1.0.1", + "read-package-json": "1 || 2", + "semver": "2.x || 3.x || 4 || 5", + "validate-npm-package-license": "^3.0.1", + "validate-npm-package-name": "^3.0.0" + } + }, + "invert-kv": { + "version": "1.0.0", + "bundled": true + }, + "ip": { + "version": "1.1.5", + "bundled": true + }, + "ip-regex": { + "version": "2.1.0", + "bundled": true + }, + "is-callable": { + "version": "1.1.4", + "bundled": true + }, + "is-ci": { + "version": "1.1.0", + "bundled": true, + "requires": { + "ci-info": "^1.0.0" + }, + "dependencies": { + "ci-info": { + "version": "1.6.0", + "bundled": true + } + } + }, + "is-cidr": { + "version": "3.0.0", + "bundled": true, + "requires": { + "cidr-regex": "^2.0.10" + } + }, + "is-date-object": { + "version": "1.0.1", + "bundled": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "bundled": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "is-installed-globally": { + "version": "0.1.0", + "bundled": true, + "requires": { + "global-dirs": "^0.1.0", + "is-path-inside": "^1.0.0" + } + }, + "is-npm": { + "version": "1.0.0", + "bundled": true + }, + "is-obj": { + "version": "1.0.1", + "bundled": true + }, + "is-path-inside": { + "version": "1.0.1", + "bundled": true, + "requires": { + "path-is-inside": "^1.0.1" + } + }, + "is-redirect": { + "version": "1.0.0", + "bundled": true + }, + "is-regex": { + "version": "1.0.4", + "bundled": true, + "requires": { + "has": "^1.0.1" + } + }, + "is-retry-allowed": { + "version": "1.1.0", + "bundled": true + }, + "is-stream": { + "version": "1.1.0", + "bundled": true + }, + "is-symbol": { + "version": "1.0.2", + "bundled": true, + "requires": { + "has-symbols": "^1.0.0" + } + }, + "is-typedarray": { + "version": "1.0.0", + "bundled": true + }, + "isarray": { + "version": "1.0.0", + "bundled": true + }, + "isexe": { + "version": "2.0.0", + "bundled": true + }, + "isstream": { + "version": "0.1.2", + "bundled": true + }, + "jsbn": { + "version": "0.1.1", + "bundled": true, + "optional": true + }, + "json-parse-better-errors": { + "version": "1.0.2", + "bundled": true + }, + "json-schema": { + "version": "0.2.3", + "bundled": true + }, + "json-schema-traverse": { + "version": "0.3.1", + "bundled": true + }, + "json-stringify-safe": { + "version": "5.0.1", + "bundled": true + }, + "jsonparse": { + "version": "1.3.1", + "bundled": true + }, + "jsprim": { + "version": "1.4.1", + "bundled": true, + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.2.3", + "verror": "1.10.0" + } + }, + "latest-version": { + "version": "3.1.0", + "bundled": true, + "requires": { + "package-json": "^4.0.0" + } + }, + "lazy-property": { + "version": "1.0.0", + "bundled": true + }, + "lcid": { + "version": "1.0.0", + "bundled": true, + "requires": { + "invert-kv": "^1.0.0" + } + }, + "libcipm": { + "version": "4.0.3", + "bundled": true, + "requires": { + "bin-links": "^1.1.2", + "bluebird": "^3.5.1", + "figgy-pudding": "^3.5.1", + "find-npm-prefix": "^1.0.2", + "graceful-fs": "^4.1.11", + "ini": "^1.3.5", + "lock-verify": "^2.0.2", + "mkdirp": "^0.5.1", + "npm-lifecycle": "^3.0.0", + "npm-logical-tree": "^1.2.1", + "npm-package-arg": "^6.1.0", + "pacote": "^9.1.0", + "read-package-json": "^2.0.13", + "rimraf": "^2.6.2", + "worker-farm": "^1.6.0" + } + }, + "libnpm": { + "version": "3.0.1", + "bundled": true, + "requires": { + "bin-links": "^1.1.2", + "bluebird": "^3.5.3", + "find-npm-prefix": "^1.0.2", + "libnpmaccess": "^3.0.2", + "libnpmconfig": "^1.2.1", + "libnpmhook": "^5.0.3", + "libnpmorg": "^1.0.1", + "libnpmpublish": "^1.1.2", + "libnpmsearch": "^2.0.2", + "libnpmteam": "^1.0.2", + "lock-verify": "^2.0.2", + "npm-lifecycle": "^3.0.0", + "npm-logical-tree": "^1.2.1", + "npm-package-arg": "^6.1.0", + "npm-profile": "^4.0.2", + "npm-registry-fetch": "^4.0.0", + "npmlog": "^4.1.2", + "pacote": "^9.5.3", + "read-package-json": "^2.0.13", + "stringify-package": "^1.0.0" + } + }, + "libnpmaccess": { + "version": "3.0.2", + "bundled": true, + "requires": { + "aproba": "^2.0.0", + "get-stream": "^4.0.0", + "npm-package-arg": "^6.1.0", + "npm-registry-fetch": "^4.0.0" + } + }, + "libnpmconfig": { + "version": "1.2.1", + "bundled": true, + "requires": { + "figgy-pudding": "^3.5.1", + "find-up": "^3.0.0", + "ini": "^1.3.5" + }, + "dependencies": { + "find-up": { + "version": "3.0.0", + "bundled": true, + "requires": { + "locate-path": "^3.0.0" + } + }, + "locate-path": { + "version": "3.0.0", + "bundled": true, + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "p-limit": { + "version": "2.2.0", + "bundled": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "bundled": true, + "requires": { + "p-limit": "^2.0.0" + } + }, + "p-try": { + "version": "2.2.0", + "bundled": true + } + } + }, + "libnpmhook": { + "version": "5.0.3", + "bundled": true, + "requires": { + "aproba": "^2.0.0", + "figgy-pudding": "^3.4.1", + "get-stream": "^4.0.0", + "npm-registry-fetch": "^4.0.0" + } + }, + "libnpmorg": { + "version": "1.0.1", + "bundled": true, + "requires": { + "aproba": "^2.0.0", + "figgy-pudding": "^3.4.1", + "get-stream": "^4.0.0", + "npm-registry-fetch": "^4.0.0" + } + }, + "libnpmpublish": { + "version": "1.1.2", + "bundled": true, + "requires": { + "aproba": "^2.0.0", + "figgy-pudding": "^3.5.1", + "get-stream": "^4.0.0", + "lodash.clonedeep": "^4.5.0", + "normalize-package-data": "^2.4.0", + "npm-package-arg": "^6.1.0", + "npm-registry-fetch": "^4.0.0", + "semver": "^5.5.1", + "ssri": "^6.0.1" + } + }, + "libnpmsearch": { + "version": "2.0.2", + "bundled": true, + "requires": { + "figgy-pudding": "^3.5.1", + "get-stream": "^4.0.0", + "npm-registry-fetch": "^4.0.0" + } + }, + "libnpmteam": { + "version": "1.0.2", + "bundled": true, + "requires": { + "aproba": "^2.0.0", + "figgy-pudding": "^3.4.1", + "get-stream": "^4.0.0", + "npm-registry-fetch": "^4.0.0" + } + }, + "libnpx": { + "version": "10.2.0", + "bundled": true, + "requires": { + "dotenv": "^5.0.1", + "npm-package-arg": "^6.0.0", + "rimraf": "^2.6.2", + "safe-buffer": "^5.1.0", + "update-notifier": "^2.3.0", + "which": "^1.3.0", + "y18n": "^4.0.0", + "yargs": "^11.0.0" + } + }, + "locate-path": { + "version": "2.0.0", + "bundled": true, + "requires": { + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" + } + }, + "lock-verify": { + "version": "2.1.0", + "bundled": true, + "requires": { + "npm-package-arg": "^6.1.0", + "semver": "^5.4.1" + } + }, + "lockfile": { + "version": "1.0.4", + "bundled": true, + "requires": { + "signal-exit": "^3.0.2" + } + }, + "lodash._baseindexof": { + "version": "3.1.0", + "bundled": true + }, + "lodash._baseuniq": { + "version": "4.6.0", + "bundled": true, + "requires": { + "lodash._createset": "~4.0.0", + "lodash._root": "~3.0.0" + } + }, + "lodash._bindcallback": { + "version": "3.0.1", + "bundled": true + }, + "lodash._cacheindexof": { + "version": "3.0.2", + "bundled": true + }, + "lodash._createcache": { + "version": "3.1.2", + "bundled": true, + "requires": { + "lodash._getnative": "^3.0.0" + } + }, + "lodash._createset": { + "version": "4.0.3", + "bundled": true + }, + "lodash._getnative": { + "version": "3.9.1", + "bundled": true + }, + "lodash._root": { + "version": "3.0.1", + "bundled": true + }, + "lodash.clonedeep": { + "version": "4.5.0", + "bundled": true + }, + "lodash.restparam": { + "version": "3.6.1", + "bundled": true + }, + "lodash.union": { + "version": "4.6.0", + "bundled": true + }, + "lodash.uniq": { + "version": "4.5.0", + "bundled": true + }, + "lodash.without": { + "version": "4.4.0", + "bundled": true + }, + "lowercase-keys": { + "version": "1.0.1", + "bundled": true + }, + "lru-cache": { + "version": "5.1.1", + "bundled": true, + "requires": { + "yallist": "^3.0.2" + } + }, + "make-dir": { + "version": "1.3.0", + "bundled": true, + "requires": { + "pify": "^3.0.0" + } + }, + "make-fetch-happen": { + "version": "5.0.0", + "bundled": true, + "requires": { + "agentkeepalive": "^3.4.1", + "cacache": "^12.0.0", + "http-cache-semantics": "^3.8.1", + "http-proxy-agent": "^2.1.0", + "https-proxy-agent": "^2.2.1", + "lru-cache": "^5.1.1", + "mississippi": "^3.0.0", + "node-fetch-npm": "^2.0.2", + "promise-retry": "^1.1.1", + "socks-proxy-agent": "^4.0.0", + "ssri": "^6.0.0" + } + }, + "meant": { + "version": "1.0.1", + "bundled": true + }, + "mem": { + "version": "1.1.0", + "bundled": true, + "requires": { + "mimic-fn": "^1.0.0" + } + }, + "mime-db": { + "version": "1.35.0", + "bundled": true + }, + "mime-types": { + "version": "2.1.19", + "bundled": true, + "requires": { + "mime-db": "~1.35.0" + } + }, + "mimic-fn": { + "version": "1.2.0", + "bundled": true + }, + "minimatch": { + "version": "3.0.4", + "bundled": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "bundled": true + }, + "minipass": { + "version": "2.3.3", + "bundled": true, + "requires": { + "safe-buffer": "^5.1.2", + "yallist": "^3.0.0" + }, + "dependencies": { + "yallist": { + "version": "3.0.2", + "bundled": true + } + } + }, + "minizlib": { + "version": "1.2.1", + "bundled": true, + "requires": { + "minipass": "^2.2.1" + } + }, + "mississippi": { + "version": "3.0.0", + "bundled": true, + "requires": { + "concat-stream": "^1.5.0", + "duplexify": "^3.4.2", + "end-of-stream": "^1.1.0", + "flush-write-stream": "^1.0.0", + "from2": "^2.1.0", + "parallel-transform": "^1.1.0", + "pump": "^3.0.0", + "pumpify": "^1.3.3", + "stream-each": "^1.1.0", + "through2": "^2.0.0" + } + }, + "mkdirp": { + "version": "0.5.1", + "bundled": true, + "requires": { + "minimist": "0.0.8" + } + }, + "move-concurrently": { + "version": "1.0.1", + "bundled": true, + "requires": { + "aproba": "^1.1.1", + "copy-concurrently": "^1.0.0", + "fs-write-stream-atomic": "^1.0.8", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.3" + }, + "dependencies": { + "aproba": { + "version": "1.2.0", + "bundled": true + } + } + }, + "ms": { + "version": "2.1.1", + "bundled": true + }, + "mute-stream": { + "version": "0.0.7", + "bundled": true + }, + "node-fetch-npm": { + "version": "2.0.2", + "bundled": true, + "requires": { + "encoding": "^0.1.11", + "json-parse-better-errors": "^1.0.0", + "safe-buffer": "^5.1.1" + } + }, + "node-gyp": { + "version": "5.0.3", + "bundled": true, + "requires": { + "env-paths": "^1.0.0", + "glob": "^7.0.3", + "graceful-fs": "^4.1.2", + "mkdirp": "^0.5.0", + "nopt": "2 || 3", + "npmlog": "0 || 1 || 2 || 3 || 4", + "request": "^2.87.0", + "rimraf": "2", + "semver": "~5.3.0", + "tar": "^4.4.8", + "which": "1" + }, + "dependencies": { + "nopt": { + "version": "3.0.6", + "bundled": true, + "requires": { + "abbrev": "1" + } + }, + "semver": { + "version": "5.3.0", + "bundled": true + } + } + }, + "nopt": { + "version": "4.0.1", + "bundled": true, + "requires": { + "abbrev": "1", + "osenv": "^0.1.4" + } + }, + "normalize-package-data": { + "version": "2.5.0", + "bundled": true, + "requires": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + }, + "dependencies": { + "resolve": { + "version": "1.10.0", + "bundled": true, + "requires": { + "path-parse": "^1.0.6" + } + } + } + }, + "npm-audit-report": { + "version": "1.3.2", + "bundled": true, + "requires": { + "cli-table3": "^0.5.0", + "console-control-strings": "^1.1.0" + } + }, + "npm-bundled": { + "version": "1.0.6", + "bundled": true + }, + "npm-cache-filename": { + "version": "1.0.2", + "bundled": true + }, + "npm-install-checks": { + "version": "3.0.0", + "bundled": true, + "requires": { + "semver": "^2.3.0 || 3.x || 4 || 5" + } + }, + "npm-lifecycle": { + "version": "3.1.3", + "bundled": true, + "requires": { + "byline": "^5.0.0", + "graceful-fs": "^4.1.15", + "node-gyp": "^5.0.2", + "resolve-from": "^4.0.0", + "slide": "^1.1.6", + "uid-number": "0.0.6", + "umask": "^1.1.0", + "which": "^1.3.1" + } + }, + "npm-logical-tree": { + "version": "1.2.1", + "bundled": true + }, + "npm-package-arg": { + "version": "6.1.1", + "bundled": true, + "requires": { + "hosted-git-info": "^2.7.1", + "osenv": "^0.1.5", + "semver": "^5.6.0", + "validate-npm-package-name": "^3.0.0" + } + }, + "npm-packlist": { + "version": "1.4.4", + "bundled": true, + "requires": { + "ignore-walk": "^3.0.1", + "npm-bundled": "^1.0.1" + } + }, + "npm-pick-manifest": { + "version": "3.0.2", + "bundled": true, + "requires": { + "figgy-pudding": "^3.5.1", + "npm-package-arg": "^6.0.0", + "semver": "^5.4.1" + } + }, + "npm-profile": { + "version": "4.0.2", + "bundled": true, + "requires": { + "aproba": "^1.1.2 || 2", + "figgy-pudding": "^3.4.1", + "npm-registry-fetch": "^4.0.0" + } + }, + "npm-registry-fetch": { + "version": "4.0.0", + "bundled": true, + "requires": { + "JSONStream": "^1.3.4", + "bluebird": "^3.5.1", + "figgy-pudding": "^3.4.1", + "lru-cache": "^5.1.1", + "make-fetch-happen": "^5.0.0", + "npm-package-arg": "^6.1.0" + } + }, + "npm-run-path": { + "version": "2.0.2", + "bundled": true, + "requires": { + "path-key": "^2.0.0" + } + }, + "npm-user-validate": { + "version": "1.0.0", + "bundled": true + }, + "npmlog": { + "version": "4.1.2", + "bundled": true, + "requires": { + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" + } + }, + "number-is-nan": { + "version": "1.0.1", + "bundled": true + }, + "oauth-sign": { + "version": "0.9.0", + "bundled": true + }, + "object-assign": { + "version": "4.1.1", + "bundled": true + }, + "object-keys": { + "version": "1.0.12", + "bundled": true + }, + "object.getownpropertydescriptors": { + "version": "2.0.3", + "bundled": true, + "requires": { + "define-properties": "^1.1.2", + "es-abstract": "^1.5.1" + } + }, + "once": { + "version": "1.4.0", + "bundled": true, + "requires": { + "wrappy": "1" + } + }, + "opener": { + "version": "1.5.1", + "bundled": true + }, + "os-homedir": { + "version": "1.0.2", + "bundled": true + }, + "os-locale": { + "version": "2.1.0", + "bundled": true, + "requires": { + "execa": "^0.7.0", + "lcid": "^1.0.0", + "mem": "^1.1.0" + } + }, + "os-tmpdir": { + "version": "1.0.2", + "bundled": true + }, + "osenv": { + "version": "0.1.5", + "bundled": true, + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } + }, + "p-finally": { + "version": "1.0.0", + "bundled": true + }, + "p-limit": { + "version": "1.2.0", + "bundled": true, + "requires": { + "p-try": "^1.0.0" + } + }, + "p-locate": { + "version": "2.0.0", + "bundled": true, + "requires": { + "p-limit": "^1.1.0" + } + }, + "p-try": { + "version": "1.0.0", + "bundled": true + }, + "package-json": { + "version": "4.0.1", + "bundled": true, + "requires": { + "got": "^6.7.1", + "registry-auth-token": "^3.0.1", + "registry-url": "^3.0.3", + "semver": "^5.1.0" + } + }, + "pacote": { + "version": "9.5.8", + "bundled": true, + "requires": { + "bluebird": "^3.5.3", + "cacache": "^12.0.2", + "chownr": "^1.1.2", + "figgy-pudding": "^3.5.1", + "get-stream": "^4.1.0", + "glob": "^7.1.3", + "infer-owner": "^1.0.4", + "lru-cache": "^5.1.1", + "make-fetch-happen": "^5.0.0", + "minimatch": "^3.0.4", + "minipass": "^2.3.5", + "mississippi": "^3.0.0", + "mkdirp": "^0.5.1", + "normalize-package-data": "^2.4.0", + "npm-package-arg": "^6.1.0", + "npm-packlist": "^1.1.12", + "npm-pick-manifest": "^3.0.0", + "npm-registry-fetch": "^4.0.0", + "osenv": "^0.1.5", + "promise-inflight": "^1.0.1", + "promise-retry": "^1.1.1", + "protoduck": "^5.0.1", + "rimraf": "^2.6.2", + "safe-buffer": "^5.1.2", + "semver": "^5.6.0", + "ssri": "^6.0.1", + "tar": "^4.4.10", + "unique-filename": "^1.1.1", + "which": "^1.3.1" + }, + "dependencies": { + "minipass": { + "version": "2.3.5", + "bundled": true, + "requires": { + "safe-buffer": "^5.1.2", + "yallist": "^3.0.0" + } + } + } + }, + "parallel-transform": { + "version": "1.1.0", + "bundled": true, + "requires": { + "cyclist": "~0.2.2", + "inherits": "^2.0.3", + "readable-stream": "^2.1.5" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "path-exists": { + "version": "3.0.0", + "bundled": true + }, + "path-is-absolute": { + "version": "1.0.1", + "bundled": true + }, + "path-is-inside": { + "version": "1.0.2", + "bundled": true + }, + "path-key": { + "version": "2.0.1", + "bundled": true + }, + "path-parse": { + "version": "1.0.6", + "bundled": true + }, + "performance-now": { + "version": "2.1.0", + "bundled": true + }, + "pify": { + "version": "3.0.0", + "bundled": true + }, + "prepend-http": { + "version": "1.0.4", + "bundled": true + }, + "process-nextick-args": { + "version": "2.0.0", + "bundled": true + }, + "promise-inflight": { + "version": "1.0.1", + "bundled": true + }, + "promise-retry": { + "version": "1.1.1", + "bundled": true, + "requires": { + "err-code": "^1.0.0", + "retry": "^0.10.0" + }, + "dependencies": { + "retry": { + "version": "0.10.1", + "bundled": true + } + } + }, + "promzard": { + "version": "0.3.0", + "bundled": true, + "requires": { + "read": "1" + } + }, + "proto-list": { + "version": "1.2.4", + "bundled": true + }, + "protoduck": { + "version": "5.0.1", + "bundled": true, + "requires": { + "genfun": "^5.0.0" + } + }, + "prr": { + "version": "1.0.1", + "bundled": true + }, + "pseudomap": { + "version": "1.0.2", + "bundled": true + }, + "psl": { + "version": "1.1.29", + "bundled": true + }, + "pump": { + "version": "3.0.0", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "pumpify": { + "version": "1.5.1", + "bundled": true, + "requires": { + "duplexify": "^3.6.0", + "inherits": "^2.0.3", + "pump": "^2.0.0" + }, + "dependencies": { + "pump": { + "version": "2.0.1", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + } + } + }, + "punycode": { + "version": "1.4.1", + "bundled": true + }, + "qrcode-terminal": { + "version": "0.12.0", + "bundled": true + }, + "qs": { + "version": "6.5.2", + "bundled": true + }, + "query-string": { + "version": "6.8.2", + "bundled": true, + "requires": { + "decode-uri-component": "^0.2.0", + "split-on-first": "^1.0.0", + "strict-uri-encode": "^2.0.0" + } + }, + "qw": { + "version": "1.0.1", + "bundled": true + }, + "rc": { + "version": "1.2.7", + "bundled": true, + "requires": { + "deep-extend": "^0.5.1", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "bundled": true + } + } + }, + "read": { + "version": "1.0.7", + "bundled": true, + "requires": { + "mute-stream": "~0.0.4" + } + }, + "read-cmd-shim": { + "version": "1.0.4", + "bundled": true, + "requires": { + "graceful-fs": "^4.1.2" + } + }, + "read-installed": { + "version": "4.0.3", + "bundled": true, + "requires": { + "debuglog": "^1.0.1", + "graceful-fs": "^4.1.2", + "read-package-json": "^2.0.0", + "readdir-scoped-modules": "^1.0.0", + "semver": "2 || 3 || 4 || 5", + "slide": "~1.1.3", + "util-extend": "^1.0.1" + } + }, + "read-package-json": { + "version": "2.1.0", + "bundled": true, + "requires": { + "glob": "^7.1.1", + "graceful-fs": "^4.1.2", + "json-parse-better-errors": "^1.0.1", + "normalize-package-data": "^2.0.0", + "slash": "^1.0.0" + } + }, + "read-package-tree": { + "version": "5.3.1", + "bundled": true, + "requires": { + "read-package-json": "^2.0.0", + "readdir-scoped-modules": "^1.0.0", + "util-promisify": "^2.1.0" + } + }, + "readable-stream": { + "version": "3.4.0", + "bundled": true, + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + }, + "readdir-scoped-modules": { + "version": "1.1.0", + "bundled": true, + "requires": { + "debuglog": "^1.0.1", + "dezalgo": "^1.0.0", + "graceful-fs": "^4.1.2", + "once": "^1.3.0" + } + }, + "registry-auth-token": { + "version": "3.3.2", + "bundled": true, + "requires": { + "rc": "^1.1.6", + "safe-buffer": "^5.0.1" + } + }, + "registry-url": { + "version": "3.1.0", + "bundled": true, + "requires": { + "rc": "^1.0.1" + } + }, + "request": { + "version": "2.88.0", + "bundled": true, + "requires": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.0", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.4.3", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + } + }, + "require-directory": { + "version": "2.1.1", + "bundled": true + }, + "require-main-filename": { + "version": "1.0.1", + "bundled": true + }, + "resolve-from": { + "version": "4.0.0", + "bundled": true + }, + "retry": { + "version": "0.12.0", + "bundled": true + }, + "rimraf": { + "version": "2.6.3", + "bundled": true, + "requires": { + "glob": "^7.1.3" + } + }, + "run-queue": { + "version": "1.0.3", + "bundled": true, + "requires": { + "aproba": "^1.1.1" + }, + "dependencies": { + "aproba": { + "version": "1.2.0", + "bundled": true + } + } + }, + "safe-buffer": { + "version": "5.1.2", + "bundled": true + }, + "safer-buffer": { + "version": "2.1.2", + "bundled": true + }, + "semver": { + "version": "5.7.1", + "bundled": true + }, + "semver-diff": { + "version": "2.1.0", + "bundled": true, + "requires": { + "semver": "^5.0.3" + } + }, + "set-blocking": { + "version": "2.0.0", + "bundled": true + }, + "sha": { + "version": "3.0.0", + "bundled": true, + "requires": { + "graceful-fs": "^4.1.2" + } + }, + "shebang-command": { + "version": "1.2.0", + "bundled": true, + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "bundled": true + }, + "signal-exit": { + "version": "3.0.2", + "bundled": true + }, + "slash": { + "version": "1.0.0", + "bundled": true + }, + "slide": { + "version": "1.1.6", + "bundled": true + }, + "smart-buffer": { + "version": "4.0.2", + "bundled": true + }, + "socks": { + "version": "2.3.2", + "bundled": true, + "requires": { + "ip": "^1.1.5", + "smart-buffer": "4.0.2" + } + }, + "socks-proxy-agent": { + "version": "4.0.2", + "bundled": true, + "requires": { + "agent-base": "~4.2.1", + "socks": "~2.3.2" + }, + "dependencies": { + "agent-base": { + "version": "4.2.1", + "bundled": true, + "requires": { + "es6-promisify": "^5.0.0" + } + } + } + }, + "sorted-object": { + "version": "2.0.1", + "bundled": true + }, + "sorted-union-stream": { + "version": "2.1.3", + "bundled": true, + "requires": { + "from2": "^1.3.0", + "stream-iterate": "^1.1.0" + }, + "dependencies": { + "from2": { + "version": "1.3.0", + "bundled": true, + "requires": { + "inherits": "~2.0.1", + "readable-stream": "~1.1.10" + } + }, + "isarray": { + "version": "0.0.1", + "bundled": true + }, + "readable-stream": { + "version": "1.1.14", + "bundled": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "string_decoder": { + "version": "0.10.31", + "bundled": true + } + } + }, + "spdx-correct": { + "version": "3.0.0", + "bundled": true, + "requires": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-exceptions": { + "version": "2.1.0", + "bundled": true + }, + "spdx-expression-parse": { + "version": "3.0.0", + "bundled": true, + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-license-ids": { + "version": "3.0.3", + "bundled": true + }, + "split-on-first": { + "version": "1.1.0", + "bundled": true + }, + "sshpk": { + "version": "1.14.2", + "bundled": true, + "requires": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + } + }, + "ssri": { + "version": "6.0.1", + "bundled": true, + "requires": { + "figgy-pudding": "^3.5.1" + } + }, + "stream-each": { + "version": "1.2.2", + "bundled": true, + "requires": { + "end-of-stream": "^1.1.0", + "stream-shift": "^1.0.0" + } + }, + "stream-iterate": { + "version": "1.2.0", + "bundled": true, + "requires": { + "readable-stream": "^2.1.5", + "stream-shift": "^1.0.0" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "stream-shift": { + "version": "1.0.0", + "bundled": true + }, + "strict-uri-encode": { + "version": "2.0.0", + "bundled": true + }, + "string-width": { + "version": "2.1.1", + "bundled": true, + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "bundled": true + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "bundled": true + }, + "strip-ansi": { + "version": "4.0.0", + "bundled": true, + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "string_decoder": { + "version": "1.2.0", + "bundled": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "stringify-package": { + "version": "1.0.0", + "bundled": true + }, + "strip-ansi": { + "version": "3.0.1", + "bundled": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "strip-eof": { + "version": "1.0.0", + "bundled": true + }, + "strip-json-comments": { + "version": "2.0.1", + "bundled": true + }, + "supports-color": { + "version": "5.4.0", + "bundled": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "tar": { + "version": "4.4.10", + "bundled": true, + "requires": { + "chownr": "^1.1.1", + "fs-minipass": "^1.2.5", + "minipass": "^2.3.5", + "minizlib": "^1.2.1", + "mkdirp": "^0.5.0", + "safe-buffer": "^5.1.2", + "yallist": "^3.0.3" + }, + "dependencies": { + "minipass": { + "version": "2.3.5", + "bundled": true, + "requires": { + "safe-buffer": "^5.1.2", + "yallist": "^3.0.0" + } + }, + "yallist": { + "version": "3.0.3", + "bundled": true + } + } + }, + "term-size": { + "version": "1.2.0", + "bundled": true, + "requires": { + "execa": "^0.7.0" + } + }, + "text-table": { + "version": "0.2.0", + "bundled": true + }, + "through": { + "version": "2.3.8", + "bundled": true + }, + "through2": { + "version": "2.0.3", + "bundled": true, + "requires": { + "readable-stream": "^2.1.5", + "xtend": "~4.0.1" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "timed-out": { + "version": "4.0.1", + "bundled": true + }, + "tiny-relative-date": { + "version": "1.3.0", + "bundled": true + }, + "tough-cookie": { + "version": "2.4.3", + "bundled": true, + "requires": { + "psl": "^1.1.24", + "punycode": "^1.4.1" + } + }, + "tunnel-agent": { + "version": "0.6.0", + "bundled": true, + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "tweetnacl": { + "version": "0.14.5", + "bundled": true, + "optional": true + }, + "typedarray": { + "version": "0.0.6", + "bundled": true + }, + "uid-number": { + "version": "0.0.6", + "bundled": true + }, + "umask": { + "version": "1.1.0", + "bundled": true + }, + "unique-filename": { + "version": "1.1.1", + "bundled": true, + "requires": { + "unique-slug": "^2.0.0" + } + }, + "unique-slug": { + "version": "2.0.0", + "bundled": true, + "requires": { + "imurmurhash": "^0.1.4" + } + }, + "unique-string": { + "version": "1.0.0", + "bundled": true, + "requires": { + "crypto-random-string": "^1.0.0" + } + }, + "unpipe": { + "version": "1.0.0", + "bundled": true + }, + "unzip-response": { + "version": "2.0.1", + "bundled": true + }, + "update-notifier": { + "version": "2.5.0", + "bundled": true, + "requires": { + "boxen": "^1.2.1", + "chalk": "^2.0.1", + "configstore": "^3.0.0", + "import-lazy": "^2.1.0", + "is-ci": "^1.0.10", + "is-installed-globally": "^0.1.0", + "is-npm": "^1.0.0", + "latest-version": "^3.0.0", + "semver-diff": "^2.0.0", + "xdg-basedir": "^3.0.0" + } + }, + "url-parse-lax": { + "version": "1.0.0", + "bundled": true, + "requires": { + "prepend-http": "^1.0.1" + } + }, + "util-deprecate": { + "version": "1.0.2", + "bundled": true + }, + "util-extend": { + "version": "1.0.3", + "bundled": true + }, + "util-promisify": { + "version": "2.1.0", + "bundled": true, + "requires": { + "object.getownpropertydescriptors": "^2.0.3" + } + }, + "uuid": { + "version": "3.3.2", + "bundled": true + }, + "validate-npm-package-license": { + "version": "3.0.4", + "bundled": true, + "requires": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "validate-npm-package-name": { + "version": "3.0.0", + "bundled": true, + "requires": { + "builtins": "^1.0.3" + } + }, + "verror": { + "version": "1.10.0", + "bundled": true, + "requires": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "wcwidth": { + "version": "1.0.1", + "bundled": true, + "requires": { + "defaults": "^1.0.3" + } + }, + "which": { + "version": "1.3.1", + "bundled": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "which-module": { + "version": "2.0.0", + "bundled": true + }, + "wide-align": { + "version": "1.1.2", + "bundled": true, + "requires": { + "string-width": "^1.0.2" + }, + "dependencies": { + "string-width": { + "version": "1.0.2", + "bundled": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + } + } + }, + "widest-line": { + "version": "2.0.0", + "bundled": true, + "requires": { + "string-width": "^2.1.1" + } + }, + "worker-farm": { + "version": "1.7.0", + "bundled": true, + "requires": { + "errno": "~0.1.7" + } + }, + "wrap-ansi": { + "version": "2.1.0", + "bundled": true, + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1" + }, + "dependencies": { + "string-width": { + "version": "1.0.2", + "bundled": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + } + } + }, + "wrappy": { + "version": "1.0.2", + "bundled": true + }, + "write-file-atomic": { + "version": "2.4.3", + "bundled": true, + "requires": { + "graceful-fs": "^4.1.11", + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.2" + } + }, + "xdg-basedir": { + "version": "3.0.0", + "bundled": true + }, + "xtend": { + "version": "4.0.1", + "bundled": true + }, + "y18n": { + "version": "4.0.0", + "bundled": true + }, + "yallist": { + "version": "3.0.3", + "bundled": true + }, + "yargs": { + "version": "11.0.0", + "bundled": true, + "requires": { + "cliui": "^4.0.0", + "decamelize": "^1.1.1", + "find-up": "^2.1.0", + "get-caller-file": "^1.0.1", + "os-locale": "^2.0.0", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^2.0.0", + "which-module": "^2.0.0", + "y18n": "^3.2.1", + "yargs-parser": "^9.0.2" + }, + "dependencies": { + "y18n": { + "version": "3.2.1", + "bundled": true + } + } + }, + "yargs-parser": { + "version": "9.0.2", + "bundled": true, + "requires": { + "camelcase": "^4.1.0" + } + } + } + }, + "oclazyload": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/oclazyload/-/oclazyload-0.6.3.tgz", + "integrity": "sha1-Kjirv/QJDAihEBZxkZRbWfLoJ5w=" + }, + "regenerator-runtime": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.12.1.tgz", + "integrity": "sha512-odxIc1/vDlo4iZcfXqRYFj0vpXFNoGdKMAUieAlFYO6m/nl5e9KR/beGf41z4a1FI+aQgtjhuaSlDxQ0hmkrHg==" + }, + "require-yaml": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/require-yaml/-/require-yaml-0.0.1.tgz", + "integrity": "sha1-LhsY2RPDuqcqWk03O28Tjd0sMr0=", + "requires": { + "js-yaml": "^3.13.1" + }, + "dependencies": { + "js-yaml": { + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + } + } + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" + }, + "validator": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/validator/-/validator-6.3.0.tgz", + "integrity": "sha1-R84j7Y1Ord+p1LjvAHG2zxB418g=" + } + } +} diff --git a/front/package.json b/front/package.json new file mode 100644 index 000000000..1eb3a8b8e --- /dev/null +++ b/front/package.json @@ -0,0 +1,25 @@ +{ + "name": "salix-front", + "version": "1.0.0", + "author": "Verdnatura Levante SL", + "description": "Salix frontend", + "license": "GPL-3.0", + "repository": { + "type": "git", + "url": "https://gitea.verdnatura.es/verdnatura/salix" + }, + "dependencies": { + "@babel/polyfill": "^7.2.5", + "@uirouter/angularjs": "^1.0.20", + "angular": "^1.7.5", + "angular-animate": "^1.7.8", + "angular-translate": "^2.18.1", + "angular-translate-loader-partial": "^2.18.1", + "js-yaml": "^3.13.1", + "mg-crud": "^1.1.2", + "npm": "^6.11.3", + "oclazyload": "^0.6.3", + "require-yaml": "0.0.1", + "validator": "^6.3.0" + } +} diff --git a/client/salix/src/bootstrap.js b/front/salix/bootstrap.js similarity index 76% rename from client/salix/src/bootstrap.js rename to front/salix/bootstrap.js index dd7a61388..2b959636d 100644 --- a/client/salix/src/bootstrap.js +++ b/front/salix/bootstrap.js @@ -1,4 +1,4 @@ -import {ng} from 'vendor'; +import {ng} from 'core/vendor'; import appName from './module'; export const bootstrap = () => { @@ -10,8 +10,10 @@ export const bootstrap = () => { })(); let _element = _script && document.querySelector(_script.getAttribute(selector)); - if (!_element) { + if (!_element) throw new Error('Element is not defined'); - } - ng.bootstrap(_element, [appName]); + + ng.bootstrap(_element, [appName], { + strictDi: true + }); }; diff --git a/front/salix/components/app/app.html b/front/salix/components/app/app.html new file mode 100644 index 000000000..5432609c2 --- /dev/null +++ b/front/salix/components/app/app.html @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git a/front/salix/components/app/app.js b/front/salix/components/app/app.js new file mode 100644 index 000000000..1f8cdb46e --- /dev/null +++ b/front/salix/components/app/app.js @@ -0,0 +1,42 @@ +import ngModule from '../../module'; +import './style.scss'; +import Component from 'core/lib/component'; + +/** + * The main graphical application component. + * + * @property {SideMenu} leftMenu The left menu, if it's present + * @property {SideMenu} rightMenu The left menu, if it's present + */ +export default class App extends Component { + $postLink() { + this.vnApp.logger = this; + } + + get showLayout() { + let state = this.$state.current.name; + return state && state != 'login'; + } + + $onDestroy() { + this.deregisterCallback(); + this.vnApp.logger = null; + } + + showMessage(message) { + this.$.snackbar.show({message: message}); + } + + showSuccess(message) { + this.$.snackbar.showSuccess({message: message}); + } + + showError(message) { + this.$.snackbar.showError({message: message}); + } +} + +ngModule.vnComponent('vnApp', { + template: require('./app.html'), + controller: App +}); diff --git a/front/salix/components/app/style.scss b/front/salix/components/app/style.scss new file mode 100644 index 000000000..aab37c8a3 --- /dev/null +++ b/front/salix/components/app/style.scss @@ -0,0 +1,17 @@ +@import "variables"; + +vn-app { + display: block; + height: inherit; + + ui-view { + display: block; + box-sizing: border-box; + height: inherit; + + &.ng-enter { + animation-name: nothing, slideIn; + animation-duration: 400ms, 200ms; + } + } +} diff --git a/front/salix/components/background/background.js b/front/salix/components/background/background.js new file mode 100644 index 000000000..423b033ce --- /dev/null +++ b/front/salix/components/background/background.js @@ -0,0 +1 @@ +import './style.scss'; diff --git a/front/salix/components/background/style.scss b/front/salix/components/background/style.scss new file mode 100644 index 000000000..c75b69c52 --- /dev/null +++ b/front/salix/components/background/style.scss @@ -0,0 +1,26 @@ +@import "variables"; + +@keyframes fadein { + from { + opacity: 0; + } +} + +vn-background { + display: none; + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background-color: black; + z-index: 14; + + @media screen and (max-width: $mobile-width) { + &.shown { + display: block; + opacity: .3; + animation: 500ms ease-out fadein; + } + } +} diff --git a/front/salix/components/descriptor/index.html b/front/salix/components/descriptor/index.html new file mode 100644 index 000000000..3804be627 --- /dev/null +++ b/front/salix/components/descriptor/index.html @@ -0,0 +1,24 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/front/salix/components/descriptor/index.js b/front/salix/components/descriptor/index.js new file mode 100644 index 000000000..504812b15 --- /dev/null +++ b/front/salix/components/descriptor/index.js @@ -0,0 +1,12 @@ +import ngModule from '../../module'; +import './style.scss'; + +export default class QuickLinks {} + +ngModule.component('vnQuickLinks', { + template: require('./index.html'), + controller: QuickLinks, + bindings: { + links: ' .header { + display: flex; + background: $color-main; + justify-content: space-between; + align-items: stretch; + color: $color-font-dark; + + & > * { + @extend %clickable; + min-width: 45px; + height: 45px; + box-sizing: border-box; + display: flex; + align-items: center; + justify-content: center; + color: inherit; + + & > vn-icon { + padding: 10px; + } + vn-icon { + font-size: 1.8em; + } + } + } + & > .body { + padding: $spacing-sm; + + & > * { + padding: $spacing-sm; + } + & > .attributes > h5 { + padding-bottom: $spacing-sm; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + } + & > .icons { + display: flex; + align-items: center; + justify-content: center; + padding: 0; + + & > vn-icon { + padding: $spacing-sm; + color: $color-marginal; + font-size: 1.5em; + + &.bright { + color: $color-main; + opacity: 1; + } + } + } + .quicklinks, + vn-quick-links { + display: flex; + align-items: center; + justify-content: center; + + & > a { + padding: 0 $spacing-md; + margin: 0 $spacing-sm; + + & > vn-icon { + font-size: 1.8em; + padding: 0; + } + } + } + } +} +.vn-popover { + .vn-descriptor > .header > a:first-child { + visibility: hidden; + } +} \ No newline at end of file diff --git a/front/salix/components/home/home.html b/front/salix/components/home/home.html new file mode 100644 index 000000000..b3fc02d0d --- /dev/null +++ b/front/salix/components/home/home.html @@ -0,0 +1,20 @@ + diff --git a/front/salix/components/home/home.js b/front/salix/components/home/home.js new file mode 100644 index 000000000..367880b31 --- /dev/null +++ b/front/salix/components/home/home.js @@ -0,0 +1,34 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +export default class Controller extends Component { + constructor($element, $, vnModules, $sce) { + super($element, $); + this.modules = vnModules.get(); + this.$sce = $sce; + } + + getModuleName(mod) { + let getName = mod => { + let name = this.$t(mod.name); + let upper = name.toUpperCase(); + if (!mod.keyBind) return name; + let index = upper.indexOf(mod.keyBind); + if (index === -1) return name; + + let newName = name.substr(0, index); + newName += `${name.substr(index, 1)}`; + newName += name.substr(index + 1); + return newName; + }; + + return this.$sce.trustAsHtml(getName(mod)); + } +} +Controller.$inject = ['$element', '$scope', 'vnModules', '$sce']; + +ngModule.component('vnHome', { + template: require('./home.html'), + controller: Controller +}); diff --git a/front/salix/components/home/style.scss b/front/salix/components/home/style.scss new file mode 100644 index 000000000..268260bbd --- /dev/null +++ b/front/salix/components/home/style.scss @@ -0,0 +1,67 @@ +@import "effects"; + +vn-home { + display: block; + padding: .5em; + + & > div { + & > h6 { + color: #3C393B; + text-align: center; + margin-bottom: 15px; + } + & > .modules { + display: flex; + flex: 1; + flex-direction: row; + justify-content: center; + flex-wrap: wrap; + max-width: 44em; + margin: 0 auto; + + & > a { + @extend %clickable-light; + overflow:hidden; + border-radius: 6px; + background-color: $color-button; + color: $color-font-dark; + display: flex; + flex-direction: column; + height: 8em; + width: 8em; + margin: .5em; + padding: 1em; + justify-content: center; + + & > div { + height: 70px; + display: flex; + align-items: center; + justify-content: center; + + & > vn-icon { + display: block; + font-size: 3.5em; + } + } + & > span { + font-size: 0.9em; + text-align: center; + } + & > h4 { + max-width: 100%; + text-align: center; + font-size: 12pt; + overflow: hidden; + color: inherit; + margin: 0; + line-height: 1.5em; + + /* & > .bind-letter { + color: #FD0; + } */ + } + } + } + } +} \ No newline at end of file diff --git a/front/salix/components/index.js b/front/salix/components/index.js new file mode 100644 index 000000000..2afd55edf --- /dev/null +++ b/front/salix/components/index.js @@ -0,0 +1,14 @@ +import './app/app'; +import './background/background'; +import './descriptor'; +import './home/home'; +import './layout'; +import './left-menu/left-menu'; +import './login/login'; +import './module-card'; +import './module-main'; +import './side-menu/side-menu'; +import './section'; +import './summary'; +import './topbar/topbar'; +import './user-popover'; diff --git a/front/salix/components/layout/index..js b/front/salix/components/layout/index..js new file mode 100644 index 000000000..9fdcfc034 --- /dev/null +++ b/front/salix/components/layout/index..js @@ -0,0 +1,24 @@ +import './index.js'; + +describe('Component vnMainMenu', () => { + let $httpBackend; + let controller; + + beforeEach(ngModule('salix')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + let vnModules = {get: () => {}}; + $httpBackend = _$httpBackend_; + controller = $componentController('vnMainMenu', {vnModules}); + })); + + describe('getCurrentUserName()', () => { + it(`should set the user name property in the controller`, () => { + $httpBackend.expect('GET', `Accounts/getUserData`).respond({name: 'batman'}); + controller.getCurrentUserName(); + $httpBackend.flush(); + + expect(controller.$.$root.user.name).toEqual('batman'); + }); + }); +}); diff --git a/front/salix/components/layout/index.html b/front/salix/components/layout/index.html new file mode 100644 index 000000000..0ad400114 --- /dev/null +++ b/front/salix/components/layout/index.html @@ -0,0 +1,77 @@ + + + +
    + +
    + {{$ctrl.$state.current.description}} +
    + + +
    + +
    + + + + + + +
    + +
      +
    • + + Home +
    • +
    • + + {{::mod.name}} +
    • +
    +
    + + +
    + + + + + + + + + + + {{::mod.name}} + + + + + \ No newline at end of file diff --git a/front/salix/components/layout/index.js b/front/salix/components/layout/index.js new file mode 100644 index 000000000..883b010ba --- /dev/null +++ b/front/salix/components/layout/index.js @@ -0,0 +1,30 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +export class Layout extends Component { + constructor($element, $, vnModules) { + super($element, $); + this.modules = vnModules.get(); + } + + $onInit() { + this.getUserData(); + } + + getUserData() { + this.$http.get('Accounts/getCurrentUserData').then(json => { + this.$.$root.user = json.data; + window.localStorage.currentUserWorkerId = json.data.workerId; + }); + } +} +Layout.$inject = ['$element', '$scope', 'vnModules']; + +ngModule.component('vnLayout', { + template: require('./index.html'), + controller: Layout, + require: { + app: '^vnApp' + } +}); diff --git a/front/salix/components/layout/index.spec.js b/front/salix/components/layout/index.spec.js new file mode 100644 index 000000000..7163acb65 --- /dev/null +++ b/front/salix/components/layout/index.spec.js @@ -0,0 +1,25 @@ +import './index.js'; + +describe('Component vnLayout', () => { + let $httpBackend; + let controller; + + beforeEach(ngModule('salix')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + let vnModules = {get: () => {}}; + $httpBackend = _$httpBackend_; + let $element = angular.element('
    '); + controller = $componentController('vnLayout', {$element, vnModules}); + })); + + describe('getUserData()', () => { + it(`should set the user name property in the controller`, () => { + $httpBackend.expect('GET', `Accounts/getCurrentUserData`).respond({name: 'batman'}); + controller.getUserData(); + $httpBackend.flush(); + + expect(controller.$.$root.user.name).toEqual('batman'); + }); + }); +}); diff --git a/client/salix/src/components/app/logo.svg b/front/salix/components/layout/logo-text.svg similarity index 100% rename from client/salix/src/components/app/logo.svg rename to front/salix/components/layout/logo-text.svg diff --git a/front/salix/components/layout/logo.svg b/front/salix/components/layout/logo.svg new file mode 100644 index 000000000..1a111f2f1 --- /dev/null +++ b/front/salix/components/layout/logo.svg @@ -0,0 +1,80 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + diff --git a/front/salix/components/layout/style.scss b/front/salix/components/layout/style.scss new file mode 100644 index 000000000..9a9d903a6 --- /dev/null +++ b/front/salix/components/layout/style.scss @@ -0,0 +1,159 @@ +@import "effects"; + +vn-layout { + & > vn-topbar { + position: fixed; + top: 0; + right: 0; + left: 0; + z-index: 10; + box-shadow: 0 .1em .2em $color-shadow; + height: $topbar-height; + padding: 0 1em; + justify-content: space-between; + + & > .side { + flex: auto; + display: flex; + align-items: center; + width: 5em; + transition: width 200ms; + } + & > .start { + padding-right: 1em; + overflow: hidden; + + & > .logo > img { + height: 2em; + display: block; + } + & > .main-title { + font-size: 1.6em; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + padding-left: .4em; + } + & > vn-spinner { + padding: 0 .4em; + } + } + & > vn-slot { + flex: auto; + } + & > .end { + padding-left: 1em; + justify-content: flex-end; + } + .show-menu { + display: none; + } + .vn-button { + color: inherit; + font-size: 1.05em; + padding: 0; + } + } + & > vn-side-menu > .menu { + display: flex; + flex-direction: column; + align-items: stretch; + + & > vn-slot { + flex: 1; + overflow: auto; + } + } + &.left-menu { + & > vn-topbar > .start { + width: 5em + $menu-width; + } + & > .main-view { + padding-left: $menu-width; + } + } + &.right-menu { + & > vn-topbar > .end { + width: 5em + $menu-width; + } + & > .main-view { + padding-right: $menu-width; + } + } + & > .main-view { + padding-top: $topbar-height; + } + ui-view { + & > * { + display: block; + padding: $spacing-md; + } + &.ng-enter { + vn-side-menu { + opacity: 0; + animation: fadeIn 200ms ease-out 200ms; + } + [fixed-bottom-right] { + opacity: 0; + animation: amplify 200ms ease-out 200ms; + } + } + } + @media screen and (max-width: $mobile-width) { + & > vn-topbar { + & > .start > .logo { + display: none; + } + & > .side { + flex: 1; + } + .show-menu { + display: block; + } + } + &.left-menu { + & > vn-topbar { + left: 0; + } + & > .main-view { + padding-left: 0; + } + } + &.right-menu { + & > .main-view { + padding-right: 0; + } + } + ui-view > * { + padding-left: 0; + padding-right: 0; + } + } +} +.vn-popover .modules-menu { + list-style-type: none; + margin: 0; + color: $color-font-dark; + + & > li { + @extend %clickable-light; + background-color: $color-main; + margin-bottom: .6em; + padding: .8em; + border-radius: .1em; + min-width: 8em; + white-space: nowrap; + + &:last-child { + margin-bottom: 0; + } + & > vn-icon { + padding-right: .3em; + vertical-align: middle; + } + } +} +#user { + font-size: 1.5em; + height: auto; +} diff --git a/front/salix/components/left-menu/left-menu.html b/front/salix/components/left-menu/left-menu.html new file mode 100644 index 000000000..73488a24b --- /dev/null +++ b/front/salix/components/left-menu/left-menu.html @@ -0,0 +1,32 @@ + diff --git a/front/salix/components/left-menu/left-menu.js b/front/salix/components/left-menu/left-menu.js new file mode 100644 index 000000000..92adb02aa --- /dev/null +++ b/front/salix/components/left-menu/left-menu.js @@ -0,0 +1,122 @@ +import ngModule from '../../module'; +import './style.scss'; + +export default class LeftMenu { + constructor($state, $transitions, aclService, $timeout, $element) { + this.$element = $element; + this.$timeout = $timeout; + this.$state = $state; + this.aclService = aclService; + this.deregisterCallback = $transitions.onSuccess({}, + () => this.activateItem()); + this.source = 'main'; + this._depth = 3; + } + + $onInit() { + this.items = this.fetchItems(); + this.activateItem(); + } + + set depth(value) { + this._depth = value; + this.activateItem(); + } + + get depth() { + return this._depth; + } + + fetchItems() { + let states = this.$state.router.stateRegistry.states; + let moduleIndex = this.$state.current.data.moduleIndex; + let moduleFile = window.routes[moduleIndex] || []; + let menu = moduleFile.menus && moduleFile.menus[this.source] || []; + let items = []; + + let addItem = (items, item) => { + let state = states[item.state]; + if (!state) return; + + state = state.self; + let acl = state.data.acl; + + if (acl && !this.aclService.hasAny(acl)) + return; + + items.push({ + icon: item.icon, + description: state.description, + state: item.state + }); + }; + + for (let item of menu) { + if (item.state) + addItem(items, item); + else { + let childs = []; + + for (let child of item.childs) + addItem(childs, child); + + if (childs.length > 0) { + items.push({ + icon: item.icon, + description: item.description, + childs: childs + }); + } + } + } + + return items; + } + + activateItem() { + let myState = this.$state.current.name + .split('.') + .slice(0, this._depth) + .join('.'); + let re = new RegExp(`^${myState}(\\..*)?$`); + + if (this.items) { + // Check items matching current path + for (let item of this.items) { + item.active = re.test(item.state); + + if (item.childs) { + for (let child of item.childs) { + child.active = re.test(child.state); + if (child.active) + item.active = child.active; + } + } + } + } + } + + setActive(item) { + if (item.state) return; + item.active = !item.active; + + this.$timeout(() => { + let element = this.$element[0].querySelector('a.expanded'); + if (element) element.scrollIntoView(); + }); + } + + $onDestroy() { + this.deregisterCallback(); + } +} +LeftMenu.$inject = ['$state', '$transitions', 'aclService', '$timeout', '$element']; + +ngModule.component('vnLeftMenu', { + template: require('./left-menu.html'), + controller: LeftMenu, + bindings: { + source: '@?', + depth: ' { + let controller; + let $element; + + beforeEach(ngModule('salix')); + + beforeEach(angular.mock.inject(($componentController, $state, $window) => { + $element = angular.element('
    '); + $state.current.name = 'client.card.summary'; + $state.current.data = {moduleIndex: 0}; + $window.routes = [{menu: []}]; + controller = $componentController('vnLeftMenu', {$state, $window, $element}); + controller.items = [ + {description: 'Client', state: 'client', icon: null, childs: []}, + {description: 'Client', state: 'client.card', icon: null, childs: []}, + {description: 'Client summary', state: 'client.card.summary', icon: 'myicon', childs: []} + ]; + })); + + it(`should set items in the controller for the left menu`, () => { + expect(controller.items.length).toEqual(3); + expect(controller.items[2].state).toEqual('client.card.summary'); + }); + + describe('depth() setter', () => { + it(`should set depth property and call activateItem()`, () => { + spyOn(controller, 'activateItem'); + controller.depth = 3; + + expect(controller.depth).toEqual(3); + expect(controller.activateItem).toHaveBeenCalledWith(); + }); + }); + + describe('activateItem()', () => { + it(`should set active property to a route item if the current state matches up to a given depth`, () => { + controller._depth = 3; + controller.activateItem(); + + expect(controller.items[2].active).toBeTruthy(); + }); + }); +}); diff --git a/front/salix/components/left-menu/style.scss b/front/salix/components/left-menu/style.scss new file mode 100644 index 000000000..b98e2db2b --- /dev/null +++ b/front/salix/components/left-menu/style.scss @@ -0,0 +1,18 @@ +@import "effects"; + +@import "variables"; + +vn-left-menu { + & > .vn-list { + padding: $spacing-md 0; + + & > li > .vn-item { + & > [side] > vn-icon[icon="keyboard_arrow_down"] { + transition: transform 200ms; + } + &.expanded > [side] > vn-icon[icon="keyboard_arrow_down"] { + transform: rotate(180deg); + } + } + } +} diff --git a/client/auth/src/login/locale/en.yml b/front/salix/components/login/locale/en.yml similarity index 100% rename from client/auth/src/login/locale/en.yml rename to front/salix/components/login/locale/en.yml diff --git a/client/auth/src/login/locale/es.yml b/front/salix/components/login/locale/es.yml similarity index 100% rename from client/auth/src/login/locale/es.yml rename to front/salix/components/login/locale/es.yml diff --git a/front/salix/components/login/login.html b/front/salix/components/login/login.html new file mode 100644 index 000000000..b15714a23 --- /dev/null +++ b/front/salix/components/login/login.html @@ -0,0 +1,27 @@ +
    + +
    + + + + + + + +
    +
    diff --git a/front/salix/components/login/login.js b/front/salix/components/login/login.js new file mode 100644 index 000000000..efb5e02bb --- /dev/null +++ b/front/salix/components/login/login.js @@ -0,0 +1,43 @@ +import ngModule from '../../module'; +import './style.scss'; + +/** + * A simple login form. + */ +export default class Controller { + constructor($, $element, vnAuth) { + Object.assign(this, { + $, + $element, + vnAuth, + user: localStorage.getItem('lastUser'), + remember: true + }); + } + + submit() { + this.loading = true; + this.vnAuth.login(this.user, this.password, this.remember) + .then(() => { + localStorage.setItem('lastUser', this.user); + this.loading = false; + }) + .catch(err => { + this.loading = false; + this.password = ''; + this.focusUser(); + throw err; + }); + } + + focusUser() { + this.$.userField.select(); + this.$.userField.focus(); + } +} +Controller.$inject = ['$scope', '$element', 'vnAuth']; + +ngModule.component('vnLogin', { + template: require('./login.html'), + controller: Controller +}); diff --git a/front/salix/components/login/logo.svg b/front/salix/components/login/logo.svg new file mode 100644 index 000000000..1fae1108f --- /dev/null +++ b/front/salix/components/login/logo.svg @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/front/salix/components/login/style.scss b/front/salix/components/login/style.scss new file mode 100644 index 000000000..e098fbdb4 --- /dev/null +++ b/front/salix/components/login/style.scss @@ -0,0 +1,74 @@ +@import "variables"; + +vn-login { + position: absolute; + height: 100%; + width: 100%; + margin: 0; + padding: 0; + color: $color-font; + font-size: 1.1em; + font-weight: normal; + background-color: $color-bg-dark; + display: flex; + justify-content: center; + align-items: center; + overflow: auto; + + & > .box { + box-sizing: border-box; + position: absolute; + max-width: 19em; + min-width: 15em; + padding: 3em; + background-color: $color-bg-panel; + box-shadow: 0 0 1em 0 rgba(0, 0, 0, .6); + border-radius: .5em; + + & > img { + width: 100%; + padding-bottom: 1em; + } + & > form { + & > .vn-textfield { + width: 100%; + } + & > .vn-check { + display: block; + .md-label { + white-space: inherit; + } + } + & > .footer { + margin-top: 2em; + text-align: center; + position: relative; + + & > vn-submit { + display: block; + + & > input { + display: block; + width: 100%; + } + } + & > .spinner-wrapper { + position: absolute; + width: 0; + top: .2em; + right: -.5em; + overflow: visible; + } + } + } + } + + @media screen and (max-width: 600px) { + background-color: $color-bg-panel; + + & > .box { + padding: 1em; + box-shadow: none; + } + } +} diff --git a/front/salix/components/module-card/index.js b/front/salix/components/module-card/index.js new file mode 100644 index 000000000..9131cc772 --- /dev/null +++ b/front/salix/components/module-card/index.js @@ -0,0 +1,29 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +/** + * Base class for module cards. + */ +export default class ModuleCard extends Component { + constructor($element, $) { + super($element, $); + this.element.classList.add('vn-module-card'); + } + + $onInit() { + this.reload(); + } + + /** + * Reloads the card data. Should be implemented or overriden by child + * classes. + */ + reload() { + throw new Error('ModuleCard::reload() method not implemented'); + } +} + +ngModule.vnComponent('vnModuleCard', { + controller: ModuleCard +}); diff --git a/front/salix/components/module-card/style.scss b/front/salix/components/module-card/style.scss new file mode 100644 index 000000000..0ae943efc --- /dev/null +++ b/front/salix/components/module-card/style.scss @@ -0,0 +1,5 @@ +@import "variables"; + +.vn-module-card { + padding: 0; +} \ No newline at end of file diff --git a/front/salix/components/module-main/index.html b/front/salix/components/module-main/index.html new file mode 100644 index 000000000..6e04f06d0 --- /dev/null +++ b/front/salix/components/module-main/index.html @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/front/salix/components/module-main/index.js b/front/salix/components/module-main/index.js new file mode 100644 index 000000000..39fbe42b8 --- /dev/null +++ b/front/salix/components/module-main/index.js @@ -0,0 +1,15 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +export default class ModuleMain extends Component { + constructor($element, $) { + super($element, $); + this.element.classList.add('vn-module-main'); + } +} + +ngModule.vnComponent('vnModuleMain', { + template: require('./index.html'), + controller: ModuleMain +}); diff --git a/front/salix/components/module-main/style.scss b/front/salix/components/module-main/style.scss new file mode 100644 index 000000000..d9bdbd940 --- /dev/null +++ b/front/salix/components/module-main/style.scss @@ -0,0 +1,5 @@ +@import "variables"; + +.vn-module-main { + padding: 0; +} \ No newline at end of file diff --git a/front/salix/components/section/index.js b/front/salix/components/section/index.js new file mode 100644 index 000000000..a0c7484b4 --- /dev/null +++ b/front/salix/components/section/index.js @@ -0,0 +1,14 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +export default class Section extends Component { + constructor($element, $) { + super($element, $); + this.element.classList.add('vn-section'); + } +} + +ngModule.vnComponent('vnSection', { + controller: Section +}); diff --git a/client/client/src/notes/style.css b/front/salix/components/section/style.scss similarity index 100% rename from client/client/src/notes/style.css rename to front/salix/components/section/style.scss diff --git a/front/salix/components/side-menu/side-menu.html b/front/salix/components/side-menu/side-menu.html new file mode 100644 index 000000000..b56d3cece --- /dev/null +++ b/front/salix/components/side-menu/side-menu.html @@ -0,0 +1,9 @@ + + + diff --git a/front/salix/components/side-menu/side-menu.js b/front/salix/components/side-menu/side-menu.js new file mode 100644 index 000000000..c2b5b421e --- /dev/null +++ b/front/salix/components/side-menu/side-menu.js @@ -0,0 +1,81 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +/** + * A side menu. + * + * @property {String} side [left|right] The side where the menu is displayed + * @property {Boolean} shown Whether the menu it's currently displayed (Only for small viewports) + */ +export default class SideMenu extends Component { + constructor($element, $) { + super($element, $); + this.side = 'left'; + } + + $onInit() { + this.menu = this.$element[0].querySelector('.menu'); + + if (this.side == 'right') { + this.menu.classList.add('right'); + this.layout.rightMenu = this; + this.layout.element.classList.add('right-menu'); + } else { + this.menu.classList.add('left'); + this.layout.leftMenu = this; + this.layout.element.classList.add('left-menu'); + } + } + + $onDestroy() { + if (this.side == 'right') { + this.layout.rightMenu = null; + this.layout.element.classList.remove('right-menu'); + } else { + this.layout.leftMenu = null; + this.layout.element.classList.remove('left-menu'); + } + + this.hide(); + } + + onEscape(event) { + if (!event.defaultPrevented && event.key == 'Escape') { + this.hide(); + this.$.$digest(); + } + } + + onTransition(transition) { + if (transition.from().name !== transition.to().name) + this.hide(); + } + + show() { + if (this.shown) return; + this.shown = true; + this.handler = e => this.onEscape(e); + this.$window.addEventListener('keydown', this.handler); + this.stateHandler = this.$transitions.onStart({}, t => this.onTransition(t)); + } + + hide() { + if (!this.shown) return; + this.$window.removeEventListener('keydown', this.handler); + this.stateHandler(); + this.shown = false; + } +} + +ngModule.component('vnSideMenu', { + template: require('./side-menu.html'), + controller: SideMenu, + transclude: true, + bindings: { + side: '@?' + }, + require: { + layout: '^vnLayout' + } +}); diff --git a/front/salix/components/side-menu/style.scss b/front/salix/components/side-menu/style.scss new file mode 100644 index 000000000..239d15cf6 --- /dev/null +++ b/front/salix/components/side-menu/style.scss @@ -0,0 +1,41 @@ +@import "variables"; + +vn-side-menu { + display: block; +} +vn-side-menu > .menu { + display: block; + position: fixed; + z-index: 5; + bottom: 0; + width: $menu-width; + min-width: $menu-width; + background-color: $color-bg-panel; + box-shadow: 0 .1em .2em $color-shadow; + overflow: auto; + top: $topbar-height; + + &.left { + left: 0; + } + &.right { + right: 0; + } + + @media screen and (max-width: $mobile-width) { + transition: transform 200ms ease-out; + z-index: 15; + top: 0; + + &.left { + transform: translateZ(0) translateX(-$menu-width); + } + &.right { + top: 0; + transform: translateZ(0) translateX($menu-width); + } + &.shown { + transform: translateZ(0) translateX(0); + } + } +} diff --git a/front/salix/components/summary/index.js b/front/salix/components/summary/index.js new file mode 100644 index 000000000..423b033ce --- /dev/null +++ b/front/salix/components/summary/index.js @@ -0,0 +1 @@ +import './style.scss'; diff --git a/front/salix/components/summary/style.scss b/front/salix/components/summary/style.scss new file mode 100644 index 000000000..f0d6ae038 --- /dev/null +++ b/front/salix/components/summary/style.scss @@ -0,0 +1,63 @@ +@import "./variables"; + +.summary { + margin: 0 auto; + max-width: 950px; + + & > h5 { + padding: $spacing-sm; + border: none; + background: $color-main; + color: $color-font-dark; + margin: 0; + text-align: center; + line-height: 1.3em; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + & > vn-horizontal { + flex-wrap: wrap; + padding: $spacing-md; + overflow: hidden; + align-items: flex-start; + + h4 { + margin-bottom: $spacing-md; + text-transform: uppercase; + font-size: 15pt; + line-height: 1; + padding: 7px; + padding-bottom: 4px; /* Bottom line-height fix */ + font-weight: lighter; + background-color: $color-main-light; + border-bottom: .1em solid $color-main; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + & > * { + margin: $spacing-sm; + min-width: 14em; + padding: 0; + } + & > vn-auto { + width: 100%; + } + vn-label-value > section { + margin-bottom: .3em; + } + } + p:after { + content: ' '; + overflow: hidden; + display: block; + clear: both + } +} + +.vn-popup .summary { + border: none; + box-shadow: none; + margin: 0; +} diff --git a/front/salix/components/topbar/style.scss b/front/salix/components/topbar/style.scss new file mode 100644 index 000000000..d7a5173f6 --- /dev/null +++ b/front/salix/components/topbar/style.scss @@ -0,0 +1,9 @@ +@import "variables"; + +vn-topbar { + display: flex; + align-items: center; + color: $color-font-dark; + box-sizing: border-box; + background-color: $color-header; +} diff --git a/front/salix/components/topbar/topbar.html b/front/salix/components/topbar/topbar.html new file mode 100644 index 000000000..faeb0c65e --- /dev/null +++ b/front/salix/components/topbar/topbar.html @@ -0,0 +1,2 @@ +
    +
    \ No newline at end of file diff --git a/front/salix/components/topbar/topbar.js b/front/salix/components/topbar/topbar.js new file mode 100644 index 000000000..423b033ce --- /dev/null +++ b/front/salix/components/topbar/topbar.js @@ -0,0 +1 @@ +import './style.scss'; diff --git a/front/salix/components/user-popover/index.html b/front/salix/components/user-popover/index.html new file mode 100644 index 000000000..f34219d26 --- /dev/null +++ b/front/salix/components/user-popover/index.html @@ -0,0 +1,102 @@ + + + + + + +
    + +
    +
    +
    +
    + {{$root.user.nickname}} +
    +
    + {{::$root.user.name}} +
    +
    + + +
    + + My account + +
    +
    + + + + {{id}}: {{bank}} + + + + + + + + + +
    +
    \ No newline at end of file diff --git a/front/salix/components/user-popover/index.js b/front/salix/components/user-popover/index.js new file mode 100644 index 000000000..764b0cae9 --- /dev/null +++ b/front/salix/components/user-popover/index.js @@ -0,0 +1,95 @@ +import ngModule from '../../module'; +import './style.scss'; + +let languages = { + es: 'Español', + en: 'English', + ca: 'Català', + pt: 'Português', + fr: 'Français', + nl: 'Nederlands', + mn: 'Монгол хэл' +}; + +class Controller { + constructor($, $translate, vnConfig, vnAuth) { + Object.assign(this, { + $, + $translate, + vnConfig, + vnAuth, + lang: $translate.use(), + langs: [] + }); + + for (let code of $translate.getAvailableLanguageKeys()) { + this.langs.push({ + code: code, + name: languages[code] ? languages[code] : code + }); + } + + vnConfig.initialize(); + } + + set lang(value) { + this._lang = value; + this.$translate.use(value); + } + + get lang() { + return this._lang; + } + + set localBankFk(value) { + this.vnConfig.setLocal('bankFk', value); + } + + get localBankFk() { + return this.vnConfig.local.bankFk; + } + + set localWarehouseFk(value) { + this.vnConfig.setLocal('warehouseFk', value); + } + + get localWarehouseFk() { + return this.vnConfig.local.warehouseFk; + } + + set localCompanyFk(value) { + this.vnConfig.setLocal('companyFk', value); + } + + get localCompanyFk() { + return this.vnConfig.local.companyFk; + } + + set warehouseFk(value) { + this.vnConfig.setUser('warehouseFk', value); + } + + get warehouseFk() { + return this.vnConfig.user.warehouseFk; + } + + set companyFk(value) { + this.vnConfig.setUser('companyFk', value); + } + + get companyFk() { + return this.vnConfig.user.companyFk; + } + + show(event) { + this.$.warehouses.refresh(); + this.$.companies.refresh(); + this.$.popover.show(event.target); + } +} +Controller.$inject = ['$scope', '$translate', 'vnConfig', 'vnAuth']; + +ngModule.component('vnUserPopover', { + template: require('./index.html'), + controller: Controller +}); diff --git a/front/salix/components/user-popover/index.spec.js b/front/salix/components/user-popover/index.spec.js new file mode 100644 index 000000000..217471ca5 --- /dev/null +++ b/front/salix/components/user-popover/index.spec.js @@ -0,0 +1,61 @@ +import './index.js'; + +describe('Salix', () => { + describe('Component vnUserPopover', () => { + let controller; + let $scope; + + beforeEach(ngModule('salix')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, $httpBackend) => { + $httpBackend.expectGET('UserConfigs/getUserConfig'); + + $scope = $rootScope.$new(); + controller = $componentController('vnUserPopover', {$scope}); + })); + + afterEach(() => { + $scope.$destroy(); + }); + + describe('localBankFk() setter', () => { + it('should set local bank', () => { + controller.localBankFk = 4; + + expect(controller.localBankFk).toBe(4); + }); + }); + + describe('localWarehouseFk() setter', () => { + it('should set local warehouse', () => { + controller.localWarehouseFk = 4; + + expect(controller.localWarehouseFk).toBe(4); + }); + }); + + describe('localCompanyFk() setter', () => { + it('should set local company', () => { + controller.localCompanyFk = 4; + + expect(controller.localCompanyFk).toBe(4); + }); + }); + + describe('warehouseFk() setter', () => { + it('should set user warehouse', () => { + controller.warehouseFk = 4; + + expect(controller.warehouseFk).toBe(4); + }); + }); + + describe('companyFk() setter', () => { + it('should set user company', () => { + controller.companyFk = 4; + + expect(controller.companyFk).toBe(4); + }); + }); + }); +}); diff --git a/front/salix/components/user-popover/locale/es.yml b/front/salix/components/user-popover/locale/es.yml new file mode 100644 index 000000000..7518a98bc --- /dev/null +++ b/front/salix/components/user-popover/locale/es.yml @@ -0,0 +1,6 @@ +My account: Mi cuenta +Local warehouse: Almacén local +Local bank: Banco local +Local company: Empresa local +User warehouse: Almacén del usuario +User company: Empresa del usuario \ No newline at end of file diff --git a/front/salix/components/user-popover/style.scss b/front/salix/components/user-popover/style.scss new file mode 100644 index 000000000..c8325c9f6 --- /dev/null +++ b/front/salix/components/user-popover/style.scss @@ -0,0 +1,37 @@ +@import "variables"; + +.vn-popover .user-popover { + width: 16em; + + & > .profile-card { + display: flex; + align-items: center; + + & > vn-icon { + font-size: 80px; + color: $color-font-bg-marginal; + } + & > div { + display: flex; + flex-direction: column; + justify-content: space-between; + flex: 1; + + & > div { + display: flex; + padding-bottom: .5em; + + & > .user { + flex: 1; + max-width: 8em; + } + } + } + } +} +#logout { + float: right; + height: initial; + vertical-align: middle; + font-size: 1em; +} \ No newline at end of file diff --git a/services/loopback/favicon.ico b/front/salix/favicon.ico similarity index 100% rename from services/loopback/favicon.ico rename to front/salix/favicon.ico diff --git a/front/salix/index.ejs b/front/salix/index.ejs new file mode 100644 index 000000000..3aed9d9a6 --- /dev/null +++ b/front/salix/index.ejs @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + diff --git a/front/salix/index.js b/front/salix/index.js new file mode 100644 index 000000000..5220f36f6 --- /dev/null +++ b/front/salix/index.js @@ -0,0 +1,5 @@ +import './module'; +import './routes'; +import './components'; +import './services'; +import './styles'; diff --git a/front/salix/locale/en.yml b/front/salix/locale/en.yml new file mode 100644 index 000000000..749ffb2f3 --- /dev/null +++ b/front/salix/locale/en.yml @@ -0,0 +1,12 @@ +Applications: Applications +Home: Home +Notifications: Notifications +Logout: Logout +Language: Language +Change language: Change language +Profile: Profile +Data saved!: Data saved! +Push on applications menu: To open a module push on applications menu +Clients: Clients +Modules access: Modules access +Return to home: Return to home \ No newline at end of file diff --git a/front/salix/locale/es.yml b/front/salix/locale/es.yml new file mode 100644 index 000000000..2f65ab255 --- /dev/null +++ b/front/salix/locale/es.yml @@ -0,0 +1,56 @@ +Applications: Aplicaciones +Account: Cuenta +Language: Idioma +Change language: Cambiar idioma +Data saved!: ¡Datos guardados! +Home: Inicio +Logout: Cerrar sesión +Modules access : Acceso a módulos +Return to home: Volver a inicio +Notifications: Notificaciones +Name: Nombre +Preview: Vista previa +Profile: Perfil +Push on applications menu: Para abrir un módulo pulsa en el menú de aplicaciones +Return to module index: Volver a la página principal del módulo +What is new: Novedades de la versión +Settings: Ajustes + +# Actions + +Back: Volver +Save: Guardar +Create: Crear +Send: Enviar +Delete: Eliminar +Order by: Ordenar por +Order: Orden +Ascendant: Ascendente +Descendant: Descendente +Add: Añadir +Remove: Quitar + +# Modules + +Agencies: Agencias +Claims: Reclamaciones +Clients: Clientes +Items: Artículos +Orders: Cesta +Tickets: Tickets +Travels: Envíos +Workers: Trabajadores +Routes: Rutas +Locator: Localizador +Invoices out: Facturas emitidas + +# Common + +Summary: Vista previa +Basic data: Datos básicos +List: Listado + +# Misc + +Phone: Teléfono +Id: Id diff --git a/front/salix/manifest.json b/front/salix/manifest.json new file mode 100644 index 000000000..29deedbcd --- /dev/null +++ b/front/salix/manifest.json @@ -0,0 +1,12 @@ +{ + "name": "Salix", + "start_url": "index.html", + "display": "standalone", + "theme_color": "#3d3d3d", + "icons": [ + { + "src": "favicon.ico", + "sizes": "512x512" + } + ] +} diff --git a/front/salix/module.js b/front/salix/module.js new file mode 100644 index 000000000..2354e0dff --- /dev/null +++ b/front/salix/module.js @@ -0,0 +1,129 @@ +import {ng} from 'core/vendor'; +import 'core'; + +export const appName = 'salix'; + +const ngModule = ng.module('salix', ['vnCore']); +export default ngModule; + +run.$inject = ['$window', '$rootScope', 'vnAuth', 'vnApp', '$state']; +export function run($window, $rootScope, vnAuth, vnApp, $state) { + $window.validations = {}; + vnApp.name = appName; + + vnAuth.initialize(); + + $rootScope.$on('$viewContentLoaded', () => {}); + window.myAppErrorLog = []; + $state.defaultErrorHandler(function(error) { + if (error.type === 3) // ABORTED_TRANSITION + window.myAppErrorLog.push(error); + }); + + if ($window.routes) { + let keybindings = {}; + + for (const mod of $window.routes) { + if (!mod || !mod.keybindings) + continue; + + for (const binding of mod.keybindings) { + let err; + if (!binding.key) + err = `Missing attribute 'key' in binding`; + else if (!binding.state) + err = `Missing attribute 'state' in binding`; + else if (keybindings[binding.key]) + err = `Binding key redeclared`; + + if (err) + console.warn(`${err}: ${mod.module}: ${JSON.stringify(binding)}`); + else + keybindings[binding.key] = binding.state; + } + } + + $window.addEventListener('keyup', function(event) { + if (event.defaultPrevented || !event.altKey || !event.ctrlKey) + return; + + let state = keybindings[event.key]; + if (state) { + $state.go(state); + event.preventDefault(); + } + }); + } +} +ngModule.run(run); + +config.$inject = ['$translatePartialLoaderProvider', '$httpProvider', '$compileProvider']; +export function config($translatePartialLoaderProvider, $httpProvider, $compileProvider) { + $translatePartialLoaderProvider.addPart(appName); + $httpProvider.interceptors.push('vnInterceptor'); + + $compileProvider + .debugInfoEnabled(false) + .commentDirectivesEnabled(false) + .cssClassDirectivesEnabled(false); +} +ngModule.config(config); + +// Unhandled exceptions + +$exceptionHandler.$inject = ['vnApp', '$window', '$state', '$injector']; +function $exceptionHandler(vnApp, $window, $state, $injector) { + return function(exception, cause) { + let message; + let messageT; + let $translate = $injector.get('$translate'); + + if (exception.name == 'HttpError') { + switch (exception.xhrStatus) { + case 'timeout': + case 'abort': + return; + } + + switch (exception.status) { + case 401: + if ($state.current.name != 'login') { + messageT = 'Session has expired'; + let params = {continue: $window.location.hash}; + $state.go('login', params); + } else + messageT = 'Invalid login'; + break; + case 403: + messageT = 'Access denied'; + break; + case 502: + messageT = 'It seems that the server has fall down'; + break; + case -1: + messageT = 'Could not contact the server'; + break; + } + + if (!messageT) { + let data = exception.data; + + if (data && data.error instanceof Object) + message = data.error.message; + else + message = exception.statusText; + } + } else if (exception.name == 'UserError') + messageT = exception.message; + else { + vnApp.showError('Ups! Something went wrong'); + console.error(exception); + throw exception; + } + + if (messageT) + message = $translate.instant(messageT); + vnApp.showError(message); + }; +} +ngModule.factory('$exceptionHandler', $exceptionHandler); diff --git a/front/salix/routes.js b/front/salix/routes.js new file mode 100644 index 000000000..600907ff1 --- /dev/null +++ b/front/salix/routes.js @@ -0,0 +1,75 @@ +import ngModule from './module'; +import getMainRoute from 'core/lib/get-main-route'; + +config.$inject = ['$stateProvider', '$urlRouterProvider']; +function config($stateProvider, $urlRouterProvider) { + $urlRouterProvider.otherwise('/'); + + $stateProvider + .state('login', { + url: '/login?continue', + description: 'Login', + views: { + login: {template: ''} + } + }) + .state('home', { + url: '/', + description: 'Home', + template: '' + }); + + for (let file in window.routes) { + let routeFile = window.routes[file]; + let fileRoutes = routeFile.routes; + let moduleName = routeFile.module; + let validations = routeFile.validations || false; + let mainModule = getMainRoute(fileRoutes); + + if (!mainModule) continue; + + for (let route of fileRoutes) { + let configRoute = { + url: route.url, + template: `<${route.component} ${getParams(route)}>`, + description: route.description, + reloadOnSearch: false, + resolve: { + loader: loader(moduleName, validations) + }, + data: { + moduleIndex: file, + acl: route.acl + } + }; + if (route.abstract) + configRoute.abstract = true; + if (route.routeParams) + configRoute.params = route.routeParams; + + $stateProvider.state(route.state, configRoute); + } + } + + function getParams(route) { + let params = ''; + let temporalParams = []; + + if (!route.params) + return params; + + Object.keys(route.params).forEach(key => { + temporalParams.push(`${key} = "${route.params[key]}"`); + }); + return temporalParams.join(' '); + } + + function loader(moduleName) { + load.$inject = ['vnModuleLoader']; + function load(moduleLoader) { + return moduleLoader.load(moduleName); + } + return load; + } +} +ngModule.config(config); diff --git a/client/route/src/card/style.css b/front/salix/services/index.js similarity index 100% rename from client/route/src/card/style.css rename to front/salix/services/index.js diff --git a/front/salix/styles/index.js b/front/salix/styles/index.js new file mode 100644 index 000000000..5ea238d2b --- /dev/null +++ b/front/salix/styles/index.js @@ -0,0 +1,4 @@ +import './misc.scss'; +import './modal-form.scss'; +import './order-product.scss'; +import './photo-list.scss'; diff --git a/front/salix/styles/misc.scss b/front/salix/styles/misc.scss new file mode 100644 index 000000000..1f2d79981 --- /dev/null +++ b/front/salix/styles/misc.scss @@ -0,0 +1,146 @@ +@import "./variables"; +@import "./effects"; + +form vn-horizontal { + align-items: center; + min-height: 2.8em; + + & > * { + box-sizing: border-box; + margin: 0 $spacing-xs; + + &:first-child { + margin-left: 0; + margin-right: $spacing-sm; + } + &:last-child { + margin-left: $spacing-sm; + margin-right: 0; + } + &:first-child:last-child { + margin: 0; + } + } + + @media screen and (max-width: $mobile-width) { + flex-direction: column; + align-items: initial; + + & > * { + &, + &:first-child, + &:last-child { + margin: 0; + } + } + } +} + +.link { + color: $color-font-link; +} +.link { + cursor: pointer; + + &:hover { + text-decoration: underline; + } +} +.unselectable { + -moz-user-select: none; + -webkit-user-select: none; + -ms-user-select: none; + user-select: none; +} +vn-bg-title { + display: block; + text-align: center; + padding: 1em; + color: gray; + font-size: 1.3em; +} +.totalBox { + border: 1px solid #CCC; + text-align: right; + justify-content: center; + align-items: center; + padding: $spacing-md; + max-width: 14em; +} +.form { + height: 100%; + box-sizing: border-box; + padding: $spacing-lg; + max-width: 1000px; +} +html [fixed-bottom-right] { + position: fixed; + bottom: 2em; + right: 2em; +} +.list > vn-none { + min-width: 60px; +} +.list-element { + padding: 8px 0 0 0; + border-bottom: 1px solid $color-spacer; + + i { + color: $color-main; + } +} +html [pointer], .pointer{ + cursor: pointer; +} +html [noDrop], .noDrop{ + cursor: no-drop; +} +vn-button-bar { + display: block; + margin-top: $spacing-sm; +} +vn-tool-bar { + display: flex; + + & > * { + margin-right: .6em; + } +} +html [scrollable] { + min-height: 1px; + flex: 1; + flex-basis: 0.000000001px; +} +.ellipsize { + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; +} +.counter { + @extend %active; + + &.small { + font-size: 0.7em + } +} + +/* XXX: Deprecated, use classes with text prefix */ + +[color-main] { + color: $color-main; +} +[color-marginal] { + color: $color-marginal; +} +[uppercase], .uppercase { + text-transform: uppercase; +} +html [text-center] { + text-align: center; +} +html [text-right] { + text-align: right; +} +html [text-left] { + text-align: left; +} diff --git a/front/salix/styles/modal-form.scss b/front/salix/styles/modal-form.scss new file mode 100644 index 000000000..0f728178d --- /dev/null +++ b/front/salix/styles/modal-form.scss @@ -0,0 +1,34 @@ +@import './variables'; + +vn-dialog.modal-form { + vn-horizontal.header { + padding: $spacing-sm; + background-color: $color-main; + + h5 { + color: white; + margin: 0 auto; + } + } + table { + width: 100% + } + & > div { + padding: 0 !important; + } + .vn-textfield { + width: 100%; + } + .buttons { + margin-top: 0 !important; + } + p { + display: none; + } + button.close > vn-icon { + color: white !important; + } + vn-ticket-sale-edit-discount > div { + padding-bottom: 0 !important; + } +} \ No newline at end of file diff --git a/front/salix/styles/order-product.scss b/front/salix/styles/order-product.scss new file mode 100644 index 000000000..df14f5558 --- /dev/null +++ b/front/salix/styles/order-product.scss @@ -0,0 +1,95 @@ +@import "./variables"; + +.catalog-list { + align-items: flex-start; + flex-wrap: wrap; + justify-content: center; + + & > .product { + box-sizing: border-box; + padding: $spacing-sm; + width: 28em; + overflow: hidden; + + & > vn-card { + display: flex; + height: 12em; + + .image { + width: 12em; + height: 12em; + + img { + width: 100%; + height: 100%; + } + } + .description { + flex: 1; + display: flex; + flex-direction: column; + box-sizing: border-box; + height: 100%; + width: 100%; + overflow: hidden; + padding: .8em; + + & > h3 { + font-family: vn-font; + margin: 0; + margin-bottom: .3em; + font-weight: normal; + line-height: initial; + font-size: 1.05em; + max-height:2.4em; + overflow: hidden; + } + & > h4 { + color: $color-font-secondary; + text-transform: uppercase; + margin-bottom: .3em; + line-height: initial; + font-size: 1em; + flex: 1; + } + & > .tags { + padding-bottom: .2em; + height: 3em; + + & > vn-label-value { + font-size: .8em; + } + } + } + .footer { + font-size: .8em; + + & > .price { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + display: flex; + align-items: center; + justify-content: space-between; + + & > span { + flex: 1; + + &:first-child, + &:last-child { + font-size: 1.4em; + } + } + + & > vn-icon-button { + padding: 0; + } + } + & > .priceKg { + color: $color-font-secondary; + font-size: .8em; + } + } + } + } +} diff --git a/front/salix/styles/photo-list.scss b/front/salix/styles/photo-list.scss new file mode 100644 index 000000000..3737c508a --- /dev/null +++ b/front/salix/styles/photo-list.scss @@ -0,0 +1,40 @@ +@import "./variables"; + +.photo-list { + justify-content: center; + align-items: flex-start; + align-content: flex-start; + flex-wrap: wrap; + + .photo { + box-sizing: border-box; + transition: all 0.5s; + padding: $spacing-sm; + position: relative; + opacity: 0.7; + width: 28em; + + .image { + box-shadow: 0 2px 2px 0 rgba(0,0,0,.14), + 0 3px 1px -2px rgba(0,0,0,.2), + 0 1px 5px 0 rgba(0,0,0,.12); + background: no-repeat center center fixed; + background-size: cover !important; + overflow: hidden; + cursor: zoom-in; + height: 100%; + + img { + max-width: 100% + } + } + .actions { + position: absolute; + right: 1em; + top: 1em + } + } + .photo:hover { + opacity: 1 + } +} \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js index 1b4578c86..4036bb993 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,12 +1,11 @@ require('require-yaml'); const gulp = require('gulp'); -const runSequence = require('run-sequence'); -const fs = require('fs-extra'); const exec = require('child_process').exec; const PluginError = require('plugin-error'); const argv = require('minimist')(process.argv.slice(2)); const log = require('fancy-log'); -const environment = require('gulp-env'); +const request = require('request'); +const e2eConfig = require('./e2e/helpers/config.js'); // Configuration @@ -15,383 +14,380 @@ let isWindows = /^win/.test(process.platform); if (argv.NODE_ENV) process.env.NODE_ENV = argv.NODE_ENV; -let env = process.env.NODE_ENV ? process.env.NODE_ENV : 'development'; - let langs = ['es', 'en']; -let srcDir = './client'; -let servicesDir = './services'; +let srcDir = './front'; +let modulesDir = './modules'; +let buildDir = 'dist'; +let containerId = 'salix-db'; -let wpConfig = require('./webpack.config.yml'); -let buildDir = wpConfig.buildDir; -let devServerPort = wpConfig.devServerPort; +let dataSources = require('./loopback/server/datasources.json'); +let dbConf = dataSources.vn; -let nginxDir = `${servicesDir}/nginx`; -let proxyConf = require(`${nginxDir}/config.yml`); -let proxyEnvFile = `${nginxDir}/config.${env}.yml`; - -if (fs.existsSync(proxyEnvFile)) - Object.assign(proxyConf, require(proxyEnvFile)); - -let defaultService = proxyConf.main; -let defaultPort = proxyConf.defaultPort; +let backSources = [ + '!node_modules', + 'loopback', + 'modules/*/back/**', + 'modules/*/back/*', + 'back', + 'print' +]; // Development -gulp.task('default', () => { - return gulp.start('environment', 'services', 'client'); -}); +const localesRoutes = gulp.parallel(locales, routes); +localesRoutes.description = `Builds locales and routes`; -gulp.task('environment', async () => { - await environment({ - file: '.env.json' +const front = gulp.series(clean, gulp.parallel(localesRoutes, watch, webpackDevServer)); +front.description = `Starts frontend service`; + +function backOnly(done) { + let app = require(`./loopback/server/server`); + app.start(); + app.on('started', done); +} +backOnly.description = `Starts backend service`; + +function backWatch(done) { + const nodemon = require('gulp-nodemon'); + + // XXX: Workaround to avoid nodemon bug + // https://github.com/remy/nodemon/issues/1346 + let commands = ['node --inspect ./node_modules/gulp/bin/gulp.js']; + if (!isWindows) commands.unshift('sleep 1'); + + nodemon({ + exec: commands.join(' && '), + ext: 'js html css json', + args: ['backOnly'], + watch: backSources, + done: done }); -}); +} +backWatch.description = `Starts backend in waching mode`; -gulp.task('client', ['build-clean'], async () => { - await runSequenceP(['routes', 'locales'], 'watch', 'webpack-dev-server'); -}); +const back = gulp.series(dockerStart, backWatch); +back.description = `Starts backend and database service`; -/** - * Starts all backend services, including the nginx proxy and the database. - */ -gulp.task('services', async () => { - await runSequenceP('environment', 'docker-start', 'services-only', 'nginx'); -}); +const defaultTask = gulp.parallel(front, back); +defaultTask.description = `Starts all application services`; -/** - * Starts backend services. - */ -gulp.task('services-only', async () => { - const services = await getServices(); - for (let service of services) - require(service.index).start(service.port); -}); +// Backend tests -/** - * Runs the e2e tests, restoring the fixtures first. - */ -gulp.task('e2e', ['docker'], async () => { - await runSequenceP('e2e-only'); -}); +async function backTestOnce() { + let bootOptions; -gulp.task('smokes', ['docker'], async () => { - await runSequenceP('smokes-only'); -}); + if (argv['random']) + bootOptions = {dataSources}; + + let app = require(`./loopback/server/server`); + app.boot(bootOptions); + + await new Promise((resolve, reject) => { + const jasmine = require('gulp-jasmine'); + + let options = {errorOnFail: false}; + + if (argv.junit) { + const reporters = require('jasmine-reporters'); + options.reporter = new reporters.JUnitXmlReporter(); + } + + let backSpecFiles = [ + 'back/**/*.spec.js', + 'loopback/**/*.spec.js', + 'modules/*/back/**/*.spec.js' + ]; + + gulp.src(backSpecFiles) + .pipe(jasmine(options)) + .on('end', resolve) + .on('error', reject) + .resume(); + }); + + await app.disconnect(); +} +backTestOnce.description = `Runs the backend tests once, can receive --junit arg to save reports on a xml file`; + +async function backTestDockerOnce() { + let containerId = await docker(); + let err; + + try { + await backTestOnce(); + } catch (e) { + err = e; + } + + if (argv['random']) + await execP(`docker rm -fv ${containerId}`); + if (err) throw err; +} +backTestDockerOnce.description = `Runs backend tests using in site container once`; + +async function backTestDocker() { + let containerId = await docker(); + let err; + + try { + await backTest(); + } catch (e) { + err = e; + } + + if (argv['random']) + await execP(`docker rm -fv ${containerId}`); + if (err) throw err; +} +backTestDocker.description = `Runs backend tests restoring fixtures first`; + +function backTest(done) { + const nodemon = require('gulp-nodemon'); + + nodemon({ + exec: ['node ./node_modules/gulp/bin/gulp.js'], + args: ['backTestOnce'], + watch: backSources, + done: done + }); +} +backTest.description = `Watches for changes in modules to execute backTest task`; + +// End to end tests + +function e2eOnly() { + require('@babel/register')({presets: ['@babel/preset-env']}); + require('@babel/polyfill'); -/** - * Runs the e2e tests. - */ -gulp.task('e2e-only', () => { const jasmine = require('gulp-jasmine'); - return gulp.src('./e2e_tests.js') - .pipe(jasmine({reporter: 'none'})); -}); + const SpecReporter = require('jasmine-spec-reporter').SpecReporter; + const createNightmare = require('./e2e/helpers/nightmare'); -gulp.task('smokes-only', () => { + if (argv.show || argv.s) + process.env.E2E_SHOW = true; + process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = true; + + + const specFiles = [ + `${__dirname}/e2e/paths/01*/*[sS]pec.js`, + `${__dirname}/e2e/paths/02*/*[sS]pec.js`, + `${__dirname}/e2e/paths/03*/*[sS]pec.js`, + `${__dirname}/e2e/paths/04*/*[sS]pec.js`, + `${__dirname}/e2e/paths/05*/*[sS]pec.js`, + `${__dirname}/e2e/paths/06*/*[sS]pec.js`, + `${__dirname}/e2e/paths/07*/*[sS]pec.js`, + `${__dirname}/e2e/paths/08*/*[sS]pec.js`, + `${__dirname}/e2e/paths/09*/*[sS]pec.js`, + `${__dirname}/e2e/paths/**/*[sS]pec.js`, + `${__dirname}/e2e/helpers/extensions.js` + ]; + + return gulp.src(specFiles).pipe(jasmine({ + errorOnFail: false, + timeout: 10000, + reporter: [ + new SpecReporter({ + spec: { + displayStacktrace: 'summary', + displaySuccessful: true, + displayFailedSpec: true, + displaySpecDuration: true, + } + }) + ] + }) + .on('jasmineDone', function() { + const nightmare = createNightmare(); + nightmare.end(() => {}); + }) + ); +} +e2eOnly.description = `Runs the e2e tests only`; + +async function backendStatus() { + const milliseconds = 250; + return new Promise(resolve => { + let timer; + let attempts = 1; + timer = setInterval(() => { + const url = `${e2eConfig.url}/api/Applications/status`; + request.get(url, (err, res) => { + if (err || attempts > 100) // 250ms * 100 => 25s timeout + throw new Error('Could not connect to backend'); + else if (res && res.body == 'true') { + clearInterval(timer); + resolve(attempts); + } else + attempts++; + }); + }, milliseconds); + }); +} +backendStatus.description = `Performs a simple requests to check the backend status`; + +e2e = gulp.series(docker, async function isBackendReady() { + const attempts = await backendStatus(); + log(`Backend ready after ${attempts} attempt(s)`); + + return attempts; +}, e2eOnly); +e2e.description = `Restarts database and runs the e2e tests`; + +function smokesOnly() { const jasmine = require('gulp-jasmine'); - return gulp.src('./smokes_tests.js') - .pipe(jasmine({reporter: 'none'})); -}); + return gulp.src('./e2e/smokes-tests.js') + .pipe(jasmine({reporter: 'none'})); +} +smokesOnly.description = `Runs the smokes tests only`; -/** - * Runs the backend tests. - */ -// gulp.task('test', ['test-only'], async () => { -// gulp.watch('./services/**/*', ['test-only']); -// gulp.unwatch('./services/node_modules'); -// }); +smokes = gulp.series(docker, smokesOnly); +smokes.description = `Restarts database and runs the smokes tests`; -// gulp.task('test-only', () => { -// const jasmine = require('gulp-jasmine'); -// gulp.src('./services/loopback/common/**/*[sS]pec.js') -// .pipe(jasmine( -// require('./services-test.config') -// )); -// }); - -/** - * Cleans all generated project files. - */ -gulp.task('clean', ['build-clean', 'nginx-clean']); - -/** - * Alias for the 'install' task. - */ -gulp.task('i', ['install']); - -/** - * Installs node dependencies in all project directories. - */ -gulp.task('install', () => { +function install() { const install = require('gulp-install'); const print = require('gulp-print'); - let packageFiles = []; - let services = fs.readdirSync(servicesDir); - services.push('..'); - services.forEach(service => { - packageFiles.push(`${servicesDir}/${service}/package.json`); - }); + let npmArgs = []; + if (argv.ci) npmArgs = ['--no-audit', '--prefer-offline']; + + let packageFiles = ['front/package.json', 'print/package.json']; return gulp.src(packageFiles) .pipe(print(filepath => { return `Installing packages in ${filepath}`; })) - .pipe(install({ - npm: ['--no-package-lock'] - })); -}); + .pipe(install({npm: npmArgs})); +} +install.description = `Installs node dependencies in all directories`; + +const i = gulp.series(install); +i.description = `Alias for the 'install' task`; // Deployment -gulp.task('build', ['clean'], async () => { - await runSequenceP(['environment', 'routes', 'locales', 'webpack', 'docker-compose', 'nginx-conf']); -}); +const build = gulp.series(clean, gulp.parallel(localesRoutes, webpack)); +build.description = `Generates binaries and configuration files`; -gulp.task('docker-compose', async () => { - const yaml = require('js-yaml'); - - let compose = await fs.readFile('./docker-compose.tpl.yml', 'utf8'); - let composeYml = yaml.safeLoad(compose); - let services = await getServices(); - - for (let service of services) { - let dockerFile = `${__dirname}/services/${service.name}/Dockerfile`; - - // if (await fs.exists(`./services/${service.name}/Dockerfile`)) - // dockerFile = 'Dockerfile'; - - composeYml.services[service.name] = { - environment: [ - 'NODE_ENV=${NODE_ENV}', - 'salixHost=${salixHost}', - 'salixPort=${salixPort}', - 'salixUser=${salixUser}', - 'salixPassword=${salixPassword}' - ], - container_name: `\${BRANCH_NAME}-${service.name}`, - image: `${service.name}:\${TAG}`, - build: { - context: `./services`, - dockerfile: dockerFile - }, - ports: [`${service.port}:${defaultPort}`] - }; - composeYml.services.nginx.links.push( - `${service.name}:\${BRANCH_NAME}-${service.name}` - ); - } - - let ymlString = yaml.safeDump(composeYml); - await fs.writeFile('./docker-compose.yml', ymlString); -}); - -/** - * Cleans all files generated by the 'build' task. - */ -gulp.task('build-clean', () => { +function clean() { const del = require('del'); const files = [ - `${buildDir}/*`, - `!${buildDir}/templates`, - `!${buildDir}/images`, - `docker-compose.yml` + `${buildDir}/*` ]; return del(files, {force: true}); -}); - -// Nginx & services - -let nginxConf = 'temp/nginx.conf'; -let nginxTemp = `${nginxDir}/temp`; - -/** - * Starts the nginx process, if it is started, restarts it. - */ -gulp.task('nginx', async () => { - await runSequenceP('nginx-stop', 'nginx-start'); -}); - -/** - * Starts the nginx process, generating it's configuration file first. - */ -gulp.task('nginx-start', ['nginx-conf'], async () => { - let nginxBin = await nginxGetBin(); - - if (isWindows) - nginxBin = `start /B ${nginxBin}`; - - log(`Application will be available at http://${proxyConf.host}:${proxyConf.port}/`); - await execP(`${nginxBin} -c "${nginxConf}" -p "${nginxDir}"`); -}); - -/** - * Stops the nginx process. - */ -gulp.task('nginx-stop', async () => { - try { - let nginxBin = await nginxGetBin(); - await fs.stat(`${nginxTemp}/nginx.pid`); - await execP(`${nginxBin} -c "${nginxConf}" -p "${nginxDir}" -s stop`); - } catch (e) {} -}); - -/** - * Generates the nginx configuration file. If NODE_ENV is defined and the - * 'nginx.[environment].mst' file exists, it is used as a template, otherwise, - * the 'nginx.mst' template file is used. - */ -gulp.task('nginx-conf', ['nginx-stop'], async () => { - const mustache = require('mustache'); - - if (!await fs.exists(nginxTemp)) - await fs.mkdir(nginxTemp); - - let params = { - services: await getServices(), - defaultService: defaultService, - defaultPort: defaultPort, - devServerPort: devServerPort, - port: proxyConf.port, - host: proxyConf.host - }; - - let confFile = `${nginxDir}/nginx.${env}.mst`; - - if (!await fs.exists(confFile)) - confFile = `${nginxDir}/nginx.mst`; - - let template = await fs.readFile(confFile, 'utf8'); - let nginxConf = mustache.render(template, params); - - await fs.writeFile(`${nginxTemp}/nginx.conf`, nginxConf); -}); - -/** - * Cleans all files generated by nginx. - */ -gulp.task('nginx-clean', ['nginx-stop'], () => { - const del = require('del'); - return del([`${nginxTemp}/*`], {force: true}); -}); - -async function nginxGetBin() { - if (isWindows) - return 'nginx'; - try { - let nginxBin = '/usr/sbin/nginx'; - await fs.stat(nginxBin); - return nginxBin; - } catch (e) { - return 'nginx'; - } -} - -async function getServices() { - let services; - let startPort = defaultPort + 1; - services = []; - - const serviceDirs = await fs.readdir(servicesDir); - const exclude = ['loopback']; - - for (let service of serviceDirs) { - let index = `${servicesDir}/${service}/server/server.js`; - if (!await fs.exists(index) || exclude.indexOf(service) !== -1) continue; - - let port = service == defaultService ? defaultPort : startPort++; - services.push({ - name: service, - index: index, - port: port - }); - } - - return services; } +clean.description = `Cleans all files generated by the 'build' task`; // Webpack -gulp.task('webpack', function(callback) { - const webpack = require('webpack'); +function webpack(done) { + const webpackCompile = require('webpack'); + const merge = require('webpack-merge'); - const webpackConfig = require('./webpack.config.js'); - let configCopy = Object.create(webpackConfig); - let compiler = webpack(configCopy); + let wpConfig = require('./webpack.config.js'); + wpConfig = merge(wpConfig, {}); + + let compiler = webpackCompile(wpConfig); compiler.run(function(err, stats) { if (err) throw new PluginError('webpack', err); - log('[webpack]', stats.toString({colors: true})); - callback(); + log('[webpack]', stats.toString(wpConfig.stats)); + done(); }); -}); +} +webpack.description = `Transpiles application into files`; -gulp.task('webpack-dev-server', function() { - const WebpackDevServer = require('webpack-dev-server'); +function webpackDevServer(done) { const webpack = require('webpack'); + const merge = require('webpack-merge'); + const WebpackDevServer = require('webpack-dev-server'); - const webpackConfig = require('./webpack.config.js'); - let configCopy = Object.create(webpackConfig); + let wpConfig = require('./webpack.config.js'); + wpConfig = merge(wpConfig, {}); - for (let entry in configCopy.entry) { - configCopy.entry[entry] - .unshift(`webpack-dev-server/client?http://127.0.0.1:${devServerPort}/`); + let devServer = wpConfig.devServer; + + for (let entryName in wpConfig.entry) { + let entry = wpConfig.entry[entryName]; + if (!Array.isArray(entry)) + entry = [entry]; + + let wdsAssets = [ + `webpack-dev-server/client?http://localhost:${devServer.port}/`, + `webpack/hot/dev-server` + ]; + wpConfig.entry[entryName] = wdsAssets.concat(entry); } - let compiler = webpack(configCopy); - new WebpackDevServer(compiler, { - publicPath: '/', - contentBase: buildDir, - quiet: false, - noInfo: false, - // hot: true, - stats: { - assets: true, - colors: true, - version: false, - hash: false, - timings: true, - chunks: false, - chunkModules: false - } - }).listen(devServerPort, '127.0.0.1', function(err) { - if (err) throw new PluginError('webpack-dev-server', err); - }); -}); + let compiler = webpack(wpConfig); + new WebpackDevServer(compiler, wpConfig.devServer) + .listen(devServer.port, devServer.host, function(err) { + if (err) throw new PluginError('webpack-dev-server', err); + // XXX: Keep the server alive or continue? + done(); + }); +} +webpackDevServer.description = `Transpiles application into memory`; // Locale -let localeFiles = `${srcDir}/**/locale/*.yml`; +let localeFiles = [ + `${srcDir}/**/locale/*.yml`, + `${modulesDir}/*/front/**/locale/*.yml` +]; /** * Mixes all locale files into one JSON file per module and language. It looks * recursively in all project directories for locale folders with per language * yaml translation files. + * + * @return {Stream} The merged gulp streams */ -gulp.task('locales', function() { - const extend = require('gulp-extend'); +function locales() { + const mergeJson = require('gulp-merge-json'); + const gulpFile = require('gulp-file'); const yaml = require('gulp-yaml'); const merge = require('merge-stream'); - const modules = require('./client/modules.yml'); + const fs = require('fs-extra'); let streams = []; + let localePaths = []; - for (let mod in modules) + let modules = fs.readdirSync(modulesDir); + for (let mod of modules) + localePaths[mod] = `${modulesDir}/${mod}`; + + let baseMods = ['core', 'salix']; + for (let mod of baseMods) + localePaths[mod] = `${srcDir}/${mod}`; + + for (let mod in localePaths) { + let path = localePaths[mod]; for (let lang of langs) { - let localeFiles = `./client/${mod}/**/locale/${lang}.yml`; + let localeFiles = `${path}/**/locale/${lang}.yml`; streams.push(gulp.src(localeFiles) .pipe(yaml()) - .pipe(extend(`${lang}.json`)) + .pipe(mergeJson({fileName: `${lang}.json`})) .pipe(gulp.dest(`${buildDir}/locale/${mod}`))); } + } + + for (let mod in localePaths) { + for (let lang of langs) { + let file = `${buildDir}/locale/${mod}/${lang}.json`; + if (fs.existsSync(file)) continue; + streams.push(gulpFile('en.json', '{}', {src: true}) + .pipe(gulp.dest(`${buildDir}/locale/${mod}`))); + } + } return merge(streams); -}); +} +locales.description = `Generates client locale files`; // Routes -let routeFiles = `${srcDir}/**/routes.json`; +let routeFiles = `${modulesDir}/*/front/routes.json`; -gulp.task('routes', function() { +function routes() { const concat = require('gulp-concat'); const wrap = require('gulp-wrap'); @@ -399,115 +395,146 @@ gulp.task('routes', function() { .pipe(concat('routes.js', {newLine: ','})) .pipe(wrap('var routes = [<%=contents%>\n];')) .pipe(gulp.dest(buildDir)); -}); +} +routes.description = 'Merges all module routes file into one file'; // Watch -gulp.task('watch', function() { - gulp.watch(routeFiles, ['routes']); - gulp.watch(localeFiles, ['locales']); -}); +function watch(done) { + gulp.watch(routeFiles, gulp.series(routes)); + gulp.watch(localeFiles, gulp.series(locales)); + done(); +} +watch.description = `Watches for changes in routes and locale files`; // Docker /** - * Rebuilds the docker and it's image, if these already exist, destroys and - * rebuilds them. + * Builds the database image and runs a container. It only rebuilds the + * image when fixtures have been modified or when the day on which the + * image was built is different to today. Some workarounds have been used + * to avoid a bug with OverlayFS driver on MacOS. */ -gulp.task('docker', async () => { - try { - await execP('docker rm -f dblocal'); - } catch (e) {} - try { - await execP('docker rmi dblocal:latest'); - } catch (e) {} +async function docker() { + let d = new Date(); + let pad = v => v < 10 ? '0' + v : v; + let stamp = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; + await execP(`docker build --build-arg STAMP=${stamp} -t salix-db ./db`); - await runSequenceP('docker-run'); -}); + let dockerArgs = `--name ${containerId} -p 3306:${dbConf.port}`; + + if (argv['random']) + dockerArgs = '-p 3306'; + else { + try { + await execP(`docker rm -fv ${containerId}`); + } catch (e) {} + } + + let runChown = process.platform != 'linux'; + if (argv['run-chown']) runChown = true; + + let result = await execP(`docker run --env RUN_CHOWN=${runChown} -d ${dockerArgs} salix-db`); + containerId = result.stdout; + + try { + if (argv['random']) { + let inspect = await execP(`docker inspect -f "{{json .NetworkSettings}}" ${containerId}`); + let netSettings = JSON.parse(inspect.stdout); + + dbConf.host = netSettings.Gateway; + dbConf.port = netSettings.Ports['3306/tcp'][0]['HostPort']; + } + + if (runChown) await dockerWait(); + } catch (err) { + if (argv['random']) + await execP(`docker rm -fv ${containerId}`); + throw err; + } + + return containerId; +} +docker.description = `Builds the database image and runs a container`; /** - * Does the minium effort to start the docker, if it doesn't exists calls - * the 'docker-run' task, if it is started does nothing. Keep in mind that when + * Does the minium effort to start the database container, if it doesn't exists + * calls the 'docker' task, if it is started does nothing. Keep in mind that when * you do not rebuild the docker you may be using an outdated version of it. * See the 'docker' task for more info. */ -gulp.task('docker-start', async () => { +async function dockerStart() { let state; try { - let result = await execP('docker container inspect -f "{{json .State}}" dblocal'); + let result = await execP(`docker inspect -f "{{json .State}}" ${containerId}`); state = JSON.parse(result.stdout); } catch (err) { - return await runSequenceP('docker-run'); + return await docker(); } switch (state.Status) { case 'running': return; case 'exited': - return await execP('docker start dblocal'); + await execP(`docker start ${containerId}`); + await dockerWait(); + return; default: - throw new Error(`Unknown docker status: ${status}`); + throw new Error(`Unknown docker status: ${state.Status}`); } -}); +} +dockerStart.description = `Starts the database container`; -/** - * Runs the docker, if the container or it's image doesn't exists builds them. - */ -gulp.task('docker-run', async () => { - try { - await execP('docker image inspect -f "{{json .Id}}" dblocal'); - } catch (err) { - await execP('docker build -t dblocal:latest ./services/db'); - } +function dockerWait() { + return new Promise((resolve, reject) => { + const mysql = require('mysql2'); - await execP('docker run -d --name dblocal -p 3306:3306 dblocal'); - await runSequenceP('docker-wait'); -}); + let interval = 100; + let elapsedTime = 0; + let maxInterval = 4 * 60 * 1000; -/** - * Waits until MySQL docker is started and ready to serve connections. - */ -gulp.task('docker-wait', callback => { - const mysql = require('mysql2'); + let myConf = { + user: dbConf.username, + password: dbConf.password, + host: dbConf.host, + port: dbConf.port + }; - let interval = 1; - let elapsedTime = 0; - let maxInterval = 30 * 60; + log('Waiting for MySQL init process...'); + checker(); - log('Waiting for MySQL init process...'); - checker(); + async function checker() { + elapsedTime += interval; + let state; - async function checker() { - elapsedTime += interval; - let state; + try { + let result = await execP(`docker container inspect -f "{{json .State}}" ${containerId}`); + state = JSON.parse(result.stdout); + } catch (err) { + return reject(new Error(err.message)); + } - try { - let result = await execP('docker container inspect -f "{{json .State}}" dblocal'); - state = JSON.parse(result.stdout); - } catch (err) { - return callback(new Error(err.message)); + if (state.Status === 'exited') + return reject(new Error('Docker exited, please see the docker logs for more info')); + + let conn = mysql.createConnection(myConf); + conn.on('error', () => {}); + conn.connect(err => { + conn.destroy(); + if (!err) { + log('MySQL process ready.'); + return resolve(); + } + + if (elapsedTime >= maxInterval) + reject(new Error(`MySQL not initialized whithin ${elapsedTime / 1000} secs`)); + else + setTimeout(checker, interval); + }); } - - if (state.Status === 'exited') - return callback(new Error('Docker exited, please see the docker logs for more info')); - - let conn = mysql.createConnection({ - host: 'localhost', - user: 'root', - password: 'root' - }); - conn.on('error', () => {}); - conn.connect(err => { - conn.destroy(); - if (!err) return callback(); - - if (elapsedTime >= maxInterval) - callback(new Error(`MySQL not initialized whithin ${elapsedTime} secs`)); - else - setTimeout(checker, interval * 1000); - }); - } -}); + }); +} +dockerWait.description = `Waits until database service is ready`; // Helpers @@ -522,30 +549,42 @@ function execP(command) { exec(command, (err, stdout, stderr) => { if (err) reject(err); - else + else { resolve({ stdout: stdout, stderr: stderr }); + } }); }); } -/** - * Promisified version of runSequence(). - * - * @param {String} args The list of gulp task names - * @return {Promise} The promise - */ -function runSequenceP() { - return new Promise((resolve, reject) => { - let args = Array.prototype.slice.call(arguments); - args.push(err => { - if (err) - reject(err); - else - resolve(); - }); - runSequence(...args); - }); -} +module.exports = { + default: defaultTask, + front, + back, + backOnly, + backWatch, + backTestOnce, + backTestDockerOnce, + backTest, + backTestDocker, + e2e, + e2eOnly, + smokes, + smokesOnly, + i, + install, + build, + clean, + webpack, + webpackDevServer, + routes, + locales, + localesRoutes, + watch, + docker, + dockerStart, + dockerWait, + backendStatus +}; diff --git a/jest-front.js b/jest-front.js new file mode 100644 index 000000000..40c0e52fc --- /dev/null +++ b/jest-front.js @@ -0,0 +1,34 @@ +import 'angular'; +import 'angular-mocks'; +import core from './front/core/module.js'; +import './front/salix/components/app/app.js'; +import './modules/agency/front/module.js'; +import './modules/claim/front/module.js'; +import './modules/client/front/module.js'; +import './modules/invoiceOut/front/module.js'; +import './modules/item/front/module.js'; +import './modules/order/front/module.js'; +import './modules/route/front/module.js'; +import './modules/ticket/front/module.js'; +import './modules/travel/front/module.js'; +import './modules/worker/front/module.js'; + +core.run(vnInterceptor => { + vnInterceptor.setApiPath(null); +}); + +window.ngModule = function(moduleName) { + return angular.mock.module(moduleName, function($provide, $translateProvider) { + // Avoid unexpected request warnings caused by angular translate + // https://angular-translate.github.io/docs/#/guide/22_unit-testing-with-angular-translate + $provide.factory('customLocaleLoader', function($q) { + return function() { + let deferred = $q.defer(); + deferred.resolve({}); + return deferred.promise; + }; + }); + + $translateProvider.useLoader('customLocaleLoader'); + }); +}; diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 000000000..facd1c8a7 --- /dev/null +++ b/jest.config.js @@ -0,0 +1,204 @@ +// For a detailed explanation regarding each configuration property, visit: +// https://jestjs.io/docs/en/configuration.html + +module.exports = { + + // All imported modules in your tests should be mocked automatically + // automock: false, + + // Stop running tests after `n` failures + // bail: 0, + + // Respect "browser" field in package.json when resolving modules + // browser: false, + + // The directory where Jest should store its cached dependency information + // cacheDirectory: "/private/var/folders/_b/2qg94x6n3kd0h_71bp2426wm0000gn/T/jest_dx", + + // Automatically clear mock calls and instances between every test + // clearMocks: true, + + // Indicates whether the coverage information should be collected while executing the test + // collectCoverage: false, + + // An array of glob patterns indicating a set of files for which coverage information should be collected + // collectCoverageFrom: null, + + // The directory where Jest should output its coverage files + coverageDirectory: 'coverage', + + // An array of regexp pattern strings used to skip coverage collection + coveragePathIgnorePatterns: [ + '/node_modules/', + '.spec.js' + ], + + // A list of reporter names that Jest uses when writing coverage reports + // coverageReporters: [ + // "json", + // "text", + // "lcov", + // "clover" + // ], + + // An object that configures minimum threshold enforcement for coverage results + // coverageThreshold: null, + + // A path to a custom dependency extractor + // dependencyExtractor: null, + + // Make calling deprecated APIs throw helpful error messages + // errorOnDeprecated: false, + + // Force coverage collection from ignored files using an array of glob patterns + // forceCoverageMatch: [], + + // A path to a module which exports an async function that is triggered once before all test suites + // globalSetup: null, + + // A path to a module which exports an async function that is triggered once after all test suites + // globalTeardown: null, + + // A set of global variables that need to be available in all test environments + // globals: {}, + + // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. + // maxWorkers: "50%", + + // An array of directory names to be searched recursively up from the requiring module's location + moduleDirectories: [ + `front`, + `modules`, + `front/node_modules`, + `node_modules` + ], + + // An array of file extensions your modules use + moduleFileExtensions: [ + 'js', + // "json", + // "jsx", + // "ts", + // "tsx", + // "node" + ], + + // A map from regular expressions to module names that allow to stub out resources with a single module + moduleNameMapper: { + '\\.(css|scss)$': 'identity-obj-proxy', + '\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '/fileMock.js', + }, + + // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader + // modulePathIgnorePatterns: [], + + // Activates notifications for test results + // notify: false, + + // An enum that specifies notification mode. Requires { notify: true } + // notifyMode: "failure-change", + + // A preset that is used as a base for Jest's configuration + // preset: null, + + // Run tests from one or more projects + // projects: null, + + // Use this configuration option to add custom reporters to Jest + // reporters: undefined, + + // Automatically reset mock state between every test + // resetMocks: false, + + // Reset the module registry before running each individual test + // resetModules: false, + + // A path to a custom resolver + // resolver: null, + + // Automatically restore mock state between every test + // restoreMocks: false, + + // The root directory that Jest should scan for tests and modules within + // rootDir: null, + + // A list of paths to directories that Jest should use to search for files in + // roots: [ + // "" + // ], + + // Allows you to use a custom runner instead of Jest's default test runner + // runner: "jest-runner", + + // The paths to modules that run some code to configure or set up the testing environment before each test + // setupFiles: [], + + // A list of paths to modules that run some code to configure or set up the testing framework before each test + setupFilesAfterEnv: [ + './jest-front.js' + ], + + // A list of paths to snapshot serializer modules Jest should use for snapshot testing + // snapshotSerializers: [], + + // The test environment that will be used for testing + // testEnvironment: 'node', + + // Options that will be passed to the testEnvironment + // testEnvironmentOptions: {}, + + // Adds a location field to test results + // testLocationInResults: false, + + // The glob patterns Jest uses to detect test files + testMatch: [ + '**/front/**/*.spec.js', + // 'loopback/**/*.spec.js', + // 'modules/*/back/**/*.spec.js' + // "**/__tests__/**/*.[jt]s?(x)", + // "**/?(*.)+(spec|test).[tj]s?(x)" + ], + + // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped + // testPathIgnorePatterns: [ + // "/node_modules/" + // ], + + // The regexp pattern or array of patterns that Jest uses to detect test files + // testRegex: [], + + // This option allows the use of a custom results processor + // testResultsProcessor: null, + + // This option allows use of a custom test runner + // testRunner: "jasmine2", + + // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href + testURL: 'http://localhost', + + // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" + // timers: "real", + + // A map from regular expressions to paths to transformers + transform: { + '^.+\\.js?$': 'babel-jest', + '^.+\\.html$': 'html-loader-jest' + }, + + // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation + // transformIgnorePatterns: [ + // '/node_modules/' + // ], + + // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them + // unmockedModulePathPatterns: undefined, + + // Indicates whether each individual test should be reported during the run + verbose: false, + + // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode + // watchPathIgnorePatterns: [], + + // Whether to use watchman for file crawling + // watchman: true, +}; diff --git a/karma.conf.js b/karma.conf.js deleted file mode 100644 index 0518f8cd0..000000000 --- a/karma.conf.js +++ /dev/null @@ -1,116 +0,0 @@ -var webpackConfig = require('./webpack.config.js'); -delete webpackConfig.entry; -delete webpackConfig.output; -webpackConfig.devtool = 'inline-source-map'; -webpackConfig.plugins = []; - -// Karma configuration -// Generated on Tue Aug 22 2017 13:37:43 GMT+0200 (CEST) - -module.exports = function(config) { - let baseConfig = { - - // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: '', - - // frameworks to use - // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ['jasmine'], - - // list of files / patterns to load in the browser - files: [ - {pattern: 'client/test_index.js', watched: false} - ], - - // list of files to exclude - exclude: [], - - webpack: webpackConfig, - - webpackMiddleware: { - stats: 'errors-only' - }, - - webpackServer: { - noInfo: true - }, - - // preprocess matching files before serving them to the browser - // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor - preprocessors: { - './client/test_index.js': ['webpack', 'sourcemap'] - }, - - // test results reporter to use - // possible values: 'dots', 'progress' - // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ['progress'], - - // web server port - port: 9876, - - // enable / disable colors in the output (reporters and logs) - colors: true, - - // level of logging - // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG - logLevel: config.LOG_INFO, - - // enable / disable watching file and executing tests whenever any file changes - autoWatch: true, - - // start these browsers - // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - browsers: [], - - // Continuous Integration mode - // if true, Karma captures browsers, runs the tests and exits - singleRun: false, - - // Concurrency level - // how many browser should be started simultaneous - concurrency: Infinity, - - plugins: [ - 'karma-jasmine', - 'karma-webpack', - 'karma-chrome-launcher', - 'karma-firefox-launcher', - 'karma-sourcemap-loader' - ] - }; - - let browserConfig; - - if (process.env.FIREFOX_BIN) { - browserConfig = { - browsers: ['FirefoxHeadless'], - customLaunchers: { - FirefoxHeadless: { - base: 'Firefox', - flags: ['-headless'] - } - } - }; - } else { - browserConfig = { - browsers: ['ChromeNoSandboxHeadless'], - customLaunchers: { - ChromeNoSandboxHeadless: { - base: 'Chrome', - flags: [ - '--no-sandbox', - // See https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md - '--headless', - '--disable-gpu', - // Without a remote debugging port, Google Chrome exits immediately. - ' --remote-debugging-port=9222' - ] - } - } - }; - } - - Object.assign(baseConfig, browserConfig); - config.set(baseConfig); -}; diff --git a/services/loopback/README.md b/loopback/README.md similarity index 100% rename from services/loopback/README.md rename to loopback/README.md diff --git a/loopback/common/methods/application/status.js b/loopback/common/methods/application/status.js new file mode 100644 index 000000000..43cfe5b60 --- /dev/null +++ b/loopback/common/methods/application/status.js @@ -0,0 +1,19 @@ + +module.exports = Self => { + Self.remoteMethod('status', { + description: 'Gets the backend status', + returns: { + type: 'Object', + root: true + }, + http: { + path: `/status`, + verb: 'GET' + } + }); + + Self.status = async() => { + await Self.rawSql(`SELECT TRUE`); + return true; + }; +}; diff --git a/loopback/common/methods/schema/model-info.js b/loopback/common/methods/schema/model-info.js new file mode 100644 index 000000000..a95b60627 --- /dev/null +++ b/loopback/common/methods/schema/model-info.js @@ -0,0 +1,82 @@ + +module.exports = Self => { + Self.remoteMethod('modelInfo', { + description: 'Gets all models information', + accepts: [ + { + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + } + ], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/modelInfo`, + verb: 'GET' + } + }); + + Self.modelInfo = async function(ctx) { + let json = {}; + let models = Self.app.models; + + for (let modelName in models) { + let model = models[modelName]; + let validations = model.validations; + let jsonValidations = {}; + + for (let fieldName in validations) { + let jsonField = []; + + for (let validation of validations[fieldName]) { + let options = validation.options; + + if ((options && options.async) || + (validation.validation == 'custom' && !validation.isExportable)) + continue; + + let validationCp = Object.assign({}, validation); + + if (validationCp.message) + validationCp.message = ctx.req.__(validationCp.message); + + jsonField.push(toJson(validationCp)); + } + + jsonValidations[fieldName] = jsonField; + } + + json[modelName] = { + properties: model.definition.rawProperties, + validations: jsonValidations + }; + } + + return json; + }; + + function toJson(object) { + let json = {}; + + for (let prop in object) { + let value = object[prop]; + + switch (typeof value) { + case 'object': + if (value instanceof RegExp) + json[prop] = value.source; + break; + case 'function': + json[prop] = value.toString(); + break; + default: + json[prop] = value; + } + } + + return json; + } +}; diff --git a/loopback/common/methods/vn-model/getSetValues.js b/loopback/common/methods/vn-model/getSetValues.js new file mode 100644 index 000000000..ac6485d3c --- /dev/null +++ b/loopback/common/methods/vn-model/getSetValues.js @@ -0,0 +1,55 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + /** + * Returns a set of allowed values defined on table scheme + * @param {String} column - Model or Table column name + * @return {Array} - Array of set values + */ + Self.getSetValues = async function(column) { + let model = this.app.models[this.modelName].definition; + let properties = model.properties; + let tableName = this.modelName; + let schema = null; + + if (model.settings && model.settings.mysql) { + let tableSplit = model.settings.mysql.table.split('.'); + tableName = tableSplit.pop(); + schema = tableSplit.pop() || null; + } + + let property = properties[column]; + + if (!property) + throw new UserError(`Column does not exist`); + + let columnName = property.mysql + ? property.mysql.columnName + : column; + + let columnInfo = await this.rawSql( + `SELECT column_type columnType + FROM information_schema.columns + WHERE table_name = ? + AND table_schema = IFNULL(?, DATABASE()) + AND column_name = ?`, + [tableName, schema, columnName] + ); + + if (!columnInfo || !columnInfo[0]) + throw new UserError(`Cannot fetch column values`); + + let setValues; + setValues = columnInfo[0].columnType + .replace(/^set\((.*)\)$/i, '$1') + .replace(/'/g, '') + .match(new RegExp(/(\w+)+/, 'ig')); + + let values = []; + setValues.forEach(setValue => { + values.push({value: setValue}); + }); + + return values; + }; +}; diff --git a/loopback/common/methods/vn-model/specs/crud.spec.js b/loopback/common/methods/vn-model/specs/crud.spec.js new file mode 100644 index 000000000..e2d261f98 --- /dev/null +++ b/loopback/common/methods/vn-model/specs/crud.spec.js @@ -0,0 +1,42 @@ +const app = require('vn-loopback/server/server'); + +describe('Model crud()', () => { + let insertId; + let ItemBarcode = app.models.ItemBarcode; + + it('should inherit crud method from VnModel', () => { + expect(ItemBarcode.crud).toBeDefined(); + }); + + it('should create a new instance', async() => { + let data = {code: '500', itemFk: '1'}; + let creates = [data]; + + await ItemBarcode.crud(null, null, creates); + let instance = await ItemBarcode.findOne({where: data}); + insertId = instance.id; + + expect(instance).not.toEqual(null); + expect(instance.code).toEqual('500'); + }); + + it('should update the instance', async() => { + let updates = [{ + where: {id: insertId}, + data: {code: '501', itemFk: 1} + }]; + + await ItemBarcode.crud(null, updates); + let instance = await ItemBarcode.findById(insertId); + + expect(instance.code).toEqual('501'); + }); + + it('should delete the created instance', async() => { + let deletes = [insertId]; + await ItemBarcode.crud(deletes); + let instance = await ItemBarcode.findById(insertId); + + expect(instance).toEqual(null); + }); +}); diff --git a/loopback/common/methods/vn-model/specs/getSetValues.spec.js b/loopback/common/methods/vn-model/specs/getSetValues.spec.js new file mode 100644 index 000000000..cd64697c9 --- /dev/null +++ b/loopback/common/methods/vn-model/specs/getSetValues.spec.js @@ -0,0 +1,16 @@ +const app = require('vn-loopback/server/server'); + +describe('Model getSetValues()', () => { + it('should extend getSetValues properties to any model passed', () => { + let exampleModel = app.models.Order; + + expect(exampleModel.getSetValues).toBeDefined(); + }); + + it('should return an array of set values from model column sourceApp', async() => { + let result = await app.models.Order.getSetValues('sourceApp'); + + expect(result.length).toEqual(6); + expect(result[5].value).toEqual('TABLET_VN'); + }); +}); diff --git a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js new file mode 100644 index 000000000..48b67528a --- /dev/null +++ b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js @@ -0,0 +1,19 @@ +const app = require('vn-loopback/server/server'); + +describe('Model rewriteDbError()', () => { + it('should extend rewriteDbError properties to any model passed', () => { + let exampleModel = app.models.ItemNiche; + + expect(exampleModel.rewriteDbError).toBeDefined(); + }); + + it('should handle a duplicated warehouse error', async() => { + let itemNiche = {itemFk: 1, warehouseFK: 1, code: 'A1'}; + let error; + await app.models.ItemNiche.create(itemNiche).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`The warehouse can't be repeated`); + }); + }); +}); diff --git a/loopback/common/models/application.js b/loopback/common/models/application.js new file mode 100644 index 000000000..ff7599fac --- /dev/null +++ b/loopback/common/models/application.js @@ -0,0 +1,4 @@ + +module.exports = function(Self) { + require('../methods/application/status')(Self); +}; diff --git a/loopback/common/models/application.json b/loopback/common/models/application.json new file mode 100644 index 000000000..0bb489720 --- /dev/null +++ b/loopback/common/models/application.json @@ -0,0 +1,12 @@ +{ + "name": "Application", + "base": "VnModel", + "acls": [ + { + "property": "status", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/loopback/common/models/field-acl.json b/loopback/common/models/field-acl.json new file mode 100644 index 000000000..25ed949b9 --- /dev/null +++ b/loopback/common/models/field-acl.json @@ -0,0 +1,27 @@ +{ + "name": "FieldAcl", + "base": "VnModel", + "options": { + "mysql": { + "table": "salix.fieldAcl" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "model": { + "type": "String" + }, + "property":{ + "type": "String" + }, + "actionType":{ + "type": "String" + }, + "role":{ + "type": "String" + } + } +} diff --git a/loopback/common/models/loggable.js b/loopback/common/models/loggable.js new file mode 100644 index 000000000..a6d0e8474 --- /dev/null +++ b/loopback/common/models/loggable.js @@ -0,0 +1,289 @@ +const pick = require('object.pick'); +const LoopBackContext = require('loopback-context'); + +module.exports = function(Self) { + Self.setup = function() { + Self.super_.setup.call(this); + }; + + Self.observe('after save', async function(ctx) { + const loopBackContext = LoopBackContext.getCurrentContext(); + await logInModel(ctx, loopBackContext); + }); + + Self.observe('before save', async function(ctx) { + let options = {}; + if (ctx.options && ctx.options.transaction) + options.transaction = ctx.options.transaction; + + let oldInstance; + let oldInstanceFk; + let newInstance; + + if (ctx.data) { + oldInstanceFk = pick(ctx.currentInstance, Object.keys(ctx.data)); + newInstance = await fkToValue(ctx.data, ctx); + oldInstance = await fkToValue(oldInstanceFk, ctx); + if (ctx.where && !ctx.currentInstance) { + let fields = Object.keys(ctx.data); + ctx.oldInstances = await ctx.Model.app.models[ctx.Model.definition.name].find({where: ctx.where, fields: fields}, options); + } + } + if (ctx.isNewInstance) + newInstance = await fkToValue(ctx.instance.__data, ctx); + + ctx.hookState.oldInstance = oldInstance; + ctx.hookState.newInstance = newInstance; + }); + + Self.observe('before delete', async function(ctx) { + let options = {}; + if (ctx.options && ctx.options.transaction) + options.transaction = ctx.options.transaction; + + if (ctx.where) { + let affectedModel = ctx.Model.definition.name; + let definition = ctx.Model.definition; + let deletedInstances = await ctx.Model.app.models[affectedModel].find({where: ctx.where}, options); + let relation = definition.settings.log.relation; + + if (relation) { + let primaryKey = ctx.Model.relations[relation].keyFrom; + + let arrangedDeletedInstances = []; + for (let i = 0; i < deletedInstances.length; i++) { + if (primaryKey) + deletedInstances[i].originFk = deletedInstances[i][primaryKey]; + let arrangedInstance = await fkToValue(deletedInstances[i], ctx); + arrangedDeletedInstances[i] = arrangedInstance; + } + ctx.hookState.oldInstance = arrangedDeletedInstances; + } + } + }); + + Self.observe('after delete', async function(ctx) { + const loopBackContext = LoopBackContext.getCurrentContext(); + if (ctx.hookState.oldInstance) + logDeletedInstances(ctx, loopBackContext); + }); + + async function logDeletedInstances(ctx, loopBackContext) { + let options = {}; + if (ctx.options && ctx.options.transaction) + options.transaction = ctx.options.transaction; + + ctx.hookState.oldInstance.forEach(async instance => { + let userFk; + if (loopBackContext) + userFk = loopBackContext.active.accessToken.userId; + + let definition = ctx.Model.definition; + + let changedModelValue = definition.settings.log.changedModelValue; + let logRecord = { + originFk: instance.originFk, + userFk: userFk, + action: 'delete', + changedModel: ctx.Model.definition.name, + changedModelId: instance.id, + changedModelValue: instance[changedModelValue], + oldInstance: instance, + newInstance: {} + }; + + delete instance.originFk; + + let logModel = definition.settings.log.model; + await ctx.Model.app.models[logModel].create(logRecord, options); + }); + } + + async function fkToValue(instance, ctx) { + let options = {}; + if (ctx.options && ctx.options.transaction) + options.transaction = ctx.options.transaction; + + let cleanInstance = JSON.parse(JSON.stringify(instance)); + let result = {}; + for (let key in cleanInstance) { + let val = cleanInstance[key]; + if (val === undefined || val === null) continue; + for (let key1 in ctx.Model.relations) { + let val1 = ctx.Model.relations[key1]; + if (val1.keyFrom == key && key != 'id') { + let recordSet = await ctx.Model.app.models[val1.modelTo.modelName].findById(val, null, options); + + let showField = val1.modelTo && val1.modelTo.definition.settings.log && val1.modelTo.definition.settings.log.showField && recordSet && recordSet[val1.modelTo.definition.settings.log.showField]; + if (!showField) { + const showFieldNames = [ + 'name', + 'description', + 'code' + ]; + for (field of showFieldNames) { + if (val1.modelTo.definition.properties && val1.modelTo.definition.properties[field] && recordSet && recordSet[field]) { + showField = field; + break; + } + } + } + + if (showField && recordSet && recordSet[showField]) { + val = recordSet[showField]; + break; + } + + val = recordSet && recordSet.id || val; + break; + } + } + result[key] = val; + } + return result; + } + + async function logInModel(ctx, loopBackContext) { + let options = {}; + if (ctx.options && ctx.options.transaction) + options.transaction = ctx.options.transaction; + + let definition = ctx.Model.definition; + let primaryKey; + for (let property in definition.properties) { + if (definition.properties[property].id) { + primaryKey = property; + break; + } + } + + if (!primaryKey) throw new Error('Primary key not found'); + let originId; + + // RELATIONS LOG + let changedModelId; + + if (ctx.instance && !definition.settings.log.relation) { + originId = ctx.instance.id; + changedModelId = ctx.instance.id; + } else if (definition.settings.log.relation) { + primaryKey = ctx.Model.relations[definition.settings.log.relation].keyFrom; + + if (ctx.where && ctx.where[primaryKey]) + originId = ctx.where[primaryKey]; + else if (ctx.instance) { + originId = ctx.instance[primaryKey]; + changedModelId = ctx.instance.id; + } + } else { + originId = ctx.currentInstance.id; + changedModelId = ctx.currentInstance.id; + } + + // Sets the changedModelValue to save and the instances changed in case its an updateAll + let showField = definition.settings.log.showField; + let where; + if (showField && (!ctx.instance || !ctx.instance[showField]) && ctx.where) { + changedModelId = []; + where = []; + let changedInstances = await ctx.Model.app.models[definition.name].find({where: ctx.where, fields: ['id', showField, primaryKey]}, options); + changedInstances.forEach(element => { + where.push(element[showField]); + changedModelId.push(element.id); + originId = element[primaryKey]; + }); + } else if (ctx.hookState.oldInstance) + where = ctx.instance[showField]; + + + // Set oldInstance, newInstance, userFk and action + let oldInstance = {}; + if (ctx.hookState.oldInstance) + Object.assign(oldInstance, ctx.hookState.oldInstance); + + let newInstance = {}; + if (ctx.hookState.newInstance) + Object.assign(newInstance, ctx.hookState.newInstance); + + let userFk; + if (loopBackContext) + userFk = loopBackContext.active.accessToken.userId; + + let action = setActionType(ctx); + + removeUnloggableProperties(definition, oldInstance); + removeUnloggableProperties(definition, newInstance); + + let logRecord = { + originFk: originId, + userFk: userFk, + action: action, + changedModel: ctx.Model.definition.name, + changedModelId: changedModelId, + changedModelValue: where, + oldInstance: oldInstance, + newInstance: newInstance + }; + + let logsToSave = setLogsToSave(where, changedModelId, logRecord, ctx); + let logModel = definition.settings.log.model; + + await ctx.Model.app.models[logModel].create(logsToSave, options); + } + + /** + * Removes unwanted properties + * @param {*} definition Model definition + * @param {*} properties Modified object properties + */ + function removeUnloggableProperties(definition, properties) { + const propList = Object.keys(properties); + const propDefs = new Map(); + + for (let property in definition.properties) { + const propertyDef = definition.properties[property]; + + propDefs.set(property, propertyDef); + } + + for (let property of propList) { + const propertyDef = propDefs.get(property); + + if (!propertyDef) return; + + if (propertyDef.log === false) + delete properties[property]; + else if (propertyDef.logValue === false) + properties[property] = null; + } + } + + // this function retuns all the instances changed in case this is an updateAll + function setLogsToSave(changedInstances, changedInstancesIds, logRecord, ctx) { + let promises = []; + if (changedInstances && typeof changedInstances == 'object') { + for (let i = 0; i < changedInstances.length; i++) { + logRecord.changedModelId = changedInstancesIds[i]; + logRecord.changedModelValue = changedInstances[i]; + if (ctx.oldInstances) + logRecord.oldInstance = ctx.oldInstances[i]; + promises.push(JSON.parse(JSON.stringify(logRecord))); + } + } else + return logRecord; + + return promises; + } + + function setActionType(ctx) { + let oldInstance = ctx.hookState.oldInstance; + let newInstance = ctx.hookState.newInstance; + + if (oldInstance && newInstance) + return 'update'; + else if (!oldInstance && newInstance) + return 'insert'; + + return 'delete'; + } +}; diff --git a/loopback/common/models/loggable.json b/loopback/common/models/loggable.json new file mode 100644 index 000000000..9101532a3 --- /dev/null +++ b/loopback/common/models/loggable.json @@ -0,0 +1,5 @@ +{ + "name": "Loggable", + "base": "VnModel", + "validateUpsert": true +} diff --git a/loopback/common/models/schema.js b/loopback/common/models/schema.js new file mode 100644 index 000000000..f88cc895c --- /dev/null +++ b/loopback/common/models/schema.js @@ -0,0 +1,4 @@ + +module.exports = function(Self) { + require('../methods/schema/model-info')(Self); +}; diff --git a/loopback/common/models/schema.json b/loopback/common/models/schema.json new file mode 100644 index 000000000..face506ff --- /dev/null +++ b/loopback/common/models/schema.json @@ -0,0 +1,13 @@ +{ + "name": "Schema", + "base": "PersistedModel", + "acls": [ + { + "property": "validations", + "accessType": "EXECUTE", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/loopback/common/models/vn-model.js b/loopback/common/models/vn-model.js new file mode 100644 index 000000000..0191967b1 --- /dev/null +++ b/loopback/common/models/vn-model.js @@ -0,0 +1,277 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const UserError = require('vn-loopback/util/user-error'); + +module.exports = function(Self) { + Self.ParameterizedSQL = ParameterizedSQL; + + require('../methods/vn-model/getSetValues')(Self); + + Object.assign(Self, { + setup() { + Self.super_.setup.call(this); + + /** + * Setting a global transaction timeout to find out if the service + * is blocked because the connection pool is empty. + */ + this.once('dataSourceAttached', () => { + let orgBeginTransaction = this.beginTransaction; + this.beginTransaction = function(options, cb) { + options = options || {}; + if (!options.timeout) + options.timeout = 120000; + return orgBeginTransaction.call(this, options, cb); + }; + }); + + // Register field ACL validation + /* this.beforeRemote('prototype.patchAttributes', ctx => this.checkUpdateAcls(ctx)); + this.beforeRemote('updateAll', ctx => this.checkUpdateAcls(ctx)); + this.beforeRemote('patchOrCreate', ctx => this.checkInsertAcls(ctx)); + this.beforeRemote('create', ctx => this.checkInsertAcls(ctx)); + this.beforeRemote('replaceById', ctx => this.checkInsertAcls(ctx)); + this.beforeRemote('replaceOrCreate', ctx => this.checkInsertAcls(ctx)); */ + + this.remoteMethod('crud', { + description: `Create, update or/and delete instances from model with a single request`, + accessType: 'WRITE', + accepts: [ + { + arg: 'deletes', + description: `Identifiers of instances to delete`, + type: ['Integer'] + }, { + arg: 'updates', + description: `Instances to update with it's identifier {where, data}`, + type: ['Object'] + }, { + arg: 'creates', + description: `Instances to create`, + type: ['Object'] + } + ] + }); + }, + + async crud(deletes, updates, creates) { + let tx = await this.beginTransaction({}); + + try { + let options = {transaction: tx}; + + if (deletes) { + let promises = []; + for (let id of deletes) + promises.push(this.destroyById(id, options)); + await Promise.all(promises); + } + if (updates) { + let promises = []; + for (let update of updates) + promises.push(this.upsertWithWhere(update.where, update.data, options)); + await Promise.all(promises); + } + if (creates && creates.length) { + try { + await this.create(creates, options); + } catch (error) { + throw error[error.length - 1]; + } + } + + await tx.commit(); + } catch (error) { + await tx.rollback(); + throw error; + } + }, + + /** + * Wrapper for remoteMethod() but adding the context as + * extra argument at the beginning of arguments list. + * + * @param {String} methodName The method name + * @param {Object} options The method options + */ + remoteMethodCtx(methodName, options) { + if (options.accepts === undefined) + options.accepts = []; + else if (!Array.isArray(options.accepts)) + options.accepts = [options.accepts]; + + options.accepts.unshift({ + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + }); + this.remoteMethod(methodName, options); + }, + + /** + * Adds a validation, marking it as exportable to the browser. + * Exportable validation functions should be synchronous and totally + * independent from other code because they are parsed in the browser + * using eval(). + * + * @param {String} propertyName The property name + * @param {Function} validatorFn The validation function + * @param {Object} options The validation options + */ + validateBinded(propertyName, validatorFn, options) { + let customValidator = function(err) { + if (!validatorFn(this[propertyName])) err(); + }; + options.isExportable = true; + options.bindedFunction = validatorFn; + this.validate(propertyName, customValidator, options); + }, + + /** + * Catches database errors overriding create() and upsert() methods. + * + * @param {Function} replaceErrFunc - Callback + */ + rewriteDbError(replaceErrFunc) { + function replaceErr(err, replaceErrFunc) { + if (Array.isArray(err)) { + let errs = []; + for (let e of err) + errs.push(replaceErrFunc(e)); + return errs; + } + return replaceErrFunc(err); + } + + function rewriteMethod(methodName) { + const realMethod = this[methodName]; + return async(data, options, cb) => { + if (options instanceof Function) { + cb = options; + options = null; + } + + try { + const result = await realMethod.call(this, data, options); + + if (cb) cb(null, result); + } catch (err) { + let myErr = replaceErr(err, replaceErrFunc); + if (cb) + cb(myErr); + else + throw myErr; + } + }; + } + + this.once('attached', () => { + this.remove = + this.deleteAll = + this.destroyAll = rewriteMethod.call(this, 'remove'); + this.upsert = rewriteMethod.call(this, 'upsert'); + this.create = rewriteMethod.call(this, 'create'); + }); + }, + + /* + * Shortcut to VnMySQL.executeP() + */ + rawSql(query, params, options, cb) { + return this.dataSource.connector.executeP(query, params, options, cb); + }, + + /* + * Shortcut to VnMySQL.executeStmt() + */ + rawStmt(stmt, options) { + return this.dataSource.connector.executeStmt(stmt, options); + }, + + /* + * Shortcut to VnMySQL.makeLimit() + */ + makeLimit(filter) { + return this.dataSource.connector.makeLimit(filter); + }, + + /* + * Shortcut to VnMySQL.makeSuffix() + */ + makeSuffix(filter) { + return this.dataSource.connector.makeSuffix(filter); + }, + + /* + * Shortcut to VnMySQL.buildModelSuffix() + */ + buildSuffix(filter, tableAlias) { + return this.dataSource.connector.buildModelSuffix(this.modelName, filter, tableAlias); + }, + + async checkAcls(ctx, actionType) { + let userId = ctx.req.accessToken.userId; + let models = this.app.models; + let userRoles = await models.Account.getRoles(userId); + let data = ctx.args.data; + let modelAcls; + + function modifiedProperties(data) { + let properties = []; + + for (property in data) + properties.push(property); + + return properties; + } + + modelAcls = await models.FieldAcl.find({ + where: { + and: [ + {model: this.modelName}, + {role: {inq: userRoles}}, + {property: '*'}, + {or: [{actionType: '*'}, {actionType: actionType}]} + ] + } + }); + + let allowedAll = modelAcls.find(acl => { + return acl.property == '*'; + }); + + if (allowedAll) + return; + + modelAcls = await models.FieldAcl.find({ + where: { + and: [ + {model: this.modelName}, + {role: {inq: userRoles}}, + {property: {inq: modifiedProperties(data)}}, + {or: [{actionType: '*'}, {actionType: actionType}]} + ] + } + }); + + let propsHash = {}; + for (let acl of modelAcls) + propsHash[acl.property] = true; + + let allowedProperties = Object.keys(data).every(property => { + return propsHash[property]; + }); + + if (!allowedProperties) + throw new UserError(`You don't have enough privileges`); + }, + + checkUpdateAcls(ctx) { + return this.checkAcls(ctx, 'update'); + }, + + checkInsertAcls(ctx) { + return this.checkAcls(ctx, 'insert'); + } + }); +}; diff --git a/services/loopback/common/models/vn-model.json b/loopback/common/models/vn-model.json similarity index 100% rename from services/loopback/common/models/vn-model.json rename to loopback/common/models/vn-model.json diff --git a/loopback/locale/en.json b/loopback/locale/en.json new file mode 100644 index 000000000..91339d14e --- /dev/null +++ b/loopback/locale/en.json @@ -0,0 +1,61 @@ +{ + "State cannot be blank": "State cannot be blank", + "Cannot be blank": "Cannot be blank", + "The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero", + "The grade must be an integer greater than or equal to zero": "The grade must be an integer greater than or equal to zero", + "Invalid email": "Invalid email", + "Name cannot be blank": "Name cannot be blank", + "Phone cannot be blank": "Phone cannot be blank", + "Description should have maximum of 45 characters": "Description should have maximum of 45 characters", + "Period cannot be blank": "Period cannot be blank", + "Sample type cannot be blank": "Sample type cannot be blank", + "That payment method requires an IBAN": "That payment method requires an IBAN", + "That payment method requires a BIC": "That payment method requires a BIC", + "The default consignee can not be unchecked": "The default consignee can not be unchecked", + "You can't make changes on a client with verified data": "You can't make changes on a client with verified data", + "Enter an integer different to zero": "Enter an integer different to zero", + "Package cannot be blank": "Package cannot be blank", + "The new quantity should be smaller than the old one": "The new quantity should be smaller than the old one", + "The sales of this ticket can't be modified": "The sales of this ticket can't be modified", + "Cannot check Equalization Tax in this NIF/CIF": "Cannot check Equalization Tax in this NIF/CIF", + "You can't create an order for a frozen client": "You can't create an order for a frozen client", + "This address doesn't exist": "This address doesn't exist", + "Warehouse cannot be blank": "Warehouse cannot be blank", + "Agency cannot be blank": "Agency cannot be blank", + "The IBAN does not have the correct format": "The IBAN does not have the correct format", + "You can't make changes on the basic data of an confirmed order or with rows": "You can't make changes on the basic data of an confirmed order or with rows", + "You can't create a ticket for a inactive client": "You can't create a ticket for a inactive client", + "Worker cannot be blank": "Worker cannot be blank", + "You must delete the claim id %d first": "You must delete the claim id %d first", + "You don't have enough privileges": "You don't have enough privileges", + "Tag value cannot be blank": "Tag value cannot be blank", + "A client with that Web User name already exists": "A client with that Web User name already exists", + "The warehouse can't be repeated": "The warehouse can't be repeated", + "Barcode must be unique": "Barcode must be unique", + "You don't have enough privileges to do that": "You don't have enough privileges to do that", + "You can't create a ticket for a frozen client": "You can't create a ticket for a frozen client", + "can't be blank": "can't be blank", + "Street cannot be empty": "Street cannot be empty", + "City cannot be empty": "City cannot be empty", + "EXTENSION_INVALID_FORMAT": "Invalid extension", + "The secret can't be blank": "The secret can't be blank", + "Invalid TIN": "Invalid Tax number", + "This ticket can't be invoiced": "This ticket can't be invoiced", + "The value should be a number": "The value should be a number", + "The current ticket can't be modified": "The current ticket can't be modified", + "Extension format is invalid": "Extension format is invalid", + "NO_ZONE_FOR_THIS_PARAMETERS": "NO_ZONE_FOR_THIS_PARAMETERS", + "This client can't be invoiced": "This client can't be invoiced", + "The introduced hour already exists": "The introduced hour already exists", + "Invalid parameters to create a new ticket": "Invalid parameters to create a new ticket", + "Concept cannot be blank": "Concept cannot be blank", + "Ticket id cannot be blank": "Ticket id cannot be blank", + "Weekday cannot be blank": "Weekday cannot be blank", + "This ticket can not be modified": "This ticket can not be modified", + "You can't delete a confirmed order": "You can't delete a confirmed order", + "Value has an invalid format": "Value has an invalid format", + "The postcode doesn't exists. Ensure you put the correct format": "The postcode doesn't exists. Ensure you put the correct format", + "Can't create stowaway for this ticket": "Can't create stowaway for this ticket", + "Has deleted the ticket id": "Has deleted the ticket id [#{{id}}]({{{url}}})", + "Swift / BIC can't be empty": "Swift / BIC can't be empty" +} \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json new file mode 100644 index 000000000..15fd89f5e --- /dev/null +++ b/loopback/locale/es.json @@ -0,0 +1,122 @@ +{ + "Phone format is invalid": "El formato del teléfono no es correcto", + "You are not allowed to change the credit": "No tienes privilegios para modificar el crédito", + "Unable to mark the equivalence surcharge": "No se puede marcar el recargo de equivalencia", + "The default consignee can not be unchecked": "No se puede desmarcar el consignatario predeterminado", + "Unable to default a disabled consignee": "No se puede poner predeterminado un consignatario desactivado", + "Can't be blank": "No puede estar en blanco", + "Invalid TIN": "NIF/CIF invalido", + "TIN must be unique": "El NIF/CIF debe ser único", + "A client with that Web User name already exists": "Ya existe un cliente con ese Usuario Web", + "Is invalid": "Is invalid", + "Quantity cannot be zero": "La cantidad no puede ser cero", + "Enter an integer different to zero": "Introduce un entero distinto de cero", + "Package cannot be blank": "El embalaje no puede estar en blanco", + "The company name must be unique": "La razón social debe ser única", + "Invalid email": "Correo electrónico inválido", + "The IBAN does not have the correct format": "El IBAN no tiene el formato correcto", + "That payment method requires an IBAN": "El método de pago seleccionado requiere un IBAN", + "That payment method requires a BIC": "El método de pago seleccionado requiere un BIC", + "State cannot be blank": "El estado no puede estar en blanco", + "Worker cannot be blank": "El trabajador no puede estar en blanco", + "Cannot change the payment method if no salesperson": "No se puede cambiar la forma de pago si no hay comercial asignado", + "can't be blank": "El campo no puede estar vacío", + "Observation type must be unique": "El tipo de observación no puede repetirse", + "The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero", + "The grade must be similar to the last one": "El grade debe ser similar al último", + "Only manager can change the credit": "Solo el gerente puede cambiar el credito de este cliente", + "Name cannot be blank": "El nombre no puede estar en blanco", + "Phone cannot be blank": "El teléfono no puede estar en blanco", + "Period cannot be blank": "El periodo no puede estar en blanco", + "Choose a company": "Selecciona una empresa", + "Se debe rellenar el campo de texto": "Se debe rellenar el campo de texto", + "Description should have maximum of 45 characters": "La descripción debe tener maximo 45 caracteres", + "Cannot be blank": "El campo no puede estar en blanco", + "The grade must be an integer greater than or equal to zero": "El grade debe ser un entero mayor o igual a cero", + "Sample type cannot be blank": "El tipo de plantilla no puede quedar en blanco", + "Description cannot be blank": "Se debe rellenar el campo de texto", + "The new quantity should be smaller than the old one": "La nueva cantidad debe de ser menor que la anterior", + "The value should not be greater than 100%": "El valor no debe de ser mayor de 100%", + "The value should be a number": "El valor debe ser un numero", + "This order is not editable": "Esta orden no se puede modificar", + "You can't create an order for a frozen client": "No puedes crear una orden para un cliente congelado", + "You can't create an order for a client that has a debt": "No puedes crear una orden para un cliente con deuda", + "is not a valid date": "No es una fecha valida", + "Barcode must be unique": "El código de barras debe ser único", + "The warehouse can't be repeated": "El almacén no puede repetirse", + "The tag can't be repeated": "El tag no puede repetirse", + "The observation type can't be repeated": "El tipo de observación no puede repetirse", + "A claim with that sale already exists": "Ya existe una reclamación para esta línea", + "You don't have enough privileges to change that field": "No tienes permisos para cambiar ese campo", + "Warehouse cannot be blank": "El almacén no puede quedar en blanco", + "Agency cannot be blank": "La agencia no puede quedar en blanco", + "You can't make changes on a client with verified data": "No puedes hacer cambios en un cliente con datos comprobados", + "This address doesn't exist": "Este consignatario no existe", + "You can't create an order for a inactive client": "You can't create an order for a inactive client", + "You can't create an order for a client that doesn't has tax data verified": "You can't create an order for a client that doesn't has tax data verified", + "You must delete the claim id %d first": "Antes debes borrar la reclamacion %d", + "You don't have enough privileges": "No tienes suficientes permisos", + "Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF", + "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos basicos de una orden con artículos", + "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no esta permitido el uso de la letra ñ", + "You can't create a ticket for a frozen client": "No puedes crear un ticket para un cliente congelado", + "You can't create a ticket for a inactive client": "No puedes crear un ticket para un cliente inactivo", + "Tag value cannot be blank": "El valor del tag no puede quedar en blanco", + "ORDER_EMPTY": "Cesta vacía", + "You don't have enough privileges to do that": "No tienes permisos para cambiar esto", + "NO SE PUEDE DESACTIVAR EL CONSIGNAT": "NO SE PUEDE DESACTIVAR EL CONSIGNAT", + "Error. El NIF/CIF está repetido": "Error. El NIF/CIF está repetido", + "Street cannot be empty": "Dirección no puede estar en blanco", + "City cannot be empty": "Cuidad no puede estar en blanco", + "Code cannot be blank": "Código no puede estar en blanco", + "You cannot remove this department": "No puedes eliminar este departamento", + "The extension must be unique": "La extensión debe ser unica", + "The secret can't be blank": "La contraseña no puede estar en blanco", + "We weren't able to send this SMS": "No hemos podido enviar el SMS", + "This client can't be invoiced": "Este cliente no puede ser facturado", + "This ticket can't be invoiced": "Este ticket no puede ser facturado", + "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado", + "This ticket can not be modified": "Este ticket no puede ser modificado", + "The introduced hour already exists": "Esta hora ya ha sido introducida", + "INFINITE_LOOP": "Existe una dependencia entre dos Jefes", + "The sales of the current ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas", + "The sales of the receiver ticket can't be modified": "Las lineas del ticket al que envias no pueden ser modificadas", + "NO_AGENCY_AVAILABLE": "No hay una zona de reparto disponible con estos parámetros", + "ERROR_PAST_SHIPMENT": "No puedes seleccionar una fecha de envío en pasado", + "The current ticket can't be modified": "El ticket actual no puede ser modificado", + "The sales of this ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas", + "Please select at least one sale": "Por favor selecciona al menos una linea", + "All sales must belong to the same ticket": "Todas las lineas deben pertenecer al mismo ticket", + "NO_ZONE_FOR_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", + "This item doesn't exists": "El artículo no existe", + "NOT_ZONE_WITH_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", + "Extension format is invalid": "El formato de la extensión es inválido", + "Invalid parameters to create a new ticket": "Parámetros inválidos para crear un nuevo ticket", + "This item is not available": "Este artículo no está disponible", + "This postcode already exists": "Este código postal ya existe", + "Concept cannot be blank": "El concepto no puede quedar en blanco", + "File doesn't exists": "El archivo no existe", + "You don't have privileges to change the zone": "No tienes permisos para cambiar la zona", + "This ticket is already on weekly tickets": "Este ticket ya está en tickets programados", + "Ticket id cannot be blank": "El id de ticket no puede quedar en blanco", + "Weekday cannot be blank": "El día de la semana no puede quedar en blanco", + "You can't delete a confirmed order": "No puedes borrar un pedido confirmado", + "Can't create stowaway for this ticket": "No se puede crear un polizon para este ticket", + "The socialName has an invalid format": "El nombre fiscal tiene un formato incorrecto", + "Invalid quantity": "Cantidad invalida", + "This postal code is not valid": "This postal code is not valid", + "is invalid": "is invalid", + "The postcode doesn't exists. Ensure you put the correct format": "El código postal no existe. Asegúrate de ponerlo con el formato correcto", + "The department name can't be repeated": "El nombre del departamento no puede repetirse", + "This phone already exists": "Este teléfono ya existe", + "You cannot move a parent to its own sons": "No puedes mover un elemento padre a uno de sus hijos", + "You can't create a claim for a removed ticket": "No puedes crear una reclamación para un ticket eliminado", + "You cannot delete a ticket that part of it is being prepared": "No puedes eliminar un ticket en el que una parte que está siendo preparada", + "You must delete all the buy requests first": "Debes eliminar todas las peticiones de compra primero", + "Has deleted the ticket id": "Ha eliminado el ticket id [#{{id}}]({{{url}}})", + "You should specify a date": "Debes especificar una fecha", + "You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fín", + "Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fín", + "You should mark at least one week day": "Debes marcar al menos un día de la semana", + "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío" +} \ No newline at end of file diff --git a/loopback/package.json b/loopback/package.json new file mode 100644 index 000000000..08b9cd418 --- /dev/null +++ b/loopback/package.json @@ -0,0 +1,14 @@ +{ + "name": "vn-loopback", + "version": "1.0.0", + "main": "server/server.js", + "scripts": { + "start": "node ." + }, + "repository": { + "type": "git", + "url": "https://git.verdnatura.es/salix" + }, + "license": "GPL-3.0", + "description": "Loopback wrapper" +} diff --git a/loopback/server/boot/print.js b/loopback/server/boot/print.js new file mode 100644 index 000000000..0f6af4d56 --- /dev/null +++ b/loopback/server/boot/print.js @@ -0,0 +1,3 @@ +module.exports = function(app) { + require('../../../print/boot.js')(app); +}; diff --git a/services/loopback/server/boot/root.js b/loopback/server/boot/root.js similarity index 92% rename from services/loopback/server/boot/root.js rename to loopback/server/boot/root.js index d71fe0387..f70b32cb0 100644 --- a/services/loopback/server/boot/root.js +++ b/loopback/server/boot/root.js @@ -1,4 +1,3 @@ - module.exports = function(app) { let models = app.models(); models.forEach(function(model) { @@ -27,9 +26,11 @@ module.exports = function(app) { app.enableAuth(); - var router = app.loopback.Router(); + // eslint-disable-next-line new-cap + let router = app.loopback.Router(); router.get('/status', app.loopback.status()); app.use(router); + /* let ds = app.dataSources.auth; //ds.automigrate(function() { diff --git a/loopback/server/boot/salix.js b/loopback/server/boot/salix.js new file mode 100644 index 000000000..018389e40 --- /dev/null +++ b/loopback/server/boot/salix.js @@ -0,0 +1,9 @@ +module.exports = function(app) { + // FIXME: Fix until the original can be used + app.get('/api/modelInfo', function(req, res) { + app.models.Schema.modelInfo({req}).then(json => { + res.set('Content-Type', 'application/json'); + res.send(JSON.stringify(json)); + }); + }); +}; diff --git a/loopback/server/boot/storage.js b/loopback/server/boot/storage.js new file mode 100644 index 000000000..12662ab73 --- /dev/null +++ b/loopback/server/boot/storage.js @@ -0,0 +1,18 @@ +const uuid = require('uuid/v1'); +const md5 = require('md5'); + +module.exports = app => { + const storageConnector = app.dataSources.storage.connector; + + storageConnector.getFilename = function(file) { + return `${uuid()}.${storageConnector.getFileExtension(file.name)}`; + }; + + storageConnector.getFileExtension = function(fileName) { + return fileName.split('.').pop().toLowerCase(); + }; + + storageConnector.getPathHash = function(id) { + return md5(id.toString()).substring(0, 3); + }; +}; diff --git a/services/loopback/server/component-config.json b/loopback/server/component-config.json similarity index 100% rename from services/loopback/server/component-config.json rename to loopback/server/component-config.json diff --git a/services/loopback/server/config.json b/loopback/server/config.json similarity index 100% rename from services/loopback/server/config.json rename to loopback/server/config.json diff --git a/loopback/server/connectors/vn-mysql.js b/loopback/server/connectors/vn-mysql.js new file mode 100644 index 000000000..5c625be85 --- /dev/null +++ b/loopback/server/connectors/vn-mysql.js @@ -0,0 +1,222 @@ +const mysql = require('mysql'); +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const MySQL = require('loopback-connector-mysql').MySQL; +const EnumFactory = require('loopback-connector-mysql').EnumFactory; +const fs = require('fs'); + +class VnMySQL extends MySQL { + /** + * Promisified version of execute(). + * + * @param {String} query The SQL query string + * @param {Array} params The query parameters + * @param {Object} options The loopback options + * @param {Function} cb The callback + * @return {Promise} The operation promise + */ + executeP(query, params, options = {}, cb) { + return new Promise((resolve, reject) => { + this.execute(query, params, options, (error, response) => { + if (cb) + cb(error, response); + if (error) + reject(error); + else + resolve(response); + }); + }); + } + + /** + * Executes an SQL query from an Stmt. + * + * @param {ParameterizedSql} stmt - Stmt object + * @param {Object} options Query options (Ex: {transaction}) + * @return {Object} Connector promise + */ + executeStmt(stmt, options) { + return this.executeP(stmt.sql, stmt.params, options); + } + + /** + * Executes a query from an SQL script. + * + * @param {String} sqlScript The sql script file + * @param {Array} params The query parameters + * @param {Object} options Query options (Ex: {transaction}) + * @return {Object} Connector promise + */ + executeScript(sqlScript, params, options) { + return new Promise((resolve, reject) => { + fs.readFile(sqlScript, 'utf8', (err, contents) => { + if (err) return reject(err); + this.execute(contents, params, options) + .then(resolve, reject); + }); + }); + } + + /** + * Build the SQL WHERE clause for the where object without checking that + * properties exists in the model. + * + * @param {object} where An object for the where conditions + * @return {ParameterizedSQL} The SQL WHERE clause + */ + makeWhere(where) { + let wrappedConnector = Object.create(this); + Object.assign(wrappedConnector, { + getModelDefinition() { + return { + properties: new Proxy({}, { + get: () => true + }) + }; + }, + toColumnValue(_, val) { + return val; + }, + columnEscaped(_, property) { + return this.escapeName(property); + } + }); + + return wrappedConnector.buildWhere(null, where); + } + + /** + * Constructs SQL order clause from Loopback filter. + * + * @param {Object} order The order definition + * @return {String} Built SQL order + */ + makeOrderBy(order) { + if (!order) + return ''; + if (typeof order === 'string') + order = [order]; + + let clauses = []; + + for (let clause of order) { + let sqlOrder = ''; + let t = clause.split(/[\s,]+/); + + sqlOrder += this.escapeName(t[0]); + + if (t.length > 1) + sqlOrder += ' ' + (t[1].toUpperCase() == 'ASC' ? 'ASC' : 'DESC'); + + clauses.push(sqlOrder); + } + + return `ORDER BY ${clauses.join(', ')}`; + } + + /** + * Constructs SQL limit clause from Loopback filter. + * + * @param {Object} filter The loopback filter + * @return {String} Built SQL limit + */ + makeLimit(filter) { + let limit = parseInt(filter.limit); + let offset = parseInt(filter.offset || filter.skip); + return this._buildLimit(null, limit, offset); + } + + /** + * Constructs SQL pagination from Loopback filter. + * + * @param {Object} filter The loopback filter + * @return {String} Built SQL pagination + */ + makePagination(filter) { + return ParameterizedSQL.join([ + this.makeOrderBy(filter.order), + this.makeLimit(filter) + ]); + } + + /** + * Constructs SQL filter including where, order and limit + * clauses from Loopback filter. + * + * @param {Object} filter The loopback filter + * @return {String} Built SQL filter + */ + makeSuffix(filter) { + return ParameterizedSQL.join([ + this.makeWhere(filter.where), + this.makePagination(filter) + ]); + } + + /** + * Constructs SQL where clause from Loopback filter discarding + * properties that not pertain to the model. If defined, appends + * the table alias to each field. + * + * @param {String} model The model name + * @param {Object} where The loopback where filter + * @param {String} tableAlias Query main table alias + * @return {String} Built SQL where + */ + buildModelWhere(model, where, tableAlias) { + let parent = this; + let wrappedConnector = Object.create(this); + Object.assign(wrappedConnector, { + columnEscaped(model, property) { + let sql = tableAlias + ? this.escapeName(tableAlias) + '.' + : ''; + return sql + parent.columnEscaped(model, property); + } + }); + + return wrappedConnector.buildWhere(model, where); + } + + /** + * Constructs SQL where clause from Loopback filter discarding + * properties that not pertain to the model. If defined, appends + * the table alias to each field. + * + * @param {String} model The model name + * @param {Object} filter The loopback filter + * @param {String} tableAlias Query main table alias + * @return {String} Built SQL suffix + */ + buildModelSuffix(model, filter, tableAlias) { + return ParameterizedSQL.join([ + this.buildModelWhere(model, filter.where, tableAlias), + this.makePagination(filter) + ]); + } +} + +exports.VnMySQL = VnMySQL; + +exports.initialize = function initialize(dataSource, callback) { + dataSource.driver = mysql; + dataSource.connector = new VnMySQL(dataSource.settings); + dataSource.connector.dataSource = dataSource; + + const modelBuilder = dataSource.modelBuilder; + const defineType = modelBuilder.defineValueType ? + modelBuilder.defineValueType.bind(modelBuilder) : + modelBuilder.constructor.registerType.bind(modelBuilder.constructor); + + defineType(function Point() {}); + + dataSource.EnumFactory = EnumFactory; + + if (callback) { + if (dataSource.settings.lazyConnect) { + process.nextTick(function() { + callback(); + }); + } else + dataSource.connector.connect(callback); + } +}; diff --git a/loopback/server/datasources.json b/loopback/server/datasources.json new file mode 100644 index 000000000..0ea634484 --- /dev/null +++ b/loopback/server/datasources.json @@ -0,0 +1,40 @@ +{ + "db": { + "connector": "memory", + "timezone": "local" + }, + "vn": { + "connector": "vn-mysql", + "database": "vn", + "debug": false, + "host": "localhost", + "port": "3306", + "username": "root", + "password": "root", + "multipleStatements": true, + "legacyUtcDateProcessing": false, + "timezone": "local", + "connectTimeout": 40000, + "acquireTimeout": 20000 + }, + "storage": { + "name": "storage", + "connector": "loopback-component-storage", + "provider": "filesystem", + "root": "./e2e/dms", + "maxFileSize": "262144000", + "allowedContentTypes": [ + "application/x-7z-compressed", + "application/x-zip-compressed", + "application/x-rar-compressed", + "application/octet-stream", + "application/pdf", + "application/zip", + "application/rar", + "multipart/x-zip", + "image/png", + "image/jpeg", + "image/jpg" + ] + } +} diff --git a/services/loopback/server/middleware.development.json b/loopback/server/middleware.development.json similarity index 100% rename from services/loopback/server/middleware.development.json rename to loopback/server/middleware.development.json diff --git a/services/loopback/server/middleware.json b/loopback/server/middleware.json similarity index 77% rename from services/loopback/server/middleware.json rename to loopback/server/middleware.json index f502a94e2..60bedcdb3 100644 --- a/services/loopback/server/middleware.json +++ b/loopback/server/middleware.json @@ -1,18 +1,7 @@ { - "initial:before": { - "loopback#favicon": { - "params": "$!../favicon.ico" - } - }, + "initial:before": {}, "initial": { "compression": {}, - "cors": { - "params": { - "origin": "*", - "credentials": true, - "maxAge": 86400 - } - }, "helmet#xssFilter": {}, "helmet#frameguard": { "params": [ @@ -22,7 +11,7 @@ "helmet#hsts": { "params": { "maxAge": 0, - "includeSubdomains": true + "includeSubDomains": true } }, "helmet#hidePoweredBy": {}, @@ -60,6 +49,10 @@ }, "final:after": { "./middleware/error-handler": {}, - "strong-error-handler": {} + "strong-error-handler": { + "params": { + "log": false + } + } } } diff --git a/services/loopback/server/middleware/current-user.js b/loopback/server/middleware/current-user.js similarity index 89% rename from services/loopback/server/middleware/current-user.js rename to loopback/server/middleware/current-user.js index 253d09f83..a6624351e 100644 --- a/services/loopback/server/middleware/current-user.js +++ b/loopback/server/middleware/current-user.js @@ -6,9 +6,9 @@ module.exports = function(options) { let LoopBackContext = require('loopback-context'); let loopbackContext = LoopBackContext.getCurrentContext(); - if (loopbackContext) { + if (loopbackContext) loopbackContext.set('currentUser', req.accessToken.userId); - } + next(); }; }; diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js new file mode 100644 index 000000000..725826ae7 --- /dev/null +++ b/loopback/server/middleware/error-handler.js @@ -0,0 +1,38 @@ +const UserError = require('../../util/user-error'); +const logToConsole = require('strong-error-handler/lib/logger'); + +module.exports = function() { + return function(err, req, res, next) { + // Thrown user errors + if (err instanceof UserError) { + err.message = req.__(err.message, ...err.translateArgs); + return next(err); + } + + // Validation errors + if (err.statusCode == 422) { + try { + let code; + let messages = err.details.messages; + for (code in messages) break; + err.message = req.__(messages[code][0]); + return next(err); + } catch (e) {} + } + + // MySQL user-defined exceptions + if (err.sqlState == '45000') + return next(new UserError(req.__(err.sqlMessage))); + + // Logs error to console + + let env = process.env.NODE_ENV; + let useCustomLogging = env && env != 'development' && + (!err.statusCode || err.statusCode >= 500); + + if (useCustomLogging) + logToConsole(req, err); + + next(err); + }; +}; diff --git a/loopback/server/model-config.json b/loopback/server/model-config.json new file mode 100644 index 000000000..20e22accd --- /dev/null +++ b/loopback/server/model-config.json @@ -0,0 +1,53 @@ +{ + "AccessToken": { + "dataSource": "vn", + "options": { + "mysql": { + "table": "salix.AccessToken" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "user", + "foreignKey": "userId" + } + } + }, + "ACL": { + "dataSource": "vn", + "options": { + "mysql": { + "table": "salix.ACL" + } + } + }, + "FieldAcl": { + "dataSource": "vn" + }, + "Role": { + "dataSource": "vn", + "options": { + "mysql": { + "table": "salix.Role" + } + } + }, + "RoleMapping": { + "dataSource": "vn", + "options": { + "mysql": { + "table": "salix.RoleMapping" + } + } + }, + "user": { + "dataSource": "vn" + }, + "Schema": { + "dataSource": "vn" + }, + "Application": { + "dataSource": "vn" + } +} \ No newline at end of file diff --git a/loopback/server/server.js b/loopback/server/server.js new file mode 100644 index 000000000..188b5eb0f --- /dev/null +++ b/loopback/server/server.js @@ -0,0 +1,139 @@ +require('require-yaml'); +const loopback = require('loopback'); +const boot = require('loopback-boot'); +const DataSource = require('loopback-datasource-juggler').DataSource; +const fs = require('fs-extra'); +const i18n = require('i18n'); +const path = require('path'); + +let _resolveConnector = DataSource._resolveConnector; +DataSource._resolveConnector = function(...args) { + let name = args[0]; + let testPath = `${__dirname}/connectors/${name}.js`; + + if (fs.existsSync(testPath)) { + return { + connector: require(testPath), + error: null + }; + } + + return _resolveConnector.apply(this, args); +}; + +let app = loopback(); +module.exports = app; + +// Configuration + +let rootDir = __dirname; +let lbDir = path.resolve(`${rootDir}/..`); +let appDir = path.resolve(`${__dirname}/../..`); +let localeDir = `${lbDir}/locale`; +let modulesDir = `${appDir}/modules`; + +// Internationalization + +app.disconnect = async function() { + let promises = []; + for (let ds in this.dataSources) + promises.push(this.dataSources[ds].disconnect()); + return await Promise.all(promises); +}; + +app.start = function(bootOptions, port, callback) { + let onListen = () => { + let baseUrl = this.get('url').replace(/\/$/, ''); + let explorerPath = this.get('loopback-component-explorer').mountPath; + console.log(`Browse your REST API at: %s`, `${baseUrl}${explorerPath}`); + this.emit('started'); + callback && callback(); + }; + + this.boot(bootOptions, err => { + if (err) throw err; + let args = port ? [port, onListen] : [onListen]; + return this.listen(...args); + }); +}; + +app.boot = function(bootOptions, callback) { + // Internatinalization + + if (fs.existsSync(localeDir)) { + i18n.configure({ + directory: localeDir, + defaultLocale: 'es' + }); + + this.use(i18n.init); + } + + // Initialization + + let config = require('./config.json'); + + for (let key in config) + this.set(key, config[key]); + + let modelConfigFiles = [ + `${__dirname}/model-config.json` + ]; + let modelSources = [ + `loopback/common/models`, + `loopback/server/models`, + `${__dirname}/../common/models` + ]; + let mixinDirs = [ + `loopback/common/mixins`, + `loopback/server/mixins`, + `${__dirname}/../common/mixins` + ]; + let bootDirs = [ + `${__dirname}/boot` + ]; + + addPath(`${appDir}/back`); + + let modules = fs.readdirSync(modulesDir); + for (let mod of modules) + addPath(`${modulesDir}/${mod}/back`); + + function addPath(path) { + modelConfigFiles.push(`${path}/model-config.json`); + modelSources.push(`${path}/models`); + mixinDirs.push(`${path}/mixins`); + bootDirs.push(`${path}/boot`); + } + + let models = {}; + for (file of modelConfigFiles) { + if (fs.existsSync(file)) { + let fileModels = require(file); + for (let key in fileModels) { + if (models[key]) + console.warn(`Redeclaration of '${key}' at ${file}`); + } + Object.assign(models, fileModels); + } + } + + let myBootOptions = { + appRootDir: __dirname, + appConfigRootDir: rootDir, + modelsRootDir: rootDir, + models: models, + modelSources: modelSources, + mixinDirs: mixinDirs, + bootDirs: bootDirs + }; + + if (fs.existsSync(`/etc/salix`)) + myBootOptions.dsRootDir = `/etc/salix`; + + Object.assign(myBootOptions, bootOptions); + boot(this, myBootOptions, callback); +}; + +if (require.main === module) + app.start(); diff --git a/loopback/util/filter.js b/loopback/util/filter.js new file mode 100644 index 000000000..0681c41c1 --- /dev/null +++ b/loopback/util/filter.js @@ -0,0 +1,113 @@ + +/** + * Passes a loopback fields filter to an object. + * + * @param {Object} fields The fields object or array + * @return {Object} The fields as object + */ +function fieldsToObject(fields) { + let fieldsObj = {}; + + if (Array.isArray(fields)) { + for (let field of fields) + fieldsObj[field] = true; + } else if (typeof fields == 'object') { + for (let field in fields) { + if (fields[field]) + fieldsObj[field] = true; + } + } + + return fieldsObj; +} + +/** + * Merges two loopback fields filters. + * + * @param {Object|Array} src The source fields + * @param {Object|Array} dst The destination fields + * @return {Array} The merged fields as an array + */ +function mergeFields(src, dst) { + let fields = {}; + Object.assign(fields, + fieldsToObject(src), + fieldsToObject(dst) + ); + return Object.keys(fields); +} + +/** + * Merges two loopback where filters. + * + * @param {Object|Array} src The source where + * @param {Object|Array} dst The destination where + * @return {Array} The merged wheres + */ +function mergeWhere(src, dst) { + let and = []; + if (src) and.push(src); + if (dst) and.push(dst); + return simplifyOperation(and, 'and'); +} + +/** + * Merges two loopback filters returning the merged filter. + * + * @param {Object} src The source filter + * @param {Object} dst The destination filter + * @return {Object} The result filter + */ +function mergeFilters(src, dst) { + let res = Object.assign({}, dst); + + if (!src) + return res; + + if (src.fields) + res.fields = mergeFields(src.fields, res.fields); + if (src.where) + res.where = mergeWhere(res.where, src.where); + if (src.include) + res.include = src.include; + if (src.order) + res.order = src.order; + if (src.limit) + res.limit = src.limit; + if (src.offset) + res.offset = src.offset; + if (src.skip) + res.skip = src.skip; + + return res; +} + +function simplifyOperation(operation, operator) { + switch (operation.length) { + case 0: + return undefined; + case 1: + return operation[0]; + default: + return {[operator]: operation}; + } +} + +function buildFilter(params, builderFunc) { + let and = []; + for (let param in params) { + let value = params[param]; + if (value == null) continue; + let expr = builderFunc(param, value); + if (expr) and.push(expr); + } + return simplifyOperation(and, 'and'); +} + +module.exports = { + fieldsToObject: fieldsToObject, + mergeFields: mergeFields, + mergeWhere: mergeWhere, + mergeFilters: mergeFilters, + buildFilter: buildFilter +}; diff --git a/loopback/util/hook.js b/loopback/util/hook.js new file mode 100644 index 000000000..fcd3476de --- /dev/null +++ b/loopback/util/hook.js @@ -0,0 +1,29 @@ + +/** + * Computes the final instance state after hook is executed. + * + * @param {Object} ctx The hook context + * @return {Object} The final instance state + */ +exports.getFinalState = function(ctx) { + if (ctx.isNewInstance) + return ctx.instance; + if (ctx.currentInstance) { + return Object.assign({}, + ctx.currentInstance.__data, + ctx.data || ctx.instance + ); + } + + return null; +}; + +/** + * Determines if hook is affecting multiple instances. + * + * @param {Object} ctx The hook context + * @return {Boolean} %true for multiple instances, %false otherwhise + */ +exports.isMultiple = function(ctx) { + return !ctx.isNewInstance && !ctx.currentInstance; +}; diff --git a/loopback/util/http.js b/loopback/util/http.js new file mode 100644 index 000000000..59bfe38b0 --- /dev/null +++ b/loopback/util/http.js @@ -0,0 +1,16 @@ +/** + * Serializes an object to a query params + * + * @param {Object} obj The params object + * @return {String} Serialized params + */ +exports.httpParamSerializer = function(obj) { + let query = ''; + for (let param in obj) { + if (query != '') + query += '&'; + query += `${param}=${obj[param]}`; + } + + return query; +}; diff --git a/loopback/util/user-error.js b/loopback/util/user-error.js new file mode 100644 index 000000000..c2d01e080 --- /dev/null +++ b/loopback/util/user-error.js @@ -0,0 +1,15 @@ +/** + * Class used for user-readable errors. All thrown errors of this + * class will be translated, propagated to the client and displayed to + * the final user, so they cannot contain sensitive data and must + * be understandable by people who do not have a technical profile. + */ +module.exports = class UserError extends Error { + constructor(message, code, ...translateArgs) { + super(message); + this.name = 'UserError'; + this.statusCode = 400; + this.code = code; + this.translateArgs = translateArgs; + } +}; diff --git a/modules/agency/back/methods/agency/getAgenciesWithWarehouse.js b/modules/agency/back/methods/agency/getAgenciesWithWarehouse.js new file mode 100644 index 000000000..3a806ce44 --- /dev/null +++ b/modules/agency/back/methods/agency/getAgenciesWithWarehouse.js @@ -0,0 +1,34 @@ +module.exports = Self => { + Self.remoteMethod('getAgenciesWithWarehouse', { + description: 'Returns a list of agencies that can land a shipment on a day for an address and a warehouse', + accepts: [ + { + arg: 'addressFk', + type: 'number', + required: true + }, { + arg: 'landed', + type: 'date', + required: true + }, { + arg: 'warehouseFk', + type: 'number', + required: true + } + ], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getAgenciesWithWarehouse`, + verb: 'get' + } + }); + + Self.getAgenciesWithWarehouse = async(addressFk, landed, warehouseFk) => { + let query = `CALL vn.zone_getWarehouse(?, ?, ?)`; + let [result] = await Self.rawSql(query, [addressFk, landed, warehouseFk]); + return result; + }; +}; diff --git a/modules/agency/back/methods/agency/getLanded.js b/modules/agency/back/methods/agency/getLanded.js new file mode 100644 index 000000000..6c5a5d911 --- /dev/null +++ b/modules/agency/back/methods/agency/getLanded.js @@ -0,0 +1,57 @@ +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('getLanded', { + description: 'Returns the first shipped and landed possible for params', + accessType: 'READ', + accepts: [{ + arg: 'shipped', + type: 'date', + required: true + }, + { + arg: 'addressFk', + type: 'number', + required: true + }, + { + arg: 'agencyModeFk', + type: 'number', + required: true + }, + { + arg: 'warehouseFk', + type: 'number', + required: true + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/getLanded`, + verb: 'get' + } + }); + + Self.getLanded = async(shipped, addressFk, agencyModeFk, warehouseFk) => { + let stmts = []; + stmts.push(new ParameterizedSQL( + `CALL vn.zone_getLanded(?, ?, ?, ?)`, [ + shipped, + addressFk, + agencyModeFk, + warehouseFk + ] + )); + + let rsIndex = stmts.push( + `SELECT * FROM tmp.zoneGetLanded`) - 1; + stmts.push(`DROP TEMPORARY TABLE tmp.zoneGetLanded`); + + let sql = ParameterizedSQL.join(stmts, ';'); + let landed = await Self.rawStmt(sql); + + return landed[rsIndex][0]; + }; +}; diff --git a/modules/agency/back/methods/agency/getShipped.js b/modules/agency/back/methods/agency/getShipped.js new file mode 100644 index 000000000..1e6051696 --- /dev/null +++ b/modules/agency/back/methods/agency/getShipped.js @@ -0,0 +1,58 @@ +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('getShipped', { + description: 'Returns the first shipped possible for params', + accessType: 'READ', + accepts: [{ + arg: 'landed', + type: 'date', + required: true + }, + { + arg: 'addressFk', + type: 'number', + required: true + }, + { + arg: 'agencyModeFk', + type: 'number', + required: true + }, + { + arg: 'warehouseFk', + type: 'number', + required: true + }], + returns: { + type: 'date', + root: true + }, + http: { + path: `/getShipped`, + verb: 'get' + } + }); + + Self.getShipped = async(landed, addressFk, agencyModeFk, warehouseFk)=> { + let stmts = []; + stmts.push(new ParameterizedSQL( + `CALL vn.zone_getShippedWarehouse(?, ?, ?)`, [ + landed, + addressFk, + agencyModeFk + ] + )); + + let rsIndex = stmts.push(new ParameterizedSQL( + `SELECT * FROM tmp.zoneGetShipped WHERE warehouseFk = ?`, [ + warehouseFk + ] + )) - 1; + + let sql = ParameterizedSQL.join(stmts, ';'); + let shipped = await Self.rawStmt(sql); + + return shipped[rsIndex][0]; + }; +}; diff --git a/modules/agency/back/methods/agency/landsThatDay.js b/modules/agency/back/methods/agency/landsThatDay.js new file mode 100644 index 000000000..87da63767 --- /dev/null +++ b/modules/agency/back/methods/agency/landsThatDay.js @@ -0,0 +1,35 @@ +module.exports = Self => { + Self.remoteMethod('landsThatDay', { + description: 'Returns a list of agencies that can land a shipment on a day for an address', + accepts: [ + { + arg: 'addressFk', + type: 'number', + required: true + }, { + arg: 'landed', + type: 'date', + required: true + } + ], + returns: { + type: 'object', + root: true + }, + http: { + path: `/landsThatDay`, + verb: 'get' + } + }); + + Self.landsThatDay = async(addressFk, landed) => { + let query = ` + CALL vn.zone_getAgency(?, ?); + SELECT * FROM tmp.zoneGetAgency; + DROP TEMPORARY TABLE tmp.zoneGetAgency; + `; + let result = await Self.rawSql(query, [addressFk, landed]); + + return result[1]; + }; +}; diff --git a/modules/agency/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js b/modules/agency/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js new file mode 100644 index 000000000..614c33519 --- /dev/null +++ b/modules/agency/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js @@ -0,0 +1,19 @@ +const app = require('vn-loopback/server/server'); + +describe('Agency getAgenciesWithWarehouse()', () => { + const today = new Date(); + it('should return the agencies that can handle the given delivery request', async() => { + let agencies = await app.models.Agency.getAgenciesWithWarehouse(101, today, 1); + + expect(agencies.length).toEqual(3); + expect(agencies[0].agencyMode).toEqual('inhouse pickup'); + expect(agencies[1].agencyMode).toEqual('Other agency'); + expect(agencies[2].agencyMode).toEqual('Refund'); + }); + + it('should return no agencies if the date is incorrect', async() => { + let agencies = await app.models.Agency.getAgenciesWithWarehouse(101, null, 1); + + expect(agencies.length).toEqual(0); + }); +}); diff --git a/modules/agency/back/methods/agency/specs/getLanded.spec.js b/modules/agency/back/methods/agency/specs/getLanded.spec.js new file mode 100644 index 000000000..15c0f1ca9 --- /dev/null +++ b/modules/agency/back/methods/agency/specs/getLanded.spec.js @@ -0,0 +1,14 @@ +const app = require('vn-loopback/server/server'); + +describe('agency getLanded()', () => { + it('should return a landing date', async() => { + const shipped = new Date(); + shipped.setDate(shipped.getDate() + 1); + const addressFk = 121; + const agencyModeFk = 7; + const warehouseFk = 1; + let result = await app.models.Agency.getLanded(shipped, addressFk, agencyModeFk, warehouseFk); + + expect(result.landed).toBeDefined(); + }); +}); diff --git a/modules/agency/back/methods/agency/specs/getShipped.spec.js b/modules/agency/back/methods/agency/specs/getShipped.spec.js new file mode 100644 index 000000000..8f79dab3b --- /dev/null +++ b/modules/agency/back/methods/agency/specs/getShipped.spec.js @@ -0,0 +1,29 @@ +const app = require('vn-loopback/server/server'); + +describe('agency getShipped()', () => { + it('should return a shipment date', async() => { + const landed = new Date(); + landed.setDate(landed.getDate() + 1); + const addressFk = 121; + const agencyModeFk = 7; + const warehouseFk = 1; + + let result = await app.models.Agency.getShipped(landed, addressFk, agencyModeFk, warehouseFk); + + expect(result).toBeDefined(); + }); + + it('should not return a shipment date', async() => { + let newDate = new Date(); + newDate.setMonth(newDate.getMonth() - 1); + + const landed = newDate; + const addressFk = 121; + const agencyModeFk = 7; + const warehouseFk = 1; + + let result = await app.models.Agency.getShipped(landed, addressFk, agencyModeFk, warehouseFk); + + expect(result).toBeUndefined(); + }); +}); diff --git a/modules/agency/back/methods/agency/specs/landsThatDay.spec.js b/modules/agency/back/methods/agency/specs/landsThatDay.spec.js new file mode 100644 index 000000000..c6738afc3 --- /dev/null +++ b/modules/agency/back/methods/agency/specs/landsThatDay.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('Agency landsThatDay()', () => { + const today = new Date(); + it('should return a list of agencies that can land a shipment on a day for an address', async() => { + let agencies = await app.models.Agency.landsThatDay(101, today); + + expect(agencies.length).toBeGreaterThanOrEqual(3); + }); +}); diff --git a/modules/agency/back/methods/zone/clone.js b/modules/agency/back/methods/zone/clone.js new file mode 100644 index 000000000..fcae904b5 --- /dev/null +++ b/modules/agency/back/methods/zone/clone.js @@ -0,0 +1,74 @@ +module.exports = Self => { + Self.remoteMethod('clone', { + description: 'Clone zone and all its properties including geolocations', + accessType: 'WRITE', + accepts: { + arg: 'id', + type: 'number', + required: true, + description: 'Zone id', + http: {source: 'path'} + }, + returns: { + root: true, + type: 'Object' + }, + http: { + path: '/:id/clone', + verb: 'POST' + } + }); + + Self.clone = async id => { + const models = Self.app.models; + const tx = await Self.beginTransaction({}); + + try { + let options = {transaction: tx}; + + // Find original zone + const zone = await models.Zone.findOne({ + fields: [ + 'name', + 'hour', + 'agencyModeFk', + 'travelingDays', + 'price', + 'bonus', + 'isVolumetric'], + where: {id} + }, options); + + // Find all original included geolocations + const includedGeo = await models.ZoneIncluded.find({ + fields: ['geoFk', 'isIncluded'], + where: {zoneFk: id} + }, options); + + // Find all original selected days + const calendarDays = await models.ZoneEvent.find({ + fields: {id: false}, + where: {zoneFk: id} + }, options); + + const newZone = await Self.create(zone, options); + const newIncludedGeo = includedGeo.map(included => { + included.zoneFk = newZone.id; + return included; + }); + const newCalendayDays = calendarDays.map(day => { + day.zoneFk = newZone.id; + return day; + }); + + await models.ZoneIncluded.create(newIncludedGeo, options); + await models.ZoneEvent.create(newCalendayDays, options); + await tx.commit(); + + return newZone; + } catch (e) { + await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/agency/back/methods/zone/getEvents.js b/modules/agency/back/methods/zone/getEvents.js new file mode 100644 index 000000000..abf3d7e19 --- /dev/null +++ b/modules/agency/back/methods/zone/getEvents.js @@ -0,0 +1,38 @@ + +module.exports = Self => { + Self.remoteMethod('getEvents', { + description: 'Returns delivery days for a postcode', + accepts: [ + { + arg: 'provinceFk', + type: 'Number', + description: 'The province id', + required: true + }, { + arg: 'postCode', + type: 'String', + description: 'The postcode' + }, { + arg: 'agencyModeFk', + type: 'Number', + description: 'The agency mode id' + } + ], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/getEvents`, + verb: 'GET' + } + }); + + Self.getEvents = async(provinceFk, postCode, agencyModeFk) => { + let [events, exclusions] = await Self.rawSql( + `CALL zone_getEvents(?, ?, ?)`, + [provinceFk, postCode, agencyModeFk] + ); + return {events, exclusions}; + }; +}; diff --git a/modules/agency/back/methods/zone/getLeaves.js b/modules/agency/back/methods/zone/getLeaves.js new file mode 100644 index 000000000..c45136d4f --- /dev/null +++ b/modules/agency/back/methods/zone/getLeaves.js @@ -0,0 +1,58 @@ + +module.exports = Self => { + Self.remoteMethod('getLeaves', { + description: 'Returns the nodes for a zone', + accepts: [ + { + arg: 'id', + type: 'Number', + description: 'The zone id', + http: {source: 'path'}, + required: true + }, { + arg: 'parentId', + type: 'Number', + description: 'Get the children of the specified father', + }, { + arg: 'search', + type: 'String', + description: 'Filter nodes whose name starts with', + } + ], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/:id/getLeaves`, + verb: 'GET' + } + }); + + Self.getLeaves = async(id, parentId = null, search) => { + let [res] = await Self.rawSql( + `CALL zone_getLeaves(?, ?, ?)`, + [id, parentId, search] + ); + + let map = new Map(); + for (let node of res) { + if (!map.has(node.parentFk)) + map.set(node.parentFk, []); + map.get(node.parentFk).push(node); + } + + function setLeaves(nodes) { + if (!nodes) return; + for (let node of nodes) { + node.childs = map.get(node.id); + setLeaves(node.childs); + } + } + + let leaves = map.get(parentId); + setLeaves(leaves); + + return leaves || []; + }; +}; diff --git a/modules/agency/back/methods/zone/specs/clone.spec.js b/modules/agency/back/methods/zone/specs/clone.spec.js new file mode 100644 index 000000000..a68bef5d8 --- /dev/null +++ b/modules/agency/back/methods/zone/specs/clone.spec.js @@ -0,0 +1,17 @@ +const app = require('vn-loopback/server/server'); + +describe('agency clone()', () => { + let newZone; + + afterAll(async done => { + await app.models.Zone.destroyById(newZone.id); + done(); + }); + + it('should clone a zone', async() => { + newZone = await app.models.Zone.clone(1); + + expect(newZone.name).toEqual('Zone pickup A'); + }); +}); + diff --git a/modules/agency/back/methods/zone/toggleIsIncluded.js b/modules/agency/back/methods/zone/toggleIsIncluded.js new file mode 100644 index 000000000..ae8f7c571 --- /dev/null +++ b/modules/agency/back/methods/zone/toggleIsIncluded.js @@ -0,0 +1,41 @@ +module.exports = Self => { + Self.remoteMethod('toggleIsIncluded', { + description: 'Toggle include to delivery', + accepts: [{ + arg: 'id', + type: 'Number', + description: 'The zone id', + http: {source: 'path'}, + required: true + }, { + arg: 'geoId', + type: 'Number', + required: true + }, { + arg: 'isIncluded', + type: 'Boolean' + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/toggleIsIncluded`, + verb: 'POST' + } + }); + + Self.toggleIsIncluded = async(id, geoId, isIncluded) => { + const models = Self.app.models; + + if (isIncluded === undefined) + return models.ZoneIncluded.destroyAll({zoneFk: id, geoFk: geoId}); + else { + return models.ZoneIncluded.upsert({ + zoneFk: id, + geoFk: geoId, + isIncluded: isIncluded + }); + } + }; +}; diff --git a/modules/agency/back/model-config.json b/modules/agency/back/model-config.json new file mode 100644 index 000000000..cfdbb83d3 --- /dev/null +++ b/modules/agency/back/model-config.json @@ -0,0 +1,29 @@ +{ + "Agency": { + "dataSource": "vn" + }, + "AgencyMode": { + "dataSource": "vn" + }, + "DeliveryMethod": { + "dataSource": "vn" + }, + "Zone": { + "dataSource": "vn" + }, + "ZoneGeo": { + "dataSource": "vn" + }, + "ZoneEvent": { + "dataSource": "vn" + }, + "ZoneExclusion": { + "dataSource": "vn" + }, + "ZoneIncluded": { + "dataSource": "vn" + }, + "ZoneWarehouse": { + "dataSource": "vn" + } +} diff --git a/modules/agency/back/models/agency-mode.json b/modules/agency/back/models/agency-mode.json new file mode 100644 index 000000000..5d6814dc8 --- /dev/null +++ b/modules/agency/back/models/agency-mode.json @@ -0,0 +1,73 @@ +{ + "name": "AgencyMode", + "description": "Agency modes", + "base": "VnModel", + "options": { + "mysql": { + "table": "agencyMode" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "name": { + "type": "string", + "required": true + }, + "description": { + "type": "string" + }, + "deliveryMethodFk":{ + "type": "number" + }, + "m3": { + "type": "Number" + }, + "inflation": { + "type": "Number" + }, + "reportMail": { + "type": "string" + }, + "isActive":{ + "type": "boolean" + }, + "code": { + "type": "String", + "required": false + } + }, + "relations": { + "agency": { + "type": "belongsTo", + "model": "Agency", + "foreignKey": "agencyFk" + }, + "agencyType": { + "type": "belongsTo", + "model": "AgencyType", + "foreignKey": "agencyTypeFk" + }, + "deliveryMethod": { + "type": "belongsTo", + "model": "DeliveryMethod", + "foreignKey": "deliveryMethodFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ], + "scopes" : { + "isActive" : { + "where": {"isActive": {"neq": false}} + } + } +} \ No newline at end of file diff --git a/modules/agency/back/models/agency.js b/modules/agency/back/models/agency.js new file mode 100644 index 000000000..d921e7774 --- /dev/null +++ b/modules/agency/back/models/agency.js @@ -0,0 +1,6 @@ +module.exports = Self => { + require('../methods/agency/landsThatDay')(Self); + require('../methods/agency/getAgenciesWithWarehouse')(Self); + require('../methods/agency/getLanded')(Self); + require('../methods/agency/getShipped')(Self); +}; diff --git a/services/loopback/common/models/agency.json b/modules/agency/back/models/agency.json similarity index 100% rename from services/loopback/common/models/agency.json rename to modules/agency/back/models/agency.json diff --git a/modules/agency/back/models/delivery-method.json b/modules/agency/back/models/delivery-method.json new file mode 100644 index 000000000..8106c1d4f --- /dev/null +++ b/modules/agency/back/models/delivery-method.json @@ -0,0 +1,32 @@ +{ + "name": "DeliveryMethod", + "description": "Delivery methods", + "base": "VnModel", + "options": { + "mysql": { + "table": "deliveryMethod" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "code": { + "type": "string", + "required": true + }, + "description": { + "type": "string" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/modules/agency/back/models/zone-event.js b/modules/agency/back/models/zone-event.js new file mode 100644 index 000000000..6af031a23 --- /dev/null +++ b/modules/agency/back/models/zone-event.js @@ -0,0 +1,35 @@ +module.exports = Self => { + Self.validate('range', function(err) { + if (this.type == 'range' + && !this.started + && !this.ended) + err(); + }, { + message: `You should specify at least a start or end date` + }); + + Self.validate('validRange', function(err) { + if (this.type == 'range' + && this.started + && this.ended + && this.started >= this.ended) + err(); + }, { + message: `Start date should be lower than end date` + }); + + Self.validate('dated', function(err) { + if (this.type == 'day' && !this.dated) + err(); + }, { + message: `You should specify a date` + }); + + Self.validate('weekDays', function(err) { + if (['range', 'indefinitely'].indexOf(this.type) !== -1 + && !this.weekDays) + err(); + }, { + message: `You should mark at least one week day` + }); +}; diff --git a/modules/agency/back/models/zone-event.json b/modules/agency/back/models/zone-event.json new file mode 100644 index 000000000..0d46b1fe2 --- /dev/null +++ b/modules/agency/back/models/zone-event.json @@ -0,0 +1,53 @@ +{ + "name": "ZoneEvent", + "base": "VnModel", + "options": { + "mysql": { + "table": "zoneEvent" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "zoneFk": { + "id": true, + "type": "Number" + }, + "type": { + "type": "String" + }, + "dated": { + "type": "Date" + }, + "started": { + "type": "Date" + }, + "ended": { + "type": "Date" + }, + "weekDays": { + "type": "String" + }, + "hour": { + "type": "Date" + }, + "travelingDays": { + "type": "Number" + }, + "price": { + "type": "Number" + }, + "bonus": { + "type": "Number" + } + }, + "relations": { + "zone": { + "type": "belongsTo", + "model": "Zone", + "foreignKey": "zoneFk" + } + } +} \ No newline at end of file diff --git a/modules/agency/back/models/zone-exclusion.json b/modules/agency/back/models/zone-exclusion.json new file mode 100644 index 000000000..f1c80debd --- /dev/null +++ b/modules/agency/back/models/zone-exclusion.json @@ -0,0 +1,26 @@ +{ + "name": "ZoneExclusion", + "base": "VnModel", + "options": { + "mysql": { + "table": "zoneExclusion" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "dated": { + "type": "Date", + "required": true + } + }, + "relations": { + "zone": { + "type": "belongsTo", + "model": "Zone", + "foreignKey": "zoneFk" + } + } +} \ No newline at end of file diff --git a/modules/agency/back/models/zone-geo.json b/modules/agency/back/models/zone-geo.json new file mode 100644 index 000000000..0a001235f --- /dev/null +++ b/modules/agency/back/models/zone-geo.json @@ -0,0 +1,30 @@ +{ + "name": "ZoneGeo", + "base": "VnModel", + "options": { + "mysql": { + "table": "zoneGeo" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "name": { + "type": "String" + }, + "lft": { + "type": "Number" + }, + "rgt": { + "type": "Number" + }, + "depth": { + "type": "Number" + }, + "sons": { + "type": "Number" + } + } +} \ No newline at end of file diff --git a/modules/agency/back/models/zone-included.json b/modules/agency/back/models/zone-included.json new file mode 100644 index 000000000..9f9508824 --- /dev/null +++ b/modules/agency/back/models/zone-included.json @@ -0,0 +1,30 @@ +{ + "name": "ZoneIncluded", + "base": "VnModel", + "options": { + "mysql": { + "table": "zoneIncluded" + } + }, + "properties": { + "zoneFk": { + "id": true, + "type": "Number" + }, + "isIncluded": { + "type": "Boolean" + } + }, + "relations": { + "zone": { + "type": "belongsTo", + "model": "Zone", + "foreignKey": "zoneFk" + }, + "geo": { + "type": "belongsTo", + "model": "ZoneGeo", + "foreignKey": "geoFk" + } + } +} \ No newline at end of file diff --git a/modules/agency/back/models/zone-warehouse.json b/modules/agency/back/models/zone-warehouse.json new file mode 100644 index 000000000..afb3bc2b4 --- /dev/null +++ b/modules/agency/back/models/zone-warehouse.json @@ -0,0 +1,27 @@ +{ + "name": "ZoneWarehouse", + "base": "VnModel", + "options": { + "mysql": { + "table": "zoneWarehouse" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + } + }, + "relations": { + "zone": { + "type": "belongsTo", + "model": "Zone", + "foreignKey": "zoneFk" + }, + "warehouse": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseFk" + } + } +} \ No newline at end of file diff --git a/modules/agency/back/models/zone.js b/modules/agency/back/models/zone.js new file mode 100644 index 000000000..0c3ac24f6 --- /dev/null +++ b/modules/agency/back/models/zone.js @@ -0,0 +1,10 @@ +module.exports = Self => { + require('../methods/zone/clone')(Self); + require('../methods/zone/getLeaves')(Self); + require('../methods/zone/getEvents')(Self); + require('../methods/zone/toggleIsIncluded')(Self); + + Self.validatesPresenceOf('agencyModeFk', { + message: `Agency cannot be blank` + }); +}; diff --git a/modules/agency/back/models/zone.json b/modules/agency/back/models/zone.json new file mode 100644 index 000000000..853f1f4d2 --- /dev/null +++ b/modules/agency/back/models/zone.json @@ -0,0 +1,65 @@ +{ + "name": "Zone", + "base": "VnModel", + "options": { + "mysql": { + "table": "zone" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "name": { + "type": "String", + "required": true + }, + "hour": { + "type": "date", + "required": true + }, + "travelingDays": { + "type": "Number" + }, + "price": { + "type": "Number" + }, + "bonus": { + "type": "Number" + }, + "isVolumetric": { + "type": "Boolean" + }, + "inflation": { + "type": "Number" + } + }, + "relations": { + "geolocations": { + "type": "hasMany", + "model": "ZoneGeo", + "foreignKey": "zoneFk" + }, + "agencyMode": { + "type": "belongsTo", + "model": "AgencyMode", + "foreignKey": "agencyModeFk" + }, + "events": { + "type": "hasMany", + "model": "ZoneEvent", + "foreignKey": "zoneFk" + }, + "exclusions": { + "type": "hasMany", + "model": "ZoneExclusion", + "foreignKey": "zoneFk" + }, + "warehouses": { + "type": "hasMany", + "model": "ZoneWarehouse", + "foreignKey": "zoneFk" + } + } +} \ No newline at end of file diff --git a/modules/agency/front/basic-data/index.html b/modules/agency/front/basic-data/index.html new file mode 100644 index 000000000..ec5cc3b20 --- /dev/null +++ b/modules/agency/front/basic-data/index.html @@ -0,0 +1,100 @@ + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/modules/agency/front/basic-data/index.js b/modules/agency/front/basic-data/index.js new file mode 100644 index 000000000..a730ed362 --- /dev/null +++ b/modules/agency/front/basic-data/index.js @@ -0,0 +1,27 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $state) { + this.$scope = $scope; + this.$state = $state; + } + + onSubmit() { + this.$scope.watcher.submit().then(() => { + this.card.reload(); + }); + } +} + +Controller.$inject = ['$scope', '$state']; + +ngModule.component('vnZoneBasicData', { + template: require('./index.html'), + controller: Controller, + bindings: { + zone: '<' + }, + require: { + card: '^vnZoneCard' + } +}); diff --git a/modules/agency/front/calendar/index.html b/modules/agency/front/calendar/index.html new file mode 100644 index 000000000..b1277cbe5 --- /dev/null +++ b/modules/agency/front/calendar/index.html @@ -0,0 +1,33 @@ + +
    + + +
    + {{$ctrl.firstDay | date:'MMMM'}} + {{$ctrl.firstDay | date:'yyyy'}} - + {{$ctrl.lastDay | date:'MMMM'}} + {{$ctrl.lastDay | date:'yyyy'}} +
    + + +
    +
    + + +
    +
    \ No newline at end of file diff --git a/modules/agency/front/calendar/index.js b/modules/agency/front/calendar/index.js new file mode 100644 index 000000000..88f16d334 --- /dev/null +++ b/modules/agency/front/calendar/index.js @@ -0,0 +1,171 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + constructor($element, $, vnWeekDays) { + super($element, $); + this.vnWeekDays = vnWeekDays; + this.nMonths = 4; + + let date = new Date(); + date.setDate(1); + date.setHours(0, 0, 0, 0); + this.date = date; + } + + get date() { + return this._date; + } + + set date(value) { + this._date = value; + let stamp = value.getTime(); + + let firstDay = new Date(stamp); + firstDay.setDate(1); + this.firstDay = firstDay; + + let lastDay = new Date(stamp); + lastDay.setMonth(lastDay.getMonth() + this.nMonths); + lastDay.setDate(0); + this.lastDay = lastDay; + + this.months = []; + for (let i = 0; i < this.nMonths; i++) { + let monthDate = new Date(stamp); + monthDate.setMonth(value.getMonth() + i); + this.months.push(monthDate); + } + + this.refreshEvents(); + } + + step(direction) { + let date = new Date(this.date.getTime()); + date.setMonth(date.getMonth() + (this.nMonths * direction)); + this.date = date; + } + + get data() { + return this._data; + } + + set data(value) { + this._data = value; + + value = value || {}; + + this.events = value.events; + + function toStamp(date) { + return date && new Date(date).setHours(0, 0, 0, 0); + } + + this.exclusions = {}; + let exclusions = value.exclusions; + + if (exclusions) { + for (let exclusion of exclusions) { + let stamp = toStamp(exclusion.dated); + if (!this.exclusions[stamp]) this.exclusions[stamp] = []; + this.exclusions[stamp].push(exclusion); + } + } + + let events = value.events; + + if (events) { + for (event of events) { + event.dated = toStamp(event.dated); + event.ended = toStamp(event.ended); + event.started = toStamp(event.started); + event.wdays = this.vnWeekDays.fromSet(event.weekDays); + } + } + + this.refreshEvents(); + + let calendars = this.element.querySelectorAll('vn-calendar'); + for (let calendar of calendars) + calendar.$ctrl.repaint(); + } + + refreshEvents() { + this.days = {}; + if (!this.data) return; + + let day = new Date(this.firstDay.getTime()); + + while (day <= this.lastDay) { + let stamp = day.getTime(); + let wday = day.getDay(); + let dayEvents = []; + let exclusions = this.exclusions[stamp] || []; + + if (this.events) { + for (let event of this.events) { + let match; + + switch (event.type) { + case 'day': + match = event.dated == stamp; + break; + default: + match = event.wdays[wday] + && (!event.started || stamp >= event.started) + && (!event.ended || stamp <= event.ended); + break; + } + + if (match && !exclusions.find(e => e.zoneFk == event.zoneFk)) + dayEvents.push(event); + } + } + + if (dayEvents.length) + this.days[stamp] = dayEvents; + + day.setDate(day.getDate() + 1); + } + } + + onSelection($days, $type, $weekday) { + let $events = []; + let $exclusions = []; + + for (let day of $days) { + let stamp = day.getTime(); + $events = $events.concat(this.days[stamp] || []); + $exclusions = $exclusions.concat(this.exclusions[stamp] || []); + } + + this.emit('selection', { + $days, + $type, + $weekday, + $events, + $exclusions + }); + } + + hasEvents(day) { + let stamp = day.getTime(); + return this.days[stamp] || this.exclusions[stamp]; + } + + getClass(day) { + let stamp = day.getTime(); + return this.exclusions[stamp] && !this.days[stamp] + ? 'excluded' : ''; + } +} +Controller.$inject = ['$element', '$scope', 'vnWeekDays']; + +ngModule.component('vnZoneCalendar', { + template: require('./index.html'), + controller: Controller, + bindings: { + data: ' vn-card { + & > .header { + display: flex; + align-items: center; + justify-content: space-between; + background-color: $color-main; + color: white; + font-weight: bold; + height: 45px; + + & > .vn-button { + color: inherit; + height: 100%; + } + } + & > .calendars { + display: flex; + flex-wrap: wrap; + justify-content: space-evenly; + + & > .vn-calendar { + max-width: 18em; + + .day { + &.event .day-number { + background-color: $color-success; + } + &.excluded .day-number { + background-color: $color-alert; + } + } + } + } + } +} \ No newline at end of file diff --git a/modules/agency/front/card/index.html b/modules/agency/front/card/index.html new file mode 100644 index 000000000..ae6a7f10a --- /dev/null +++ b/modules/agency/front/card/index.html @@ -0,0 +1,5 @@ + + + + + diff --git a/modules/agency/front/card/index.js b/modules/agency/front/card/index.js new file mode 100644 index 000000000..4e8ac7e8c --- /dev/null +++ b/modules/agency/front/card/index.js @@ -0,0 +1,21 @@ +import ngModule from '../module'; +import ModuleCard from 'salix/components/module-card'; + +class Controller extends ModuleCard { + reload() { + let filter = { + include: { + relation: 'agencyMode', + scope: {fields: ['name']} + } + }; + + this.$http.get(`Zones/${this.$params.id}`, {filter}) + .then(res => this.zone = res.data); + } +} + +ngModule.vnComponent('vnZoneCard', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/agency/front/card/index.spec.js b/modules/agency/front/card/index.spec.js new file mode 100644 index 000000000..cc53fe946 --- /dev/null +++ b/modules/agency/front/card/index.spec.js @@ -0,0 +1,26 @@ +import './index.js'; + +describe('Agency Component vnZoneCard', () => { + let controller; + let $httpBackend; + let data = {id: 1, name: 'fooName'}; + + beforeEach(ngModule('agency')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_, $stateParams) => { + $httpBackend = _$httpBackend_; + + let $element = angular.element('
    '); + controller = $componentController('vnZoneCard', {$element}); + + $stateParams.id = data.id; + $httpBackend.whenRoute('GET', 'Zones/:id').respond(data); + })); + + it('should request data and set it on the controller', () => { + controller.reload(); + $httpBackend.flush(); + + expect(controller.zone).toEqual(data); + }); +}); diff --git a/modules/agency/front/create/index.html b/modules/agency/front/create/index.html new file mode 100644 index 000000000..332e8a9b8 --- /dev/null +++ b/modules/agency/front/create/index.html @@ -0,0 +1,86 @@ + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/modules/agency/front/create/index.js b/modules/agency/front/create/index.js new file mode 100644 index 000000000..98d377d0f --- /dev/null +++ b/modules/agency/front/create/index.js @@ -0,0 +1,26 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($scope, $state) { + this.$scope = $scope; + this.$state = $state; + this.zone = { + travelingDays: 0, + price: 0.20, + bonus: 0.20, + hour: new Date() + }; + } + + onSubmit() { + return this.$scope.watcher.submit().then(res => { + this.$state.go('zone.card.location', {id: res.data.id}); + }); + } +} +Controller.$inject = ['$scope', '$state']; + +ngModule.component('vnZoneCreate', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/agency/front/create/index.spec.js b/modules/agency/front/create/index.spec.js new file mode 100644 index 000000000..5b2a022f8 --- /dev/null +++ b/modules/agency/front/create/index.spec.js @@ -0,0 +1,39 @@ +import './index'; +import watcher from 'core/mocks/watcher'; + +describe('Agency Component vnZoneCreate', () => { + let $scope; + let $state; + let controller; + + beforeEach(ngModule('agency')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$state_) => { + $scope = $rootScope.$new(); + $state = _$state_; + $scope.watcher = watcher; + $scope.watcher.submit = () => { + return { + then: callback => { + callback({data: {id: 1234}}); + } + }; + }; + controller = $componentController('vnZoneCreate', {$scope}); + })); + + describe('onSubmit()', () => { + it(`should call submit() on the watcher then expect a callback`, () => { + spyOn($state, 'go'); + + controller.zone = { + name: 'Zone One' + }; + + controller.onSubmit(); + + expect(controller.$state.go).toHaveBeenCalledWith('zone.card.location', Object({id: 1234})); + }); + }); +}); + diff --git a/modules/agency/front/create/locale/es.yml b/modules/agency/front/create/locale/es.yml new file mode 100644 index 000000000..7c1317ca7 --- /dev/null +++ b/modules/agency/front/create/locale/es.yml @@ -0,0 +1,3 @@ +Traveling days: Días de viaje +Closing hour (ETD): Hora de cierre (ETD) +Bonus: Bonificación \ No newline at end of file diff --git a/modules/agency/front/delivery-days/index.html b/modules/agency/front/delivery-days/index.html new file mode 100644 index 000000000..2b8a0e423 --- /dev/null +++ b/modules/agency/front/delivery-days/index.html @@ -0,0 +1,33 @@ +
    + + +
    + +
    + + +
    {{name}}
    +
    + {{country.country}} +
    +
    +
    + + + + + +
    +
    diff --git a/modules/agency/front/delivery-days/index.js b/modules/agency/front/delivery-days/index.js new file mode 100644 index 000000000..0d7baeb60 --- /dev/null +++ b/modules/agency/front/delivery-days/index.js @@ -0,0 +1,25 @@ +import ngModule from '../module'; +import Section from 'salix/components/section'; +import './style.scss'; + +class Controller extends Section { + $onInit() { + this.$.params = {}; + } + + onSubmit() { + this.$.data = null; + this.$http.get(`Zones/getEvents`, {params: this.$.params}) + .then(res => { + let data = res.data; + this.$.data = data; + if (!data.events.length) + this.vnApp.showMessage(this.$t('No service for the specified zone')); + }); + } +} + +ngModule.component('vnZoneDeliveryDays', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/agency/front/delivery-days/style.scss b/modules/agency/front/delivery-days/style.scss new file mode 100644 index 000000000..79f95a3dc --- /dev/null +++ b/modules/agency/front/delivery-days/style.scss @@ -0,0 +1,16 @@ + +vn-zone-delivery-days { + vn-zone-calendar { + display: flex; + justify-content: center; + flex-wrap: wrap; + + & > vn-calendar { + min-width: 16.5em; + } + } + form { + display: flex; + flex-direction: column; + } +} \ No newline at end of file diff --git a/modules/agency/front/descriptor/index.html b/modules/agency/front/descriptor/index.html new file mode 100644 index 000000000..58441d10d --- /dev/null +++ b/modules/agency/front/descriptor/index.html @@ -0,0 +1,53 @@ +
    + + + + + + + + + + +
    +
    + + + + + + + + + + + + + + + + +
    +
    +
    + + \ No newline at end of file diff --git a/modules/agency/front/descriptor/index.js b/modules/agency/front/descriptor/index.js new file mode 100644 index 000000000..736d8dd31 --- /dev/null +++ b/modules/agency/front/descriptor/index.js @@ -0,0 +1,38 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $state, $http) { + this.$scope = $scope; + this.$state = $state; + this.$http = $http; + this.moreOptions = [ + {callback: this.deleteZone, name: 'Delete'} + ]; + } + + onMoreChange(callback) { + callback.call(this); + } + + deleteZone() { + this.$scope.deleteZone.show(); + } + + returnDialog(response) { + if (response === 'accept') { + this.$http.delete(`Zones/${this.zone.id}`).then(() => { + this.$state.go('zone.index'); + }); + } + } +} + +Controller.$inject = ['$scope', '$state', '$http']; + +ngModule.component('vnZoneDescriptor', { + template: require('./index.html'), + controller: Controller, + bindings: { + zone: '<' + } +}); diff --git a/modules/agency/front/events/index.html b/modules/agency/front/events/index.html new file mode 100644 index 000000000..693b24a85 --- /dev/null +++ b/modules/agency/front/events/index.html @@ -0,0 +1,179 @@ + + + +
    +
    + Edit mode +
    + + + + + + +
    +
    + Events +
    + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/agency/front/events/index.js b/modules/agency/front/events/index.js new file mode 100644 index 000000000..bea352d06 --- /dev/null +++ b/modules/agency/front/events/index.js @@ -0,0 +1,167 @@ +import ngModule from '../module'; +import Section from 'salix/components/section'; + +class Controller extends Section { + constructor($element, $, vnWeekDays) { + super($element, $); + this.vnWeekDays = vnWeekDays; + this.editMode = 'include'; + + this.path = `Zones/${this.$params.id}/events`; + this.exclusionsPath = `Zones/${this.$params.id}/exclusions`; + this.refresh(); + } + + refresh() { + let data = {}; + this.$q.all([ + this.$http.get(this.path) + .then(res => data.events = res.data), + this.$http.get(this.exclusionsPath) + .then(res => data.exclusions = res.data) + ]).finally(() => { + this.$.data = data; + }); + } + + formatWdays(weekDays) { + if (!weekDays) return; + + let abrWdays = weekDays + .split(',') + .map(wday => this.vnWeekDays.map[wday].localeAbr); + + return abrWdays.length < 7 + ? abrWdays.join(', ') + : this.$t('Everyday'); + } + + onSelection(days, type, weekday, events, exclusions) { + if (this.editMode == 'include') { + if (events.length) + this.edit(events[0]); + else + this.create(days, type, weekday); + } else { + if (exclusions.length) + this.exclusionDelete(exclusions); + else + this.exclusionCreate(days); + } + } + + onEditClick(row, event) { + if (event.defaultPrevented) return; + this.edit(row); + } + + edit(row) { + this.isNew = false; + this.selected = angular.copy(row); + this.selected.wdays = this.vnWeekDays.fromSet(row.weekDays); + this.$.dialog.show(); + } + + create(days, type, weekday) { + this.isNew = true; + + if (type == 'weekday') { + let wdays = []; + wdays[weekday] = true; + + this.selected = { + type: 'indefinitely', + wdays + }; + } else { + this.selected = { + type: 'day', + dated: days[0] + }; + } + + this.$.dialog.show(); + } + + onIncludeResponse(response) { + switch (response) { + case 'accept': { + let selected = this.selected; + let type = selected.type; + + selected.weekDays = this.vnWeekDays.toSet(selected.wdays); + + if (type == 'day') + selected.weekDays = ''; + else + selected.dated = null; + + if (type != 'range') { + selected.started = null; + selected.ended = null; + } + + let req; + + if (this.isNew) + req = this.$http.post(this.path, selected); + else + req = this.$http.put(`${this.path}/${selected.id}`, selected); + + return req.then(() => { + this.selected = null; + this.isNew = null; + this.refresh(); + }); + } + case 'delete': + return this.onDelete(this.selected.id) + .then(response => response == 'accept'); + } + } + + onDeleteClick(id, event) { + if (event.defaultPrevented) return; + event.preventDefault(); + this.onDelete(id); + } + + onDelete(id) { + return this.$.confirm.show( + response => this.onDeleteResponse(response, id)); + } + + onDeleteResponse(response, id) { + if (response != 'accept' || !id) return; + return this.$http.delete(`${this.path}/${id}`) + .then(() => this.refresh()); + } + + exclusionCreate(days) { + let exclusions = days.map(dated => { + return {dated}; + }); + + this.$http.post(this.exclusionsPath, exclusions) + .then(() => this.refresh()); + } + + exclusionDelete(exclusions) { + let reqs = []; + + for (let exclusion of exclusions) { + if (!exclusion.id) continue; + let path = `${this.exclusionsPath}/${exclusion.id}`; + reqs.push(this.$http.delete(path)); + } + + this.$q.all(reqs) + .then(() => this.refresh()); + } +} +Controller.$inject = ['$element', '$scope', 'vnWeekDays']; + +ngModule.component('vnZoneEvents', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/agency/front/events/locale/es.yml b/modules/agency/front/events/locale/es.yml new file mode 100644 index 000000000..eb0894c63 --- /dev/null +++ b/modules/agency/front/events/locale/es.yml @@ -0,0 +1,4 @@ +Edit mode: Modo de edición +Include: Incluir +Exclude: Excluir +Events: Eventos \ No newline at end of file diff --git a/modules/agency/front/index.js b/modules/agency/front/index.js new file mode 100644 index 000000000..556ec58ad --- /dev/null +++ b/modules/agency/front/index.js @@ -0,0 +1,16 @@ +export * from './module'; + +import './main'; +import './index/'; +import './delivery-days'; +import './summary'; +import './card'; +import './descriptor'; +import './search-panel'; +import './create'; +import './basic-data'; +import './warehouses'; +import './events'; +import './calendar'; +import './location'; +import './calendar'; diff --git a/modules/agency/front/index/index.html b/modules/agency/front/index/index.html new file mode 100644 index 000000000..cb820b66a --- /dev/null +++ b/modules/agency/front/index/index.html @@ -0,0 +1,78 @@ + + + + + + + + + + Id + Name + Agency + Closing + Price + + + + + + {{::zone.id}} + {{::zone.name}} + {{::zone.agencyMode.name}} + {{::zone.hour | date: 'HH:mm'}} + {{::zone.price | currency: 'EUR':2}} + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/agency/front/index/index.js b/modules/agency/front/index/index.js new file mode 100644 index 000000000..4ee44ada0 --- /dev/null +++ b/modules/agency/front/index/index.js @@ -0,0 +1,81 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($scope, $http, $state) { + this.$scope = $scope; + this.$http = $http; + this.$state = $state; + this.filter = { + include: { + relation: 'agencyMode', + scope: {fields: ['name']} + } + }; + } + + exprBuilder(param, value) { + switch (param) { + case 'search': + return /^\d+$/.test(value) + ? {id: value} + : {name: {like: `%${value}%`}}; + case 'name': + return {[param]: {like: `%${value}%`}}; + case 'agencyModeFk': + return {[param]: value}; + } + } + + /** + * Clones a zone and all its properties + * @param {Object} event - Event object + * @param {Object} zone - Selected item + */ + clone(event, zone) { + this.stopEvent(event); + this.selectedZone = zone; + this.$scope.clone.show(); + } + + /** + * Clone response callback + * @param {String} response - Response string (['accept', 'cancel']) + */ + onCloneAccept(response) { + if (!(response == 'accept' && this.selectedZone)) return; + const query = `Zones/${this.selectedZone.id}/clone`; + this.$http.post(query).then(res => { + if (res && res.data) + this.$state.go('zone.card.basicData', {id: res.data.id}); + }); + + this.selectedZone = null; + } + + /** + * Opens a summary modal + * @param {Object} event - Event object + * @param {Object} zone - Selected item + */ + preview(event, zone) { + this.stopEvent(event); + this.selectedZone = zone; + this.$scope.summary.show(); + } + + /** + * Prevents normal event propagation + * @param {Object} event - Event object + */ + stopEvent(event) { + event.preventDefault(); + event.stopImmediatePropagation(); + } +} + +Controller.$inject = ['$scope', '$http', '$state']; + +ngModule.component('vnZoneIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/agency/front/index/index.spec.js b/modules/agency/front/index/index.spec.js new file mode 100644 index 000000000..cf2fdfab5 --- /dev/null +++ b/modules/agency/front/index/index.spec.js @@ -0,0 +1,31 @@ +import './index.js'; + +describe('Agency Component vnZoneIndex', () => { + let $componentController; + let controller; + + beforeEach(ngModule('agency')); + + beforeEach(angular.mock.inject(_$componentController_ => { + $componentController = _$componentController_; + controller = $componentController('vnZoneIndex'); + })); + + describe('exprBuilder()', () => { + it('should return a formated object with the id in case of search', () => { + let param = 'search'; + let value = 1; + let result = controller.exprBuilder(param, value); + + expect(result).toEqual({id: 1}); + }); + + it('should return a formated object with the agencyModeFk in case of agencyModeFk', () => { + let param = 'agencyModeFk'; + let value = 'My Delivery'; + let result = controller.exprBuilder(param, value); + + expect(result).toEqual({agencyModeFk: 'My Delivery'}); + }); + }); +}); diff --git a/modules/agency/front/index/locale/es.yml b/modules/agency/front/index/locale/es.yml new file mode 100644 index 000000000..14195e869 --- /dev/null +++ b/modules/agency/front/index/locale/es.yml @@ -0,0 +1,2 @@ +Do you want to clone this zone?: ¿Seguro que quieres clonar esta zona? +All it's properties will be copied: Todas sus propiedades serán copiadas \ No newline at end of file diff --git a/modules/agency/front/locale/es.yml b/modules/agency/front/locale/es.yml new file mode 100644 index 000000000..588b67ec3 --- /dev/null +++ b/modules/agency/front/locale/es.yml @@ -0,0 +1,28 @@ +Agency: Agencia +Warehouses: Almacenes +Week days: Días de la semana +Exceptions: Excepciones +Exclusions: Exclusiones +Warehouse: Almacén +Hour: Hora +Price: Precio +Locations: Localizaciones +This zone will be removed: La zona será eliminada +Are you sure you want to delete this zone?: ¿Seguro de que quieres eliminar esta zona? +Zones: Zonas +New zone: Nueva zona +Volumetric: Volumétrico +Clone: Clonar +Search zone by id or name: Buscar zonas por identificador o nombre +From: Desde +To: Hasta +Closing: Cierre +One day: Un día +Range of dates: Rango de fechas +Indefinitely: Indefinido +Everyday: Todos los días +Delivery days: Días de entrega +Province: Provincia +Postcode: Código postal +Inflation: Inflación +Query: Consultar diff --git a/modules/agency/front/location/index.html b/modules/agency/front/location/index.html new file mode 100644 index 000000000..4b3523a1f --- /dev/null +++ b/modules/agency/front/location/index.html @@ -0,0 +1,28 @@ + + + + + + + +
    + + + + + + +
    diff --git a/modules/agency/front/location/index.js b/modules/agency/front/location/index.js new file mode 100644 index 000000000..9fcd055b3 --- /dev/null +++ b/modules/agency/front/location/index.js @@ -0,0 +1,60 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + $postLink() { + this.onSearch(); + } + + onSearch(params) { + this.$.model.applyFilter({}, params).then(() => { + const data = this.$.model.data; + this.$.treeview.data = data; + }); + } + + onFetch(item) { + const params = item ? {parentId: item.id} : null; + return this.$.model.applyFilter({}, params) + .then(() => this.$.model.data); + } + + onSort(a, b) { + if (b.selected !== a.selected) { + if (a.selected == null) + return 1; + if (b.selected == null) + return -1; + return b.selected - a.selected; + } + + return a.name.localeCompare(b.name); + } + + exprBuilder(param, value) { + switch (param) { + case 'search': + return {name: {like: `%${value}%`}}; + } + } + + onSelection(value, item) { + if (value == null) + value = undefined; + const params = {geoId: item.id, isIncluded: value}; + const path = `zones/${this.zone.id}/toggleIsIncluded`; + this.$http.post(path, params); + } +} + +ngModule.component('vnZoneLocation', { + template: require('./index.html'), + controller: Controller, + bindings: { + zone: '<' + }, + require: { + card: '^vnZoneCard' + } +}); diff --git a/modules/agency/front/location/style.scss b/modules/agency/front/location/style.scss new file mode 100644 index 000000000..2316a2622 --- /dev/null +++ b/modules/agency/front/location/style.scss @@ -0,0 +1,19 @@ +@import "variables"; + +vn-treeview-child { + .content > .vn-check:not(.indeterminate):not(.checked) { + color: $color-alert; + + & > .btn { + border-color: $color-alert; + } + } + .content > .vn-check.checked { + color: $color-notice; + + & > .btn { + background-color: $color-notice; + border-color: $color-notice + } + } +} \ No newline at end of file diff --git a/modules/agency/front/main/index.html b/modules/agency/front/main/index.html new file mode 100644 index 000000000..230bf7f6d --- /dev/null +++ b/modules/agency/front/main/index.html @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/modules/agency/front/main/index.js b/modules/agency/front/main/index.js new file mode 100644 index 000000000..3e8890310 --- /dev/null +++ b/modules/agency/front/main/index.js @@ -0,0 +1,9 @@ +import ngModule from '../module'; +import ModuleMain from 'salix/components/module-main'; + +export default class Zone extends ModuleMain {} + +ngModule.vnComponent('vnZone', { + controller: Zone, + template: require('./index.html') +}); diff --git a/modules/agency/front/module.js b/modules/agency/front/module.js new file mode 100644 index 000000000..cf38d7fe9 --- /dev/null +++ b/modules/agency/front/module.js @@ -0,0 +1,3 @@ +import {ng} from 'core/vendor'; + +export default ng.module('agency', ['vnCore']); diff --git a/modules/agency/front/routes.json b/modules/agency/front/routes.json new file mode 100644 index 000000000..7c5b1338d --- /dev/null +++ b/modules/agency/front/routes.json @@ -0,0 +1,83 @@ +{ + "module": "agency", + "name": "Agencies", + "icon" : "icon-delivery", + "validations" : true, + "dependencies": ["worker"], + "menus": { + "main": [ + {"state": "zone.index", "icon": "icon-delivery"}, + {"state": "zone.deliveryDays", "icon": "today"} + ], + "card": [ + {"state": "zone.card.basicData", "icon": "settings"}, + {"state": "zone.card.location", "icon": "my_location"}, + {"state": "zone.card.warehouses", "icon": "home"}, + {"state": "zone.card.events", "icon": "today"} + ] + }, + "routes": [ + { + "url": "/zone", + "state": "zone", + "abstract": true, + "component": "vn-zone", + "description": "Zones" + }, { + "url": "/index?q", + "state": "zone.index", + "component": "vn-zone-index", + "description": "Zones" + }, { + "url": "/delivery-days?q", + "state": "zone.deliveryDays", + "component": "vn-zone-delivery-days", + "description": "Delivery days" + }, { + "url": "/create", + "state": "zone.create", + "component": "vn-zone-create", + "description": "New zone" + }, { + "url": "/:id", + "state": "zone.card", + "component": "vn-zone-card", + "abstract": true, + "description": "Detail" + }, { + "url": "/summary", + "state": "zone.card.summary", + "component": "vn-zone-summary", + "description": "Summary", + "params": { + "zone": "$ctrl.zone" + } + }, { + "url": "/basic-data", + "state": "zone.card.basicData", + "component": "vn-zone-basic-data", + "description": "Basic data", + "params": { + "zone": "$ctrl.zone" + } + }, { + "url": "/warehouses", + "state": "zone.card.warehouses", + "component": "vn-zone-warehouses", + "description": "Warehouses" + }, { + "url": "/events", + "state": "zone.card.events", + "component": "vn-zone-events", + "description": "Calendar" + }, { + "url": "/location?q", + "state": "zone.card.location", + "component": "vn-zone-location", + "description": "Locations", + "params": { + "zone": "$ctrl.zone" + } + } + ] +} \ No newline at end of file diff --git a/modules/agency/front/search-panel/index.html b/modules/agency/front/search-panel/index.html new file mode 100644 index 000000000..a97428192 --- /dev/null +++ b/modules/agency/front/search-panel/index.html @@ -0,0 +1,33 @@ +
    +
    + + + + + + + + + + + + + + + +
    +
    \ No newline at end of file diff --git a/modules/agency/front/search-panel/index.js b/modules/agency/front/search-panel/index.js new file mode 100644 index 000000000..c01ac35e5 --- /dev/null +++ b/modules/agency/front/search-panel/index.js @@ -0,0 +1,7 @@ +import ngModule from '../module'; +import SearchPanel from 'core/components/searchbar/search-panel'; + +ngModule.component('vnZoneSearchPanel', { + template: require('./index.html'), + controller: SearchPanel +}); diff --git a/modules/agency/front/summary/index.html b/modules/agency/front/summary/index.html new file mode 100644 index 000000000..c2694da45 --- /dev/null +++ b/modules/agency/front/summary/index.html @@ -0,0 +1,46 @@ + +
    #{{$ctrl.summary.id}} - {{$ctrl.summary.name}}
    + + + + + + + + + + + + + + + + + + + + + + +

    Warehouses

    + + + + Name + + + + + {{zoneWarehouse.warehouse.name}} + + + +
    +
    +
    \ No newline at end of file diff --git a/modules/agency/front/summary/index.js b/modules/agency/front/summary/index.js new file mode 100644 index 000000000..636e528be --- /dev/null +++ b/modules/agency/front/summary/index.js @@ -0,0 +1,65 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; + +class Controller extends Component { + constructor($element, $, $httpParamSerializer) { + super($element, $); + + this.$httpParamSerializer = $httpParamSerializer; + } + get zone() { + return this._zone; + } + + set zone(value) { + this._zone = value; + + if (!value) return; + + this.getSummary(); + this.getWarehouses(); + } + + getSummary() { + const params = { + filter: { + include: { + relation: 'agencyMode', + fields: ['name'] + }, + where: { + id: this.zone.id + } + } + }; + const serializedParams = this.$httpParamSerializer(params); + this.$http.get(`Zones/findOne?${serializedParams}`).then(res => { + this.summary = res.data; + }); + } + + getWarehouses() { + const params = { + filter: { + include: { + relation: 'warehouse', + fields: ['name'] + } + } + }; + const serializedParams = this.$httpParamSerializer(params); + this.$http.get(`Zones/${this.zone.id}/warehouses?${serializedParams}`).then(res => { + this.zoneWarehouses = res.data; + }); + } +} + +Controller.$inject = ['$element', '$scope', '$httpParamSerializer']; + +ngModule.component('vnZoneSummary', { + template: require('./index.html'), + controller: Controller, + bindings: { + zone: '<' + } +}); diff --git a/modules/agency/front/summary/index.spec.js b/modules/agency/front/summary/index.spec.js new file mode 100644 index 000000000..d0f99dbb2 --- /dev/null +++ b/modules/agency/front/summary/index.spec.js @@ -0,0 +1,68 @@ +import './index'; + +describe('component vnZoneSummary', () => { + let $element; + let $scope; + let controller; + let $httpBackend; + let $httpParamSerializer; + + beforeEach(ngModule('agency')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_) => { + $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; + $scope = $rootScope.$new(); + $element = angular.element(``); + controller = $componentController('vnZoneSummary', {$element, $scope}); + })); + + describe('zone setter', () => { + it('should set the zone and then call both getSummary() and getWarehouses()', () => { + spyOn(controller, 'getSummary'); + spyOn(controller, 'getWarehouses'); + + controller.zone = {id: 1}; + + expect(controller.getSummary).toHaveBeenCalledWith(); + expect(controller.getWarehouses).toHaveBeenCalledWith(); + }); + }); + + describe('getSummary()', () => { + it('should perform a get and then store data on the controller', () => { + controller._zone = {id: 1}; + let params = { + filter: { + include: { + relation: 'agencyMode', + fields: ['name'] + }, + where: { + id: controller._zone.id + } + } + }; + const serializedParams = $httpParamSerializer(params); + const query = `Zones/findOne?${serializedParams}`; + $httpBackend.expectGET(query).respond({id: 1}); + controller.getSummary(); + $httpBackend.flush(); + + expect(controller.summary).toBeDefined(); + }); + }); + + xdescribe('getEntries()', () => { + it('should call the getEntries method to get the entries data', () => { + controller._travel = {id: 999}; + + const query = `/api/Travels/${controller._travel.id}/getEntries`; + $httpBackend.expectGET(query).respond('I am the entries'); + controller.getEntries(); + $httpBackend.flush(); + + expect(controller.entries).toEqual('I am the entries'); + }); + }); +}); diff --git a/modules/agency/front/warehouses/index.html b/modules/agency/front/warehouses/index.html new file mode 100644 index 000000000..1a9fee32e --- /dev/null +++ b/modules/agency/front/warehouses/index.html @@ -0,0 +1,53 @@ + + + + + + {{::row.warehouse.name}} + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/agency/front/warehouses/index.js b/modules/agency/front/warehouses/index.js new file mode 100644 index 000000000..fa99c505a --- /dev/null +++ b/modules/agency/front/warehouses/index.js @@ -0,0 +1,57 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; + +class Controller extends Component { + constructor($element, $) { + super($element, $); + + this.path = `Zones/${this.$params.id}/warehouses`; + this.refresh(); + } + + refresh() { + let filter = {include: 'warehouse'}; + this.$http.get(this.path, {params: {filter}}) + .then(res => this.$.data = res.data); + } + + onCreate() { + this.selected = {}; + this.$.dialog.show(); + } + + onSave(response) { + if (response != 'accept') return; + + this.$http.post(this.path, this.selected) + .then(() => { + this.selected = null; + this.isNew = null; + this.$.dialog.hide(); + this.refresh(); + }); + + return false; + } + + onDelete(index) { + this.$.confirm.show(); + this.deleteIndex = index; + } + + delete(response) { + if (response != 'accept') return; + let id = this.$.data[this.deleteIndex].id; + if (!id) return; + this.$http.delete(`${this.path}/${id}`) + .then(() => { + this.$.data.splice(this.deleteIndex, 1); + this.deleteIndex = null; + }); + } +} + +ngModule.component('vnZoneWarehouses', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js new file mode 100644 index 000000000..c2ab2001e --- /dev/null +++ b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js @@ -0,0 +1,174 @@ +module.exports = Self => { + Self.remoteMethodCtx('importToNewRefundTicket', { + description: 'Imports lines from claimBeginning to a new ticket with specific shipped, landed dates, agency and company', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'the claim id', + http: {source: 'path'} + }], + returns: { + type: 'string', + root: true + }, + http: { + path: `/:id/importToNewRefundTicket`, + verb: 'POST' + } + }); + + Self.importToNewRefundTicket = async(ctx, id) => { + const models = Self.app.models; + const token = ctx.req.accessToken; + const userId = token.userId; + const tx = await Self.beginTransaction({}); + const filter = { + where: {id: id}, + include: [ + { + relation: 'ticket', + scope: { + fields: ['id', 'clientFk', 'warehouseFk', 'companyFk', 'addressFk'], + include: { + relation: 'address', + scope: { + fields: ['nickname'] + } + } + } + } + ] + }; + const salesFilter = { + where: {claimFk: id}, + include: [ + { + relation: 'sale', + scope: { + fields: [ + 'id', + 'itemFk', + 'concept', + 'price', + 'discount', + 'reserved', + 'isPicked', + 'created', + 'priceFixed', + 'isPriceFixed'] + } + } + ] + }; + + try { + let options = {transaction: tx}; + const worker = await models.Worker.findOne({ + where: {userFk: userId} + }, options); + + const obsevationType = await models.ObservationType.findOne({ + where: {description: 'comercial'} + }, options); + + const agencyMode = await models.AgencyMode.findOne({ + where: {code: 'refund'} + }, options); + + const state = await models.State.findOne({ + where: {code: 'DELIVERED'} + }, options); + + const zone = await models.Zone.findOne({ + where: {agencyModeFk: agencyMode.id} + }, options); + + const claim = await models.Claim.findOne(filter, options); + const today = new Date(); + + const newRefundTicket = await models.Ticket.create({ + clientFk: claim.ticket().clientFk, + shipped: today, + landed: today, + nickname: claim.ticket().address().nickname, + warehouseFk: claim.ticket().warehouseFk, + companyFk: claim.ticket().companyFk, + addressFk: claim.ticket().addressFk, + agencyModeFk: agencyMode.id, + zoneFk: zone.id + }, options); + + await saveObservation({ + description: `Reclama ticket: ${claim.ticketFk}`, + ticketFk: newRefundTicket.id, + observationTypeFk: obsevationType.id + }, options); + + await models.TicketTracking.create({ + ticketFk: newRefundTicket.id, + stateFk: state.id, + workerFk: worker.id + }, options); + + const salesToRefund = await models.ClaimBeginning.find(salesFilter, options); + const createdSales = await addSalesToTicket(salesToRefund, newRefundTicket.id, options); + await insertIntoClaimEnd(createdSales, id, worker.id, options); + + await Self.rawSql('CALL vn.ticketCalculateClon(?, ?)', [ + newRefundTicket.id, claim.ticketFk + ], options); + + await tx.commit(); + + return newRefundTicket; + } catch (e) { + await tx.rollback(); + throw e; + } + }; + + async function addSalesToTicket(salesToRefund, ticketId, options) { + let formatedSales = []; + salesToRefund.forEach(sale => { + let formatedSale = { + itemFk: sale.sale().itemFk, + ticketFk: ticketId, + concept: sale.sale().concept, + quantity: -Math.abs(sale.quantity), + price: sale.sale().price, + discount: sale.sale().discount, + reserved: sale.sale().reserved, + isPicked: sale.sale().isPicked, + created: sale.sale().created + }; + formatedSales.push(formatedSale); + }); + return await Self.app.models.Sale.create(formatedSales, options); + } + + async function insertIntoClaimEnd(createdSales, claimId, workerId, options) { + const formatedSales = []; + createdSales.forEach(sale => { + let formatedSale = { + saleFk: sale.id, + claimFk: claimId, + workerFk: workerId + }; + formatedSales.push(formatedSale); + }); + await Self.app.models.ClaimEnd.create(formatedSales, options); + } + + async function saveObservation(observation, options) { + const query = `INSERT INTO vn.ticketObservation (ticketFk, observationTypeFk, description) VALUES(?, ?, ?) + ON DUPLICATE KEY + UPDATE description = CONCAT(vn.ticketObservation.description, VALUES(description),' ')`; + await Self.rawSql(query, [ + observation.ticketFk, + observation.observationTypeFk, + observation.description + ], options); + } +}; diff --git a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.spec.js b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.spec.js new file mode 100644 index 000000000..5fecf8bcd --- /dev/null +++ b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.spec.js @@ -0,0 +1,33 @@ +const app = require('vn-loopback/server/server'); + +describe('claimBeginning', () => { + let ticket; + let refundTicketSales; + let salesInsertedInClaimEnd; + + afterAll(async() => { + let promises = []; + promises.push(app.models.Ticket.destroyById(ticket.id)); + + promises.push(app.models.Ticket.rawSql(`DELETE FROM vn.orderTicket WHERE ticketFk ='${ticket.id}';`)); + + await Promise.all(promises); + }); + + describe('importToNewRefundTicket()', () => { + it('should create a new ticket with negative sales and insert the negative sales into claimEnd', async() => { + let ctxOfSalesAssistant = {req: {accessToken: {userId: 21}}}; + let claimId = 1; + ticket = await app.models.ClaimBeginning.importToNewRefundTicket(ctxOfSalesAssistant, claimId); + + await app.models.Ticket.findById(ticket.id); + + refundTicketSales = await app.models.Sale.find({where: {ticketFk: ticket.id}}); + salesInsertedInClaimEnd = await app.models.ClaimEnd.find({where: {claimFk: claimId}}); + + expect(refundTicketSales.length).toEqual(1); + expect(refundTicketSales[0].quantity).toEqual(-5); + expect(salesInsertedInClaimEnd[0].saleFk).toEqual(refundTicketSales[0].id); + }); + }); +}); diff --git a/modules/claim/back/methods/claim-dms/allowedContentTypes.js b/modules/claim/back/methods/claim-dms/allowedContentTypes.js new file mode 100644 index 000000000..2f5183f92 --- /dev/null +++ b/modules/claim/back/methods/claim-dms/allowedContentTypes.js @@ -0,0 +1,23 @@ +module.exports = Self => { + Self.remoteMethodCtx('allowedContentTypes', { + description: 'Returns a list of allowed contentTypes', + accessType: 'READ', + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/allowedContentTypes`, + verb: 'GET' + } + }); + + Self.allowedContentTypes = async() => { + const storageConnector = Self.app.dataSources.storage.connector; + const allowedContentTypes = storageConnector.allowedContentTypes; + const modelAllowedContentTypes = Self.definition.settings.allowedContentTypes; + + return modelAllowedContentTypes || allowedContentTypes; + }; +}; + diff --git a/modules/claim/back/methods/claim-dms/removeFile.js b/modules/claim/back/methods/claim-dms/removeFile.js new file mode 100644 index 000000000..ac546455a --- /dev/null +++ b/modules/claim/back/methods/claim-dms/removeFile.js @@ -0,0 +1,33 @@ +module.exports = Self => { + Self.remoteMethodCtx('removeFile', { + description: 'Removes a claim document', + accessType: 'WRITE', + accepts: { + arg: 'id', + type: 'Number', + description: 'The document id', + http: {source: 'path'} + }, + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/removeFile`, + verb: 'POST' + } + }); + + Self.removeFile = async(ctx, id) => { + const models = Self.app.models; + const targetClaimDms = await models.ClaimDms.findById(id); + const targetDms = await models.Dms.findById(targetClaimDms.dmsFk); + const trashDmsType = await models.DmsType.findOne({where: {code: 'trash'}}); + + await models.Dms.removeFile(ctx, targetClaimDms.dmsFk); + await targetClaimDms.destroy(); + + return targetDms.updateAttribute('dmsTypeFk', trashDmsType.id); + }; +}; + diff --git a/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js b/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js new file mode 100644 index 000000000..b1cd5686a --- /dev/null +++ b/modules/claim/back/methods/claim-dms/specs/removeFile.spec.js @@ -0,0 +1,18 @@ +const app = require('vn-loopback/server/server'); + +describe('TicketDms removeFile()', () => { + const ticketDmsId = 1; + it(`should return an error for a user without enough privileges`, async() => { + let clientId = 101; + let ctx = {req: {accessToken: {userId: clientId}}}; + + let error; + await app.models.TicketDms.removeFile(ctx, ticketDmsId).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`You don't have enough privileges`); + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/modules/claim/back/methods/claim-end/importTicketSales.js b/modules/claim/back/methods/claim-end/importTicketSales.js new file mode 100644 index 000000000..c7ca93197 --- /dev/null +++ b/modules/claim/back/methods/claim-end/importTicketSales.js @@ -0,0 +1,40 @@ +module.exports = Self => { + Self.remoteMethodCtx('importTicketSales', { + description: 'Imports lines from claimBeginning to a new ticket with specific shipped, landed dates, agency and company', + accessType: 'WRITE', + accepts: [{ + arg: 'params', + type: 'object', + http: {source: 'body'} + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/importTicketSales`, + verb: 'POST' + } + }); + + Self.importTicketSales = async(ctx, params) => { + let models = Self.app.models; + let userId = ctx.req.accessToken.userId; + let worker = await models.Worker.findOne({where: {userFk: userId}}); + + let ticketSales = await models.Sale.find({ + where: {ticketFk: params.ticketFk} + }); + + let claimEnds = []; + ticketSales.forEach(sale => { + claimEnds.push({ + saleFk: sale.id, + claimFk: params.claimFk, + workerFk: worker.id + }); + }); + + return await Self.create(claimEnds); + }; +}; diff --git a/modules/claim/back/methods/claim-end/specs/importTicketSales.spec.js b/modules/claim/back/methods/claim-end/specs/importTicketSales.spec.js new file mode 100644 index 000000000..3c2a3e0a6 --- /dev/null +++ b/modules/claim/back/methods/claim-end/specs/importTicketSales.spec.js @@ -0,0 +1,25 @@ +const app = require('vn-loopback/server/server'); + +describe('Claim importTicketSales()', () => { + let claimEnds; + + afterAll(async done => { + claimEnds.forEach(async line => { + await line.destroy(); + }); + + done(); + }); + + it('should import sales to a claim actions from an specific ticket', async() => { + let ctx = {req: {accessToken: {userId: 5}}}; + claimEnds = await app.models.ClaimEnd.importTicketSales(ctx, { + claimFk: 1, + ticketFk: 1 + }); + + expect(claimEnds.length).toEqual(4); + expect(claimEnds[0].saleFk).toEqual(1); + expect(claimEnds[2].saleFk).toEqual(3); + }); +}); diff --git a/modules/claim/back/methods/claim/createFromSales.js b/modules/claim/back/methods/claim/createFromSales.js new file mode 100644 index 000000000..bf62a526e --- /dev/null +++ b/modules/claim/back/methods/claim/createFromSales.js @@ -0,0 +1,69 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('createFromSales', { + description: 'Create a claim', + accepts: [{ + arg: 'claim', + type: 'object', + required: true, + description: ' newTicketFk, clientFk, ticketCreated', + http: {source: 'body'} + }, { + arg: 'sales', + type: 'object', + required: true, + description: '[sales IDs]', + http: {source: 'body'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/createFromSales`, + verb: 'post' + } + }); + + Self.createFromSales = async(ctx, params) => { + let models = Self.app.models; + let userId = ctx.req.accessToken.userId; + let tx = await Self.beginTransaction({}); + + try { + let options = {transaction: tx}; + + const ticketId = params.claim.ticketFk; + const ticket = await models.Ticket.findById(ticketId, null, options); + if (ticket.isDeleted) + throw new UserError(`You can't create a claim for a removed ticket`); + + const worker = await models.Worker.findOne({ + where: {userFk: userId} + }, options); + + params.claim.workerFk = worker.id; + let newClaim = await Self.create(params.claim, options); + let promises = []; + + for (const sale of params.sales) { + const newClaimBeginning = models.ClaimBeginning.create({ + saleFk: sale.id, + claimFk: newClaim.id, + quantity: sale.quantity + }, options); + + promises.push(newClaimBeginning); + } + + await Promise.all(promises); + + await tx.commit(); + return newClaim; + } catch (e) { + await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/claim/back/methods/claim/filter.js b/modules/claim/back/methods/claim/filter.js new file mode 100644 index 000000000..33909eedc --- /dev/null +++ b/modules/claim/back/methods/claim/filter.js @@ -0,0 +1,125 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const buildFilter = require('vn-loopback/util/filter').buildFilter; +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethodCtx('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accessType: 'READ', + accepts: [ + { + arg: 'filter', + type: 'Object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + http: {source: 'query'} + }, { + arg: 'tags', + type: ['Object'], + description: 'List of tags to filter with', + http: {source: 'query'} + }, { + arg: 'search', + type: 'String', + description: `If it's and integer searchs by id, otherwise it searchs by client name`, + http: {source: 'query'} + }, { + arg: 'client', + type: 'String', + description: 'The worker name', + http: {source: 'query'} + }, { + arg: 'id', + type: 'Integer', + description: 'The claim id', + http: {source: 'query'} + }, { + arg: 'clientFk', + type: 'Integer', + description: 'The client id', + http: {source: 'query'} + }, { + arg: 'claimStateFk', + type: 'Integer', + description: 'The claim state id', + http: {source: 'query'} + }, { + arg: 'salesPersonFk', + type: 'Integer', + description: 'The salesPerson id', + http: {source: 'query'} + }, { + arg: 'attenderFk', + type: 'Integer', + description: 'The attender worker id', + http: {source: 'query'} + }, { + arg: 'created', + type: 'Date', + description: 'The to date filter', + http: {source: 'query'} + } + ], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/filter`, + verb: 'GET' + } + }); + + Self.filter = async(ctx, filter) => { + let conn = Self.dataSource.connector; + + let where = buildFilter(ctx.args, (param, value) => { + switch (param) { + case 'search': + return /^\d+$/.test(value) + ? {'cl.id': value} + : { + or: [ + {'c.name': {like: `%${value}%`}} + ] + }; + case 'client': + return {'c.name': {like: `%${value}%`}}; + case 'id': + return {'cl.id': value}; + case 'clientFk': + return {'c.id': value}; + case 'claimStateFk': + return {'cl.claimStateFk': value}; + case 'salesPersonFk': + return {'c.salesPersonFk': value}; + case 'attenderFk': + return {'cl.workerFk': value}; + case 'created': + return {'cl.created': value}; + } + }); + + filter = mergeFilters(ctx.args.filter, {where}); + + let stmts = []; + let stmt; + + stmt = new ParameterizedSQL( + `SELECT cl.id, c.name, cl.clientFk, cl.workerFk, u.nickName, cs.description, cl.created + FROM claim cl + LEFT JOIN client c ON c.id = cl.clientFk + LEFT JOIN worker w ON w.id = cl.workerFk + LEFT JOIN account.user u ON u.id = w.userFk + LEFT JOIN claimState cs ON cs.id = cl.claimStateFk` + ); + + + stmt.merge(conn.makeSuffix(filter)); + let itemsIndex = stmts.push(stmt) - 1; + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + return itemsIndex === 0 ? result : result[itemsIndex]; + }; +}; diff --git a/modules/claim/back/methods/claim/getSummary.js b/modules/claim/back/methods/claim/getSummary.js new file mode 100644 index 000000000..35e4e1479 --- /dev/null +++ b/modules/claim/back/methods/claim/getSummary.js @@ -0,0 +1,146 @@ +module.exports = Self => { + Self.remoteMethod('getSummary', { + description: 'Updates the item taxes', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The item id', + http: {source: 'path'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/getSummary`, + verb: 'GET' + } + }); + + Self.getSummary = async id => { + let promises = []; + let summary = {}; + + // Claim + + let filter = { + where: {id: id}, + include: [ + { + relation: 'worker', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + }, + { + relation: 'claimState', + scope: { + fields: ['id', 'description'] + } + }, + { + relation: 'client', + scope: { + fields: ['salesPersonFk', 'name'], + include: { + relation: 'salesPerson', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + } + } + } + ] + }; + + promises.push(Self.app.models.Claim.find(filter)); + + // Claim detail + filter = { + where: {claimFk: id}, + include: [ + {relation: 'sale', + scope: { + fields: ['concept', 'ticketFk', 'price', 'quantity', 'discount', 'itemFk'], + include: { + relation: 'ticket' + } + } + } + ] + }; + promises.push(Self.app.models.ClaimBeginning.find(filter)); + + // Claim developments + filter = { + where: {claimFk: id}, + include: [ + { + relation: 'claimResponsible' + }, + { + relation: 'worker', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + }, + { + relation: 'claimReason' + }, + { + relation: 'claimResult' + }, + { + relation: 'claimRedelivery' + } + ] + }; + promises.push(Self.app.models.ClaimDevelopment.find(filter)); + + // Claim action + filter = { + where: {claimFk: id}, + include: [ + {relation: 'sale', + scope: { + fields: ['concept', 'price', 'quantity', 'discount', 'ticketFk', 'itemFk'], + include: [ + {relation: 'ticket'} + ] + } + }, + {relation: 'claimBeggining'} + ] + }; + promises.push(Self.app.models.ClaimEnd.find(filter)); + + let res = await Promise.all(promises); + + [summary.claim] = res[0]; + summary.salesClaimed = res[1]; + summary.developments = res[2]; + summary.actions = res[3]; + + return summary; + }; +}; diff --git a/modules/claim/back/methods/claim/regularizeClaim.js b/modules/claim/back/methods/claim/regularizeClaim.js new file mode 100644 index 000000000..136016b1e --- /dev/null +++ b/modules/claim/back/methods/claim/regularizeClaim.js @@ -0,0 +1,166 @@ +module.exports = Self => { + Self.remoteMethodCtx('regularizeClaim', { + description: 'Imports lines from claimBeginning to a new ticket with specific shipped, landed dates, agency and company', + accessType: 'WRITE', + accepts: [{ + arg: 'params', + type: 'object', + http: {source: 'body'} + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/regularizeClaim`, + verb: 'POST' + } + }); + + Self.regularizeClaim = async(ctx, params) => { + const userId = ctx.req.accessToken.userId; + const models = Self.app.models; + const resolvedState = 3; + + let tx = await Self.beginTransaction({}); + try { + let options = {transaction: tx}; + + const claimEnds = await models.ClaimEnd.find({ + include: { + relation: 'claimDestination', + fields: ['addressFk'] + }, + where: {claimFk: params.claimFk} + }, options); + + for (let i = 0; i < claimEnds.length; i++) { + const claimEnd = claimEnds[i]; + const destination = claimEnd.claimDestination(); + const addressFk = destination && destination.addressFk; + + if (!addressFk) + continue; + + let sale = await getSale(claimEnd.saleFk, options); + let ticketFk = await getTicketId({ + addressFk: addressFk, + companyFk: sale.ticket().companyFk, + warehouseFk: sale.ticket().warehouseFk + }, options); + + let address = await models.Address.findOne({ + where: {id: addressFk} + }, options); + + if (!ticketFk) { + ticketFk = await createTicket(ctx, { + clientFk: address.clientFk, + addressFk: addressFk, + warehouseFk: sale.ticket().warehouseFk, + companyFk: sale.ticket().companyFk, + userId: userId + }, options); + } + + await models.Sale.create({ + ticketFk: ticketFk, + itemFk: sale.itemFk, + concept: sale.concept, + quantity: -sale.quantity, + price: sale.price, + discount: 100 + }, options); + + if (sale.ticket().client().salesPerson()) { + await sendMessage(ctx, { + itemFk: sale.itemFk, + ticketFk: sale.ticketFk, + recipientFk: sale.ticket().client().salesPerson().userFk, + quantity: sale.quantity, + concept: sale.concept, + nickname: address.nickname + }, options); + } + } + + let claim = await Self.findById(params.claimFk, null, options); + claim = await claim.updateAttributes({ + claimStateFk: resolvedState + }, options); + + await tx.commit(); + + return claim; + } catch (e) { + await tx.rollback(); + throw e; + } + }; + + async function getSale(saleFk, options) { + return await Self.app.models.Sale.findOne({ + include: [ + { + relation: 'ticket', + scope: { + fields: ['clientFk', 'warehouseFk', 'companyFk'], + include: { + relation: 'client', + scope: { + include: { + relation: 'salesPerson' + } + } + } + } + }], + where: {id: saleFk} + }, options); + } + + async function getTicketId(params, options) { + const minDate = new Date(); + minDate.setHours(0, 0, 0, 0); + + const maxDate = new Date(); + maxDate.setHours(23, 59, 59, 59); + + let ticket = await Self.app.models.Ticket.findOne({ + where: { + addressFk: params.addressFk, + companyFk: params.companyFk, + warehouseFk: params.warehouseFk, + shipped: {between: [minDate, maxDate]}, + landed: {between: [minDate, maxDate]} + } + }, options); + + return ticket && ticket.id; + } + + async function createTicket(ctx, params, options) { + let ticket = await Self.app.models.Ticket.new(ctx, + { + shipped: new Date(), + landed: new Date(), + clientFk: params.clientFk, + warehouseFk: params.warehouseFk, + companyFk: params.companyFk, + addressFk: params.addressFk, + userId: params.userId + }, options); + + return ticket.id; + } + + async function sendMessage(ctx, params, options) { + const message = `Envio ${params.quantity} unidades de "${params.concept}" (#${params.itemFk}) a ` + + `"${params.nickname}" provenientes del ticket #${params.ticketFk}`; + + await Self.app.models.Message.send(ctx, { + recipientFk: params.recipientFk, + message: message + }, options); + } +}; diff --git a/modules/claim/back/methods/claim/specs/createFromSales.spec.js b/modules/claim/back/methods/claim/specs/createFromSales.spec.js new file mode 100644 index 000000000..226aeba53 --- /dev/null +++ b/modules/claim/back/methods/claim/specs/createFromSales.spec.js @@ -0,0 +1,55 @@ +const app = require('vn-loopback/server/server'); + +describe('Claim Create', () => { + let newDate = new Date(); + let createdClaimFk; + + afterAll(async done => { + await app.models.Claim.destroyById(createdClaimFk); + + done(); + }); + + let newClaim = { + ticketFk: 2, + clientFk: 101, + ticketCreated: newDate + }; + + let newSale = [{ + id: 3, + instance: 0, + quantity: 10 + }]; + + let params = {claim: newClaim, sales: newSale}; + let ctx = {req: {accessToken: {userId: 1}}}; + + it('should create a new claim', async() => { + let claim = await app.models.Claim.createFromSales(ctx, params); + + expect(claim.ticketFk).toEqual(newClaim.ticketFk); + expect(claim.clientFk).toEqual(newClaim.clientFk); + expect(claim.ticketCreated).toEqual(newClaim.ticketCreated); + expect(claim.workerFk).toEqual(newClaim.workerFk); + + let claimBeginning = await app.models.ClaimBeginning.findOne({where: {claimFk: claim.id}}); + + expect(claimBeginning.saleFk).toEqual(newSale[0].id); + expect(claimBeginning.quantity).toEqual(newSale[0].quantity); + + createdClaimFk = claim.id; + }); + + it('should not be able to create a claim if exists that sale', async() => { + let error; + + await app.models.Claim.createFromSales(ctx, params) + + .catch(e => { + error = e; + }); + + expect(error.toString()).toContain(`A claim with that sale already exists`); + }); +}); diff --git a/modules/claim/back/methods/claim/specs/filter.spec.js b/modules/claim/back/methods/claim/specs/filter.spec.js new file mode 100644 index 000000000..187fffaa4 --- /dev/null +++ b/modules/claim/back/methods/claim/specs/filter.spec.js @@ -0,0 +1,27 @@ +const app = require('vn-loopback/server/server'); + +describe('claim filter()', () => { + it('should return 1 result filtering by id', async() => { + let result = await app.models.Claim.filter({args: {filter: {}, search: 1}}); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(1); + }); + + it('should return 1 result filtering by string', async() => { + let result = await app.models.Claim.filter({args: {filter: {}, search: 'Tony Stark'}}); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(4); + }); + + it('should return 4 results filtering by worker id', async() => { + let result = await app.models.Claim.filter({args: {filter: {}, workerFk: 18}}); + + expect(result.length).toEqual(4); + expect(result[0].id).toEqual(1); + expect(result[1].id).toEqual(2); + expect(result[2].id).toEqual(3); + expect(result[3].id).toEqual(4); + }); +}); diff --git a/modules/claim/back/methods/claim/specs/getSummary.spec.js b/modules/claim/back/methods/claim/specs/getSummary.spec.js new file mode 100644 index 000000000..445903377 --- /dev/null +++ b/modules/claim/back/methods/claim/specs/getSummary.spec.js @@ -0,0 +1,13 @@ +const app = require('vn-loopback/server/server'); + +describe('claim getSummary()', () => { + it('should return summary with claim, salesClaimed, developments and actions defined ', async() => { + let result = await app.models.Claim.getSummary(1); + let keys = Object.keys(result); + + expect(keys).toContain('claim'); + expect(keys).toContain('salesClaimed'); + expect(keys).toContain('developments'); + expect(keys).toContain('actions'); + }); +}); diff --git a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js new file mode 100644 index 000000000..d838bc907 --- /dev/null +++ b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js @@ -0,0 +1,47 @@ +const app = require('vn-loopback/server/server'); + +describe('regularizeClaim()', () => { + const claimFk = 1; + const pendentState = 1; + const resolvedState = 3; + const trashDestination = 2; + const trashAddress = 12; + let claimEnds = []; + let trashTicket; + + afterAll(async done => { + let claim = await app.models.Claim.findById(claimFk); + await claim.updateAttributes({claimStateFk: pendentState}); + await app.models.Ticket.destroyById(trashTicket.id); + + claimEnds.forEach(async line => { + await line.destroy(); + }); + + done(); + }); + + it('should change claim state to resolved', async() => { + let ctx = {req: {accessToken: {userId: 18}}}; + let params = {claimFk: claimFk}; + + claimEnds = await app.models.ClaimEnd.importTicketSales(ctx, { + claimFk: claimFk, + ticketFk: 1 + }); + + claimEnds.forEach(async claimEnd => { + claimEnd.updateAttributes({claimDestinationFk: trashDestination}); + }); + + let claimBefore = await app.models.Claim.findById(params.claimFk); + await app.models.Claim.regularizeClaim(ctx, params); + let claimAfter = await app.models.Claim.findById(params.claimFk); + + trashTicket = await app.models.Ticket.findOne({where: {addressFk: 12}}); + + expect(trashTicket.addressFk).toEqual(trashAddress); + expect(claimBefore.claimStateFk).toEqual(pendentState); + expect(claimAfter.claimStateFk).toEqual(resolvedState); + }); +}); diff --git a/modules/claim/back/methods/claim/specs/updateClaim.spec.js b/modules/claim/back/methods/claim/specs/updateClaim.spec.js new file mode 100644 index 000000000..095e374bd --- /dev/null +++ b/modules/claim/back/methods/claim/specs/updateClaim.spec.js @@ -0,0 +1,94 @@ +const app = require('vn-loopback/server/server'); + +describe('Update Claim', () => { + let newDate = new Date(); + let newInstance; + let original = { + ticketFk: 3, + clientFk: 101, + ticketCreated: newDate, + workerFk: 18, + claimStateFk: 2, + isChargedToMana: true, + responsibility: 4, + observation: 'observation' + }; + + beforeAll(async done => { + newInstance = await app.models.Claim.create(original); + + done(); + }); + + afterAll(async done => { + await app.models.Claim.destroyById(newInstance.id); + + done(); + }); + + it(`should throw an error as the user doesn't have rights`, async() => { + const forbiddenState = 3; + const salesPersonId = 18; + let data = { + claimStateFk: forbiddenState, + observation: 'valid observation' + }; + let ctx = { + req: { + accessToken: { + userId: salesPersonId + } + } + }; + await app.models.Claim.updateClaim(ctx, newInstance.id, data) + .catch(e => { + error = e; + }); + + expect(error.message).toEqual(`You don't have enough privileges to change that field`); + }); + + it(`should success to update the claim within privileges `, async() => { + const correctState = 4; + const salesPersonId = 18; + let data = { + observation: 'valid observation', + claimStateFk: correctState, + }; + let ctx = { + req: { + accessToken: { + userId: salesPersonId + } + } + }; + await app.models.Claim.updateClaim(ctx, newInstance.id, data); + + let claimUpdated = await app.models.Claim.findById(newInstance.id); + + expect(claimUpdated.observation).toEqual(data.observation); + }); + + it('should change some sensible fields as salesAssistant', async() => { + const salesAssistantId = 21; + let data = { + claimStateFk: 3, + workerFk: 5, + observation: 'another valid observation' + }; + let ctx = { + req: { + accessToken: { + userId: salesAssistantId + } + } + }; + await app.models.Claim.updateClaim(ctx, newInstance.id, data); + + let claimUpdated = await app.models.Claim.findById(newInstance.id); + + expect(claimUpdated.observation).toEqual(data.observation); + expect(claimUpdated.claimStateFk).toEqual(data.claimStateFk); + expect(claimUpdated.workerFk).toEqual(data.workerFk); + }); +}); diff --git a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js new file mode 100644 index 000000000..3d3404ac5 --- /dev/null +++ b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js @@ -0,0 +1,43 @@ +const app = require('vn-loopback/server/server'); + +describe('Update Claim', () => { + let newDate = new Date(); + let newInstance; + let original = { + ticketFk: 3, + clientFk: 101, + ticketCreated: newDate, + workerFk: 18, + claimStateFk: 2, + isChargedToMana: true, + responsibility: 4, + observation: 'observation' + }; + + beforeAll(async done => { + newInstance = await app.models.Claim.create(original); + + done(); + }); + + afterAll(async done => { + await app.models.Claim.destroyById(newInstance.id); + done(); + }); + + it('should update the claim isChargedToMana attribute', async() => { + const data = {isChargedToMana: false}; + const result = await app.models.Claim.updateClaimAction(newInstance.id, data); + + expect(result.id).toEqual(newInstance.id); + expect(result.isChargedToMana).toBeFalsy(); + }); + + it('should update the claim responsibility attribute', async() => { + const data = {responsibility: 2}; + const result = await app.models.Claim.updateClaimAction(newInstance.id, data); + + expect(result.id).toEqual(newInstance.id); + expect(result.responsibility).toEqual(2); + }); +}); diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js new file mode 100644 index 000000000..51623a7a8 --- /dev/null +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -0,0 +1,56 @@ +const UserError = require('vn-loopback/util/user-error'); +module.exports = Self => { + Self.remoteMethodCtx('updateClaim', { + description: 'Update a claim with privileges', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'Claim id', + http: {source: 'path'} + }, { + arg: 'data', + type: 'object', + required: true, + description: 'Data to update on the model', + http: {source: 'body'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/updateClaim`, + verb: 'post' + } + }); + + Self.updateClaim = async(ctx, id, data) => { + let models = Self.app.models; + let claim = await models.Claim.findById(id); + + let canUpdate = await canChangeState(ctx, claim.claimStateFk); + let hasRights = await canChangeState(ctx, data.claimStateFk); + + if (!canUpdate || !hasRights) + throw new UserError(`You don't have enough privileges to change that field`); + + return await claim.updateAttributes(data); + }; + + async function canChangeState(ctx, id) { + let models = Self.app.models; + let userId = ctx.req.accessToken.userId; + + let state = await models.ClaimState.findById(id, { + include: { + relation: 'writeRole' + } + }); + let stateRole = state.writeRole().name; + let canUpdate = await models.Account.hasRole(userId, stateRole); + + return canUpdate; + } +}; diff --git a/modules/claim/back/methods/claim/updateClaimAction.js b/modules/claim/back/methods/claim/updateClaimAction.js new file mode 100644 index 000000000..c9c4f1043 --- /dev/null +++ b/modules/claim/back/methods/claim/updateClaimAction.js @@ -0,0 +1,43 @@ + +module.exports = Self => { + Self.remoteMethod('updateClaimAction', { + description: 'Update a claim with privileges', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'Claim id', + http: {source: 'path'} + }, { + arg: 'data', + type: 'object', + required: true, + description: 'Data to update on the model', + http: {source: 'body'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/updateClaimAction`, + verb: 'post' + } + }); + + Self.updateClaimAction = async(id, data) => { + let models = Self.app.models; + + let claim = await models.Claim.findById(id); + let updatedData = {}; + + if (data.hasOwnProperty('responsibility')) + updatedData.responsibility = data.responsibility; + + if (data.hasOwnProperty('isChargedToMana')) + updatedData.isChargedToMana = data.isChargedToMana; + + return await claim.updateAttributes(updatedData); + }; +}; diff --git a/modules/claim/back/methods/claim/uploadFile.js b/modules/claim/back/methods/claim/uploadFile.js new file mode 100644 index 000000000..c7565701d --- /dev/null +++ b/modules/claim/back/methods/claim/uploadFile.js @@ -0,0 +1,76 @@ +module.exports = Self => { + Self.remoteMethodCtx('uploadFile', { + description: 'Upload and attach a document', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'Number', + description: 'The claim id', + http: {source: 'path'} + }, { + arg: 'warehouseId', + type: 'Number', + description: 'The warehouse id', + required: true + }, { + arg: 'companyId', + type: 'Number', + description: 'The company id', + required: true + }, { + arg: 'dmsTypeId', + type: 'Number', + description: 'The dms type id', + required: true + }, { + arg: 'reference', + type: 'String', + required: true + }, { + arg: 'description', + type: 'String', + required: true + }, { + arg: 'hasFile', + type: 'Boolean', + description: 'True if has an attached file', + required: true + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/uploadFile`, + verb: 'POST' + } + }); + + Self.uploadFile = async(ctx, id) => { + const models = Self.app.models; + const promises = []; + const tx = await Self.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const uploadedFiles = await models.Dms.uploadFile(ctx, options); + uploadedFiles.forEach(dms => { + const newClaimDms = models.ClaimDms.create({ + claimFk: id, + dmsFk: dms.id + }, options); + + promises.push(newClaimDms); + }); + const resolvedPromises = await Promise.all(promises); + + await tx.commit(); + + return resolvedPromises; + } catch (err) { + await tx.rollback(); + throw err; + } + }; +}; diff --git a/modules/claim/back/model-config.json b/modules/claim/back/model-config.json new file mode 100644 index 000000000..16d34543c --- /dev/null +++ b/modules/claim/back/model-config.json @@ -0,0 +1,41 @@ +{ + "Claim": { + "dataSource": "vn" + }, + "ClaimBeginning": { + "dataSource": "vn" + }, + "ClaimDestination": { + "dataSource": "vn" + }, + "ClaimDevelopment": { + "dataSource": "vn" + }, + "ClaimEnd": { + "dataSource": "vn" + }, + "ClaimRatio": { + "dataSource": "vn" + }, + "ClaimReason": { + "dataSource": "vn" + }, + "ClaimRedelivery": { + "dataSource": "vn" + }, + "ClaimResponsible": { + "dataSource": "vn" + }, + "ClaimResult": { + "dataSource": "vn" + }, + "ClaimState": { + "dataSource": "vn" + }, + "ClaimDms": { + "dataSource": "vn" + }, + "ClaimLog": { + "dataSource": "vn" + } +} diff --git a/modules/claim/back/models/claim-beginning.js b/modules/claim/back/models/claim-beginning.js new file mode 100644 index 000000000..839044112 --- /dev/null +++ b/modules/claim/back/models/claim-beginning.js @@ -0,0 +1,7 @@ +module.exports = Self => { + require('../methods/claim-beginning/importToNewRefundTicket')(Self); + + Self.validatesUniquenessOf('saleFk', { + message: `A claim with that sale already exists` + }); +}; diff --git a/modules/claim/back/models/claim-beginning.json b/modules/claim/back/models/claim-beginning.json new file mode 100644 index 000000000..50506122a --- /dev/null +++ b/modules/claim/back/models/claim-beginning.json @@ -0,0 +1,32 @@ +{ + "name": "ClaimBeginning", + "base": "VnModel", + "options": { + "mysql": { + "table": "claimBeginning" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "quantity": { + "type": "Number", + "required": true + } + }, + "relations": { + "claim": { + "type": "belongsTo", + "model": "Claim", + "foreignKey": "claimFk" + }, + "sale": { + "type": "belongsTo", + "model": "Sale", + "foreignKey": "saleFk" + } + } +} diff --git a/modules/claim/back/models/claim-destination.json b/modules/claim/back/models/claim-destination.json new file mode 100644 index 000000000..8782fb815 --- /dev/null +++ b/modules/claim/back/models/claim-destination.json @@ -0,0 +1,35 @@ +{ + "name": "ClaimDestination", + "base": "VnModel", + "options": { + "mysql": { + "table": "claimDestination" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "description": { + "type": "String", + "required": true + } + }, + "relations": { + "address": { + "type": "belongsTo", + "model": "Address", + "foreignKey": "addressFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/modules/claim/back/models/claim-development.json b/modules/claim/back/models/claim-development.json new file mode 100644 index 000000000..94c677304 --- /dev/null +++ b/modules/claim/back/models/claim-development.json @@ -0,0 +1,63 @@ +{ + "name": "ClaimDevelopment", + "base": "VnModel", + "options": { + "mysql": { + "table": "claimDevelopment" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "claimFk": { + "required": true + }, + "claimResponsibleFk": { + "required": true + }, + "claimReasonFk": { + "required": true + }, + "claimResultFk": { + "required": true + }, + "claimRedeliveryFk": { + "required": true + } + }, + "relations": { + "claim": { + "type": "belongsTo", + "model": "Claim", + "foreignKey": "claimFk" + }, + "claimResponsible": { + "type": "belongsTo", + "model": "ClaimResponsible", + "foreignKey": "claimResponsibleFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "claimReason": { + "type": "belongsTo", + "model": "ClaimReason", + "foreignKey": "claimReasonFk" + }, + "claimResult": { + "type": "belongsTo", + "model": "ClaimResult", + "foreignKey": "claimResultFk" + }, + "claimRedelivery": { + "type": "belongsTo", + "model": "ClaimRedelivery", + "foreignKey": "claimRedeliveryFk" + } + } +} diff --git a/modules/claim/back/models/claim-dms.js b/modules/claim/back/models/claim-dms.js new file mode 100644 index 000000000..ab7beaaf5 --- /dev/null +++ b/modules/claim/back/models/claim-dms.js @@ -0,0 +1,4 @@ +module.exports = Self => { + require('../methods/claim-dms/removeFile')(Self); + require('../methods/claim-dms/allowedContentTypes')(Self); +}; diff --git a/modules/claim/back/models/claim-dms.json b/modules/claim/back/models/claim-dms.json new file mode 100644 index 000000000..9ef964886 --- /dev/null +++ b/modules/claim/back/models/claim-dms.json @@ -0,0 +1,37 @@ +{ + "name": "ClaimDms", + "base": "Loggable", + "log": { + "model": "ClaimLog", + "relation": "claim" + }, + "options": { + "mysql": { + "table": "claimDms" + } + }, + "allowedContentTypes": [ + "image/png", + "image/jpeg", + "image/jpg" + ], + "properties": { + "dmsFk": { + "type": "Number", + "id": true, + "required": true + } + }, + "relations": { + "claim": { + "type": "belongsTo", + "model": "Claim", + "foreignKey": "claimFk" + }, + "dms": { + "type": "belongsTo", + "model": "Dms", + "foreignKey": "dmsFk" + } + } +} \ No newline at end of file diff --git a/modules/claim/back/models/claim-end.js b/modules/claim/back/models/claim-end.js new file mode 100644 index 000000000..73531cdfc --- /dev/null +++ b/modules/claim/back/models/claim-end.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/claim-end/importTicketSales')(Self); +}; diff --git a/modules/claim/back/models/claim-end.json b/modules/claim/back/models/claim-end.json new file mode 100644 index 000000000..8f835ee84 --- /dev/null +++ b/modules/claim/back/models/claim-end.json @@ -0,0 +1,43 @@ +{ + "name": "ClaimEnd", + "base": "VnModel", + "options": { + "mysql": { + "table": "claimEnd" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + } + }, + "relations": { + "claim": { + "type": "belongsTo", + "model": "Claim", + "foreignKey": "claimFk" + }, + "sale": { + "type": "belongsTo", + "model": "Sale", + "foreignKey": "saleFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "claimDestination": { + "type": "belongsTo", + "model": "ClaimDestination", + "foreignKey": "claimDestinationFk" + }, + "claimBeggining": { + "type": "belongsTo", + "model": "ClaimDestination", + "foreignKey": "claimDestinationFk" + } + } +} diff --git a/modules/claim/back/models/claim-log.json b/modules/claim/back/models/claim-log.json new file mode 100644 index 000000000..28b3f88ec --- /dev/null +++ b/modules/claim/back/models/claim-log.json @@ -0,0 +1,58 @@ +{ + "name": "ClaimLog", + "base": "VnModel", + "options": { + "mysql": { + "table": "claimLog" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "forceId": false + }, + "originFk": { + "type": "Number", + "required": true + }, + "userFk": { + "type": "Number" + }, + "action": { + "type": "String", + "required": true + }, + "changedModel": { + "type": "String" + }, + "oldInstance": { + "type": "Object" + }, + "newInstance": { + "type": "Object" + }, + "creationDate": { + "type": "Date" + }, + "changedModelId": { + "type": "Number" + }, + "changedModelValue": { + "type": "String" + }, + "description": { + "type": "String" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + } + }, + "scope": { + "order": ["creationDate DESC", "id DESC"] + } +} diff --git a/modules/claim/back/models/claim-ratio.json b/modules/claim/back/models/claim-ratio.json new file mode 100644 index 000000000..196db72f6 --- /dev/null +++ b/modules/claim/back/models/claim-ratio.json @@ -0,0 +1,38 @@ +{ + "name": "ClaimRatio", + "base": "VnModel", + "options": { + "mysql": { + "table": "claimRatio" + } + }, + "validateUpsert": true, + "properties": { + "clientFk": { + "type": "Number", + "id": true + }, + "yearSale": { + "type": "Number" + }, + "claimAmount": { + "type": "Number" + }, + "claimingRate": { + "type": "Number" + }, + "priceIncreasing": { + "type": "Number" + }, + "packingRate": { + "type": "Number" + } + }, + "relations": { + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "clientFk" + } + } +} \ No newline at end of file diff --git a/modules/claim/back/models/claim-reason.json b/modules/claim/back/models/claim-reason.json new file mode 100644 index 000000000..562acc14e --- /dev/null +++ b/modules/claim/back/models/claim-reason.json @@ -0,0 +1,27 @@ +{ + "name": "ClaimReason", + "base": "VnModel", + "options": { + "mysql": { + "table": "claimReason" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "description": { + "type": "String" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/modules/claim/back/models/claim-redelivery.json b/modules/claim/back/models/claim-redelivery.json new file mode 100644 index 000000000..8611a3a44 --- /dev/null +++ b/modules/claim/back/models/claim-redelivery.json @@ -0,0 +1,28 @@ +{ + "name": "ClaimRedelivery", + "base": "VnModel", + "options": { + "mysql": { + "table": "claimRedelivery" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "description": { + "type": "String", + "required": true + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/modules/claim/back/models/claim-responsible.json b/modules/claim/back/models/claim-responsible.json new file mode 100644 index 000000000..6bd06605b --- /dev/null +++ b/modules/claim/back/models/claim-responsible.json @@ -0,0 +1,32 @@ +{ + "name": "ClaimResponsible", + "base": "VnModel", + "options": { + "mysql": { + "table": "claimResponsible" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "description": { + "type": "String", + "required": true + }, + "responsability": { + "type": "Number", + "required": true + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/modules/claim/back/models/claim-result.json b/modules/claim/back/models/claim-result.json new file mode 100644 index 000000000..468f271de --- /dev/null +++ b/modules/claim/back/models/claim-result.json @@ -0,0 +1,27 @@ +{ + "name": "ClaimResult", + "base": "VnModel", + "options": { + "mysql": { + "table": "claimResult" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "description": { + "type": "String" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/modules/claim/back/models/claim-state.json b/modules/claim/back/models/claim-state.json new file mode 100644 index 000000000..bf2554f38 --- /dev/null +++ b/modules/claim/back/models/claim-state.json @@ -0,0 +1,35 @@ +{ + "name": "ClaimState", + "base": "VnModel", + "options": { + "mysql": { + "table": "claimState" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "description": { + "type": "String", + "required": true + } + }, + "relations": { + "writeRole": { + "type": "belongsTo", + "model": "Role", + "foreignKey": "roleFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/modules/claim/back/models/claim.js b/modules/claim/back/models/claim.js new file mode 100644 index 000000000..234a95434 --- /dev/null +++ b/modules/claim/back/models/claim.js @@ -0,0 +1,9 @@ +module.exports = Self => { + require('../methods/claim/filter')(Self); + require('../methods/claim/getSummary')(Self); + require('../methods/claim/createFromSales')(Self); + require('../methods/claim/updateClaim')(Self); + require('../methods/claim/regularizeClaim')(Self); + require('../methods/claim/uploadFile')(Self); + require('../methods/claim/updateClaimAction')(Self); +}; diff --git a/modules/claim/back/models/claim.json b/modules/claim/back/models/claim.json new file mode 100644 index 000000000..1462c4222 --- /dev/null +++ b/modules/claim/back/models/claim.json @@ -0,0 +1,63 @@ +{ + "name": "Claim", + "base": "VnModel", + "options": { + "mysql": { + "table": "claim" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "observation": { + "type": "String" + }, + "ticketCreated": { + "type": "date", + "required": true + }, + "isChargedToMana": { + "type": "boolean" + }, + "created": { + "type": "date" + }, + "responsibility": { + "type": "Number" + }, + "ticketFk": { + "type": "Number" + }, + "claimStateFk": { + "type": "Number" + }, + "workerFk": { + "type": "Number" + } + }, + "relations": { + "claimState": { + "type": "belongsTo", + "model": "ClaimState", + "foreignKey": "claimStateFk" + }, + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "clientFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk" + } + } +} diff --git a/modules/claim/front/action/index.html b/modules/claim/front/action/index.html new file mode 100644 index 000000000..7c663eacd --- /dev/null +++ b/modules/claim/front/action/index.html @@ -0,0 +1,205 @@ + + + + + + + + + + + + +
    + + + + + + + + + + +
    + + + + + + Id + Ticket + Destination + Landed + Quantity + Description + Price + Disc. + Total + + + + + + + {{::saleClaimed.sale.itemFk | zeroFill:6}} + + + + + {{::saleClaimed.sale.ticketFk}} + + + + + + + {{::saleClaimed.sale.ticket.landed | date: 'dd/MM/yyyy'}} + {{::saleClaimed.sale.quantity}} + {{::saleClaimed.sale.concept}} + {{::saleClaimed.sale.price | currency: 'EUR':2}} + {{::saleClaimed.sale.discount}} % + + {{saleClaimed.sale.quantity * saleClaimed.sale.price * + ((100 - saleClaimed.sale.discount) / 100) | currency: 'EUR':2}} + + + + + + + + + + + + + + +
    + + + + +

    Claimable sales from ticket

    {{$ctrl.claim.ticketFk}}

    + + + + Id + Landed + Quantity + Description + Price + Disc. + Total + + + + + {{sale.saleFk}} + {{sale.landed | date: 'dd/MM/yyyy'}} + {{sale.quantity}} + {{sale.concept}} + {{sale.price | currency: 'EUR':2}} + {{sale.discount}} % + + {{sale.quantity * sale.price * ((100 - sale.discount) * / 100) | currency: 'EUR':2}} + + + + +
    +
    + + + + +
    + + + + ID + F. envio + Agencia + Almacen + + + + + {{::ticket.id}} + {{::ticket.shipped | date: 'dd/MM/yyyy'}} + {{::ticket.agencyMode.name}} + {{::ticket.warehouse.name}} + + + +
    +
    + + + + + + \ No newline at end of file diff --git a/modules/claim/front/action/index.js b/modules/claim/front/action/index.js new file mode 100644 index 000000000..7d67d58c9 --- /dev/null +++ b/modules/claim/front/action/index.js @@ -0,0 +1,187 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($stateParams, $scope, $http, $translate, vnApp) { + this.$stateParams = $stateParams; + this.$ = $scope; + this.$http = $http; + this.$translate = $translate; + this.vnApp = vnApp; + this.filter = { + where: {claimFk: $stateParams.id}, + include: [ + {relation: 'sale', + scope: { + fields: ['concept', 'ticketFk', 'price', 'quantity', 'discount', 'itemFk'], + include: { + relation: 'ticket' + } + } + }, + {relation: 'claimBeggining'}, + {relation: 'claimDestination'} + ] + }; + this.resolvedState = 3; + this.maxResponsibility = 5; + } + + openAddSalesDialog() { + this.getClaimedSales(); + this.$.addSales.show(); + } + + getClaimedSales() { + let json = encodeURIComponent(JSON.stringify(this.claim.id)); + + let query = `ClaimBeginnings/${json}`; + this.$http.get(query).then(res => { + if (res.data) + this.claimedSales = res.data; + }); + } + + addClaimedSale(saleFk) { + let saleToAdd = {saleFk: saleFk, claimFk: this.claim.id, workerFk: this.claim.workerFk, claimDestinationFk: 1}; + let query = `ClaimEnds/`; + this.$http.post(query, saleToAdd).then(() => { + this.$.model.refresh(); + this.$.addSales.hide(); + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }); + } + + deleteClaimedSale(id) { + let json = encodeURIComponent(JSON.stringify(id)); + let query = `ClaimEnds/${json}`; + this.$http.delete(query).then(() => { + this.$.model.refresh(); + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }); + } + + importToNewRefundTicket() { + let query = `ClaimBeginnings/${this.$stateParams.id}/importToNewRefundTicket`; + return this.$http.post(query).then(() => { + this.$.model.refresh(); + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }); + } + + showTicketDescriptor(event, ticketFk) { + this.$.ticketDescriptor.ticketFk = ticketFk; + this.$.ticketDescriptor.parent = event.target; + this.$.ticketDescriptor.show(); + + event.preventDefault(); + } + + focusLastInput() { + let inputs = document.querySelectorAll('#claimDestinationFk'); + inputs[inputs.length - 1].querySelector('input').focus(); + this.calculateTotals(); + } + + calculateTotals() { + this.claimedTotal = 0; + this.salesClaimed.forEach(sale => { + this.claimedTotal += (sale.sale.quantity * sale.sale.price) - ((sale.sale.discount * (sale.sale.quantity * sale.sale.price)) / 100); + }); + } + + showLastTickets(event) { + let pastWeek = new Date(); + pastWeek.setDate(-7); + + let filter = { + include: [ + {relation: 'agencyMode', fields: ['name']}, + {relation: 'warehouse', fields: ['name']} + ], + where: { + created: {gt: pastWeek}, + clientFk: this.claim.clientFk + } + }; + this.$.lastTicketsModel.filter = filter; + this.$.lastTicketsModel.refresh(); + this.$.lastTicketsPopover.parent = event.target; + this.$.lastTicketsPopover.show(); + } + + importTicketLines(ticketFk) { + let data = {claimFk: this.$stateParams.id, ticketFk: ticketFk}; + + let query = `ClaimEnds/importTicketSales`; + this.$http.post(query, data).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$.lastTicketsPopover.hide(); + this.$.model.refresh(); + }); + } + + regularize() { + let data = {claimFk: this.$stateParams.id}; + let query = `Claims/regularizeClaim`; + return this.$http.post(query, data).then(() => { + this.card.reload(); + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + if (this.claim.responsibility >= Math.ceil(this.maxResponsibility) / 2) + this.$.updateGreuge.show(); + }); + } + + onUpdateGreugeResponse(response) { + if (response !== 'accept') + return; + let greugeTypeFreight = 7; + let query = `Greuges/`; + let data = { + clientFk: this.claim.clientFk, + description: `claim: ${this.claim.id}`, + amount: 11, + greugeTypeFk: greugeTypeFreight, + ticketFk: this.claim.ticketFk + }; + + this.$http.post(query, data).then(() => { + this.card.reload(); + this.vnApp.showSuccess(this.$translate.instant('Greuge inserted!')); + }); + } + // Item Descriptor + showDescriptor(event, itemFk) { + this.$.descriptor.itemFk = itemFk; + this.$.descriptor.parent = event.target; + this.$.descriptor.show(); + } + + saveResponsibility(value) { + let query = `Claims/${this.$stateParams.id}/updateClaimAction`; + + this.$http.post(query, {responsibility: value}).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }); + } + saveMana(value) { + let query = `Claims/${this.$stateParams.id}/updateClaimAction`; + + this.$http.post(query, {isChargedToMana: value}).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }); + } +} + +Controller.$inject = ['$stateParams', '$scope', '$http', '$translate', 'vnApp']; + +ngModule.component('vnClaimAction', { + template: require('./index.html'), + controller: Controller, + bindings: { + claim: '<' + }, + require: { + card: '^vnClaimCard' + } +}); diff --git a/modules/claim/front/action/index.spec.js b/modules/claim/front/action/index.spec.js new file mode 100644 index 000000000..56597fd2f --- /dev/null +++ b/modules/claim/front/action/index.spec.js @@ -0,0 +1,185 @@ +import './index.js'; +import crudModel from 'core/mocks/crud-model'; + +describe('claim', () => { + describe('Component vnClaimAction', () => { + let controller; + let $httpBackend; + let $state; + + beforeEach(ngModule('claim')); + + beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + $state = _$state_; + $state.params.id = 1; + + controller = $componentController('vnClaimAction', {$state}); + controller.claim = {ticketFk: 1}; + controller.$.model = {refresh: () => {}}; + controller.$.addSales = { + hide: () => {}, + show: () => {} + }; + controller.$.lastTicketsModel = crudModel; + controller.$.lastTicketsPopover = { + hide: () => {}, + show: () => {} + }; + controller.card = {reload: () => {}}; + })); + + describe('openAddSalesDialog()', () => { + it('should call getClaimableFromTicket and $.addSales.show', () => { + controller.$ = {addSales: {show: () => {}}}; + spyOn(controller, 'getClaimedSales'); + spyOn(controller.$.addSales, 'show'); + controller.openAddSalesDialog(); + + expect(controller.getClaimedSales).toHaveBeenCalledWith(); + expect(controller.$.addSales.show).toHaveBeenCalledWith(); + }); + }); + + describe('getClaimedSales()', () => { + it('should make a query and set salesToClaim', () => { + controller.claim.id = 1; + $httpBackend.expectGET(`ClaimBeginnings/1`).respond(200, 1); + controller.getClaimedSales(); + $httpBackend.flush(); + + expect(controller.claimedSales).toEqual(1); + }); + }); + + describe('addClaimedSale(saleFk)', () => { + it('should make a post and call refresh, hide and showSuccess', () => { + spyOn(controller.$.model, 'refresh'); + spyOn(controller.$.addSales, 'hide'); + spyOn(controller.vnApp, 'showSuccess'); + $httpBackend.expectPOST(`ClaimEnds/`).respond({}); + controller.addClaimedSale(1); + $httpBackend.flush(); + + expect(controller.$.model.refresh).toHaveBeenCalledWith(); + expect(controller.$.addSales.hide).toHaveBeenCalledWith(); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + }); + }); + + describe('deleteClaimedSale(id)', () => { + it('should make a delete and call refresh and showSuccess', () => { + spyOn(controller.$.model, 'refresh'); + spyOn(controller.vnApp, 'showSuccess'); + $httpBackend.expectDELETE(`ClaimEnds/1`).respond({}); + controller.deleteClaimedSale(1); + $httpBackend.flush(); + + expect(controller.$.model.refresh).toHaveBeenCalledWith(); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + }); + }); + + describe('calculateTotals()', () => { + it('should calculate the total price of the items claimed', () => { + controller.salesClaimed = [ + {sale: {quantity: 5, price: 2, discount: 0}}, + {sale: {quantity: 10, price: 2, discount: 0}}, + {sale: {quantity: 10, price: 2, discount: 0}} + ]; + controller.calculateTotals(); + + expect(controller.claimedTotal).toEqual(50); + }); + }); + + describe('importToNewRefundTicket()', () => { + it('should perform a post query and add lines from a new ticket', () => { + spyOn(controller.$.model, 'refresh'); + spyOn(controller.vnApp, 'showSuccess'); + $httpBackend.expect('POST', `ClaimBeginnings/1/importToNewRefundTicket`).respond({}); + controller.importToNewRefundTicket(); + $httpBackend.flush(); + + expect(controller.$.model.refresh).toHaveBeenCalledWith(); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + }); + }); + + describe('showLastTickets()', () => { + it('should get a list of tickets and call lastTicketsPopover show() method', () => { + spyOn(controller.$.lastTicketsModel, 'refresh'); + spyOn(controller.$.lastTicketsPopover, 'show'); + controller.showLastTickets({}); + + expect(controller.$.lastTicketsModel.refresh).toHaveBeenCalledWith(); + expect(controller.$.lastTicketsPopover.show).toHaveBeenCalledWith(); + }); + }); + + describe('importTicketLines()', () => { + it('should perform a post query and add lines from an existent ticket', () => { + spyOn(controller.$.model, 'refresh'); + spyOn(controller.vnApp, 'showSuccess'); + spyOn(controller.$.lastTicketsPopover, 'hide'); + let data = {claimFk: 1, ticketFk: 1}; + $httpBackend.expect('POST', `ClaimEnds/importTicketSales`, data).respond({}); + controller.importTicketLines(1); + $httpBackend.flush(); + + expect(controller.$.model.refresh).toHaveBeenCalledWith(); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + expect(controller.$.lastTicketsPopover.hide).toHaveBeenCalledWith(); + }); + }); + + describe('regularize()', () => { + it('should perform a post query and reload the claim card', () => { + spyOn(controller.card, 'reload'); + spyOn(controller.vnApp, 'showSuccess'); + + let data = {claimFk: $state.params.id}; + $httpBackend.expect('POST', `Claims/regularizeClaim`, data).respond({}); + controller.regularize(); + $httpBackend.flush(); + + expect(controller.card.reload).toHaveBeenCalledWith(); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + }); + }); + + describe('onUpdateGreugeResponse()', () => { + it('should do nothing', () => { + spyOn(controller.$http, 'post'); + spyOn(controller.card, 'reload'); + spyOn(controller.vnApp, 'showSuccess'); + + controller.onUpdateGreugeResponse('cancel'); + + expect(controller.$http.post).not.toHaveBeenCalledWith(); + expect(controller.card.reload).not.toHaveBeenCalledWith(); + expect(controller.vnApp.showSuccess).not.toHaveBeenCalledWith('Greuge inserted!'); + }); + + it('should perform a insert into greuges', () => { + spyOn(controller.card, 'reload'); + spyOn(controller.vnApp, 'showSuccess'); + controller.claim.clientFk = 101; + controller.claim.id = 11; + let data = { + clientFk: 101, + description: `claim: ${controller.claim.id}`, + amount: 11, + greugeTypeFk: 7, + ticketFk: controller.claim.ticketFk + }; + $httpBackend.expect('POST', `Greuges/`, data).respond(); + controller.onUpdateGreugeResponse('accept'); + $httpBackend.flush(); + + expect(controller.card.reload).toHaveBeenCalledWith(); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Greuge inserted!'); + }); + }); + }); +}); diff --git a/modules/claim/front/action/locale/es.yml b/modules/claim/front/action/locale/es.yml new file mode 100644 index 000000000..3950ec06a --- /dev/null +++ b/modules/claim/front/action/locale/es.yml @@ -0,0 +1,11 @@ +Destination: Destino +Action: Actuaciones +Total claimed: Total Reclamado +Import claim: Importar reclamacion +Imports claim details: Importa detalles de la reclamacion +Import ticket: Importar ticket +Imports ticket lines: Importa las lineas de un ticket +Regularize: Regularizar +Do you want to insert greuges?: Desea insertar greuges? +Insert greuges on client card: Insertar greuges en la ficha del cliente +Greuge inserted: Greuge insertado \ No newline at end of file diff --git a/modules/claim/front/action/style.scss b/modules/claim/front/action/style.scss new file mode 100644 index 000000000..aef8d2cfd --- /dev/null +++ b/modules/claim/front/action/style.scss @@ -0,0 +1,42 @@ +vn-claim-action { + .header { + display: flex; + justify-content: space-between; + align-items: center; + align-content: center; + + vn-tool-bar { + flex: 1 + } + + .vn-check { + flex: none; + } + } + + vn-dialog[vn-id=addSales] { + tpl-body { + width: 950px; + div { + div.buttons { + display: none; + } + vn-table{ + min-width: 950px; + } + } + } + } + + vn-popover.lastTicketsPopover { + vn-table { + min-width: 650px; + overflow: auto + } + + div.ticketList { + overflow: auto; + max-height: 350px + } + } +} \ No newline at end of file diff --git a/modules/claim/front/basic-data/index.html b/modules/claim/front/basic-data/index.html new file mode 100644 index 000000000..9be04cb57 --- /dev/null +++ b/modules/claim/front/basic-data/index.html @@ -0,0 +1,60 @@ + + +
    + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/modules/claim/front/basic-data/index.js b/modules/claim/front/basic-data/index.js new file mode 100644 index 000000000..bc616dd5c --- /dev/null +++ b/modules/claim/front/basic-data/index.js @@ -0,0 +1,28 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $state, aclService) { + this.$scope = $scope; + this.$state = $state; + this.$stateParams = $state.params; + this.aclService = aclService; + } + + onSubmit() { + this.$scope.watcher.submit().then(() => { + if (this.aclService.hasAny(['salesAssistant'])) + this.$state.go('claim.card.detail'); + }); + } +} + +Controller.$inject = ['$scope', '$state', 'aclService']; + +ngModule.component('vnClaimBasicData', { + template: require('./index.html'), + controller: Controller, + bindings: { + claim: '<' + } +}); diff --git a/modules/claim/front/basic-data/index.spec.js b/modules/claim/front/basic-data/index.spec.js new file mode 100644 index 000000000..187fca275 --- /dev/null +++ b/modules/claim/front/basic-data/index.spec.js @@ -0,0 +1,27 @@ +import './index.js'; +import watcher from 'core/mocks/watcher'; + +describe('Claim', () => { + describe('Component vnClaimBasicData', () => { + let controller; + let $scope; + + beforeEach(ngModule('claim')); + + beforeEach(angular.mock.inject(($componentController, $rootScope) => { + $scope = $rootScope.$new(); + $scope.watcher = watcher; + let aclService = {hasAny: () => true}; + controller = $componentController('vnClaimBasicData', {$scope, aclService}); + })); + + describe('onSubmit()', () => { + it(`should redirect to 'claim.card.detail' state`, () => { + spyOn(controller.$state, 'go'); + controller.onSubmit(); + + expect(controller.$state.go).toHaveBeenCalledWith('claim.card.detail'); + }); + }); + }); +}); diff --git a/modules/claim/front/basic-data/locale/es.yml b/modules/claim/front/basic-data/locale/es.yml new file mode 100644 index 000000000..221b17cdc --- /dev/null +++ b/modules/claim/front/basic-data/locale/es.yml @@ -0,0 +1,6 @@ +Contact: Contacto +Claim state: Estado de la reclamación +Is paid with mana: Cargado al maná +Responsability: Responsabilidad +Company: Empresa +Sales/Client: Comercial/Cliente \ No newline at end of file diff --git a/modules/claim/front/basic-data/style.scss b/modules/claim/front/basic-data/style.scss new file mode 100644 index 000000000..5f1432879 --- /dev/null +++ b/modules/claim/front/basic-data/style.scss @@ -0,0 +1,3 @@ +vn-claim-basic-data vn-date-picker { + padding-left: 5em; +} diff --git a/modules/claim/front/card/index.html b/modules/claim/front/card/index.html new file mode 100644 index 000000000..1db6b38db --- /dev/null +++ b/modules/claim/front/card/index.html @@ -0,0 +1,5 @@ + + + + + diff --git a/modules/claim/front/card/index.js b/modules/claim/front/card/index.js new file mode 100644 index 000000000..ccd78a271 --- /dev/null +++ b/modules/claim/front/card/index.js @@ -0,0 +1,62 @@ +import ngModule from '../module'; +import ModuleCard from 'salix/components/module-card'; + +class Controller extends ModuleCard { + reload() { + let filter = { + include: [ + { + relation: 'worker', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + }, { + relation: 'ticket', + scope: { + fields: ['agencyModeFk'], + include: { + relation: 'agencyMode' + } + } + }, { + relation: 'claimState', + scope: { + fields: ['id', 'description'] + } + }, { + relation: 'client', + scope: { + fields: ['salesPersonFk', 'name', 'email'], + include: { + relation: 'salesPerson', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + + } + } + } + ] + }; + + this.$http.get(`Claims/${this.$params.id}`, {filter}) + .then(res => this.claim = res.data); + } +} + +ngModule.vnComponent('vnClaimCard', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/claim/front/card/index.spec.js b/modules/claim/front/card/index.spec.js new file mode 100644 index 000000000..1b2344925 --- /dev/null +++ b/modules/claim/front/card/index.spec.js @@ -0,0 +1,29 @@ +import './index.js'; + +describe('Claim', () => { + describe('Component vnClaimCard', () => { + let controller; + let $httpBackend; + let data = {id: 1, name: 'fooName'}; + + beforeEach(ngModule('claim')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_, $stateParams) => { + $httpBackend = _$httpBackend_; + + let $element = angular.element('
    '); + controller = $componentController('vnClaimCard', {$element}); + + $stateParams.id = data.id; + $httpBackend.whenRoute('GET', 'Claims/:id').respond(data); + })); + + it('should request data and set it on the controller', () => { + controller.reload(); + $httpBackend.flush(); + + expect(controller.claim).toEqual(data); + }); + }); +}); + diff --git a/modules/claim/front/descriptor/index.html b/modules/claim/front/descriptor/index.html new file mode 100644 index 000000000..789df37d6 --- /dev/null +++ b/modules/claim/front/descriptor/index.html @@ -0,0 +1,62 @@ +
    +
    + + + + + + + + +
    +
    +
    +
    {{$ctrl.claim.id}}
    + + + + + + + + + + + + + + +
    + + +
    +
    + + + + + diff --git a/modules/claim/front/descriptor/index.js b/modules/claim/front/descriptor/index.js new file mode 100644 index 000000000..7bc9c831a --- /dev/null +++ b/modules/claim/front/descriptor/index.js @@ -0,0 +1,116 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $state, $http, $translate, vnApp, aclService, $httpParamSerializer) { + this.$scope = $scope; + this.$state = $state; + this.$http = $http; + this.$translate = $translate; + this.vnApp = vnApp; + this.aclService = aclService; + this.$httpParamSerializer = $httpParamSerializer; + this.moreOptions = [ + {callback: this.showPickupOrder, name: 'Show Pickup order'}, + {callback: this.confirmPickupOrder, name: 'Send Pickup order'}, + {callback: this.confirmDeleteClaim, name: 'Delete claim', acl: 'salesAssistant'} + ]; + } + + onMoreOpen() { + let options = this.moreOptions.filter(option => { + const hasAclProperty = Object.hasOwnProperty.call(option, 'acl'); + + return !hasAclProperty || (hasAclProperty && this.aclService.hasAny([option.acl])); + }); + this.$scope.moreButton.data = options; + } + + onMoreChange(callback) { + callback.call(this); + } + + get claim() { + return this._claim; + } + + set claim(value) { + this._claim = value; + + if (!value) return; + + this._quicklinks = { + btnOne: { + icon: 'person', + state: `client.card.summary({id: ${value.clientFk}})`, + tooltip: 'Client card' + }, + btnTwo: { + icon: 'icon-ticket', + state: `ticket.card.summary({id: ${this.claim.ticketFk}})`, + tooltip: 'Claimed ticket' + } + }; + } + + set quicklinks(value = {}) { + this._quicklinks = Object.assign(value, this._quicklinks); + } + + get quicklinks() { + return this._quicklinks; + } + + showPickupOrder() { + const params = { + clientId: this.claim.clientFk, + claimId: this.claim.id + }; + const serializedParams = this.$httpParamSerializer(params); + let url = `api/report/claim-pickup-order?${serializedParams}`; + window.open(url); + } + + confirmPickupOrder() { + this.$scope.confirmPickupOrder.show(); + } + + sendPickupOrder(response) { + if (response === 'accept') { + const params = { + recipient: this.claim.client.email, + clientId: this.claim.clientFk, + claimId: this.claim.id + }; + const serializedParams = this.$httpParamSerializer(params); + const url = `email/claim-pickup-order?${serializedParams}`; + this.$http.get(url).then( + () => this.vnApp.showMessage(this.$translate.instant('Notification sent!')) + ); + } + } + + confirmDeleteClaim() { + this.$scope.confirmDeleteClaim.show(); + } + + deleteClaim(response) { + if (response === 'accept') { + this.$http.delete(`Claims/${this.claim.id}`).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Claim deleted!')); + this.$state.go('claim.index'); + }); + } + } +} + +Controller.$inject = ['$scope', '$state', '$http', '$translate', 'vnApp', 'aclService', '$httpParamSerializer']; + +ngModule.component('vnClaimDescriptor', { + template: require('./index.html'), + controller: Controller, + bindings: { + claim: '<', + tags: '<', + quicklinks: '<' + } +}); diff --git a/modules/claim/front/descriptor/index.spec.js b/modules/claim/front/descriptor/index.spec.js new file mode 100644 index 000000000..87da181fa --- /dev/null +++ b/modules/claim/front/descriptor/index.spec.js @@ -0,0 +1,93 @@ +import './index.js'; + +describe('Item Component vnClaimDescriptor', () => { + let $httpParamSerializer; + let $httpBackend; + let controller; + + beforeEach(ngModule('claim')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_, _$httpParamSerializer_) => { + $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; + controller = $componentController('vnClaimDescriptor'); + controller.claim = {id: 2, clientFk: 101, client: {email: 'client@email'}}; + })); + + describe('showPickupOrder()', () => { + it('should open a new window showing a pickup order PDF document', () => { + const params = { + clientId: controller.claim.clientFk, + claimId: controller.claim.id + }; + const serializedParams = $httpParamSerializer(params); + let expectedPath = `api/report/claim-pickup-order?${serializedParams}`; + spyOn(window, 'open'); + controller.showPickupOrder(); + + expect(window.open).toHaveBeenCalledWith(expectedPath); + }); + }); + + describe('confirmPickupOrder()', () => { + it('should call confirmPickupOrder.show()', () => { + controller.$scope.confirmPickupOrder = { + show: jasmine.createSpy('show') + }; + controller.claim = {id: 2}; + controller.confirmPickupOrder(); + + expect(controller.$scope.confirmPickupOrder.show).toHaveBeenCalledWith(); + }); + }); + + describe('sendPickupOrder(response)', () => { + it('should make a query and call vnApp.showMessage() if the response is accept', () => { + spyOn(controller.vnApp, 'showMessage'); + + const params = { + recipient: 'client@email', + clientId: controller.claim.clientFk, + claimId: controller.claim.id + }; + const serializedParams = $httpParamSerializer(params); + + $httpBackend.when('GET', `email/claim-pickup-order?${serializedParams}`).respond(); + $httpBackend.expect('GET', `email/claim-pickup-order?${serializedParams}`).respond(); + controller.sendPickupOrder('accept'); + $httpBackend.flush(); + + expect(controller.vnApp.showMessage).toHaveBeenCalledWith('Notification sent!'); + }); + }); + + describe('confirmDeleteClaim()', () => { + it('should call confirmDeleteClaim.show()', () => { + controller.$scope.confirmDeleteClaim = { + show: jasmine.createSpy('show') + }; + controller.claim = {id: 2}; + controller.confirmDeleteClaim(); + + expect(controller.$scope.confirmDeleteClaim.show).toHaveBeenCalledWith(); + }); + }); + + describe('deleteClaime(response)', () => { + it('should perform a query and call showSuccess if the response is accept', () => { + let response = 'accept'; + controller.claim = {id: 2}; + + spyOn(controller.vnApp, 'showSuccess'); + spyOn(controller.$state, 'go'); + $httpBackend.when('DELETE', `Claims/2`).respond(200); + $httpBackend.expect('DELETE', `Claims/2`); + controller.deleteClaim(response); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Claim deleted!'); + expect(controller.$state.go).toHaveBeenCalledWith('claim.index'); + }); + }); +}); + diff --git a/modules/claim/front/detail/index.html b/modules/claim/front/detail/index.html new file mode 100644 index 000000000..7551be257 --- /dev/null +++ b/modules/claim/front/detail/index.html @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + Landed + Quantity + Claimed + Description + Price + Disc. + Total + + + + + + {{::saleClaimed.sale.ticket.landed | date:'dd/MM/yyyy'}} + {{::saleClaimed.sale.quantity}} + + + + + + + {{::saleClaimed.sale.concept}} + + + {{::saleClaimed.sale.price | currency: 'EUR':2}} + + + {{saleClaimed.sale.discount}} % + + + + {{$ctrl.getSaleTotal(saleClaimed.sale) | currency: 'EUR':2}} + + + + + + + + + + + + + + + + + +
    Claimable sales from ticket {{$ctrl.claim.ticketFk}}
    +
    + + + + + Landed + Quantity + Description + Price + Disc. + Total + + + + + {{sale.landed | date: 'dd/MM/yyyy'}} + {{sale.quantity}} + + + {{sale.concept}} + + + {{sale.price | currency: 'EUR':2}} + {{sale.discount}} % + + {{(sale.quantity * sale.price) - ((sale.discount * (sale.quantity * sale.price))/100) | currency: 'EUR':2}} + + + + + +
    +
    + + + +
    + + +
    + +
    MANÁ: {{$ctrl.mana | currency: 'EUR':0}}
    +
    +
    + + +
    +

    Total claimed price

    +

    {{$ctrl.newPrice | currency: 'EUR':2}} +

    +
    +
    +
    +
    +
    diff --git a/modules/claim/front/detail/index.js b/modules/claim/front/detail/index.js new file mode 100644 index 000000000..f66a296c8 --- /dev/null +++ b/modules/claim/front/detail/index.js @@ -0,0 +1,175 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($state, $, $http, $translate, vnApp, aclService) { + this.$state = $state; + this.$ = $; + this.$http = $http; + this.$translate = $translate; + this.vnApp = vnApp; + this.aclService = aclService; + this.edit = {}; + this.filter = { + where: {claimFk: $state.params.id}, + include: [ + { + relation: 'sale', + scope: { + fields: ['concept', 'ticketFk', 'price', 'quantity', 'discount', 'itemFk'], + include: { + relation: 'ticket' + } + } + } + ] + }; + } + + set salesClaimed(value) { + this._salesClaimed = value; + + if (value) + this.calculateTotals(); + } + + get salesClaimed() { + return this._salesClaimed; + } + + get newDiscount() { + return this._newDiscount; + } + + set newDiscount(value) { + this._newDiscount = value; + this.updateNewPrice(); + } + + openAddSalesDialog() { + this.getClaimableFromTicket(); + this.$.addSales.show(); + } + + getClaimableFromTicket() { + let config = {params: {ticketFk: this.claim.ticketFk}}; + let query = `Sales/getClaimableFromTicket`; + this.$http.get(query, config).then(res => { + if (res.data) + this.salesToClaim = res.data; + }); + } + + addClaimedSale(index) { + let sale = this.salesToClaim[index]; + let saleToAdd = {saleFk: sale.saleFk, claimFk: this.claim.id, quantity: sale.quantity}; + let query = `ClaimBeginnings/`; + this.$http.post(query, saleToAdd).then(() => { + this.$.addSales.hide(); + this.$.model.refresh(); + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + + if (this.aclService.hasAny(['salesAssistant'])) + this.$state.go('claim.card.development'); + }); + } + + deleteClaimedSale(index) { + let sale = this.salesClaimed[index]; + let query = `ClaimBeginnings/${sale.id}`; + this.$http.delete(query).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$.model.remove(index); + this.calculateTotals(); + }); + } + + setClaimedQuantity(id, claimedQuantity) { + let params = {id: id, quantity: claimedQuantity}; + let query = `ClaimBeginnings/`; + this.$http.patch(query, params).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.calculateTotals(); + }); + } + + calculateTotals() { + this.paidTotal = 0.0; + this.claimedTotal = 0.0; + if (!this._salesClaimed) return; + + this._salesClaimed.forEach(sale => { + let orgSale = sale.sale; + this.paidTotal += this.getSaleTotal(orgSale); + this.claimedTotal += sale.quantity * orgSale.price - ((orgSale.discount * (sale.quantity * orgSale.price)) / 100); + }); + } + + getSaleTotal(sale) { + let total = 0.0; + total += sale.quantity * sale.price - ((sale.discount * (sale.quantity * sale.price)) / 100); + return total; + } + + showItemDescriptor(event, itemFk) { + event.stopImmediatePropagation(); + this.$.descriptor.itemFk = itemFk; + this.$.descriptor.parent = event.target; + this.$.descriptor.show(); + } + + showEditPopover(event, saleClaimed) { + this.saleClaimed = saleClaimed; + + if (!this.aclService.hasAny(['salesAssistant'])) + return this.vnApp.showError(this.$translate.instant('Insuficient permisos')); + + this.$.editPopover.parent = event.target; + this.$.editPopover.show(); + } + + getSalespersonMana() { + this.$http.get(`Tickets/${this.claim.ticketFk}/getSalesPersonMana`).then(res => { + this.mana = res.data; + }); + } + + updateDiscount() { + const claimedSale = this.saleClaimed.sale; + if (this.newDiscount != claimedSale.discount) { + const params = {salesIds: [claimedSale.id], newDiscount: this.newDiscount}; + const query = `Tickets/${claimedSale.ticketFk}/updateDiscount`; + + this.$http.post(query, params).then(() => { + claimedSale.discount = this.newDiscount; + this.calculateTotals(); + this.clearDiscount(); + + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }).catch(err => { + this.vnApp.showError(err.message); + }); + } + + this.$.editPopover.hide(); + } + + updateNewPrice() { + this.newPrice = (this.saleClaimed.quantity * this.saleClaimed.sale.price) - + ((this.newDiscount * (this.saleClaimed.quantity * this.saleClaimed.sale.price)) / 100); + } + + clearDiscount() { + this.newDiscount = null; + } +} + +Controller.$inject = ['$state', '$scope', '$http', '$translate', 'vnApp', 'aclService']; + +ngModule.component('vnClaimDetail', { + template: require('./index.html'), + controller: Controller, + bindings: { + claim: '<' + } +}); diff --git a/modules/claim/front/detail/index.spec.js b/modules/claim/front/detail/index.spec.js new file mode 100644 index 000000000..24491075d --- /dev/null +++ b/modules/claim/front/detail/index.spec.js @@ -0,0 +1,150 @@ +import './index.js'; +import crudModel from 'core/mocks/crud-model'; + +describe('claim', () => { + describe('Component vnClaimDetail', () => { + let $scope; + let controller; + let $httpBackend; + let $state; + let aclService; + + beforeEach(ngModule('claim')); + + beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_, $rootScope) => { + $scope = $rootScope.$new(); + $scope.descriptor = { + show: () => {} + }; + $httpBackend = _$httpBackend_; + $httpBackend.when('GET', 'Claims/ClaimBeginnings').respond({}); + $state = _$state_; + aclService = {hasAny: () => true}; + controller = $componentController('vnClaimDetail', {$state, aclService, $scope}); + controller.salesToClaim = [{saleFk: 1}, {saleFk: 2}]; + controller.salesClaimed = [{id: 1, sale: {}}]; + controller.claim = {ticketFk: 1}; + controller.$.model = crudModel; + controller.$.addSales = { + hide: () => {}, + show: () => {} + }; + controller.$.editPopover = { + hide: () => {} + }; + })); + + describe('openAddSalesDialog()', () => { + it('should call getClaimableFromTicket and $.addSales.show', () => { + controller.$ = {addSales: {show: () => {}}}; + spyOn(controller, 'getClaimableFromTicket'); + spyOn(controller.$.addSales, 'show'); + controller.openAddSalesDialog(); + + expect(controller.getClaimableFromTicket).toHaveBeenCalledWith(); + expect(controller.$.addSales.show).toHaveBeenCalledWith(); + }); + }); + + describe('getClaimableFromTicket()', () => { + it('should make a query and set salesToClaim', () => { + $httpBackend.expectGET(`Sales/getClaimableFromTicket?ticketFk=1`).respond(200, 1); + controller.getClaimableFromTicket(); + $httpBackend.flush(); + + expect(controller.salesToClaim).toEqual(1); + }); + }); + + describe('addClaimedSale(index)', () => { + it('should make a post and call refresh, hide and showSuccess', () => { + spyOn(controller.$.addSales, 'hide'); + spyOn(controller.$state, 'go'); + $httpBackend.expectPOST(`ClaimBeginnings/`).respond({}); + controller.addClaimedSale(1); + $httpBackend.flush(); + + expect(controller.$.addSales.hide).toHaveBeenCalledWith(); + expect(controller.$state.go).toHaveBeenCalledWith('claim.card.development'); + }); + }); + + describe('deleteClaimedSale(index)', () => { + it('should make a delete and call refresh and showSuccess', () => { + spyOn(controller.$.model, 'remove'); + $httpBackend.expectDELETE(`ClaimBeginnings/1`).respond({}); + controller.deleteClaimedSale(0); + $httpBackend.flush(); + + expect(controller.$.model.remove).toHaveBeenCalledWith(0); + }); + }); + + describe('setClaimedQuantity(id, claimedQuantity)', () => { + it('should make a patch and call refresh and showSuccess', () => { + spyOn(controller.vnApp, 'showSuccess'); + $httpBackend.expectPATCH(`ClaimBeginnings/`).respond({}); + controller.setClaimedQuantity(1, 1); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + }); + }); + + describe('calculateTotals()', () => { + it('should set paidTotal and claimedTotal to 0 if salesClaimed has no data', () => { + controller.salesClaimed = []; + controller.calculateTotals(); + + expect(controller.paidTotal).toEqual(0); + expect(controller.claimedTotal).toEqual(0); + }); + }); + + describe('updateDiscount()', () => { + it('should perform a query if the new discount differs from the claim discount', () => { + controller.saleClaimed = {sale: { + discount: 5, + id: 7, + ticketFk: 1, + price: 2, + quantity: 10}}; + controller.newDiscount = 10; + + + spyOn(controller.vnApp, 'showSuccess'); + spyOn(controller, 'calculateTotals'); + spyOn(controller, 'clearDiscount'); + spyOn(controller.$.editPopover, 'hide'); + + $httpBackend.when('POST', 'Tickets/1/updateDiscount').respond({}); + controller.updateDiscount(); + $httpBackend.flush(); + + expect(controller.calculateTotals).toHaveBeenCalledWith(); + expect(controller.clearDiscount).toHaveBeenCalledWith(); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + expect(controller.$.editPopover.hide).toHaveBeenCalledWith(); + }); + }); + + describe('showItemDescriptor()', () => { + it('should configure the descriptor then show it', () => { + const itemId = 500; + const event = { + stopImmediatePropagation: () => {}, + target: 'the target element' + }; + spyOn(event, 'stopImmediatePropagation'); + spyOn(controller.$.descriptor, 'show'); + + controller.showItemDescriptor(event, itemId); + + expect(event.stopImmediatePropagation).toHaveBeenCalledWith(); + expect(controller.$.descriptor.itemFk).toEqual(itemId); + expect(controller.$.descriptor.parent).toEqual(event.target); + expect(controller.$.descriptor.show).toHaveBeenCalledWith(); + }); + }); + }); +}); diff --git a/modules/claim/front/detail/locale/es.yml b/modules/claim/front/detail/locale/es.yml new file mode 100644 index 000000000..9bbfd7e86 --- /dev/null +++ b/modules/claim/front/detail/locale/es.yml @@ -0,0 +1,10 @@ +Claimed: Reclamados +Disc.: Dto. +Attended by: Atendida por +Landed: F. entrega +Price: Precio +Claimable sales from ticket: Lineas reclamables del ticket +Detail: Detalles +Add sale item: Añadir artículo +Insuficient permisos: Permisos insuficientes +Total claimed price: Precio total reclamado \ No newline at end of file diff --git a/modules/claim/front/detail/style.scss b/modules/claim/front/detail/style.scss new file mode 100644 index 000000000..6229e56fb --- /dev/null +++ b/modules/claim/front/detail/style.scss @@ -0,0 +1,27 @@ +@import "variables"; + +.vn-popover .discount-popover { + width: 16em; + + .header { + background-color: $color-main; + color: $color-font-dark; + + h5 { + color: inherit; + margin: 0 auto; + } + } + .simulatorTitle { + margin-bottom: 0px; + font-size: 12px; + color: $color-main; + } + vn-label-value { + padding-bottom: 20px; + } + .simulator{ + text-align: center; + } +} + diff --git a/modules/claim/front/development/index.html b/modules/claim/front/development/index.html new file mode 100644 index 000000000..38082847a --- /dev/null +++ b/modules/claim/front/development/index.html @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + +
    + + + + +
    +
    + + + + +
    \ No newline at end of file diff --git a/modules/claim/front/development/index.js b/modules/claim/front/development/index.js new file mode 100644 index 000000000..d6220fbca --- /dev/null +++ b/modules/claim/front/development/index.js @@ -0,0 +1,31 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($state, $scope, aclService) { + this.$state = $state; + this.$scope = $scope; + this.aclService = aclService; + } + + onSubmit() { + this.$scope.watcher.check(); + this.$scope.model.save().then(() => { + this.$scope.watcher.notifySaved(); + this.$scope.watcher.updateOriginalData(); + + if (this.aclService.hasAny(['salesAssistant'])) + this.$state.go('claim.card.action'); + }); + } +} + +Controller.$inject = ['$state', '$scope', 'aclService']; + +ngModule.component('vnClaimDevelopment', { + template: require('./index.html'), + controller: Controller, + bindings: { + claim: '<' + } +}); diff --git a/modules/claim/front/development/index.spec.js b/modules/claim/front/development/index.spec.js new file mode 100644 index 000000000..007a977c3 --- /dev/null +++ b/modules/claim/front/development/index.spec.js @@ -0,0 +1,30 @@ +import './index.js'; +import watcher from 'core/mocks/watcher'; +import crudModel from 'core/mocks/crud-model'; + +describe('Claim', () => { + describe('Component vnClaimDevelopment', () => { + let controller; + let $scope; + let aclService; + + beforeEach(ngModule('claim')); + + beforeEach(angular.mock.inject(($componentController, $rootScope) => { + $scope = $rootScope.$new(); + $scope.watcher = watcher; + $scope.model = crudModel; + aclService = {hasAny: () => true}; + controller = $componentController('vnClaimDevelopment', {$scope, aclService}); + })); + + describe('onSubmit()', () => { + it(`should redirect to 'claim.card.action' state`, () => { + spyOn(controller.$state, 'go'); + controller.onSubmit(); + + expect(controller.$state.go).toHaveBeenCalledWith('claim.card.action'); + }); + }); + }); +}); diff --git a/modules/claim/front/development/locale/es.yml b/modules/claim/front/development/locale/es.yml new file mode 100644 index 000000000..c0c4ed184 --- /dev/null +++ b/modules/claim/front/development/locale/es.yml @@ -0,0 +1,8 @@ +Destination: Destino +Development: Trazabilidad +Reason: Motivo +Result: Consecuencia +Responsible: Responsable +Worker: Trabajador +Redelivery: Devolución +Add line: Añadir Linea \ No newline at end of file diff --git a/e2e/helpers/nightmareModifiers.js b/modules/claim/front/development/style.scss similarity index 100% rename from e2e/helpers/nightmareModifiers.js rename to modules/claim/front/development/style.scss diff --git a/modules/claim/front/dms/index/index.html b/modules/claim/front/dms/index/index.html new file mode 100644 index 000000000..e3cd5da5b --- /dev/null +++ b/modules/claim/front/dms/index/index.html @@ -0,0 +1,41 @@ + + + +
    +
    +
    Drag & Drop files here...
    +
    + + +
    +
    +
    +
    + + +
    +
    +
    +
    + + + + \ No newline at end of file diff --git a/modules/claim/front/dms/index/index.js b/modules/claim/front/dms/index/index.js new file mode 100644 index 000000000..20eba62a3 --- /dev/null +++ b/modules/claim/front/dms/index/index.js @@ -0,0 +1,104 @@ +import ngModule from '../../module'; +import './style.scss'; + +class Controller { + constructor($stateParams, $scope, $http, $translate, vnToken, vnApp, vnConfig) { + this.$stateParams = $stateParams; + this.$ = $scope; + this.$http = $http; + this.$translate = $translate; + this.accessToken = vnToken.token; + this.vnApp = vnApp; + this.vnConfig = vnConfig; + } + + showWorkerDescriptor(event, workerFk) { + event.preventDefault(); + event.stopImmediatePropagation(); + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.workerFk = workerFk; + this.$.workerDescriptor.show(); + } + + showDeleteConfirm(index) { + this.dmsIndex = index; + this.$.confirm.show(); + } + + deleteDms(response) { + if (response === 'accept') { + const dmsFk = this.photos[this.dmsIndex].dmsFk; + const query = `claimDms/${dmsFk}/removeFile`; + this.$http.post(query).then(() => { + this.$.model.remove(this.dmsIndex); + this.vnApp.showSuccess(this.$translate.instant('Photo deleted')); + }); + } + } + + onDrop($event) { + const files = $event.dataTransfer.files; + this.setDefaultParams().then(() => { + this.dms.files = files; + this.create(); + }); + } + + setDefaultParams() { + const params = {filter: { + where: {code: 'claim'} + }}; + return this.$http.get('DmsTypes/findOne', {params}).then(res => { + const dmsTypeId = res.data && res.data.id; + const companyId = this.vnConfig.companyFk; + const warehouseId = this.vnConfig.warehouseFk; + this.dms = { + hasFile: false, + hasFileAttached: false, + reference: this.claim.id, + warehouseId: warehouseId, + companyId: companyId, + dmsTypeId: dmsTypeId, + description: this.$translate.instant('FileDescription', { + claimId: this.claim.id, + clientId: this.claim.client.id, + clientName: this.claim.client.name + }).toUpperCase() + }; + }); + } + + + create() { + const query = `claims/${this.claim.id}/uploadFile`; + const options = { + method: 'POST', + url: query, + params: this.dms, + headers: {'Content-Type': undefined}, + transformRequest: files => { + const formData = new FormData(); + + for (let i = 0; i < files.length; i++) + formData.append(files[i].name, files[i]); + + return formData; + }, + data: this.dms.files + }; + this.$http(options).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Photo uploaded!')); + this.$.model.refresh(); + }); + } +} + +Controller.$inject = ['$stateParams', '$scope', '$http', '$translate', 'vnToken', 'vnApp', 'vnConfig']; + +ngModule.component('vnClaimDmsIndex', { + template: require('./index.html'), + controller: Controller, + bindings: { + claim: '<' + } +}); diff --git a/modules/claim/front/dms/index/index.spec.js b/modules/claim/front/dms/index/index.spec.js new file mode 100644 index 000000000..cbb24ac75 --- /dev/null +++ b/modules/claim/front/dms/index/index.spec.js @@ -0,0 +1,81 @@ +import './index'; +import crudModel from 'core/mocks/crud-model'; + +describe('Claim', () => { + describe('Component vnClaimDmsIndex', () => { + let $componentController; + let $scope; + let $httpBackend; + let controller; + let $httpParamSerializer; + + beforeEach(ngModule('claim')); + + beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_, _$httpParamSerializer_) => { + $componentController = _$componentController_; + $httpParamSerializer = _$httpParamSerializer_; + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + controller = $componentController('vnClaimDmsIndex', {$: $scope}); + controller.$.model = crudModel; + controller.claim = { + id: 1, + client: {id: 101, name: 'Bruce Wayne'} + }; + })); + + describe('deleteDms()', () => { + it('should make an HTTP Post query', () => { + const dmsId = 1; + const dmsIndex = 0; + spyOn(controller.vnApp, 'showSuccess'); + spyOn(controller.$.model, 'remove'); + controller.photos = [{dmsFk: 1}]; + controller.dmsIndex = dmsIndex; + + $httpBackend.when('POST', `claimDms/${dmsId}/removeFile`).respond({}); + $httpBackend.expect('POST', `claimDms/${dmsId}/removeFile`); + controller.deleteDms('accept'); + $httpBackend.flush(); + + expect(controller.$.model.remove).toHaveBeenCalledWith(dmsIndex); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Photo deleted'); + }); + }); + + describe('setDefaultParams()', () => { + it('should make an HTTP GET query, then set all dms properties', () => { + const params = {filter: { + where: {code: 'claim'} + }}; + let serializedParams = $httpParamSerializer(params); + $httpBackend.when('GET', `DmsTypes/findOne?${serializedParams}`).respond({}); + $httpBackend.expect('GET', `DmsTypes/findOne?${serializedParams}`); + controller.setDefaultParams(); + $httpBackend.flush(); + + expect(controller.dms).toBeDefined(); + }); + }); + + describe('create()', () => { + it('should make an HTTP Post query, then refresh the model data', () => { + const claimId = 1; + const dmsIndex = 0; + spyOn(controller.vnApp, 'showSuccess'); + spyOn(controller.$.model, 'refresh'); + controller.photos = [{dmsFk: 1}]; + controller.dmsIndex = dmsIndex; + controller.dms = {files: []}; + + $httpBackend.when('POST', `claims/${claimId}/uploadFile`).respond({}); + $httpBackend.expect('POST', `claims/${claimId}/uploadFile`); + controller.create(); + $httpBackend.flush(); + + expect(controller.$.model.refresh).toHaveBeenCalledWith(); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Photo uploaded!'); + }); + }); + }); +}); diff --git a/modules/claim/front/dms/index/style.scss b/modules/claim/front/dms/index/style.scss new file mode 100644 index 000000000..e7e957cd8 --- /dev/null +++ b/modules/claim/front/dms/index/style.scss @@ -0,0 +1,28 @@ +@import "./variables"; + +vn-claim-dms-index { + .drop-zone { + border: 2px dashed $color-font-secondary; + color: $color-font-secondary; + box-sizing: border-box; + padding: 2em $spacing-md; + border-radius: 0.5em; + text-align: center; + font-size: 1.4em; + + vn-icon { + font-size: 3em + } + } + + .photo-list { + + padding: $spacing-md; + min-height: 100%; + + .photo { + width: 32em; + height: 18em; + } + } +} \ No newline at end of file diff --git a/modules/claim/front/dms/locale/en.yml b/modules/claim/front/dms/locale/en.yml new file mode 100644 index 000000000..a202e8bf2 --- /dev/null +++ b/modules/claim/front/dms/locale/en.yml @@ -0,0 +1,2 @@ +FileDescription: Ticket id {{ticketId}} from client {{clientName}} id {{clientId}} +ContentTypesInfo: Allowed file types {{allowedContentTypes}} \ No newline at end of file diff --git a/modules/claim/front/dms/locale/es.yml b/modules/claim/front/dms/locale/es.yml new file mode 100644 index 000000000..3e765ae78 --- /dev/null +++ b/modules/claim/front/dms/locale/es.yml @@ -0,0 +1,4 @@ +Are you sure you want to continue?: ¿Seguro que quieres continuar? +Drag & Drop files here...: Arrastra y suelta archivos aquí... +Photo deleted: Foto eliminada +Photo uploaded!: Foto subida! \ No newline at end of file diff --git a/modules/claim/front/index.js b/modules/claim/front/index.js new file mode 100644 index 000000000..4ea9ac6cc --- /dev/null +++ b/modules/claim/front/index.js @@ -0,0 +1,13 @@ +export * from './module'; + +import './main'; +import './index/'; +import './action'; +import './basic-data'; +import './card'; +import './detail'; +import './descriptor'; +import './development'; +import './search-panel'; +import './summary'; +import './dms/index'; diff --git a/modules/claim/front/index/index.html b/modules/claim/front/index/index.html new file mode 100644 index 000000000..383e55a9d --- /dev/null +++ b/modules/claim/front/index/index.html @@ -0,0 +1,73 @@ + + + + + + + + + + Id + Client + Created + Worker + State + + + + + + {{::claim.id}} + + + {{::claim.name}} + + + {{::claim.created | date:'dd/MM/yyyy'}} + + + {{::claim.nickName}} + + + + + {{::claim.description}} + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/claim/front/index/index.js b/modules/claim/front/index/index.js new file mode 100644 index 000000000..21464fea9 --- /dev/null +++ b/modules/claim/front/index/index.js @@ -0,0 +1,60 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($scope) { + this.$ = $scope; + this.ticketSelected = null; + } + + stateColor(claim) { + switch (claim.description) { + case 'Pendiente': + return 'warning'; + case 'Gestionado': + return 'notice'; + case 'Resuelto': + return 'success'; + } + } + + showClientDescriptor(event, clientFk) { + this.$.clientDescriptor.clientFk = clientFk; + this.$.clientDescriptor.parent = event.target; + this.$.clientDescriptor.show(); + event.preventDefault(); + event.stopImmediatePropagation(); + } + + showWorkerDescriptor(event, workerFk) { + event.preventDefault(); + event.stopImmediatePropagation(); + this.selectedWorker = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } + + preview(event, claim) { + this.claimSelected = claim; + this.$.dialogSummaryClaim.show(); + event.preventDefault(); + event.stopImmediatePropagation(); + } + + onDescriptorLoad() { + this.$.popover.relocate(); + } + + onSearch(params) { + if (params) + this.$.model.applyFilter(null, params); + else + this.$.model.clear(); + } +} + +Controller.$inject = ['$scope']; + +ngModule.component('vnClaimIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/claim/front/locale/es.yml b/modules/claim/front/locale/es.yml new file mode 100644 index 000000000..26b1eba32 --- /dev/null +++ b/modules/claim/front/locale/es.yml @@ -0,0 +1,17 @@ +#Ordenar alfabeticamente +Add sale: Añadir linea +Are you sure you want to send it?: ¿Seguro que quieres enviarlo? +Are you sure you want to delete this claim?: ¿Seguro que quieres eliminar esta reclamación? +Client Id: Id cliente +Claimed ticket: Ticket reclamado +Delete claim: Eliminar reclamación +Observation: Observación +Responsible: Responsable +Remove sale: Eliminar linea +Claim Id: Id reclamación +Created: Creado +Send Pickup order: Enviar orden de recogida +Show Pickup order: Ver orden de recogida +Search claim by id or client name: Buscar reclamaciones por identificador o nombre de cliente +Claim deleted!: Reclamación eliminada! + diff --git a/modules/claim/front/main/index.html b/modules/claim/front/main/index.html new file mode 100644 index 000000000..e733162b1 --- /dev/null +++ b/modules/claim/front/main/index.html @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/modules/claim/front/main/index.js b/modules/claim/front/main/index.js new file mode 100644 index 000000000..77b051897 --- /dev/null +++ b/modules/claim/front/main/index.js @@ -0,0 +1,9 @@ +import ngModule from '../module'; +import ModuleMain from 'salix/components/module-main'; + +export default class Claim extends ModuleMain {} + +ngModule.vnComponent('vnClaim', { + controller: Claim, + template: require('./index.html') +}); diff --git a/modules/claim/front/module.js b/modules/claim/front/module.js new file mode 100644 index 000000000..f26df297b --- /dev/null +++ b/modules/claim/front/module.js @@ -0,0 +1,3 @@ +import {ng} from 'core/vendor'; + +export default ng.module('claim', ['vnCore']); diff --git a/modules/claim/front/routes.json b/modules/claim/front/routes.json new file mode 100644 index 000000000..80bc77c49 --- /dev/null +++ b/modules/claim/front/routes.json @@ -0,0 +1,98 @@ +{ + "module": "claim", + "name": "Claims", + "icon": "icon-claims", + "validations": true, + "dependencies": ["worker", "item", "client"], + "menus": { + "main": [ + {"state": "claim.index", "icon": "icon-claims"} + ], + "card": [ + {"state": "claim.card.basicData", "icon": "settings"}, + {"state": "claim.card.detail", "icon": "icon-details"}, + {"state": "claim.card.dms.index", "icon": "image"}, + {"state": "claim.card.development", "icon": "icon-traceability"}, + {"state": "claim.card.action", "icon": "icon-actions"} + ] + }, + "keybindings": [ + {"key": "r", "state": "claim.index"} + ], + "routes": [ + { + "url": "/claim", + "state": "claim", + "abstract": true, + "component": "vn-claim", + "description": "Claims" + }, { + "url": "/index?q", + "state": "claim.index", + "component": "vn-claim-index", + "description": "Claims" + }, { + "url": "/:id", + "state": "claim.card", + "abstract": true, + "component": "vn-claim-card" + }, { + "url": "/summary", + "state": "claim.card.summary", + "component": "vn-claim-summary", + "description": "Summary", + "params": { + "claim": "$ctrl.claim" + } + }, { + "url": "/basic-data", + "state": "claim.card.basicData", + "component": "vn-claim-basic-data", + "description": "Basic data", + "params": { + "claim": "$ctrl.claim" + }, + "acl": ["salesPerson"] + }, { + "url": "/detail", + "state": "claim.card.detail", + "component": "vn-claim-detail", + "description": "Detail", + "params": { + "claim": "$ctrl.claim" + }, + "acl": ["salesPerson"] + }, { + "url": "/development", + "state": "claim.card.development", + "component": "vn-claim-development", + "description": "Development", + "params": { + "claim": "$ctrl.claim" + }, + "acl": ["salesAssistant"] + }, { + "url": "/action", + "state": "claim.card.action", + "component": "vn-claim-action", + "description": "Action", + "params": { + "claim": "$ctrl.claim" + }, + "acl": ["salesAssistant"] + }, { + "url": "/dms", + "state": "claim.card.dms", + "abstract": true, + "component": "ui-view" + }, { + "url" : "/index", + "state": "claim.card.dms.index", + "component": "vn-claim-dms-index", + "description": "Photos", + "params": { + "claim": "$ctrl.claim" + } + } + ] +} \ No newline at end of file diff --git a/modules/claim/front/search-panel/index.html b/modules/claim/front/search-panel/index.html new file mode 100644 index 000000000..93d3db455 --- /dev/null +++ b/modules/claim/front/search-panel/index.html @@ -0,0 +1,72 @@ +
    +
    + + + + + + + + + + + + + + + + + {{firstName}} {{name}} + + + {{firstName}} {{name}} + + + + + {{description}} + + + + + + + +
    +
    \ No newline at end of file diff --git a/modules/claim/front/search-panel/index.js b/modules/claim/front/search-panel/index.js new file mode 100644 index 000000000..b6bd2b974 --- /dev/null +++ b/modules/claim/front/search-panel/index.js @@ -0,0 +1,7 @@ +import ngModule from '../module'; +import SearchPanel from 'core/components/searchbar/search-panel'; + +ngModule.component('vnClaimSearchPanel', { + template: require('./index.html'), + controller: SearchPanel +}); diff --git a/modules/claim/front/search-panel/locale/es.yml b/modules/claim/front/search-panel/locale/es.yml new file mode 100644 index 000000000..1f892a742 --- /dev/null +++ b/modules/claim/front/search-panel/locale/es.yml @@ -0,0 +1,7 @@ +Ticket id: Id ticket +Client id: Id cliente +Nickname: Alias +From: Desde +To: Hasta +Agency: Agencia +Warehouse: Almacén \ No newline at end of file diff --git a/modules/claim/front/summary/index.html b/modules/claim/front/summary/index.html new file mode 100644 index 000000000..20dca702b --- /dev/null +++ b/modules/claim/front/summary/index.html @@ -0,0 +1,185 @@ + + + +
    {{::$ctrl.summary.claim.id}} - {{::$ctrl.summary.claim.client.name}}
    + + + + + + + + + + + + + + + + + + + + +

    Detail

    + + + + + Item + Landed + Quantity + Claimed + Description + Price + Disc. + Total + + + + + + + {{::saleClaimed.sale.itemFk | zeroFill:6}} + + + {{::saleClaimed.sale.ticket.landed | date: 'dd/MM/yyyy'}} + {{::saleClaimed.sale.quantity}} + {{::saleClaimed.quantity}} + {{::saleClaimed.sale.concept}} + {{::saleClaimed.sale.price | currency: 'EUR':2}} + {{::saleClaimed.sale.discount}} % + + {{saleClaimed.sale.quantity * saleClaimed.sale.price * + ((100 - saleClaimed.sale.discount) / 100) | currency: 'EUR':2}} + + + + + +
    + +

    Photos

    + +
    +
    +
    +
    +
    +
    + +

    Development

    + + + + + Reason + Result + Responsible + Worker + Redelivery + + + + + {{::development.claimReason.description}} + {{::development.claimResult.description}} + {{::development.claimResponsible.description}} + + + {{::development.worker.user.nickname}} + + + {{::development.claimRedelivery.description}} + + + + +
    + +

    Action

    + + + + + Item + Ticket + Destination + Landed + Quantity + Description + Price + Disc. + Total + + + + + + + {{::action.sale.itemFk | zeroFill:6}} + + + + + {{::action.sale.ticket.id | zeroFill:6}} + + + {{::action.claimBeggining.description}} + {{::action.sale.ticket.landed | date: 'dd/MM/yyyy'}} + {{::action.sale.quantity}} + {{::action.sale.concept}} + {{::action.sale.price}} + {{::action.sale.discount}} % + + {{action.sale.quantity * action.sale.price * + ((100 - action.sale.discount) / 100) | currency: 'EUR':2}} + + + + + +
    +
    +
    + + + + + + \ No newline at end of file diff --git a/modules/claim/front/summary/index.js b/modules/claim/front/summary/index.js new file mode 100644 index 000000000..448ce9b38 --- /dev/null +++ b/modules/claim/front/summary/index.js @@ -0,0 +1,70 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $http, $stateParams, vnToken) { + this.$http = $http; + this.$ = $scope; + this.$stateParams = $stateParams; + this.accessToken = vnToken.token; + } + + get claim() { + return this._claim; + } + + + set claim(value) { + this._claim = value; + + // Get DMS on summary load + if (value) + this.$.$applyAsync(() => this.loadDms()); + } + + loadDms() { + this.$.model.where = { + claimFk: this.claim.id + }; + this.$.model.refresh(); + } + + getSummary() { + this.$http.get(`Claims/${this.claim.id}/getSummary`).then(response => { + this.summary = response.data; + }); + } + + $onChanges() { + if (this.claim && this.claim.id) + this.getSummary(); + } + + showItemDescriptor(event, itemFk) { + this.$.itemDescriptor.itemFk = itemFk; + this.$.itemDescriptor.parent = event.target; + this.$.itemDescriptor.show(); + } + + showWorkerDescriptor(event, workerFk) { + this.selectedWorker = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } + + showTicketDescriptor(event, ticketId) { + this.$.ticketDescriptor.ticketFk = ticketId; + this.$.ticketDescriptor.parent = event.target; + this.$.ticketDescriptor.show(); + } +} + +Controller.$inject = ['$scope', '$http', '$stateParams', 'vnToken']; + +ngModule.component('vnClaimSummary', { + template: require('./index.html'), + controller: Controller, + bindings: { + claim: '<' + } +}); diff --git a/modules/claim/front/summary/index.spec.js b/modules/claim/front/summary/index.spec.js new file mode 100644 index 000000000..858829a68 --- /dev/null +++ b/modules/claim/front/summary/index.spec.js @@ -0,0 +1,38 @@ +import './index.js'; +import crudModel from 'core/mocks/crud-model'; + +describe('Claim', () => { + describe('Component summary', () => { + let controller; + let $httpBackend; + + beforeEach(ngModule('claim')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + controller = $componentController('vnClaimSummary'); + controller.claim = {id: 1}; + controller.$.model = crudModel; + })); + + describe('getSummary()', () => { + it('should perform a query to set summary', () => { + $httpBackend.when('GET', `Claims/1/getSummary`).respond(200, 24); + $httpBackend.expect('GET', `Claims/1/getSummary`); + controller.getSummary(); + $httpBackend.flush(); + + expect(controller.summary).toEqual(24); + }); + }); + + describe('$onChanges()', () => { + it('should call getSummary when item.id is defined', () => { + spyOn(controller, 'getSummary'); + controller.$onChanges(); + + expect(controller.getSummary).toHaveBeenCalledWith(); + }); + }); + }); +}); diff --git a/modules/claim/front/summary/style.scss b/modules/claim/front/summary/style.scss new file mode 100644 index 000000000..38136f24a --- /dev/null +++ b/modules/claim/front/summary/style.scss @@ -0,0 +1,12 @@ +@import "./variables"; + +vn-claim-summary { + .photo { + height: 15.5em; + } + .photo .image { + border: 2px solid $color-bg-dark; + border-radius: 0.2em; + } + +} \ No newline at end of file diff --git a/modules/client/back/methods/address/createDefaultAddress.js b/modules/client/back/methods/address/createDefaultAddress.js new file mode 100644 index 000000000..e524a6017 --- /dev/null +++ b/modules/client/back/methods/address/createDefaultAddress.js @@ -0,0 +1,44 @@ +module.exports = function(Self) { + Self.remoteMethod('createDefaultAddress', { + description: 'Creates both client and its web account', + accepts: { + arg: 'data', + type: 'object', + http: {source: 'body'} + }, + returns: { + root: true, + type: 'Object' + }, + http: { + verb: 'post', + path: '/createDefaultAddress' + } + }); + + Self.createDefaultAddress = async data => { + const Address = Self.app.models.Address; + const Client = Self.app.models.Client; + const tx = await Address.beginTransaction({}); + + try { + let options = {transaction: tx}; + + let address = data.address; + let newAddress = await Address.create(address, options); + let client = await Client.findById(address.clientFk, null, options); + + if (data.isDefaultAddress) { + await client.updateAttributes({ + defaultAddressFk: newAddress.id + }, options); + } + + await tx.commit(); + return newAddress; + } catch (e) { + await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/client/back/methods/address/specs/createDefaultAddress.spec.js b/modules/client/back/methods/address/specs/createDefaultAddress.spec.js new file mode 100644 index 000000000..452d9c9b7 --- /dev/null +++ b/modules/client/back/methods/address/specs/createDefaultAddress.spec.js @@ -0,0 +1,37 @@ +const app = require('vn-loopback/server/server'); + +describe('Address createDefaultAddress', () => { + let address; + let client; + + afterAll(async done => { + await client.updateAttributes({defaultAddressFk: 1}); + await address.destroy(); + + done(); + }); + + it('should verify that client defaultAddressFk is untainted', async() => { + client = await app.models.Client.findById(101); + + expect(client.defaultAddressFk).toEqual(1); + }); + + it('should create a new address and set as a client default address', async() => { + let data = { + address: { + clientFk: 101, + nickname: 'My address', + street: 'Wall Street', + city: 'New York', + + }, + isDefaultAddress: true + }; + + address = await app.models.Address.createDefaultAddress(data); + client = await app.models.Client.findById(101); + + expect(client.defaultAddressFk).toEqual(address.id); + }); +}); diff --git a/modules/client/back/methods/client-dms/allowedContentTypes.js b/modules/client/back/methods/client-dms/allowedContentTypes.js new file mode 100644 index 000000000..2f5183f92 --- /dev/null +++ b/modules/client/back/methods/client-dms/allowedContentTypes.js @@ -0,0 +1,23 @@ +module.exports = Self => { + Self.remoteMethodCtx('allowedContentTypes', { + description: 'Returns a list of allowed contentTypes', + accessType: 'READ', + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/allowedContentTypes`, + verb: 'GET' + } + }); + + Self.allowedContentTypes = async() => { + const storageConnector = Self.app.dataSources.storage.connector; + const allowedContentTypes = storageConnector.allowedContentTypes; + const modelAllowedContentTypes = Self.definition.settings.allowedContentTypes; + + return modelAllowedContentTypes || allowedContentTypes; + }; +}; + diff --git a/modules/client/back/methods/client-dms/removeFile.js b/modules/client/back/methods/client-dms/removeFile.js new file mode 100644 index 000000000..5ff123630 --- /dev/null +++ b/modules/client/back/methods/client-dms/removeFile.js @@ -0,0 +1,30 @@ +module.exports = Self => { + Self.remoteMethodCtx('removeFile', { + description: 'Removes a client document', + accessType: 'WRITE', + accepts: { + arg: 'id', + type: 'Number', + description: 'The document id', + http: {source: 'path'} + }, + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/removeFile`, + verb: 'POST' + } + }); + + Self.removeFile = async(ctx, id) => { + const models = Self.app.models; + const clientDms = await Self.findById(id); + + await models.Dms.removeFile(ctx, clientDms.dmsFk); + + return clientDms.destroy(); + }; +}; + diff --git a/modules/client/back/methods/client-dms/specs/removeFile.spec.js b/modules/client/back/methods/client-dms/specs/removeFile.spec.js new file mode 100644 index 000000000..01cf1977b --- /dev/null +++ b/modules/client/back/methods/client-dms/specs/removeFile.spec.js @@ -0,0 +1,18 @@ +const app = require('vn-loopback/server/server'); + +describe('ClientDms removeFile()', () => { + const clientDmsFk = 3; + it(`should return an error for a user without enough privileges`, async() => { + let clientId = 101; + let ctx = {req: {accessToken: {userId: clientId}}}; + + let error; + await app.models.ClientDms.removeFile(ctx, clientDmsFk).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`You don't have enough privileges`); + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/modules/client/back/methods/client/activeWorkersWithRole.js b/modules/client/back/methods/client/activeWorkersWithRole.js new file mode 100644 index 000000000..cf0bc6597 --- /dev/null +++ b/modules/client/back/methods/client/activeWorkersWithRole.js @@ -0,0 +1,67 @@ +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const buildFilter = require('vn-loopback/util/filter').buildFilter; +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethod('activeWorkersWithRole', { + description: 'Returns actives workers with salesperson role', + accessType: 'READ', + accepts: [{ + arg: 'filter', + type: 'Object', + description: 'Filter defining where and paginated data', + required: true + }], + returns: { + type: 'Worker', + root: true + }, + http: { + path: `/activeWorkersWithRole`, + verb: 'get' + } + }); + + Self.activeWorkersWithRole = async filter => { + let conn = Self.dataSource.connector; + if (filter.where && filter.where.and && Array.isArray(filter.where.and)) { + let where = {}; + filter.where.and.forEach(element => { + where[Object.keys(element)[0]] = Object.values(element)[0]; + }); + filter.where = where; + } + let clientFilter = Object.assign({}, filter); + clientFilter.where = buildFilter(filter.where, (param, value) => { + switch (param) { + case 'role': + return {'r.name': value}; + case 'firstName': + return {or: [ + {'w.firstName': {like: `%${value}%`}}, + {'w.lastName': {like: `%${value}%`}}, + {'u.name': {like: `%${value}%`}}, + {'u.nickname': {like: `%${value}%`}} + ]}; + case 'id': + return {'w.id': value}; + } + }); + + let myFilter = { + where: {'u.active': true} + }; + + myFilter = mergeFilters(myFilter, clientFilter); + + let stmt = new ParameterizedSQL( + `SELECT DISTINCT w.id, w.firstName, w.lastName, u.name, u.nickname + FROM worker w + JOIN account.user u ON u.id = w.userFk + JOIN account.roleRole i ON i.role = u.role + JOIN account.role r ON r.id = i.inheritsFrom` + ); + stmt.merge(conn.makeSuffix(myFilter)); + return await conn.executeStmt(stmt); + }; +}; diff --git a/modules/client/back/methods/client/addressesPropagateRe.js b/modules/client/back/methods/client/addressesPropagateRe.js new file mode 100644 index 000000000..31cafa654 --- /dev/null +++ b/modules/client/back/methods/client/addressesPropagateRe.js @@ -0,0 +1,43 @@ +module.exports = function(Self) { + Self.remoteMethod('addressesPropagateRe', { + description: 'Change property isEqualizated in all client addresses', + accessType: 'WRITE', + accepts: [ + { + arg: 'id', + type: 'string', + required: true, + description: 'Client id', + http: {source: 'path'} + }, + { + arg: 'data', + type: 'Object', + required: true, + description: 'data with new value', + http: {source: 'body'} + } + ], + returns: { + arg: 'data', + type: 'boolean', + root: true + }, + http: { + path: `/:id/addressesPropagateRe`, + verb: 'patch' + } + }); + + Self.addressesPropagateRe = async(id, data) => { + if (data.hasOwnProperty('isEqualizated')) { + let client = await Self.app.models.Client.findById(id); + if (client) { + await Self.app.models.Address.updateAll({clientFk: id}, data); + await client.updateAttributes({hasToInvoiceByAddress: false}); + return true; + } + } + return false; + }; +}; diff --git a/modules/client/back/methods/client/canBeInvoiced.js b/modules/client/back/methods/client/canBeInvoiced.js new file mode 100644 index 000000000..1f695aba8 --- /dev/null +++ b/modules/client/back/methods/client/canBeInvoiced.js @@ -0,0 +1,32 @@ +module.exports = function(Self) { + Self.remoteMethodCtx('canBeInvoiced', { + description: 'Change property isEqualizated in all client addresses', + accessType: 'READ', + accepts: [ + { + arg: 'id', + type: 'string', + required: true, + description: 'Client id', + http: {source: 'path'} + } + ], + returns: { + arg: 'data', + type: 'boolean', + root: true + }, + http: { + path: `/:id/canBeInvoiced`, + verb: 'get' + } + }); + + Self.canBeInvoiced = async id => { + let client = await Self.app.models.Client.findById(id, {fields: ['id', 'isTaxDataChecked', 'hasToInvoice']}); + if (client.isTaxDataChecked && client.hasToInvoice) + return true; + + return false; + }; +}; diff --git a/modules/client/back/methods/client/confirmTransaction.js b/modules/client/back/methods/client/confirmTransaction.js new file mode 100644 index 000000000..467a8627b --- /dev/null +++ b/modules/client/back/methods/client/confirmTransaction.js @@ -0,0 +1,56 @@ +module.exports = Self => { + Self.remoteMethodCtx('confirmTransaction', { + description: 'Confirm a web payment', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'Transaction id' + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/confirmTransaction`, + verb: 'POST' + } + }); + + Self.confirmTransaction = async(ctx, id) => { + let userId = ctx.req.accessToken.userId; + let tx = await Self.beginTransaction({}); + + try { + let options = {transaction: tx}; + + let oldTpvTransaction = await Self.app.models.TpvTransaction.findById(id, null, options); + + let confirm = await Self.rawSql('CALL hedera.tpvTransaction_confirmById(?)', [id], options); + + let tpvTransaction = await Self.app.models.TpvTransaction.findById(id, null, options); + + let oldInstance = {status: oldTpvTransaction.status}; + let newInstance = {status: tpvTransaction.status}; + + let logRecord = { + originFk: tpvTransaction.clientFk, + userFk: userId, + action: 'update', + changedModel: 'TpvTransaction', + changedModelId: id, + oldInstance: oldInstance, + newInstance: newInstance + }; + + await Self.app.models.ClientLog.create(logRecord, options); + + await tx.commit(); + return confirm; + } catch (e) { + await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/client/back/methods/client/createWithUser.js b/modules/client/back/methods/client/createWithUser.js new file mode 100644 index 000000000..36ab28443 --- /dev/null +++ b/modules/client/back/methods/client/createWithUser.js @@ -0,0 +1,72 @@ +module.exports = function(Self) { + Self.remoteMethod('createWithUser', { + description: 'Creates both client and its web account', + accepts: { + arg: 'data', + type: 'object', + http: {source: 'body'} + }, + returns: { + root: true, + type: 'boolean' + }, + http: { + verb: 'post', + path: '/createWithUser' + } + }); + + Self.createWithUser = async data => { + let firstEmail = data.email ? data.email.split(',')[0] : null; + let user = { + name: data.userName, + email: firstEmail, + password: parseInt(Math.random() * 100000000000000) + }; + const Account = Self.app.models.Account; + const Address = Self.app.models.Address; + const tx = await Account.beginTransaction({}); + + try { + let options = {transaction: tx}; + + let account = await Account.create(user, options); + let client = await Self.create({ + id: account.id, + name: data.name, + fi: data.fi, + socialName: data.socialName, + email: data.email, + salesPersonFk: data.salesPersonFk, + postcode: data.postcode, + street: data.street, + city: data.city, + provinceFk: data.provinceFk, + countryFk: data.countryFk, + isEqualizated: data.isEqualizated + }, options); + + + let address = await Address.create({ + clientFk: client.id, + nickname: client.name, + city: client.city, + street: client.street, + postalCode: client.postcode, + provinceFk: client.provinceFk, + isEqualizated: client.isEqualizated, + isActive: true + }, options); + + await client.updateAttributes({ + defaultAddressFk: address.id + }, options); + + await tx.commit(); + return client; + } catch (e) { + await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/client/back/methods/client/getAverageInvoiced.js b/modules/client/back/methods/client/getAverageInvoiced.js new file mode 100644 index 000000000..5c806879c --- /dev/null +++ b/modules/client/back/methods/client/getAverageInvoiced.js @@ -0,0 +1,28 @@ +module.exports = Self => { + Self.remoteMethod('getAverageInvoiced', { + description: 'Returns the annual average invoiced of a client', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'client id', + http: {source: 'path'} + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/:id/getAverageInvoiced`, + verb: 'GET' + } + }); + + Self.getAverageInvoiced = async clientFk => { + let query = `SELECT invoiced FROM vn.annualAverageInvoiced WHERE clientFk = ?`; + let [invoiced] = await Self.rawSql(query, [clientFk]); + + return invoiced; + }; +}; diff --git a/modules/client/back/methods/client/getCard.js b/modules/client/back/methods/client/getCard.js new file mode 100644 index 000000000..6c69d32a8 --- /dev/null +++ b/modules/client/back/methods/client/getCard.js @@ -0,0 +1,72 @@ +module.exports = function(Self) { + Self.remoteMethod('getCard', { + description: 'Get client basic data and debt', + accepts: { + arg: 'id', + type: 'number', + required: true, + description: 'The client id', + http: {source: 'path'} + }, + returns: { + type: 'Object', + root: true + }, + http: { + verb: 'GET', + path: '/:id/getCard' + } + }); + + Self.getCard = async function(id) { + let client = await Self.findOne({ + where: { + id: id + }, + include: [ + { + relation: 'salesPerson', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + }, { + relation: 'contactChannel', + scope: { + fields: ['id', 'name'] + } + }, { + relation: 'province', + scope: { + fields: ['id', 'name'] + } + }, { + relation: 'country', + scope: { + fields: ['id', 'country'] + } + }, { + relation: 'payMethod', + scope: { + fields: ['id', 'name'] + } + }, { + relation: 'account', + scope: { + fields: ['id', 'name', 'active'] + } + } + ] + }); + + let query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`; + client.debt = (await Self.rawSql(query, [id]))[0].debt; + + return client; + }; +}; diff --git a/services/loopback/common/methods/client/getDebt.js b/modules/client/back/methods/client/getDebt.js similarity index 87% rename from services/loopback/common/methods/client/getDebt.js rename to modules/client/back/methods/client/getDebt.js index c04c208b8..c4f167731 100644 --- a/services/loopback/common/methods/client/getDebt.js +++ b/modules/client/back/methods/client/getDebt.js @@ -21,7 +21,8 @@ module.exports = Self => { Self.getDebt = async clientFk => { let query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`; - let response = await Self.rawSql(query, [clientFk]); - return response[0]; + let [debt] = await Self.rawSql(query, [clientFk]); + + return debt; }; }; diff --git a/modules/client/back/methods/client/getMana.js b/modules/client/back/methods/client/getMana.js new file mode 100644 index 000000000..88e337e32 --- /dev/null +++ b/modules/client/back/methods/client/getMana.js @@ -0,0 +1,28 @@ +module.exports = Self => { + Self.remoteMethod('getMana', { + description: 'Returns the boolean mana of a client', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'client id', + http: {source: 'path'} + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/:id/getMana`, + verb: 'GET' + } + }); + + Self.getMana = async clientFk => { + let query = `SELECT vn.clientGetMana(?) AS mana`; + let [mana] = await Self.rawSql(query, [clientFk]); + + return mana; + }; +}; diff --git a/modules/client/back/methods/client/getTransactions.js b/modules/client/back/methods/client/getTransactions.js new file mode 100644 index 000000000..b86421a95 --- /dev/null +++ b/modules/client/back/methods/client/getTransactions.js @@ -0,0 +1,44 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('getTransactions', { + description: 'Returns last entries', + accessType: 'READ', + accepts: [{ + arg: 'filter', + type: 'Object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + http: {source: 'query'} + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/getTransactions`, + verb: 'GET' + } + }); + + Self.getTransactions = async filter => { + let conn = Self.dataSource.connector; + let stmt = new ParameterizedSQL(` + SELECT + t.id, + t.clientFk, + t.created, + t.amount / 100 amount, + t.receiptFk IS NOT NULL AS isConfirmed, + tt.message responseMessage, + te.message errorMessage + FROM hedera.tpvTransaction t + JOIN hedera.tpvMerchant m ON m.id = t.merchantFk + LEFT JOIN hedera.tpvResponse tt ON tt.id = t.response + LEFT JOIN hedera.tpvError te ON te.code = errorCode`); + + stmt.merge(conn.makeSuffix(filter, 't')); + + return await Self.rawStmt(stmt); + }; +}; diff --git a/services/loopback/common/methods/client/hasCustomerRole.js b/modules/client/back/methods/client/hasCustomerRole.js similarity index 100% rename from services/loopback/common/methods/client/hasCustomerRole.js rename to modules/client/back/methods/client/hasCustomerRole.js diff --git a/services/loopback/common/methods/client/isValidClient.js b/modules/client/back/methods/client/isValidClient.js similarity index 76% rename from services/loopback/common/methods/client/isValidClient.js rename to modules/client/back/methods/client/isValidClient.js index 583efa299..241121927 100644 --- a/services/loopback/common/methods/client/isValidClient.js +++ b/modules/client/back/methods/client/isValidClient.js @@ -29,22 +29,23 @@ module.exports = Self => { } }); - Self.isValidClient = async function(id) { + Self.isValidClient = async id => { let query = `SELECT r.name - FROM salix.Account A - JOIN vn.client C ON A.id = C.id - JOIN salix.RoleMapping rm ON rm.principalId = A.id + FROM salix.Account a + JOIN vn.client c ON a.id = c.id + JOIN salix.RoleMapping rm ON rm.principalId = a.id JOIN salix.Role r ON r.id = rm.roleId - WHERE A.id = ? AND C.isActive AND C.isTaxDataChecked`; + WHERE a.id = ? AND c.isActive AND c.isTaxDataChecked`; let roleNames = await Self.rawSql(query, [id]); - if (!roleNames.length) return false; - roleNames.forEach(role => { - if (role.name === 'employee') - return false; + let isEmployee = roleNames.findIndex(role => { + return role.name === 'employee'; }); + + if (!roleNames.length || isEmployee > -1 ) return false; + return true; }; }; diff --git a/modules/client/back/methods/client/lastActiveTickets.js b/modules/client/back/methods/client/lastActiveTickets.js new file mode 100644 index 000000000..4dc1e2c56 --- /dev/null +++ b/modules/client/back/methods/client/lastActiveTickets.js @@ -0,0 +1,39 @@ +module.exports = Self => { + Self.remoteMethod('lastActiveTickets', { + description: 'Returns the last three tickets of a client that have the alertLevel at 0 and the shiped day is gt today', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'Number', + required: true, + description: 'Client id', + http: {source: 'path'} + }, { + arg: 'ticketId', + type: 'Number', + required: true + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/:id/lastActiveTickets`, + verb: 'GET' + } + }); + + Self.lastActiveTickets = async(id, ticketId) => { + const query = ` + SELECT t.id, t.shipped, a.name AS agencyName, w.name AS warehouseName + FROM vn.ticket t + JOIN vn.ticketState ts ON t.id = ts.ticketFk + JOIN vn.agencyMode a ON t.agencyModeFk = a.id + JOIN vn.warehouse w ON t.warehouseFk = w.id + WHERE t.shipped >= CURDATE() AND t.clientFk = ? AND ts.alertLevel = 0 AND t.id <> ? + ORDER BY t.shipped + LIMIT 3`; + + return Self.rawSql(query, [id, ticketId]); + }; +}; diff --git a/services/loopback/common/methods/client/listWorkers.js b/modules/client/back/methods/client/listWorkers.js similarity index 85% rename from services/loopback/common/methods/client/listWorkers.js rename to modules/client/back/methods/client/listWorkers.js index 92339e32f..8fa4c085e 100644 --- a/services/loopback/common/methods/client/listWorkers.js +++ b/modules/client/back/methods/client/listWorkers.js @@ -16,14 +16,14 @@ module.exports = function(Self) { Self.listWorkers = function() { let query = `SELECT w.id, - CONCAT(w.firstName, IFNULL(CONCAT(" ", w.name), "")) \`name\` + CONCAT(w.firstName, IFNULL(CONCAT(" ", w.lastName), "")) \`name\` FROM worker w JOIN account.user u ON w.userFk = u.id JOIN account.roleRole rr ON rr.role = u.role JOIN account.role r ON r.id = rr.inheritsFrom WHERE u.active AND r.\`name\` = 'employee' - ORDER BY w.name ASC`; + ORDER BY w.lastName ASC`; return Self.rawSql(query); }; diff --git a/modules/client/back/methods/client/specs/activeWorkersWithRole.spec.js b/modules/client/back/methods/client/specs/activeWorkersWithRole.spec.js new file mode 100644 index 000000000..0004b2156 --- /dev/null +++ b/modules/client/back/methods/client/specs/activeWorkersWithRole.spec.js @@ -0,0 +1,23 @@ +const app = require('vn-loopback/server/server'); + +describe('Client activeWorkersWithRole', () => { + it('should return the sales people as result', async() => { + let filter = {where: {role: 'salesPerson'}}; + let result = await app.models.Client.activeWorkersWithRole(filter); + + let isSalesPerson = await app.models.Account.hasRole(result[0].id, 'salesPerson'); + + expect(result.length).toEqual(14); + expect(isSalesPerson).toBeTruthy(); + }); + + it('should return the buyers as result', async() => { + let filter = {where: {role: 'buyer'}}; + let result = await app.models.Client.activeWorkersWithRole(filter); + + let isBuyer = await app.models.Account.hasRole(result[0].id, 'buyer'); + + expect(result.length).toEqual(11); + expect(isBuyer).toBeTruthy(); + }); +}); diff --git a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js new file mode 100644 index 000000000..2ec91125d --- /dev/null +++ b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js @@ -0,0 +1,40 @@ +const app = require('vn-loopback/server/server'); + +describe('Client addressesPropagateRe', () => { + let client; + beforeEach(async() => { + client = await app.models.Client.findById(101); + await app.models.Address.update({clientFk: 101}, {isEqualizated: false}); + await client.updateAttributes({hasToInvoiceByAddress: true}); + }); + + afterAll(async done => { + await app.models.Address.update({clientFk: 101}, {isEqualizated: false}); + await client.updateAttributes({hasToInvoiceByAddress: true}); + + done(); + }); + + it('should propagate the isEqualizated on both addresses of Mr Wayne and set hasToInvoiceByAddress to false', async() => { + let id = 101; + let data = { + isEqualizated: true + }; + + let resultAddress = await app.models.Address.find({where: {clientFk: id}}); + let resultClient = await app.models.Client.find({where: {id: id}}); + + expect(resultAddress[0].isEqualizated).toBeFalsy(); + expect(resultAddress[1].isEqualizated).toBeFalsy(); + expect(resultClient[0].hasToInvoiceByAddress).toBeTruthy(); + + await app.models.Client.addressesPropagateRe(id, data); + + resultAddress = await app.models.Address.find({where: {clientFk: id}}); + resultClient = await app.models.Client.find({where: {id: id}}); + + expect(resultAddress[0].isEqualizated).toBeTruthy(); + expect(resultAddress[1].isEqualizated).toBeTruthy(); + expect(resultClient[0].hasToInvoiceByAddress).toBeFalsy(); + }); +}); diff --git a/modules/client/back/methods/client/specs/confirmTransaction.spec.js b/modules/client/back/methods/client/specs/confirmTransaction.spec.js new file mode 100644 index 000000000..5fe638001 --- /dev/null +++ b/modules/client/back/methods/client/specs/confirmTransaction.spec.js @@ -0,0 +1,24 @@ +const app = require('vn-loopback/server/server'); + +describe('Client confirmTransaction', () => { + const transactionId = 2; + + afterAll(async done => { + await app.models.Client.rawSql(` + CALL hedera.tpvTransaction_undo(?)`, [transactionId]); + + done(); + }); + + it('should call confirmTransaction() method to mark transaction as confirmed', async() => { + let ctx = {req: {accessToken: {userId: 1}}}; + await app.models.Client.confirmTransaction(ctx, transactionId); + + let [receipt] = await app.models.Client.rawSql( + `SELECT receiptFk + FROM hedera.tpvTransaction + WHERE id = ?`, [transactionId]); + + expect(receipt.receiptFk).toBeGreaterThan(0); + }); +}); diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js new file mode 100644 index 000000000..71a6e7b39 --- /dev/null +++ b/modules/client/back/methods/client/specs/createWithUser.spec.js @@ -0,0 +1,64 @@ +const app = require('vn-loopback/server/server'); + +describe('Client Create', () => { + const clientName = 'Wade'; + const AccountName = 'Deadpool'; + + afterAll(async done => { + let address = await app.models.Address.findOne({where: {nickname: clientName}}); + let client = await app.models.Client.findOne({where: {name: clientName}}); + let account = await app.models.Account.findOne({where: {name: AccountName}}); + await app.models.Address.destroyById(address.id); + await app.models.Client.destroyById(client.id); + await app.models.Account.destroyById(account.id); + + done(); + }); + + let newAccount = { + userName: 'Deadpool', + email: 'Deadpool@marvel.com', + fi: '16195279J', + name: 'Wade', + socialName: 'Deadpool Marvel', + street: 'Wall Street', + city: 'New York' + }; + + it(`should not find Deadpool as he's not created yet`, async() => { + let account = await app.models.Account.findOne({where: {name: newAccount.userName}}); + let client = await app.models.Client.findOne({where: {name: newAccount.name}}); + + expect(account).toEqual(null); + expect(client).toEqual(null); + }); + + it('should create a new account', async() => { + let client = await app.models.Client.createWithUser(newAccount); + let account = await app.models.Account.findOne({where: {name: newAccount.userName}}); + + expect(account.name).toEqual(newAccount.userName); + + expect(client.id).toEqual(account.id); + expect(client.name).toEqual(newAccount.name); + expect(client.email).toEqual(newAccount.email); + expect(client.fi).toEqual(newAccount.fi); + expect(client.socialName).toEqual(newAccount.socialName); + }); + + it('should find an existing account', async() => { + let account = await app.models.Account.findOne({where: {name: newAccount.userName}}); + + expect(account.name).toEqual(newAccount.userName); + }); + + it('should not be able to create a user if exists', async() => { + try { + let client = await app.models.Client.createWithUser(newAccount); + + expect(client).toBeNull(); + } catch (err) { + expect(err.details.codes.name[0]).toEqual('uniqueness'); + } + }); +}); diff --git a/modules/client/back/methods/client/specs/getAverageInvoiced.spec.js b/modules/client/back/methods/client/specs/getAverageInvoiced.spec.js new file mode 100644 index 000000000..fd30270e7 --- /dev/null +++ b/modules/client/back/methods/client/specs/getAverageInvoiced.spec.js @@ -0,0 +1,9 @@ +const app = require('vn-loopback/server/server'); + +describe('client getAverageInvoiced()', () => { + it('should call the getAverageInvoiced method', async() => { + const {invoiced} = await app.models.Client.getAverageInvoiced(101); + + expect(invoiced).toEqual(1500); + }); +}); diff --git a/modules/client/back/methods/client/specs/getCard.spec.js b/modules/client/back/methods/client/specs/getCard.spec.js new file mode 100644 index 000000000..18519d440 --- /dev/null +++ b/modules/client/back/methods/client/specs/getCard.spec.js @@ -0,0 +1,12 @@ +const app = require('vn-loopback/server/server'); + +describe('Client get', () => { + it('should receive a formated card of Bruce Wayne', async() => { + let id = 101; + let result = await app.models.Client.getCard(id); + + expect(result.id).toEqual(101); + expect(result.name).toEqual('Bruce Wayne'); + expect(result.debt).toEqual(889.38); + }); +}); diff --git a/modules/client/back/methods/client/specs/getDebt.spec.js b/modules/client/back/methods/client/specs/getDebt.spec.js new file mode 100644 index 000000000..9e539c219 --- /dev/null +++ b/modules/client/back/methods/client/specs/getDebt.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('client getDebt()', () => { + it('should return the client debt', async() => { + let result = await app.models.Client.getDebt(101); + + expect(result.debt).toEqual(889.38); + }); +}); + diff --git a/modules/client/back/methods/client/specs/getMana.spec.js b/modules/client/back/methods/client/specs/getMana.spec.js new file mode 100644 index 000000000..e6fb09c90 --- /dev/null +++ b/modules/client/back/methods/client/specs/getMana.spec.js @@ -0,0 +1,9 @@ +const app = require('vn-loopback/server/server'); + +describe('client getMana()', () => { + it('should call the getMana method', async() => { + let result = await app.models.Client.getMana(105); + + expect(result.mana).toEqual(0.34); + }); +}); diff --git a/modules/client/back/methods/client/specs/getTransactions.spec.js b/modules/client/back/methods/client/specs/getTransactions.spec.js new file mode 100644 index 000000000..f04cf9050 --- /dev/null +++ b/modules/client/back/methods/client/specs/getTransactions.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('Client getTransations', () => { + it('should call getTransations() method to receive a list of Web Payments from Bruce Wayne', async() => { + let filter = {where: {clientFk: 101}}; + let result = await app.models.Client.getTransactions(filter); + + expect(result[1].id).toBeTruthy(); + }); +}); diff --git a/services/loopback/common/methods/client/specs/hasCustomerRole.spec.js b/modules/client/back/methods/client/specs/hasCustomerRole.spec.js similarity index 79% rename from services/loopback/common/methods/client/specs/hasCustomerRole.spec.js rename to modules/client/back/methods/client/specs/hasCustomerRole.spec.js index c1b25f8a9..87306afa7 100644 --- a/services/loopback/common/methods/client/specs/hasCustomerRole.spec.js +++ b/modules/client/back/methods/client/specs/hasCustomerRole.spec.js @@ -1,5 +1,4 @@ -const app = require('../../../../../client/server/server'); -const catchErrors = require('../../../../../../services/utils/jasmineHelpers').catchErrors; +const app = require('vn-loopback/server/server'); describe('Client hasCustomerRole', () => { it('should call the hasCustomerRole() method with a customer id', done => { @@ -7,7 +6,7 @@ describe('Client hasCustomerRole', () => { let params = {}; let callback = (error, result) => { - if (error) return catchErrors(done)(error); + if (error) return done.fail(error); expect(result).toEqual(jasmine.objectContaining({isCustomer: 1})); done(); @@ -21,7 +20,7 @@ describe('Client hasCustomerRole', () => { let params = {}; let callback = (error, result) => { - if (error) return catchErrors(done)(error); + if (error) return done.fail(error); expect(result).toEqual(jasmine.objectContaining({isCustomer: 0})); done(); @@ -35,7 +34,7 @@ describe('Client hasCustomerRole', () => { let params = {}; let callback = (error, result) => { - if (error) return catchErrors(done)(error); + if (error) return done.fail(error); expect(result).toEqual(jasmine.objectContaining({isCustomer: 0})); done(); @@ -49,7 +48,7 @@ describe('Client hasCustomerRole', () => { let params = {}; let callback = (error, result) => { - if (error) return catchErrors(done)(error); + if (error) return done.fail(error); expect(result).toEqual(jasmine.objectContaining({isCustomer: 0})); done(); diff --git a/modules/client/back/methods/client/specs/isValidClient.spec.js b/modules/client/back/methods/client/specs/isValidClient.spec.js new file mode 100644 index 000000000..446392374 --- /dev/null +++ b/modules/client/back/methods/client/specs/isValidClient.spec.js @@ -0,0 +1,45 @@ +const app = require('vn-loopback/server/server'); + +describe('Client isValidClient', () => { + it('should call the isValidClient() method with a client id and receive true', async() => { + let id = 101; + let result = await app.models.Client.isValidClient(id); + + expect(result).toBeTruthy(); + }); + + it('should call the isValidClient() method with an employee id to receive false', async() => { + let id = 1; + let result = await app.models.Client.isValidClient(id); + + expect(result).toBeFalsy(); + }); + + it('should call the isValidClient() method with an unexistant id and receive false', async() => { + let id = 999999; + let result = await app.models.Client.isValidClient(id); + + expect(result).toBeFalsy(); + }); + + it('should call the isValidClient() method with an invalid id and receive false', async() => { + let id = 'Pepinillos'; + let result = await app.models.Client.isValidClient(id); + + expect(result).toBeFalsy(); + }); + + it('should call the isValidClient() method with a customer id which isnt active and return false', async() => { + let id = '106'; + let result = await app.models.Client.isValidClient(id); + + expect(result).toBeFalsy(); + }); + + it('should call the isValidClient() method with a customer id which his data isnt verified and return false', async() => { + let id = '110'; + let result = await app.models.Client.isValidClient(id); + + expect(result).toBeFalsy(); + }); +}); diff --git a/modules/client/back/methods/client/specs/listWorkers.spec.js b/modules/client/back/methods/client/specs/listWorkers.spec.js new file mode 100644 index 000000000..728268457 --- /dev/null +++ b/modules/client/back/methods/client/specs/listWorkers.spec.js @@ -0,0 +1,14 @@ +const app = require('vn-loopback/server/server'); + +describe('Client listWorkers', () => { + it('should call the listWorkers()', done => { + app.models.Client.listWorkers() + .then(result => { + let amountOfEmployees = Object.keys(result).length; + + expect(amountOfEmployees).toEqual(49); + done(); + }) + .catch(done.fail); + }); +}); diff --git a/modules/client/back/methods/client/specs/summary.spec.js b/modules/client/back/methods/client/specs/summary.spec.js new file mode 100644 index 000000000..e4ebd9c67 --- /dev/null +++ b/modules/client/back/methods/client/specs/summary.spec.js @@ -0,0 +1,46 @@ +const app = require('vn-loopback/server/server'); + +describe('client summary()', () => { + it('should return a summary object containing data', async() => { + let result = await app.models.Client.summary(101); + + expect(result.id).toEqual(101); + expect(result.name).toEqual('Bruce Wayne'); + }); + + it('should return a summary object containing mana', async() => { + let result = await app.models.Client.summary(105); + + expect(result.mana.mana).toEqual(0.34); + }); + + it('should return a summary object containing debt', async() => { + let result = await app.models.Client.summary(101); + + expect(result.debt.debt).toEqual(889.38); + }); + + it('should return a summary object containing averageInvoiced', async() => { + let result = await app.models.Client.summary(101); + + expect(result.averageInvoiced.invoiced).toEqual(1500); + }); + + it('should return a summary object containing totalGreuge', async() => { + let result = await app.models.Client.summary(101); + + expect(result.totalGreuge).toEqual(203.71); + }); + + it('should return a summary object without containing active recoveries', async() => { + let result = await app.models.Client.summary(101); + + expect(result.recovery).toEqual(null); + }); + + it('should return a summary object containing active recoveries', async() => { + let result = await app.models.Client.summary(102); + + expect(result.recovery.id).toEqual(3); + }); +}); diff --git a/modules/client/back/methods/client/specs/threeLastActive.spec.js b/modules/client/back/methods/client/specs/threeLastActive.spec.js new file mode 100644 index 000000000..cd76a0b5b --- /dev/null +++ b/modules/client/back/methods/client/specs/threeLastActive.spec.js @@ -0,0 +1,12 @@ +const app = require('vn-loopback/server/server'); + +describe('client lastActiveTickets()', () => { + it('should return the last three active tickets', async() => { + const clientId = 109; + const ticketId = 19; + + let result = await app.models.Client.lastActiveTickets(clientId, ticketId); + + expect(result.length).toEqual(3); + }); +}); diff --git a/modules/client/back/methods/client/specs/updateFiscalData.spec.js b/modules/client/back/methods/client/specs/updateFiscalData.spec.js new file mode 100644 index 000000000..90136cec7 --- /dev/null +++ b/modules/client/back/methods/client/specs/updateFiscalData.spec.js @@ -0,0 +1,57 @@ +const app = require('vn-loopback/server/server'); + +describe('Client updateFiscalData', () => { + afterAll(async done => { + let ctxOfAdmin = {req: {accessToken: {userId: 5}}}; + let validparams = {postcode: 46460}; + let idWithDataChecked = 101; + + await app.models.Client.updateFiscalData(ctxOfAdmin, validparams, idWithDataChecked); + + done(); + }); + + it('should return an error if the user is not administrative and the isTaxDataChecked value is true', async() => { + let error; + + let ctxOfNoAdmin = {req: {accessToken: {userId: 1}}}; + let params = []; + let idWithDataChecked = 101; + + await app.models.Client.updateFiscalData(ctxOfNoAdmin, params, idWithDataChecked) + .catch(e => { + error = e; + }); + + expect(error.toString()).toContain(`You can't make changes on a client with verified data`); + }); + + it('should return an error if the user is administrative and the isTaxDataChecked value is true BUT the params aint valid', async() => { + let error; + + let ctxOfAdmin = {req: {accessToken: {userId: 5}}}; + let invalidparams = {invalid: 'param for update'}; + let idWithDataChecked = 101; + + await app.models.Client.updateFiscalData(ctxOfAdmin, invalidparams, idWithDataChecked) + .catch(e => { + error = e; + }); + + expect(error.toString()).toContain(`You don't have enough privileges to do that`); + }); + + it('should update the client fiscal data and return the count if changes made', async() => { + let ctxOfAdmin = {req: {accessToken: {userId: 5}}}; + let validparams = {postcode: 46680}; + let idWithDataChecked = 101; + + let client = await app.models.Client.findById(idWithDataChecked); + + expect(client.postcode).toEqual('46460'); + + let result = await app.models.Client.updateFiscalData(ctxOfAdmin, validparams, idWithDataChecked); + + expect(result.postcode).toEqual('46680'); + }); +}); diff --git a/modules/client/back/methods/client/specs/uploadFile.spec.js b/modules/client/back/methods/client/specs/uploadFile.spec.js new file mode 100644 index 000000000..15110731e --- /dev/null +++ b/modules/client/back/methods/client/specs/uploadFile.spec.js @@ -0,0 +1,19 @@ +const app = require('vn-loopback/server/server'); + +describe('Client uploadFile()', () => { + it(`should return an error for a user without enough privileges`, async() => { + let clientId = 101; + let currentUserId = 102; + let paymentLawTypeId = 12; + let ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: paymentLawTypeId}}; + + let error; + await app.models.Client.uploadFile(ctx, clientId).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`You don't have enough privileges`); + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/modules/client/back/methods/client/summary.js b/modules/client/back/methods/client/summary.js new file mode 100644 index 000000000..155d95d9e --- /dev/null +++ b/modules/client/back/methods/client/summary.js @@ -0,0 +1,137 @@ +module.exports = Self => { + Self.remoteMethod('summary', { + description: 'Returns a client summary', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'client id', + http: {source: 'path'} + }], + returns: { + type: [this.modelName], + root: true + }, + http: { + path: `/:id/summary`, + verb: 'GET' + } + }); + + Self.summary = async clientFk => { + let models = Self.app.models; + let summaryObj = await getSummary(models.Client, clientFk); + + summaryObj.mana = await models.Client.getMana(clientFk); + summaryObj.debt = await models.Client.getDebt(clientFk); + summaryObj.averageInvoiced = await models.Client.getAverageInvoiced(clientFk); + summaryObj.totalGreuge = await models.Greuge.sumAmount(clientFk); + summaryObj.recovery = await getRecoveries(models.Recovery, clientFk); + + return summaryObj; + }; + + async function getSummary(client, clientId) { + let filter = { + include: [ + { + relation: 'account', + scope: { + fields: ['name', 'active'] + } + }, + { + relation: 'salesPerson', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + }, + { + relation: 'country', + scope: { + fields: ['country'] + } + }, + { + relation: 'province', + scope: { + fields: ['name'] + } + }, + { + relation: 'contactChannel', + scope: { + fields: ['name'] + } + }, + { + relation: 'payMethod', + scope: { + fields: ['name'] + } + }, + { + relation: 'defaultAddress', + scope: { + fields: ['nickname', 'street', 'city', 'postalCode'] + } + }, + { + relation: 'classifications', + scope: { + include: { + relation: 'insurances', + scope: { + fields: ['id', 'grade', 'created'], + order: 'created DESC' + } + }, + where: {finished: null} + } + }, + { + relation: 'defaulters', + scope: { + fields: ['amount'], + order: 'created DESC', + limit: 1 + } + }, + { + relation: 'clientRisks', + scope: { + fields: ['amount', 'companyFk'] + } + }, + { + relation: 'claimsRatio', + scope: { + fields: ['claimingRate', 'priceIncreasing'], + limit: 1 + } + } + ], + where: {id: clientId} + }; + + return await client.findOne(filter); + } + + async function getRecoveries(recovery, clientId) { + let filter = { + where: { + and: [{clientFk: clientId}, {or: [{finished: null}, {finished: {gt: Date.now()}}]}] + }, + limit: 1 + }; + + return await recovery.findOne(filter); + } +}; diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js new file mode 100644 index 000000000..0f7810ed2 --- /dev/null +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -0,0 +1,68 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('updateFiscalData', { + description: 'Updates billing data of a client', + accessType: 'WRITE', + accepts: [{ + arg: 'data', + type: 'Object', + required: true, + description: 'Params to update', + http: {source: 'body'} + }, { + arg: 'id', + type: 'string', + required: true, + description: 'Model id', + http: {source: 'path'} + }], + returns: { + arg: 'res', + type: 'String', + root: true + }, + http: { + path: `/:id/updateFiscalData`, + verb: 'PATCH' + } + }); + + Self.updateFiscalData = async(ctx, params, id) => { + let userId = ctx.req.accessToken.userId; + let isSalesAssistant = await Self.app.models.Account.hasRole(userId, 'salesAssistant'); + let [taxData] = await Self.app.models.Client.find({where: {id: id}, fields: ['isTaxDataChecked']}); + + if (!isSalesAssistant && taxData.isTaxDataChecked) + throw new UserError(`You can't make changes on a client with verified data`); + + let validUpdateParams = [ + 'socialName', + 'fi', + 'street', + 'postcode', + 'city', + 'countryFk', + 'provinceFk', + 'isActive', + 'isFreezed', + 'hasToInvoice', + 'isVies', + 'isToBeMailed', + 'hasToInvoiceByAddress', + 'isEqualizated', + 'isTaxDataVerified', + 'isTaxDataChecked' + ]; + + for (const key in params) { + if (validUpdateParams.indexOf(key) === -1) + throw new UserError(`You don't have enough privileges to do that`); + } + + params.id = id; + + let client = await Self.app.models.Client.findById(id); + return await client.updateAttributes(params); + }; +}; diff --git a/modules/client/back/methods/client/uploadFile.js b/modules/client/back/methods/client/uploadFile.js new file mode 100644 index 000000000..6ec96e301 --- /dev/null +++ b/modules/client/back/methods/client/uploadFile.js @@ -0,0 +1,76 @@ +module.exports = Self => { + Self.remoteMethodCtx('uploadFile', { + description: 'Upload and attach a file to a client', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'Number', + description: 'The client id', + http: {source: 'path'} + }, { + arg: 'warehouseId', + type: 'Number', + description: 'The warehouse id', + required: true + }, { + arg: 'companyId', + type: 'Number', + description: 'The company id', + required: true + }, { + arg: 'dmsTypeId', + type: 'Number', + description: 'The dms type id', + required: true + }, { + arg: 'reference', + type: 'String', + required: true + }, { + arg: 'description', + type: 'String', + required: true + }, { + arg: 'hasFile', + type: 'Boolean', + description: 'True if has an attached file', + required: true + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/uploadFile`, + verb: 'POST' + } + }); + + Self.uploadFile = async(ctx, id) => { + const models = Self.app.models; + const promises = []; + const tx = await Self.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const uploadedFiles = await models.Dms.uploadFile(ctx, options); + uploadedFiles.forEach(dms => { + const newClientDms = models.ClientDms.create({ + clientFk: id, + dmsFk: dms.id + }, options); + + promises.push(newClientDms); + }); + const resolvedPromises = await Promise.all(promises); + + await tx.commit(); + + return resolvedPromises; + } catch (err) { + await tx.rollback(); + throw err; + } + }; +}; diff --git a/modules/client/back/methods/credit-classification/createWithInsurance.js b/modules/client/back/methods/credit-classification/createWithInsurance.js new file mode 100644 index 000000000..368e9a41a --- /dev/null +++ b/modules/client/back/methods/credit-classification/createWithInsurance.js @@ -0,0 +1,50 @@ +module.exports = Self => { + Self.remoteMethod('createWithInsurance', { + description: 'Creates both classification and one insurance', + accepts: [{ + arg: 'data', + type: 'object', + http: {source: 'body'} + }, { + arg: 'context', + type: 'object', + http: function(ctx) { + return ctx; + } + }], + returns: { + root: true, + type: 'boolean' + }, + http: { + verb: 'post', + path: '/createWithInsurance' + } + }); + + Self.createWithInsurance = async(data, ctx) => { + let tx = await Self.beginTransaction({}); + + try { + let options = {transaction: tx}; + + let classificationSchema = {client: data.clientFk, started: data.started}; + let newClassification = await Self.create(classificationSchema, options); + let CreditInsurance = Self.app.models.CreditInsurance; + let insuranceSchema = { + creditClassification: newClassification.id, + credit: data.credit, + grade: data.grade + }; + + let newCreditInsurance = await CreditInsurance.create(insuranceSchema, options); + await tx.commit(); + await CreditInsurance.messageSend(newCreditInsurance, ctx.req.accessToken); + + return newClassification; + } catch (e) { + await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/client/back/methods/credit-classification/createWithInsurance.spec.js b/modules/client/back/methods/credit-classification/createWithInsurance.spec.js new file mode 100644 index 000000000..4e5b5127e --- /dev/null +++ b/modules/client/back/methods/credit-classification/createWithInsurance.spec.js @@ -0,0 +1,53 @@ +const app = require('vn-loopback/server/server'); + +describe('Client createWithInsurance', () => { + let classificationId; + + afterAll(async done => { + await app.models.CreditClassification.destroyById(classificationId); + + done(); + }); + + it('should verify the classifications and insurances are untainted', async() => { + let classifications = await app.models.CreditClassification.find(); + let insurances = await app.models.CreditInsurance.find(); + + expect(classifications.length).toEqual(5); + expect(insurances.length).toEqual(3); + }); + + it('should not create the insurance if couldnt create the classification', async() => { + let error; + let data = {clientFk: null, started: Date.now(), credit: 999, grade: 255}; + let ctx = {req: {accessToken: {userId: 101}}}; + await app.models.CreditClassification.createWithInsurance(data, ctx) + .catch(e => { + error = e; + }); + + expect(error.toString()).toBe('Error: ER_BAD_NULL_ERROR: Column \'client\' cannot be null'); + + let classifications = await app.models.CreditClassification.find(); + let insurances = await app.models.CreditInsurance.find(); + + expect(classifications.length).toEqual(5); + expect(insurances.length).toEqual(3); + }); + + it('should create a new client credit classification with insurance', async() => { + let data = {clientFk: 101, started: Date.now(), credit: 999, grade: 255}; + let ctx = {req: {accessToken: {userId: 101}}}; + let result = await app.models.CreditClassification.createWithInsurance(data, ctx); + + classificationId = result.id; + + expect(result.client).toEqual(101); + + let classifications = await app.models.CreditClassification.find(); + let insurances = await app.models.CreditInsurance.find(); + + expect(classifications.length).toEqual(6); + expect(insurances.length).toEqual(4); + }); +}); diff --git a/modules/client/back/methods/greuge/specs/sumAmount.spec.js b/modules/client/back/methods/greuge/specs/sumAmount.spec.js new file mode 100644 index 000000000..fc84bca98 --- /dev/null +++ b/modules/client/back/methods/greuge/specs/sumAmount.spec.js @@ -0,0 +1,14 @@ +const totalGreuge = require('../sumAmount'); + +describe('Greuge totalGreuge()', () => { + it('should call the sumAmount method', async() => { + let clientFk = 1; + let self = jasmine.createSpyObj('self', ['remoteMethod', 'rawSql']); + self.rawSql.and.returnValue(Promise.resolve([{sumAmount: 6000}])); + totalGreuge(self); + + let result = await self.sumAmount(clientFk); + + expect(result).toBe(6000); + }); +}); diff --git a/modules/client/back/methods/greuge/sumAmount.js b/modules/client/back/methods/greuge/sumAmount.js new file mode 100644 index 000000000..dcc780168 --- /dev/null +++ b/modules/client/back/methods/greuge/sumAmount.js @@ -0,0 +1,31 @@ +module.exports = Self => { + Self.remoteMethod('sumAmount', { + description: 'Returns the sum of greuge for a client', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'clientFk', + http: {source: 'path'} + }], + returns: { + arg: 'sumAmount' + }, + http: { + path: `/:id/sumAmount`, + verb: 'get' + } + }); + + Self.sumAmount = async clientFk => { + let query = `SELECT SUM(amount) AS sumAmount FROM vn.greuge WHERE clientFk = ?`; + try { + let [response] = await Self.rawSql(query, [clientFk]); + + return response ? response.sumAmount : 0; + } catch (e) { + throw new Error(e); + } + }; +}; diff --git a/modules/client/back/methods/receipt/filter.js b/modules/client/back/methods/receipt/filter.js new file mode 100644 index 000000000..5c0d6c1dd --- /dev/null +++ b/modules/client/back/methods/receipt/filter.js @@ -0,0 +1,85 @@ +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accessType: 'READ', + accepts: [ + { + arg: 'filter', + type: 'Object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + http: {source: 'query'} + }, { + arg: 'params', + type: 'Object', + description: 'clientFk', + http: {source: 'query'} + } + ], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/filter`, + verb: 'GET' + } + }); + + Self.filter = async(filter, params) => { + let stmt = new ParameterizedSQL( + `SELECT * FROM ( + SELECT + r.id, + r.isConciliate, + r.payed, + r.workerFk, + c.code company, + r.created, + r.invoiceFk ref, + NULL debit, + r.amountPaid credit, + r.bankFk, + u.nickname userNickname, + r.clientFk, + FALSE hasPdf, + FALSE isInvoice + FROM vn.receipt r + LEFT JOIN vn.worker w ON w.id = r.workerFk + LEFT JOIN account.user u ON u.id = w.userFk + JOIN vn.company c ON c.id = r.companyFk + WHERE r.clientFk = ? AND r.companyFk = ? + UNION ALL + SELECT + i.id, + TRUE, + i.issued, + NULL, + c.code, + i.created, + i.ref, + i.amount, + NULL, + NULL, + NULL, + i.clientFk, + i.hasPdf, + TRUE isInvoice + FROM vn.invoiceOut i + JOIN vn.company c ON c.id = i.companyFk + WHERE i.clientFk = ? AND i.companyFk = ? + ORDER BY payed DESC, created DESC + ) t + ORDER BY payed DESC, created DESC`, [ + params.clientFk, + params.companyFk, + params.clientFk, + params.companyFk, + ] + ); + + stmt.merge(Self.makeLimit(filter)); + return await Self.rawStmt(stmt); + }; +}; diff --git a/modules/client/back/methods/receipt/specs/filter.spec.js b/modules/client/back/methods/receipt/specs/filter.spec.js new file mode 100644 index 000000000..5e8ccd807 --- /dev/null +++ b/modules/client/back/methods/receipt/specs/filter.spec.js @@ -0,0 +1,14 @@ +const app = require('vn-loopback/server/server'); + +describe('receipt filter()', () => { + it('should return the receipts', async() => { + let filter = {limit: 20}; + let params = { + clientFk: 101, + companyFk: 442 + }; + let result = await app.models.Receipt.filter(filter, params); + + expect(result.length).toBeGreaterThan(0); + }); +}); diff --git a/modules/client/back/methods/recovery/hasActiveRecovery.js b/modules/client/back/methods/recovery/hasActiveRecovery.js new file mode 100644 index 000000000..81a8a5f40 --- /dev/null +++ b/modules/client/back/methods/recovery/hasActiveRecovery.js @@ -0,0 +1,34 @@ +module.exports = Self => { + Self.remoteMethod('hasActiveRecovery', { + description: 'Returns a boolean that is true when a client has an active recovery', + accessType: 'READ', + accepts: [ + { + arg: 'clientFk', + type: 'number', + required: true, + description: 'The id of a client', + http: {source: 'path'} + } + ], + returns: { + type: 'boolean', + root: true + }, + http: { + path: `/:clientFk/hasActiveRecovery`, + verb: 'GET' + } + }); + + Self.hasActiveRecovery = async id => { + let result = await Self.rawSql( + `SELECT count(*) AS hasActiveRecovery + FROM vn.recovery + WHERE clientFk = ? + AND IFNULL(finished,CURDATE()) >= CURDATE();`, + [id] + ); + return result[0].hasActiveRecovery != 0; + }; +}; diff --git a/modules/client/back/methods/recovery/hasActiveRecovery.spec.js b/modules/client/back/methods/recovery/hasActiveRecovery.spec.js new file mode 100644 index 000000000..218d10df5 --- /dev/null +++ b/modules/client/back/methods/recovery/hasActiveRecovery.spec.js @@ -0,0 +1,15 @@ +const app = require('vn-loopback/server/server'); + +describe('client hasActiveRecovery', () => { + it(`should return false if the client doesn't owes`, async() => { + let hasActiveRecovery = await app.models.Recovery.hasActiveRecovery(101); + + expect(hasActiveRecovery).toBeFalsy(); + }); + + it('should return true if the client owes', async() => { + let hasActiveRecovery = await app.models.Recovery.hasActiveRecovery(102); + + expect(hasActiveRecovery).toBeTruthy(); + }); +}); diff --git a/modules/client/back/methods/sms/send.js b/modules/client/back/methods/sms/send.js new file mode 100644 index 000000000..e56b5567e --- /dev/null +++ b/modules/client/back/methods/sms/send.js @@ -0,0 +1,92 @@ +const soap = require('soap'); +const xmlParser = require('xml2js').parseString; +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('send', { + description: 'Sends SMS to a destination phone', + accessType: 'WRITE', + accepts: [{ + arg: 'destinationFk', + type: 'Integer' + }, + { + arg: 'destination', + type: 'String', + required: true, + }, + { + arg: 'message', + type: 'String', + required: true, + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/send`, + verb: 'POST' + } + }); + + Self.send = async(ctx, destinationFk, destination, message) => { + const userId = ctx.req.accessToken.userId; + const smsConfig = await Self.app.models.SmsConfig.findOne(); + const soapClient = await soap.createClientAsync(smsConfig.uri); + const params = { + user: smsConfig.user, + pass: smsConfig.password, + src: smsConfig.title, + dst: destination, + msg: message + }; + + let xmlResponse; + let xmlResult; + let xmlParsed; + let status; + + + try { + if (process.env.NODE_ENV !== 'production') { + status = { + codigo: [200], + descripcion: ['Fake response'] + }; + } else { + [xmlResponse] = await soapClient.sendSMSAsync(params); + xmlResult = xmlResponse.result.$value; + xmlParsed = await new Promise((resolve, reject) => { + xmlParser(xmlResult, (err, result) => { + if (err) + reject(err); + resolve(result); + }); + }); + [status] = xmlParsed['xtratelecom-sms-response'].sms; + } + } catch (e) { + console.error(e); + } + + const statusCode = status.codigo[0]; + const statusDescription = status.descripcion[0]; + + const newSms = { + senderFk: userId, + destinationFk: destinationFk || null, + destination: destination, + message: message, + statusCode: statusCode, + status: statusDescription + }; + + const sms = await Self.create(newSms); + + if (statusCode != 200) + throw new UserError(`We weren't able to send this SMS`); + + return sms; + }; +}; diff --git a/modules/client/back/methods/sms/send.spec.js b/modules/client/back/methods/sms/send.spec.js new file mode 100644 index 000000000..612a16cf1 --- /dev/null +++ b/modules/client/back/methods/sms/send.spec.js @@ -0,0 +1,37 @@ +const app = require('vn-loopback/server/server'); +const soap = require('soap'); + +describe('sms send()', () => { + it('should return the expected message and status code', async() => { + const code = 200; + const smsConfig = await app.models.SmsConfig.findOne(); + const soapClient = await soap.createClientAsync(smsConfig.uri); + spyOn(soap, 'createClientAsync').and.returnValue(soapClient); + spyOn(soapClient, 'sendSMSAsync').and.returnValue([{ + result: { + $value: + ` + + + ${code} + + + Envio en procesamiento + + + 1 + + + + 444328681 + + ` + } + }]); + let ctx = {req: {accessToken: {userId: 1}}}; + let result = await app.models.Sms.send(ctx, 105, 'destination', 'My SMS Body'); + + expect(result.statusCode).toEqual(200); + expect(result.status).toContain('Fake response'); + }); +}); diff --git a/modules/client/back/model-config.json b/modules/client/back/model-config.json new file mode 100644 index 000000000..3aa709eb7 --- /dev/null +++ b/modules/client/back/model-config.json @@ -0,0 +1,98 @@ +{ + "Address": { + "dataSource": "vn" + }, + "AddressObservation": { + "dataSource": "vn" + }, + "BankEntity": { + "dataSource": "vn" + }, + "Client": { + "dataSource": "vn" + }, + "ClientContact": { + "dataSource": "vn" + }, + "ClientCredit": { + "dataSource": "vn" + }, + "ClientCreditLimit": { + "dataSource": "vn" + }, + "ClientLog": { + "dataSource": "vn" + }, + "ClientObservation": { + "dataSource": "vn" + }, + "ClientRisk": { + "dataSource": "vn" + }, + "ContactChannel": { + "dataSource": "vn" + }, + "CreditClassification": { + "dataSource": "vn" + }, + "CreditInsurance": { + "dataSource": "vn" + }, + "ClientType": { + "dataSource": "vn" + }, + "Defaulter": { + "dataSource": "vn" + }, + "Greuge": { + "dataSource": "vn" + }, + "GreugeType": { + "dataSource": "vn" + }, + "Mandate": { + "dataSource": "vn" + }, + "MandateType": { + "dataSource": "vn" + }, + "ObservationType": { + "dataSource": "vn" + }, + "PayMethod": { + "dataSource": "vn" + }, + "Receipt": { + "dataSource": "vn" + }, + "Recovery": { + "dataSource": "vn" + }, + "Sample": { + "dataSource": "vn" + }, + "ClientSample": { + "dataSource": "vn" + }, + "Sms": { + "dataSource": "vn" + }, + "SmsConfig": { + "dataSource": "vn" + }, + "TpvError": { + "dataSource": "vn" + }, + "TpvMerchant": { + "dataSource": "vn" + }, + "TpvResponse": { + "dataSource": "vn" + }, + "TpvTransaction": { + "dataSource": "vn" + }, + "ClientDms": { + "dataSource": "vn" + } +} diff --git a/modules/client/back/models/address-observation.js b/modules/client/back/models/address-observation.js new file mode 100644 index 000000000..1c0a8aef7 --- /dev/null +++ b/modules/client/back/models/address-observation.js @@ -0,0 +1,21 @@ +module.exports = function(Self) { + Self.validateAsync('typeUnique', typeIsUnique, { + message: 'Observation type must be unique' + }); + async function typeIsUnique(err, done) { + let filter = { + fields: ['id'], + where: { + observationTypeFk: this.observationTypeFk, + addressFk: this.addressFk + } + }; + + if (this.id) + filter.where.id = {neq: this.id}; + + if (await Self.findOne(filter)) + err(); + done(); + } +}; diff --git a/modules/client/back/models/address-observation.json b/modules/client/back/models/address-observation.json new file mode 100644 index 000000000..3096c8e5d --- /dev/null +++ b/modules/client/back/models/address-observation.json @@ -0,0 +1,36 @@ +{ + "name": "AddressObservation", + "base": "VnModel", + "options": { + "mysql": { + "table": "addressObservation" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "description": { + "type": "string", + "required": true + }, + "observationTypeFk": { + "required": true + } + }, + "relations": { + "address": { + "type": "belongsTo", + "model": "Address", + "foreignKey": "addressFk" + }, + "observationType": { + "type": "belongsTo", + "model": "ObservationType", + "foreignKey": "observationTypeFk" + } + } +} + \ No newline at end of file diff --git a/modules/client/back/models/address.js b/modules/client/back/models/address.js new file mode 100644 index 000000000..afdacdee5 --- /dev/null +++ b/modules/client/back/models/address.js @@ -0,0 +1,85 @@ +let UserError = require('vn-loopback/util/user-error'); +let getFinalState = require('vn-loopback/util/hook').getFinalState; +let isMultiple = require('vn-loopback/util/hook').isMultiple; + +module.exports = Self => { + // Methods + require('../methods/address/createDefaultAddress')(Self); + + Self.validateAsync('isEqualizated', cannotHaveET, { + message: 'Cannot check Equalization Tax in this NIF/CIF' + }); + + async function cannotHaveET(err, done) { + let client = await Self.app.models.Client.findById(this.clientFk); + let cannotHaveET; + if (client && client.fi) { + let tin = client.fi.toUpperCase(); + cannotHaveET = /^[A-B]/.test(tin); + } else + cannotHaveET = false; + + + if (cannotHaveET && this.isEqualizated) + err(); + done(); + } + + Self.beforeRemote('findById', function(ctx, modelInstance, next) { + ctx.args.filter = { + include: [{ + relation: 'province', + scope: { + fields: ['id', 'name'] + } + }, { + relation: 'agencyMode', + scope: { + fields: ['id', 'name'] + } + }] + }; + next(); + }); + + Self.validateAsync('postalCode', hasValidPostcode, { + message: `The postcode doesn't exists. Ensure you put the correct format` + }); + + async function hasValidPostcode(err, done) { + if (!this.postalCode) + return done(); + + const models = Self.app.models; + const postcode = await models.Postcode.findById(this.postalCode); + + if (!postcode) err(); + done(); + } + + // Helpers + + Self.observe('before save', async function(ctx) { + const Client = Self.app.models.Client; + + if (isMultiple(ctx)) return; + + let transaction = {}; + if (ctx.options && ctx.options.transaction) + transaction = ctx.options.transaction; + + let changes = ctx.data || ctx.instance; + let finalState = getFinalState(ctx); + + const client = await Client.findById(finalState.clientFk, { + fields: ['isEqualizated', 'defaultAddressFk'] + }, {transaction}); + + if (changes.isActive == false && client.defaultAddressFk === finalState.id) + throw new UserError('The default consignee can not be unchecked'); + + // Propagate client isEqualizated to all addresses + if (ctx.isNewInstance == true) + ctx.instance.isEqualizated = client.isEqualizated; + }); +}; diff --git a/services/loopback/common/models/address.json b/modules/client/back/models/address.json similarity index 91% rename from services/loopback/common/models/address.json rename to modules/client/back/models/address.json index cc72cb3d4..ffc80c49b 100644 --- a/services/loopback/common/models/address.json +++ b/modules/client/back/models/address.json @@ -1,7 +1,12 @@ { "name": "Address", "description": "Client addresses", - "base": "VnModel", + "base": "Loggable", + "log": { + "model": "ClientLog", + "relation": "client", + "showField": "nickname" + }, "options": { "mysql": { "table": "address" @@ -37,9 +42,6 @@ "isActive": { "type": "boolean" }, - "isDefaultAddress": { - "type": "boolean" - }, "longitude": { "type": "Number" }, diff --git a/modules/client/back/models/bank-entity.js b/modules/client/back/models/bank-entity.js new file mode 100644 index 000000000..4cfa7fc91 --- /dev/null +++ b/modules/client/back/models/bank-entity.js @@ -0,0 +1,8 @@ +module.exports = Self => { + Self.validatesPresenceOf('name', { + message: `Name cannot be blank` + }); + Self.validatesPresenceOf('bic', { + message: `Swift / BIC can't be empty` + }); +}; diff --git a/modules/client/back/models/bank-entity.json b/modules/client/back/models/bank-entity.json new file mode 100644 index 000000000..c45cd4336 --- /dev/null +++ b/modules/client/back/models/bank-entity.json @@ -0,0 +1,29 @@ +{ + "name": "BankEntity", + "base": "VnModel", + "options": { + "mysql": { + "table": "bankEntity" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "bic": { + "type": "String" + }, + "name": { + "type": "String" + } + }, + "relations": { + "country": { + "type": "belongsTo", + "model": "Country", + "foreignKey": "countryFk" + } + } +} \ No newline at end of file diff --git a/modules/client/back/models/client-contact.js b/modules/client/back/models/client-contact.js new file mode 100644 index 000000000..db9d72ef6 --- /dev/null +++ b/modules/client/back/models/client-contact.js @@ -0,0 +1,9 @@ +module.exports = Self => { + Self.validatesPresenceOf('name', { + message: 'Name cannot be blank' + }); + + Self.validatesPresenceOf('phone', { + message: 'Phone cannot be blank' + }); +}; diff --git a/modules/client/back/models/client-contact.json b/modules/client/back/models/client-contact.json new file mode 100644 index 000000000..ea916c072 --- /dev/null +++ b/modules/client/back/models/client-contact.json @@ -0,0 +1,36 @@ +{ + "name": "ClientContact", + "description": "Client phone contacts", + "base": "Loggable", + "log": { + "model": "ClientLog", + "relation": "client", + "showField": "name" + }, + "options": { + "mysql": { + "table": "clientContact" + } + }, + "validateUpsert": true, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "name": { + "type": "string" + }, + "phone": { + "type": "string" + } + }, + "relations": { + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "clientFk" + } + } + } \ No newline at end of file diff --git a/services/loopback/common/models/client-credit-limit.json b/modules/client/back/models/client-credit-limit.json similarity index 100% rename from services/loopback/common/models/client-credit-limit.json rename to modules/client/back/models/client-credit-limit.json diff --git a/services/client/common/models/client-credit.json b/modules/client/back/models/client-credit.json similarity index 91% rename from services/client/common/models/client-credit.json rename to modules/client/back/models/client-credit.json index 96ea26829..2b71fbe2d 100644 --- a/services/client/common/models/client-credit.json +++ b/modules/client/back/models/client-credit.json @@ -4,8 +4,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "clientCredit", - "database": "vn" + "table": "clientCredit" } }, "validateUpsert": true, diff --git a/modules/client/back/models/client-dms.js b/modules/client/back/models/client-dms.js new file mode 100644 index 000000000..0cffb042c --- /dev/null +++ b/modules/client/back/models/client-dms.js @@ -0,0 +1,4 @@ +module.exports = Self => { + require('../methods/client-dms/removeFile')(Self); + require('../methods/client-dms/allowedContentTypes')(Self); +}; diff --git a/modules/client/back/models/client-dms.json b/modules/client/back/models/client-dms.json new file mode 100644 index 000000000..28ad21917 --- /dev/null +++ b/modules/client/back/models/client-dms.json @@ -0,0 +1,38 @@ +{ + "name": "ClientDms", + "base": "Loggable", + "log": { + "model":"ClientLog", + "relation": "client", + "showField": "dmsFk" + }, + "options": { + "mysql": { + "table": "clientDms" + } + }, + "properties": { + "dmsFk": { + "type": "Number", + "id": true, + "required": true + }, + "clientFk": { + "type": "Number", + "required": true + } + }, + "relations": { + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "clientFk" + }, + "dms": { + "type": "belongsTo", + "model": "Dms", + "foreignKey": "dmsFk" + } + } +} + diff --git a/modules/client/back/models/client-log.json b/modules/client/back/models/client-log.json new file mode 100644 index 000000000..50c892e85 --- /dev/null +++ b/modules/client/back/models/client-log.json @@ -0,0 +1,58 @@ +{ + "name": "ClientLog", + "base": "VnModel", + "options": { + "mysql": { + "table": "clientLog" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "forceId": false + }, + "originFk": { + "type": "Number", + "required": true + }, + "userFk": { + "type": "Number" + }, + "action": { + "type": "String", + "required": true + }, + "changedModel": { + "type": "String" + }, + "oldInstance": { + "type": "Object" + }, + "newInstance": { + "type": "Object" + }, + "creationDate": { + "type": "Date" + }, + "changedModelId": { + "type": "Number" + }, + "changedModelValue": { + "type": "String" + }, + "description": { + "type": "String" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + } + }, + "scope": { + "order": ["creationDate DESC", "id DESC"] + } +} diff --git a/services/client/common/models/client-observation.js b/modules/client/back/models/client-observation.js similarity index 85% rename from services/client/common/models/client-observation.js rename to modules/client/back/models/client-observation.js index 1ae98fe67..f208cb552 100644 --- a/services/client/common/models/client-observation.js +++ b/modules/client/back/models/client-observation.js @@ -1,5 +1,5 @@ module.exports = function(Self) { - Self.validate('text', isEnabled, {message: 'Se debe rellenar el campo de texto'}); + Self.validate('text', isEnabled, {message: 'Description cannot be blank'}); function isEnabled(err) { if (!this.text) err(); } diff --git a/modules/client/back/models/client-observation.json b/modules/client/back/models/client-observation.json new file mode 100644 index 000000000..a9c7b483a --- /dev/null +++ b/modules/client/back/models/client-observation.json @@ -0,0 +1,58 @@ +{ + "name": "ClientObservation", + "description": "Client notes", + "base": "Loggable", + "log": { + "model": "ClientLog", + "relation": "client" + }, + "options": { + "mysql": { + "table": "clientObservation" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "clientFk": { + "type": "Number" + }, + "text": { + "type": "string", + "description": "Text" + }, + "created": { + "type": "date", + "description": "Creation date and time" + } + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "clientFk" + } + }, + "scope": { + "include": { + "relation": "worker", + "scope": { + "fields": ["userFk"], + "include": { + "relation": "user", + "scope": { + "fields": ["nickname"] + } + } + } + } + } +} diff --git a/modules/client/back/models/client-risk.json b/modules/client/back/models/client-risk.json new file mode 100644 index 000000000..f76483fca --- /dev/null +++ b/modules/client/back/models/client-risk.json @@ -0,0 +1,34 @@ +{ + "name": "ClientRisk", + "base": "VnModel", + "options": { + "mysql": { + "table": "clientRisk" + } + }, + "properties": { + "clientFk": { + "type": "Number", + "id": true + }, + "companyFk": { + "type": "Number", + "id": true + }, + "amount": { + "type": "Number" + } + }, + "relations": { + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "clientFk" + }, + "company": { + "type": "belongsTo", + "model": "Company", + "foreignKey": "companyFk" + } + } + } \ No newline at end of file diff --git a/modules/client/back/models/client-sample.js b/modules/client/back/models/client-sample.js new file mode 100644 index 000000000..c7cda2412 --- /dev/null +++ b/modules/client/back/models/client-sample.js @@ -0,0 +1,59 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.validatesPresenceOf('typeFk', { + message: 'Sample type cannot be blank' + }); + + Self.observe('before save', async function(ctx) { + let models = Self.app.models; + let changes = ctx.data || ctx.instance; + + let sample = await models.Sample.findById(changes.typeFk); + + if (sample.hasCompany && !changes.companyFk) + throw new UserError('Choose a company'); + + const mandateSamples = [ + {sample: 'sepa-core', type: 'CORE'}, + {sample: 'client-lcr', type: 'LCR'} + ]; + + const mandate = mandateSamples.find(mandate => { + return mandate.sample === sample.code; + }); + + // Renew mandate + if (mandate) { + let mandateType = await models.MandateType.findOne({ + where: {name: mandate.type} + }); + + let oldMandate = await models.Mandate.findOne({ + where: { + clientFk: changes.clientFk, + companyFk: changes.companyFk, + mandateTypeFk: mandateType.id, + finished: null + } + }); + + // Disable old mandate + if (oldMandate) + oldMandate.updateAttribute('finished', new Date()); + + // Create a new mandate + await models.Mandate.create({ + clientFk: changes.clientFk, + companyFk: changes.companyFk, + mandateTypeFk: mandateType.id + }); + } + + // Apply workerFk + let filter = {where: {userFk: ctx.options.accessToken.userId}}; + let worker = await Self.app.models.Worker.findOne(filter); + + changes.workerFk = worker.id; + }); +}; diff --git a/modules/client/back/models/client-sample.json b/modules/client/back/models/client-sample.json new file mode 100644 index 000000000..812da8be8 --- /dev/null +++ b/modules/client/back/models/client-sample.json @@ -0,0 +1,51 @@ +{ + "name": "ClientSample", + "base": "Loggable", + "log": { + "model": "ClientLog", + "relation": "client", + "showField": "type" + }, + "options": { + "mysql": { + "table": "clientSample" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "created": { + "type": "date" + } + }, + "relations": { + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "clientFk" + }, + "type": { + "type": "belongsTo", + "model": "Sample", + "foreignKey": "typeFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "account": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + }, + "company": { + "type": "belongsTo", + "model": "Company", + "foreignKey": "companyFk" + } + } +} diff --git a/modules/client/back/models/client-type.json b/modules/client/back/models/client-type.json new file mode 100644 index 000000000..a91cc38b6 --- /dev/null +++ b/modules/client/back/models/client-type.json @@ -0,0 +1,24 @@ +{ + "name": "ClientType", + "base": "VnModel", + "options": { + "mysql": { + "table": "clientType" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true + }, + "code": { + "type": "String" + }, + "type": { + "type": "String" + }, + "isCreatedAsServed": { + "type": "Number" + } + } +} \ No newline at end of file diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js new file mode 100644 index 000000000..73626b408 --- /dev/null +++ b/modules/client/back/models/client.js @@ -0,0 +1,318 @@ +let request = require('request-promise-native'); +let UserError = require('vn-loopback/util/user-error'); +let getFinalState = require('vn-loopback/util/hook').getFinalState; +let isMultiple = require('vn-loopback/util/hook').isMultiple; +const httpParamSerializer = require('vn-loopback/util/http').httpParamSerializer; +const LoopBackContext = require('loopback-context'); + +module.exports = Self => { + // Methods + require('../methods/client/activeWorkersWithRole')(Self); + require('../methods/client/getCard')(Self); + require('../methods/client/createWithUser')(Self); + require('../methods/client/listWorkers')(Self); + require('../methods/client/hasCustomerRole')(Self); + require('../methods/client/isValidClient')(Self); + require('../methods/client/addressesPropagateRe')(Self); + require('../methods/client/getDebt')(Self); + require('../methods/client/getMana')(Self); + require('../methods/client/getAverageInvoiced')(Self); + require('../methods/client/summary')(Self); + require('../methods/client/updateFiscalData')(Self); + require('../methods/client/getTransactions')(Self); + require('../methods/client/confirmTransaction')(Self); + require('../methods/client/canBeInvoiced')(Self); + require('../methods/client/uploadFile')(Self); + require('../methods/client/lastActiveTickets')(Self); + + // Validations + + Self.validatesPresenceOf('street', { + message: 'Street cannot be empty' + }); + + Self.validatesPresenceOf('city', { + message: 'City cannot be empty' + }); + + Self.validatesUniquenessOf('fi', { + message: 'TIN must be unique' + }); + + Self.validatesUniquenessOf('socialName', { + message: 'The company name must be unique' + }); + + Self.validatesFormatOf('email', { + message: 'Invalid email', + allowNull: true, + allowBlank: true, + with: /^[\w|.|-]+@[\w|-]+(\.[\w|-]+)*(,[\w|.|-]+@[\w|-]+(\.[\w|-]+)*)*$/ + }); + + Self.validatesLengthOf('postcode', { + allowNull: true, + allowBlank: true, + min: 3, max: 10 + }); + + Self.validateAsync('iban', ibanNeedsValidation, { + message: 'The IBAN does not have the correct format' + }); + let validateIban = require('../validations/validateIban'); + async function ibanNeedsValidation(err, done) { + let filter = { + fields: ['code'], + where: {id: this.countryFk} + }; + let country = await Self.app.models.Country.findOne(filter); + let code = country ? country.code.toLowerCase() : null; + if (code != 'es') + return done(); + + if (!validateIban(this.iban)) + err(); + done(); + } + + Self.validateAsync('fi', tinIsValid, { + message: 'Invalid TIN' + }); + + let validateTin = require('../validations/validateTin'); + async function tinIsValid(err, done) { + if (!this.isTaxDataChecked) + return done(); + + let filter = { + fields: ['code'], + where: {id: this.countryFk} + }; + let country = await Self.app.models.Country.findOne(filter); + let code = country ? country.code.toLowerCase() : null; + + if (!this.fi || !validateTin(this.fi, code)) + err(); + done(); + } + + Self.validate('payMethod', hasSalesMan, { + message: 'Cannot change the payment method if no salesperson' + }); + + function hasSalesMan(err) { + if (this.payMethod && !this.salesPerson) + err(); + } + + Self.validate('isEqualizated', cannotHaveET, { + message: 'Cannot check Equalization Tax in this NIF/CIF' + }); + + function cannotHaveET(err) { + if (!this.fi) return; + + let tin = this.fi.toUpperCase(); + let cannotHaveET = /^[A-B]/.test(tin); + + if (cannotHaveET && this.isEqualizated) + err(); + } + + Self.validateAsync('payMethodFk', hasIban, { + message: 'That payment method requires an IBAN' + }); + + function hasIban(err, done) { + Self.app.models.PayMethod.findById(this.payMethodFk, (_, instance) => { + if (instance && instance.ibanRequired && !this.iban) + err(); + done(); + }); + } + + Self.validateAsync('bankEntityFk', hasBic, { + message: 'That payment method requires a BIC' + }); + + function hasBic(err, done) { + if (this.iban && !this.bankEntityFk) + err(); + done(); + } + + Self.validateAsync('defaultAddressFk', isActive, + {message: 'Unable to default a disabled consignee'} + ); + + async function isActive(err, done) { + if (!this.defaultAddressFk) + return done(); + + const address = await Self.app.models.Address.findById(this.defaultAddressFk); + if (address && !address.isActive) err(); + done(); + } + + Self.validateAsync('postCode', hasValidPostcode, { + message: `The postcode doesn't exists. Ensure you put the correct format` + }); + + async function hasValidPostcode(err, done) { + if (!this.postcode) + return done(); + + const models = Self.app.models; + const postcode = await models.Postcode.findById(this.postcode); + + if (!postcode) err(); + done(); + } + + function isAlpha(value) { + const regexp = new RegExp(/^[ñça-zA-Z0-9\s]*$/i); + + return regexp.test(value); + } + + Self.observe('before save', async function(ctx) { + let changes = ctx.data || ctx.instance; + let orgData = ctx.currentInstance; + let finalState = getFinalState(ctx); + let payMethodWithIban = 4; + + // Validate socialName format + const socialNameChanged = orgData && changes + && orgData.socialName != changes.socialName; + + if (socialNameChanged && !isAlpha(changes.socialName)) + throw new UserError('The socialName has an invalid format'); + + + if (changes.salesPerson === null) { + changes.credit = 0; + changes.discount = 0; + changes.payMethodFk = 5; // Credit card + } + + let payMethodFk = changes.payMethodFk || (orgData && orgData.payMethodFk); + let dueDay = changes.dueDay || (orgData && orgData.dueDay); + + if (payMethodFk == payMethodWithIban && dueDay == 0) + changes.dueDay = 5; + + if (isMultiple(ctx)) return; + + if (changes.credit !== undefined) { + await validateCreditChange(ctx, finalState); + let filter = {fields: ['id'], where: {userFk: ctx.options.accessToken.userId}}; + let worker = await Self.app.models.Worker.findOne(filter); + + let newCredit = { + amount: changes.credit, + clientFk: finalState.id, + workerFk: worker ? worker.id : null + }; + await Self.app.models.ClientCredit.create(newCredit); + } + }); + + Self.observe('after save', async ctx => { + if (ctx.isNewInstance) return; + + const hookState = ctx.hookState; + const newInstance = hookState.newInstance; + const oldInstance = hookState.oldInstance; + const instance = ctx.instance; + + const payMethodChanged = oldInstance.payMethodFk != newInstance.payMethodFk; + const ibanChanged = oldInstance.iban != newInstance.iban; + const dueDayChanged = oldInstance.dueDay != newInstance.dueDay; + + if (payMethodChanged || ibanChanged || dueDayChanged) { + const message = `La forma de pago del cliente con id ${instance.id} ha cambiado`; + const salesPersonFk = instance.salesPersonFk; + + if (salesPersonFk) { + const salesPerson = await Self.app.models.Worker.findById(salesPersonFk); + await Self.app.models.Message.send(ctx, { + recipientFk: salesPerson.userFk, + message: message + }); + } + + // Send email to client + + if (!instance.email) return; + const loopBackContext = LoopBackContext.getCurrentContext(); + const headers = loopBackContext.active.http.req.headers; + const params = { + clientId: instance.id, + recipient: instance.email + }; + const serializedParams = httpParamSerializer(params); + const query = `${headers.origin}/api/email/payment-update?${serializedParams}`; + await request.get(query); + } + }); + + async function validateCreditChange(ctx, finalState) { + let models = Self.app.models; + let userId = ctx.options.accessToken.userId; + + let currentUserIsManager = await models.Account.hasRole(userId, 'manager'); + if (currentUserIsManager) + return; + + let filter = { + fields: ['roleFk'], + where: { + maxAmount: {gt: ctx.data.credit} + } + }; + + let limits = await models.ClientCreditLimit.find(filter); + + if (limits.length == 0) + throw new UserError('Credit limits not found'); + + // Si el usuario no tiene alguno de los roles no continua + + let requiredRoles = []; + for (limit of limits) + requiredRoles.push(limit.roleFk); + + let where = { + roleId: {inq: requiredRoles}, + principalType: 'USER', + principalId: userId + }; + let count = await models.RoleMapping.count(where); + + if (count <= 0) + throw new UserError('The role cannot set this credit amount'); + + // Si se puso a 0 por gerencia, solo gerencia puede aumentarlo + + let query = 'SELECT * FROM clientCredit WHERE clientFk = ? ORDER BY created DESC LIMIT 1'; + let instances = await Self.rawSql(query, [finalState.id]); + + if (instances.length !== 1 || instances[0].amount > 0) + return; + + query = ` + SELECT COUNT(*) AS hasRoleManager + FROM worker em + JOIN account.user ac ON ac.id = em.userFk + JOIN salix.RoleMapping rm ON rm.principalId = ac.id + JOIN account.role r on r.id = rm.roleId + WHERE em.id = ? + AND rm.principalType = 'USER' + AND r.name = 'manager'`; + + let instance = await Self.rawSql(query, [instances[0].workerFk]); + + if (instance[0].hasRoleManager) + throw new UserError('Only manager can change the credit'); + } +}; diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json new file mode 100644 index 000000000..c62ae3832 --- /dev/null +++ b/modules/client/back/models/client.json @@ -0,0 +1,205 @@ +{ + "name": "Client", + "base": "Loggable", + "log": { + "model":"ClientLog", + "showField": "id" + }, + "options": { + "mysql": { + "table": "client" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "name": { + "type": "string", + "required": true + }, + "fi": { + "type": "string", + "description": "Fiscal indentifier" + }, + "socialName": { + "type": "string", + "required": true + }, + "contact": { + "type": "string" + }, + "street": { + "type": "string", + "required": true + }, + "city": { + "type": "string", + "required": true + }, + "postcode": { + "type": "string" + }, + "email": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "mobile": { + "type": "string" + }, + "isActive": { + "type": "boolean" + }, + "credit": { + "type": "Number" + }, + "creditInsurance": { + "type": "Number" + }, + "iban": { + "type": "string" + }, + "dueDay": { + "type": "Number" + }, + "isEqualizated": { + "type": "boolean", + "description": "The client has equalization tax" + }, + "isFreezed": { + "type": "boolean", + "description": "The client frozen" + }, + "hasToInvoiceByAddress": { + "type": "boolean", + "description": "The client has to be invoiced by address" + }, + "hasToInvoice": { + "type": "boolean", + "description": "Global invoicing enabled for the client" + }, + "isToBeMailed": { + "type": "boolean", + "description": "Send invoices by email" + }, + "hasSepaVnl": { + "type": "boolean" + }, + "hasLcr": { + "type": "boolean" + }, + "hasCoreVnl": { + "type": "boolean" + }, + "hasCoreVnh": { + "type": "boolean" + }, + "isTaxDataChecked":{ + "type": "boolean" + }, + "eypbc": { + "type": "boolean" + }, + "quality": { + "type": "Number" + }, + "isVies": { + "type": "boolean" + }, + "isRelevant": { + "type": "boolean" + }, + "accountingAccount": { + "type": "string" + }, + "created": { + "type": "Date" + } + }, + "relations": { + "account": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "id" + }, + "payMethod": { + "type": "belongsTo", + "model": "PayMethod", + "foreignKey": "payMethodFk" + }, + "salesPerson": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "salesPersonFk" + }, + "province": { + "type": "belongsTo", + "model": "Province", + "foreignKey": "provinceFk" + }, + "country": { + "type": "belongsTo", + "model": "Country", + "foreignKey": "countryFk" + }, + "contactChannel": { + "type": "belongsTo", + "model": "ContactChannel", + "foreignKey": "contactChannelFk" + }, + "type": { + "type": "belongsTo", + "model": "ClientType", + "foreignKey": "clientTypeFk" + }, + "addresses": { + "type": "hasMany", + "model": "Address", + "foreignKey": "clientFk" + }, + "greuge": { + "type": "hasMany", + "model": "Greuge", + "foreignKey": "clientFk" + }, + "classifications": { + "type": "hasMany", + "model": "CreditClassification", + "foreignKey": "client" + }, + "defaultAddress": { + "type": "belongsTo", + "model": "Address", + "foreignKey": "defaultAddressFk" + }, + "contacts": { + "type": "hasMany", + "model": "ClientContact", + "foreignKey": "clientFk" + }, + "bank": { + "type": "belongsTo", + "model": "BankEntity", + "foreignKey": "bankEntityFk" + }, + "defaulters": { + "type": "hasMany", + "model": "Defaulter", + "foreignKey": "clientFk" + }, + "clientRisks": { + "type": "hasMany", + "model": "ClientRisk", + "foreignKey": "clientFk" + }, + "claimsRatio": { + "type": "hasOne", + "model": "ClaimRatio", + "foreignKey": "clientFk" + } + } +} \ No newline at end of file diff --git a/services/loopback/common/models/contact-channel.json b/modules/client/back/models/contact-channel.json similarity index 100% rename from services/loopback/common/models/contact-channel.json rename to modules/client/back/models/contact-channel.json diff --git a/modules/client/back/models/credit-classification.js b/modules/client/back/models/credit-classification.js new file mode 100644 index 000000000..9c3728dce --- /dev/null +++ b/modules/client/back/models/credit-classification.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/credit-classification/createWithInsurance')(Self); +}; diff --git a/services/client/common/models/credit-classification.json b/modules/client/back/models/credit-classification.json similarity index 94% rename from services/client/common/models/credit-classification.json rename to modules/client/back/models/credit-classification.json index 01087314a..2e636af63 100644 --- a/services/client/common/models/credit-classification.json +++ b/modules/client/back/models/credit-classification.json @@ -28,12 +28,12 @@ } }, "relations": { - "client": { + "customer": { "type": "belongsTo", "model": "Client", "foreignKey": "client" }, - "creditInsurance": { + "insurances": { "type": "hasMany", "model": "CreditInsurance", "foreignKey": "creditClassification" diff --git a/modules/client/back/models/credit-insurance.js b/modules/client/back/models/credit-insurance.js new file mode 100644 index 000000000..3310ffb11 --- /dev/null +++ b/modules/client/back/models/credit-insurance.js @@ -0,0 +1,91 @@ +module.exports = function(Self) { + Self.validateCredit = function(credit) { + return credit >= 0; + }; + + Self.validateBinded('credit', Self.validateCredit, { + message: 'The credit must be an integer greater than or equal to zero', + allowNull: false, + allowBlank: false + }); + + Self.validateGrade = function(grade) { + return typeof grade === 'undefined' || grade >= 0; + }; + + Self.validateBinded('grade', Self.validateGrade, { + message: 'The grade must be an integer greater than or equal to zero', + allowNull: true + }); + + async function validateNullGrade(err, done) { + let filter = { + fields: ['grade'], + where: { + creditClassification: this.creditClassification + }, + order: 'created DESC' + }; + let insurance = await Self.findOne(filter); + + if (insurance && (!insurance.grade && this.grade || insurance.grade && !this.grade)) + err(); + + done(); + } + + Self.validateAsync('nullGrade', validateNullGrade, { + message: 'The grade must be similar to the last one' + }); + + Self.messageSend = async function(data, accessToken) { + let filter = { + include: { + relation: 'classification', + scope: { + fields: ['client'], + include: { + relation: 'customer', + scope: { + fields: ['name', 'salesPersonFk'], + include: { + relation: 'salesPerson', + scope: { + fields: 'userFk', + include: { + relation: 'user', + scope: { + fields: ['name'] + } + } + } + } + } + } + } + } + }; + + let ctx = {req: {accessToken: accessToken}}; + let insurance = await Self.findById(data.id, filter); + let customer = insurance.classification().customer(); + + if (!customer.salesPerson()) return; + let salesPersonId = customer.salesPerson().user().id; + let grade = data.grade ? `(Grado ${data.grade})` : '(Sin grado)'; + let params = { + recipientFk: salesPersonId, + message: `He cambiado el crédito asegurado del ` + + `cliente "${customer.name}" a ${data.credit} € ${grade}` + }; + + Self.app.models.Message.send(ctx, params); + }; + + // Update from transaction misses ctx accessToken. + // Fixed passing accessToken from method messageSend() + Self.observe('after save', async function(ctx) { + if (ctx.options.accessToken) + await Self.messageSend(ctx.instance, ctx.options.accessToken); + }); +}; diff --git a/modules/client/back/models/credit-insurance.json b/modules/client/back/models/credit-insurance.json new file mode 100644 index 000000000..688c511fb --- /dev/null +++ b/modules/client/back/models/credit-insurance.json @@ -0,0 +1,36 @@ +{ + "name": "CreditInsurance", + "description": "Credit insurance", + "base": "VnModel", + "options": { + "mysql": { + "table": "creditInsurance" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "credit": { + "type": "Number" + }, + "created": { + "type": "date", + "mysql": { + "columnName": "creationDate" + } + }, + "grade": { + "type": "Number" + } + }, + "relations": { + "classification": { + "type": "belongsTo", + "model": "CreditClassification", + "foreignKey": "creditClassification" + } + } +} \ No newline at end of file diff --git a/modules/client/back/models/defaulter.json b/modules/client/back/models/defaulter.json new file mode 100644 index 000000000..8d50356f1 --- /dev/null +++ b/modules/client/back/models/defaulter.json @@ -0,0 +1,31 @@ +{ + "name": "Defaulter", + "description": "defaulters client", + "base": "VnModel", + "options": { + "mysql": { + "table": "defaulter" + } + }, + "properties": { + "created": { + "type": "Date" + }, + "amount": { + "type": "Number" + }, + "defaulterSinced": { + "type": "Number" + }, + "hasChanged": { + "type": "Number" + } + }, + "relations": { + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "clientFk" + } + } +} \ No newline at end of file diff --git a/services/client/common/models/greuge-type.json b/modules/client/back/models/greuge-type.json similarity index 100% rename from services/client/common/models/greuge-type.json rename to modules/client/back/models/greuge-type.json diff --git a/modules/client/back/models/greuge.js b/modules/client/back/models/greuge.js new file mode 100644 index 000000000..bd5f2865d --- /dev/null +++ b/modules/client/back/models/greuge.js @@ -0,0 +1,8 @@ +module.exports = function(Self) { + require('../methods/greuge/sumAmount')(Self); + + Self.validatesLengthOf('description', { + max: 45, + message: 'Description should have maximum of 45 characters' + }); +}; diff --git a/modules/client/back/models/greuge.json b/modules/client/back/models/greuge.json new file mode 100644 index 000000000..2abc33f7c --- /dev/null +++ b/modules/client/back/models/greuge.json @@ -0,0 +1,57 @@ +{ + "name": "Greuge", + "base": "Loggable", + "log": { + "model": "ClientLog", + "relation": "client", + "showField": "description" + }, + "options": { + "mysql": { + "table": "greuge" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "description": { + "type": "String", + "required": true + }, + "amount": { + "type": "Number", + "required": true + }, + "shipped": { + "type": "date" + }, + "created": { + "type": "date" + }, + "greugeTypeFk": { + "type": "Number", + "required": true + } + + }, + "relations": { + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "clientFk" + }, + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk" + }, + "greugeType": { + "type": "belongsTo", + "model": "GreugeType", + "foreignKey": "greugeTypeFk" + } + } +} \ No newline at end of file diff --git a/services/client/common/models/mandate-type.json b/modules/client/back/models/mandate-type.json similarity index 100% rename from services/client/common/models/mandate-type.json rename to modules/client/back/models/mandate-type.json diff --git a/services/client/common/models/mandate.json b/modules/client/back/models/mandate.json similarity index 100% rename from services/client/common/models/mandate.json rename to modules/client/back/models/mandate.json diff --git a/modules/client/back/models/observation-type.json b/modules/client/back/models/observation-type.json new file mode 100644 index 000000000..64f58d224 --- /dev/null +++ b/modules/client/back/models/observation-type.json @@ -0,0 +1,29 @@ +{ + "name": "ObservationType", + "base": "VnModel", + "options": { + "mysql": { + "table": "observationType" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "description": { + "type": "String", + "required": true + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} + \ No newline at end of file diff --git a/services/loopback/common/models/pay-method.json b/modules/client/back/models/pay-method.json similarity index 100% rename from services/loopback/common/models/pay-method.json rename to modules/client/back/models/pay-method.json diff --git a/modules/client/back/models/receipt.js b/modules/client/back/models/receipt.js new file mode 100644 index 000000000..6cc767e2c --- /dev/null +++ b/modules/client/back/models/receipt.js @@ -0,0 +1,13 @@ +module.exports = function(Self) { + require('../methods/receipt/filter')(Self); + + Self.observe('before save', async function(ctx) { + if (ctx.isNewInstance) { + let token = ctx.options.accessToken; + let userId = token && token.userId; + let worker = await Self.app.models.Worker.findOne({where: {userFk: userId}}); + + ctx.instance.workerFk = worker.id; + } + }); +}; diff --git a/modules/client/back/models/receipt.json b/modules/client/back/models/receipt.json new file mode 100644 index 000000000..c953ae507 --- /dev/null +++ b/modules/client/back/models/receipt.json @@ -0,0 +1,59 @@ +{ + "name": "Receipt", + "base": "VnModel", + "options": { + "mysql": { + "table": "receipt" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "amountPaid": { + "type": "Number" + }, + "amountUnpaid": { + "type": "Number" + }, + "payed": { + "type": "date" + }, + "created": { + "type": "date" + }, + "isConciliate": { + "type": "date" + }, + "description": { + "type": "string", + "mysql": { + "columnName": "invoiceFk" + } + } + }, + "relations": { + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "clientFk" + }, + "company": { + "type": "belongsTo", + "model": "Company", + "foreignKey": "companyFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "bank": { + "type": "belongsTo", + "model": "Bank", + "foreignKey": "bankFk" + } + } +} \ No newline at end of file diff --git a/modules/client/back/models/recovery.js b/modules/client/back/models/recovery.js new file mode 100644 index 000000000..61e86edfc --- /dev/null +++ b/modules/client/back/models/recovery.js @@ -0,0 +1,5 @@ +module.exports = function(Self) { + require('../methods/recovery/hasActiveRecovery')(Self); + + Self.validatesPresenceOf('period', {message: 'Period cannot be blank'}); +}; diff --git a/services/client/common/models/recovery.json b/modules/client/back/models/recovery.json similarity index 86% rename from services/client/common/models/recovery.json rename to modules/client/back/models/recovery.json index ef1bbb0cc..5a26cd842 100644 --- a/services/client/common/models/recovery.json +++ b/modules/client/back/models/recovery.json @@ -1,6 +1,10 @@ { "name": "Recovery", - "base": "VnModel", + "base": "Loggable", + "log": { + "model": "ClientLog", + "relation": "client" + }, "options": { "mysql": { "table": "recovery" diff --git a/modules/client/back/models/sample.json b/modules/client/back/models/sample.json new file mode 100644 index 000000000..8993250f3 --- /dev/null +++ b/modules/client/back/models/sample.json @@ -0,0 +1,41 @@ +{ + "name": "Sample", + "base": "VnModel", + "options": { + "mysql": { + "table": "sample" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "code": { + "type": "String" + }, + "description": { + "type": "String" + }, + "isVisible": { + "type": "Boolean" + }, + "hasCompany": { + "type": "Number" + } + }, + "scopes": { + "visible": { + "where": {"isVisible": true} + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] + } \ No newline at end of file diff --git a/modules/client/back/models/sms-config.json b/modules/client/back/models/sms-config.json new file mode 100644 index 000000000..3134f8674 --- /dev/null +++ b/modules/client/back/models/sms-config.json @@ -0,0 +1,29 @@ +{ + "name": "SmsConfig", + "description": "Sms configuration", + "base": "VnModel", + "options": { + "mysql": { + "table": "smsConfig" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "uri": { + "type": "String" + }, + "user": { + "type": "String" + }, + "password": { + "type": "String" + }, + "title": { + "type": "String" + } + } +} diff --git a/modules/client/back/models/sms.js b/modules/client/back/models/sms.js new file mode 100644 index 000000000..a823d864a --- /dev/null +++ b/modules/client/back/models/sms.js @@ -0,0 +1,4 @@ +module.exports = Self => { + // Methods + require('../methods/sms/send')(Self); +}; diff --git a/modules/client/back/models/sms.json b/modules/client/back/models/sms.json new file mode 100644 index 000000000..aa9737478 --- /dev/null +++ b/modules/client/back/models/sms.json @@ -0,0 +1,55 @@ +{ + "name": "Sms", + "description": "Sms sent to client", + "base": "Loggable", + "log": { + "model":"ClientLog", + "relation": "recipient" + }, + "options": { + "mysql": { + "table": "sms" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "sender": { + "type": "String", + "required": true + }, + "destination": { + "type": "String", + "required": true + }, + "message": { + "type": "String", + "required": true + }, + "statusCode": { + "type": "Number", + "required": true + }, + "status": { + "type": "String" + }, + "created": { + "type": "Date" + } + }, + "relations": { + "sender": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "senderFk" + }, + "recipient": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "destinationFk" + } + } +} diff --git a/modules/client/back/models/specs/address.spec.js b/modules/client/back/models/specs/address.spec.js new file mode 100644 index 000000000..49fb709bf --- /dev/null +++ b/modules/client/back/models/specs/address.spec.js @@ -0,0 +1,55 @@ +const app = require('vn-loopback/server/server'); + +describe('loopback model address', () => { + let createdAddressId; + + afterAll(async done => { + let client = await app.models.Client.findById(101); + + await app.models.Address.destroyById(createdAddressId); + await client.updateAttribute('isEqualizated', false); + + done(); + }); + + describe('observe()', () => { + it('should throw an error when deactivating a consignee if its the default address', async() => { + let error; + let address = await app.models.Address.findById(1); + + await address.updateAttribute('isActive', false) + .catch(e => { + error = e; + + expect(error.message).toEqual('The default consignee can not be unchecked'); + }); + + expect(error).toBeDefined(); + }); + + it('should set isEqualizated to true of a given Client to trigger any new address to have it', async() => { + let client = await app.models.Client.findById(101); + + expect(client.isEqualizated).toBeFalsy(); + + await client.updateAttribute('isEqualizated', true); + + let newAddress = await app.models.Address.create({ + clientFk: 101, + agencyModeFk: 5, + city: 'here', + isActive: true, + mobile: '555555555', + nickname: 'Test address', + phone: '555555555', + postalCode: '46000', + provinceFk: 1, + street: 'Test address' + }); + + expect(newAddress.isEqualizated).toBeTruthy(); + + createdAddressId = newAddress.id; + }); + }); +}); diff --git a/modules/client/back/models/tpv-error.json b/modules/client/back/models/tpv-error.json new file mode 100644 index 000000000..61e2a7156 --- /dev/null +++ b/modules/client/back/models/tpv-error.json @@ -0,0 +1,21 @@ +{ + "name": "TpvError", + "base": "VnModel", + "options": { + "mysql": { + "table": "hedera.tpvError" + } + }, + "properties": { + "code": { + "type": "String", + "id": true, + "description": "Identifier" + }, + "message": { + "type": "string", + "required": true + } + } +} + \ No newline at end of file diff --git a/modules/client/back/models/tpv-merchant.json b/modules/client/back/models/tpv-merchant.json new file mode 100644 index 000000000..db5c937d8 --- /dev/null +++ b/modules/client/back/models/tpv-merchant.json @@ -0,0 +1,32 @@ +{ + "name": "TpvMerchant", + "base": "VnModel", + "options": { + "mysql": { + "table": "hedera.tpvMerchant" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "description": { + "type": "string", + "required": true + }, + "secretKey": { + "type": "string", + "required": true + } + }, + "relations": { + "company": { + "type": "belongsTo", + "model": "Company", + "foreignKey": "companyFk" + } + } +} + \ No newline at end of file diff --git a/modules/client/back/models/tpv-response.json b/modules/client/back/models/tpv-response.json new file mode 100644 index 000000000..d3a382b5f --- /dev/null +++ b/modules/client/back/models/tpv-response.json @@ -0,0 +1,21 @@ +{ + "name": "TpvResponse", + "base": "VnModel", + "options": { + "mysql": { + "table": "hedera.tpvResponse" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "message": { + "type": "string", + "required": true + } + } +} + \ No newline at end of file diff --git a/modules/client/back/models/tpv-transaction.json b/modules/client/back/models/tpv-transaction.json new file mode 100644 index 000000000..011616d98 --- /dev/null +++ b/modules/client/back/models/tpv-transaction.json @@ -0,0 +1,48 @@ +{ + "name": "TpvTransaction", + "base": "VnModel", + "options": { + "mysql": { + "table": "hedera.tpvTransaction" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "merchantFk": { + "type": "Number" + }, + "clientFk": { + "type": "Number" + }, + "receiptFk": { + "type": "Number" + }, + "amount": { + "type": "Number" + }, + "response": { + "type": "Number" + }, + "errorCode": { + "type": "String" + }, + "status": { + "type": "String" + }, + "created": { + "type": "Date" + } + }, + "relations": { + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "clientFk" + } + } +} + \ No newline at end of file diff --git a/modules/client/back/validations/specs/validateIban.spec.js b/modules/client/back/validations/specs/validateIban.spec.js new file mode 100644 index 000000000..a5d08d4c4 --- /dev/null +++ b/modules/client/back/validations/specs/validateIban.spec.js @@ -0,0 +1,21 @@ +const validateIban = require('../validateIban'); + +describe('IBAN validation', () => { + it('should return false for non-IBAN input', () => { + let isValid = validateIban('Pepinillos'); + + expect(isValid).toBeFalsy(); + }); + + it('should return false for invalid spanish IBAN input', () => { + let isValid = validateIban('ES00 9999 0000 9999 0000 9999'); + + expect(isValid).toBeFalsy(); + }); + + it('should return true for valid spanish IBAN', () => { + let isValid = validateIban('ES91 2100 0418 4502 0005 1332'); + + expect(isValid).toBeTruthy(); + }); +}); diff --git a/modules/client/back/validations/specs/validateTin.spec.js b/modules/client/back/validations/specs/validateTin.spec.js new file mode 100644 index 000000000..cd05ef862 --- /dev/null +++ b/modules/client/back/validations/specs/validateTin.spec.js @@ -0,0 +1,81 @@ +const validateDni = require('../validateTin'); + +describe('TIN validation', () => { + it('should return true for any TIN when no country is passed', () => { + let isValid = validateDni('Pepinillos'); + + expect(isValid).toBeTruthy(); + }); + + describe('Spanish', () => { + it('should return true for valid spanish TIN', () => { + let isValid = validateDni('20849756A', 'es'); + + expect(isValid).toBeTruthy(); + }); + + it('should return false for spanish TIN with exceeded digits', () => { + let isValid = validateDni('208497563239A', 'es'); + + expect(isValid).toBeFalsy(); + }); + + it('should return false for spanish TIN with invalid letter', () => { + let isValid = validateDni('20243746E', 'es'); + + expect(isValid).toBeFalsy(); + }); + + it('should return true for valid spanish CIF', () => { + let isValid = validateDni('B97367486', 'es'); + + expect(isValid).toBeTruthy(); + }); + + it('should return false for spanish CIF with invalid letter', () => { + let isValid = validateDni('A97527786', 'es'); + + expect(isValid).toBeFalsy(); + }); + }); + + describe('Italian', () => { + it('should return true for valid italian TIN', () => { + let isValid = validateDni('12345678911', 'it'); + + expect(isValid).toBeTruthy(); + }); + + it('should return false for italian TIN with exceeded digits', () => { + let isValid = validateDni('123456789112', 'it'); + + expect(isValid).toBeFalsy(); + }); + + it('should return false for italian TIN with bad syntax', () => { + let isValid = validateDni('1234567891A', 'it'); + + expect(isValid).toBeFalsy(); + }); + }); + + describe('Portuguese', () => { + it('should return true for valid portuguese TIN', () => { + let isValid = validateDni('123456789', 'pt'); + + expect(isValid).toBeTruthy(); + }); + + it('should return false for portuguese TIN with exceeded digits', () => { + let isValid = validateDni('12345678910', 'pt'); + + expect(isValid).toBeFalsy(); + }); + + it('should return false for portuguese TIN with bad syntax', () => { + let isValid = validateDni('12345678A', 'pt'); + + expect(isValid).toBeFalsy(); + }); + }); +}); diff --git a/modules/client/back/validations/validateIban.js b/modules/client/back/validations/validateIban.js new file mode 100644 index 000000000..3ca09ef95 --- /dev/null +++ b/modules/client/back/validations/validateIban.js @@ -0,0 +1,50 @@ +module.exports = function(iban) { + if (iban == null) return true; + if (typeof iban != 'string') return false; + + iban = iban.toUpperCase(); + iban = trim(iban); + iban = iban.replace(/\s/g, ''); + + if (iban.length != 24) + return false; + + // Se coge las primeras dos letras y se pasan a números + let letter1 = iban.substring(0, 1); + let letter2 = iban.substring(1, 2); + let num1 = getIbanNumber(letter1); + let num2 = getIbanNumber(letter2); + + // Se sustituye las letras por números. + let isbanaux = String(num1) + String(num2) + iban.substring(2); + + // Se mueve los 6 primeros caracteres al final de la cadena. + isbanaux = isbanaux.substring(6) + isbanaux.substring(0, 6); + + // Se calcula el resto, llamando a la función module97, definida más abajo + let resto = module97(isbanaux); + + if (resto == 1) + return true; + + return false; + + function module97(iban) { + let parts = Math.ceil(iban.length / 7); + let remainer = ''; + + for (let i = 1; i <= parts; i++) + remainer = String(parseFloat(remainer + iban.substr((i - 1) * 7, 7)) % 97); + + return remainer; + } + + function getIbanNumber(letra) { + let letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + return letters.search(letra) + 10; + } + + function trim(text) { + return (text || '').replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g, ''); + } +}; diff --git a/modules/client/back/validations/validateTin.js b/modules/client/back/validations/validateTin.js new file mode 100644 index 000000000..23efcb200 --- /dev/null +++ b/modules/client/back/validations/validateTin.js @@ -0,0 +1,69 @@ +module.exports = function(tin, country) { + if (tin == null || country == null) + return true; + if (typeof tin != 'string' || typeof country != 'string') + return false; + + tin = tin.toUpperCase(); + country = country.toLowerCase(); + + let len = tin.length; + + let validators = { + es: { + regExp: /^[A-Z0-9]\d{7}[A-Z0-9]$/, + validate: () => { + let isCif = /[A-W]/.test(tin.charAt(0)); + let lastDigit = tin.charAt(len - 1); + let computedDigit; + + if (isCif) { + let numbers = tin.substring(1, 8) + .split('') + .map(x => parseInt(x)); + + let pairSum = numbers + .filter((_, i) => i % 2 != 0) + .reduce((a, x) => a + x); + + let oddSum = numbers + .filter((_, i) => i % 2 == 0) + .map(x => x * 2) + .join('') + .split('') + .map(x => parseInt(x)) + .reduce((a, x) => a + x); + + let sum = (pairSum + oddSum).toString(); + let units = parseInt(sum.charAt(sum.length - 1)); + let control = units == 0 ? 0 : 10 - units; + let isLetter = /^[A-Z]$/.test(lastDigit); + computedDigit = isLetter ? 'JABCDEFGHI'.charAt(control) : control.toString(); + } else { + // Foreign NIF + let index = 'XYZ'.indexOf(tin.charAt(0)); + let nif = index == -1 ? tin : index.toString() + tin.substring(1); + + let rest = parseInt(nif.substring(0, 8)) % 23; + computedDigit = 'TRWAGMYFPDXBNJZSQVHLCKE'.charAt(rest); + } + + return computedDigit == lastDigit; + } + }, + it: { + regExp: /^(\d{11}|[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z])$/ + }, + pt: { + regExp: /^\d{9}$/ + } + }; + + let validator = validators[country]; + + if (!validator) + return true; + + return validator.regExp.test(tin) + && (!validator.validate || validator.validate()); +}; diff --git a/modules/client/front/address/create/index.html b/modules/client/front/address/create/index.html new file mode 100644 index 000000000..43f6e3589 --- /dev/null +++ b/modules/client/front/address/create/index.html @@ -0,0 +1,132 @@ + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + diff --git a/modules/client/front/address/create/index.js b/modules/client/front/address/create/index.js new file mode 100644 index 000000000..3cd8af614 --- /dev/null +++ b/modules/client/front/address/create/index.js @@ -0,0 +1,55 @@ +import ngModule from '../../module'; + +export default class Controller { + constructor($, $state) { + this.$ = $; + this.$state = $state; + this.data = { + address: { + clientFk: parseInt($state.params.id), + isActive: true + }, + isDefaultAddress: false + }; + this.address = this.data.address; + } + + get postcodeSelection() { + return this._postcodeSelection; + } + + set postcodeSelection(selection) { + this._postcodeSelection = selection; + + if (!selection) return; + + const town = selection.town; + const province = town.province; + + this.address.city = town.name; + this.address.provinceFk = province.id; + } + + onResponse(response) { + this.address.postalCode = response.code; + } + + onSubmit() { + this.$.watcher.submit().then(res => { + if (res.data && this.data.isDefaultAddress) + this.client.defaultAddressFk = res.data.id; + + this.$state.go('client.card.address.index'); + }); + } +} + +Controller.$inject = ['$scope', '$state']; + +ngModule.component('vnClientAddressCreate', { + template: require('./index.html'), + controller: Controller, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/address/create/index.spec.js b/modules/client/front/address/create/index.spec.js new file mode 100644 index 000000000..e840ec2d8 --- /dev/null +++ b/modules/client/front/address/create/index.spec.js @@ -0,0 +1,77 @@ +import './index'; +import watcher from 'core/mocks/watcher'; + +describe('Client', () => { + describe('Component vnClientAddressCreate', () => { + let controller; + let $componentController; + let $state; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject((_$componentController_, _$state_) => { + $componentController = _$componentController_; + $state = _$state_; + $state.params.id = '1234'; + controller = $componentController('vnClientAddressCreate', {$state}); + controller.$.watcher = watcher; + controller.$.watcher.submit = () => { + return { + then: callback => { + callback({data: {id: 124}}); + } + }; + }; + controller.client = {id: 101, defaultAddressFk: 121}; + })); + + it('should define and set address property', () => { + expect(controller.data.address.clientFk).toBe(1234); + expect(controller.data.address.isActive).toBe(true); + }); + + describe('onSubmit()', () => { + it('should perform a PATCH and not set value to defaultAddressFk property', () => { + spyOn(controller.$state, 'go'); + controller.data.isDefaultAddress = false; + controller.onSubmit(); + + expect(controller.client.defaultAddressFk).toEqual(121); + expect(controller.$state.go).toHaveBeenCalledWith('client.card.address.index'); + }); + + it('should perform a PATCH and set a value to defaultAddressFk property', () => { + spyOn(controller.$state, 'go'); + controller.data.isDefaultAddress = true; + controller.onSubmit(); + + expect(controller.client.defaultAddressFk).toEqual(124); + expect(controller.$state.go).toHaveBeenCalledWith('client.card.address.index'); + }); + }); + + describe('postcodeSelection() setter', () => { + it(`should set the town, province and contry properties`, () => { + controller.postcodeSelection = { + townFk: 1, + code: 46001, + town: { + id: 1, + name: 'New York', + province: { + id: 1, + name: 'New york', + country: { + id: 2, + name: 'USA' + } + } + } + }; + + expect(controller.address.city).toEqual('New York'); + expect(controller.address.provinceFk).toEqual(1); + }); + }); + }); +}); diff --git a/client/client/src/address-create/locale/es.yml b/modules/client/front/address/create/locale/es.yml similarity index 100% rename from client/client/src/address-create/locale/es.yml rename to modules/client/front/address/create/locale/es.yml diff --git a/modules/client/front/address/edit/index.html b/modules/client/front/address/edit/index.html new file mode 100644 index 000000000..ed3758e33 --- /dev/null +++ b/modules/client/front/address/edit/index.html @@ -0,0 +1,180 @@ + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Notes +
    + + + + + + + + + + + + +
    +
    + + + + +
    + + + + + diff --git a/modules/client/front/address/edit/index.js b/modules/client/front/address/edit/index.js new file mode 100644 index 000000000..7c7b274a6 --- /dev/null +++ b/modules/client/front/address/edit/index.js @@ -0,0 +1,46 @@ +import ngModule from '../../module'; + +export default class Controller { + constructor($scope, $state) { + this.$ = $scope; + this.$state = $state; + this.$stateParams = $state.params; + } + + removeObservation(index) { + this.$.watcher.setDirty(); + this.$.model.remove(index); + } + + cancel() { + this.goToIndex(); + } + + goToIndex() { + this.$state.go('client.card.address.index'); + } + + onResponse(response) { + this.address.postalCode = response.code; + } + + onSubmit() { + this.$.watcher.check(); + this.$.watcher.realSubmit() + .then(() => this.$.model.save(true)) + .then(() => { + this.$.watcher.notifySaved(); + this.card.reload(); + this.goToIndex(); + }); + } +} +Controller.$inject = ['$scope', '$state']; + +ngModule.component('vnClientAddressEdit', { + template: require('./index.html'), + controller: Controller, + require: { + card: '^vnClientCard' + } +}); diff --git a/modules/client/front/address/edit/index.spec.js b/modules/client/front/address/edit/index.spec.js new file mode 100644 index 000000000..aa1f59669 --- /dev/null +++ b/modules/client/front/address/edit/index.spec.js @@ -0,0 +1,59 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientAddressEdit', () => { + let $state; + let controller; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, _$state_) => { + $state = _$state_; + $state.params.addressId = '1'; + controller = $componentController('vnClientAddressEdit', {$state}); + controller.$.watcher = { + setDirty: () => {}, + setPristine: () => {}, + realSubmit: () => {}, + check: () => {}, + notifySaved: () => {} + }; + controller.$.model = { + remove: () => {}, + save: () => {} + }; + controller.card = { + reload: () => {} + }; + })); + + describe('removeObservation()', () => { + it('should call $.watcher.setDirty() and $.model.remove(index)', () => { + spyOn(controller.$.watcher, 'setDirty'); + spyOn(controller.$.model, 'remove'); + controller.removeObservation(1); + + expect(controller.$.model.remove).toHaveBeenCalledWith(1); + expect(controller.$.watcher.setDirty).toHaveBeenCalledWith(); + }); + }); + + describe('cancel()', () => { + it('should call goToIndex()', () => { + spyOn(controller, 'goToIndex'); + controller.cancel(); + + expect(controller.goToIndex).toHaveBeenCalledWith(); + }); + }); + + describe('goToIndex()', () => { + it('should call $state.go("client.card.address.index")', () => { + spyOn(controller.$state, 'go'); + controller.goToIndex(); + + expect(controller.$state.go).toHaveBeenCalledWith('client.card.address.index'); + }); + }); + }); +}); diff --git a/modules/client/front/address/edit/locale/es.yml b/modules/client/front/address/edit/locale/es.yml new file mode 100644 index 000000000..f1aa52834 --- /dev/null +++ b/modules/client/front/address/edit/locale/es.yml @@ -0,0 +1,7 @@ +Enabled: Activo +Is equalizated: Recargo de equivalencia +Observation type: Tipo de observación +Description: Descripción +The observation type must be unique: El tipo de observación ha de ser único +Remove note: Quitar nota +Add note: Añadir nota \ No newline at end of file diff --git a/modules/client/front/address/index/index.html b/modules/client/front/address/index/index.html new file mode 100644 index 000000000..c78f51748 --- /dev/null +++ b/modules/client/front/address/index/index.html @@ -0,0 +1,72 @@ + + + + + + + + + diff --git a/modules/client/front/address/index/index.js b/modules/client/front/address/index/index.js new file mode 100644 index 000000000..5ba2ad063 --- /dev/null +++ b/modules/client/front/address/index/index.js @@ -0,0 +1,80 @@ +import ngModule from '../../module'; +import './style.scss'; + +class Controller { + constructor($http, $scope, $stateParams) { + this.$http = $http; + this.$scope = $scope; + this.$stateParams = $stateParams; + this.filter = { + fields: [ + 'id', + 'isDefaultAddress', + 'isActive', + 'nickname', + 'street', + 'city', + 'provinceFk', + 'phone', + 'mobile', + 'isEqualizated' + ], + order: [ + 'isDefaultAddress DESC', + 'isActive DESC', + 'nickname ASC'], + include: [ + { + relation: 'observations', + scope: { + include: 'observationType' + } + }, { + relation: 'province', + scope: { + fields: ['id', 'name'] + } + } + ] + }; + } + + onStarClick(event) { + event.stopPropagation(); + event.preventDefault(); + } + + setDefault(address) { + let query = `Clients/${this.$stateParams.id}`; + let params = {defaultAddressFk: address.id}; + this.$http.patch(query, params).then(res => { + if (res.data) { + this.client.defaultAddressFk = res.data.defaultAddressFk; + this.sortAddresses(); + } + }); + } + + isDefaultAddress(address) { + return this.client && this.client.defaultAddressFk === address.id; + } + + /** + * Sort address by default address + */ + sortAddresses() { + if (!this.client || !this.addresses) return; + this.addresses = this.addresses.sort((a, b) => { + return this.isDefaultAddress(b) - this.isDefaultAddress(a); + }); + } +} +Controller.$inject = ['$http', '$scope', '$stateParams']; + +ngModule.component('vnClientAddressIndex', { + template: require('./index.html'), + controller: Controller, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/address/index/index.spec.js b/modules/client/front/address/index/index.spec.js new file mode 100644 index 000000000..61495e7a3 --- /dev/null +++ b/modules/client/front/address/index/index.spec.js @@ -0,0 +1,70 @@ +import './index'; +import crudModel from 'core/mocks/crud-model'; + +describe('Client', () => { + describe('Component vnClientAddressIndex', () => { + let controller; + let $scope; + let $stateParams; + let $httpBackend; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$stateParams_, _$httpBackend_) => { + $stateParams = _$stateParams_; + $stateParams.id = 1; + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + controller = $componentController('vnClientAddressIndex', {$stateParams, $scope}); + controller.client = {id: 101, defaultAddressFk: 121}; + controller.$scope.model = crudModel; + })); + + describe('setDefault()', () => { + it('should perform a PATCH and set a value to defaultAddressFk property', () => { + spyOn(controller, 'sortAddresses'); + let address = {id: 1}; + let data = {defaultAddressFk: address.id}; + let expectedResult = {defaultAddressFk: address.id}; + + $httpBackend.when('PATCH', `Clients/1`, data).respond(200, expectedResult); + $httpBackend.expect('PATCH', `Clients/1`, data); + controller.setDefault(address); + $httpBackend.flush(); + + expect(controller.client.defaultAddressFk).toEqual(1); + expect(controller.sortAddresses).toHaveBeenCalledWith(); + }); + }); + + describe('isDefaultAddress()', () => { + it('should return true if a passed address is the current default one', () => { + let address = {id: 121}; + let result = controller.isDefaultAddress(address); + + expect(result).toBeTruthy(); + }); + + it('should return false if a passed address is the current default one', () => { + let address = {id: 1}; + let result = controller.isDefaultAddress(address); + + expect(result).toBeFalsy(); + }); + }); + + describe('sortAddresses()', () => { + it('should return an array of addresses sorted by client defaultAddressFk', () => { + controller.client.defaultAddressFk = 123; + controller.addresses = [ + {id: 121, nickname: 'My address one'}, + {id: 122, nickname: 'My address two'}, + {id: 123, nickname: 'My address three'}]; + + controller.sortAddresses(); + + expect(controller.addresses[0].id).toEqual(123); + }); + }); + }); +}); diff --git a/client/client/src/addresses/locale/es.yml b/modules/client/front/address/index/locale/es.yml similarity index 100% rename from client/client/src/addresses/locale/es.yml rename to modules/client/front/address/index/locale/es.yml diff --git a/modules/client/front/address/index/style.scss b/modules/client/front/address/index/style.scss new file mode 100644 index 000000000..27bd8c40e --- /dev/null +++ b/modules/client/front/address/index/style.scss @@ -0,0 +1,21 @@ +@import "variables"; +@import "./effects"; + +vn-client-address-index { + .address { + padding-bottom: $spacing-md; + + &:last-child { + padding-bottom: 0; + } + & > a { + @extend %clickable; + box-sizing: border-box; + display: flex; + align-items: center; + width: 100%; + color: inherit; + overflow: hidden; + } + } +} \ No newline at end of file diff --git a/modules/client/front/balance/create/index.html b/modules/client/front/balance/create/index.html new file mode 100644 index 000000000..36f45653f --- /dev/null +++ b/modules/client/front/balance/create/index.html @@ -0,0 +1,47 @@ + + + + +
    New payment
    +
    +
    + + + + + + + + + + + + +
    + + + + +
    +
    \ No newline at end of file diff --git a/modules/client/front/balance/create/index.js b/modules/client/front/balance/create/index.js new file mode 100644 index 000000000..a480fac72 --- /dev/null +++ b/modules/client/front/balance/create/index.js @@ -0,0 +1,103 @@ +import ngModule from '../../module'; +import './style.scss'; + +class Controller { + constructor($scope, $state, $http, vnApp, $translate, vnConfig) { + this.$http = $http; + this.$ = $scope; + this.$state = $state; + this.vnApp = vnApp; + this.$translate = $translate; + + this.receipt = { + payed: new Date(), + clientFk: this.$state.params.id, + companyFk: vnConfig.companyFk, + bankFk: vnConfig.bankFk + }; + } + + set payed(value) { + this.receipt.payed = value; + } + + set bankFk(value) { + this.receipt.bankFk = value; + } + + set amountPaid(value) { + this.receipt.amountPaid = value; + } + + get amountPaid() { + return this.receipt.amountPaid; + } + + set clientFk(value) { + this.receipt.clientFk = value; + } + + get clientFk() { + return this.receipt.clientFk; + } + + set companyFk(value) { + this.receipt.companyFk = value; + this.getAmountPaid(); + } + + set description(value) { + this.receipt.description = value; + } + + get description() { + return this.receipt.description; + } + + getAmountPaid() { + let filter = { + where: { + clientFk: this.$state.params.id, + companyFk: this.receipt.companyFk + } + }; + + let query = `ClientRisks?filter=${JSON.stringify(filter)}`; + this.$http.get(query).then(res => { + this.receipt.amountPaid = (res.data.length && res.data[0].amount) || null; + }); + } + + show() { + this.$.dialog.show(); + } + + hide() { + this.$.dialog.hide(); + } + + save() { + let query = `receipts`; + this.$http.post(query, this.receipt).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.hide(); + if (this.onResponse) + this.onResponse(); + }); + } +} +Controller.$inject = ['$scope', '$state', '$http', 'vnApp', '$translate', 'vnConfig']; + +ngModule.component('vnClientBalanceCreate', { + template: require('./index.html'), + controller: Controller, + bindings: { + payed: ' + + + +
    + + + + + + + + +
    +
    Total by company
    + + + + +
    +
    +
    +
    + + + + + + Date + Creation date + Employee + Reference + Bank + Debit + Havings + Balance + Conciliated + + + + + + + + {{::balance.payed | date:'dd/MM/yyyy'}} + + + + + {{::balance.created | date:'dd/MM/yyyy HH:mm'}} + + + + + {{::balance.userNickname}} + + + + + {{balance.isInvoice ? 'BILL' : balance.ref | translate: {ref: balance.ref} }} + + + {{::balance.bankFk}} + {{::balance.debit | currency: 'EUR':2}} + {{::balance.credit | currency: 'EUR':2}} + {{balance.balance | currency: 'EUR':2}} + + + + + + + + + + + + + + + +
    + + + + + + + + \ No newline at end of file diff --git a/modules/client/front/balance/index/index.js b/modules/client/front/balance/index/index.js new file mode 100644 index 000000000..782b5f121 --- /dev/null +++ b/modules/client/front/balance/index/index.js @@ -0,0 +1,131 @@ +import ngModule from '../../module'; +import './style.scss'; + +class Controller { + constructor($stateParams, $translate, $scope, vnToken, $http, vnConfig) { + this.$http = $http; + this.$ = $scope; + this.$stateParams = $stateParams; + this.$translate = $translate; + + this.accessToken = vnToken.token; + this.vnConfig = vnConfig; + this.filter = { + include: { + relation: 'company', + scope: { + fields: ['code'], + }, + }, + where: { + clientFk: $stateParams.id, + companyFk: this.companyFk + }, + }; + this.params = { + params: { + clientFk: this.$stateParams.id, + companyFk: this.companyFk, + }, + }; + } + + get companyFk() { + if (!this._companyFk) + return this.vnConfig.companyFk; + + return this._companyFk; + } + + set companyFk(id) { + this._companyFk = id; + } + setOrder(value) { + this.params.params.companyFk = value; + this.filter.where.companyFk = value; + this.refresh(); + } + + refresh() { + this.$.model.refresh(); + this.$.riskModel.refresh(); + } + + set balances(value) { + this._balances = value; + + if (!value) return; + const params = {filter: this.filter}; + this.$http.get(`ClientRisks`, {params}).then(response => { + if (response.data) { + this.clientRisks = response.data; + + this.getBalances(); + } + }); + } + + get balances() { + return this._balances; + } + + getCurrentBalance() { + const selectedCompany = this.$.company.selection; + const currentBalance = this.clientRisks.find(balance => { + return balance.companyFk === selectedCompany.id; + }); + + return currentBalance.amount; + } + + getBalances() { + this.balances.forEach((balance, index) => { + if (index === 0) + balance.balance = this.getCurrentBalance(); + if (index > 0) { + let previousBalance = this.balances[index - 1]; + + balance.balance = previousBalance.balance - (previousBalance.debit - previousBalance.credit); + } + }); + } + + + openCreateDialog() { + this.$.balanceCreateDialog.companyFk = this.companyFk; + this.$.balanceCreateDialog.onResponse = () => { + this.refresh(); + }; + this.$.balanceCreateDialog.show(); + } + + showWorkerDescriptor(event, workerFk) { + if (event.defaultPrevented) return; + + event.preventDefault(); + event.stopPropagation(); + + this.selectedWorker = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } + + showInvoiceOutDescriptor(event, balance) { + if (!balance.isInvoice) return; + if (event.defaultPrevented) return; + + event.preventDefault(); + event.stopPropagation(); + + this.selectedInvoiceOut = balance.id; + this.$.invoiceOutDescriptor.parent = event.target; + this.$.invoiceOutDescriptor.show(); + } +} + +Controller.$inject = ['$stateParams', '$translate', '$scope', 'vnToken', '$http', 'vnConfig']; + +ngModule.component('vnClientBalanceIndex', { + template: require('./index.html'), + controller: Controller, +}); diff --git a/modules/client/front/balance/index/index.spec.js b/modules/client/front/balance/index/index.spec.js new file mode 100644 index 000000000..6de7bb3cb --- /dev/null +++ b/modules/client/front/balance/index/index.spec.js @@ -0,0 +1,44 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientBalanceIndex', () => { + let $componentController; + let $scope; + let $httpBackend; + let $httpParamSerializer; + let controller; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_, _$httpParamSerializer_) => { + $componentController = _$componentController_; + $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; + $scope = $rootScope.$new(); + controller = $componentController('vnClientBalanceIndex', {$scope}); + })); + + describe('balances() setter', () => { + it('should calculate the balance for each line from the oldest date to the newest', () => { + controller.getCurrentBalance = jasmine.createSpy(controller, 'getCurrentBalance').and.returnValue(1000); + let balances = [ + {credit: -100, debit: 0}, + {credit: 0, debit: 300}, + {credit: 100, debit: 0}, + {credit: 0, debit: -300} + ]; + const params = {filter: controller.filter}; + let serializedParams = $httpParamSerializer(params); + $httpBackend.when('GET', `ClientRisks?${serializedParams}`).respond(balances); + $httpBackend.expect('GET', `ClientRisks?${serializedParams}`); + controller.balances = balances; + $httpBackend.flush(); + + expect(controller.balances[0].balance).toEqual(1000); + expect(controller.balances[1].balance).toEqual(900); + expect(controller.balances[2].balance).toEqual(600); + expect(controller.balances[3].balance).toEqual(700); + }); + }); + }); +}); diff --git a/modules/client/front/balance/index/locale/es.yml b/modules/client/front/balance/index/locale/es.yml new file mode 100644 index 000000000..05ef7070a --- /dev/null +++ b/modules/client/front/balance/index/locale/es.yml @@ -0,0 +1,11 @@ +Creation date: Fecha de creación +Reference: Referencia +Bank: Caja +Debit: Debe +Conciliated: Conciliado +New payment: Añadir pago +Havings: Haber +Balance: Balance +Total by company: Total por empresa +Download PDF: Descargar PDF +BILL: N/FRA {{ref}} \ No newline at end of file diff --git a/modules/client/front/balance/index/style.scss b/modules/client/front/balance/index/style.scss new file mode 100644 index 000000000..74d3bc09b --- /dev/null +++ b/modules/client/front/balance/index/style.scss @@ -0,0 +1,10 @@ + +@import "./variables"; + +vn-client-balance-index { + .totalBox { + border: $border-thin-light; + text-align: left; + float: right + } +} \ No newline at end of file diff --git a/modules/client/front/basic-data/index.html b/modules/client/front/basic-data/index.html new file mode 100644 index 000000000..8c00f7a18 --- /dev/null +++ b/modules/client/front/basic-data/index.html @@ -0,0 +1,72 @@ + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/modules/client/front/basic-data/index.js b/modules/client/front/basic-data/index.js new file mode 100644 index 000000000..093ef4bec --- /dev/null +++ b/modules/client/front/basic-data/index.js @@ -0,0 +1,8 @@ +import ngModule from '../module'; + +ngModule.component('vnClientBasicData', { + template: require('./index.html'), + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/basic-data/locale/es.yml b/modules/client/front/basic-data/locale/es.yml new file mode 100644 index 000000000..139d86d7d --- /dev/null +++ b/modules/client/front/basic-data/locale/es.yml @@ -0,0 +1,15 @@ +Comercial Name: Nombre comercial +Tax number: NIF/CIF +Social name: Razón social +Phone: Teléfono +Mobile: Móvil +Fax: Fax +Email: E-mail +Salesperson: Comercial +Channel: Canal +You can save multiple emails: >- + Puede guardar varios correos electrónicos encadenándolos mediante comas + sin espacios, ejemplo: user@dominio.com, user2@dominio.com siendo el primer + correo electrónico el principal +Contact: Contacto +Undo changes: Deshacer cambios \ No newline at end of file diff --git a/modules/client/front/billing-data/index.html b/modules/client/front/billing-data/index.html new file mode 100644 index 000000000..891c9364f --- /dev/null +++ b/modules/client/front/billing-data/index.html @@ -0,0 +1,146 @@ + + + +
    + + + + + + + + + + + + + + {{bic}} + +
    {{name}}
    +
    +
    +
    + + + + +
    +
    + + + + + + + + +
    + + + + +
    + + + + +
    New bank entity
    + + + + + + + + + + + + + + + + +
    + + + + +
    \ No newline at end of file diff --git a/modules/client/front/billing-data/index.js b/modules/client/front/billing-data/index.js new file mode 100644 index 000000000..589c4f528 --- /dev/null +++ b/modules/client/front/billing-data/index.js @@ -0,0 +1,86 @@ +import ngModule from '../module'; +import Section from 'salix/components/section'; + +export default class Controller extends Section { + get client() { + return this._client; + } + + set client(value) { + this._client = value; + + if (!value) return; + + if (!value.bankEntityFk) + this.autofillBic(); + } + + onSubmit() { + let shouldNotify = false; + + if (this.hasPaymethodChanges()) + shouldNotify = true; + + this.$.watcher.submit().then(() => { + if (shouldNotify) + this.vnApp.showMessage(this.$t('Notification sent!')); + }); + } + + hasPaymethodChanges() { + let orgData = this.$.watcher.orgData; + + let payMethod = orgData.payMethodFk != this.client.payMethodFk; + let iban = orgData.iban != this.client.iban; + let dueDay = orgData.dueDay != this.client.dueDay; + + return payMethod || iban || dueDay; + } + + onAddEntityClick(event) { + event.preventDefault(); + this.newBankEntity = { + countryFk: Number.parseInt(this.client.countryFk) + }; + this.$.bankEntityDialog.show(); + } + + onBankEntityAccept() { + return this.$http.post(`BankEntities`, this.newBankEntity) + .then(res => this.client.bankEntityFk = res.data.id); + } + + get ibanCountry() { + if (!this.client || !this.client.iban) return false; + + let countryCode = this.client.iban.substr(0, 2); + + return countryCode; + } + + autofillBic() { + if (!this.client || !this.client.iban) return; + + let bankEntityId = parseInt(this.client.iban.substr(4, 4)); + let filter = {where: {id: bankEntityId}}; + + if (this.ibanCountry != 'ES') return; + + this.$http.get(`BankEntities`, {filter}).then(response => { + const hasData = response.data && response.data[0]; + + if (hasData) + this.client.bankEntityFk = response.data[0].id; + else if (!hasData) + this.client.bankEntityFk = null; + }); + } +} + +ngModule.component('vnClientBillingData', { + template: require('./index.html'), + controller: Controller, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/billing-data/index.spec.js b/modules/client/front/billing-data/index.spec.js new file mode 100644 index 000000000..ade8b2fff --- /dev/null +++ b/modules/client/front/billing-data/index.spec.js @@ -0,0 +1,102 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientBillingData', () => { + let $httpBackend; + let $scope; + let controller; + let vnApp; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_, _vnApp_) => { + let $element = angular.element(''); + $httpBackend = _$httpBackend_; + vnApp = _vnApp_; + $scope = $rootScope.$new(); + $scope.watcher = {}; + spyOn(vnApp, 'showError'); + controller = $componentController('vnClientBillingData', {$element, $scope}); + controller.client = {id: 101, name: 'Client name', payMethodFk: 4}; + $scope.watcher.orgData = {id: 101, name: 'Client name', payMethodFk: 4}; + })); + + describe('hasPaymethodChanges()', () => { + it(`should return true if there are changes on payMethod data`, () => { + controller.client.payMethodFk = 5; + + expect(controller.hasPaymethodChanges()).toBeTruthy(); + }); + + it(`should return false if there are no changes on payMethod data`, () => { + controller.client.payMethodFk = 4; + + expect(controller.hasPaymethodChanges()).toBeFalsy(); + }); + }); + + describe('onBankEntityAccept()', () => { + it('should request to create a new bank entity', () => { + let newBankEntity = { + name: 'My new bank entity', + bic: 'ES123', + countryFk: 1, + id: 999 + }; + controller.newBankEntity = newBankEntity; + $httpBackend.expectPOST('BankEntities', newBankEntity).respond({id: 999}); + controller.onBankEntityAccept(); + $httpBackend.flush(); + + expect(controller.client.bankEntityFk).toEqual(newBankEntity.id); + }); + }); + + describe('autofillBic()', () => { + it(`Should do nothing if there is not client`, () => { + controller.client = undefined; + + controller.autofillBic(); + + expect(controller.client).toBeUndefined(); + }); + + it(`Should do nothing if the iban is not spanish`, () => { + controller.client.iban = 'FR9121000418450200051332'; + + controller.autofillBic(); + + expect(controller.client.bankEntityFk).toBeUndefined(); + }); + + it(`Should set the bankEntityId in the client`, () => { + controller.client.iban = 'ES9121000418450200051332'; + + $httpBackend.whenRoute('GET', `BankEntities`).respond([{id: 123}]); + controller.autofillBic(); + $httpBackend.flush(); + + expect(controller.client.bankEntityFk).toEqual(123); + }); + + it(`Should set clients bankEntityFk to null if no bank entity founds`, () => { + controller.client.iban = 'ES9121000418450200051332'; + + $httpBackend.whenRoute('GET', `BankEntities`).respond([]); + controller.autofillBic(); + $httpBackend.flush(); + + expect(controller.client.bankEntityFk).toBeNull(); + }); + }); + + describe('ibanCountry()', () => { + it('should return a country code from iban', () => { + controller.client.iban = 'ES123'; + let countryCode = controller.ibanCountry; + + expect(countryCode).toEqual('ES'); + }); + }); + }); +}); diff --git a/modules/client/front/billing-data/locale/en.yml b/modules/client/front/billing-data/locale/en.yml new file mode 100644 index 000000000..20177159b --- /dev/null +++ b/modules/client/front/billing-data/locale/en.yml @@ -0,0 +1,14 @@ +Changed terms: Payment terms have changed +Notify customer?: Do you want to notify customer? +No: No +Yes, notify: Yes, notify +Notification sent!: Notification sent! +Notification error: Error while sending notification +Yes, propagate: Yes, propagate +Equivalent tax spreaded: Equivalent tax spreaded +Invoice by address: Invoice by address +Equalization tax: Equalization tax +Due day: Due day +Received core VNL: VNL core received +Received B2B VNL: VNL B2B received +Save: Save \ No newline at end of file diff --git a/modules/client/front/billing-data/locale/es.yml b/modules/client/front/billing-data/locale/es.yml new file mode 100644 index 000000000..a7ecbbdae --- /dev/null +++ b/modules/client/front/billing-data/locale/es.yml @@ -0,0 +1,18 @@ +Changed terms: Has modificado las condiciones de pago +Notify customer?: ¿Deseas notificar al cliente de dichos cambios? +No: No +Yes, notify: Sí, notificar +Notification sent!: ¡Notificación enviada! +Notification error: Error al enviar notificación +Yes, propagate: Si, propagar +Equivalent tax spreaded: Recargo de equivalencia propagado +Invoice by address: Facturar por consignatario +Equalization tax: Recargo de equivalencia +Due day: Vencimiento +Received LCR: Recibido LCR +Received core VNL: Recibido core VNL +Received B2B VNL: Recibido B2B VNL +Save: Guardar +New bank entity: Nueva entidad bancaria +Name can't be empty: El nombre no puede quedar vacío +Entity Code: Código \ No newline at end of file diff --git a/modules/client/front/card/index.html b/modules/client/front/card/index.html new file mode 100644 index 000000000..b4fe95820 --- /dev/null +++ b/modules/client/front/card/index.html @@ -0,0 +1,5 @@ + + + + + diff --git a/modules/client/front/card/index.js b/modules/client/front/card/index.js new file mode 100644 index 000000000..5aacc83ea --- /dev/null +++ b/modules/client/front/card/index.js @@ -0,0 +1,15 @@ +import ngModule from '../module'; +import ModuleCard from 'salix/components/module-card'; + +export default class Controller extends ModuleCard { + reload() { + this.$http.get(`Clients/${this.$params.id}/getCard`) + .then(res => this.client = res.data); + } +} + +ngModule.component('vnClientCard', { + template: require('./index.html'), + controller: Controller +}); + diff --git a/modules/client/front/card/index.spec.js b/modules/client/front/card/index.spec.js new file mode 100644 index 000000000..72272fe89 --- /dev/null +++ b/modules/client/front/card/index.spec.js @@ -0,0 +1,28 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientCard', () => { + let controller; + let $httpBackend; + let data = {id: 1, name: 'fooName'}; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_, $stateParams) => { + $httpBackend = _$httpBackend_; + + let $element = angular.element('
    '); + controller = $componentController('vnClientCard', {$element}); + + $stateParams.id = data.id; + $httpBackend.whenRoute('GET', 'Clients/:id/getCard').respond(data); + })); + + it('should request data and set it on the controller', () => { + controller.$onInit(); + $httpBackend.flush(); + + expect(controller.client).toEqual(data); + }); + }); +}); diff --git a/modules/client/front/contact/index.html b/modules/client/front/contact/index.html new file mode 100644 index 000000000..2cefdd86d --- /dev/null +++ b/modules/client/front/contact/index.html @@ -0,0 +1,51 @@ + + + + +
    + + + + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/modules/client/front/contact/index.js b/modules/client/front/contact/index.js new file mode 100644 index 000000000..4b0cc95ca --- /dev/null +++ b/modules/client/front/contact/index.js @@ -0,0 +1,35 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $stateParams, $translate) { + this.$scope = $scope; + this.$stateParams = $stateParams; + this.$translate = $translate; + } + + add() { + this.$scope.model.insert({ + clientFk: this.client.id, + name: this.$translate.instant('Phone'), + phone: null + }); + } + + onSubmit() { + this.$scope.watcher.check(); + this.$scope.model.save().then(() => { + this.$scope.watcher.notifySaved(); + this.$scope.model.refresh(); + }); + } +} + +Controller.$inject = ['$scope', '$stateParams', '$translate']; + +ngModule.component('vnClientContact', { + template: require('./index.html'), + controller: Controller, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/create/index.html b/modules/client/front/create/index.html new file mode 100644 index 000000000..ce4b7d4ed --- /dev/null +++ b/modules/client/front/create/index.html @@ -0,0 +1,155 @@ + + + +
    + + + + + + {{firstName}} {{lastName}} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + \ No newline at end of file diff --git a/modules/client/front/create/index.js b/modules/client/front/create/index.js new file mode 100644 index 000000000..241de110f --- /dev/null +++ b/modules/client/front/create/index.js @@ -0,0 +1,48 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($scope, $state, $http, $translate, vnApp) { + this.$ = $scope; + this.$state = $state; + this.$http = $http; + this.$translate = $translate; + this.vnApp = vnApp; + this.client = { + active: true + }; + } + + get postcodeSelection() { + return this._postcodeSelection; + } + + set postcodeSelection(selection) { + this._postcodeSelection = selection; + + if (!selection) return; + + const town = selection.town; + const province = town.province; + const country = province.country; + + this.client.city = town.name; + this.client.provinceFk = province.id; + this.client.countryFk = country.id; + } + + onResponse(response) { + this.client.postcode = response.code; + } + + onSubmit() { + return this.$.watcher.submit().then( + json => this.$state.go('client.card.basicData', {id: json.data.id}) + ); + } +} +Controller.$inject = ['$scope', '$state', '$http', '$translate', 'vnApp']; + +ngModule.component('vnClientCreate', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/client/front/create/index.spec.js b/modules/client/front/create/index.spec.js new file mode 100644 index 000000000..b59dffe44 --- /dev/null +++ b/modules/client/front/create/index.spec.js @@ -0,0 +1,68 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientCreate', () => { + let $componentController; + let $scope; + let $state; + let controller; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$state_) => { + $componentController = _$componentController_; + $scope = $rootScope.$new(); + $state = _$state_; + $scope.watcher = { + submit: () => { + return { + then: callback => { + callback({data: {id: '1234'}}); + } + }; + } + }; + controller = $componentController('vnClientCreate', {$scope: $scope}); + })); + + it('should define and set scope, state and client properties', () => { + expect(controller.$).toBe($scope); + expect(controller.$state).toBe($state); + expect(controller.client.active).toBe(true); + }); + + describe('onSubmit()', () => { + it(`should call submit() on the watcher then expect a callback`, () => { + spyOn($state, 'go'); + controller.onSubmit(); + + expect(controller.$state.go).toHaveBeenCalledWith('client.card.basicData', {id: '1234'}); + }); + }); + + describe('postcodeSelection() setter', () => { + it(`should set the town, province and contry properties`, () => { + controller.postcodeSelection = { + townFk: 1, + code: 46001, + town: { + id: 1, + name: 'New York', + province: { + id: 1, + name: 'New york', + country: { + id: 2, + name: 'USA' + } + } + } + }; + + expect(controller.client.city).toEqual('New York'); + expect(controller.client.provinceFk).toEqual(1); + expect(controller.client.countryFk).toEqual(2); + }); + }); + }); +}); diff --git a/modules/client/front/create/locale/es.yml b/modules/client/front/create/locale/es.yml new file mode 100644 index 000000000..6922ba917 --- /dev/null +++ b/modules/client/front/create/locale/es.yml @@ -0,0 +1,10 @@ +Name: Nombre +Tax number: NIF/CIF +Business name: Razón social +Web user: Usuario Web +Email: E-mail +Create and edit: Crear y editar +You can save multiple emails: >- + Puede guardar varios correos electrónicos encadenándolos mediante comas + sin espacios, ejemplo: user@dominio.com, user2@dominio.com siendo el primer + correo electrónico el principal \ No newline at end of file diff --git a/modules/client/front/credit-insurance/create/index.html b/modules/client/front/credit-insurance/create/index.html new file mode 100644 index 000000000..d1dc081b7 --- /dev/null +++ b/modules/client/front/credit-insurance/create/index.html @@ -0,0 +1,31 @@ +
    + + + + + + + + + + + + + + +
    diff --git a/modules/client/front/credit-insurance/create/index.js b/modules/client/front/credit-insurance/create/index.js new file mode 100644 index 000000000..86c067086 --- /dev/null +++ b/modules/client/front/credit-insurance/create/index.js @@ -0,0 +1,43 @@ +import ngModule from '../../module'; + +class Controller { + constructor($http, $filter, $state, $scope, $translate, vnApp) { + this.$http = $http; + this.$state = $state; + this.$scope = $scope; + this.$translate = $translate; + this.vnApp = vnApp; + this.creditClassification = { + started: $filter('date')(new Date(), 'yyyy-MM-dd HH:mm') + }; + } + + onSubmit() { + if (this.$scope.form.$invalid) + return this.vnApp.showError(this.$translate.instant('Some fields are invalid')); + + let query = `creditClassifications/createWithInsurance`; + let data = this.creditClassification; + data.clientFk = this.client.id; + + this.$http.post(query, data).then(res => { + if (res.data) { + this.card.reload(); + this.$state.go('client.card.creditInsurance.index'); + } + }); + } +} + +Controller.$inject = ['$http', '$filter', '$state', '$scope', '$translate', 'vnApp']; + +ngModule.component('vnClientCreditInsuranceCreate', { + template: require('./index.html'), + controller: Controller, + require: { + card: '^vnClientCard' + }, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/credit-insurance/create/index.spec.js b/modules/client/front/credit-insurance/create/index.spec.js new file mode 100644 index 000000000..1d1cd0e08 --- /dev/null +++ b/modules/client/front/credit-insurance/create/index.spec.js @@ -0,0 +1,47 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientCreditInsuranceCreate', () => { + let controller; + let $scope; + let $httpBackend; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + $scope.form = { + $invalid: false + }; + controller = $componentController('vnClientCreditInsuranceCreate', {$scope}); + controller.client = {id: 101}; + controller.card = { + reload: () => {} + }; + })); + + describe('onSubmit()', () => { + it('should perform a POST query', () => { + let started = new Date(); + controller.creditClassification = { + started: started, + credit: 300, + grade: 1 + }; + + let newData = { + started: started, + credit: 300, + grade: 1, + clientFk: 101 + }; + + $httpBackend.whenPOST(`creditClassifications/createWithInsurance`, newData).respond(200, true); + $httpBackend.expectPOST(`creditClassifications/createWithInsurance`, newData); + controller.onSubmit(); + $httpBackend.flush(); + }); + }); + }); +}); diff --git a/modules/client/front/credit-insurance/index/index.html b/modules/client/front/credit-insurance/index/index.html new file mode 100644 index 000000000..d2bf1fef6 --- /dev/null +++ b/modules/client/front/credit-insurance/index/index.html @@ -0,0 +1,66 @@ + + + + + + + + + + +
    Since {{::classification.started | date:'dd/MM/yyyy'}}
    +
    To {{classification.finished | date:'dd/MM/yyyy'}}
    +
    + + + + + + + + + + + + + + + + + + + +
    +
    +
    +
    +
    + + + + \ No newline at end of file diff --git a/modules/client/front/credit-insurance/index/index.js b/modules/client/front/credit-insurance/index/index.js new file mode 100644 index 000000000..accdc8c5d --- /dev/null +++ b/modules/client/front/credit-insurance/index/index.js @@ -0,0 +1,76 @@ +import ngModule from '../../module'; +import './style.scss'; + +class Controller { + constructor($http, $scope) { + this.$http = $http; + this.$scope = $scope; + } + + $onChanges() { + if (this.client && this.client.id) + this._getClassifications(this.client.id); + } + + _getClassifications(clientId) { + let filter = { + order: 'finished ASC, started DESC', + include: [ + { + relation: 'insurances', + scope: { + fields: ['id', 'credit', 'created', 'grade'], + order: 'created DESC', + limit: 2 + } + } + + ], + where: {client: clientId} + }; + filter = encodeURIComponent(JSON.stringify(filter)); + + let query = `CreditClassifications?filter=${filter}`; + this.$http.get(query).then(res => { + if (res.data) + this.classifications = res.data; + }); + } + + canCreateNew() { + if (!this.classifications) + return false; + + let items = this.classifications; + for (let i = 0; i < items.length; i++) { + if (!items[i].finished) + return false; + } + + return true; + } + + closeContract(classification) { + this.classificationId = classification.id; + this.$scope.closeContract.show(); + } + + returnDialog(response) { + if (response === 'accept') { + let params = {finished: Date.now()}; + this.$http.patch(`CreditClassifications/${this.classificationId}`, params).then(() => { + this._getClassifications(this.client.id); + }); + } + } +} + +Controller.$inject = ['$http', '$scope']; + +ngModule.component('vnClientCreditInsuranceIndex', { + template: require('./index.html'), + controller: Controller, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/credit-insurance/index/index.spec.js b/modules/client/front/credit-insurance/index/index.spec.js new file mode 100644 index 000000000..733936bf2 --- /dev/null +++ b/modules/client/front/credit-insurance/index/index.spec.js @@ -0,0 +1,86 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientCreditInsuranceIndex', () => { + let controller; + let $httpBackend; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + controller = $componentController('vnClientCreditInsuranceIndex'); + controller.client = {id: 101}; + })); + + describe('_getClassifications()', () => { + it('should perform a GET query to define the classifications property in the controller', () => { + let res = ['some classifications']; + let query = 'CreditClassifications?filter=%7B%22order%22%3A%22finished%20ASC%2C%20started%20DESC%22%2C%22include%22%3A%5B%7B%22relation%22%3A%22insurances%22%2C%22scope%22%3A%7B%22fields%22%3A%5B%22id%22%2C%22credit%22%2C%22created%22%2C%22grade%22%5D%2C%22order%22%3A%22created%20DESC%22%2C%22limit%22%3A2%7D%7D%5D%2C%22where%22%3A%7B%7D%7D'; + + $httpBackend.whenGET(query).respond(res); + $httpBackend.expectGET(query); + controller._getClassifications(); + $httpBackend.flush(); + + expect(controller.classifications).toEqual(['some classifications']); + }); + }); + + describe('canCreateNew()', () => { + it(`should return false if doesn't have classifications`, () => { + let result = controller.canCreateNew(); + + expect(result).toBeFalsy(); + }); + + it(`should return false if finds a classification without due date`, () => { + controller.classifications = [ + {finished: Date.now()}, + {finished: null} + ]; + + let result = controller.canCreateNew(); + + expect(result).toBeFalsy(); + }); + + it(`should return true if all classifications are defined with due date`, () => { + controller.classifications = [ + {finished: Date.now()}, + {finished: Date.now()} + ]; + + let result = controller.canCreateNew(); + + expect(result).toBeTruthy(); + }); + }); + + describe('closeContract()', () => { + it('should define the classificationId property of the controller and then call the show method()', () => { + controller.$scope.closeContract = {show: () => {}}; + spyOn(controller.$scope.closeContract, 'show'); + + expect(controller.classificationId).toBeFalsy(); + controller.closeContract({id: 1}); + + expect(controller.classificationId).toEqual(1); + expect(controller.$scope.closeContract.show).toHaveBeenCalledWith(); + }); + }); + + describe('returnDialog()', () => { + it('should call the returnDialog method and perform a PATCH query, then call _getClassifications method', () => { + spyOn(controller, '_getClassifications'); + controller.classificationId = 1; + $httpBackend.when('PATCH', `CreditClassifications/1`).respond(200); + $httpBackend.expect('PATCH', `CreditClassifications/1`); + controller.returnDialog('accept'); + $httpBackend.flush(); + + expect(controller._getClassifications).toHaveBeenCalledWith(101); + }); + }); + }); +}); diff --git a/modules/client/front/credit-insurance/index/locale/es.yml b/modules/client/front/credit-insurance/index/locale/es.yml new file mode 100644 index 000000000..014faffbe --- /dev/null +++ b/modules/client/front/credit-insurance/index/locale/es.yml @@ -0,0 +1,4 @@ +Contract credit insurance: Contratos de seguro de crédito +Close contract: Cerrar contrato +View credits: Ver créditos +Are you sure you want to close this contract?: ¿Seguro que quieres cerrar este contrato? \ No newline at end of file diff --git a/modules/client/front/credit-insurance/index/style.scss b/modules/client/front/credit-insurance/index/style.scss new file mode 100644 index 000000000..6b4f25e2c --- /dev/null +++ b/modules/client/front/credit-insurance/index/style.scss @@ -0,0 +1,5 @@ +vn-client-credit-insurance-index{ + .insurance:last-child { + padding-bottom: 0; + } +} \ No newline at end of file diff --git a/modules/client/front/credit-insurance/insurance/create/index.html b/modules/client/front/credit-insurance/insurance/create/index.html new file mode 100644 index 000000000..2331cf40b --- /dev/null +++ b/modules/client/front/credit-insurance/insurance/create/index.html @@ -0,0 +1,43 @@ + + + +
    + + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/modules/client/front/credit-insurance/insurance/create/index.js b/modules/client/front/credit-insurance/insurance/create/index.js new file mode 100644 index 000000000..2c7670ff5 --- /dev/null +++ b/modules/client/front/credit-insurance/insurance/create/index.js @@ -0,0 +1,33 @@ +import ngModule from '../../../module'; + +class Controller { + constructor($scope, $state, $filter) { + this.$scope = $scope; + this.$state = $state; + this.insurance = { + created: $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss') + }; + } + + onSubmit() { + let params = {classificationId: this.$state.params.classificationId}; + let state = 'client.card.creditInsurance.insurance.index'; + + this.$scope.watcher.submitGo(state, params).then(() => { + this.card.reload(); + }); + } +} + +Controller.$inject = ['$scope', '$state', '$filter']; + +ngModule.component('vnClientCreditInsuranceInsuranceCreate', { + template: require('./index.html'), + controller: Controller, + require: { + card: '^vnClientCard' + }, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/credit-insurance/insurance/index/index.html b/modules/client/front/credit-insurance/insurance/index/index.html new file mode 100644 index 000000000..28f44f044 --- /dev/null +++ b/modules/client/front/credit-insurance/insurance/index/index.html @@ -0,0 +1,38 @@ + + +
    + + + + + + Created + Grade + Credit + + + + + {{::insurance.created | date: 'dd/MM/yyyy'}} + {{::insurance.grade}} + {{::insurance.credit | currency: 'EUR': 2}} + + + + + +
    + + + \ No newline at end of file diff --git a/modules/client/front/credit-insurance/insurance/index/index.js b/modules/client/front/credit-insurance/insurance/index/index.js new file mode 100644 index 000000000..4851bf200 --- /dev/null +++ b/modules/client/front/credit-insurance/insurance/index/index.js @@ -0,0 +1,38 @@ +import ngModule from '../../../module'; + +class Controller { + constructor($stateParams, $http) { + this.$stateParams = $stateParams; + this.$http = $http; + this.isClosed = true; + this.filter = { + include: [ + {relation: 'classification'} + ] + }; + } + + $onInit() { + let filter = { + fields: ['finished'], + where: {id: this.$stateParams.classificationId} + }; + filter = encodeURIComponent(JSON.stringify(filter)); + + let query = `CreditClassifications?filter=${filter}`; + this.$http.get(query).then(res => { + if (res.data) + this.isClosed = res.data[0].finished != null; + }); + } +} + +Controller.$inject = ['$stateParams', '$http']; + +ngModule.component('vnClientCreditInsuranceInsuranceIndex', { + template: require('./index.html'), + controller: Controller, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/credit-insurance/insurance/index/index.spec.js b/modules/client/front/credit-insurance/insurance/index/index.spec.js new file mode 100644 index 000000000..8c3cdee83 --- /dev/null +++ b/modules/client/front/credit-insurance/insurance/index/index.spec.js @@ -0,0 +1,30 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientCreditInsuranceInsuranceIndex', () => { + let controller; + let $httpBackend; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + let $stateParams = {classificationId: 1}; + $httpBackend = _$httpBackend_; + controller = $componentController('vnClientCreditInsuranceInsuranceIndex', {$stateParams}); + })); + + describe('$onInit()', () => { + it('should perform a query to GET credit the credit classification', () => { + let res = [{finished: 'some value'}]; + let query = 'CreditClassifications?filter=%7B%22fields%22%3A%5B%22finished%22%5D%2C%22where%22%3A%7B%22id%22%3A1%7D%7D'; + + $httpBackend.whenGET(query).respond(res); + $httpBackend.expectGET(query); + controller.$onInit(); + $httpBackend.flush(); + + expect(controller.isClosed).toBe(true); + }); + }); + }); +}); diff --git a/modules/client/front/credit-insurance/insurance/index/locale/es.yml b/modules/client/front/credit-insurance/insurance/index/locale/es.yml new file mode 100644 index 000000000..84ce712a0 --- /dev/null +++ b/modules/client/front/credit-insurance/insurance/index/locale/es.yml @@ -0,0 +1 @@ +Created: Creado \ No newline at end of file diff --git a/modules/client/front/credit/create/index.html b/modules/client/front/credit/create/index.html new file mode 100644 index 000000000..c77c1556c --- /dev/null +++ b/modules/client/front/credit/create/index.html @@ -0,0 +1,31 @@ + + + +
    + + + + + + + + + + +
    + + diff --git a/modules/client/front/credit/create/index.js b/modules/client/front/credit/create/index.js new file mode 100644 index 000000000..7493073b6 --- /dev/null +++ b/modules/client/front/credit/create/index.js @@ -0,0 +1,50 @@ +import ngModule from '../../module'; + +class Controller { + constructor($http, $scope, $state) { + this.$http = $http; + this.$scope = $scope; + this.$state = $state; + } + + onSubmit() { + this.$http.get(`Recoveries/${this.$state.params.id}/hasActiveRecovery`).then(res => { + let activeRecovery = res.data; + if (activeRecovery) + this.$scope.confirmation.show(); + else + this.addCredit(); + }); + } + + cancel() { + this.goToIndex(); + } + + returnDialog(response) { + if (response === 'accept') + this.addCredit(); + } + + goToIndex() { + this.$state.go('client.card.credit.index'); + } + + addCredit() { + this.$scope.watcher.submit().then( + () => { + this.goToIndex(); + } + ); + } +} + +Controller.$inject = ['$http', '$scope', '$state']; + +ngModule.component('vnClientCreditCreate', { + template: require('./index.html'), + controller: Controller, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/credit/create/index.spec.js b/modules/client/front/credit/create/index.spec.js new file mode 100644 index 000000000..3dd96aaa1 --- /dev/null +++ b/modules/client/front/credit/create/index.spec.js @@ -0,0 +1,93 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientCreditCreate', () => { + let controller; + let $httpBackend; + let $state; + let $scope; + let client; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_, $rootScope, _$state_) => { + $scope = $rootScope.$new(); + $scope.confirmation = {show: () => { + return { + then: () => {} + }; + }}; + $scope.watcher = { + submit: () => { + return { + then: callback => { + callback(); + } + }; + } + }; + client = {credit: 0}; + $state = _$state_; + $state.params.id = 101; + $httpBackend = _$httpBackend_; + controller = $componentController('vnClientCreditCreate', {$scope, $state}); + })); + + describe('onSubmit()', () => { + it('should perform a query to check (GET) if the client has an active recovery', () => { + $httpBackend.whenGET(`Recoveries/101/hasActiveRecovery`).respond(true); + $httpBackend.expectGET(`Recoveries/101/hasActiveRecovery`); + controller.onSubmit(); + $httpBackend.flush(); + }); + + it('should call show() method when the client have a recovery', () => { + spyOn(controller.$scope.confirmation, 'show'); + $httpBackend.whenGET(`Recoveries/101/hasActiveRecovery`).respond(true); + $httpBackend.expectGET(`Recoveries/101/hasActiveRecovery`); + controller.onSubmit(); + $httpBackend.flush(); + + expect(controller.$scope.confirmation.show).toHaveBeenCalledWith(); + }); + + it('should call addCredit() method when the client doesnt have a recovery', () => { + spyOn(controller, 'addCredit'); + $httpBackend.whenGET(`Recoveries/101/hasActiveRecovery`).respond(false); + $httpBackend.expectGET(`Recoveries/101/hasActiveRecovery`); + controller.onSubmit(); + $httpBackend.flush(); + + expect(controller.addCredit).toHaveBeenCalledWith(); + }); + }); + + describe('cancel()', () => { + it('should call goToIndex()', () => { + spyOn(controller, 'goToIndex'); + controller.cancel(); + + expect(controller.goToIndex).toHaveBeenCalledWith(); + }); + }); + + describe('returnDialog()', () => { + it('should call addCredit() when is called with accept', () => { + spyOn(controller, 'addCredit'); + controller.returnDialog('accept'); + + expect(controller.addCredit).toHaveBeenCalledWith(); + }); + }); + + describe('addCredit()', () => { + it('should call the function go() on $state to go to the credit list', () => { + spyOn($state, 'go'); + client.credit = 1; + controller.addCredit(); + + expect(controller.$state.go).toHaveBeenCalledWith('client.card.credit.index'); + }); + }); + }); +}); diff --git a/modules/client/front/credit/index/index.html b/modules/client/front/credit/index/index.html new file mode 100644 index 000000000..03de6f0e7 --- /dev/null +++ b/modules/client/front/credit/index/index.html @@ -0,0 +1,41 @@ + + + + + + + + Since + Employee + Credit + + + + + {{::credit.created | date:'dd/MM/yyyy HH:mm'}} + {{::credit.worker.user.nickname}} + {{::credit.amount | currency:'EUR':2}} + + + + + + + diff --git a/modules/client/front/credit/index/index.js b/modules/client/front/credit/index/index.js new file mode 100644 index 000000000..e8fae8d9d --- /dev/null +++ b/modules/client/front/credit/index/index.js @@ -0,0 +1,30 @@ +import ngModule from '../../module'; + +class Controller { + constructor($stateParams) { + this.$stateParams = $stateParams; + this.filter = { + include: [ + { + relation: 'worker', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + } + ] + }; + } +} + +Controller.$inject = ['$stateParams']; + +ngModule.component('vnClientCreditIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/client/front/credit/index/locale/es.yml b/modules/client/front/credit/index/locale/es.yml new file mode 100644 index 000000000..a15a1085f --- /dev/null +++ b/modules/client/front/credit/index/locale/es.yml @@ -0,0 +1,2 @@ +Since : Desde +Employee : Empleado \ No newline at end of file diff --git a/modules/client/front/descriptor-popover/index.html b/modules/client/front/descriptor-popover/index.html new file mode 100644 index 000000000..e7b2f583a --- /dev/null +++ b/modules/client/front/descriptor-popover/index.html @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/modules/client/front/descriptor-popover/index.js b/modules/client/front/descriptor-popover/index.js new file mode 100644 index 000000000..816eaf05e --- /dev/null +++ b/modules/client/front/descriptor-popover/index.js @@ -0,0 +1,71 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + constructor($element, $scope, $http, $timeout, $q) { + super($element, $scope); + this.$timeout = $timeout; + this.$http = $http; + this.$q = $q; + this.client = null; + this._quicklinks = {}; + } + + set clientFk(id) { + if (id == this._clientFk) return; + + this._clientFk = id; + this.client = null; + this.getCard(); + } + + set client(value) { + this._client = value; + this.$timeout(() => this.$.popover.relocate()); + } + + get client() { + return this._client; + } + + get quicklinks() { + return this._quicklinks; + } + + set quicklinks(value = {}) { + Object.keys(value).forEach(key => { + this._quicklinks[key] = value[key]; + }); + } + + show() { + this.$.popover.parent = this.parent; + this.$.popover.show(); + } + + getCard() { + if (this.canceler) + this.canceler.resolve(); + + this.canceler = this.$q.defer(); + + let options = {timeout: this.canceler.promise}; + this.$http.get(`Clients/${this._clientFk}/getCard`, options).then( + response => { + this.client = response.data; + this.canceler = null; + } + ); + } +} +Controller.$inject = ['$element', '$scope', '$http', '$timeout', '$q']; + +ngModule.component('vnClientDescriptorPopover', { + template: require('./index.html'), + controller: Controller, + bindings: { + clientFk: '<', + quicklinks: '<' + } +}); diff --git a/modules/client/front/descriptor-popover/index.spec.js b/modules/client/front/descriptor-popover/index.spec.js new file mode 100644 index 000000000..6e76d3062 --- /dev/null +++ b/modules/client/front/descriptor-popover/index.spec.js @@ -0,0 +1,80 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientDescriptorPopover', () => { + let $httpBackend; + let $scope; + let controller; + let $element; + let $timeout; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_, _$timeout_) => { + $httpBackend = _$httpBackend_; + $timeout = _$timeout_; + $element = angular.element(`
    `); + $scope = $rootScope.$new(); + $scope.popover = {relocate: () => {}, show: () => {}}; + controller = $componentController('vnClientDescriptorPopover', {$scope, $element}); + })); + + describe('clientFk()', () => { + it(`should not apply any changes if the received id is the same stored in _clientFk`, () => { + controller.client = 'I exist!'; + controller._clientFk = 1; + spyOn(controller, 'getCard'); + controller.clientFk = 1; + + expect(controller.client).toEqual('I exist!'); + expect(controller._clientFk).toEqual(1); + expect(controller.getCard).not.toHaveBeenCalled(); + }); + + it(`should set the received id into _clientFk, set the client to null and then call getCard()`, () => { + controller.client = `Please don't`; + controller._clientFk = 1; + spyOn(controller, 'getCard'); + controller.clientFk = 999; + + expect(controller.client).toBeNull(); + expect(controller._clientFk).toEqual(999); + expect(controller.getCard).toHaveBeenCalledWith(); + }); + }); + + describe('client()', () => { + it(`should save the client into _client and then call relocate()`, () => { + spyOn(controller.$.popover, 'relocate'); + controller.client = `i'm the client!`; + $timeout.flush(); + + expect(controller._client).toEqual(`i'm the client!`); + expect(controller.$.popover.relocate).toHaveBeenCalledWith(); + }); + }); + + describe('show()', () => { + it(`should call the show()`, () => { + spyOn(controller.$.popover, 'show'); + controller.show(); + + expect(controller.$.popover.show).toHaveBeenCalledWith(); + }); + }); + + describe('getCard()', () => { + it(`should perform a get query to store the client data into the controller`, () => { + controller.clientFk = 1; + controller.canceler = null; + let response = {}; + $httpBackend.when('GET', `Clients/${controller._clientFk}/getCard`).respond(response); + $httpBackend.expect('GET', `Clients/${controller._clientFk}/getCard`); + controller.getCard(); + $httpBackend.flush(); + + expect(controller.client).toEqual(response); + }); + }); + }); +}); diff --git a/modules/client/front/descriptor-popover/style.scss b/modules/client/front/descriptor-popover/style.scss new file mode 100644 index 000000000..0262c4ac0 --- /dev/null +++ b/modules/client/front/descriptor-popover/style.scss @@ -0,0 +1,9 @@ +vn-client-descriptor-popover { + vn-client-descriptor { + display: block; + width: 16em; + & > vn-card{ + margin: 0!important; + } + } +} diff --git a/modules/client/front/descriptor/index.html b/modules/client/front/descriptor/index.html new file mode 100644 index 000000000..722802c66 --- /dev/null +++ b/modules/client/front/descriptor/index.html @@ -0,0 +1,73 @@ +
    +
    + + + + + + + + +
    +
    +
    +
    {{$ctrl.client.name}}
    + + + + + + + + + + +
    +
    + + + + + + + + + + +
    + + +
    +
    + + + \ No newline at end of file diff --git a/modules/client/front/descriptor/index.js b/modules/client/front/descriptor/index.js new file mode 100644 index 000000000..332d87deb --- /dev/null +++ b/modules/client/front/descriptor/index.js @@ -0,0 +1,77 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; + +class Controller extends Component { + constructor($element, $) { + super($element, $); + + this.moreOptions = [ + {name: 'Simple ticket', callback: this.newTicket}, + {name: 'Send SMS', callback: this.showSMSDialog}, + ]; + } + + onMoreChange(callback) { + callback.call(this); + } + + get client() { + return this._client; + } + + set client(value) { + this._client = value; + + if (!value) return; + + if (this.$params.sendSMS) + this.showSMSDialog(); + + this._quicklinks = { + btnOne: { + icon: 'icon-ticket', + state: `ticket.index({q: '{"clientFk": ${value.id}}'})`, + tooltip: 'Client ticket list' + }, + btnTwo: { + icon: 'icon-basketadd', + state: `order.create({clientFk: ${value.id}})`, + tooltip: 'New order' + } + }; + } + + set quicklinks(value = {}) { + this._quicklinks = Object.assign(value, this._quicklinks); + } + + get quicklinks() { + return this._quicklinks; + } + + newTicket() { + this.$state.go('ticket.create', {clientFk: this.client.id}); + } + + showSMSDialog() { + const phone = this.$params.phone || this.client.phone; + const message = this.$params.message || ''; + this.newSMS = { + destinationFk: this.client.id, + destination: phone, + message: message + }; + this.$.sms.open(); + } +} + +Controller.$inject = ['$element', '$scope']; + +ngModule.component('vnClientDescriptor', { + template: require('./index.html'), + bindings: { + client: '<', + quicklinks: '<' + }, + controller: Controller +}); diff --git a/modules/client/front/descriptor/locale/es.yml b/modules/client/front/descriptor/locale/es.yml new file mode 100644 index 000000000..5ae6935d0 --- /dev/null +++ b/modules/client/front/descriptor/locale/es.yml @@ -0,0 +1 @@ +Simple ticket: Ticket simple \ No newline at end of file diff --git a/modules/client/front/dms/create/index.html b/modules/client/front/dms/create/index.html new file mode 100644 index 000000000..4ed221ae8 --- /dev/null +++ b/modules/client/front/dms/create/index.html @@ -0,0 +1,83 @@ + + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    diff --git a/modules/client/front/dms/create/index.js b/modules/client/front/dms/create/index.js new file mode 100644 index 000000000..46c4d7565 --- /dev/null +++ b/modules/client/front/dms/create/index.js @@ -0,0 +1,117 @@ +import ngModule from '../../module'; +import './style.scss'; + +class Controller { + constructor($scope, $http, $state, $translate, vnApp, vnConfig) { + this.$ = $scope; + this.$http = $http; + this.$state = $state; + this.$translate = $translate; + this.vnApp = vnApp; + this.vnConfig = vnConfig; + this.dms = { + files: [], + hasFile: false, + hasFileAttached: false + }; + } + + get client() { + return this._client; + } + + set client(value) { + this._client = value; + + if (value) { + this.setDefaultParams(); + this.getAllowedContentTypes(); + } + } + + getAllowedContentTypes() { + this.$http.get('clientDms/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + + get contentTypesInfo() { + return this.$translate.instant('ContentTypesInfo', { + allowedContentTypes: this.allowedContentTypes + }); + } + + setDefaultParams() { + const params = {filter: { + where: {code: 'paymentsLaw'} + }}; + this.$http.get('DmsTypes/findOne', {params}).then(res => { + const dmsType = res.data && res.data; + const companyId = this.vnConfig.companyFk; + const warehouseId = this.vnConfig.warehouseFk; + const defaultParams = { + reference: this.client.id, + warehouseId: warehouseId, + companyId: companyId, + dmsTypeId: dmsType.id, + description: this.$translate.instant('ClientFileDescription', { + dmsTypeName: dmsType.name, + clientId: this.client.id, + clientName: this.client.name + }).toUpperCase() + }; + + this.dms = Object.assign(this.dms, defaultParams); + }); + } + + onSubmit() { + const query = `clients/${this.client.id}/uploadFile`; + const options = { + method: 'POST', + url: query, + params: this.dms, + headers: { + 'Content-Type': undefined + }, + transformRequest: files => { + const formData = new FormData(); + + for (let i = 0; i < files.length; i++) + formData.append(files[i].name, files[i]); + + return formData; + }, + data: this.dms.files + }; + this.$http(options).then(res => { + if (res) { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$.watcher.updateOriginalData(); + this.$state.go('client.card.dms.index'); + } + }); + } + + onFileChange(files) { + let hasFileAttached = false; + + if (files.length > 0) + hasFileAttached = true; + + this.$.$applyAsync(() => { + this.dms.hasFileAttached = hasFileAttached; + }); + } +} + +Controller.$inject = ['$scope', '$http', '$state', '$translate', 'vnApp', 'vnConfig']; + +ngModule.component('vnClientDmsCreate', { + template: require('./index.html'), + controller: Controller, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/dms/create/index.spec.js b/modules/client/front/dms/create/index.spec.js new file mode 100644 index 000000000..4ff8ce122 --- /dev/null +++ b/modules/client/front/dms/create/index.spec.js @@ -0,0 +1,75 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientDmsCreate', () => { + let controller; + let $scope; + let $httpBackend; + let $httpParamSerializer; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_) => { + $scope = $rootScope.$new(); + $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; + controller = $componentController('vnClientDmsCreate', {$scope}); + controller._client = {id: 101, name: 'Bruce wayne'}; + })); + + describe('client() setter', () => { + it('should set the client data and then call setDefaultParams() and getAllowedContentTypes()', () => { + spyOn(controller, 'setDefaultParams'); + spyOn(controller, 'getAllowedContentTypes'); + controller.client = { + id: 15, + name: 'Bruce wayne' + }; + + expect(controller.client).toBeDefined(); + expect(controller.setDefaultParams).toHaveBeenCalledWith(); + expect(controller.getAllowedContentTypes).toHaveBeenCalledWith(); + }); + }); + + describe('setDefaultParams()', () => { + it('should perform a GET query and define the dms property on controller', () => { + const params = {filter: { + where: {code: 'paymentsLaw'} + }}; + let serializedParams = $httpParamSerializer(params); + $httpBackend.when('GET', `DmsTypes/findOne?${serializedParams}`).respond({id: 12, code: 'paymentsLaw'}); + $httpBackend.expect('GET', `DmsTypes/findOne?${serializedParams}`); + controller.setDefaultParams(); + $httpBackend.flush(); + + expect(controller.dms).toBeDefined(); + expect(controller.dms.reference).toEqual(101); + expect(controller.dms.dmsTypeId).toEqual(12); + }); + }); + + describe('onFileChange()', () => { + it('should set dms hasFileAttached property to true if has any files', () => { + const files = [{id: 1, name: 'MyFile'}]; + controller.onFileChange(files); + $scope.$apply(); + + expect(controller.dms.hasFileAttached).toBeTruthy(); + }); + }); + + describe('getAllowedContentTypes()', () => { + it('should make an HTTP GET request to get the allowed content types', () => { + const expectedResponse = ['image/png', 'image/jpg']; + $httpBackend.when('GET', `clientDms/allowedContentTypes`).respond(expectedResponse); + $httpBackend.expect('GET', `clientDms/allowedContentTypes`); + controller.getAllowedContentTypes(); + $httpBackend.flush(); + + expect(controller.allowedContentTypes).toBeDefined(); + expect(controller.allowedContentTypes).toEqual('image/png, image/jpg'); + }); + }); + }); +}); diff --git a/modules/client/front/dms/create/style.scss b/modules/client/front/dms/create/style.scss new file mode 100644 index 000000000..73f136fc1 --- /dev/null +++ b/modules/client/front/dms/create/style.scss @@ -0,0 +1,7 @@ +vn-ticket-request { + .vn-textfield { + margin: 0!important; + max-width: 100px; + } +} + diff --git a/modules/client/front/dms/edit/index.html b/modules/client/front/dms/edit/index.html new file mode 100644 index 000000000..dbc2e0ed1 --- /dev/null +++ b/modules/client/front/dms/edit/index.html @@ -0,0 +1,74 @@ + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    diff --git a/modules/client/front/dms/edit/index.js b/modules/client/front/dms/edit/index.js new file mode 100644 index 000000000..460aa17a7 --- /dev/null +++ b/modules/client/front/dms/edit/index.js @@ -0,0 +1,104 @@ +import ngModule from '../../module'; +import './style.scss'; + +class Controller { + constructor($scope, $http, $state, $translate, vnApp) { + this.$ = $scope; + this.$http = $http; + this.$state = $state; + this.$stateParams = $state.params; + this.$translate = $translate; + this.vnApp = vnApp; + } + + get client() { + return this._client; + } + + set client(value) { + this._client = value; + + if (value) { + this.setDefaultParams(); + this.getAllowedContentTypes(); + } + } + + getAllowedContentTypes() { + this.$http.get('clientDms/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + + get contentTypesInfo() { + return this.$translate.instant('ContentTypesInfo', { + allowedContentTypes: this.allowedContentTypes + }); + } + + setDefaultParams() { + const path = `Dms/${this.$stateParams.dmsId}`; + this.$http.get(path).then(res => { + const dms = res.data && res.data; + this.dms = { + reference: dms.reference, + warehouseId: dms.warehouseFk, + companyId: dms.companyFk, + dmsTypeId: dms.dmsTypeFk, + description: dms.description, + hasFile: dms.hasFile, + hasFileAttached: false, + files: [] + }; + }); + } + + onSubmit() { + const query = `dms/${this.$stateParams.dmsId}/updateFile`; + const options = { + method: 'POST', + url: query, + params: this.dms, + headers: { + 'Content-Type': undefined + }, + transformRequest: files => { + const formData = new FormData(); + + for (let i = 0; i < files.length; i++) + formData.append(files[i].name, files[i]); + + return formData; + }, + data: this.dms.files + }; + this.$http(options).then(res => { + if (res) { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$.watcher.updateOriginalData(); + this.$state.go('client.card.dms.index'); + } + }); + } + + onFileChange(files) { + let hasFileAttached = false; + if (files.length > 0) + hasFileAttached = true; + + this.$.$applyAsync(() => { + this.dms.hasFileAttached = hasFileAttached; + }); + } +} + +Controller.$inject = ['$scope', '$http', '$state', '$translate', 'vnApp']; + +ngModule.component('vnClientDmsEdit', { + template: require('./index.html'), + controller: Controller, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/dms/edit/index.spec.js b/modules/client/front/dms/edit/index.spec.js new file mode 100644 index 000000000..732a90868 --- /dev/null +++ b/modules/client/front/dms/edit/index.spec.js @@ -0,0 +1,83 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientDmsEdit', () => { + let controller; + let $scope; + let $httpBackend; + let $state; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_) => { + $scope = $rootScope.$new(); + $httpBackend = _$httpBackend_; + $state = {params: {dmsId: 1}}; + controller = $componentController('vnClientDmsEdit', {$scope, $state}); + controller._client = {id: 1}; + })); + + describe('client() setter', () => { + it('should set the client data and then call setDefaultParams() and getAllowedContentTypes()', () => { + spyOn(controller, 'setDefaultParams'); + spyOn(controller, 'getAllowedContentTypes'); + controller._client = undefined; + controller.client = { + id: 15 + }; + + expect(controller.setDefaultParams).toHaveBeenCalledWith(); + expect(controller.client).toBeDefined(); + expect(controller.getAllowedContentTypes).toHaveBeenCalledWith(); + }); + }); + + describe('setDefaultParams()', () => { + it('should perform a GET query and define the dms property on controller', () => { + const dmsId = 1; + const expectedResponse = { + reference: 101, + warehouseFk: 1, + companyFk: 442, + dmsTypeFk: 12, + description: 'Test', + hasFile: false, + hasFileAttached: false + }; + + $httpBackend.when('GET', `Dms/${dmsId}`).respond(expectedResponse); + $httpBackend.expect('GET', `Dms/${dmsId}`).respond(expectedResponse); + controller.setDefaultParams(); + $httpBackend.flush(); + + expect(controller.dms).toBeDefined(); + expect(controller.dms.reference).toEqual(101); + expect(controller.dms.dmsTypeId).toEqual(12); + }); + }); + + describe('onFileChange()', () => { + it('should set dms hasFileAttached property to true if has any files', () => { + const files = [{id: 1, name: 'MyFile'}]; + controller.dms = {hasFileAttached: false}; + controller.onFileChange(files); + $scope.$apply(); + + expect(controller.dms.hasFileAttached).toBeTruthy(); + }); + }); + + describe('getAllowedContentTypes()', () => { + it('should make an HTTP GET request to get the allowed content types', () => { + const expectedResponse = ['image/png', 'image/jpg']; + $httpBackend.when('GET', `clientDms/allowedContentTypes`).respond(expectedResponse); + $httpBackend.expect('GET', `clientDms/allowedContentTypes`); + controller.getAllowedContentTypes(); + $httpBackend.flush(); + + expect(controller.allowedContentTypes).toBeDefined(); + expect(controller.allowedContentTypes).toEqual('image/png, image/jpg'); + }); + }); + }); +}); diff --git a/modules/client/front/dms/edit/style.scss b/modules/client/front/dms/edit/style.scss new file mode 100644 index 000000000..73f136fc1 --- /dev/null +++ b/modules/client/front/dms/edit/style.scss @@ -0,0 +1,7 @@ +vn-ticket-request { + .vn-textfield { + margin: 0!important; + max-width: 100px; + } +} + diff --git a/modules/client/front/dms/index/index.html b/modules/client/front/dms/index/index.html new file mode 100644 index 000000000..9ecafe887 --- /dev/null +++ b/modules/client/front/dms/index/index.html @@ -0,0 +1,118 @@ + + + + + + + + Id + Type + Order + Reference + Description + Original + File + Employee + Created + + + + + + + + {{::document.dmsFk}} + + + {{::document.dms.dmsType.name}} + + + + + {{::document.dms.hardCopyNumber}} + + + + + {{::document.dms.reference}} + + + + + {{::document.dms.description}} + + + + + + + + + {{::document.dms.file}} + + + + + {{::document.dms.worker.user.nickname | dashIfEmpty}} + + + {{::document.dms.created | date:'dd/MM/yyyy HH:mm'}} + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/client/front/dms/index/index.js b/modules/client/front/dms/index/index.js new file mode 100644 index 000000000..0f1c8a2dc --- /dev/null +++ b/modules/client/front/dms/index/index.js @@ -0,0 +1,79 @@ +import ngModule from '../../module'; +import './style.scss'; + +class Controller { + constructor($stateParams, $scope, vnToken, $http, vnApp, $translate) { + this.$stateParams = $stateParams; + this.$ = $scope; + this.accessToken = vnToken.token; + this.$http = $http; + this.vnApp = vnApp; + this.$translate = $translate; + this.filter = { + include: { + relation: 'dms', + scope: { + fields: [ + 'dmsTypeFk', + 'reference', + 'hardCopyNumber', + 'workerFk', + 'description', + 'hasFile', + 'file', + 'created', + ], + include: [{ + relation: 'dmsType', + scope: { + fields: ['name'] + } + }, + { + relation: 'worker', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + }, + } + }] + }, + } + }; + } + + showWorkerDescriptor(event, workerFk) { + event.preventDefault(); + event.stopImmediatePropagation(); + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.workerFk = workerFk; + this.$.workerDescriptor.show(); + } + + showDeleteConfirm(index) { + this.dmsIndex = index; + this.$.confirm.show(); + } + + deleteDms(response) { + if (response === 'accept') { + const dmsFk = this.clientDms[this.dmsIndex].dmsFk; + const query = `clientDms/${dmsFk}/removeFile`; + this.$http.post(query).then(() => { + this.$.model.remove(this.dmsIndex); + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }); + } + } +} + +Controller.$inject = ['$stateParams', '$scope', 'vnToken', '$http', 'vnApp', '$translate']; + +ngModule.component('vnClientDmsIndex', { + template: require('./index.html'), + controller: Controller, +}); diff --git a/modules/client/front/dms/index/index.spec.js b/modules/client/front/dms/index/index.spec.js new file mode 100644 index 000000000..16190177b --- /dev/null +++ b/modules/client/front/dms/index/index.spec.js @@ -0,0 +1,40 @@ +import './index'; +import crudModel from 'core/mocks/crud-model'; + +describe('Client', () => { + describe('Component vnClientDmsIndex', () => { + let $componentController; + let $scope; + let $httpBackend; + let controller; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_) => { + $componentController = _$componentController_; + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + controller = $componentController('vnClientDmsIndex', {$: $scope}); + controller.$.model = crudModel; + })); + + describe('deleteDms()', () => { + it('should make an HTTP Post query', () => { + const dmsId = 1; + const dmsIndex = 0; + spyOn(controller.vnApp, 'showSuccess'); + spyOn(controller.$.model, 'remove'); + controller.clientDms = [{dmsFk: 1}]; + controller.dmsIndex = dmsIndex; + + $httpBackend.when('POST', `clientDms/${dmsId}/removeFile`).respond({}); + $httpBackend.expect('POST', `clientDms/${dmsId}/removeFile`); + controller.deleteDms('accept'); + $httpBackend.flush(); + + expect(controller.$.model.remove).toHaveBeenCalledWith(dmsIndex); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + }); + }); + }); +}); diff --git a/modules/client/front/dms/index/locale/es.yml b/modules/client/front/dms/index/locale/es.yml new file mode 100644 index 000000000..0994c7d86 --- /dev/null +++ b/modules/client/front/dms/index/locale/es.yml @@ -0,0 +1,9 @@ +Type: Tipo +File management: Gestión documental +File: Fichero +Hard copy: Copia +This file will be deleted: Este fichero va a ser borrado +Are you sure?: Estas seguro? +File deleted: Fichero eliminado +Remove file: Eliminar fichero +Download file: Descargar fichero \ No newline at end of file diff --git a/modules/client/front/dms/index/style.scss b/modules/client/front/dms/index/style.scss new file mode 100644 index 000000000..a6758e2e6 --- /dev/null +++ b/modules/client/front/dms/index/style.scss @@ -0,0 +1,6 @@ +vn-client-risk-index { + .totalBox { + display: table; + float: right; + } +} \ No newline at end of file diff --git a/modules/client/front/dms/locale/en.yml b/modules/client/front/dms/locale/en.yml new file mode 100644 index 000000000..766853fca --- /dev/null +++ b/modules/client/front/dms/locale/en.yml @@ -0,0 +1,2 @@ +ClientFileDescription: "{{dmsTypeName}} from client {{clientName}} id {{clientId}}" +ContentTypesInfo: Allowed file types {{allowedContentTypes}} \ No newline at end of file diff --git a/modules/client/front/dms/locale/es.yml b/modules/client/front/dms/locale/es.yml new file mode 100644 index 000000000..4185098f3 --- /dev/null +++ b/modules/client/front/dms/locale/es.yml @@ -0,0 +1,14 @@ +Upload file: Subir fichero +Edit file: Editar fichero +Upload: Subir +File: Fichero +ClientFileDescription: "{{dmsTypeName}} del cliente {{clientName}} id {{clientId}}" +ContentTypesInfo: "Tipos de archivo permitidos: {{allowedContentTypes}}" +Generate identifier for original file: Generar identificador para archivo original +File management: Gestión documental +Hard copy: Copia +This file will be deleted: Este fichero va a ser borrado +Are you sure?: Estas seguro? +File deleted: Fichero eliminado +Remove file: Eliminar fichero +Download file: Descargar fichero \ No newline at end of file diff --git a/modules/client/front/fiscal-data/index.html b/modules/client/front/fiscal-data/index.html new file mode 100644 index 000000000..524873f86 --- /dev/null +++ b/modules/client/front/fiscal-data/index.html @@ -0,0 +1,152 @@ + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + diff --git a/modules/client/front/fiscal-data/index.js b/modules/client/front/fiscal-data/index.js new file mode 100644 index 000000000..8a2d85109 --- /dev/null +++ b/modules/client/front/fiscal-data/index.js @@ -0,0 +1,67 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($scope, $http, vnApp, $translate) { + this.$ = $scope; + this.$http = $http; + this.vnApp = vnApp; + this.translate = $translate; + this.isEqualizated = undefined; + this.copyData(); + } + + $onChanges() { + this.copyData(); + } + + copyData() { + if (this.client) + this.isEqualizated = this.client.isEqualizated; + } + + buyerHaspermissions() { + if (!this.client) return true; + return !this.client.isTaxDataChecked; + } + + onSubmit() { + if (this.isEqualizated != this.client.isEqualizated) { + this.oldHasToInvoiceByAddress = this.client.hasToInvoiceByAddress; + this.client.hasToInvoiceByAddress = false; + } + + return this.$.watcher.submit().then( + () => this.checkEtChanges()); + } + + checkEtChanges() { + let equals = this.isEqualizated == this.client.isEqualizated; + this.isEqualizated = this.client.isEqualizated; + + if (!equals && !this.oldHasToInvoiceByAddress) + this.$.propagateIsEqualizated.show(); + else if (!equals) + this.returnDialogEt('accept'); + + delete this.oldHasToInvoiceByAddress; + } + + returnDialogEt(response) { + if (response === 'accept') { + this.$http.patch(`Clients/${this.client.id}/addressesPropagateRe`, {isEqualizated: this.client.isEqualizated}).then( + () => this.vnApp.showMessage(this.translate.instant('Equivalent tax spreaded')) + ); + } + } +} + +Controller.$inject = ['$scope', '$http', 'vnApp', '$translate']; + +ngModule.component('vnClientFiscalData', { + template: require('./index.html'), + controller: Controller, + require: {card: '^vnClientCard'}, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/fiscal-data/index.spec.js b/modules/client/front/fiscal-data/index.spec.js new file mode 100644 index 000000000..5b5c5eab8 --- /dev/null +++ b/modules/client/front/fiscal-data/index.spec.js @@ -0,0 +1,28 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientFiscalData', () => { + let $httpBackend; + let $scope; + let controller; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + controller = $componentController('vnClientFiscalData', {$scope}); + controller.card = {reload: () => {}}; + })); + + describe('returnDialogEt()', () => { + it('should request to patch the propagation of tax status', () => { + controller.client = {id: 123, isEqualizated: false}; + $httpBackend.when('PATCH', `Clients/${controller.client.id}/addressesPropagateRe`, {isEqualizated: controller.client.isEqualizated}).respond('done'); + $httpBackend.expectPATCH(`Clients/${controller.client.id}/addressesPropagateRe`, {isEqualizated: controller.client.isEqualizated}); + controller.returnDialogEt('accept'); + $httpBackend.flush(); + }); + }); + }); +}); diff --git a/modules/client/front/fiscal-data/locale/es.yml b/modules/client/front/fiscal-data/locale/es.yml new file mode 100644 index 000000000..4cadd236f --- /dev/null +++ b/modules/client/front/fiscal-data/locale/es.yml @@ -0,0 +1,6 @@ +Yes, notify: Sí, notificar +You changed the equalization tax: Has cambiado el recargo de equivalencia +Do you want to spread the change?: ¿Deseas propagar el cambio a sus consignatarios? +Frozen: Congelado +In order to invoice, this field is not consulted, but the consignee's ET. When modifying this field if the invoice by address option is not checked, the change will be automatically propagated to all addresses, otherwise the user will be asked if he wants to propagate it or not.: Para facturar no se consulta este campo, sino el RE de consignatario. Al modificar este campo si no esta marcada la casilla Facturar por consignatario, se propagará automáticamente el cambio a todos los consignatarios, en caso contrario preguntará al usuario si quiere o no propagar. +You can use letters and spaces: Se pueden utilizar letras y espacios \ No newline at end of file diff --git a/modules/client/front/greuge/create/index.html b/modules/client/front/greuge/create/index.html new file mode 100644 index 000000000..f2eeacd88 --- /dev/null +++ b/modules/client/front/greuge/create/index.html @@ -0,0 +1,45 @@ + + + +
    + + + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/modules/client/front/greuge/create/index.js b/modules/client/front/greuge/create/index.js new file mode 100644 index 000000000..b0a2eec93 --- /dev/null +++ b/modules/client/front/greuge/create/index.js @@ -0,0 +1,34 @@ +import ngModule from '../../module'; + +class Controller { + constructor($scope, $state, $filter) { + this.$ = $scope; + this.$state = $state; + this.greuge = { + shipped: new Date(), + clientFk: $state.params.id + }; + } + + cancel() { + this.goToIndex(); + } + + goToIndex() { + this.$state.go('client.card.greuge.index'); + } + + onSubmit() { + this.$.watcher.submit().then( + () => { + this.goToIndex(); + } + ); + } +} +Controller.$inject = ['$scope', '$state', '$filter']; + +ngModule.component('vnClientGreugeCreate', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/client/front/greuge/create/index.spec.js b/modules/client/front/greuge/create/index.spec.js new file mode 100644 index 000000000..76b361cc5 --- /dev/null +++ b/modules/client/front/greuge/create/index.spec.js @@ -0,0 +1,37 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientGreugeCreate', () => { + let $componentController; + let $scope; + let $state; + let controller; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$state_) => { + $componentController = _$componentController_; + $scope = $rootScope.$new(); + $state = _$state_; + $scope.watcher = { + submit: () => { + return { + then: callback => { + callback(); + } + }; + } + }; + controller = $componentController('vnClientGreugeCreate', {$scope: $scope}); + })); + + describe('onSubmit()', () => { + it('should call the function go() on $state to go to the greuges list', () => { + spyOn($state, 'go'); + controller.onSubmit(); + + expect(controller.$state.go).toHaveBeenCalledWith('client.card.greuge.index'); + }); + }); + }); +}); diff --git a/modules/client/front/greuge/index/index.html b/modules/client/front/greuge/index/index.html new file mode 100644 index 000000000..636caaca2 --- /dev/null +++ b/modules/client/front/greuge/index/index.html @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + Date + Comment + Type + Amount + + + + + {{::greuge.shipped | date:'dd/MM/yyyy HH:mm' }} + {{::greuge.description}} + {{::greuge.greugeType.name}} + {{::greuge.amount | currency: 'EUR': 2}} + + + + + + + + diff --git a/modules/client/front/greuge/index/index.js b/modules/client/front/greuge/index/index.js new file mode 100644 index 000000000..b89b01d7e --- /dev/null +++ b/modules/client/front/greuge/index/index.js @@ -0,0 +1,25 @@ +import ngModule from '../../module'; + +class Controller { + constructor($stateParams) { + this.$stateParams = $stateParams; + this.filter = { + include: [ + { + relation: 'greugeType', + scope: { + fields: ['id', 'name'] + } + } + ], + order: 'shipped DESC, amount' + }; + } +} + +Controller.$inject = ['$stateParams']; + +ngModule.component('vnClientGreugeIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/client/front/greuge/index/locale/es.yml b/modules/client/front/greuge/index/locale/es.yml new file mode 100644 index 000000000..513e6ff7b --- /dev/null +++ b/modules/client/front/greuge/index/locale/es.yml @@ -0,0 +1,4 @@ +Date: Fecha +Comment: Comentario +Amount: Importe +Type: Tipo \ No newline at end of file diff --git a/modules/client/front/index.js b/modules/client/front/index.js new file mode 100644 index 000000000..324046206 --- /dev/null +++ b/modules/client/front/index.js @@ -0,0 +1,42 @@ +export * from './module'; + +import './main'; +import './index/'; +import './card'; +import './create'; +import './basic-data'; +import './fiscal-data'; +import './billing-data'; +import './descriptor'; +import './descriptor-popover'; +import './search-panel'; +import './address/index'; +import './address/create'; +import './address/edit'; +import './note/index'; +import './note/create'; +import './web-access'; +import './credit/index'; +import './credit/create'; +import './greuge/index'; +import './greuge/create'; +import './balance/index'; +import './balance/create'; +import './mandate'; +import './summary'; +import './recovery/index'; +import './recovery/create'; +import './credit-insurance/index'; +import './credit-insurance/create'; +import './credit-insurance/insurance/index'; +import './credit-insurance/insurance/create'; +import './contact'; +import './sample/index'; +import './sample/create'; +import './web-payment'; +import './log'; +import './sms'; +import './postcode'; +import './dms/index'; +import './dms/create'; +import './dms/edit'; diff --git a/modules/client/front/index/index.html b/modules/client/front/index/index.html new file mode 100644 index 000000000..35a5234aa --- /dev/null +++ b/modules/client/front/index/index.html @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/client/front/index/index.js b/modules/client/front/index/index.js new file mode 100644 index 000000000..56ab594ff --- /dev/null +++ b/modules/client/front/index/index.js @@ -0,0 +1,59 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($scope, $state) { + this.$ = $scope; + this.$state = $state; + this.clientSelected = null; + } + + exprBuilder(param, value) { + switch (param) { + case 'search': + return /^\d+$/.test(value) + ? {id: value} + : {name: {like: `%${value}%`}}; + case 'phone': + return { + or: [ + {phone: value}, + {mobile: value} + ] + }; + case 'name': + case 'socialName': + case 'city': + return {[param]: {like: `%${value}%`}}; + case 'id': + case 'fi': + case 'postcode': + case 'email': + case 'salesPersonFk': + return {[param]: value}; + } + } + + openSummary(client, event) { + if (event.defaultPrevented) return; + event.preventDefault(); + event.stopPropagation(); + + this.clientSelected = client; + this.$.dialogSummaryClient.show(); + } + + filterTickets(client, event) { + if (event.defaultPrevented) return; + event.preventDefault(); + event.stopPropagation(); + + this.$state.go(`ticket.index`, + {q: JSON.stringify({clientFk: client.id})}); + } +} +Controller.$inject = ['$scope', '$state']; + +ngModule.component('vnClientIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/client/front/index/index.spec.js b/modules/client/front/index/index.spec.js new file mode 100644 index 000000000..da149838d --- /dev/null +++ b/modules/client/front/index/index.spec.js @@ -0,0 +1,25 @@ +import './index'; + +describe('Client index', () => { + let $state; + let controller; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, _$state_) => { + $state = _$state_; + controller = $componentController('vnClientIndex'); + })); + + describe('filterTickets()', () => { + it('should navigate to the ticket index using params as filter', () => { + const client = {id: 101}; + const event = new MouseEvent('click', {cancelable: true}); + spyOn($state, 'go'); + + controller.filterTickets(client, event); + + expect($state.go).toHaveBeenCalledWith('ticket.index', jasmine.any(Object)); + }); + }); +}); diff --git a/modules/client/front/index/locale/es.yml b/modules/client/front/index/locale/es.yml new file mode 100644 index 000000000..bfbbbddd0 --- /dev/null +++ b/modules/client/front/index/locale/es.yml @@ -0,0 +1,6 @@ +Client id: Id cliente +Phone: Teléfono +Town/City: Ciudad +Email: E-mail +View client: Ver cliente +Client tickets: Listado de tickets del cliente \ No newline at end of file diff --git a/modules/client/front/locale/es.yml b/modules/client/front/locale/es.yml new file mode 100644 index 000000000..1b44b5652 --- /dev/null +++ b/modules/client/front/locale/es.yml @@ -0,0 +1,58 @@ +Active: Activo +Amount: Importe +Client: Cliente +Comercial Name: Comercial +Has to invoice: Factura +Invoice by mail: Factura via e-mail +Country: País +Street: Domicilio fiscal +City: Municipio +Postcode: Código postal +Province: Provincia +Address: Consignatario +Verified data: Datos comprobados +Remove contact: Quitar contacto +Client ticket list: Listado de tickets del cliente +Add contact: Añadir contacto +Sent: Enviado +Worker: Trabajador +Sample: Plantilla +Credit: Crédito +Are you sure you want to delete this expedition?: ¿Está seguro de eliminar esta expedición? +Others: Otros +New order: Nuevo pedido +Client frozen: Cliente congelado +Client has debt: Cliente con riesgo +Client inactive: Cliente inactivo +Client not checked: Cliente no comprobado +Credit insurance: Crédito asegurado +Web Account inactive: Sin acceso Web +Search client by id or name: Buscar clientes por identificador o nombre + +# Sections + +Clients: Clientes +New client: Nuevo cliente +Fiscal data: Datos fiscales +Billing data: Forma de pago +Addresses: Consignatarios +New address: Nuevo consignatario +Edit address: Editar consignatario +Web access: Acceso web +Notes: Notas +New note: Nueva nota +Credits: Créditos +New credit: Nuevo crédito +New greuge: Nuevo greuge +Mandates: Mandatos +Invoices: Facturas +Recoveries: Recobros +New recovery: Nuevo recobro +Credit contracts: Contratos de crédito +New contract: Nuevo contrato +Edit contract: Editar contrato +Requested credits: Créditos solicitados +Contacts: Contactos +Samples: Plantillas +Send sample: Enviar plantilla +Log: Historial \ No newline at end of file diff --git a/modules/client/front/log/index.html b/modules/client/front/log/index.html new file mode 100644 index 000000000..90874d0cb --- /dev/null +++ b/modules/client/front/log/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/modules/client/front/log/index.js b/modules/client/front/log/index.js new file mode 100644 index 000000000..2f01d229c --- /dev/null +++ b/modules/client/front/log/index.js @@ -0,0 +1,15 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $stateParams) { + this.$scope = $scope; + this.$stateParams = $stateParams; + } +} + +Controller.$inject = ['$scope', '$stateParams']; + +ngModule.component('vnClientLog', { + template: require('./index.html'), + controller: Controller, +}); diff --git a/modules/client/front/main/index.html b/modules/client/front/main/index.html new file mode 100644 index 000000000..1ae1d211b --- /dev/null +++ b/modules/client/front/main/index.html @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/modules/client/front/main/index.js b/modules/client/front/main/index.js new file mode 100644 index 000000000..890165a19 --- /dev/null +++ b/modules/client/front/main/index.js @@ -0,0 +1,9 @@ +import ngModule from '../module'; +import ModuleMain from 'salix/components/module-main'; + +export default class Client extends ModuleMain {} + +ngModule.vnComponent('vnClient', { + controller: Client, + template: require('./index.html') +}); diff --git a/modules/client/front/mandate/index.html b/modules/client/front/mandate/index.html new file mode 100644 index 000000000..79016761f --- /dev/null +++ b/modules/client/front/mandate/index.html @@ -0,0 +1,36 @@ + + + + + + + + Id + Company + Type + Register date + End date + + + + + {{::mandate.id}} + {{::mandate.company.code}} + {{::mandate.mandateType.name}} + {{::mandate.created | date:'dd/MM/yyyy HH:mm' }} + {{::mandate.finished | date:'dd/MM/yyyy HH:mm' || '-'}} + + + + + \ No newline at end of file diff --git a/modules/client/front/mandate/index.js b/modules/client/front/mandate/index.js new file mode 100644 index 000000000..607bb335b --- /dev/null +++ b/modules/client/front/mandate/index.js @@ -0,0 +1,29 @@ +import ngModule from '../module'; + +class Controller { + constructor($stateParams) { + this.$stateParams = $stateParams; + this.filter = { + include: [ + { + relation: 'mandateType', + scope: { + fields: ['id', 'name'] + } + }, { + relation: 'company', + scope: { + fields: ['id', 'code'] + } + } + ] + }; + } +} + +Controller.$inject = ['$stateParams']; + +ngModule.component('vnClientMandate', { + template: require('./index.html'), + controller: Controller +}); diff --git a/client/client/src/mandate/locale/es.yml b/modules/client/front/mandate/locale/es.yml similarity index 100% rename from client/client/src/mandate/locale/es.yml rename to modules/client/front/mandate/locale/es.yml diff --git a/modules/client/front/module.js b/modules/client/front/module.js new file mode 100644 index 000000000..a42e20d42 --- /dev/null +++ b/modules/client/front/module.js @@ -0,0 +1,3 @@ +import {ng} from 'core/vendor'; + +export default ng.module('client', ['salix']); diff --git a/modules/client/front/note/create/index.html b/modules/client/front/note/create/index.html new file mode 100644 index 000000000..c9c351199 --- /dev/null +++ b/modules/client/front/note/create/index.html @@ -0,0 +1,24 @@ + + +
    + + + + + + + + + + +
    \ No newline at end of file diff --git a/modules/client/front/note/create/index.js b/modules/client/front/note/create/index.js new file mode 100644 index 000000000..75c7ebc80 --- /dev/null +++ b/modules/client/front/note/create/index.js @@ -0,0 +1,21 @@ +import ngModule from '../../module'; + +export default class Controller { + constructor($state) { + this.$state = $state; + this.note = { + clientFk: parseInt($state.params.id), + text: null + }; + } + + cancel() { + this.$state.go('client.card.note.index', {id: this.$state.params.id}); + } +} +Controller.$inject = ['$state']; + +ngModule.component('vnNoteCreate', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/client/front/note/create/index.spec.js b/modules/client/front/note/create/index.spec.js new file mode 100644 index 000000000..5ac62efa3 --- /dev/null +++ b/modules/client/front/note/create/index.spec.js @@ -0,0 +1,23 @@ +import './index'; + +describe('Client', () => { + describe('Component vnNoteCreate', () => { + let $componentController; + let $state; + let controller; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject((_$componentController_, _$state_) => { + $componentController = _$componentController_; + $state = _$state_; + $state.params.id = '1234'; + controller = $componentController('vnNoteCreate', {$state: $state}); + })); + + it('should define clientFk using $state.params.id', () => { + expect(controller.note.clientFk).toBe(1234); + expect(controller.note.client).toBe(undefined); + }); + }); +}); diff --git a/client/client/src/note-create/locale/es.yml b/modules/client/front/note/create/locale/es.yml similarity index 100% rename from client/client/src/note-create/locale/es.yml rename to modules/client/front/note/create/locale/es.yml diff --git a/modules/client/front/note/index/index.html b/modules/client/front/note/index/index.html new file mode 100644 index 000000000..a77362ff6 --- /dev/null +++ b/modules/client/front/note/index/index.html @@ -0,0 +1,31 @@ + + + + +
    + + {{::note.worker.user.nickname}} + {{::note.created | date:'dd/MM/yyyy HH:mm'}} + + + {{::note.text}} + +
    +
    +
    + + + diff --git a/modules/client/front/note/index/index.js b/modules/client/front/note/index/index.js new file mode 100644 index 000000000..ef1f0d5fb --- /dev/null +++ b/modules/client/front/note/index/index.js @@ -0,0 +1,21 @@ +import ngModule from '../../module'; +import './style.scss'; + +export default class Controller { + constructor($stateParams) { + this.$stateParams = $stateParams; + this.filter = { + order: 'created DESC', + }; + } +} + +Controller.$inject = ['$stateParams']; + +ngModule.component('vnClientNote', { + template: require('./index.html'), + controller: Controller, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/note/index/style.scss b/modules/client/front/note/index/style.scss new file mode 100644 index 000000000..44ae2cee7 --- /dev/null +++ b/modules/client/front/note/index/style.scss @@ -0,0 +1,5 @@ +vn-client-note { + .note:last-child { + margin-bottom: 0; + } +} \ No newline at end of file diff --git a/modules/client/front/postcode/index.html b/modules/client/front/postcode/index.html new file mode 100644 index 000000000..55990281c --- /dev/null +++ b/modules/client/front/postcode/index.html @@ -0,0 +1,50 @@ + + +
    New postcode
    +

    Please, ensure you put the correct data!

    + + + + + + + + + + + + +
    + + + + +
    \ No newline at end of file diff --git a/modules/client/front/postcode/index.js b/modules/client/front/postcode/index.js new file mode 100644 index 000000000..bbf0b1953 --- /dev/null +++ b/modules/client/front/postcode/index.js @@ -0,0 +1,70 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + constructor($element, $scope, $http, $translate, vnApp) { + super($element, $scope); + this.$ = $scope; + this.$http = $http; + this.$translate = $translate; + this.vnApp = vnApp; + } + + get townSelection() { + return this._townSelection; + } + + set townSelection(selection) { + this._townSelection = selection; + + if (!selection) return; + + const province = selection.province; + const country = province.country; + + this.data.provinceFk = province.id; + this.data.countryFk = country.id; + } + + open() { + this.$.postcodeDialog.show(); + } + + onOpen() { + this.$.postcode.focus(); + } + + onResponse(response) { + if (response == 'accept') { + try { + if (!this.data.code) + throw new Error(`The postcode can't be empty`); + if (!this.data.townFk) + throw new Error(`The town can't be empty`); + + this.$http.patch(`postcodes`, this.data).then(response => { + if (response.data) { + this.vnApp.showMessage(this.$translate.instant('The postcode has been saved')); + + this.emit('response', {response: response.data}); + } + }); + } catch (e) { + this.vnApp.showError(this.$translate.instant(e.message)); + return false; + } + } + return true; + } +} + +Controller.$inject = ['$element', '$scope', '$http', '$translate', 'vnApp']; + +ngModule.component('vnClientPostcode', { + template: require('./index.html'), + controller: Controller, + bindings: { + data: '<', + } +}); diff --git a/modules/client/front/postcode/index.spec.js b/modules/client/front/postcode/index.spec.js new file mode 100644 index 000000000..2ca3f8c7b --- /dev/null +++ b/modules/client/front/postcode/index.spec.js @@ -0,0 +1,34 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientPostcode', () => { + let controller; + let $httpBackend; + let $element; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + $element = angular.element(''); + controller = $componentController('vnClientPostcode', {$element}); + controller.client = {id: 101}; + })); + + describe('onResponse()', () => { + it('should perform a POST query and show a success snackbar', () => { + let params = {townFk: 1, provinceFk: 1, countryFk: 1, code: '46460'}; + controller.data = {townFk: 1, provinceFk: 1, countryFk: 1, code: '46460'}; + + spyOn(controller.vnApp, 'showMessage'); + $httpBackend.when('PATCH', `postcodes`, params).respond(200, params); + $httpBackend.expect('PATCH', `postcodes`, params).respond(params); + + controller.onResponse('accept'); + $httpBackend.flush(); + + expect(controller.vnApp.showMessage).toHaveBeenCalledWith('The postcode has been saved'); + }); + }); + }); +}); diff --git a/modules/client/front/postcode/locale/es.yml b/modules/client/front/postcode/locale/es.yml new file mode 100644 index 000000000..ab8b0fc21 --- /dev/null +++ b/modules/client/front/postcode/locale/es.yml @@ -0,0 +1,5 @@ +New postcode: Nuevo código postal +Please, ensure you put the correct data!: ¡Por favor, asegúrate de poner los datos correctos! +The postcode can't be empty: El código postal no puede quedar vacío +The town can't be empty: La población no puede quedar vacía +The postcode has been saved: El código postal ha sido guardado \ No newline at end of file diff --git a/modules/client/front/postcode/style.scss b/modules/client/front/postcode/style.scss new file mode 100644 index 000000000..b9ef984b7 --- /dev/null +++ b/modules/client/front/postcode/style.scss @@ -0,0 +1,9 @@ +@import "variables"; + +vn-client-postcode { + vn-dialog { + p { + color: $color-alert + } + } +} \ No newline at end of file diff --git a/modules/client/front/recovery/create/index.html b/modules/client/front/recovery/create/index.html new file mode 100644 index 000000000..56eb7eeb7 --- /dev/null +++ b/modules/client/front/recovery/create/index.html @@ -0,0 +1,42 @@ + + + +
    + + + + + + + + + + + + + + + + +
    diff --git a/modules/client/front/recovery/create/index.js b/modules/client/front/recovery/create/index.js new file mode 100644 index 000000000..ee69e0861 --- /dev/null +++ b/modules/client/front/recovery/create/index.js @@ -0,0 +1,34 @@ +import ngModule from '../../module'; + +class Controller { + constructor($scope, $state, $filter) { + this.$ = $scope; + this.$state = $state; + this.recovery = { + started: new Date() + }; + } + + cancel() { + this.goToIndex(); + } + + goToIndex() { + this.$state.go('client.card.recovery.index'); + } + + onSubmit() { + this.recovery.clientFk = this.$state.params.id; + this.$.watcher.submit().then( + () => { + this.goToIndex(); + } + ); + } +} +Controller.$inject = ['$scope', '$state', '$filter']; + +ngModule.component('vnClientRecoveryCreate', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/client/front/recovery/create/index.spec.js b/modules/client/front/recovery/create/index.spec.js new file mode 100644 index 000000000..d1d3f39f2 --- /dev/null +++ b/modules/client/front/recovery/create/index.spec.js @@ -0,0 +1,37 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientRecoveryCreate', () => { + let $componentController; + let $scope; + let $state; + let controller; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$state_) => { + $componentController = _$componentController_; + $scope = $rootScope.$new(); + $state = _$state_; + $scope.watcher = { + submit: () => { + return { + then: callback => { + callback(); + } + }; + } + }; + controller = $componentController('vnClientRecoveryCreate', {$scope: $scope}); + })); + + describe('onSubmit()', () => { + it('should call the function go() on $state to go to the recovery list', () => { + spyOn($state, 'go'); + controller.onSubmit(); + + expect(controller.$state.go).toHaveBeenCalledWith('client.card.recovery.index'); + }); + }); + }); +}); diff --git a/modules/client/front/recovery/create/locale/es.yml b/modules/client/front/recovery/create/locale/es.yml new file mode 100644 index 000000000..29877c03c --- /dev/null +++ b/modules/client/front/recovery/create/locale/es.yml @@ -0,0 +1 @@ +Period: Periodo \ No newline at end of file diff --git a/modules/client/front/recovery/index/index.html b/modules/client/front/recovery/index/index.html new file mode 100644 index 000000000..d5c28dc88 --- /dev/null +++ b/modules/client/front/recovery/index/index.html @@ -0,0 +1,53 @@ + + + + + + + + + Since + To + Amount + Period + + + + + + + + + {{::recovery.started | date:'dd/MM/yyyy' }} + {{recovery.finished | date:'dd/MM/yyyy' }} + {{::recovery.amount | currency: 'EUR': 0}} + {{::recovery.period}} + + + + + + + diff --git a/modules/client/front/recovery/index/index.js b/modules/client/front/recovery/index/index.js new file mode 100644 index 000000000..b291ddc04 --- /dev/null +++ b/modules/client/front/recovery/index/index.js @@ -0,0 +1,25 @@ +import ngModule from '../../module'; + +class Controller { + constructor($stateParams, $scope, $http) { + this.$stateParams = $stateParams; + this.$scope = $scope; + this.$http = $http; + } + + setFinished(recovery) { + if (!recovery.finished) { + let params = {finished: Date.now()}; + this.$http.patch(`Recoveries/${recovery.id}`, params).then( + () => this.$scope.model.refresh() + ); + } + } +} + +Controller.$inject = ['$stateParams', '$scope', '$http']; + +ngModule.component('vnClientRecoveryIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/client/front/recovery/index/locale/es.yml b/modules/client/front/recovery/index/locale/es.yml new file mode 100644 index 000000000..0cb5b3ed6 --- /dev/null +++ b/modules/client/front/recovery/index/locale/es.yml @@ -0,0 +1,4 @@ +Since: Desde +Employee: Empleado +To: Hasta +Finish that recovery period: Terminar el recobro \ No newline at end of file diff --git a/modules/client/front/routes.json b/modules/client/front/routes.json new file mode 100644 index 000000000..ef0d8cc7a --- /dev/null +++ b/modules/client/front/routes.json @@ -0,0 +1,355 @@ +{ + "module": "client", + "name": "Clients", + "icon": "icon-person", + "validations" : true, + "dependencies": ["worker", "invoiceOut"], + "menus": { + "main": [ + {"state": "client.index", "icon": "icon-person"} + ], + "card": [ + {"state": "client.card.basicData", "icon": "settings"}, + {"state": "client.card.fiscalData", "icon": "account_balance"}, + {"state": "client.card.billingData", "icon": "icon-payment"}, + {"state": "client.card.address.index", "icon": "icon-delivery"}, + {"state": "client.card.note.index", "icon": "insert_drive_file"}, + {"state": "client.card.credit.index", "icon": "credit_card"}, + {"state": "client.card.greuge.index", "icon": "work"}, + {"state": "client.card.balance.index", "icon": "icon-invoices"}, + {"state": "client.card.recovery.index", "icon": "icon-recovery"}, + {"state": "client.card.log", "icon": "history"}, + { + "description": "Others", + "icon": "more", + "childs": [ + {"state": "client.card.webAccess", "icon": "cloud"}, + {"state": "client.card.mandate", "icon": "pan_tool"}, + {"state": "client.card.creditInsurance.index", "icon": "icon-solunion"}, + {"state": "client.card.contact", "icon": "contact_phone"}, + {"state": "client.card.sample.index", "icon": "mail"}, + {"state": "client.card.webPayment", "icon": "icon-onlinepayment"}, + {"state": "client.card.dms.index", "icon": "cloud_upload"} + ] + } + ] + }, + "keybindings": [ + {"key": "c", "state": "client.index"} + ], + "routes": [ + { + "url": "/client", + "state": "client", + "abstract": true, + "component": "vn-client", + "description": "Clients", + "acl": ["employee"] + }, { + "url": "/index?q", + "state": "client.index", + "component": "vn-client-index", + "description": "Clients" + }, { + "url": "/create", + "state": "client.create", + "component": "vn-client-create", + "description": "New client" + }, { + "url": "/:id?sendSMS&phone&message", + "state": "client.card", + "abstract": true, + "component": "vn-client-card" + }, { + "url": "/summary", + "state": "client.card.summary", + "component": "vn-client-summary", + "description": "Summary", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/basic-data", + "state": "client.card.basicData", + "component": "vn-client-basic-data", + "description": "Basic data", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/fiscal-data", + "state": "client.card.fiscalData", + "component": "vn-client-fiscal-data", + "description": "Fiscal data", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/billing-data", + "state": "client.card.billingData", + "component": "vn-client-billing-data", + "description": "Billing data", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/address", + "state": "client.card.address", + "component": "ui-view", + "abstract": true + }, { + "url": "/index", + "state": "client.card.address.index", + "component": "vn-client-address-index", + "description": "Addresses", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/create", + "state": "client.card.address.create", + "component": "vn-client-address-create", + "description": "New address", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/:addressId/edit", + "state": "client.card.address.edit", + "component": "vn-client-address-edit", + "description": "Edit address" + }, { + "url": "/web-access", + "state": "client.card.webAccess", + "component": "vn-client-web-access", + "description": "Web access", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/note", + "state": "client.card.note", + "component": "ui-view", + "abstract": true + }, { + "url": "/index", + "state": "client.card.note.index", + "component": "vn-client-note", + "description": "Notes", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/create", + "state": "client.card.note.create", + "component": "vn-note-create", + "description": "New note" + }, { + "url": "/credit", + "abstract": true, + "state": "client.card.credit", + "component": "ui-view" + }, { + "url": "/index", + "state": "client.card.credit.index", + "component": "vn-client-credit-index", + "description": "Credits", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/create", + "state": "client.card.credit.create", + "component": "vn-client-credit-create", + "description": "New credit", + "acl": ["teamBoss"], + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/greuge", + "abstract": true, + "state": "client.card.greuge", + "component": "ui-view" + }, { + "url": "/index", + "state": "client.card.greuge.index", + "component": "vn-client-greuge-index", + "description": "Greuges", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/create", + "state": "client.card.greuge.create", + "component": "vn-client-greuge-create", + "description": "New greuge", + "acl": ["salesAssistant"], + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/mandate", + "state": "client.card.mandate", + "component": "vn-client-mandate", + "description": "Mandates" + }, { + "url": "/balance", + "abstract": true, + "state": "client.card.balance", + "component": "ui-view" + }, { + "url": "/index", + "state": "client.card.balance.index", + "component": "vn-client-balance-index", + "description": "Balance", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/create?payed&companyFk&bankFk&payedAmount", + "state": "client.card.balance.create", + "component": "vn-client-balance-create", + "description": "New payment", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/recovery", + "abstract": true, + "state": "client.card.recovery", + "component": "ui-view" + }, { + "url": "/index", + "state": "client.card.recovery.index", + "component": "vn-client-recovery-index", + "description": "Recoveries", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/create", + "state": "client.card.recovery.create", + "component": "vn-client-recovery-create", + "description": "New recovery", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/credit-insurance", + "abstract": true, + "state": "client.card.creditInsurance", + "component": "ui-view", + "acl": ["insurance"] + }, { + "url": "/index", + "state": "client.card.creditInsurance.index", + "component": "vn-client-credit-insurance-index", + "description": "Credit contracts", + "acl": ["insurance"], + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/create", + "state": "client.card.creditInsurance.create", + "component": "vn-client-credit-insurance-create", + "description": "New insurance", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/insurance", + "abstract": true, + "state": "client.card.creditInsurance.insurance", + "component": "ui-view", + "acl": ["insurance"] + }, { + "url": "/:classificationId/index", + "state": "client.card.creditInsurance.insurance.index", + "component": "vn-client-credit-insurance-insurance-index", + "description": "Requested credits", + "acl": ["insurance"], + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/:classificationId/create", + "state": "client.card.creditInsurance.insurance.create", + "component": "vn-client-credit-insurance-insurance-create", + "description": "New credit", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/contact", + "state": "client.card.contact", + "component": "vn-client-contact", + "description": "Contacts", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/sample", + "abstract": true, + "state": "client.card.sample", + "component": "ui-view" + }, { + "url": "/index", + "state": "client.card.sample.index", + "component": "vn-client-sample-index", + "description": "Samples", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/create", + "state": "client.card.sample.create", + "component": "vn-client-sample-create", + "description": "Send sample", + "params": { + "client": "$ctrl.client" + } + }, { + "url": "/web-payment", + "state": "client.card.webPayment", + "component": "vn-client-web-payment", + "description": "Web Payment" + }, { + "url" : "/log", + "state": "client.card.log", + "component": "vn-client-log", + "description": "Log" + }, + { + "url": "/dms", + "state": "client.card.dms", + "abstract": true, + "component": "ui-view" + }, + { + "url": "/index", + "state": "client.card.dms.index", + "component": "vn-client-dms-index", + "description": "File management" + }, + { + "url": "/create", + "state": "client.card.dms.create", + "component": "vn-client-dms-create", + "description": "Upload file", + "params": { + "client": "$ctrl.client" + } + }, + { + "url": "/:dmsId/edit", + "state": "client.card.dms.edit", + "component": "vn-client-dms-edit", + "description": "Edit file", + "params": { + "client": "$ctrl.client" + } + } + ] +} diff --git a/modules/client/front/sample/create/index.html b/modules/client/front/sample/create/index.html new file mode 100644 index 000000000..6a87d55b6 --- /dev/null +++ b/modules/client/front/sample/create/index.html @@ -0,0 +1,57 @@ + + + + + +
    + + + + + + + + + + + + + + + + + +
    + + + +
    + +
    +
    +
    diff --git a/modules/client/front/sample/create/index.js b/modules/client/front/sample/create/index.js new file mode 100644 index 000000000..49d90f569 --- /dev/null +++ b/modules/client/front/sample/create/index.js @@ -0,0 +1,108 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + constructor($element, $, vnApp, $httpParamSerializer, vnConfig) { + super($element, $); + this.vnApp = vnApp; + this.$httpParamSerializer = $httpParamSerializer; + this.vnConfig = vnConfig; + this.clientSample = { + clientFk: this.$params.id, + companyFk: vnConfig.companyFk + }; + } + + get client() { + return this._client; + } + + set client(value) { + this._client = value; + + if (value) + this.clientSample.recipient = value.email; + } + + get companyId() { + if (!this.clientSample.companyFk) + this.clientSample.companyFk = this.vnConfig.companyFk; + return this.clientSample.companyFk; + } + + set companyId(value) { + this.clientSample.companyFk = value; + } + + showPreview() { + let sampleType = this.$.sampleType.selection; + + if (!sampleType) + return this.vnApp.showError(this.$translate.instant('Choose a sample')); + + if (sampleType.hasCompany && !this.clientSample.companyFk) + return this.vnApp.showError(this.$translate.instant('Choose a company')); + + const params = { + clientId: this.$params.id, + recipient: this.clientSample.recipient, + isPreview: true + }; + + if (sampleType.hasCompany) + params.companyId = this.clientSample.companyFk; + + const serializedParams = this.$httpParamSerializer(params); + const query = `email/${sampleType.code}?${serializedParams}`; + this.$http.get(query).then(res => { + this.$.showPreview.show(); + let dialog = document.body.querySelector('div.vn-dialog'); + let body = dialog.querySelector('tpl-body'); + let scroll = dialog.querySelector('div:first-child'); + + body.innerHTML = res.data; + scroll.scrollTop = 0; + }); + } + + onSubmit() { + this.$.watcher.check(); + this.$.watcher.realSubmit().then(() => + this.sendSample() + ); + } + + sendSample() { + let sampleType = this.$.sampleType.selection; + let params = { + clientId: this.$params.id, + recipient: this.clientSample.recipient + }; + + if (!sampleType) + return this.vnApp.showError(this.$translate.instant('Choose a sample')); + + if (sampleType.hasCompany && !this.clientSample.companyFk) + return this.vnApp.showError(this.$translate.instant('Choose a company')); + + if (sampleType.hasCompany) + params.companyId = this.clientSample.companyFk; + + const serializedParams = this.$httpParamSerializer(params); + const query = `email/${sampleType.code}?${serializedParams}`; + this.$http.get(query).then(res => { + this.vnApp.showSuccess(this.$translate.instant('Notification sent!')); + this.$state.go('client.card.sample.index'); + }); + } +} +Controller.$inject = ['$element', '$scope', 'vnApp', '$httpParamSerializer', 'vnConfig']; + +ngModule.component('vnClientSampleCreate', { + template: require('./index.html'), + controller: Controller, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/sample/create/index.spec.js b/modules/client/front/sample/create/index.spec.js new file mode 100644 index 000000000..efcda5401 --- /dev/null +++ b/modules/client/front/sample/create/index.spec.js @@ -0,0 +1,184 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientSampleCreate', () => { + let $httpParamSerializer; + let $scope; + let $element; + let $httpBackend; + let $state; + let controller; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_, $rootScope, _$state_, _$httpParamSerializer_) => { + $scope = $rootScope.$new(); + $scope.sampleType = {}; + $scope.watcher = { + check: () => {}, + realSubmit: () => { + return { + then: callback => { + callback(); + } + }; + } + }; + $scope.showPreview = { + element: { + querySelector: () => { + return { + innerHTML: () => {} + }; + } + }, + show: () => {} + }; + $state = _$state_; + $state.params.id = 101; + $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; + $element = angular.element(''); + controller = $componentController('vnClientSampleCreate', {$element, $scope}); + })); + + describe('showPreview()', () => { + it(`should perform a query (GET) and open a sample preview`, () => { + spyOn(controller.$.showPreview, 'show'); + const element = document.createElement('div'); + document.body.querySelector = () => { + return { + querySelector: () => { + return element; + } + }; + }; + + controller.$.sampleType.selection = { + hasCompany: false, + code: 'MyReport' + }; + + controller.clientSample = { + clientFk: 101 + }; + + let event = {preventDefault: () => {}}; + + const params = { + clientId: 101, + isPreview: true + }; + const serializedParams = $httpParamSerializer(params); + + $httpBackend.when('GET', `email/MyReport?${serializedParams}`).respond(true); + $httpBackend.expect('GET', `email/MyReport?${serializedParams}`); + controller.showPreview(event); + $httpBackend.flush(); + + expect(controller.$.showPreview.show).toHaveBeenCalledWith(); + }); + + it(`should perform a query (GET) with companyFk param and open a sample preview`, () => { + spyOn(controller.$.showPreview, 'show'); + const element = document.createElement('div'); + document.body.querySelector = () => { + return { + querySelector: () => { + return element; + } + }; + }; + + controller.$.sampleType.selection = { + hasCompany: true, + code: 'MyReport' + }; + + controller.clientSample = { + clientFk: 101, + companyFk: 442 + }; + + let event = {preventDefault: () => {}}; + + const params = { + clientId: 101, + companyId: 442, + isPreview: true + }; + const serializedParams = $httpParamSerializer(params); + + $httpBackend.when('GET', `email/MyReport?${serializedParams}`).respond(true); + $httpBackend.expect('GET', `email/MyReport?${serializedParams}`); + controller.showPreview(event); + $httpBackend.flush(); + + expect(controller.$.showPreview.show).toHaveBeenCalledWith(); + }); + }); + + describe('onSubmit()', () => { + it(`should call sendSample() method`, () => { + spyOn(controller, 'sendSample'); + controller.onSubmit(); + + expect(controller.sendSample).toHaveBeenCalledWith(); + }); + }); + + describe('sendSample()', () => { + it(`should perform a query (GET) and call go() method`, () => { + spyOn(controller.$state, 'go'); + + controller.$.sampleType.selection = { + hasCompany: false, + code: 'MyReport' + }; + + controller.clientSample = { + clientFk: 101 + }; + + const params = { + clientId: 101 + }; + const serializedParams = $httpParamSerializer(params); + + $httpBackend.when('GET', `email/MyReport?${serializedParams}`).respond(true); + $httpBackend.expect('GET', `email/MyReport?${serializedParams}`); + controller.sendSample(); + $httpBackend.flush(); + + expect(controller.$state.go).toHaveBeenCalledWith('client.card.sample.index'); + }); + + it(`should perform a query (GET) with companyFk param and call go() method`, () => { + spyOn(controller.$state, 'go'); + + controller.$.sampleType.selection = { + hasCompany: true, + code: 'MyReport' + }; + + controller.clientSample = { + clientFk: 101, + companyFk: 442 + }; + + const params = { + clientId: 101, + companyId: 442 + }; + const serializedParams = $httpParamSerializer(params); + + $httpBackend.when('GET', `email/MyReport?${serializedParams}`).respond(true); + $httpBackend.expect('GET', `email/MyReport?${serializedParams}`); + controller.sendSample(); + $httpBackend.flush(); + + expect(controller.$state.go).toHaveBeenCalledWith('client.card.sample.index'); + }); + }); + }); +}); diff --git a/modules/client/front/sample/create/locale/es.yml b/modules/client/front/sample/create/locale/es.yml new file mode 100644 index 000000000..d1ef82c0e --- /dev/null +++ b/modules/client/front/sample/create/locale/es.yml @@ -0,0 +1,3 @@ +Choose a sample: Selecciona una plantilla +Choose a company: Selecciona una empresa +Recipient: Destinatario \ No newline at end of file diff --git a/modules/client/front/sample/create/style.scss b/modules/client/front/sample/create/style.scss new file mode 100644 index 000000000..fdd01f729 --- /dev/null +++ b/modules/client/front/sample/create/style.scss @@ -0,0 +1,34 @@ +div.vn-dialog { + tpl-body.client-sample-dialog { + width: 800px; + + .container, .container h1 { + font-family: "Roboto","Helvetica","Arial",sans-serif; + font-size: 1em !important; + + h1 { + font-weight: bold; + margin: auto + } + + p { + margin: 1em 0 + } + + footer p { + font-size: 10px !important; + line-height: 10px + } + } + + + .title h1 { + font-size: 2em !important; + margin: 0 + } + + .loading { + text-align: center + } + } +} diff --git a/modules/client/front/sample/index/index.html b/modules/client/front/sample/index/index.html new file mode 100644 index 000000000..4825d4121 --- /dev/null +++ b/modules/client/front/sample/index/index.html @@ -0,0 +1,54 @@ + + + + + + + + Sent + Description + Worker + Company + + + + + {{::sample.created | date:'dd/MM/yyyy HH:mm' }} + + {{::sample.type.description}} + + + + {{::sample.worker.user.nickname}} + + + {{::sample.company.code}} + + + + + + + + + + + \ No newline at end of file diff --git a/modules/client/front/sample/index/index.js b/modules/client/front/sample/index/index.js new file mode 100644 index 000000000..4ce12e27c --- /dev/null +++ b/modules/client/front/sample/index/index.js @@ -0,0 +1,53 @@ +import ngModule from '../../module'; + +class Controller { + constructor($scope, $stateParams) { + this.$ = $scope; + this.$stateParams = $stateParams; + this.filter = { + include: [ + { + relation: 'type', + scope: { + fields: ['code', 'description'] + } + }, + { + relation: 'worker', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + }, + { + relation: 'company', + scope: { + fields: ['code'] + } + } + ] + }; + } + showWorkerDescriptor(event, workerFk) { + if (event.defaultPrevented) return; + + event.preventDefault(); + event.stopImmediatePropagation(); + + this.selectedWorker = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } +} + +Controller.$inject = ['$scope', '$stateParams']; + +ngModule.component('vnClientSampleIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/client/front/search-panel/index.html b/modules/client/front/search-panel/index.html new file mode 100644 index 000000000..579f044c1 --- /dev/null +++ b/modules/client/front/search-panel/index.html @@ -0,0 +1,76 @@ +
    +
    + + + + + + + + + + + + + + + {{firstName}} {{name}} + + + + + + + + + + + + + + + + + + + + + +
    +
    diff --git a/modules/client/front/search-panel/index.js b/modules/client/front/search-panel/index.js new file mode 100644 index 000000000..8c30982f5 --- /dev/null +++ b/modules/client/front/search-panel/index.js @@ -0,0 +1,7 @@ +import ngModule from '../module'; +import SearchPanel from 'core/components/searchbar/search-panel'; + +ngModule.component('vnClientSearchPanel', { + template: require('./index.html'), + controller: SearchPanel +}); diff --git a/modules/client/front/search-panel/locale/es.yml b/modules/client/front/search-panel/locale/es.yml new file mode 100644 index 000000000..93d2faf53 --- /dev/null +++ b/modules/client/front/search-panel/locale/es.yml @@ -0,0 +1,8 @@ +Client id: Id cliente +Tax number: NIF/CIF +Name: Nombre +Social name: Razon social +Town/City: Ciudad +Postcode: Código postal +Email: E-mail +Phone: Teléfono \ No newline at end of file diff --git a/modules/client/front/sms/index.html b/modules/client/front/sms/index.html new file mode 100644 index 000000000..501558512 --- /dev/null +++ b/modules/client/front/sms/index.html @@ -0,0 +1,26 @@ + + +
    Send SMS
    + + + + + + + + +
    + + + + +
    \ No newline at end of file diff --git a/modules/client/front/sms/index.js b/modules/client/front/sms/index.js new file mode 100644 index 000000000..580a02d27 --- /dev/null +++ b/modules/client/front/sms/index.js @@ -0,0 +1,38 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + constructor($element, $scope, $http, $translate, vnApp) { + super($element, $scope); + + this.$scope = $scope; + this.$http = $http; + this.$translate = $translate; + this.vnApp = vnApp; + } + + open() { + this.$scope.SMSDialog.show(); + } + + onResponse(response) { + if (response === 'accept') { + this.$http.post(`Sms/send`, this.sms).then(res => { + this.vnApp.showMessage(this.$translate.instant('SMS sent!')); + + if (res.data) this.emit('send', {response: res.data}); + }); + } + } +} + +Controller.$inject = ['$element', '$scope', '$http', '$translate', 'vnApp']; + +ngModule.component('vnClientSms', { + template: require('./index.html'), + controller: Controller, + bindings: { + sms: '<', + } +}); diff --git a/modules/client/front/sms/index.spec.js b/modules/client/front/sms/index.spec.js new file mode 100644 index 000000000..bda1cc013 --- /dev/null +++ b/modules/client/front/sms/index.spec.js @@ -0,0 +1,34 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientSms', () => { + let controller; + let $httpBackend; + let $element; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + $element = angular.element(''); + controller = $componentController('vnClientSms', {$element}); + controller.client = {id: 101}; + })); + + describe('onResponse()', () => { + it('should perform a POST query and show a success snackbar', () => { + let params = {destinationFk: 101, destination: 111111111, message: 'My SMS'}; + controller.sms = {destinationFk: 101, destination: 111111111, message: 'My SMS'}; + + spyOn(controller.vnApp, 'showMessage'); + $httpBackend.when('POST', `Sms/send`, params).respond(200, params); + $httpBackend.expect('POST', `Sms/send`, params).respond(params); + + controller.onResponse('accept'); + $httpBackend.flush(); + + expect(controller.vnApp.showMessage).toHaveBeenCalledWith('SMS sent!'); + }); + }); + }); +}); diff --git a/modules/client/front/sms/locale/es.yml b/modules/client/front/sms/locale/es.yml new file mode 100644 index 000000000..10247b926 --- /dev/null +++ b/modules/client/front/sms/locale/es.yml @@ -0,0 +1,4 @@ +Send SMS: Enviar SMS +Destination: Destinatario +Message: Mensaje +SMS sent!: ¡SMS enviado! \ No newline at end of file diff --git a/modules/client/front/sms/style.scss b/modules/client/front/sms/style.scss new file mode 100644 index 000000000..60a625880 --- /dev/null +++ b/modules/client/front/sms/style.scss @@ -0,0 +1,7 @@ +@import "variables"; + +vn-client-sms { + textarea { + height: 8em + } +} \ No newline at end of file diff --git a/modules/client/front/summary/index.html b/modules/client/front/summary/index.html new file mode 100644 index 000000000..eccf45873 --- /dev/null +++ b/modules/client/front/summary/index.html @@ -0,0 +1,200 @@ + +
    {{$ctrl.summary.name}} - {{$ctrl.summary.id}} - {{$ctrl.summary.salesPerson.user.nickname}}
    + + +

    Basic data

    + + + + + + + + + + + + + + + + +
    + +

    Fiscal address

    + + + + + + + + + + + + + + +
    + +

    Fiscal data

    + + + + + + + + + + + + + + + + +
    + +

    Pay method

    + + + + + + + + + + + + + + +
    + +

    Default address

    + + + + + + +
    + +

    Web access

    + + + + + + +
    + +

    Business data

    + + + + + + + + + + +
    + +

    Financial information

    + + + + + + + + + + + + + + +
    +
    +
    \ No newline at end of file diff --git a/modules/client/front/summary/index.js b/modules/client/front/summary/index.js new file mode 100644 index 000000000..fdf0984b7 --- /dev/null +++ b/modules/client/front/summary/index.js @@ -0,0 +1,52 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($http) { + this.$http = $http; + } + + $onChanges() { + if (!this.client) + return; + + this.$http.get(`Clients/${this.client.id}/summary`).then(res => { + if (res && res.data) { + this.summary = res.data; + + if (res.data.classifications.length) + this.grade = res.data.classifications[0].insurances[0].grade; + + this.summary.sumRisk = this.sumRisk(); + } + }); + } + + sumRisk() { + let total = 0; + this.summary.clientRisks.forEach(risk => { + total += risk.amount; + }); + return total; + } + + claimRate(priceIncreasing) { + if (priceIncreasing) + return priceIncreasing * 100; + } + + claimingRate(rate) { + if (rate) + return rate * 100; + } +} + +Controller.$inject = ['$http']; + +ngModule.component('vnClientSummary', { + template: require('./index.html'), + controller: Controller, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/summary/index.spec.js b/modules/client/front/summary/index.spec.js new file mode 100644 index 000000000..24f9b55dc --- /dev/null +++ b/modules/client/front/summary/index.spec.js @@ -0,0 +1,50 @@ +import './index'; + +describe('Client', () => { + describe('Component vnClientSummary', () => { + let controller; + let $httpBackend; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + controller = $componentController('vnClientSummary'); + controller.client = {id: 101}; + })); + + describe('$onChanges()', () => { + it('should perform a GET query and define summary property', () => { + let res = {name: 'Superman', classifications: []}; + + spyOn(controller, 'sumRisk'); + $httpBackend.when('GET', `Clients/101/summary`).respond(200, res); + $httpBackend.expect('GET', `Clients/101/summary`); + + controller.$onChanges(); + $httpBackend.flush(); + + expect(controller.summary).toBeDefined(); + expect(controller.summary.name).toEqual('Superman'); + }); + }); + + describe('sumRisk()', () => { + it('should sum property amount of an array', () => { + controller.summary = { + clientRisks: [{ + companyFk: 442, + amount: 100 + }, + { + companyFk: 567, + amount: 200 + }]}; + + let result = controller.sumRisk(); + + expect(result).toEqual(300); + }); + }); + }); +}); diff --git a/modules/client/front/summary/locale/es.yml b/modules/client/front/summary/locale/es.yml new file mode 100644 index 000000000..24068e4ad --- /dev/null +++ b/modules/client/front/summary/locale/es.yml @@ -0,0 +1,19 @@ +Default address: Consignatario predeterminado +Total greuge: Greuge total +Financial information: Datos financieros +Mana: Maná +Risk: Riesgo +Secured credit: Crédito asegurado +Average invoiced: Consumo medio +Sales person: Comercial +Recovery: Recobro +Balance due: Saldo vencido +Rate: Tarifa +Business data: Datos comerciales +Recovery since: Recobro desde +Fiscal address: Dirección fiscal +Invoices minus payments plus orders not yet invoiced: Facturas menos recibos mas pedidos sin facturar +Verdnatura's maximum risk: Riesgo máximo asumido por Verdnatura +Solunion's maximum risk: Riesgo máximo asumido por Solunion +Invoices minus payments: Facturas menos recibos +Deviated invoices minus payments: Facturas fuera de plazo menos recibos diff --git a/modules/client/front/summary/style.scss b/modules/client/front/summary/style.scss new file mode 100644 index 000000000..1520659d2 --- /dev/null +++ b/modules/client/front/summary/style.scss @@ -0,0 +1,7 @@ +@import "variables"; + +vn-client-summary { + .alert span { + color: $color-alert !important + } +} \ No newline at end of file diff --git a/modules/client/front/web-access/index.html b/modules/client/front/web-access/index.html new file mode 100644 index 000000000..590e823d3 --- /dev/null +++ b/modules/client/front/web-access/index.html @@ -0,0 +1,54 @@ + + +
    + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + diff --git a/modules/client/front/web-access/index.js b/modules/client/front/web-access/index.js new file mode 100644 index 000000000..bdd5375a3 --- /dev/null +++ b/modules/client/front/web-access/index.js @@ -0,0 +1,75 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($scope, $http, vnApp, $translate) { + this.$ = $scope; + this.$http = $http; + this.vnApp = vnApp; + this.$translate = $translate; + this.canChangePassword = false; + this.canEnableCheckBox = true; + } + + $onChanges() { + if (this.client) { + this.account = this.client.account; + this.isCustomer(); + this.checkConditions(); + } + } + + isCustomer() { + if (this.client.id) { + this.$http.get(`Clients/${this.client.id}/hasCustomerRole`).then(res => { + this.canChangePassword = res.data && res.data.isCustomer; + }); + } + } + + checkConditions() { + if (this.client.id) { + this.$http.get(`Clients/${this.client.id}/isValidClient`).then(res => { + this.canEnableCheckBox = res.data; + }); + } + } + + onPassOpen() { + this.newPassword = ''; + this.repeatPassword = ''; + this.$.$apply(); + } + + onPassChange(response) { + if (response == 'accept') { + try { + if (!this.newPassword) + throw new Error(`You must enter a new password`); + if (this.newPassword != this.repeatPassword) + throw new Error(`Passwords don't match`); + let account = { + password: this.newPassword + }; + + this.$http.patch(`Accounts/${this.client.id}`, account).then(res => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }); + } catch (e) { + this.vnApp.showError(this.$translate.instant(e.message)); + + return false; + } + } + + return true; + } +} +Controller.$inject = ['$scope', '$http', 'vnApp', '$translate']; + +ngModule.component('vnClientWebAccess', { + template: require('./index.html'), + controller: Controller, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/web-access/index.spec.js b/modules/client/front/web-access/index.spec.js new file mode 100644 index 000000000..f8eb7b2ef --- /dev/null +++ b/modules/client/front/web-access/index.spec.js @@ -0,0 +1,103 @@ +import './index'; + +describe('Component VnClientWebAccess', () => { + let $httpBackend; + let $scope; + let vnApp; + let controller; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_, _vnApp_) => { + $scope = $rootScope.$new(); + $httpBackend = _$httpBackend_; + vnApp = _vnApp_; + spyOn(vnApp, 'showError'); + controller = $componentController('vnClientWebAccess', {$scope}); + })); + + describe('$onChanges()', () => { + it(`should pass client's account data to account then call isCustomer function`, () => { + spyOn(controller, 'isCustomer'); + controller.client = {client: 'Bruce Wayne', account: 'Wayne Industries'}; + controller.account = {}; + controller.$onChanges(); + + expect(controller.account).toBe('Wayne Industries'); + expect(controller.isCustomer).toHaveBeenCalledWith(); + }); + }); + + describe('isCustomer()', () => { + it(`should perform a query if client is defined with an ID`, () => { + controller.client = {id: '1234'}; + controller.isCustomer(); + + $httpBackend.when('GET', `Clients/${controller.client.id}/hasCustomerRole`).respond('ok'); + $httpBackend.expectGET(`Clients/${controller.client.id}/hasCustomerRole`); + $httpBackend.flush(); + }); + }); + + describe('checkConditions()', () => { + it(`should perform a query to check if the client is valid and then store a boolean into the controller`, () => { + controller.client = {id: '1234'}; + + expect(controller.canEnableCheckBox).toBeTruthy(); + + $httpBackend.when('GET', `Clients/${controller.client.id}/isValidClient`).respond(false); + $httpBackend.expectGET(`Clients/${controller.client.id}/isValidClient`); + controller.checkConditions(); + $httpBackend.flush(); + + expect(controller.canEnableCheckBox).toBeFalsy(); + }); + }); + + describe('onPassOpen()', () => { + it('should set passwords to empty values', () => { + controller.newPassword = 'm24x8'; + controller.repeatPassword = 'm24x8'; + controller.onPassOpen(); + + expect(controller.newPassword).toBe(''); + expect(controller.repeatPassword).toBe(''); + }); + }); + + describe('onPassChange()', () => { + it('should request to update the password', () => { + controller.client = {id: '1234'}; + controller.newPassword = 'm24x8'; + controller.repeatPassword = 'm24x8'; + controller.canChangePassword = true; + $httpBackend.when('PATCH', 'Accounts/1234').respond('done'); + $httpBackend.expectPATCH('Accounts/1234', {password: 'm24x8'}); + controller.onPassChange('accept'); + $httpBackend.flush(); + }); + + describe(`when password is empty`, () => { + it(`should throw 'You must enter a new password' error`, () => { + controller.client = {id: '1234'}; + controller.newPassword = ''; + controller.canChangePassword = true; + controller.onPassChange('accept'); + + expect(vnApp.showError).toHaveBeenCalledWith(`You must enter a new password`); + }); + }); + + describe(`when passwords don't match`, () => { + it(`should throw Passwords don't match error`, () => { + controller.client = {id: '1234'}; + controller.newPassword = 'm24x8'; + controller.canChangePassword = true; + controller.repeatPassword = 'notMatchingPassword'; + controller.onPassChange('accept'); + + expect(vnApp.showError).toHaveBeenCalledWith(`Passwords don't match`); + }); + }); + }); +}); diff --git a/modules/client/front/web-access/locale/es.yml b/modules/client/front/web-access/locale/es.yml new file mode 100644 index 000000000..4a3ac0ab4 --- /dev/null +++ b/modules/client/front/web-access/locale/es.yml @@ -0,0 +1,7 @@ +User: Usuario +Enable web access: Habilitar acceso web +New password: Nueva contraseña +Repeat password: Repetir contraseña +Change password: Cambiar contraseña +Passwords don't match: Las contraseñas no coinciden +You must enter a new password: Debes introducir una nueva contraseña \ No newline at end of file diff --git a/modules/client/front/web-payment/index.html b/modules/client/front/web-payment/index.html new file mode 100644 index 000000000..110f4a2bf --- /dev/null +++ b/modules/client/front/web-payment/index.html @@ -0,0 +1,55 @@ + + + + + + + + State + Id + Date + Amount + + + + + + + + + + + + {{::transaction.id}} + {{::transaction.created | date:'dd/MM/yyyy HH:mm'}} + {{::transaction.amount | currency: 'EUR':2}} + + + + + + + + + \ No newline at end of file diff --git a/modules/client/front/web-payment/index.js b/modules/client/front/web-payment/index.js new file mode 100644 index 000000000..4c379dcad --- /dev/null +++ b/modules/client/front/web-payment/index.js @@ -0,0 +1,34 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $http, $stateParams) { + this.$scope = $scope; + this.$http = $http; + this.$stateParams = $stateParams; + } + + confirm(transaction) { + const path = 'Clients/confirmTransaction'; + let data = {id: transaction.id}; + this.$http.post(path, data).then(res => { + this.$scope.model.refresh(); + }); + } + + getFormattedMessage(transaction) { + const errorMessage = transaction.errorMessage ? transaction.errorMessage : ''; + const separator = transaction.errorMessage && transaction.responseMessage ? '
    ' : ''; + const responseMessage = transaction.responseMessage ? transaction.responseMessage : ''; + return `${errorMessage}` + + separator + + `${responseMessage}`; + } +} + +Controller.$inject = ['$scope', '$http', '$stateParams']; + +ngModule.component('vnClientWebPayment', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/client/front/web-payment/index.spec.js b/modules/client/front/web-payment/index.spec.js new file mode 100644 index 000000000..f5a801ccb --- /dev/null +++ b/modules/client/front/web-payment/index.spec.js @@ -0,0 +1,45 @@ +import './index'; +import crudModel from 'core/mocks/crud-model'; + +describe('Component vnClientWebPayment', () => { + let $httpBackend; + let $scope; + let vnApp; + let controller; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_, _vnApp_) => { + $scope = $rootScope.$new(); + $scope.model = crudModel; + $httpBackend = _$httpBackend_; + vnApp = _vnApp_; + spyOn(vnApp, 'showError'); + controller = $componentController('vnClientWebPayment', {$scope: $scope}); + })); + + describe('confirm()', () => { + it(`should confirm a transaction`, () => { + let transaction = {id: 1}; + let query = 'Clients/confirmTransaction'; + + controller.confirm(transaction); + $httpBackend.when('POST', query, transaction).respond('ok'); + $httpBackend.expect('POST', query, transaction); + $httpBackend.flush(); + }); + }); + + describe('getFormattedMessage()', () => { + it(`should return error message and response Message`, () => { + let transaction = { + errorMessage: 'My error message', + responseMessage: 'My response message' + }; + let result = controller.getFormattedMessage(transaction); + + expect(result).toContain('My error message'); + expect(result).toContain('My response message'); + }); + }); +}); diff --git a/modules/client/front/web-payment/locale/es.yml b/modules/client/front/web-payment/locale/es.yml new file mode 100644 index 000000000..8e988857c --- /dev/null +++ b/modules/client/front/web-payment/locale/es.yml @@ -0,0 +1,5 @@ +Web Payment: Pago Web +Confirmed: Confirmado +Confirm transaction: Confirmar transacción +Confirm: Confirmar +State: Estado \ No newline at end of file diff --git a/modules/client/front/web-payment/style.scss b/modules/client/front/web-payment/style.scss new file mode 100644 index 000000000..3c9b3b705 --- /dev/null +++ b/modules/client/front/web-payment/style.scss @@ -0,0 +1,10 @@ +@import "variables"; + +vn-client-web-payment { + vn-icon[icon=clear] { + color: $color-alert; + } + vn-icon[icon=check] { + color: $color-success; + } +} \ No newline at end of file diff --git a/modules/invoiceOut/back/methods/invoiceOut/book.js b/modules/invoiceOut/back/methods/invoiceOut/book.js new file mode 100644 index 000000000..a3a909f2a --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/book.js @@ -0,0 +1,30 @@ + +module.exports = Self => { + Self.remoteMethod('book', { + description: 'Book a invoiceOut', + accessType: 'WRITE', + accepts: { + arg: 'ref', + type: 'string', + required: true, + description: 'The invoiceOut ref', + http: {source: 'path'} + }, + returns: { + type: 'object', + root: true + }, + http: { + path: '/:ref/book', + verb: 'POST' + } + }); + + Self.book = async ref => { + let ticketAddress = await Self.app.models.Ticket.findOne({where: {invoiceOut: ref}}); + let invoiceCompany = await Self.app.models.InvoiceOut.findOne({where: {ref: ref}}); + let [taxArea] = await Self.rawSql(`Select vn.addressTaxArea(?, ?) AS code`, [ticketAddress.address, invoiceCompany.company]); + + return Self.rawSql(`CALL vn.invoiceOutAgain(?, ?)`, [ref, taxArea.code]); + }; +}; diff --git a/modules/invoiceOut/back/methods/invoiceOut/delete.js b/modules/invoiceOut/back/methods/invoiceOut/delete.js new file mode 100644 index 000000000..127786ded --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/delete.js @@ -0,0 +1,45 @@ + +module.exports = Self => { + Self.remoteMethod('delete', { + description: 'Delete a invoiceOut', + accessType: 'WRITE', + accepts: { + arg: 'id', + type: 'string', + required: true, + description: 'The invoiceOut id', + http: {source: 'path'} + }, + returns: { + type: 'object', + root: true + }, + http: { + path: '/:id/delete', + verb: 'POST' + } + }); + + Self.delete = async id => { + const transaction = await Self.beginTransaction({}); + try { + let options = {transaction: transaction}; + + let invoiceOut = await Self.findById(id); + let tickets = await Self.app.models.Ticket.find({where: {refFk: invoiceOut.ref}}); + + const promises = []; + tickets.forEach(ticket => { + promises.push(ticket.updateAttribute('refFk', null, options)); + }); + + await Promise.all(promises); + await invoiceOut.destroy(options); + await transaction.commit(); + return tickets; + } catch (e) { + await transaction.rollback(); + throw e; + } + }; +}; diff --git a/modules/invoiceOut/back/methods/invoiceOut/download.js b/modules/invoiceOut/back/methods/invoiceOut/download.js new file mode 100644 index 000000000..3c9924fc3 --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/download.js @@ -0,0 +1,59 @@ +const fs = require('fs-extra'); + +module.exports = Self => { + Self.remoteMethod('download', { + description: 'Download an invoice PDF', + accessType: 'READ', + accepts: [ + { + arg: 'id', + type: 'String', + description: 'The invoice id', + http: {source: 'path'} + } + ], + returns: [ + { + arg: 'body', + type: 'file', + root: true + }, { + arg: 'Content-Type', + type: 'String', + http: {target: 'header'} + }, { + arg: 'Content-Disposition', + type: 'String', + http: {target: 'header'} + } + ], + http: { + path: `/:id/download`, + verb: 'GET' + } + }); + + Self.download = async function(id) { + let file; + let env = process.env.NODE_ENV; + let [invoice] = await Self.rawSql(`SELECT invoiceOut_getPath(?) path`, [id]); + + if (env && env != 'development') { + file = { + path: `/var/lib/salix/pdfs/${invoice.path}`, + contentType: 'application/pdf', + name: `${id}.pdf` + }; + } else { + file = { + path: `${process.cwd()}/README.md`, + contentType: 'text/plain', + name: `README.md` + }; + } + + await fs.access(file.path); + let stream = fs.createReadStream(file.path); + return [stream, file.contentType, `filename="${file.name}"`]; + }; +}; diff --git a/modules/invoiceOut/back/methods/invoiceOut/filter.js b/modules/invoiceOut/back/methods/invoiceOut/filter.js new file mode 100644 index 000000000..8b6d00763 --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/filter.js @@ -0,0 +1,130 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const buildFilter = require('vn-loopback/util/filter').buildFilter; +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethodCtx('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accessType: 'READ', + accepts: [ + { + arg: 'filter', + type: 'Object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + http: {source: 'query'} + }, + { + arg: 'search', + type: 'String', + description: 'Searchs the invoiceOut by id', + http: {source: 'query'} + }, { + arg: 'clientFk', + type: 'Integer', + description: 'The client id', + http: {source: 'query'} + }, { + arg: 'hasPdf', + type: 'Boolean', + description: 'Whether the the invoiceOut has PDF or not', + http: {source: 'query'} + }, { + arg: 'amount', + type: 'Number', + description: 'The amount filter', + http: {source: 'query'} + }, { + arg: 'min', + type: 'Number', + description: 'The minimun amount flter', + http: {source: 'query'} + }, { + arg: 'max', + type: 'Number', + description: 'The maximun amount flter', + http: {source: 'query'} + }, { + arg: 'issued', + type: 'Date', + description: 'The issued date filter', + http: {source: 'query'} + }, { + arg: 'created', + type: 'Date', + description: 'The created date filter', + http: {source: 'query'} + }, { + arg: 'dued', + type: 'Date', + description: 'The due date filter', + http: {source: 'query'} + } + ], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/filter`, + verb: 'GET' + } + }); + + Self.filter = async(ctx, filter) => { + let conn = Self.dataSource.connector; + + let where = buildFilter(ctx.args, (param, value) => { + switch (param) { + case 'search': + return {'i.ref': {like: `%${value}%`}}; + case 'min': + return {'i.amount': {gte: value}}; + case 'max': + return {'i.amount': {lte: value}}; + case 'hasPdf': + return {'i.hasPdf': value}; + case 'created': + return {'i.created': value}; + case 'clientFk': + return {'i.clientFk': value}; + case 'amount': + case 'companyFk': + case 'issued': + case 'dued': + param = `i.${param}`; + return {[param]: value}; + } + }); + + filter = mergeFilters(filter, {where}); + + let stmts = []; + let stmt; + + stmt = new ParameterizedSQL( + `SELECT + i.id, + i.ref, + i.issued, + i.amount, + i.created, + i.dued, + i.clientFk, + i.hasPdf, + c.socialName AS clientSocialName, + co.code AS companyCode + FROM invoiceOut i + LEFT JOIN client c ON c.id = i.clientFk + LEFT JOIN company co ON co.id = i.companyFk` + ); + + stmt.merge(conn.makeSuffix(filter)); + let itemsIndex = stmts.push(stmt) - 1; + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + return itemsIndex === 0 ? result : result[itemsIndex]; + }; +}; + diff --git a/modules/invoiceOut/back/methods/invoiceOut/regenerate.js b/modules/invoiceOut/back/methods/invoiceOut/regenerate.js new file mode 100644 index 000000000..fda12c3cb --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/regenerate.js @@ -0,0 +1,51 @@ +module.exports = Self => { + Self.remoteMethodCtx('regenerate', { + description: 'Sends an invoice to a regeneration queue', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The invoiceOut id', + http: {source: 'path'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: '/:id/regenerate', + verb: 'POST' + } + }); + + Self.regenerate = async(ctx, id) => { + const userId = ctx.req.accessToken.userId; + const models = Self.app.models; + const invoiceReportFk = 30; // Should be deprecated + const worker = await models.Worker.findOne({where: {userFk: userId}}); + const tx = await Self.beginTransaction({}); + + try { + let options = {transaction: tx}; + + // Remove all invoice references from tickets + const invoiceOut = await models.InvoiceOut.findById(id, null, options); + await invoiceOut.updateAttributes({ + hasPdf: false + }); + + // Send to print queue + await Self.rawSql(` + INSERT INTO vn.printServerQueue (reportFk, param1, workerFk) + VALUES (?, ?, ?)`, [invoiceReportFk, id, worker.id], options); + + await tx.commit(); + + return invoiceOut; + } catch (e) { + await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js new file mode 100644 index 000000000..345e29125 --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js @@ -0,0 +1,36 @@ +const app = require('vn-loopback/server/server'); + +describe('invoiceOut book()', () => { + const invoiceOutId = 1; + let invoiceOutRef; + let OriginalInvoiceOut; + let updatedInvoiceOut; + let bookedDate; + + afterAll(async done => { + updatedInvoiceOut.updateAttributes({booked: OriginalInvoiceOut.booked, hasPdf: OriginalInvoiceOut.hasPdf}); + + done(); + }); + + it('should check that invoice out booked is untainted', async() => { + const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); + + bookedDate = invoiceOut.booked; + + expect(invoiceOut.booked).toBeDefined(); + expect(invoiceOut.hasPdf).toBeTruthy(); + }); + + it(`should confirm the book property have been updated`, async() => { + OriginalInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); + invoiceOutRef = OriginalInvoiceOut.ref; + + await app.models.InvoiceOut.book(invoiceOutRef); + + updatedInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); + + expect(updatedInvoiceOut.booked).not.toEqual(bookedDate); + expect(updatedInvoiceOut.hasPdf).toBeFalsy(); + }); +}); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js new file mode 100644 index 000000000..0d272a81d --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js @@ -0,0 +1,36 @@ +const app = require('vn-loopback/server/server'); + +describe('invoiceOut delete()', () => { + const invoiceOutId = 2; + let originalInvoiceOut; + let originalTicket; + + afterAll(async done => { + const newInvoiceOut = await app.models.InvoiceOut.create(originalInvoiceOut); + await newInvoiceOut.updateAttribute('ref', originalInvoiceOut.ref); + + const promises = []; + promises.push(originalTicket.updateAttribute('refFk', newInvoiceOut.ref)); + Promise.all(promises); + + done(); + }); + + it('should check that there is one ticket in the target invoiceOut', async() => { + const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); + const tickets = await app.models.Ticket.find({where: {refFk: invoiceOut.ref}}); + + expect(tickets.length).toEqual(1); + expect(tickets[0].id).toEqual(3); + }); + + it(`should delete the target invoiceOut then check the ticket doesn't have a refFk anymore`, async() => { + originalInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); + await app.models.InvoiceOut.delete(invoiceOutId); + originalTicket = await app.models.Ticket.findById(3); + const deletedInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); + + expect(deletedInvoiceOut).toBeNull(); + expect(originalTicket.refFk).toBeNull(); + }); +}); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js new file mode 100644 index 000000000..09289896f --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/download.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('InvoiceOut download()', () => { + it('should return the downloaded fine name', async() => { + let result = await app.models.InvoiceOut.download(1); + + expect(result[1]).toEqual('text/plain'); + expect(result[2]).toEqual('filename="README.md"'); + }); +}); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/filter.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/filter.spec.js new file mode 100644 index 000000000..09f67eced --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/filter.spec.js @@ -0,0 +1,109 @@ +const app = require('vn-loopback/server/server'); + +describe('InvoiceOut filter()', () => { + let today = new Date(); + today.setHours(2, 0, 0, 0); + + it('should return the invoice out matching ref', async() => { + let ctx = { + args: { + search: 'T4444444', + } + }; + + let result = await app.models.InvoiceOut.filter(ctx); + + expect(result.length).toEqual(1); + expect(result[0].ref).toEqual('T4444444'); + }); + + it('should return the invoice out matching clientFk', async() => { + let ctx = { + args: { + clientFk: 102, + } + }; + + let result = await app.models.InvoiceOut.filter(ctx); + + expect(result.length).toEqual(1); + expect(result[0].ref).toEqual('T2222222'); + }); + + it('should return the invoice out matching hasPdf', async() => { + let ctx = { + args: { + hasPdf: true, + } + }; + + let result = await app.models.InvoiceOut.filter(ctx); + + expect(result.length).toEqual(5); + }); + + it('should return the invoice out matching amount', async() => { + let ctx = { + args: { + amount: 121.36, + } + }; + + let result = await app.models.InvoiceOut.filter(ctx); + + expect(result.length).toEqual(1); + expect(result[0].ref).toEqual('T2222222'); + }); + + it('should return the invoice out matching min and max', async() => { + let ctx = { + args: { + min: 0, + max: 100, + } + }; + + let result = await app.models.InvoiceOut.filter(ctx); + + expect(result.length).toEqual(3); + }); + + // #1428 cuadrar formato de horas + xit('should return the invoice out matching issued', async() => { + let ctx = { + args: { + issued: today, + } + }; + + let result = await app.models.InvoiceOut.filter(ctx); + + expect(result.length).toEqual(1); + }); + + // #1428 cuadrar formato de horas + xit('should return the invoice out matching created', async() => { + let ctx = { + args: { + created: today, + } + }; + + let result = await app.models.InvoiceOut.filter(ctx); + + expect(result.length).toEqual(5); + }); + + // #1428 cuadrar formato de horas + xit('should return the invoice out matching dued', async() => { + let ctx = { + args: { + dued: today + } + }; + + let result = await app.models.InvoiceOut.filter(ctx); + + expect(result.length).toEqual(1); + }); +}); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/regenerate.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/regenerate.spec.js new file mode 100644 index 000000000..43cb9023b --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/regenerate.spec.js @@ -0,0 +1,39 @@ +const app = require('vn-loopback/server/server'); + +describe('invoiceOut regenerate()', () => { + const invoiceReportFk = 30; + const invoiceOutId = 1; + + afterAll(async done => { + const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); + await invoiceOut.updateAttributes({hasPdf: true}); + await app.models.InvoiceOut.rawSql(` + DELETE FROM vn.printServerQueue + WHERE reportFk = ?`, [invoiceReportFk]); + + done(); + }); + + it('should check that the invoice has a PDF and is not in print generation queue', async() => { + const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); + const [queue] = await app.models.InvoiceOut.rawSql(` + SELECT COUNT(*) AS total + FROM vn.printServerQueue + WHERE reportFk = ?`, [invoiceReportFk]); + + expect(invoiceOut.hasPdf).toBeTruthy(); + expect(queue.total).toEqual(0); + }); + + it(`should mark the invoice as doesn't have PDF and add it to a print queue`, async() => { + const ctx = {req: {accessToken: {userId: 5}}}; + const invoiceOut = await app.models.InvoiceOut.regenerate(ctx, invoiceOutId); + const [queue] = await app.models.InvoiceOut.rawSql(` + SELECT COUNT(*) AS total + FROM vn.printServerQueue + WHERE reportFk = ?`, [invoiceReportFk]); + + expect(invoiceOut.hasPdf).toBeFalsy(); + expect(queue.total).toEqual(1); + }); +}); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/summary.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/summary.spec.js new file mode 100644 index 000000000..1b1b84d15 --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/summary.spec.js @@ -0,0 +1,33 @@ +const app = require('vn-loopback/server/server'); + +describe('invoiceOut summary()', () => { + it('should return a summary object containing data from one invoiceOut', async() => { + const result = await app.models.InvoiceOut.summary(1); + + expect(result.invoiceOut.id).toEqual(1); + }); + + it(`should return a summary object containing data from it's tickets`, async() => { + const summary = await app.models.InvoiceOut.summary(1); + const tickets = summary.invoiceOut.tickets(); + + expect(summary.invoiceOut.ref).toEqual('T1111111'); + expect(tickets.length).toEqual(2); + }); + + it(`should return a summary object containing it's supplier country`, async() => { + const summary = await app.models.InvoiceOut.summary(1); + const supplier = summary.invoiceOut.supplier(); + + expect(summary.invoiceOut.ref).toEqual('T1111111'); + expect(supplier.id).toEqual(442); + expect(supplier.countryFk).toEqual(1); + }); + + it(`should return a summary object containing idata from it's tax types`, async() => { + const summary = await app.models.InvoiceOut.summary(1); + + expect(summary.invoiceOut.ref).toEqual('T1111111'); + expect(summary.invoiceOut.taxesBreakdown.length).toEqual(2); + }); +}); diff --git a/modules/invoiceOut/back/methods/invoiceOut/summary.js b/modules/invoiceOut/back/methods/invoiceOut/summary.js new file mode 100644 index 000000000..caa2a1c06 --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/summary.js @@ -0,0 +1,111 @@ +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('summary', { + description: 'The invoiceOut summary', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The invoiceOut id', + http: {source: 'path'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/summary`, + verb: 'GET' + } + }); + + Self.summary = async id => { + const conn = Self.dataSource.connector; + let summary = {}; + + const filter = { + fields: [ + 'id', + 'ref', + 'issued', + 'dued', + 'amount', + 'created', + 'booked', + 'clientFk', + 'companyFk', + 'hasPdf' + ], + where: {id: id}, + include: [ + { + relation: 'company', + scope: { + fields: ['id', 'code'] + } + }, + { + relation: 'supplier', + scope: { + fields: ['id', 'countryFk'] + } + }, + { + relation: 'client', + scope: { + fields: ['id', 'socialName'] + } + }, + { + relation: 'tickets' + } + ] + }; + + summary.invoiceOut = await Self.app.models.InvoiceOut.findOne(filter); + + let stmts = []; + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.ticket'); + + stmt = new ParameterizedSQL(` + CREATE TEMPORARY TABLE tmp.ticket + (INDEX (ticketFk)) ENGINE = MEMORY + SELECT id ticketFk FROM vn.ticket WHERE refFk=?`, [summary.invoiceOut.ref]); + stmts.push(stmt); + + stmts.push('CALL ticketGetTotal()'); + + let ticketTotalsIndex = stmts.push('SELECT * FROM tmp.ticketTotal') - 1; + + stmt = new ParameterizedSQL(` + SELECT iot.* , pgc.*, IF(pe.equFk IS NULL, taxableBase, 0) AS Base, pgc.rate / 100 as vatPercent + FROM vn.invoiceOutTax iot + JOIN vn.pgc ON pgc.code = iot.pgcFk + LEFT JOIN vn.pgcEqu pe ON pe.equFk = pgc.code + WHERE invoiceOutFk = ?`, [summary.invoiceOut.id]); + let invoiceOutTaxesIndex = stmts.push(stmt) - 1; + + stmts.push( + `DROP TEMPORARY TABLE + tmp.ticket, + tmp.ticketTotal`); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + + totalMap = {}; + for (ticketTotal of result[ticketTotalsIndex]) + totalMap[ticketTotal.ticketFk] = ticketTotal.total; + + summary.invoiceOut.tickets().forEach(ticket => { + ticket.total = totalMap[ticket.id]; + }); + + summary.invoiceOut.taxesBreakdown = result[invoiceOutTaxesIndex]; + + return summary; + }; +}; diff --git a/modules/invoiceOut/back/model-config.json b/modules/invoiceOut/back/model-config.json new file mode 100644 index 000000000..f3492dbe6 --- /dev/null +++ b/modules/invoiceOut/back/model-config.json @@ -0,0 +1,5 @@ +{ + "InvoiceOut": { + "dataSource": "vn" + } +} diff --git a/modules/invoiceOut/back/models/invoiceOut.js b/modules/invoiceOut/back/models/invoiceOut.js new file mode 100644 index 000000000..8046f1dc4 --- /dev/null +++ b/modules/invoiceOut/back/models/invoiceOut.js @@ -0,0 +1,8 @@ +module.exports = Self => { + require('../methods/invoiceOut/filter')(Self); + require('../methods/invoiceOut/summary')(Self); + require('../methods/invoiceOut/download')(Self); + require('../methods/invoiceOut/regenerate')(Self); + require('../methods/invoiceOut/delete')(Self); + require('../methods/invoiceOut/book')(Self); +}; diff --git a/modules/invoiceOut/back/models/invoiceOut.json b/modules/invoiceOut/back/models/invoiceOut.json new file mode 100644 index 000000000..45c4c2774 --- /dev/null +++ b/modules/invoiceOut/back/models/invoiceOut.json @@ -0,0 +1,68 @@ +{ + "name": "InvoiceOut", + "base": "VnModel", + "options": { + "mysql": { + "table": "invoiceOut" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "ref": { + "type": "String", + "required": true + }, + "serial": { + "type": "String" + }, + "issued": { + "type": "date" + }, + "amount": { + "type": "Number" + }, + "created": { + "type": "date" + }, + "dued": { + "type": "date" + }, + "booked": { + "type": "date" + }, + "hasPdf": { + "type": "Boolean" + } + }, + "relations": { + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "clientFk" + }, + "company": { + "type": "belongsTo", + "model": "Company", + "foreignKey": "companyFk", + "required": true + }, + "supplier": { + "type": "belongsTo", + "model": "Supplier", + "foreignKey": "companyFk", + "required": true + }, + "tickets": { + "type": "hasMany", + "model": "Ticket", + "foreignKey": "refFk", + "primaryKey": "ref" + } + } +} + + diff --git a/modules/invoiceOut/front/card/index.html b/modules/invoiceOut/front/card/index.html new file mode 100644 index 000000000..c70ac06e1 --- /dev/null +++ b/modules/invoiceOut/front/card/index.html @@ -0,0 +1,5 @@ + + + + + diff --git a/modules/invoiceOut/front/card/index.js b/modules/invoiceOut/front/card/index.js new file mode 100644 index 000000000..0ad91f4c2 --- /dev/null +++ b/modules/invoiceOut/front/card/index.js @@ -0,0 +1,39 @@ +import ngModule from '../module'; +import ModuleCard from 'salix/components/module-card'; + +class Controller extends ModuleCard { + reload() { + const filter = { + fields: [ + 'id', + 'ref', + 'issued', + 'amount', + 'clientFk', + 'companyFk' + ], + include: [ + { + relation: 'company', + scope: { + fields: ['id', 'code'] + } + }, { + relation: 'client', + scope: { + fields: ['id', 'socialName', 'name'] + } + } + ] + }; + + this.$http.get(`InvoiceOuts/${this.$params.id}`, {filter}) + .then(res => this.invoiceOut = res.data); + } +} + +ngModule.component('vnInvoiceOutCard', { + template: require('./index.html'), + controller: Controller +}); + diff --git a/modules/invoiceOut/front/descriptor-popover/index.html b/modules/invoiceOut/front/descriptor-popover/index.html new file mode 100644 index 000000000..c4234535c --- /dev/null +++ b/modules/invoiceOut/front/descriptor-popover/index.html @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/modules/invoiceOut/front/descriptor-popover/index.js b/modules/invoiceOut/front/descriptor-popover/index.js new file mode 100644 index 000000000..2e3fb15fd --- /dev/null +++ b/modules/invoiceOut/front/descriptor-popover/index.js @@ -0,0 +1,81 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + constructor($element, $scope, $http, $timeout, $q) { + super($element, $scope); + this.$timeout = $timeout; + this.$http = $http; + this.$q = $q; + this.worker = null; + this._quicklinks = {}; + } + + set invoiceOutId(id) { + if (id == this._invoiceOutId) return; + + this._invoiceOutId = id; + this.invoiceOut = null; + this.loadData(); + } + + get invoiceOutId() { + return this._invoiceOutId; + } + + get quicklinks() { + return this._quicklinks; + } + + set quicklinks(value = {}) { + Object.keys(value).forEach(key => { + this._quicklinks[key] = value[key]; + }); + } + + show() { + this.$.popover.parent = this.parent; + this.$.popover.show(); + } + + loadData() { + let query = `InvoiceOuts/findOne`; + let filter = { + where: { + id: this._invoiceOutId + }, + include: [ + { + relation: 'company', + scope: { + fields: ['id', 'code'] + } + }, + { + relation: 'client', + scope: { + fields: ['id', 'name'] + } + } + ] + }; + + this.$http.get(query, {params: {filter}}).then(res => { + this.invoiceOut = res.data; + this.$.$applyAsync(() => { + this.$.popover.relocate(); + }); + }); + } +} +Controller.$inject = ['$element', '$scope', '$http', '$timeout', '$q']; + +ngModule.component('vnInvoiceOutDescriptorPopover', { + template: require('./index.html'), + controller: Controller, + bindings: { + invoiceOutId: '<', + quicklinks: '<' + } +}); diff --git a/modules/invoiceOut/front/descriptor-popover/style.scss b/modules/invoiceOut/front/descriptor-popover/style.scss new file mode 100644 index 000000000..58e65d320 --- /dev/null +++ b/modules/invoiceOut/front/descriptor-popover/style.scss @@ -0,0 +1,11 @@ +vn-ticket-descriptor-popover { + vn-ticket-descriptor { + display: block; + width: 16em; + max-height: 28em; + + & > vn-card { + margin: 0!important; + } + } +} \ No newline at end of file diff --git a/modules/invoiceOut/front/descriptor/index.html b/modules/invoiceOut/front/descriptor/index.html new file mode 100644 index 000000000..981c23e34 --- /dev/null +++ b/modules/invoiceOut/front/descriptor/index.html @@ -0,0 +1,50 @@ +
    +
    + + + + + + + + +
    +
    +
    +
    {{$ctrl.invoiceOut.ref}}
    + + + + + + + + +
    + + +
    +
    + + + + \ No newline at end of file diff --git a/modules/invoiceOut/front/descriptor/index.js b/modules/invoiceOut/front/descriptor/index.js new file mode 100644 index 000000000..a69f6ed8b --- /dev/null +++ b/modules/invoiceOut/front/descriptor/index.js @@ -0,0 +1,106 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, vnToken, vnApp, $state, $translate, $http, aclService) { + this.$scope = $scope; + this.accessToken = vnToken.token; + this.vnApp = vnApp; + this.$state = $state; + this.$translate = $translate; + this.$http = $http; + this.aclService = aclService; + this.moreOptions = [ + {callback: this.showInvoiceOutPdf, name: 'Show invoice PDF'}, + {callback: this.showDeleteInvoiceOutDialog, name: 'Delete Invoice', acl: 'invoicing'}, + {callback: this.showBookInvoiceOutDialog, name: 'Book invoice', acl: 'invoicing'} + ]; + } + + onMoreOpen() { + let options = this.moreOptions.filter(option => { + const hasAclProperty = Object.hasOwnProperty.call(option, 'acl'); + + return !hasAclProperty || (hasAclProperty && this.aclService.hasAny([option.acl])); + }); + this.$scope.moreButton.data = options; + } + + onMoreChange(callback) { + callback.call(this); + } + + set invoiceOut(value) { + this._invoiceOut = value; + + if (value) { + this._quicklinks = { + btnOne: { + icon: 'icon-person', + state: `client.card.summary({id: ${value.clientFk}})`, + tooltip: 'Client card' + }, + btnTwo: { + icon: 'icon-ticket', + state: `ticket.index({q: '{"refFk": "${value.ref}"}'})`, + tooltip: 'Invoice ticket list' + } + }; + } + } + + get invoiceOut() { + return this._invoiceOut; + } + + showInvoiceOutPdf() { + let url = `api/InvoiceOuts/${this.invoiceOut.id}/download?access_token=${this.accessToken}`; + window.open(url, '_blank'); + } + + showDeleteInvoiceOutDialog() { + this.$scope.deleteConfirmation.show(); + } + + showBookInvoiceOutDialog() { + this.$scope.bookConfirmation.show(); + } + + deleteInvoiceOut(response) { + if (response === 'accept') { + const query = `InvoiceOuts/${this.invoiceOut.id}/delete`; + this.$http.post(query).then(() => { + this.vnApp.showSuccess(this.$translate.instant('InvoiceOut deleted')); + this.$state.go('invoiceOut.index'); + }); + } + } + + bookInvoiceOut(response) { + if (response === 'accept') { + const query = `InvoiceOuts/${this.invoiceOut.ref}/book`; + this.$http.post(query).then(() => { + this.vnApp.showSuccess(this.$translate.instant('InvoiceOut booked')); + this.$state.reload(); + }); + } + } + + set quicklinks(value = {}) { + this._quicklinks = Object.assign(value, this._quicklinks); + } + + get quicklinks() { + return this._quicklinks; + } +} + +Controller.$inject = ['$scope', 'vnToken', 'vnApp', '$state', '$translate', '$http', 'aclService']; + +ngModule.component('vnInvoiceOutDescriptor', { + template: require('./index.html'), + bindings: { + invoiceOut: '<', + quicklinks: '<' + }, + controller: Controller +}); diff --git a/modules/invoiceOut/front/descriptor/locale/es.yml b/modules/invoiceOut/front/descriptor/locale/es.yml new file mode 100644 index 000000000..e85be96bf --- /dev/null +++ b/modules/invoiceOut/front/descriptor/locale/es.yml @@ -0,0 +1,11 @@ +Volume exceded: Volumen excedido +Volume: Volumen +Client card: Ficha del cliente +Invoice ticket list: Listado de tickets de la factura +Show invoice PDF: Ver factura en PDF +Delete Invoice: Eliminar factura +InvoiceOut deleted: Factura eliminada +Are you sure you want to delete this invoice?: Estas seguro de eliminar esta factura? +Book invoice: Asentar factura +InvoiceOut booked: Factura asentada +Are you sure you want to book this invoice?: Estas seguro de querer asentar esta factura? \ No newline at end of file diff --git a/modules/invoiceOut/front/index.js b/modules/invoiceOut/front/index.js new file mode 100644 index 000000000..9843e188b --- /dev/null +++ b/modules/invoiceOut/front/index.js @@ -0,0 +1,9 @@ +export * from './module'; + +import './main'; +import './index/'; +import './search-panel'; +import './summary'; +import './card'; +import './descriptor'; +import './descriptor-popover'; diff --git a/modules/invoiceOut/front/index/index.html b/modules/invoiceOut/front/index/index.html new file mode 100644 index 000000000..c798b8bc6 --- /dev/null +++ b/modules/invoiceOut/front/index/index.html @@ -0,0 +1,75 @@ + + + + + + + + + + Reference + Issued + Amount + Client + Created + Company + Due date + + + + + + + {{::invoiceOut.ref | dashIfEmpty}} + {{::invoiceOut.issued | date:'dd/MM/yyyy' | dashIfEmpty}} + {{::invoiceOut.amount | currency: 'EUR': 2 | dashIfEmpty}} + + + {{::invoiceOut.clientSocialName | dashIfEmpty}} + + + {{::invoiceOut.created | date:'dd/MM/yyyy' | dashIfEmpty}} + {{::invoiceOut.companyCode | dashIfEmpty}} + {{::invoiceOut.dued | date:'dd/MM/yyyy' | dashIfEmpty}} + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/invoiceOut/front/index/index.js b/modules/invoiceOut/front/index/index.js new file mode 100644 index 000000000..dd8219fae --- /dev/null +++ b/modules/invoiceOut/front/index/index.js @@ -0,0 +1,49 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($scope, vnToken) { + this.accessToken = vnToken.token; + this.$ = $scope; + this.selectedInvoiceOut = null; + } + + showClientDescriptor(event, clientFk) { + this.$.clientDescriptor.clientFk = clientFk; + this.$.clientDescriptor.parent = event.target; + this.$.clientDescriptor.show(); + event.preventDefault(); + event.stopImmediatePropagation(); + } + + preview(event, invoiceOut) { + this.selectedInvoiceOut = invoiceOut; + this.$.summary.show(); + event.preventDefault(); + event.stopImmediatePropagation(); + } + + onDescriptorLoad() { + this.$.popover.relocate(); + } + + openPdf(id, event) { + let url = `api/InvoiceOuts/${id}/download?access_token=${this.accessToken}`; + window.open(url, '_blank'); + event.preventDefault(); + event.stopImmediatePropagation(); + } + + onSearch(params) { + if (params) + this.$.model.applyFilter(null, params); + else + this.$.model.clear(); + } +} + +Controller.$inject = ['$scope', 'vnToken']; + +ngModule.component('vnInvoiceOutIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/invoiceOut/front/index/locale/es.yml b/modules/invoiceOut/front/index/locale/es.yml new file mode 100644 index 000000000..eb22e1779 --- /dev/null +++ b/modules/invoiceOut/front/index/locale/es.yml @@ -0,0 +1,6 @@ +Created: Fecha creacion +Issued: Fecha factura +Due date: Fecha vencimiento +Has PDF: PDF disponible +Minimum: Minimo +Maximum: Máximo \ No newline at end of file diff --git a/modules/invoiceOut/front/locale/es.yml b/modules/invoiceOut/front/locale/es.yml new file mode 100644 index 000000000..87de48f56 --- /dev/null +++ b/modules/invoiceOut/front/locale/es.yml @@ -0,0 +1,2 @@ +Invoice out: Facturas +Search invoices by reference: Buscar facturas por referencia \ No newline at end of file diff --git a/modules/invoiceOut/front/main/index.html b/modules/invoiceOut/front/main/index.html new file mode 100644 index 000000000..18e72ed5e --- /dev/null +++ b/modules/invoiceOut/front/main/index.html @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/modules/invoiceOut/front/main/index.js b/modules/invoiceOut/front/main/index.js new file mode 100644 index 000000000..ad37e9c4b --- /dev/null +++ b/modules/invoiceOut/front/main/index.js @@ -0,0 +1,9 @@ +import ngModule from '../module'; +import ModuleMain from 'salix/components/module-main'; + +export default class InvoiceOut extends ModuleMain {} + +ngModule.vnComponent('vnInvoiceOut', { + controller: InvoiceOut, + template: require('./index.html') +}); diff --git a/modules/invoiceOut/front/module.js b/modules/invoiceOut/front/module.js new file mode 100644 index 000000000..59d8e1e4a --- /dev/null +++ b/modules/invoiceOut/front/module.js @@ -0,0 +1,3 @@ +import {ng} from 'core/vendor'; + +export default ng.module('invoiceOut', ['vnCore']); diff --git a/modules/invoiceOut/front/routes.json b/modules/invoiceOut/front/routes.json new file mode 100644 index 000000000..8f828a634 --- /dev/null +++ b/modules/invoiceOut/front/routes.json @@ -0,0 +1,43 @@ +{ + "module": "invoiceOut", + "name": "Invoices out", + "icon": "icon-invoices", + "validations" : true, + "dependencies": ["worker", "client", "ticket"], + "menus": { + "main": [ + {"state": "invoiceOut.index", "icon": "icon-invoices"} + ] + }, + "routes": [ + { + "url": "/invoice-out", + "state": "invoiceOut", + "abstract": true, + "component": "vn-invoice-out", + "description": "InvoiceOut", + "acl": ["employee"] + }, + { + "url": "/index?q", + "state": "invoiceOut.index", + "component": "vn-invoice-out-index", + "description": "Invoice out" + }, + { + "url": "/summary", + "state": "invoiceOut.card.summary", + "component": "vn-invoice-out-summary", + "description": "Summary", + "params": { + "invoice-out": "$ctrl.invoiceOut" + } + }, + { + "url": "/:id", + "state": "invoiceOut.card", + "abstract": true, + "component": "vn-invoice-out-card" + } + ] +} \ No newline at end of file diff --git a/modules/invoiceOut/front/search-panel/index.html b/modules/invoiceOut/front/search-panel/index.html new file mode 100644 index 000000000..ec469264c --- /dev/null +++ b/modules/invoiceOut/front/search-panel/index.html @@ -0,0 +1,63 @@ +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    diff --git a/modules/invoiceOut/front/search-panel/index.js b/modules/invoiceOut/front/search-panel/index.js new file mode 100644 index 000000000..1ca545ec7 --- /dev/null +++ b/modules/invoiceOut/front/search-panel/index.js @@ -0,0 +1,7 @@ +import ngModule from '../module'; +import SearchPanel from 'core/components/searchbar/search-panel'; + +ngModule.component('vnInvoiceSearchPanel', { + template: require('./index.html'), + controller: SearchPanel +}); diff --git a/modules/invoiceOut/front/summary/index.html b/modules/invoiceOut/front/summary/index.html new file mode 100644 index 000000000..990957079 --- /dev/null +++ b/modules/invoiceOut/front/summary/index.html @@ -0,0 +1,82 @@ + +
    {{$ctrl.summary.invoiceOut.ref}} - {{$ctrl.summary.invoiceOut.client.socialName}}
    + + + + + + + + + + + + + + +

    Desglose impositivo

    + + + + Type + Taxable base + Rate + Fee + + + + + {{tax.name}} + {{tax.taxableBase | currency: 'EUR': 2}} + {{tax.rate}}% + {{tax.vat | currency: 'EUR': 2}} + + + +
    + +

    Ticket

    + + + + Ticket id + Alias + Shipped + Amount + + + + + + + {{ticket.id}} + + + + + {{ticket.nickname}} + + + {{ticket.shipped | date: 'dd/MM/yyyy'}} + {{ticket.total | currency: 'EUR': 2}} + + + +
    +
    +
    + + + + \ No newline at end of file diff --git a/modules/invoiceOut/front/summary/index.js b/modules/invoiceOut/front/summary/index.js new file mode 100644 index 000000000..0596c616f --- /dev/null +++ b/modules/invoiceOut/front/summary/index.js @@ -0,0 +1,56 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $http, vnToken) { + this.accessToken = vnToken.token; + this.$http = $http; + this.$ = $scope; + } + + set invoiceOut(value) { + this._invoiceOut = value; + if (value && value.id) + this.getSummary(); + } + + get invoiceOut() { + return this._invoiceOut; + } + + getSummary() { + this.$http.get(`InvoiceOuts/${this.invoiceOut.id}/summary`).then(response => { + this.summary = response.data; + }); + } + + showClientDescriptor(event, clientFk) { + this.$.clientDescriptor.clientFk = clientFk; + this.$.clientDescriptor.parent = event.target; + this.$.clientDescriptor.show(); + event.preventDefault(); + } + + showTicketDescriptor(event, ticketFk) { + this.$.ticketDescriptor.ticketFk = ticketFk; + this.$.ticketDescriptor.parent = event.target; + this.$.ticketDescriptor.show(); + event.preventDefault(); + } + + preview(event, invoiceOut) { + this.selectedInvoiceOut = invoiceOut; + this.$.invoiceOutSummaryDialog.show(); + event.preventDefault(); + } +} + +Controller.$inject = ['$scope', '$http', 'vnToken']; + +ngModule.component('vnInvoiceOutSummary', { + template: require('./index.html'), + controller: Controller, + bindings: { + invoiceOut: '<' + } +}); diff --git a/modules/invoiceOut/front/summary/index.spec.js b/modules/invoiceOut/front/summary/index.spec.js new file mode 100644 index 000000000..f6ab4cb91 --- /dev/null +++ b/modules/invoiceOut/front/summary/index.spec.js @@ -0,0 +1,27 @@ +import './index.js'; + +describe('InvoiceOut', () => { + describe('Component summary', () => { + let controller; + let $httpBackend; + + beforeEach(ngModule('invoiceOut')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + controller = $componentController('vnInvoiceOutSummary'); + controller.invoiceOut = {id: 1}; + })); + + describe('getSummary()', () => { + it('should perform a query to set summary', () => { + $httpBackend.when('GET', `InvoiceOuts/1/summary`).respond(200, 'the data you are looking for'); + $httpBackend.expect('GET', `InvoiceOuts/1/summary`); + controller.getSummary(); + $httpBackend.flush(); + + expect(controller.summary).toEqual('the data you are looking for'); + }); + }); + }); +}); diff --git a/modules/invoiceOut/front/summary/locale/es.yml b/modules/invoiceOut/front/summary/locale/es.yml new file mode 100644 index 000000000..d1b4a2406 --- /dev/null +++ b/modules/invoiceOut/front/summary/locale/es.yml @@ -0,0 +1,11 @@ +Date: Fecha +Created: Creada +Due: Vencimiento +Booked: Asentado +General VAT: IVA general +Reduced VAT: IVA reducido +Shipped: F. envío +Type: Tipo +Rate: Tasa +Fee: Cuota +Taxable base: Base imp. \ No newline at end of file diff --git a/modules/invoiceOut/front/summary/style.scss b/modules/invoiceOut/front/summary/style.scss new file mode 100644 index 000000000..dcad44362 --- /dev/null +++ b/modules/invoiceOut/front/summary/style.scss @@ -0,0 +1,10 @@ +@import "variables"; + + +vn-invoice-out-summary .summary { + max-width: $width-lg; + + vn-icon[icon=insert_drive_file]{ + color: $color-font-secondary; + } +} \ No newline at end of file diff --git a/modules/item/back/methods/item-barcode/specs/toItem.spec.js b/modules/item/back/methods/item-barcode/specs/toItem.spec.js new file mode 100644 index 000000000..9e81dc590 --- /dev/null +++ b/modules/item/back/methods/item-barcode/specs/toItem.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('item-barcode toItem()', () => { + it('should return the same number if there is a barcode and a item with the same ID', async() => { + let barcode = 3; + let result = await app.models.ItemBarcode.toItem(barcode); + + expect(result).toBe(3); + }); +}); diff --git a/modules/item/back/methods/item-barcode/toItem.js b/modules/item/back/methods/item-barcode/toItem.js new file mode 100644 index 000000000..0fbbf4508 --- /dev/null +++ b/modules/item/back/methods/item-barcode/toItem.js @@ -0,0 +1,28 @@ +module.exports = Self => { + Self.remoteMethod('toItem', { + description: 'Returns last entries', + accessType: 'READ', + accepts: [{ + arg: 'barcode', + type: 'Number', + required: true, + description: 'barcode' + }], + returns: { + type: 'Number', + root: true + }, + http: { + path: `/:barcode/toItem`, + verb: 'GET' + } + }); + + Self.toItem = async barcode => { + let query = `SELECT vn.barcodeToItem(?)`; + let [item] = await Self.rawSql(query, [barcode]); + if (item) + item = Object.values(item); + return item[0]; + }; +}; diff --git a/modules/item/back/methods/item-tag/filterItemTags.js b/modules/item/back/methods/item-tag/filterItemTags.js new file mode 100644 index 000000000..ed5973c17 --- /dev/null +++ b/modules/item/back/methods/item-tag/filterItemTags.js @@ -0,0 +1,41 @@ +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethod('filterItemTags', { + description: 'Returns the distinct values of a tag property', + accessType: 'READ', + accepts: [{ + arg: 'tagFk', + type: 'number', + required: true, + description: 'The foreign key from tag table', + http: {source: 'path'} + }, { + arg: 'filter', + type: 'Object', + description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string` + }], + returns: { + root: true, + type: ['object'] + }, + http: { + path: `/filterItemTags/:tagFk`, + verb: 'get' + } + }); + + Self.filterItemTags = async(tagFk, filter) => { + let conn = Self.dataSource.connector; + let where = {tagFk: tagFk}; + myFilter = mergeFilters(filter, {where}); + + stmt = new ParameterizedSQL( + `SELECT DISTINCT(value) + FROM itemTag`); + stmt.merge(conn.makeSuffix(myFilter)); + + return await conn.executeStmt(stmt); + }; +}; diff --git a/modules/item/back/methods/item-tag/specs/filterItemTags.spec.js b/modules/item/back/methods/item-tag/specs/filterItemTags.spec.js new file mode 100644 index 000000000..272367327 --- /dev/null +++ b/modules/item/back/methods/item-tag/specs/filterItemTags.spec.js @@ -0,0 +1,9 @@ +const app = require('vn-loopback/server/server'); + +describe('item filterItemTags()', () => { + it('should filter ItemTags table', async() => { + let [result] = await app.models.ItemTag.filterItemTags(1, {}); + + expect(result.value).toEqual('Black'); + }); +}); diff --git a/modules/item/back/methods/item/clone.js b/modules/item/back/methods/item/clone.js new file mode 100644 index 000000000..f543164fc --- /dev/null +++ b/modules/item/back/methods/item/clone.js @@ -0,0 +1,128 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethod('clone', { + description: 'clone item', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'origin itemId', + http: {source: 'path'} + }], + returns: { + type: 'Object', + description: 'new cloned itemId', + root: true, + }, + http: { + path: `/:id/clone`, + verb: 'post' + } + }); + + Self.clone = async itemId => { + let tx = await Self.beginTransaction({}); + + try { + let options = {transaction: tx}; + + const origin = await Self.findById(itemId, null, options); + if (!origin) + throw new UserError(`This item doesn't exists`); + + origin.itemTag = undefined; + origin.description = undefined; + origin.image = undefined; + origin.comment = undefined; + origin.size = undefined; + + const newItem = await Self.create(origin, options); + + await cloneTaxes(origin.id, newItem.id, options); + await cloneBotanical(origin.id, newItem.id, options); + await cloneTags(origin.id, newItem.id, options); + + await tx.commit(); + return newItem; + } catch (e) { + await tx.rollback(); + throw e; + } + }; + + /** + * Clone original taxes to new item + * @param {Integer} originalId - Original item id + * @param {Integer} newId - New item id + * @param {Object} options - Transaction options + */ + async function cloneTaxes(originalId, newId, options) { + const models = Self.app.models; + const originalTaxes = await models.ItemTaxCountry.find({ + where: {itemFk: originalId}, + fields: ['botanical', 'countryFk', 'taxClassFk'] + }, options); + + const promises = []; + for (tax of originalTaxes) { + tax.itemFk = newId; + + const newTax = models.ItemTaxCountry.upsertWithWhere({ + itemFk: newId, + countryFk: tax.countryFk, + }, tax, options); + + promises.push(newTax); + } + + await Promise.all(promises); + } + + /** + * Clone original botanical to new item + * @param {Integer} originalId - Original item id + * @param {Integer} newId - New item id + * @param {Object} options - Transaction options + */ + async function cloneBotanical(originalId, newId, options) { + const models = Self.app.models; + const botanical = await models.ItemBotanical.findOne({ + where: {itemFk: originalId}, + fields: ['botanical', 'genusFk', 'specieFk'] + }, options); + + if (botanical) { + botanical.itemFk = newId; + + await models.ItemBotanical.create(botanical, options); + } + } + + /** + * Clone original item tags to new item + * @param {Integer} originalId - Original item id + * @param {Integer} newId - New item id + * @param {Object} options - Transaction options + */ + async function cloneTags(originalId, newId, options) { + const models = Self.app.models; + const originalTags = await models.ItemTag.find({ + where: { + itemFk: originalId + }, + fields: ['tagFk', 'value', 'priority'] + }, options); + + const promises = []; + for (tag of originalTags) { + tag.itemFk = newId; + const newItemTag = models.ItemTag.create(tag, options); + + promises.push(newItemTag); + } + + await Promise.all(promises); + } +}; diff --git a/modules/item/back/methods/item/filter.js b/modules/item/back/methods/item/filter.js new file mode 100644 index 000000000..ad7edfa8c --- /dev/null +++ b/modules/item/back/methods/item/filter.js @@ -0,0 +1,172 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const buildFilter = require('vn-loopback/util/filter').buildFilter; +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethodCtx('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accessType: 'READ', + accepts: [ + { + arg: 'filter', + type: 'Object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + http: {source: 'query'} + }, { + arg: 'tags', + type: ['Object'], + description: 'List of tags to filter with', + http: {source: 'query'} + }, { + arg: 'search', + type: 'String', + description: `If it's and integer searchs by id, otherwise it searchs by name`, + http: {source: 'query'} + }, { + arg: 'id', + type: 'Integer', + description: 'Item id', + http: {source: 'query'} + }, { + arg: 'categoryFk', + type: 'Integer', + description: 'Category id', + http: {source: 'query'} + }, { + arg: 'typeFk', + type: 'Integer', + description: 'Type id', + http: {source: 'query'} + }, { + arg: 'isActive', + type: 'Boolean', + description: 'Whether the the item is o not active', + http: {source: 'query'} + }, { + arg: 'salesPersonFk', + type: 'Integer', + description: 'The buyer of the item', + http: {source: 'query'} + } + ], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/filter`, + verb: 'GET' + } + }); + + Self.filter = async(ctx, filter) => { + let conn = Self.dataSource.connector; + let codeWhere; + + if (ctx.args.search) { + let items = await Self.app.models.ItemBarcode.find({ + where: {code: ctx.args.search}, + fields: ['itemFk'] + }); + let itemIds = []; + for (const item of items) + itemIds.push(item.itemFk); + + codeWhere = {'i.id': {inq: itemIds}}; + } + + let where = buildFilter(ctx.args, (param, value) => { + switch (param) { + case 'search': + return /^\d+$/.test(value) + ? {or: [{'i.id': value}, codeWhere]} + : {or: [{'i.name': {like: `%${value}%`}}, codeWhere]}; + case 'id': + return {'i.id': value}; + case 'description': + return {'i.description': {like: `%${value}%`}}; + case 'categoryFk': + return {'ic.id': value}; + case 'salesPersonFk': + return {'t.workerFk': value}; + case 'typeFk': + return {'i.typeFk': value}; + case 'isActive': + return {'i.isActive': value}; + } + }); + filter = mergeFilters(filter, {where}); + + let stmts = []; + let stmt; + + stmt = new ParameterizedSQL( + `SELECT i.id, + i.image, + i.name, + i.description, + i.size, + i.tag5, i.value5, + i.tag6, i.value6, + i.tag7, i.value7, + i.tag8, i.value8, + i.tag9, i.value9, + i.tag10, i.value10, + i.subName, + i.isActive, + t.name type, + t.workerFk buyerFk, + u.nickname userNickname, + intr.description AS intrastat, + i.stems, + ori.code AS origin, + ic.name AS category, + i.density, + b.grouping, + b.packing, + itn.code AS niche, @visibleCalc + FROM item i + LEFT JOIN itemType t ON t.id = i.typeFk + LEFT JOIN itemCategory ic ON ic.id = t.categoryFk + LEFT JOIN worker w ON w.id = t.workerFk + LEFT JOIN account.user u ON u.id = w.userFk + LEFT JOIN intrastat intr ON intr.id = i.intrastatFk + LEFT JOIN producer pr ON pr.id = i.producerFk + LEFT JOIN origin ori ON ori.id = i.originFk + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = t.warehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN itemPlacement itn ON itn.itemFk = i.id AND itn.warehouseFk = t.warehouseFk` + ); + + if (ctx.args.tags) { + let i = 1; + for (const tag of ctx.args.tags) { + const tAlias = `it${i++}`; + + if (tag.tagFk) { + stmt.merge({ + sql: `JOIN vn.itemTag ${tAlias} ON ${tAlias}.itemFk = i.id + AND ${tAlias}.tagFk = ? + AND ${tAlias}.value LIKE ?`, + params: [tag.tagFk, `%${tag.value}%`], + }); + } else { + stmt.merge({ + sql: `JOIN vn.itemTag ${tAlias} ON ${tAlias}.itemFk = i.id + AND ${tAlias}.value LIKE ?`, + params: [`%${tag.value}%`], + }); + } + } + } + + stmt.merge(conn.makeWhere(filter.where)); + stmt.merge(conn.makePagination(filter)); + + let itemsIndex = stmts.push(stmt) - 1; + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + return itemsIndex === 0 ? result : result[itemsIndex]; + }; +}; diff --git a/modules/item/back/methods/item/getCard.js b/modules/item/back/methods/item/getCard.js new file mode 100644 index 000000000..9780c5601 --- /dev/null +++ b/modules/item/back/methods/item/getCard.js @@ -0,0 +1,65 @@ +module.exports = Self => { + Self.remoteMethod('getCard', { + description: 'Return the card for a given item id', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The item id', + http: {source: 'path'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/getCard`, + verb: 'GET' + } + }); + + Self.getCard = async id => { + let item = {}; + + // Item basic data + let filter = { + where: {id: id}, + include: [ + { + relation: 'itemType', + scope: { + fields: ['id', 'name', 'workerFk', 'warehouseFk'], + include: [{ + relation: 'worker', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + }] + } + }, + { + relation: 'tags', + scope: { + fields: ['id', 'value', 'tagFk'], + include: [{ + relation: 'tag', + scope: { + fields: ['id', 'name'] + } + }] + } + } + ] + }; + [item] = await Self.app.models.Item.find(filter); + + return item; + }; +}; diff --git a/modules/item/back/methods/item/getDiary.js b/modules/item/back/methods/item/getDiary.js new file mode 100644 index 000000000..5d8259867 --- /dev/null +++ b/modules/item/back/methods/item/getDiary.js @@ -0,0 +1,27 @@ +module.exports = Self => { + Self.remoteMethod('getDiary', { + description: 'Returns the ', + accessType: 'READ', + accepts: [{ + arg: 'filter', + type: 'Object', + required: true, + description: 'Filter defining where and paginated data', + http: {source: 'query'} + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/getDiary`, + verb: 'GET' + } + }); + + Self.getDiary = async filter => { + let where = filter.where; + let [diary] = await Self.rawSql(`CALL vn.itemDiary(?, ?)`, [where.itemFk, where.warehouseFk]); + return diary; + }; +}; diff --git a/modules/item/back/methods/item/getLastEntries.js b/modules/item/back/methods/item/getLastEntries.js new file mode 100644 index 000000000..bab808cef --- /dev/null +++ b/modules/item/back/methods/item/getLastEntries.js @@ -0,0 +1,27 @@ +module.exports = Self => { + Self.remoteMethod('getLastEntries', { + description: 'Returns last entries', + accessType: 'READ', + accepts: [{ + arg: 'filter', + type: 'object', + required: true, + description: 'itemFk, id' + }], + returns: { + type: 'Array', + root: true + }, + http: { + path: `/getLastEntries`, + verb: 'GET' + } + }); + + Self.getLastEntries = async filter => { + let where = filter.where; + let query = `CALL vn.itemLastEntries(?, ?)`; + let [lastEntries] = await Self.rawSql(query, [where.itemFk, where.date]); + return lastEntries; + }; +}; diff --git a/modules/item/back/methods/item/getSummary.js b/modules/item/back/methods/item/getSummary.js new file mode 100644 index 000000000..4fb9d9ed1 --- /dev/null +++ b/modules/item/back/methods/item/getSummary.js @@ -0,0 +1,115 @@ +module.exports = Self => { + Self.remoteMethod('getSummary', { + description: 'return the item information', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The item id', + http: {source: 'path'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/getSummary`, + verb: 'GET' + } + }); + + Self.getSummary = async id => { + let promises = []; + let summary = {}; + + // Item basic data and taxes + let filter = { + where: {id: id}, + include: [ + {relation: 'itemType', + scope: { + fields: ['id', 'name', 'workerFk', 'warehouseFk'], + include: [{ + relation: 'worker', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + }] + } + }, + {relation: 'intrastat'}, + {relation: 'itemBarcode'}, + {relation: 'expense'}, + {relation: 'origin'}, + {relation: 'taxes', + scope: { + fields: ['id', 'countryFk', 'taxClassFk'], + include: [{ + relation: 'country', + scope: { + fields: ['id', 'country'] + } + }, { + relation: 'taxClass', + scope: { + fields: ['id', 'description'] + } + }] + } + } + ] + }; + promises.push(Self.app.models.Item.find(filter)); + + // Tags + filter = { + where: { + itemFk: id + }, + order: 'priority', + include: { + relation: 'tag' + } + }; + promises.push(Self.app.models.ItemTag.find(filter)); + + // Botanical + filter = { + where: {itemFk: id}, + include: [{relation: 'genus'}, {relation: 'specie'}] + }; + promises.push(Self.app.models.ItemBotanical.find(filter)); + + // Niches + filter = { + where: {itemFk: id}, + include: {relation: 'warehouse'} + }; + promises.push(Self.app.models.ItemNiche.find(filter)); + + let res = await Promise.all(promises); + + [summary.item] = res[0]; + summary.tags = res[1]; + [summary.botanical] = res[2]; + summary.niches = res[3]; + + // Visible Avaible + let query = ` + CALL vn.item_getVisibleAvailable(?,curdate(),?,?)`; + + let options = [summary.item.id, summary.item.itemType().warehouseFk, false]; + [res] = await Self.rawSql(query, options); + + summary.available = res[0].available ? res[0].available : '-'; + summary.visible = res[0].visible ? res[0].visible : '-'; + return summary; + }; +}; diff --git a/modules/item/back/methods/item/getVisibleAvailable.js b/modules/item/back/methods/item/getVisibleAvailable.js new file mode 100644 index 000000000..7f0855740 --- /dev/null +++ b/modules/item/back/methods/item/getVisibleAvailable.js @@ -0,0 +1,36 @@ +module.exports = Self => { + Self.remoteMethod('getVisibleAvailable', { + description: 'Returns visible and available for params', + accepts: [ + { + arg: 'id', + type: 'Number', + required: true, + }, + { + arg: 'warehouseFk', + type: 'Number', + required: true, + }], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/:id/getVisibleAvailable`, + verb: 'GET' + } + }); + + Self.getVisibleAvailable = async(id, warehouseFk) => { + let query = ` + CALL vn.item_getVisibleAvailable(?,curdate(),?,?)`; + + let options = [id, warehouseFk, false]; + [res] = await Self.rawSql(query, options); + + return { + available: res[0].available, + visible: res[0].visible}; + }; +}; diff --git a/modules/item/back/methods/item/getWasteDetail.js b/modules/item/back/methods/item/getWasteDetail.js new file mode 100644 index 000000000..906269044 --- /dev/null +++ b/modules/item/back/methods/item/getWasteDetail.js @@ -0,0 +1,41 @@ +module.exports = Self => { + Self.remoteMethod('getWasteDetail', { + description: 'Returns the ', + accessType: 'READ', + accepts: [], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/getWasteDetail`, + verb: 'GET' + } + }); + + Self.getWasteDetail = async() => { + const [wastes] = await Self.rawSql(`CALL bs.weekWaste_getDetail()`); + + const details = []; + + for (let waste of wastes) { + const buyerName = waste.buyer; + + let buyerDetail = details.find(waste => { + return waste.buyer == buyerName; + }); + + if (!buyerDetail) { + buyerDetail = { + buyer: buyerName, + lines: [] + }; + details.push(buyerDetail); + } + + buyerDetail.lines.push(waste); + } + + return details; + }; +}; diff --git a/modules/item/back/methods/item/new.js b/modules/item/back/methods/item/new.js new file mode 100644 index 000000000..1d3f6f230 --- /dev/null +++ b/modules/item/back/methods/item/new.js @@ -0,0 +1,73 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethod('new', { + description: 'Create a new item and returns the new ID', + accessType: 'WRITE', + accepts: [{ + arg: 'params', + type: 'object', + http: {source: 'body'} + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/new`, + verb: 'post' + } + }); + + Self.new = async params => { + let validUpdateParams = [ + 'provisionalName', + 'typeFk', + 'intrastatFk', + 'originFk', + 'relevancy' + ]; + + for (const key in params) { + if (validUpdateParams.indexOf(key) === -1) + throw new UserError(`You don't have enough privileges to do that`); + } + + let tx = await Self.beginTransaction({}); + try { + let options = {transaction: tx}; + + let provisionalName = params.provisionalName; + delete params.provisionalName; + + let item = await Self.app.models.Item.create(params, options); + + let typeTags = await Self.app.models.ItemTypeTag.find({where: {itemTypeFk: item.typeFk}}); + let query = `SET @isTriggerDisabled = TRUE`; + await Self.rawSql(query, null, options); + + let nameTag = await Self.app.models.Tag.findOne({where: {name: 'Nombre temporal'}}); + + let newTags = []; + + newTags.push({itemFk: item.id, tagFk: nameTag.id, value: provisionalName, priority: '2'}); + typeTags.forEach(typeTag => { + newTags.push({itemFk: item.id, tagFk: typeTag.tagFk, value: '', priority: typeTag.priority}); + }); + + await Self.app.models.ItemTag.create(newTags, options); + + query = `SET @isTriggerDisabled = FALSE`; + await Self.rawSql(query, null, options); + + + query = `CALL vn.itemRefreshTags(?)`; + await Self.rawSql(query, [item.id], options); + await tx.commit(); + return item; + } catch (e) { + await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/item/back/methods/item/regularize.js b/modules/item/back/methods/item/regularize.js new file mode 100644 index 000000000..b9c646086 --- /dev/null +++ b/modules/item/back/methods/item/regularize.js @@ -0,0 +1,126 @@ +module.exports = Self => { + Self.remoteMethodCtx('regularize', { + description: 'Sends items to the trash', + accessType: 'WRITE', + accepts: [{ + arg: 'itemFk', + type: 'number', + required: true, + description: 'The item id', + }, { + arg: 'quantity', + type: 'number', + required: true, + description: 'The visible quantity', + }, { + arg: 'warehouseFk', + type: 'number', + required: true, + description: 'The id of the warehouse where the inventory happened', + }], + returns: { + type: 'boolean', + root: true + }, + http: { + path: `/regularize`, + verb: 'post' + } + }); + + Self.regularize = async(ctx, itemFk, quantity, warehouseFk) => { + const userId = ctx.req.accessToken.userId; + const models = Self.app.models; + + const itemDestination = await models.ClaimDestination.findOne({ + include: { + relation: 'address', + scope: { + fields: ['clientFk'] + } + }, + where: {description: 'Corregido'} + }); + + let tx = await Self.beginTransaction({}); + try { + let options = {transaction: tx}; + + let item = await models.Item.findById(itemFk); + + let ticketFk = await getTicketId({ + clientFk: itemDestination.address.clientFk, + addressFk: itemDestination.addressFk, + warehouseFk: warehouseFk + }, options); + + if (!ticketFk) { + ticketFk = await createTicket(ctx, { + clientFk: itemDestination.address().clientFk, + addressFk: itemDestination.addressFk, + warehouseFk: warehouseFk, + userId: userId + }, options); + } + + + let query = ` + CALL vn.item_getVisibleAvailable(?,curdate(),?,?)`; + + let params = [itemFk, warehouseFk, true]; + let [res] = await Self.rawSql(query, params, options); + + let newQuantity = res[0].visible - quantity; + + await models.Sale.create({ + ticketFk: ticketFk, + itemFk: itemFk, + concept: item.name, + quantity: newQuantity, + discount: 100 + }, options); + + await tx.commit(); + return ticketFk; + } catch (e) { + await tx.rollback(); + throw e; + } + + async function createTicket(ctx, params, options) { + let ticket = await Self.app.models.Ticket.new( + ctx, + { + shipped: new Date(), + landed: new Date(), + clientFk: params.clientFk, + warehouseFk: params.warehouseFk, + companyFk: params.companyFk, + addressFk: params.addressFk, + userId: params.userId + }, options); + + return ticket.id; + } + + + async function getTicketId(params, options) { + const minDate = new Date(); + minDate.setHours(0, 0, 0, 0); + + const maxDate = new Date(); + maxDate.setHours(23, 59, 59, 59); + + let ticket = await Self.app.models.Ticket.findOne({ + where: { + addressFk: params.addressFk, + warehouseFk: params.warehouseFk, + shipped: {between: [minDate, maxDate]}, + landed: {between: [minDate, maxDate]} + } + }, options); + + return ticket && ticket.id; + } + }; +}; diff --git a/modules/item/back/methods/item/specs/clone.spec.js b/modules/item/back/methods/item/specs/clone.spec.js new file mode 100644 index 000000000..55142ee63 --- /dev/null +++ b/modules/item/back/methods/item/specs/clone.spec.js @@ -0,0 +1,37 @@ +const app = require('vn-loopback/server/server'); + +describe('item clone()', () => { + let nextItemId; + + beforeEach(async() => { + let query = `SELECT i1.id + 1 as id FROM vn.item i1 + LEFT JOIN vn.item i2 ON i1.id + 1 = i2.id + WHERE i2.id IS NULL ORDER BY i1.id LIMIT 1`; + + [nextAvailableId] = await app.models.Item.rawSql(query); + nextItemId = nextAvailableId.id; + }); + + it('should clone the given item and it should have the expected id', async() => { + let itemFk = 1; + let result = await app.models.Item.clone(itemFk); + + expect(result.id).toEqual(nextItemId); + expect(result.image).toBeUndefined(); + expect(result.itemTag).toBeUndefined(); + expect(result.comment).toBeUndefined(); + expect(result.description).toBeUndefined(); + }); + + it('should attempt to clone the given item but give an error as it doesnt exist', async() => { + let error; + let itemFk = 999; + await app.models.Item.clone(itemFk) + .catch(e => { + expect(e.message).toContain(`This item doesn't exists`); + error = e; + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/modules/item/back/methods/item/specs/filter.spec.js b/modules/item/back/methods/item/specs/filter.spec.js new file mode 100644 index 000000000..72175ccc4 --- /dev/null +++ b/modules/item/back/methods/item/specs/filter.spec.js @@ -0,0 +1,30 @@ +const app = require('vn-loopback/server/server'); + +describe('item filter()', () => { + it('should return 1 result filtering by id', async() => { + let filter = {}; + let result = await app.models.Item.filter({args: {filter: filter, search: 1}}); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(1); + }); + + it('should return 1 result filtering by barcode', async() => { + let filter = {}; + let result = await app.models.Item.filter({args: {filter: filter, search: 4444444444}}); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(2); + }); + + it('should return 2 results using filter and tags', async() => { + let filter = { + order: 'isActive ASC, name', + limit: 8 + }; + let tags = [{value: 'medical box', tagFk: 58}]; + let result = await app.models.Item.filter({args: {filter: filter, typeFk: 5, tags: tags}}); + + expect(result.length).toEqual(2); + }); +}); diff --git a/modules/item/back/methods/item/specs/getDiary.spec.js b/modules/item/back/methods/item/specs/getDiary.spec.js new file mode 100644 index 000000000..d47ac1d7d --- /dev/null +++ b/modules/item/back/methods/item/specs/getDiary.spec.js @@ -0,0 +1,14 @@ +const app = require('vn-loopback/server/server'); + +describe('item getDiary()', () => { + it('should check the property balance of the 4 resultant entries', async() => { + let params = {where: {itemFk: 1, warehouseFk: 2}}; + let result = await app.models.Item.getDiary(params); + + expect(result.length).toBe(4); + expect(result[0].balance).toBe(-100); + expect(result[1].balance).toBe(-110); + expect(result[2].balance).toBe(-110); + expect(result[3].balance).toBe(-210); + }); +}); diff --git a/modules/item/back/methods/item/specs/getLastEntries.spec.js b/modules/item/back/methods/item/specs/getLastEntries.spec.js new file mode 100644 index 000000000..5c996d8e3 --- /dev/null +++ b/modules/item/back/methods/item/specs/getLastEntries.spec.js @@ -0,0 +1,22 @@ +const app = require('vn-loopback/server/server'); + +describe('item getLastEntries()', () => { + it('should return one entry for a given item', async() => { + let date = new Date(); + let filter = {where: {itemFk: 1, date: date}}; + let result = await app.models.Item.getLastEntries(filter); + + expect(result.length).toEqual(1); + }); + + it('should return five entries for a given item', async() => { + let date = new Date(); + + date.setMonth(date.getMonth() - 2, 1); + + let filter = {where: {itemFk: 1, date: date}}; + let result = await app.models.Item.getLastEntries(filter); + + expect(result.length).toEqual(5); + }); +}); diff --git a/modules/item/back/methods/item/specs/getSummary.spec.js b/modules/item/back/methods/item/specs/getSummary.spec.js new file mode 100644 index 000000000..2dfa0cd99 --- /dev/null +++ b/modules/item/back/methods/item/specs/getSummary.spec.js @@ -0,0 +1,15 @@ +const app = require('vn-loopback/server/server'); + +describe('item getSummary()', () => { + it('should return summary with item, tags, botanical, niches, available and visible defined ', async() => { + let result = await app.models.Item.getSummary(1); + let keys = Object.keys(result); + + expect(keys).toContain('item'); + expect(keys).toContain('tags'); + expect(keys).toContain('botanical'); + expect(keys).toContain('niches'); + expect(keys).toContain('available'); + expect(keys).toContain('visible'); + }); +}); diff --git a/modules/item/back/methods/item/specs/getWasteDetail.spec.js b/modules/item/back/methods/item/specs/getWasteDetail.spec.js new file mode 100644 index 000000000..1874371a0 --- /dev/null +++ b/modules/item/back/methods/item/specs/getWasteDetail.spec.js @@ -0,0 +1,23 @@ +const app = require('vn-loopback/server/server'); + +describe('item getWasteDetail()', () => { + it('should check for the waste breakdown for every worker', async() => { + let result = await app.models.Item.getWasteDetail(); + + const firstBuyer = result[0].buyer; + const firstBuyerLines = result[0].lines; + const secondBuyer = result[1].buyer; + const secondBuyerLines = result[1].lines; + const thirdBuyer = result[2].buyer; + const thirdBuyerLines = result[2].lines; + + expect(result.length).toEqual(3); + expect(firstBuyer).toEqual('CharlesXavier'); + expect(firstBuyerLines.length).toEqual(4); + expect(secondBuyer).toEqual('DavidCharlesHaller'); + expect(secondBuyerLines.length).toEqual(3); + + expect(thirdBuyer).toEqual('HankPym'); + expect(thirdBuyerLines.length).toEqual(3); + }); +}); diff --git a/modules/item/back/methods/item/specs/new.spec.js b/modules/item/back/methods/item/specs/new.spec.js new file mode 100644 index 000000000..007178c97 --- /dev/null +++ b/modules/item/back/methods/item/specs/new.spec.js @@ -0,0 +1,42 @@ +const app = require('vn-loopback/server/server'); + +describe('item new()', () => { + let item; + + afterAll(async done => { + let sql = 'DELETE FROM vn.itemLog WHERE originFk = ?'; + await app.models.Item.rawSql(sql, [item.id]); + + sql = 'DELETE FROM vn.item WHERE id = ?'; + await app.models.Item.rawSql(sql, [item.id]); + + + done(); + }); + + it('should create a new item, adding the name as a tag', async() => { + let itemParams = { + intrastatFk: 5080000, + originFk: 1, + provisionalName: 'planta', + typeFk: 2, + relevancy: 0 + }; + item = await app.models.Item.new(itemParams); + let temporalNameTag = await app.models.Tag.findOne({where: {name: 'Nombre temporal'}}); + + let temporalName = await app.models.ItemTag.findOne({ + where: { + itemFk: item.id, + tagFk: temporalNameTag.id, + } + }); + item = await app.models.Item.findById(item.id); + + expect(item.intrastatFk).toEqual(5080000); + expect(item.originFk).toEqual(1); + expect(item.typeFk).toEqual(2); + expect(item.name).toEqual('planta'); + expect(temporalName.value).toEqual('planta'); + }); +}); diff --git a/modules/item/back/methods/item/specs/regularize.spec.js b/modules/item/back/methods/item/specs/regularize.spec.js new file mode 100644 index 000000000..a5d7c1c95 --- /dev/null +++ b/modules/item/back/methods/item/specs/regularize.spec.js @@ -0,0 +1,35 @@ +const app = require('vn-loopback/server/server'); + +describe('regularize()', () => { + const itemFk = 1; + const warehouseFk = 1; + const trashAddress = 11; + let trashTicket; + + afterAll(async done => { + await app.models.Ticket.destroyById(trashTicket.id); + + done(); + }); + + it('should create a new ticket and add a line', async() => { + let ctx = {req: {accessToken: {userId: 18}}}; + + + let query = `CALL vn.item_getVisibleAvailable(?,curdate(),?,?)`; + + let options = [itemFk, warehouseFk, true]; + + let [res] = await app.models.Item.rawSql(query, options); + let visible = res[0].visible; + let saleQuantity = visible - 11; + + let ticketFk = await app.models.Item.regularize(ctx, itemFk, 11, warehouseFk); + let sale = await app.models.Sale.findOne({where: {ticketFk: ticketFk}}); + trashTicket = await app.models.Ticket.findById(ticketFk); + + expect(sale.quantity).toEqual(saleQuantity); + expect(sale.discount).toEqual(100); + expect(trashTicket.addressFk).toEqual(trashAddress); + }); +}); diff --git a/modules/item/back/methods/item/specs/updateTaxes.spec.js b/modules/item/back/methods/item/specs/updateTaxes.spec.js new file mode 100644 index 000000000..c488cbc5f --- /dev/null +++ b/modules/item/back/methods/item/specs/updateTaxes.spec.js @@ -0,0 +1,42 @@ +const app = require('vn-loopback/server/server'); + +describe('item updateTaxes()', () => { + afterAll(async done => { + let taxesInFixtures = [{id: 3, taxClassFk: 1}]; + + await app.models.Item.updateTaxes(taxesInFixtures); + + done(); + }); + + it('should throw an error if the taxClassFk is blank', async() => { + let error; + let taxes = [{id: 3, taxClassFk: undefined}]; + + await app.models.Item.updateTaxes(taxes) + .catch(err => { + expect(err.message).toEqual('Tax class cannot be blank'); + error = err; + }); + + expect(error).toBeDefined(); + }); + + it('should update the tax of a given country of an item', async() => { + let taxCountry = await app.models.ItemTaxCountry.findById(3); + + expect(taxCountry.taxClassFk).toEqual(1); + + let taxes = [{id: 3, taxClassFk: 2}]; + + let result = await app.models.Item.updateTaxes(taxes); + + expect(result).toBeTruthy(); + }); + + it('should confirm the tax class was updated', async() => { + let taxCountry = await app.models.ItemTaxCountry.findById(3); + + expect(taxCountry.taxClassFk).toEqual(2); + }); +}); diff --git a/modules/item/back/methods/item/updateTaxes.js b/modules/item/back/methods/item/updateTaxes.js new file mode 100644 index 000000000..9b7ffd372 --- /dev/null +++ b/modules/item/back/methods/item/updateTaxes.js @@ -0,0 +1,38 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethod('updateTaxes', { + description: 'Updates the item taxes', + accessType: 'WRITE', + accepts: [{ + arg: 'taxes', + type: ['object'], + required: true, + description: 'The list of taxes to update', + http: {source: 'body'} + }], + returns: { + type: 'boolean', + root: true + }, + http: { + path: `/updateTaxes`, + verb: 'post' + } + }); + + Self.updateTaxes = async taxes => { + let promises = []; + for (let tax of taxes) { + if (!tax.taxClassFk) + throw new UserError('Tax class cannot be blank'); + + promises.push(Self.app.models.ItemTaxCountry.update( + {id: tax.id}, + {taxClassFk: tax.taxClassFk} + )); + } + await Promise.all(promises); + return true; + }; +}; diff --git a/modules/item/back/model-config.json b/modules/item/back/model-config.json new file mode 100644 index 000000000..db8eed9d5 --- /dev/null +++ b/modules/item/back/model-config.json @@ -0,0 +1,74 @@ +{ + "Expense": { + "dataSource": "vn" + }, + "Genus": { + "dataSource": "vn" + }, + "Ink": { + "dataSource": "vn" + }, + "Intrastat": { + "dataSource": "vn" + }, + "Item": { + "dataSource": "vn" + }, + "ItemBarcode": { + "dataSource": "vn" + }, + "ItemBotanical": { + "dataSource": "vn" + }, + "ItemCategory": { + "dataSource": "vn" + }, + "ItemLog": { + "dataSource": "vn" + }, + "ItemNiche": { + "dataSource": "vn" + }, + "ItemPlacement": { + "dataSource": "vn" + }, + "ItemTag": { + "dataSource": "vn" + }, + "ItemTaxCountry": { + "dataSource": "vn" + }, + "ItemType": { + "dataSource": "vn" + }, + "ItemTypeTag": { + "dataSource": "vn" + }, + "ItemShelvingSale": { + "dataSource": "vn" + }, + "Origin": { + "dataSource": "vn" + }, + "Producer": { + "dataSource": "vn" + }, + "Specie": { + "dataSource": "vn" + }, + "Tag": { + "dataSource": "vn" + }, + "TaxClass": { + "dataSource": "vn" + }, + "TaxCode": { + "dataSource": "vn" + }, + "TaxType": { + "dataSource": "vn" + }, + "Supplier": { + "dataSource": "vn" + } +} diff --git a/modules/item/back/models/expense.json b/modules/item/back/models/expense.json new file mode 100644 index 000000000..c0ef2c487 --- /dev/null +++ b/modules/item/back/models/expense.json @@ -0,0 +1,37 @@ +{ + "name": "Expense", + "base": "VnModel", + "options": { + "mysql": { + "table": "expence" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "name": { + "type": "String" + }, + "isWithheld": { + "type": "Number" + } + }, + "relations": { + "taxType": { + "type": "belongsTo", + "model": "TaxType", + "foreignKey": "taxTypeFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/services/item/common/models/genus.json b/modules/item/back/models/genus.json similarity index 95% rename from services/item/common/models/genus.json rename to modules/item/back/models/genus.json index 1026e6f05..48eab3169 100644 --- a/services/item/common/models/genus.json +++ b/modules/item/back/models/genus.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "genus" + "table": "edi.genus" } }, "properties": { diff --git a/services/item/common/models/ink.json b/modules/item/back/models/ink.json similarity index 94% rename from services/item/common/models/ink.json rename to modules/item/back/models/ink.json index 04117aa3b..a3cd857bf 100644 --- a/services/item/common/models/ink.json +++ b/modules/item/back/models/ink.json @@ -8,7 +8,7 @@ }, "properties": { "id": { - "type": "Number", + "type": "String", "id": true, "description": "Identifier" }, diff --git a/services/item/common/models/intrastat.json b/modules/item/back/models/intrastat.json similarity index 100% rename from services/item/common/models/intrastat.json rename to modules/item/back/models/intrastat.json diff --git a/modules/item/back/models/item-barcode.js b/modules/item/back/models/item-barcode.js new file mode 100644 index 000000000..b608a7fe9 --- /dev/null +++ b/modules/item/back/models/item-barcode.js @@ -0,0 +1,7 @@ +module.exports = Self => { + require('../methods/item-barcode/toItem')(Self); + + Self.validatesUniquenessOf('code', { + message: `Barcode must be unique` + }); +}; diff --git a/modules/item/back/models/item-barcode.json b/modules/item/back/models/item-barcode.json new file mode 100644 index 000000000..b9de53dd1 --- /dev/null +++ b/modules/item/back/models/item-barcode.json @@ -0,0 +1,32 @@ +{ + "name": "ItemBarcode", + "base": "Loggable", + "log": { + "model": "ItemLog", + "relation": "item", + "showField": "code" + }, + "options": { + "mysql": { + "table": "itemBarcode" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "code": { + "type": "String", + "required": true + } + }, + "relations": { + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk" + } + } +} diff --git a/services/item/common/models/item-botanical.json b/modules/item/back/models/item-botanical.json similarity index 85% rename from services/item/common/models/item-botanical.json rename to modules/item/back/models/item-botanical.json index 655f0d48c..12248602d 100644 --- a/services/item/common/models/item-botanical.json +++ b/modules/item/back/models/item-botanical.json @@ -1,6 +1,11 @@ { "name": "ItemBotanical", - "base": "VnModel", + "base": "Loggable", + "log": { + "model": "ItemLog", + "relation": "item", + "showField": "botanical" + }, "options": { "mysql": { "table": "itemBotanical" diff --git a/modules/item/back/models/item-category.json b/modules/item/back/models/item-category.json new file mode 100644 index 000000000..fe6d804d8 --- /dev/null +++ b/modules/item/back/models/item-category.json @@ -0,0 +1,45 @@ +{ + "name": "ItemCategory", + "base": "VnModel", + "options": { + "mysql": { + "table": "itemCategory" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "name": { + "type": "String" + }, + "display": { + "type": "Boolean" + }, + "icon": { + "type": "String" + } + }, + "relations": { + "itemTypes": { + "type": "hasMany", + "model": "ItemType", + "foreignKey": "categoryFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ], + "scope": { + "where": { + "display": {"gte": 1} + } + } +} \ No newline at end of file diff --git a/modules/item/back/models/item-log.json b/modules/item/back/models/item-log.json new file mode 100644 index 000000000..c52931193 --- /dev/null +++ b/modules/item/back/models/item-log.json @@ -0,0 +1,58 @@ +{ + "name": "ItemLog", + "base": "VnModel", + "options": { + "mysql": { + "table": "itemLog" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "forceId": false + }, + "originFk": { + "type": "Number", + "required": true + }, + "userFk": { + "type": "Number" + }, + "action": { + "type": "String", + "required": true + }, + "changedModel": { + "type": "String" + }, + "oldInstance": { + "type": "Object" + }, + "newInstance": { + "type": "Object" + }, + "creationDate": { + "type": "Date" + }, + "changedModelId": { + "type": "Number" + }, + "changedModelValue": { + "type": "String" + }, + "description": { + "type": "String" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + } + }, + "scope": { + "order": ["creationDate DESC", "id DESC"] + } +} diff --git a/modules/item/back/models/item-niche.js b/modules/item/back/models/item-niche.js new file mode 100644 index 000000000..b9e388881 --- /dev/null +++ b/modules/item/back/models/item-niche.js @@ -0,0 +1,9 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError(`The warehouse can't be repeated`); + return err; + }); +}; diff --git a/modules/item/back/models/item-niche.json b/modules/item/back/models/item-niche.json new file mode 100644 index 000000000..260eb07b9 --- /dev/null +++ b/modules/item/back/models/item-niche.json @@ -0,0 +1,42 @@ +{ + "name": "ItemNiche", + "base": "Loggable", + "log": { + "model": "ItemLog", + "relation": "item", + "showField": "code" + }, + "options": { + "mysql": { + "table": "itemPlacement" + } + }, + "properties": { + "id": { + "type": "Number", + "id": 1, + "description": "Identifier" + }, + "warehouseFk": { + "type": "Number", + "description": "Identifier" + }, + "code": { + "type": "String", + "required": true + } + }, + "relations": { + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk" + }, + "warehouse": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseFk", + "required": true + } + } +} diff --git a/services/item/common/models/item-placement.json b/modules/item/back/models/item-placement.json similarity index 100% rename from services/item/common/models/item-placement.json rename to modules/item/back/models/item-placement.json diff --git a/modules/item/back/models/item-shelving-sale.json b/modules/item/back/models/item-shelving-sale.json new file mode 100644 index 000000000..547c882a0 --- /dev/null +++ b/modules/item/back/models/item-shelving-sale.json @@ -0,0 +1,34 @@ +{ + "name": "ItemShelvingSale", + "base": "VnModel", + "options": { + "mysql": { + "table": "itemShelvingSale" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "quantity": { + "type": "Number" + }, + "created": { + "type": "Date" + } + }, + "relations": { + "sale": { + "type": "belongsTo", + "model": "Sale", + "foreignKey": "saleFk" + }, + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + } + } +} diff --git a/modules/item/back/models/item-tag.js b/modules/item/back/models/item-tag.js new file mode 100644 index 000000000..891d11558 --- /dev/null +++ b/modules/item/back/models/item-tag.js @@ -0,0 +1,13 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + require('../methods/item-tag/filterItemTags')(Self); + + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError(`The tag can't be repeated`); + if (err.code === 'ER_BAD_NULL_ERROR') + return new UserError(`Tag value cannot be blank`); + return err; + }); +}; diff --git a/modules/item/back/models/item-tag.json b/modules/item/back/models/item-tag.json new file mode 100644 index 000000000..6beeb29d3 --- /dev/null +++ b/modules/item/back/models/item-tag.json @@ -0,0 +1,56 @@ +{ + "name": "ItemTag", + "base": "Loggable", + "log": { + "model": "ItemLog", + "relation": "item", + "showField": "value" + }, + "options": { + "mysql": { + "table": "itemTag" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "value": { + "type": "String" + }, + "itemFk": { + "type": "Number", + "required": true + }, + "tagFk": { + "type": "Number", + "required": true + }, + "priority": { + "type": "Number", + "required": true + } + }, + "relations": { + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk" + }, + "tag": { + "type": "belongsTo", + "model": "Tag", + "foreignKey": "tagFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/modules/item/back/models/item-tax-country.json b/modules/item/back/models/item-tax-country.json new file mode 100644 index 000000000..24c621518 --- /dev/null +++ b/modules/item/back/models/item-tax-country.json @@ -0,0 +1,50 @@ +{ + "name": "ItemTaxCountry", + "base": "Loggable", + "log": { + "model": "ItemLog", + "relation": "item", + "showField": "countryFk" + }, + "options": { + "mysql": { + "table": "itemTaxCountry" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "effectived": { + "type": "Boolean" + }, + "itemFk": { + "type": "Number" + }, + "countryFk": { + "type": "Number" + }, + "taxClassFk": { + "type": "Number" + } + }, + "relations": { + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk" + }, + "country": { + "type": "belongsTo", + "model": "Country", + "foreignKey": "countryFk" + }, + "taxClass": { + "type": "belongsTo", + "model": "TaxClass", + "foreignKey": "taxClassFk" + } + } +} \ No newline at end of file diff --git a/modules/item/back/models/item-type-tag.json b/modules/item/back/models/item-type-tag.json new file mode 100644 index 000000000..ca374e00e --- /dev/null +++ b/modules/item/back/models/item-type-tag.json @@ -0,0 +1,31 @@ +{ + "name": "ItemTypeTag", + "base": "VnModel", + "options": { + "mysql": { + "table": "itemTypeTag" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "priority": { + "type": "Number" + } + }, + "relations": { + "type": { + "type": "belongsTo", + "model": "ItemType", + "foreignKey": "itemTypeFk" + }, + "tag": { + "type": "belongsTo", + "model": "Tag", + "foreignKey": "tagFk" + } + } +} \ No newline at end of file diff --git a/modules/item/back/models/item-type.json b/modules/item/back/models/item-type.json new file mode 100644 index 000000000..b9f038f84 --- /dev/null +++ b/modules/item/back/models/item-type.json @@ -0,0 +1,53 @@ +{ + "name": "ItemType", + "base": "VnModel", + "options": { + "mysql": { + "table": "itemType" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "code": { + "type": "String" + }, + "name": { + "type": "String" + }, + "life": { + "type": "Number" + }, + "isPackaging": { + "type": "Boolean" + } + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "warehouse": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseFk" + }, + "category": { + "type": "belongsTo", + "model": "ItemCategory", + "foreignKey": "categoryFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/modules/item/back/models/item.js b/modules/item/back/models/item.js new file mode 100644 index 000000000..6c221e94d --- /dev/null +++ b/modules/item/back/models/item.js @@ -0,0 +1,38 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + require('../methods/item/filter')(Self); + require('../methods/item/clone')(Self); + require('../methods/item/updateTaxes')(Self); + require('../methods/item/getDiary')(Self); + require('../methods/item/getLastEntries')(Self); + require('../methods/item/getSummary')(Self); + require('../methods/item/getCard')(Self); + require('../methods/item/regularize')(Self); + require('../methods/item/getVisibleAvailable')(Self); + require('../methods/item/new')(Self); + require('../methods/item/getWasteDetail')(Self); + + Self.validatesPresenceOf('originFk', {message: 'Cannot be blank'}); + + Self.observe('before save', async function(ctx) { + await Self.availableId(ctx); + }); + + Self.availableId = async function(ctx) { + if (ctx.isNewInstance) { + try { + let query = `SELECT i1.id + 1 as id FROM vn.item i1 + LEFT JOIN vn.item i2 ON i1.id + 1 = i2.id + WHERE i2.id IS NULL ORDER BY i1.id LIMIT 1`; + + let newId = await Self.rawSql(query); + + ctx.instance.id = newId[0].id; + return ctx.instance.id; + } catch (e) { + throw new UserError(e); + } + } + }; +}; diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json new file mode 100644 index 000000000..d8d1cb64d --- /dev/null +++ b/modules/item/back/models/item.json @@ -0,0 +1,179 @@ +{ + "name": "Item", + "base": "Loggable", + "log": { + "model":"ItemLog", + "showField": "id" + }, + "options": { + "mysql": { + "table": "item" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Id" + }, + "name": { + "type": "String", + "description": "Name" + }, + "size": { + "type": "Number", + "description": "Size" + }, + "category": { + "type": "String", + "description": "Category" + }, + "typeFk": { + "type": "Number", + "description": "Type", + "required": true + }, + "stems": { + "type": "Number", + "description": "Stems" + }, + "description": { + "type": "String", + "description": "Description" + }, + "isOnOffer": { + "type": "Boolean", + "description": "Offer" + }, + "isBargain": { + "type": "Boolean", + "description": "Bargain" + }, + "isActive": { + "type": "Boolean", + "description": "Active" + }, + "comment": { + "type": "String", + "description": "Comment" + }, + "relevancy": { + "type": "Number", + "description": "Relevancy" + }, + "density": { + "type": "Number", + "description": "Density" + }, + "image": { + "type": "String", + "description": "Image" + }, + "longName": { + "type": "String", + "description": "Long name" + }, + "subName": { + "type": "String", + "description": "Subname" + }, + "tag5": { + "type": "String" + }, + "value5": { + "type": "String" + }, + "tag6": { + "type": "String" + }, + "value6": { + "type": "String" + }, + "tag7": { + "type": "String" + }, + "value7": { + "type": "String" + }, + "tag8": { + "type": "String" + }, + "value8": { + "type": "String" + }, + "tag9": { + "type": "String" + }, + "value9": { + "type": "String" + }, + "tag10": { + "type": "String" + }, + "value10": { + "type": "String" + }, + "hasKgPrice": { + "type": "Boolean", + "description": "Price per Kg" + }, + "expenseFk": { + "type": "Number", + "mysql": { + "columnName": "expenceFk" + } + } + }, + "relations": { + "itemType": { + "type": "belongsTo", + "model": "ItemType", + "foreignKey": "typeFk" + }, + "ink": { + "type": "belongsTo", + "model": "Ink", + "foreignKey": "inkFk" + }, + "origin": { + "type": "belongsTo", + "model": "Origin", + "foreignKey": "originFk" + }, + "producer": { + "type": "belongsTo", + "model": "Producer", + "foreignKey": "producerFk" + }, + "intrastat": { + "type": "belongsTo", + "model": "Intrastat", + "foreignKey": "intrastatFk" + }, + "expense": { + "type": "belongsTo", + "model": "Expense", + "foreignKey": "expenseFk" + }, + "tags": { + "type": "hasMany", + "model": "ItemTag", + "foreignKey": "itemFk" + }, + "itemBarcode": { + "type": "hasMany", + "model": "ItemBarcode", + "foreignKey": "itemFk" + }, + "taxes": { + "type": "hasMany", + "model": "ItemTaxCountry", + "foreignKey": "itemFk" + }, + "itemNiche": { + "type": "hasMany", + "model": "ItemNiche", + "foreignKey": "itemFk" + } + } + } \ No newline at end of file diff --git a/services/item/common/models/origin.json b/modules/item/back/models/origin.json similarity index 100% rename from services/item/common/models/origin.json rename to modules/item/back/models/origin.json diff --git a/services/item/common/models/producer.json b/modules/item/back/models/producer.json similarity index 100% rename from services/item/common/models/producer.json rename to modules/item/back/models/producer.json diff --git a/services/item/common/models/specie.json b/modules/item/back/models/specie.json similarity index 96% rename from services/item/common/models/specie.json rename to modules/item/back/models/specie.json index afa669af3..1388be53b 100644 --- a/services/item/common/models/specie.json +++ b/modules/item/back/models/specie.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "specie" + "table": "edi.specie" } }, "properties": { diff --git a/modules/item/back/models/specs/item.spec.js b/modules/item/back/models/specs/item.spec.js new file mode 100644 index 000000000..9038c2e56 --- /dev/null +++ b/modules/item/back/models/specs/item.spec.js @@ -0,0 +1,22 @@ +const app = require('vn-loopback/server/server'); + +describe('loopback model Item', () => { + describe('availableId()', () => { + let nextItemId; + beforeEach(async() => { + let query = `SELECT i1.id + 1 as id FROM vn.item i1 + LEFT JOIN vn.item i2 ON i1.id + 1 = i2.id + WHERE i2.id IS NULL ORDER BY i1.id LIMIT 1`; + + [nextAvailableId] = await app.models.Item.rawSql(query); + nextItemId = nextAvailableId.id; + }); + + it('should return the next available id for an item', async() => { + let context = {isNewInstance: true, instance: {}}; + let result = await app.models.Item.availableId(context); + + expect(result).toEqual(nextItemId); + }); + }); +}); diff --git a/modules/item/back/models/supplier.json b/modules/item/back/models/supplier.json new file mode 100644 index 000000000..bc13e79b9 --- /dev/null +++ b/modules/item/back/models/supplier.json @@ -0,0 +1,78 @@ +{ + "name": "Supplier", + "base": "VnModel", + "options": { + "mysql": { + "table": "supplier" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "name": { + "type": "String" + }, + "account": { + "type": "Number" + }, + "countryFk": { + "type": "Number" + }, + "nif": { + "type": "String" + }, + "isFarmer": { + "type": "Boolean" + }, + "phone": { + "type": "Number" + }, + "retAccount": { + "type": "Number" + }, + "commision": { + "type": "Boolean" + }, + "created": { + "type": "Date" + }, + "poscodeFk": { + "type": "Number" + }, + "isActive": { + "type": "Boolean" + }, + "street": { + "type": "String" + }, + "city": { + "type": "String" + }, + "provinceFk": { + "type": "Number" + }, + "postCode": { + "type": "Number" + }, + "payMethodFk": { + "type": "Number" + }, + "payDemFk": { + "type": "Number" + }, + "nickname": { + "type": "String" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/services/item/common/models/tag.json b/modules/item/back/models/tag.json similarity index 76% rename from services/item/common/models/tag.json rename to modules/item/back/models/tag.json index b327c6588..4cd1ad74e 100644 --- a/services/item/common/models/tag.json +++ b/modules/item/back/models/tag.json @@ -3,8 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "tag", - "database": "vn" + "table": "tag" } }, "properties": { @@ -18,13 +17,19 @@ "required": true }, "isFree": { - "type": "Number" + "type": "Boolean" }, "sourceTable": { "type": "String" }, "unit": { "type": "String" + }, + "isQuantitative": { + "type": "Boolean", + "mysql": { + "columnName": "isQuantitatif" + } } }, "acls": [ diff --git a/services/item/common/models/tax-class.json b/modules/item/back/models/tax-class.json similarity index 100% rename from services/item/common/models/tax-class.json rename to modules/item/back/models/tax-class.json diff --git a/services/item/common/models/tax-code.json b/modules/item/back/models/tax-code.json similarity index 100% rename from services/item/common/models/tax-code.json rename to modules/item/back/models/tax-code.json diff --git a/services/item/common/models/tax-type.json b/modules/item/back/models/tax-type.json similarity index 100% rename from services/item/common/models/tax-type.json rename to modules/item/back/models/tax-type.json diff --git a/modules/item/front/barcode/index.html b/modules/item/front/barcode/index.html new file mode 100644 index 000000000..dba745d28 --- /dev/null +++ b/modules/item/front/barcode/index.html @@ -0,0 +1,47 @@ + + + + +
    + + + + + + + + + + + + + + + + + +
    diff --git a/modules/item/front/barcode/index.js b/modules/item/front/barcode/index.js new file mode 100644 index 000000000..4096ab7eb --- /dev/null +++ b/modules/item/front/barcode/index.js @@ -0,0 +1,23 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($stateParams, $scope) { + this.$stateParams = $stateParams; + this.$scope = $scope; + } + + onSubmit() { + this.$scope.watcher.check(); + this.$scope.model.save().then(() => { + this.$scope.watcher.notifySaved(); + this.$scope.model.refresh(); + }); + } +} + +Controller.$inject = ['$stateParams', '$scope']; + +ngModule.component('vnItemBarcode', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/item/front/basic-data/__snapshots__/index.spec.js.snap b/modules/item/front/basic-data/__snapshots__/index.spec.js.snap new file mode 100644 index 000000000..92219bb33 --- /dev/null +++ b/modules/item/front/basic-data/__snapshots__/index.spec.js.snap @@ -0,0 +1,3 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`vnItemBasicData Component vnItemBasicData $onChanges() should pass the data to the watcher 1`] = `"the current value of an item"`; diff --git a/modules/item/front/basic-data/index.html b/modules/item/front/basic-data/index.html new file mode 100644 index 000000000..4fe9bfe21 --- /dev/null +++ b/modules/item/front/basic-data/index.html @@ -0,0 +1,128 @@ + + + + +
    + + + + + + + + + + + + +
    {{::id}}
    +
    {{::description}}
    +
    +
    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + + + +
    diff --git a/modules/item/front/basic-data/index.js b/modules/item/front/basic-data/index.js new file mode 100644 index 000000000..123aa59cd --- /dev/null +++ b/modules/item/front/basic-data/index.js @@ -0,0 +1,24 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $timeout) { + this.$scope = $scope; + this.$timeout = $timeout; + } + + $onChanges(data) { + this.$timeout(() => { + this.$scope.watcher.data = data.item.currentValue; + }); + } +} + +Controller.$inject = ['$scope', '$timeout']; + +ngModule.component('vnItemBasicData', { + template: require('./index.html'), + bindings: { + item: '<' + }, + controller: Controller +}); diff --git a/modules/item/front/basic-data/index.spec.js b/modules/item/front/basic-data/index.spec.js new file mode 100644 index 000000000..e7578b54c --- /dev/null +++ b/modules/item/front/basic-data/index.spec.js @@ -0,0 +1,28 @@ +import './index.js'; + +describe('vnItemBasicData', () => { + describe('Component vnItemBasicData', () => { + let $scope; + let controller; + let $timeout; + + beforeEach(ngModule('item')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$timeout_) => { + $timeout = _$timeout_; + $scope = $rootScope.$new(); + controller = $componentController('vnItemBasicData', {$scope, $timeout}); + controller.$scope.watcher = {}; + })); + + describe('$onChanges()', () => { + it('should pass the data to the watcher', () => { + const data = {item: {currentValue: 'the current value of an item'}}; + controller.$onChanges(data); + $timeout.flush(); + + expect(controller.$scope.watcher.data).toMatchSnapshot(); + }); + }); + }); +}); diff --git a/modules/item/front/basic-data/locale/es.yml b/modules/item/front/basic-data/locale/es.yml new file mode 100644 index 000000000..67780557a --- /dev/null +++ b/modules/item/front/basic-data/locale/es.yml @@ -0,0 +1,8 @@ +Reference: Referencia +Full name calculates based on tags 1-3. Is not recommended to change it manually: >- + El nombre completo se calcula + basado en los tags 1-3. + No se recomienda cambiarlo manualmente +Is active: Activo +Expense: Gasto +Price in kg: Precio en kg \ No newline at end of file diff --git a/modules/item/front/botanical/index.html b/modules/item/front/botanical/index.html new file mode 100644 index 000000000..8353841b3 --- /dev/null +++ b/modules/item/front/botanical/index.html @@ -0,0 +1,47 @@ + + + + +
    + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/modules/item/front/botanical/index.js b/modules/item/front/botanical/index.js new file mode 100644 index 000000000..51161d53a --- /dev/null +++ b/modules/item/front/botanical/index.js @@ -0,0 +1,34 @@ +import ngModule from '../module'; + +class Controller { + constructor($http, $state) { + this.$http = $http; + this.$state = $state; + this.botanical = { + itemFk: this.$state.params.id + }; + } + + _getBotanical() { + let filter = { + where: {itemFk: this.$state.params.id}, + include: [{relation: 'genus'}, {relation: 'specie'}] + }; + this.$http.get(`ItemBotanicals?filter=${JSON.stringify(filter)}`) + .then(res => { + if (res.data.length) + this.botanical = res.data[0]; + }); + } + + $onInit() { + this._getBotanical(); + } +} + +Controller.$inject = ['$http', '$state']; + +ngModule.component('vnItemBotanical', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/item/front/botanical/index.spec.js b/modules/item/front/botanical/index.spec.js new file mode 100644 index 000000000..f4b6fa3c2 --- /dev/null +++ b/modules/item/front/botanical/index.spec.js @@ -0,0 +1,30 @@ +import './index.js'; + +describe('ItemBotanical', () => { + describe('Component vnItemBotanical', () => { + let $httpBackend; + let $state; + let controller; + + beforeEach(ngModule('item')); + + beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + $state = { + params: { + id: 123 + } + }; + controller = $componentController('vnItemBotanical', {$state}); + })); + + describe('_getBotanical()', () => { + it('should request to patch the propagation of botanical status', () => { + $httpBackend.whenGET('ItemBotanicals?filter={"where":{"itemFk":123},"include":[{"relation":"genus"},{"relation":"specie"}]}').respond({data: 'item'}); + $httpBackend.expectGET('ItemBotanicals?filter={"where":{"itemFk":123},"include":[{"relation":"genus"},{"relation":"specie"}]}'); + controller.$onInit(); + $httpBackend.flush(); + }); + }); + }); +}); diff --git a/modules/item/front/card/index.html b/modules/item/front/card/index.html new file mode 100644 index 000000000..f547a9e7a --- /dev/null +++ b/modules/item/front/card/index.html @@ -0,0 +1,5 @@ + + + + + diff --git a/modules/item/front/card/index.js b/modules/item/front/card/index.js new file mode 100644 index 000000000..12167500f --- /dev/null +++ b/modules/item/front/card/index.js @@ -0,0 +1,14 @@ +import ngModule from '../module'; +import ModuleCard from 'salix/components/module-card'; + +class Controller extends ModuleCard { + reload() { + this.$http.get(`Items/${this.$params.id}/getCard`) + .then(res => this.item = res.data); + } +} + +ngModule.component('vnItemCard', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/item/front/card/index.spec.js b/modules/item/front/card/index.spec.js new file mode 100644 index 000000000..c0ea80e69 --- /dev/null +++ b/modules/item/front/card/index.spec.js @@ -0,0 +1,28 @@ +import './index.js'; + +describe('Item', () => { + describe('Component vnItemCard', () => { + let controller; + let $httpBackend; + let data = {id: 1, name: 'fooName'}; + + beforeEach(ngModule('item')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_, $stateParams) => { + $httpBackend = _$httpBackend_; + + let $element = angular.element('
    '); + controller = $componentController('vnItemCard', {$element}); + + $stateParams.id = data.id; + $httpBackend.whenRoute('GET', 'Items/:id/getCard').respond(data); + })); + + it('should request data and set it on the controller', () => { + controller.reload(); + $httpBackend.flush(); + + expect(controller.item).toEqual(data); + }); + }); +}); diff --git a/modules/item/front/create/index.html b/modules/item/front/create/index.html new file mode 100644 index 000000000..0c00aa8e9 --- /dev/null +++ b/modules/item/front/create/index.html @@ -0,0 +1,63 @@ + + + +
    + + + + + + + + +
    {{::code}}
    +
    {{::name}}
    +
    +
    + + +
    {{::id}}
    +
    {{::description}}
    +
    +
    +
    + + + + +
    + + + + + + +
    diff --git a/modules/item/front/create/index.js b/modules/item/front/create/index.js new file mode 100644 index 000000000..646baa8cd --- /dev/null +++ b/modules/item/front/create/index.js @@ -0,0 +1,24 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $state) { + this.$ = $scope; + this.$state = $state; + this.item = { + relevancy: 0 + }; + } + + onSubmit() { + this.$.watcher.submit().then( + json => this.$state.go('item.card.basicData', {id: json.data.id}) + ); + } +} + +Controller.$inject = ['$scope', '$state']; + +ngModule.component('vnItemCreate', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/item/front/create/index.spec.js b/modules/item/front/create/index.spec.js new file mode 100644 index 000000000..cb58cdaa3 --- /dev/null +++ b/modules/item/front/create/index.spec.js @@ -0,0 +1,38 @@ +import './index.js'; + +describe('Item', () => { + describe('Component vnItemCreate', () => { + let $componentController; + let $scope; + let $state; + let controller; + + beforeEach(ngModule('item')); + + beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$state_) => { + $componentController = _$componentController_; + $scope = $rootScope.$new(); + $state = _$state_; + $scope.watcher = { + submit: () => { + return { + then: callback => { + callback({data: {id: 1}}); + } + }; + } + }; + controller = $componentController('vnItemCreate', {$scope: $scope}); + })); + + describe('onSubmit()', () => { + it(`should call submit() on the watcher then expect a callback`, () => { + spyOn($state, 'go'); + controller.onSubmit(); + + expect(controller.$state.go).toHaveBeenCalledWith('item.card.basicData', {id: 1}); + }); + }); + }); +}); + diff --git a/modules/item/front/create/locale/es.yml b/modules/item/front/create/locale/es.yml new file mode 100644 index 000000000..041826e1c --- /dev/null +++ b/modules/item/front/create/locale/es.yml @@ -0,0 +1 @@ +Temporal name: Nombre temporal \ No newline at end of file diff --git a/modules/item/front/descriptor-popover/index.html b/modules/item/front/descriptor-popover/index.html new file mode 100644 index 000000000..41b4badb4 --- /dev/null +++ b/modules/item/front/descriptor-popover/index.html @@ -0,0 +1,12 @@ + + + + + + diff --git a/modules/item/front/descriptor-popover/index.js b/modules/item/front/descriptor-popover/index.js new file mode 100644 index 000000000..42886fd58 --- /dev/null +++ b/modules/item/front/descriptor-popover/index.js @@ -0,0 +1,80 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + constructor($element, $scope, $http, $timeout, $q) { + super($element, $scope); + this.$timeout = $timeout; + this.$http = $http; + this.$q = $q; + this.item = null; + this._quicklinks = {}; + } + + set itemFk(id) { + if (id == this._itemFk) return; + + this._itemFk = id; + this.item = null; + this._quicklinks = { + btnThree: { + icon: 'icon-transaction', + state: `item.card.diary({ + id: ${id}, + })`, + tooltip: 'Item diary' + } + }; + this.getCard(); + } + + set item(value) { + this._item = value; + this.$timeout(() => this.$.popover.relocate()); + } + + get item() { + return this._item; + } + + get quicklinks() { + return this._quicklinks; + } + + set quicklinks(value = {}) { + Object.keys(value).forEach(key => { + this._quicklinks[key] = value[key]; + }); + } + + show() { + this.$.popover.parent = this.parent; + this.$.popover.show(); + } + + getCard() { + if (this.canceler) + this.canceler.resolve(); + + this.canceler = this.$q.defer(); + + let options = {timeout: this.canceler.promise}; + this.$http.get(`Items/${this._itemFk}/getCard`, options).then( + response => { + this.item = response.data; + this.canceler = null; + } + ); + } +} +Controller.$inject = ['$element', '$scope', '$http', '$timeout', '$q']; + +ngModule.component('vnItemDescriptorPopover', { + template: require('./index.html'), + controller: Controller, + bindings: { + itemFk: '<', + quicklinks: '<' + } +}); diff --git a/modules/item/front/descriptor-popover/index.spec.js b/modules/item/front/descriptor-popover/index.spec.js new file mode 100644 index 000000000..67708faf2 --- /dev/null +++ b/modules/item/front/descriptor-popover/index.spec.js @@ -0,0 +1,80 @@ +import './index.js'; + +describe('Item', () => { + describe('Component vnItemDescriptorPopover', () => { + let $httpBackend; + let $scope; + let controller; + let $element; + let $timeout; + + beforeEach(ngModule('item')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_, _$timeout_) => { + $httpBackend = _$httpBackend_; + $timeout = _$timeout_; + $element = angular.element(`
    `); + $scope = $rootScope.$new(); + $scope.popover = {relocate: () => {}, show: () => {}}; + controller = $componentController('vnItemDescriptorPopover', {$scope, $element}); + })); + + describe('itemFk()', () => { + it(`should not apply any changes if the received id is the same stored in _itemFk`, () => { + controller.item = 'I exist!'; + controller._itemFk = 1; + spyOn(controller, 'getCard'); + controller.itemFk = 1; + + expect(controller.item).toEqual('I exist!'); + expect(controller._itemFk).toEqual(1); + expect(controller.getCard).not.toHaveBeenCalled(); + }); + + it(`should set the received id into _itemFk, set the item to null and then call getCard()`, () => { + controller.item = `Please don't`; + controller._itemFk = 1; + spyOn(controller, 'getCard'); + controller.itemFk = 999; + + expect(controller.item).toBeNull(); + expect(controller._itemFk).toEqual(999); + expect(controller.getCard).toHaveBeenCalledWith(); + }); + }); + + describe('item()', () => { + it(`should save the item into _item and then call relocate()`, () => { + spyOn(controller.$.popover, 'relocate'); + controller.item = `i'm the item!`; + $timeout.flush(); + + expect(controller._item).toEqual(`i'm the item!`); + expect(controller.$.popover.relocate).toHaveBeenCalledWith(); + }); + }); + + describe('show()', () => { + it(`should call the show()`, () => { + spyOn(controller.$.popover, 'show'); + controller.show(); + + expect(controller.$.popover.show).toHaveBeenCalledWith(); + }); + }); + + describe('getCard()', () => { + it(`should perform a get query to store the item data into the controller`, () => { + controller.itemFk = 1; + controller.canceler = null; + let response = {}; + $httpBackend.when('GET', `Items/${controller._itemFk}/getCard`).respond(response); + $httpBackend.expect('GET', `Items/${controller._itemFk}/getCard`); + controller.getCard(); + $httpBackend.flush(); + + expect(controller.item).toEqual(response); + }); + }); + }); +}); diff --git a/modules/item/front/descriptor-popover/style.scss b/modules/item/front/descriptor-popover/style.scss new file mode 100644 index 000000000..6c03a004e --- /dev/null +++ b/modules/item/front/descriptor-popover/style.scss @@ -0,0 +1,5 @@ +body > .vn-popover vn-item-descriptor { + display: block; + width: 16em; + min-height: 28em; +} \ No newline at end of file diff --git a/modules/item/front/descriptor/index.html b/modules/item/front/descriptor/index.html new file mode 100644 index 000000000..2ee454c0d --- /dev/null +++ b/modules/item/front/descriptor/index.html @@ -0,0 +1,104 @@ +
    +
    + + + + + + + + +
    +
    +
    + + + + + +
    + + +

    Visible

    +

    {{$ctrl.visible | dashIfEmpty}}

    +
    + +

    Available

    +

    {{$ctrl.available | dashIfEmpty}}

    +
    +
    +
    +
    +
    +
    {{$ctrl.item.id}}
    + + + + + + +
    +
    + + +
    + + +
    +
    + + +
    +
    + Regularize stock +
    + + + + +
    +
    + + + + +
    \ No newline at end of file diff --git a/modules/item/front/descriptor/index.js b/modules/item/front/descriptor/index.js new file mode 100644 index 000000000..c4e66dfe3 --- /dev/null +++ b/modules/item/front/descriptor/index.js @@ -0,0 +1,106 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($state, $scope, $http, vnApp, $translate, vnConfig) { + this.$state = $state; + this.$scope = $scope; + this.$http = $http; + this.vnApp = vnApp; + this.$translate = $translate; + this.vnConfig = vnConfig; + this.moreOptions = [ + {callback: this.showRegularizeDialog, name: 'Regularize stock'} + ]; + } + + set quantity(value) { + this._quantity = parseInt(value); + } + + get quantity() { + return this._quantity; + } + + set warehouseFk(value) { + if (value) + this._warehouseFk = value; + } + get warehouseFk() { + if (!this._warehouseFk) + this._warehouseFk = this.vnConfig.warehouseFk; + + return this._warehouseFk; + } + + set item(value) { + this._item = value; + if (value && value.itemType && value.itemType.warehouseFk) + this.updateStock(value.itemType.warehouseFk); + } + + get item() { + return this._item; + } + + updateStock(warehouseFk) { + this.available = null; + this.visible = null; + if (this._item && this._item.id) { + let options = { + params: { + warehouseFk: warehouseFk + } + }; + this.$http.get(`Items/${this._item.id}/getVisibleAvailable`, options).then(response => { + this.available = response.data.available; + this.visible = response.data.visible; + }); + } + } + + onMoreChange(callback) { + callback.call(this); + } + + showRegularizeDialog() { + this.$scope.regularize.show(); + } + + set quicklinks(value = {}) { + this._quicklinks = Object.assign(value, this._quicklinks); + } + + get quicklinks() { + return this._quicklinks; + } + + saveRegularize(response) { + if (response == 'accept') { + this.$http.post(`Items/regularize`, { + itemFk: this.item.id, + quantity: this.quantity, + warehouseFk: this.warehouseFk + }).then(res => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.updateStock(this.item.itemType.warehouseFk); + }); + } + } + + clearRegularizeDialog() { + this.warehouseFk = null; + this.quantity = null; + } +} + +Controller.$inject = ['$state', '$scope', '$http', 'vnApp', '$translate', 'vnConfig']; + +ngModule.component('vnItemDescriptor', { + template: require('./index.html'), + controller: Controller, + bindings: { + item: '<', + quicklinks: '<' + } +}); diff --git a/modules/item/front/descriptor/locale/es.yml b/modules/item/front/descriptor/locale/es.yml new file mode 100644 index 000000000..548b9b6e0 --- /dev/null +++ b/modules/item/front/descriptor/locale/es.yml @@ -0,0 +1,3 @@ +Regularize stock: Regularizar stock +Type the visible quantity: Introduce la cantidad visible +Item inactive: Artículo inactivo \ No newline at end of file diff --git a/modules/item/front/descriptor/style.scss b/modules/item/front/descriptor/style.scss new file mode 100644 index 000000000..c4847bead --- /dev/null +++ b/modules/item/front/descriptor/style.scss @@ -0,0 +1,15 @@ + +vn-item-descriptor { + display: block; + + img[ng-src] { + height: 100%; + width: 100%; + display: block; + } + vn-dialog[vn-id=regularize]{ + .vn-textfield{ + width: 100% + } + } +} diff --git a/modules/item/front/diary/index.html b/modules/item/front/diary/index.html new file mode 100644 index 000000000..f3c9ff63a --- /dev/null +++ b/modules/item/front/diary/index.html @@ -0,0 +1,86 @@ + + + + + + + + + + + + + Date + Id + State + Reference + Client + In + Out + Balance + + + + + + + {{::sale.date | date:'dd/MM/yyyy' }} + + + + + {{::sale.origin | dashIfEmpty}} + + + {{::sale.stateName | dashIfEmpty}} + {{::sale.reference | dashIfEmpty}} + + + {{::sale.name | dashIfEmpty}} + + + {{::sale.in | dashIfEmpty}} + {{::sale.out | dashIfEmpty}} + + + {{::sale.balance | dashIfEmpty}} + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/item/front/diary/index.js b/modules/item/front/diary/index.js new file mode 100644 index 000000000..6d9f80641 --- /dev/null +++ b/modules/item/front/diary/index.js @@ -0,0 +1,183 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $http, $state, $window, $translate, $stateParams) { + this.$scope = $scope; + this.$http = $http; + this.$state = $state; + this.$stateParams = $stateParams; + this.$window = $window; + this.$translate = $translate; + } + + get item() { + return this._item; + } + + set item(value) { + this._item = value; + + this.filter = { + where: {itemFk: this.$stateParams.id} + }; + + this.$scope.$applyAsync(() => { + if (this.$stateParams.warehouseFk) + this.warehouseFk = this.$stateParams.warehouseFk; + else if (value) + this.warehouseFk = value.itemType.warehouseFk; + + if (this.$stateParams.ticketFk) + this.ticketFk = this.$stateParams.ticketFk; + }); + } + + set warehouseFk(value) { + if (value && value != this._warehouseFk) { + this._warehouseFk = value; + + this.$state.go(this.$state.current.name, { + warehouseFk: value + }); + + this.filter.where.warehouseFk = value; + this.$scope.model.refresh(); + } + } + + get warehouseFk() { + return this._warehouseFk; + } + + get freeLineIndex() { + let lines = this.$scope.model.data; + let minDate = new Date(); + minDate.setHours(0, 0, 0, 0); + + let maxDate = new Date(); + maxDate.setHours(23, 59, 59, 59); + + + for (let i = 0; i < lines.length; i++) { + const dated = new Date(lines[i].date); + + let isForFuture = dated > maxDate; + let isForToday = (dated >= minDate && dated <= maxDate); + + if (isForFuture || isForToday) + return i; + } + } + + get onPreparationLineIndex() { + let lines = this.$scope.model.data; + for (let i = this.freeLineIndex; i >= 0; i--) { + let line = lines[i]; + + let currentDate = new Date(); + currentDate.setHours(0, 0, 0, 0); + + let isPastDate = new Date(lines[i].date) < currentDate; + let isPicked = line.alertLevel == 1 && line.isPicked; + + if ((isPicked) || line.alertLevel > 1 || isPastDate) + return i + 1; + } + } + + get givenTicketIndex() { + let lines = this.$scope.model.data; + + for (let i = lines.length - 1; i > 0; i--) { + let line = lines[i]; + + if (line.origin == this.ticketFk) + return i; + } + } + + scrollToLine() { + let body = this.$window.document.body; + let selectedTicketLineIndex = this.givenTicketIndex; + let lineIndex = this.onPreparationLineIndex; + + + let lines = body.querySelector('vn-tbody').children; + + if (lineIndex == undefined || !lines.length) return; + + + let onPreparationLine = lines[lineIndex]; + + + let balance = onPreparationLine.querySelector('.balanceSpan'); + balance.classList.add('message'); + balance.title = this.$translate.instant('Visible quantity'); + + let headerOffset = body.querySelector('vn-topbar').getBoundingClientRect(); + let headerHeight = headerOffset.height; + + let offsetTop; + if (this.ticketFk) { + let selectedTicketLine = lines[selectedTicketLineIndex]; + let id = selectedTicketLine.querySelector('[name=origin]'); + id.classList.add('message'); + offsetTop = selectedTicketLine.offsetTop - headerHeight; + } else + offsetTop = onPreparationLine.offsetTop - headerHeight; + + this.$window.scrollTo(0, offsetTop); + this.ticketFk = null; + } + + /** + * Compares a date with the current one + * @param {Object} date - Date to compare + * @return {Boolean} - Returns true if the two dates equals + */ + isToday(date) { + let today = new Date(); + today.setHours(0, 0, 0, 0); + + let comparedDate = new Date(date); + comparedDate.setHours(0, 0, 0, 0); + + if (!(today - comparedDate)) + return true; + } + + showDescriptor(event, sale) { + if (!sale.isTicket) return; + + this.$scope.descriptor.ticketFk = sale.origin; + this.$scope.descriptor.parent = event.target; + this.$scope.descriptor.show(); + + event.preventDefault(); + } + + showClientDescriptor(event, sale) { + if (!sale.isTicket) return; + + this.$scope.clientDescriptor.clientFk = sale.clientFk; + this.$scope.clientDescriptor.parent = event.target; + this.$scope.clientDescriptor.show(); + + event.preventDefault(); + } + + onDescriptorLoad() { + this.$scope.popover.relocate(); + } +} + +Controller.$inject = ['$scope', '$http', '$state', '$window', '$translate', '$stateParams']; + +ngModule.component('vnItemDiary', { + template: require('./index.html'), + controller: Controller, + bindings: { + item: '<' + } +}); diff --git a/modules/item/front/diary/index.spec.js b/modules/item/front/diary/index.spec.js new file mode 100644 index 000000000..9286f2863 --- /dev/null +++ b/modules/item/front/diary/index.spec.js @@ -0,0 +1,111 @@ +import './index.js'; +import crudModel from 'core/mocks/crud-model'; + +describe('Item', () => { + describe('Component vnItemDiary', () => { + let $stateParams; + let $scope; + let controller; + + beforeEach(ngModule('item')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$stateParams_) => { + $stateParams = _$stateParams_; + $stateParams.id = 1; + $scope = $rootScope.$new(); + controller = $componentController('vnItemDiary', {$scope, $stateParams}); + controller.$scope.model = crudModel; + })); + + describe('isToday()', () => { + it(`should call isToday() an return true if an specified date is the current date`, () => { + let date = new Date(); + + let result = controller.isToday(date); + + expect(result).toBeTruthy(); + }); + + it(`should call isToday() an return false if an specified date is the current date`, () => { + let date = '2018-07-03'; + + let result = controller.isToday(date); + + expect(result).toBeFalsy(); + }); + }); + + describe('freeLineIndex()', () => { + it(`should call freeLineIndex() and return an index from line with alertLevel 0 and current date`, () => { + let currentDate = new Date(); + currentDate.setDate(currentDate.getDate() + 1); + + controller.$scope.model = {data: [ + {name: 'My item 1', alertLevel: 3, date: '2018-05-02'}, + {name: 'My item 2', alertLevel: 1, date: '2018-05-03'}, + {name: 'My item 3', alertLevel: 0, date: currentDate}] + }; + let result = controller.freeLineIndex; + + expect(result).toEqual(2); + }); + }); + + describe('onPreparationLineIndex()', () => { + it(`should call onPreparationLineIndex() and return an index from line with alertLevel 1 and isPicked true`, () => { + let currentDate = new Date(); + currentDate.setDate(currentDate.getDate() + 1); + controller.$scope.model = {data: [ + {name: 'My item 1', alertLevel: 3, isPicked: true, date: currentDate}, + {name: 'My item 3', alertLevel: 1, isPicked: true, date: currentDate}, + {name: 'My item 4', alertLevel: 1, isPicked: false, date: currentDate}, + {name: 'My item 5', alertLevel: 0, isPicked: false, date: currentDate}] + }; + let result = controller.onPreparationLineIndex; + + expect(result).toEqual(1); + }); + }); + + describe('set item()', () => { + it(`should set warehouseFk property based on itemType warehouseFk`, () => { + spyOn(controller.$scope, '$applyAsync').and.callThrough(); + controller.item = {id: 1, itemType: {warehouseFk: 1}}; + + expect(controller.$scope.$applyAsync).toHaveBeenCalledWith(jasmine.any(Function)); + $scope.$apply(); + + expect(controller.warehouseFk).toEqual(1); + expect(controller.item.id).toEqual(1); + }); + + it(`should set warehouseFk property based on url query warehouseFk`, () => { + spyOn(controller.$scope, '$applyAsync').and.callThrough(); + controller.$stateParams.warehouseFk = 4; + controller.item = {id: 1, itemType: {warehouseFk: 1}}; + + expect(controller.$scope.$applyAsync).toHaveBeenCalledWith(jasmine.any(Function)); + $scope.$apply(); + + expect(controller.warehouseFk).toEqual(4); + expect(controller.item.id).toEqual(1); + }); + }); + + describe('givenTicketIndex() setter', () => { + it(`should return the index position of the line of a given ticket fk`, () => { + controller.$scope.model = {data: [ + {name: 'My item 1', origin: 1, alertLevel: 3, isPicked: true, date: '2018-05-02'}, + {name: 'My item 3', origin: 2, alertLevel: 1, isPicked: true, date: '2018-05-03'}, + {name: 'My item 4', origin: 3, alertLevel: 1, isPicked: false, date: '2018-05-03'}] + }; + controller.ticketFk = 2; + + let index = controller.givenTicketIndex; + + expect(controller.$scope.model.data[index].origin).toEqual(2); + }); + }); + }); +}); + diff --git a/modules/item/front/diary/locale/es.yml b/modules/item/front/diary/locale/es.yml new file mode 100644 index 000000000..e00816d78 --- /dev/null +++ b/modules/item/front/diary/locale/es.yml @@ -0,0 +1,4 @@ +In: Entrada +Out: Salida +Visible quantity: Cantidad visible +Ticket/Entry: Ticket/Entrada \ No newline at end of file diff --git a/modules/item/front/diary/style.scss b/modules/item/front/diary/style.scss new file mode 100644 index 000000000..e8d261ec2 --- /dev/null +++ b/modules/item/front/diary/style.scss @@ -0,0 +1,30 @@ +@import "variables"; + +vn-item-diary { + & > vn-vertical { + display: block; + } + vn-horizontal { + justify-content: center; + } + vn-autocomplete > div { + width: 400px; + } + .balanceNegative .balance { + color: $color-alert; + } + .isIn .in { + color: $color-success; + font-weight: bold; + } + .isToday .date { + color: white; + background-color: $color-main; + } + .truncate { + max-width: 250px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } +} \ No newline at end of file diff --git a/modules/item/front/fetched-tags/index.html b/modules/item/front/fetched-tags/index.html new file mode 100644 index 000000000..6982ab6ac --- /dev/null +++ b/modules/item/front/fetched-tags/index.html @@ -0,0 +1,44 @@ + + {{$ctrl.name}} + +

    {{$ctrl.subName}}

    +
    + +
    + {{::$ctrl.item.value5}} +
    +
    + {{::$ctrl.item.value6}} +
    +
    + {{::$ctrl.item.value7}} +
    +
    + {{::$ctrl.item.value8}} +
    +
    + {{::$ctrl.item.value9}} +
    +
    + {{::$ctrl.item.value10}} +
    +
    +
    \ No newline at end of file diff --git a/modules/item/front/fetched-tags/index.js b/modules/item/front/fetched-tags/index.js new file mode 100644 index 000000000..b88e853b4 --- /dev/null +++ b/modules/item/front/fetched-tags/index.js @@ -0,0 +1,12 @@ +import ngModule from '../module'; +import './style.scss'; + +ngModule.component('vnFetchedTags', { + template: require('./index.html'), + bindings: { + maxLength: '<', + item: '<', + name: ' vn-horizontal { + align-items: center; + + & > vn-one { + overflow: hidden; + text-overflow: ellipsis; + min-width: 5em; + } + + & > vn-one:nth-child(2) h3 { + color: $color-font-secondary; + text-transform: uppercase; + line-height: initial; + text-align: center; + font-size: 1em + } + + & > vn-auto { + display: flex; + padding-left: .4em; + min-width: 12em; + + & > .inline-tag { + display: inline-block; + color: $color-font-secondary; + margin-left: .4em; + text-align: center; + font-size: .8em; + height: 1.25em; + padding: .1em; + border-radius: .1em; + width: 4em; + min-width: 4em; + border: 1px solid $color-spacer; + + &.empty { + border: 1px solid $color-spacer-light; + } + } + } + @media screen and (max-width: 1600px) { + flex-direction: column; + + & > vn-one { + padding-bottom: .2em + } + & > vn-auto { + white-space: initial; + padding-left: 0; + flex-wrap: wrap; + justify-content: center; + + & > .inline-tag { + margin: .1em; + } + } + } + } +} \ No newline at end of file diff --git a/modules/item/front/index.js b/modules/item/front/index.js new file mode 100644 index 000000000..0f11c0563 --- /dev/null +++ b/modules/item/front/index.js @@ -0,0 +1,24 @@ +export * from './module'; + +import './main'; +import './index/'; +import './search-panel'; +import './diary'; +import './create'; +import './card'; +import './descriptor'; +import './descriptor-popover'; +import './basic-data'; +import './fetched-tags'; +import './tags'; +import './tax'; +import './log'; +import './request'; +import './request-search-panel'; +import './last-entries'; +import './niche'; +import './botanical'; +import './barcode'; +import './summary'; +import './waste'; + diff --git a/modules/item/front/index/index.html b/modules/item/front/index/index.html new file mode 100644 index 000000000..c83ce5ed1 --- /dev/null +++ b/modules/item/front/index/index.html @@ -0,0 +1,130 @@ + + + + + + + + + + + Id + Grouping + Packing + Description + Stems + Size + Niche + Type + Category + Intrastat + Origin + Buyer + Density + Active + + + + + + + + + + + {{::item.id | zeroFill:6}} + + + {{::item.grouping | dashIfEmpty}} + {{::item.packing | dashIfEmpty}} + + + + + {{::item.stems}} + {{::item.size}} + {{::item.niche}} + + {{::item.type}} + + + {{::item.category}} + + + {{::item.intrastat}} + + {{::item.origin}} + + + {{::item.userNickname}} + + + {{::item.density}} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/item/front/index/index.js b/modules/item/front/index/index.js new file mode 100644 index 000000000..087021577 --- /dev/null +++ b/modules/item/front/index/index.js @@ -0,0 +1,83 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($http, $state, $scope, aclService) { + this.aclService = aclService; + this.$http = $http; + this.$state = $state; + this.$ = $scope; + this.itemSelected = null; + this.imagesPath = '//verdnatura.es/vn-image-data/catalog'; + + this.showFields = { + id: false, + actions: false + }; + } + + stopEvent(event) { + event.preventDefault(); + event.stopImmediatePropagation(); + } + + onSearch(params) { + if (params) + this.$.model.applyFilter(null, params); + else + this.$.model.clear(); + } + + showItemDescriptor(event, itemFk) { + if (event.defaultPrevented) return; + + event.preventDefault(); + event.stopPropagation(); + + this.$.itemDescriptor.itemFk = itemFk; + this.$.itemDescriptor.parent = event.target; + this.$.itemDescriptor.show(); + } + + + showWorkerDescriptor(event, workerFk) { + if (event.defaultPrevented) return; + + event.preventDefault(); + event.stopPropagation(); + + this.selectedWorker = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } + + cloneItem(event, item) { + this.stopEvent(event); + this.itemSelected = item; + this.$.clone.show(); + } + + onCloneAccept(response) { + if (!(response == 'accept' && this.itemSelected)) + return; + + this.$http.post(`Items/${this.itemSelected.id}/clone`).then(res => { + if (res && res.data && res.data.id) + this.$state.go('item.card.tags', {id: res.data.id}); + }); + + this.itemSelected = null; + } + + preview(event, item) { + this.stopEvent(event); + this.itemSelected = item; + this.$.preview.show(); + } +} +Controller.$inject = ['$http', '$state', '$scope', 'aclService']; + +ngModule.component('vnItemIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/item/front/index/index.spec.js b/modules/item/front/index/index.spec.js new file mode 100644 index 000000000..0de80323e --- /dev/null +++ b/modules/item/front/index/index.spec.js @@ -0,0 +1,58 @@ +import './index.js'; + +describe('Item', () => { + describe('Component vnItemIndex', () => { + let $state; + let controller; + let $httpBackend; + + beforeEach(ngModule('item')); + + beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_) => { + $state = _$state_; + $httpBackend = _$httpBackend_; + controller = $componentController('vnItemIndex', {$state}); + })); + + describe('onCloneAccept()', () => { + it('should do nothing if response is not accept', () => { + spyOn(controller.$state, 'go'); + + let response = 'ERROR!'; + controller.itemSelected = 'check me'; + + controller.onCloneAccept(response); + + expect(controller.$state.go).not.toHaveBeenCalledWith(); + expect(controller.itemSelected).toEqual('check me'); + }); + + it('should do nothing if response is accept but itemSelected is not defined in the controller', () => { + spyOn(controller.$state, 'go'); + + let response = 'accept'; + controller.itemSelected = undefined; + + controller.onCloneAccept(response); + + expect(controller.$state.go).not.toHaveBeenCalledWith(); + expect(controller.itemSelected).toBeUndefined(); + }); + + it('should perform a post query and then call go() then update itemSelected in the controller', () => { + spyOn(controller.$state, 'go'); + + let response = 'accept'; + controller.itemSelected = {id: 1}; + + $httpBackend.when('POST', `Items/1/clone`).respond({id: 99}); + $httpBackend.expect('POST', `Items/1/clone`); + controller.onCloneAccept(response); + $httpBackend.flush(); + + expect(controller.$state.go).toHaveBeenCalledWith('item.card.tags', {id: 99}); + expect(controller.itemSelected).toBeNull(); + }); + }); + }); +}); diff --git a/modules/item/front/index/locale/es.yml b/modules/item/front/index/locale/es.yml new file mode 100644 index 000000000..0d72edd28 --- /dev/null +++ b/modules/item/front/index/locale/es.yml @@ -0,0 +1,2 @@ +picture: Foto +Buy requests: Peticiones de compra \ No newline at end of file diff --git a/client/item/src/list/preview.svg b/modules/item/front/index/preview.svg similarity index 100% rename from client/item/src/list/preview.svg rename to modules/item/front/index/preview.svg diff --git a/modules/item/front/index/style.scss b/modules/item/front/index/style.scss new file mode 100644 index 000000000..1cbc88124 --- /dev/null +++ b/modules/item/front/index/style.scss @@ -0,0 +1,35 @@ +@import "variables"; + +vn-item-product { + display: block; + + .id { + background-color: $color-main; + color: $color-font-dark; + margin-bottom: 0em; + } + .image { + height: 7em; + width: 7em; + + & > img { + max-height: 100%; + max-width: 100%; + border-radius: .2em; + } + } + vn-label-value:first-of-type section{ + margin-top: 0.6em; + } + vn-fetched-tags vn-horizontal{ + margin-top: 0.9em; + } +} + +vn-table { + img { + border-radius: 50%; + width: 50px; + height: 50px; + } +} \ No newline at end of file diff --git a/modules/item/front/last-entries/index.html b/modules/item/front/last-entries/index.html new file mode 100644 index 000000000..28ba9989b --- /dev/null +++ b/modules/item/front/last-entries/index.html @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + Ig + Warehouse + Landed + Entry + P.P.U + P.P.P + Label + Packing + Grouping + Stems + Quantity + Cost + Cube + Provider + + + + + + + + + {{::entry.warehouse| dashIfEmpty}} + {{::entry.landed | date:'dd/MM/yyyy HH:mm'}} + {{::entry.entryFk | dashIfEmpty}} + {{::entry.price2 | dashIfEmpty}} + {{::entry.price3 | dashIfEmpty}} + {{entry.stickers | dashIfEmpty}} + + + {{::entry.packing | dashIfEmpty}} + + + + + {{::entry.grouping | dashIfEmpty}} + + + {{::entry.stems | dashIfEmpty}} + {{::entry.quantity}} + {{::entry.buyingValue | dashIfEmpty}} + {{::entry.packageFk | dashIfEmpty}} + {{::entry.supplier | dashIfEmpty}} + + + + + + + diff --git a/modules/item/front/last-entries/index.js b/modules/item/front/last-entries/index.js new file mode 100644 index 000000000..3ef89f086 --- /dev/null +++ b/modules/item/front/last-entries/index.js @@ -0,0 +1,44 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $stateParams) { + this.$scope = $scope; + this.$stateParams = $stateParams; + + let defaultDate = new Date(); + defaultDate.setDate(defaultDate.getDate() - 75); + defaultDate.setHours(0, 0, 0, 0); + + this.filter = { + where: { + itemFk: $stateParams.id, + date: defaultDate + } + }; + this._date = defaultDate; + } + + set date(value) { + this._date = value; + + if (!value) return; + + this.filter.where.date = value; + this.$scope.model.refresh(); + } + + get date() { + return this._date; + } +} + +Controller.$inject = ['$scope', '$stateParams']; + +ngModule.component('vnItemLastEntries', { + template: require('./index.html'), + controller: Controller, + bindings: { + item: '<' + } +}); diff --git a/modules/item/front/last-entries/locale/es.yml b/modules/item/front/last-entries/locale/es.yml new file mode 100644 index 000000000..0eac6eaa6 --- /dev/null +++ b/modules/item/front/last-entries/locale/es.yml @@ -0,0 +1,12 @@ +Since: Desde +Landed: F. entrega +Stems: Tallos +Quantity: Cantidad +Cost: Coste +Label: Etiquetas +Entry: Entrada +Ignored: Ignorado +Provider: Proveedor +Cube: Cubo +Price Per Unit: Precio Por Unidad +Price Per Package: Precio Por Paquete \ No newline at end of file diff --git a/modules/item/front/last-entries/style.scss b/modules/item/front/last-entries/style.scss new file mode 100644 index 000000000..6188daabc --- /dev/null +++ b/modules/item/front/last-entries/style.scss @@ -0,0 +1,24 @@ +@import "variables"; + +vn-item-last-entries { + .round { + background-color: $color-spacer; + border-radius: 25px; + float: right; + width: 25px; + color: $color-font-dark; + text-align: center; + font-weight: bold; + } + vn-horizontal { + justify-content: center; + } + vn-date-picker { + flex: none !important; + } + @media screen and (max-width: 1440px) { + .expendable { + display: none; + } + } +} diff --git a/modules/item/front/locale/es.yml b/modules/item/front/locale/es.yml new file mode 100644 index 000000000..9580fd156 --- /dev/null +++ b/modules/item/front/locale/es.yml @@ -0,0 +1,64 @@ +Item: Artículo +View item: Ver artículo +Category: Reino +Description: Descripción +Size: Medida +Item family: Familia +Name: Nombre +Full name: Nombre completo +Relevancy: Relevancia +Picture: Foto +Changed by: Cambiado por +Action: Acción +Date: Fecha +Preview: Vista previa +Clone: Clonar +Do you want to clone this item?: ¿Desea clonar este artículo? +All it's properties will be copied: Todas sus propiedades serán copiadas +Yes, clone: Si, clonar +Value: Valor +Priority: Prioridad +Country: País +Select warehouse: Selecione almacén +Class: Clase +Intrastat code: Código intrastat +Warehouse: Almacén +Code: Código +State: Estado +Species: Especie +Add tag: Añadir etiqueta +Remove tag: Quitar etiqueta +Add niche: Añadir nicho +Remove niche: Quitar nicho +Add barcode: Añadir código de barras +Remove barcode: Quitar código de barras +Buyer: Comprador +Tag: Etiqueta +Worker: Trabajador +Available: Disponible +Create: Crear +Client card: Ficha del cliente +Shipped: F. envío +stems: Tallos +Compression: Compresión +Density: Densidad +Search items by id, name or barcode: Buscar articulos por identificador, nombre o codigo de barras +SalesPerson: Comercial +Concept: Concepto + +# Sections +Items: Artículos +List: Listado +New item: Nuevo artículo +Summary: Vista previa +Basic data: Datos básicos +Tax: IVA +History: Historial +Niches: Nichos +Botanical: Botánico +Barcodes: Códigos de barras +Diary: Histórico +Item diary: Registro de compra-venta +Last entries: Últimas entradas +Tags: Etiquetas +Waste breakdown: Desglose de mermas \ No newline at end of file diff --git a/modules/item/front/log/index.html b/modules/item/front/log/index.html new file mode 100644 index 000000000..3a6bb92ad --- /dev/null +++ b/modules/item/front/log/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/modules/item/front/log/index.js b/modules/item/front/log/index.js new file mode 100644 index 000000000..9253147c7 --- /dev/null +++ b/modules/item/front/log/index.js @@ -0,0 +1,15 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $stateParams) { + this.$scope = $scope; + this.$stateParams = $stateParams; + } +} + +Controller.$inject = ['$scope', '$stateParams']; + +ngModule.component('vnItemLog', { + template: require('./index.html'), + controller: Controller, +}); diff --git a/modules/item/front/main/index.html b/modules/item/front/main/index.html new file mode 100644 index 000000000..758bfd55e --- /dev/null +++ b/modules/item/front/main/index.html @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/modules/item/front/main/index.js b/modules/item/front/main/index.js new file mode 100644 index 000000000..f34369982 --- /dev/null +++ b/modules/item/front/main/index.js @@ -0,0 +1,9 @@ +import ngModule from '../module'; +import ModuleMain from 'salix/components/module-main'; + +export default class Items extends ModuleMain {} + +ngModule.vnComponent('vnItems', { + controller: Items, + template: require('./index.html') +}); diff --git a/modules/item/front/module.js b/modules/item/front/module.js new file mode 100644 index 000000000..0265f92a2 --- /dev/null +++ b/modules/item/front/module.js @@ -0,0 +1,3 @@ +import {ng} from 'core/vendor'; + +export default ng.module('item', ['vnCore']); diff --git a/modules/item/front/niche/index.html b/modules/item/front/niche/index.html new file mode 100644 index 000000000..70dabe671 --- /dev/null +++ b/modules/item/front/niche/index.html @@ -0,0 +1,55 @@ + + + + +
    + + + + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/modules/item/front/niche/index.js b/modules/item/front/niche/index.js new file mode 100644 index 000000000..5d2442c58 --- /dev/null +++ b/modules/item/front/niche/index.js @@ -0,0 +1,23 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($stateParams, $scope) { + this.$stateParams = $stateParams; + this.$scope = $scope; + } + + onSubmit() { + this.$scope.watcher.check(); + this.$scope.model.save().then(() => { + this.$scope.watcher.notifySaved(); + this.$scope.model.refresh(); + }); + } +} + +Controller.$inject = ['$stateParams', '$scope']; + +ngModule.component('vnItemNiche', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/item/front/request-search-panel/index.html b/modules/item/front/request-search-panel/index.html new file mode 100644 index 000000000..4f95abf77 --- /dev/null +++ b/modules/item/front/request-search-panel/index.html @@ -0,0 +1,67 @@ +
    +
    + + + + + + + + + {{nickname}} + + + + + + + + + + + + + + + + + + + + + + + +
    +
    diff --git a/modules/item/front/request-search-panel/index.js b/modules/item/front/request-search-panel/index.js new file mode 100644 index 000000000..07fcefd6b --- /dev/null +++ b/modules/item/front/request-search-panel/index.js @@ -0,0 +1,7 @@ +import ngModule from '../module'; +import SearchPanel from 'core/components/searchbar/search-panel'; + +ngModule.component('vnRequestSearchPanel', { + template: require('./index.html'), + controller: SearchPanel +}); diff --git a/client/item/src/filter-panel/locale/es.yml b/modules/item/front/request-search-panel/locale/es.yml similarity index 100% rename from client/item/src/filter-panel/locale/es.yml rename to modules/item/front/request-search-panel/locale/es.yml diff --git a/modules/item/front/request/index.html b/modules/item/front/request/index.html new file mode 100644 index 000000000..6d6e786dc --- /dev/null +++ b/modules/item/front/request/index.html @@ -0,0 +1,136 @@ + + + + + + + + + + + + Ticket ID + Shipped + Warehouse + SalesPerson + Description + Requested + Price + Atender + Item + Achieved + Concept + State + + + + + + + {{request.ticketFk}} + + + + + {{::request.shipped | date: 'dd/MM/yyyy'}} + + + {{::request.warehouse}} + + + {{::request.salesPersonNickname}} + + + {{::request.description}} + {{::request.quantity}} + {{::request.price | currency: 'EUR':2}} + + + {{::request.atenderNickname}} + + + + {{request.itemFk}} + + + + + + + {{request.saleQuantity}} + + + + + + + + {{request.itemDescription}} + + + {{$ctrl.getState(request.isOk)}} + + + + + + + + + + + + + + + + + + + +
    Specify the reasons to deny this request
    + + + + +
    + + + + +
    \ No newline at end of file diff --git a/modules/item/front/request/index.js b/modules/item/front/request/index.js new file mode 100644 index 000000000..b56df41a8 --- /dev/null +++ b/modules/item/front/request/index.js @@ -0,0 +1,157 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +export default class Controller extends Component { + constructor($element, $) { + super($element, $); + + if (!this.$state.q) { + const today = new Date(); + today.setHours(23, 59, 59, 59); + + const lastWeek = new Date(); + lastWeek.setHours(0, 0, 0, 0); + lastWeek.setDate(lastWeek.getDate() - 7); + + this.filter = { + where: { + isOk: false, + mine: true, + from: lastWeek, + to: today + } + }; + } + } + + $postLink() { + if (this.filter) + this.onSearch(this.filter); + } + + getState(isOk) { + if (isOk === null) + return 'Nueva'; + else if (isOk === -1 || isOk) + return 'Aceptada'; + else + return 'Denegada'; + } + + confirmRequest(request) { + if (request.itemFk && request.saleQuantity) { + let params = { + itemFk: request.itemFk, + quantity: request.saleQuantity + }; + + let query = `TicketRequests/${request.id}/confirm`; + this.$http.post(query, params).then(res => { + request.itemDescription = res.data.concept; + request.isOk = true; + + this.vnApp.showSuccess(this.$t('Data saved!')); + }); + } + } + + changeQuantity(request) { + if (request.saleFk) { + let params = { + quantity: request.saleQuantity + }; + + let endpoint = `Sales/${request.saleFk}/`; + + this.$http.patch(endpoint, params).then(() => { + this.vnApp.showSuccess(this.$t('Data saved!')); + }).then(() => this.confirmRequest(request)); + } else + this.confirmRequest(request); + } + + compareDate(date) { + let today = new Date(); + today.setHours(0, 0, 0, 0); + let timeTicket = new Date(date); + timeTicket.setHours(0, 0, 0, 0); + + let comparation = today - timeTicket; + + if (comparation == 0) + return 'warning'; + if (comparation < 0) + return 'success'; + } + + onSearch(params) { + if (params) + this.$.model.applyFilter(null, params); + else + this.$.model.clear(); + } + + showDenyReason(event, requestId) { + this.selectedRequest = requestId; + this.$.denyReason.parent = event.target; + this.$.denyReason.show(); + document.querySelector('vn-item-request vn-textarea textArea').focus(); + } + + clear() { + delete this.denyRequestId; + } + + denyRequest(response) { + if (response !== 'accept') return; + + let params = { + observation: this.denyObservation + }; + + let query = `TicketRequests/${this.selectedRequest.id}/deny`; + this.$http.post(query, params).then(res => { + const request = res.data; + this.selectedRequest.isOk = request.isOk; + this.selectedRequest.attenderFk = request.attenderFk; + this.selectedRequest.response = request.response; + + this.vnApp.showSuccess(this.$t('Data saved!')); + this.denyObservation = null; + }); + } + + showTicketDescriptor(event, ticketFk) { + this.$.ticketDescriptor.ticketFk = ticketFk; + this.$.ticketDescriptor.parent = event.target; + this.$.ticketDescriptor.show(); + event.preventDefault(); + event.stopImmediatePropagation(); + } + + showItemDescriptor(event, itemFk) { + this.$.itemDescriptor.itemFk = itemFk; + this.$.itemDescriptor.parent = event.target; + this.$.itemDescriptor.show(); + } + + showWorkerDescriptor(event, workerFk) { + this.$.workerDescriptor.workerFk = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } + + onDescriptorLoad() { + this.$.popover.relocate(); + } + + preventNavigation(event) { + event.preventDefault(); + } +} + +ngModule.component('vnItemRequest', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/item/front/request/index.spec.js b/modules/item/front/request/index.spec.js new file mode 100644 index 000000000..4c1e31634 --- /dev/null +++ b/modules/item/front/request/index.spec.js @@ -0,0 +1,133 @@ +import './index.js'; +import crudModel from 'core/mocks/crud-model'; + +describe('Item', () => { + describe('Component vnItemRequest', () => { + let $scope; + let $element; + let controller; + let $httpBackend; + + beforeEach(ngModule('item')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + $scope.model = crudModel; + $scope.denyReason = {hide: () => {}}; + $element = angular.element(''); + controller = $componentController('vnItemRequest', {$element, $scope}); + })); + + afterAll(() => { + $scope.$destroy(); + $element.remove(); + }); + + describe('getState()', () => { + it(`should return an string depending to the isOK value`, () => { + let isOk = null; + let result = controller.getState(isOk); + + expect(result).toEqual('Nueva'); + + isOk = 1; + result = controller.getState(isOk); + + expect(result).toEqual('Aceptada'); + + isOk = 0; + result = controller.getState(isOk); + + expect(result).toEqual('Denegada'); + }); + }); + + describe('confirmRequest()', () => { + it(`should do nothing if the request does't have itemFk or saleQuantity`, () => { + let request = {}; + spyOn(controller.vnApp, 'showSuccess'); + + controller.confirmRequest(request); + + expect(controller.vnApp.showSuccess).not.toHaveBeenCalledWith(); + }); + + it('should perform a query and call vnApp.showSuccess() and refresh if the conditions are met', () => { + spyOn(controller.vnApp, 'showSuccess'); + let model = controller.$.model; + spyOn(model, 'refresh'); + + const expectedResult = {concept: 'Melee Weapon'}; + let request = {itemFk: 1, saleQuantity: 1, id: 1}; + + $httpBackend.when('POST', `TicketRequests/${request.id}/confirm`).respond(expectedResult); + $httpBackend.expect('POST', `TicketRequests/${request.id}/confirm`).respond(expectedResult); + controller.confirmRequest(request); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + }); + }); + + describe('changeQuantity()', () => { + it(`should call confirmRequest() if there's no sale id in the request`, () => { + let request = {}; + spyOn(controller, 'confirmRequest'); + + controller.changeQuantity(request); + + expect(controller.confirmRequest).toHaveBeenCalledWith(jasmine.any(Object)); + }); + + it(`should perform a query and call vnApp.showSuccess() if the conditions are met`, () => { + let request = {saleFk: 1, saleQuantity: 1}; + spyOn(controller.vnApp, 'showSuccess'); + + + $httpBackend.when('PATCH', `Sales/${request.saleFk}/`).respond(); + $httpBackend.expect('PATCH', `Sales/${request.saleFk}/`).respond(); + controller.changeQuantity(request); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + }); + }); + + describe('compareDate()', () => { + it(`should return "success" if receives a future date`, () => { + let date = '3019-02-18T11:00:00.000Z'; + + let result = controller.compareDate(date); + + expect(result).toEqual('success'); + }); + + it(`should return "warning" if date is today`, () => { + let date = new Date(); + + let result = controller.compareDate(date); + + expect(result).toEqual('warning'); + }); + }); + + describe('denyRequest()', () => { + it(`should perform a query and call vnApp.showSuccess(), refresh(), hide() and set denyObservation to null in the controller`, () => { + spyOn(controller.vnApp, 'showSuccess'); + + const request = {id: 1}; + const expectedResult = {isOk: false, attenderFk: 106, response: 'Denied!'}; + controller.selectedRequest = request; + + $httpBackend.when('POST', `TicketRequests/${request.id}/deny`).respond(expectedResult); + $httpBackend.expect('POST', `TicketRequests/${request.id}/deny`).respond(expectedResult); + controller.denyRequest('accept'); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + }); + }); + }); +}); + diff --git a/modules/item/front/request/locale/es.yml b/modules/item/front/request/locale/es.yml new file mode 100644 index 000000000..33710a327 --- /dev/null +++ b/modules/item/front/request/locale/es.yml @@ -0,0 +1,6 @@ +Discard: Descartar +Specify the reasons to deny this request: Especifica las razones para descartar la petición +Buy requests: Peticiones de compra +Search request by id or alias: Buscar peticiones por identificador o alias +Requested: Solicitado +Achieved: Conseguido \ No newline at end of file diff --git a/modules/item/front/request/style.scss b/modules/item/front/request/style.scss new file mode 100644 index 000000000..0af32c309 --- /dev/null +++ b/modules/item/front/request/style.scss @@ -0,0 +1,18 @@ +@import "variables"; + +vn-item-request { + vn-dialog[vn-id="denyReason"] { + button.close { + display: none + } + vn-button { + margin: 0 auto + } + vn-textarea { + width: 100% + } + } + vn-icon[icon=insert_drive_file]{ + color: $color-font-secondary; + } +} \ No newline at end of file diff --git a/modules/item/front/routes.json b/modules/item/front/routes.json new file mode 100644 index 000000000..a3cf0bee6 --- /dev/null +++ b/modules/item/front/routes.json @@ -0,0 +1,149 @@ +{ + "module": "item", + "name": "Items", + "icon": "icon-item", + "validations" : true, + "dependencies": ["worker", "client", "ticket"], + "menus": { + "main": [ + {"state": "item.index", "icon": "icon-item"}, + {"state": "item.request", "icon": "pan_tool"}, + {"state": "item.waste", "icon": "icon-claims"} + ], + "card": [ + {"state": "item.card.basicData", "icon": "settings"}, + {"state": "item.card.tags", "icon": "icon-tags"}, + {"state": "item.card.tax", "icon": "icon-tax"}, + {"state": "item.card.niche", "icon": "place"}, + {"state": "item.card.botanical", "icon": "local_florist"}, + {"state": "item.card.itemBarcode", "icon": "icon-barcode"}, + {"state": "item.card.diary", "icon": "icon-transaction"}, + {"state": "item.card.last-entries", "icon": "icon-regentry"}, + {"state": "item.card.log", "icon": "history"} + ] + }, + "keybindings": [ + {"key": "a", "state": "item.index"} + ], + "routes": [ + { + "url": "/item", + "state": "item", + "abstract": true, + "description": "Items", + "component": "vn-items" + }, { + "url": "/index?q", + "state": "item.index", + "component": "vn-item-index", + "description": "Items" + }, { + "url": "/create", + "state": "item.create", + "component": "vn-item-create", + "description": "New item" + }, { + "url": "/:id", + "state": "item.card", + "abstract": true, + "component": "vn-item-card" + }, { + "url" : "/basic-data", + "state": "item.card.basicData", + "component": "vn-item-basic-data", + "description": "Basic data", + "params": { + "item": "$ctrl.item" + }, + "acl": ["buyer"] + }, { + "url" : "/tags", + "state": "item.card.tags", + "component": "vn-item-tags", + "description": "Tags", + "params": { + "item-tags": "$ctrl.itemTags" + }, + "acl": ["buyer", "replenisher"] + }, { + "url" : "/tax", + "state": "item.card.tax", + "component": "vn-item-tax", + "description": "Tax", + "acl": ["administrative","buyer"] + }, { + "url" : "/niche", + "state": "item.card.niche", + "component": "vn-item-niche", + "description": "Niches", + "params": { + "item": "$ctrl.item" + }, + "acl": ["buyer","replenisher"] + }, { + "url" : "/botanical", + "state": "item.card.botanical", + "component": "vn-item-botanical", + "description": "Botanical", + "params": { + "item": "$ctrl.item" + }, + "acl": ["buyer"] + }, { + "url" : "/barcode", + "state": "item.card.itemBarcode", + "component": "vn-item-barcode", + "description": "Barcodes", + "params": { + "item": "$ctrl.item" + }, + "acl": ["buyer","replenisher"] + }, { + "url" : "/summary", + "state": "item.card.summary", + "component": "vn-item-summary", + "description": "Summary", + "params": { + "item": "$ctrl.item" + } + }, { + "url" : "/diary?warehouseFk&ticketFk", + "state": "item.card.diary", + "component": "vn-item-diary", + "description": "Diary", + "params": { + "item": "$ctrl.item" + }, + "acl": ["employee"] + }, { + "url" : "/last-entries", + "state": "item.card.last-entries", + "component": "vn-item-last-entries", + "description": "Last entries", + "params": { + "item": "$ctrl.item" + }, + "acl": ["employee"] + }, { + "url" : "/log", + "state": "item.card.log", + "component": "vn-item-log", + "description": "Log" + }, { + "url" : "/request?q", + "state": "item.request", + "component": "vn-item-request", + "description": "Buy requests", + "params": { + "item": "$ctrl.item" + }, + "acl": ["employee"] + }, { + "url" : "/waste", + "state": "item.waste", + "component": "vn-item-waste", + "description": "Waste breakdown", + "acl": ["buyer"] + } + ] +} \ No newline at end of file diff --git a/modules/item/front/search-panel/index.html b/modules/item/front/search-panel/index.html new file mode 100644 index 000000000..ea0d854f5 --- /dev/null +++ b/modules/item/front/search-panel/index.html @@ -0,0 +1,155 @@ + +
    +
    + + + + + + + + + + + + + + + + + Tags + + + + + + + + + + + + + + + + + More fields + + + + + + + + +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    + + + +
    +
    diff --git a/modules/item/front/search-panel/index.js b/modules/item/front/search-panel/index.js new file mode 100644 index 000000000..6b3e7786d --- /dev/null +++ b/modules/item/front/search-panel/index.js @@ -0,0 +1,79 @@ +import ngModule from '../module'; +import SearchPanel from 'core/components/searchbar/search-panel'; + +class Controller extends SearchPanel { + constructor($element, $) { + super($element, $); + let model = 'Item'; + let moreFields = ['id', 'description', 'name', 'isActive']; + + let properties; + let validations = window.validations; + + if (validations && validations[model]) + properties = validations[model].properties; + else + properties = {}; + + this.moreFields = []; + for (let field of moreFields) { + let prop = properties[field]; + this.moreFields.push({ + name: field, + label: prop ? prop.description : field, + type: prop ? prop.type : null + }); + } + } + + get filter() { + let filter = this.$.filter; + + for (let fieldFilter of this.fieldFilters) + filter[fieldFilter.name] = fieldFilter.value; + + return filter; + } + + set filter(value) { + if (!value) + value = {}; + if (!value.tags) + value.tags = [{}]; + + this.fieldFilters = []; + for (let field of this.moreFields) { + if (value[field.name] != undefined) { + this.fieldFilters.push({ + name: field.name, + value: value[field.name], + info: field + }); + } + } + + this.$.filter = value; + } + + getSourceTable(selection) { + if (!selection || selection.isFree === true) + return null; + + if (selection.sourceTable) { + return '' + + selection.sourceTable.charAt(0).toUpperCase() + + selection.sourceTable.substring(1) + 's'; + } else if (selection.sourceTable == null) + return `ItemTags/filterItemTags/${selection.id}`; + } + + removeField(index, field) { + this.fieldFilters.splice(index, 1); + this.$.filter[field] = undefined; + } +} + +ngModule.component('vnItemSearchPanel', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/item/front/search-panel/index.spec.js b/modules/item/front/search-panel/index.spec.js new file mode 100644 index 000000000..cc0cf0375 --- /dev/null +++ b/modules/item/front/search-panel/index.spec.js @@ -0,0 +1,45 @@ +import './index.js'; + +describe('Item', () => { + describe('Component vnItemSearchPanel', () => { + let $element; + let controller; + + beforeEach(ngModule('item')); + + beforeEach(angular.mock.inject($componentController => { + $element = angular.element(`
    `); + controller = $componentController('vnItemSearchPanel', {$element}); + })); + + describe('getSourceTable()', () => { + it(`should return null if there's no selection`, () => { + let selection = null; + let result = controller.getSourceTable(selection); + + expect(result).toBeNull(); + }); + + it(`should return null if there's a selection but its isFree property is truthy`, () => { + let selection = {isFree: true}; + let result = controller.getSourceTable(selection); + + expect(result).toBeNull(); + }); + + it(`should return the formated sourceTable concatenated to a path`, () => { + let selection = {sourceTable: 'hello guy'}; + let result = controller.getSourceTable(selection); + + expect(result).toEqual('Hello guys'); + }); + + it(`should return a path if there's no sourceTable and the selection has an id`, () => { + let selection = {id: 99}; + let result = controller.getSourceTable(selection); + + expect(result).toEqual(`ItemTags/filterItemTags/${selection.id}`); + }); + }); + }); +}); diff --git a/modules/item/front/search-panel/locale/es.yml b/modules/item/front/search-panel/locale/es.yml new file mode 100644 index 000000000..197da0695 --- /dev/null +++ b/modules/item/front/search-panel/locale/es.yml @@ -0,0 +1,8 @@ +Ink: Tinta +Origin: Origen +Producer: Productor. +With visible: Con visible +Field: Campo +More fields: Más campos +Add field: Añadir campo +Remove field: Quitar campo \ No newline at end of file diff --git a/modules/item/front/summary/index.html b/modules/item/front/summary/index.html new file mode 100644 index 000000000..bee9df310 --- /dev/null +++ b/modules/item/front/summary/index.html @@ -0,0 +1,108 @@ + +
    {{$ctrl.item.id}} - {{$ctrl.summary.item.name}}
    + + + + + +

    Visible

    +

    {{$ctrl.summary.visible}}

    +
    + +

    Available

    +

    {{$ctrl.summary.available}}

    +
    +
    +
    + +

    Basic data

    + + + + + + + + + + + + + + +
    + +

    Other data

    + + + + + + + + + + + + + + +
    + +

    Tags

    + + +
    + +

    Tax

    + + +
    + +

    Niche

    + + +
    + +

    Botanical

    + + + + + + +
    + +

    Barcode

    +

    + {{barcode.code}} +

    +
    +
    +
    \ No newline at end of file diff --git a/modules/item/front/summary/index.js b/modules/item/front/summary/index.js new file mode 100644 index 000000000..7e12abda0 --- /dev/null +++ b/modules/item/front/summary/index.js @@ -0,0 +1,29 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($http) { + this.$http = $http; + } + + getSummary() { + this.$http.get(`Items/${this.item.id}/getSummary`).then(response => { + this.summary = response.data; + }); + } + + $onChanges() { + if (this.item && this.item.id) + this.getSummary(); + } +} + +Controller.$inject = ['$http']; + +ngModule.component('vnItemSummary', { + template: require('./index.html'), + controller: Controller, + bindings: { + item: '<', + }, +}); diff --git a/modules/item/front/summary/index.spec.js b/modules/item/front/summary/index.spec.js new file mode 100644 index 000000000..1b6c2a812 --- /dev/null +++ b/modules/item/front/summary/index.spec.js @@ -0,0 +1,37 @@ +import './index.js'; + +describe('Item', () => { + describe('Component summary', () => { + let controller; + let $httpBackend; + + beforeEach(ngModule('item')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + controller = $componentController('vnItemSummary'); + controller.item = {id: 1}; + })); + + describe('getSummary()', () => { + it('should perform a query to set summary', () => { + let data = {id: 1, name: 'Gem of mind'}; + $httpBackend.when('GET', `Items/1/getSummary`).respond(200, data); + $httpBackend.expect('GET', `Items/1/getSummary`); + controller.getSummary(); + $httpBackend.flush(); + + expect(controller.summary).toEqual(data); + }); + }); + + describe('$onChanges()', () => { + it('should call getSummary when item.id is defined', () => { + spyOn(controller, 'getSummary'); + controller.$onChanges(); + + expect(controller.getSummary).toHaveBeenCalledWith(); + }); + }); + }); +}); diff --git a/modules/item/front/summary/locale/es.yml b/modules/item/front/summary/locale/es.yml new file mode 100644 index 000000000..3324e13d5 --- /dev/null +++ b/modules/item/front/summary/locale/es.yml @@ -0,0 +1,3 @@ +Niche: Nichos +Barcode: Códigos de barras +Other data: Otros datos \ No newline at end of file diff --git a/modules/item/front/summary/style.scss b/modules/item/front/summary/style.scss new file mode 100644 index 000000000..bb7e5d227 --- /dev/null +++ b/modules/item/front/summary/style.scss @@ -0,0 +1,35 @@ +@import "./variables"; + +vn-item-summary { + p { + margin: 0; + } +} + +.item-state { + padding: .4em; + background-color: $color-main; + color: $color-font-dark; + + p { + font-size: .8em; + text-align: center; + margin: 0; + + &:first-child { + text-transform: uppercase; + line-height: 1; + } + &:last-child { + font-size: 1.5em; + font-weight: bold; + } + } + vn-one { + padding: 0; + + &:nth-child(1) { + border-right: .1em solid white; + } + } +} \ No newline at end of file diff --git a/modules/item/front/tags/index.html b/modules/item/front/tags/index.html new file mode 100644 index 000000000..b7b61107d --- /dev/null +++ b/modules/item/front/tags/index.html @@ -0,0 +1,83 @@ + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/modules/item/front/tags/index.js b/modules/item/front/tags/index.js new file mode 100644 index 000000000..c12e1b9b5 --- /dev/null +++ b/modules/item/front/tags/index.js @@ -0,0 +1,83 @@ +import ngModule from '../module'; + +class Controller { + constructor($stateParams, $scope) { + this.$stateParams = $stateParams; + this.$scope = $scope; + this.include = { + relation: 'tag', + scope: { + fields: ['id', 'name', 'isFree', 'sourceTable'] + } + }; + this.sourceTables = {}; + } + + set itemTags(value) { + if (value) { + value.forEach(tag => { + this.getSourceTable(tag); + }); + + this._itemTags = value; + } + } + + get itemTags() { + return this._itemTags; + } + + getSourceTable(obj) { + let sourceTable; + this.sourceTables[obj.id] = {}; + let tag = obj.tag || obj.selection; + + if (!tag || !tag.sourceTable && (tag.isFree === true || tag.isFree === undefined)) + sourceTable = null; + else if (tag.sourceTable) { + sourceTable = '' + tag.sourceTable.charAt(0).toUpperCase() + + tag.sourceTable.substring(1) + 's'; + this.sourceTables[obj.id].field = 'name'; + } else { + sourceTable = `ItemTags/filterItemTags/${tag.id}`; + this.sourceTables[obj.id].field = 'value'; + } + + this.sourceTables[obj.id].url = sourceTable; + } + + add() { + this.$scope.model.insert({ + itemFk: this.$stateParams.id, + priority: this.getHighestPriority() + }); + } + + getHighestPriority() { + let max = 0; + this.$scope.model.data.forEach(tag => { + if (tag.priority > max) + max = tag.priority; + }); + return max + 1; + } + + onSubmit() { + this.$scope.watcher.check(); + this.$scope.model.save().then(() => { + this.$scope.watcher.notifySaved(); + this.$scope.watcher.updateOriginalData(); + this.card.reload(); + }); + } +} + +Controller.$inject = ['$stateParams', '$scope']; + +ngModule.component('vnItemTags', { + template: require('./index.html'), + controller: Controller, + require: { + card: '^vnItemCard' + } +}); diff --git a/modules/item/front/tags/index.spec.js b/modules/item/front/tags/index.spec.js new file mode 100644 index 000000000..d1b5acccc --- /dev/null +++ b/modules/item/front/tags/index.spec.js @@ -0,0 +1,73 @@ +import './index.js'; +import crudModel from 'core/mocks/crud-model'; + +describe('Item', () => { + describe('Component vnItemTags', () => { + let $scope; + let controller; + + beforeEach(ngModule('item')); + + beforeEach(angular.mock.inject(($componentController, $rootScope) => { + $scope = $rootScope.$new(); + $scope.model = crudModel; + $scope.model.data = [{priority: 1}, {priority: 2}, {priority: 1}]; + controller = $componentController('vnItemTags', {$scope}); + })); + + describe('itemTags setter', () => { + it('should call getSourceTable one time for each element in the value array', () => { + spyOn(controller, 'getSourceTable'); + let itemTags = [ + {id: 1}, + {id: 2}, + {id: 3}, + {id: 4} + ]; + + controller.itemTags = itemTags; + + expect(controller.getSourceTable.calls.count()).toEqual(4); + expect(controller.itemTags).toEqual(itemTags); + }); + }); + + describe('getSourceTable', () => { + it('should return null when the property isFree equals true', () => { + let tag = {id: 1}; + controller.getSourceTable(tag); + + expect(controller.sourceTables[1].url).toBe(null); + }); + + it('should return the route of the model in loopback with the first char of the string uppercase and adding a s', () => { + let tag = {id: 1, tag: {sourceTable: 'ink'}}; + controller.getSourceTable(tag); + + expect(controller.sourceTables[1].url).toBe('Inks'); + }); + + it('should return the route filteritemtags with the id of the selection', () => { + let tag = {id: 1, tag: {id: 3, sourceTable: null, isFree: false}}; + controller.getSourceTable(tag); + + expect(controller.sourceTables[1].url).toBe('ItemTags/filterItemTags/3'); + }); + }); + + describe('getHighestPriority', () => { + it('should return the highest priority value + 1 from the array', () => { + let result = controller.getHighestPriority(); + + expect(result).toEqual(3); + }); + + it('should return 1 when there is no priority defined', () => { + $scope.model.data = []; + let result = controller.getHighestPriority(); + + expect(result).toEqual(1); + }); + }); + }); +}); diff --git a/modules/item/front/tax/index.html b/modules/item/front/tax/index.html new file mode 100644 index 000000000..39feaa13d --- /dev/null +++ b/modules/item/front/tax/index.html @@ -0,0 +1,34 @@ + + + + +
    + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/modules/item/front/tax/index.js b/modules/item/front/tax/index.js new file mode 100644 index 000000000..e0c2428de --- /dev/null +++ b/modules/item/front/tax/index.js @@ -0,0 +1,49 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($stateParams, $http, $translate, $scope) { + this.$ = $scope; + this.$http = $http; + this.$stateParams = $stateParams; + this._ = $translate; + } + + $onInit() { + this.getTaxes(); + } + + getTaxes() { + let filter = { + fields: ['id', 'countryFk', 'taxClassFk'], + include: [{ + relation: 'country', + scope: {fields: ['country']} + }] + }; + + let url = `Items/${this.$stateParams.id}/taxes`; + this.$http.get(url, {params: {filter}}).then(json => { + this.taxes = json.data; + }); + } + + submit() { + let data = []; + for (let tax of this.taxes) + data.push({id: tax.id, taxClassFk: tax.taxClassFk}); + + this.$.watcher.check(); + let url = `Items/updateTaxes`; + this.$http.post(url, data).then(() => { + this.$.watcher.notifySaved(); + this.$.watcher.updateOriginalData(); + }); + } +} + +Controller.$inject = ['$stateParams', '$http', '$translate', '$scope']; + +ngModule.component('vnItemTax', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/item/front/tax/index.spec.js b/modules/item/front/tax/index.spec.js new file mode 100644 index 000000000..ddc582ad3 --- /dev/null +++ b/modules/item/front/tax/index.spec.js @@ -0,0 +1,65 @@ +import './index.js'; + +describe('Item', () => { + describe('Component vnItemTax', () => { + let $element; + let $stateParams; + let controller; + let $httpBackend; + + beforeEach(ngModule('item')); + + beforeEach(angular.mock.inject((_$httpBackend_, $rootScope, _$stateParams_, $compile) => { + $stateParams = _$stateParams_; + $stateParams.id = 1; + $httpBackend = _$httpBackend_; + + $httpBackend.whenRoute('GET', 'TaxClasses') + .respond([ + {id: 1, description: 'Reduced VAT', code: 'R'}, + {id: 2, description: 'General VAT', code: 'G'} + ]); + + $httpBackend.whenRoute('GET', 'Items/:id/taxes') + .respond([ + {id: 1, taxClassFk: 1} + ]); + + $element = $compile(` { + $element.remove(); + }); + + describe('getTaxes()', () => { + it('should perform a query to set the array of taxes into the controller', () => { + $httpBackend.flush(); + + expect(controller.taxes[0].id).toEqual(1); + expect(controller.taxes[0].taxClassFk).toEqual(1); + }); + }); + + describe('submit()', () => { + it('should perform a post to update taxes', () => { + spyOn(controller.$.watcher, 'notifySaved'); + spyOn(controller.$.watcher, 'updateOriginalData'); + controller.taxes = [ + {id: 37, countryFk: 1, taxClassFk: 1, country: {id: 1, country: 'España'}} + ]; + controller.$.watcher.data = [ + {id: 37, countryFk: 1, taxClassFk: 2, country: {id: 1, country: 'España'}} + ]; + + $httpBackend.whenPOST(`Items/updateTaxes`).respond('oki doki'); + controller.submit(); + $httpBackend.flush(); + + expect(controller.$.watcher.notifySaved).toHaveBeenCalledWith(); + expect(controller.$.watcher.updateOriginalData).toHaveBeenCalledWith(); + }); + }); + }); +}); diff --git a/modules/item/front/waste/index.html b/modules/item/front/waste/index.html new file mode 100644 index 000000000..d363f0ce0 --- /dev/null +++ b/modules/item/front/waste/index.html @@ -0,0 +1,32 @@ + + + + +
    + +
    {{detail.buyer}}
    +
    + + + + Family + Percentage + Dwindle + Total + + + + + {{::waste.family}} + {{::(waste.percentage / 100) | percentage: 2}} + {{::waste.dwindle | currency: 'EUR'}} + {{::waste.total | currency: 'EUR'}} + + + +
    +
    +
    diff --git a/modules/item/front/waste/index.js b/modules/item/front/waste/index.js new file mode 100644 index 000000000..9344c2222 --- /dev/null +++ b/modules/item/front/waste/index.js @@ -0,0 +1,8 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +ngModule.component('vnItemWaste', { + template: require('./index.html'), + controller: Component +}); diff --git a/modules/item/front/waste/locale/es.yml b/modules/item/front/waste/locale/es.yml new file mode 100644 index 000000000..9f08e3a72 --- /dev/null +++ b/modules/item/front/waste/locale/es.yml @@ -0,0 +1,3 @@ +Family: Familia +Percentage: Porcentaje +Dwindle: Mermas \ No newline at end of file diff --git a/modules/item/front/waste/style.scss b/modules/item/front/waste/style.scss new file mode 100644 index 000000000..59e9a3b68 --- /dev/null +++ b/modules/item/front/waste/style.scss @@ -0,0 +1,25 @@ +@import "variables"; + +vn-item-waste { + .header { + margin-bottom: 16px; + text-transform: uppercase; + font-size: 15pt; + line-height: 1; + padding: 7px; + padding-bottom: 7px; + padding-bottom: 4px; + font-weight: lighter; + background-color: #fde6ca; + border-bottom: 0.1em solid #f7931e; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + vn-table vn-th.waste-family, + vn-table vn-td.waste-family { + max-width: 4em; + width: 4em + } +} \ No newline at end of file diff --git a/modules/order/back/methods/order-row/addToOrder.js b/modules/order/back/methods/order-row/addToOrder.js new file mode 100644 index 000000000..45304917c --- /dev/null +++ b/modules/order/back/methods/order-row/addToOrder.js @@ -0,0 +1,42 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethod('addToOrder', { + description: 'Creates rows (lines) for a order', + accessType: 'WRITE', + accepts: [{ + arg: 'params', + type: 'object', + required: true, + description: 'order id, [items]', + http: {source: 'body'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/addToOrder`, + verb: 'POST' + } + }); + + Self.addToOrder = async params => { + let isEditable = await Self.app.models.Order.isEditable(params.orderFk); + + if (!isEditable) + throw new UserError('This order is not editable'); + + let promises = []; + params.items.forEach(item => { + promises.push( + Self.rawSql( + `CALL hedera.order_addItem(?, ?, ?, ?)`, + [params.orderFk, item.warehouseFk, item.itemFk, item.quantity] + ) + ); + }); + await Promise.all(promises); + return true; + }; +}; diff --git a/modules/order/back/methods/order-row/removes.js b/modules/order/back/methods/order-row/removes.js new file mode 100644 index 000000000..86f0e70d7 --- /dev/null +++ b/modules/order/back/methods/order-row/removes.js @@ -0,0 +1,39 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethod('removes', { + description: 'Delete an Order Row', + accessType: 'WRITE', + accepts: [{ + arg: 'params', + type: 'object', + required: true, + description: '[Row IDs], actualOrderId', + http: {source: 'body'} + }], + returns: { + type: 'string', + root: true + }, + http: { + path: `/removes`, + verb: 'post' + } + }); + + Self.removes = async params => { + if (!params.rows || !params.rows.length) + throw new UserError('There is nothing to delete'); + + let isEditable = await Self.app.models.Order.isEditable(params.actualOrderId); + + if (!isEditable) + throw new UserError('This order is not editable'); + + let promises = []; + for (let i = 0; i < params.rows.length; i++) + promises.push(Self.app.models.OrderRow.destroyById(params.rows[i])); + + return await Promise.all(promises); + }; +}; diff --git a/modules/order/back/methods/order-row/specs/addToOrder.spec.js b/modules/order/back/methods/order-row/specs/addToOrder.spec.js new file mode 100644 index 000000000..3b832dee2 --- /dev/null +++ b/modules/order/back/methods/order-row/specs/addToOrder.spec.js @@ -0,0 +1,34 @@ +const app = require('vn-loopback/server/server'); + +describe('order addToOrder()', () => { + const orderId = 8; + let rowToDelete; + afterAll(async done => { + await app.models.OrderRow.removes({rows: [rowToDelete], actualOrderId: orderId}); + + done(); + }); + + it('should add a row to a given order', async() => { + let unmodifiedRows = await app.models.OrderRow.find({where: {orderFk: orderId}}); + + expect(unmodifiedRows.length).toBe(2); + + let params = { + orderFk: orderId, + items: [{ + itemFk: 1, + quantity: 10, + warehouseFk: 1 + }] + }; + + await app.models.OrderRow.addToOrder(params); + + let modifiedRows = await app.models.OrderRow.find({where: {orderFk: orderId}}); + + rowToDelete = modifiedRows[modifiedRows.length - 1].id; + + expect(modifiedRows.length).toBe(3); + }); +}); diff --git a/modules/order/back/methods/order-row/specs/removes.spec.js b/modules/order/back/methods/order-row/specs/removes.spec.js new file mode 100644 index 000000000..1c68c6052 --- /dev/null +++ b/modules/order/back/methods/order-row/specs/removes.spec.js @@ -0,0 +1,47 @@ +const app = require('vn-loopback/server/server'); + +describe('order removes()', () => { + let row; + let newRow; + + beforeAll(async done => { + row = await app.models.OrderRow.findOne({where: {id: 12}}); + row.id = null; + newRow = await app.models.OrderRow.create(row); + + done(); + }); + + it('should throw an error if rows property is empty', async() => { + let error; + try { + await app.models.OrderRow.removes({rows: []}); + } catch (e) { + error = e; + } + + expect(error).toEqual(new Error('There is nothing to delete')); + }); + + it('should throw an error if the row selected is not editable', async() => { + let error; + try { + await app.models.OrderRow.removes({rows: [2]}); + } catch (e) { + error = e; + } + + expect(error).toEqual(new Error('This order is not editable')); + }); + + it('should delete the row', async() => { + let params = { + rows: [newRow.id], + actualOrderId: 16 + }; + + let res = await app.models.OrderRow.removes(params); + + expect(res).toEqual([{count: 1}]); + }); +}); diff --git a/modules/order/back/methods/order/catalogFilter.js b/modules/order/back/methods/order/catalogFilter.js new file mode 100644 index 000000000..3814aa12d --- /dev/null +++ b/modules/order/back/methods/order/catalogFilter.js @@ -0,0 +1,201 @@ +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('catalogFilter', { + description: 'Find all instances of the model matched by filter from the data source.', + accessType: 'READ', + accepts: [ + { + arg: 'orderFk', + type: 'Number', + required: true + }, + { + arg: 'orderBy', + type: 'Object', + description: 'Items order', + required: true + }, + { + arg: 'filter', + type: 'Object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string' + }, + { + arg: 'tags', + type: ['Object'], + description: 'Filter by tag' + }, + ], + returns: { + type: ['Object'], + root: true, + }, + http: { + path: `/catalogFilter`, + verb: 'GET', + }, + }); + + Self.catalogFilter = async(orderFk, orderBy, filter, tags) => { + let conn = Self.dataSource.connector; + const stmts = []; + let stmt; + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.item'); + + stmt = new ParameterizedSQL( + `CREATE TEMPORARY TABLE tmp.item + (PRIMARY KEY (itemFk)) ENGINE = MEMORY + SELECT DISTINCT + i.id AS itemFk, + i.typeFk, + it.categoryFk + FROM vn.item i + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk`); + + // Filter by tag + if (tags) { + let i = 1; + for (const tag of tags) { + const tAlias = `it${i++}`; + + if (tag.tagFk) { + stmt.merge({ + sql: `JOIN vn.itemTag ${tAlias} ON ${tAlias}.itemFk = i.id + AND ${tAlias}.tagFk = ? + AND ${tAlias}.value LIKE ?`, + params: [tag.tagFk, `%${tag.value}%`], + }); + } else { + stmt.merge({ + sql: `JOIN vn.itemTag ${tAlias} ON ${tAlias}.itemFk = i.id + AND ${tAlias}.value LIKE ?`, + params: [`%${tag.value}%`], + }); + } + } + } + + stmt.merge(conn.makeWhere(filter.where)); + stmts.push(stmt); + + // Calculate items + const order = await Self.findById(orderFk); + stmts.push(new ParameterizedSQL( + 'CALL vn.catalog_calculate(?, ?, ?)', [ + order.landed, + order.address_id, + order.agency_id, + ] + )); + + stmt = new ParameterizedSQL(`SELECT + i.id, + i.name, + i.subName, + i.image, + i.tag5, + i.value5, + i.tag6, + i.value6, + i.tag7, + i.value7, + i.tag8, + i.value8, + tci.price, + tci.available, + w.lastName AS lastName, + w.firstName, + tci.priceKg + FROM tmp.ticketCalculateItem tci + JOIN vn.item i ON i.id = tci.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + LEFT JOIN vn.ink ON ink.id = i.inkFk + JOIN vn.worker w on w.id = it.workerFk`); + + // Apply order by tag + if (orderBy.isTag) { + stmt.merge({ + sql: ` + LEFT JOIN vn.itemTag itg + LEFT JOIN vn.tag t ON t.id = itg.tagFk + ON itg.itemFk = tci.itemFk AND itg.tagFk = ?`, + params: [orderBy.field], + }); + + let way = orderBy.way == 'DESC' ? 'DESC' : 'ASC'; + let tag = await Self.app.models.Tag.findById(orderBy.field); + let orderSql = ` + ORDER BY + itg.value IS NULL, + ${tag.isQuantitative ? 'CAST(itg.value AS SIGNED)' : 'itg.value'} + ${way}`; + + stmt.merge(orderSql); + } else { + // Apply order by field + let orderParam = `${orderBy.field} ${orderBy.way}`; + orderParam = orderParam.split(/\s*,/).map(param => param.trim()); + stmt.merge(conn.makeOrderBy(orderParam)); + } + + stmt.merge(Self.makeLimit(filter)); + const itemsIndex = stmts.push(stmt) - 1; + + // Apply item prices + const pricesIndex = stmts.push( + `SELECT + tcp.itemFk, + tcp.grouping, + tcp.price, + tcp.rate, + tcp.warehouseFk, + tcp.priceKg, + w.name AS warehouse + FROM tmp.ticketComponentPrice tcp + JOIN vn.warehouse w ON w.id = tcp.warehouseFk`) - 1; + + // Get tags from all items + const itemTagsIndex = stmts.push( + `SELECT + it.tagFk, + it.itemFk, + t.name + FROM tmp.ticketCalculateItem tci + JOIN vn.itemTag it ON it.itemFk = tci.itemFk + JOIN vn.tag t ON t.id = it.tagFk`) - 1; + + // Clean temporary tables + stmts.push('CALL vn.ticketCalculatePurge()'); + + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await conn.executeStmt(sql); + + // Add prices to items + result[itemsIndex].forEach(item => { + result[pricesIndex].forEach(price => { + if (item.id === price.itemFk) { + if (item.prices) + item.prices.push(price); + else + item.prices = [price]; + + item.available = price.grouping; + } + }); + }); + + // Attach item tags + result[itemsIndex].forEach(item => { + item.tags = []; + result[itemTagsIndex].forEach(itemTag => { + if (item.id === itemTag.itemFk) + item.tags.push(itemTag); + }); + }); + + return result[itemsIndex]; + }; +}; diff --git a/modules/order/back/methods/order/confirm.js b/modules/order/back/methods/order/confirm.js new file mode 100644 index 000000000..b9e4f5ab2 --- /dev/null +++ b/modules/order/back/methods/order/confirm.js @@ -0,0 +1,27 @@ +module.exports = Self => { + Self.remoteMethodCtx('confirm', { + description: 'Confirms an order', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'order id', + http: {source: 'path'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/confirm`, + verb: 'POST' + } + }); + + Self.confirm = async(ctx, orderFk) => { + const userId = ctx.req.accessToken.userId; + let query = `CALL hedera.order_confirmWithUser(?, ?)`; + return await Self.rawSql(query, [orderFk, userId]); + }; +}; diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js new file mode 100644 index 000000000..1eaa167a7 --- /dev/null +++ b/modules/order/back/methods/order/filter.js @@ -0,0 +1,195 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const buildFilter = require('vn-loopback/util/filter').buildFilter; +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethod('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accepts: [ + { + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + }, { + arg: 'filter', + type: 'Object', + description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string` + }, { + arg: 'search', + type: 'String', + description: `If it's and integer searchs by id, otherwise it searchs by nickname` + }, { + arg: 'from', + type: 'Date', + description: `The from date` + }, { + arg: 'to', + type: 'Date', + description: `The to date` + }, { + arg: 'id', + type: 'Integer', + description: `The ticket id` + }, { + arg: 'clientFk', + type: 'Integer', + description: `The client id` + }, { + arg: 'ticketFk', + type: 'Integer', + description: `The ticket id` + }, { + arg: 'agencyModeFk', + type: 'Integer', + description: `The agency mode id` + }, { + arg: 'workerFk', + type: 'Integer', + description: `The salesperson id` + }, { + arg: 'myTeam', + type: 'Boolean', + description: `Whether to show only tickets for the current logged user team (For now it shows only the current user tickets)` + }, { + arg: 'isConfirmed', + type: 'Boolean', + description: `Order is confirmed` + } + ], + returns: { + type: ['Object'], + root: true + }, + http: { + path: '/filter', + verb: 'GET' + } + }); + + Self.filter = async(ctx, filter) => { + let conn = Self.dataSource.connector; + let worker = await Self.app.models.Worker.findOne({ + where: {userFk: ctx.req.accessToken.userId}, + include: [ + {relation: 'collegues'} + ] + }); + let teamIds = []; + + if (worker.collegues().length && ctx.args.myTeam) { + worker.collegues().forEach(collegue => { + teamIds.push(collegue.collegueFk); + }); + } + + if (worker.collegues().length === 0 && ctx.args.myTeam) { + worker = await Self.app.models.Worker.findOne({ + fields: ['id'], + where: {userFk: ctx.req.accessToken.userId} + }); + teamIds = [worker && worker.id]; + } + + if (ctx.args && ctx.args.myTeam) + ctx.args.teamIds = teamIds; + let where = buildFilter(ctx.args, (param, value) => { + switch (param) { + case 'search': + return /^\d+$/.test(value) + ? {'o.id': value} + : {or: [ + {'c.name': {like: `%${value}%`}} + ]}; + // return {'o.id': value}; + case 'from': + return {'o.date_send': {gte: value}}; + case 'to': + return {'o.date_send': {lte: value}}; + case 'workerFk': + return {'c.salesPersonFk': value}; + case 'clientFk': + return {'o.customer_id': value}; + case 'agencyModeFk': + return {'o.agency_id': value}; + case 'sourceApp': + return {'o.source_app': value}; + case 'ticketFk': + return {'ort.ticketFk': value}; + case 'isConfirmed': + return {'o.confirmed': value ? 1 : 0}; + case 'myTeam': + return {'c.salesPersonFk': {inq: teamIds}}; + case 'id': + param = `o.${param}`; + return {[param]: value}; + } + }); + + filter = mergeFilters(filter, {where}); + + let stmts = []; + let stmt; + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.filter'); + + stmt = new ParameterizedSQL( + `CREATE TEMPORARY TABLE tmp.filter + (INDEX (id)) + ENGINE = MEMORY + SELECT + o.id, + o.date_send landed, + o.date_make created, + o.customer_id clientFk, + o.agency_id agencyModeFk, + o.address_id addressFk, + o.company_id companyFk, + o.source_app sourceApp, + o.confirmed isConfirmed, + c.name clientName, + c.salesPersonFk, + u.nickname workerNickname, + co.code companyCode + FROM hedera.order o + LEFT JOIN address a ON a.id = o.address_id + LEFT JOIN agencyMode am ON am.id = o.agency_id + LEFT JOIN client c ON c.id = o.customer_id + LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN account.user u ON u.id = wk.userFk + LEFT JOIN company co ON co.id = o.company_id`); + + if (ctx.args && ctx.args.ticketFk) { + stmt.merge({ + sql: `LEFT JOIN orderTicket ort ON ort.orderFk = o.id` + }); + } + stmt.merge(conn.makeSuffix(filter)); + stmts.push(stmt); + + stmts.push(` + CREATE TEMPORARY TABLE tmp.order + (INDEX (orderFk)) + ENGINE = MEMORY + SELECT id AS orderFk + FROM tmp.filter`); + + stmts.push('CALL hedera.order_getTotal()'); + + let orderIndex = stmts.push(` + SELECT f.*, ot.* + FROM tmp.filter f + LEFT JOIN tmp.orderTotal ot ON ot.orderFk = f.id`) - 1; + + stmts.push(` + DROP TEMPORARY TABLE + tmp.order, + tmp.orderTotal, + tmp.filter`); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + + return result[orderIndex]; + }; +}; diff --git a/modules/order/back/methods/order/getItemTypeAvailable.js b/modules/order/back/methods/order/getItemTypeAvailable.js new file mode 100644 index 000000000..977a2cf85 --- /dev/null +++ b/modules/order/back/methods/order/getItemTypeAvailable.js @@ -0,0 +1,57 @@ +const app = require('vn-loopback/server/server'); +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('getItemTypeAvailable', { + description: 'Gets the item types available for an rder and item category ', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'order id', + http: {source: 'path'} + }, + { + arg: 'itemCategoryId', + type: 'number', + required: true + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/:id/getItemTypeAvailable`, + verb: 'GET' + } + }); + + Self.getItemTypeAvailable = async(orderId, itemCategoryId) => { + let stmts = []; + let stmt; + + let order = await app.models.Order.findById(orderId); + stmt = new ParameterizedSQL('call vn.available_calc(?, ?, ?)', [ + order.landed, + order.addressFk, + order.agencyModeFk + ]); + stmts.push(stmt); + stmt = new ParameterizedSQL(`SELECT it.id, it.name + FROM tmp.availableCalc ac + JOIN cache.available a ON a.calc_id = ac.calcFk + JOIN item i ON i.id = a.item_id + JOIN itemType it ON it.id = i.typeFk + WHERE it.categoryFk = ? + GROUP BY it.id`, [ + itemCategoryId + ]); + let categoriesIndex = stmts.push(stmt) - 1; + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await Self.rawStmt(sql); + + return result[categoriesIndex]; + }; +}; diff --git a/modules/order/back/methods/order/getSourceValues.js b/modules/order/back/methods/order/getSourceValues.js new file mode 100644 index 000000000..da3685c62 --- /dev/null +++ b/modules/order/back/methods/order/getSourceValues.js @@ -0,0 +1,18 @@ +module.exports = Self => { + Self.remoteMethod('getSourceValues', { + description: 'Gets the sourceApp type set', + accessType: 'READ', + returns: { + type: ['String'], + root: true + }, + http: { + path: `/getSourceValues`, + verb: 'GET' + } + }); + + Self.getSourceValues = async () => { + return Self.getSetValues('sourceApp'); + }; +}; diff --git a/modules/order/back/methods/order/getTaxes.js b/modules/order/back/methods/order/getTaxes.js new file mode 100644 index 000000000..e7ffd467b --- /dev/null +++ b/modules/order/back/methods/order/getTaxes.js @@ -0,0 +1,53 @@ +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('getTaxes', { + description: 'Gets the taxes of a given order', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'order id', + http: {source: 'path'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/getTaxes`, + verb: 'GET' + } + }); + + Self.getTaxes = async orderFk => { + let conn = Self.dataSource.connector; + let stmts = []; + let stmt; + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.order'); + + + stmt = new ParameterizedSQL(` + CREATE TEMPORARY TABLE tmp.order + (INDEX (orderFk)) + ENGINE = MEMORY + SELECT ? AS orderFk`, [orderFk]); + stmts.push(stmt); + + stmts.push('CALL hedera.order_getTax()'); + + let orderTaxIndex = stmts.push('SELECT * FROM tmp.orderAmount') - 1; + + stmts.push(` + DROP TEMPORARY TABLE + tmp.order, + tmp.orderTax`); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + + return result[orderTaxIndex]; + }; +}; diff --git a/modules/order/back/methods/order/getTotal.js b/modules/order/back/methods/order/getTotal.js new file mode 100644 index 000000000..32d46f605 --- /dev/null +++ b/modules/order/back/methods/order/getTotal.js @@ -0,0 +1,28 @@ +module.exports = Self => { + Self.remoteMethod('getTotal', { + description: 'Gets the total for an order', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'ticket id', + http: {source: 'path'} + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/:id/getTotal`, + verb: 'GET' + } + }); + + Self.getTotal = async orderFk => { + let query = `SELECT hedera.order_getTotal(?) total;`; + let [total] = await Self.rawSql(query, [orderFk]); + + return total.total; + }; +}; diff --git a/modules/order/back/methods/order/getTotalVolume.js b/modules/order/back/methods/order/getTotalVolume.js new file mode 100644 index 000000000..93dbcbee8 --- /dev/null +++ b/modules/order/back/methods/order/getTotalVolume.js @@ -0,0 +1,27 @@ +module.exports = Self => { + Self.remoteMethod('getTotalVolume', { + description: 'Gets the total volume for an order', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'ticket id', + http: {source: 'path'} + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/:id/getTotalVolume`, + verb: 'GET' + } + }); + + Self.getTotalVolume = async orderFk => { + let query = `SELECT vn.orderTotalVolume(?) totalVolume, vn.orderTotalVolumeBoxes(?) totalBoxes`; + let [res] = await Self.rawSql(query, [orderFk, orderFk]); + return res; + }; +}; diff --git a/modules/order/back/methods/order/getVAT.js b/modules/order/back/methods/order/getVAT.js new file mode 100644 index 000000000..146d1254b --- /dev/null +++ b/modules/order/back/methods/order/getVAT.js @@ -0,0 +1,31 @@ +module.exports = Self => { + Self.remoteMethod('getVAT', { + description: 'Returns order total VAT', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'order id', + http: {source: 'path'} + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/:id/getVAT`, + verb: 'GET' + } + }); + + Self.getVAT = async orderId => { + let totalTax = 0.00; + let taxes = await Self.app.models.Order.getTaxes(orderId); + taxes.forEach(tax => { + totalTax += tax.tax; + }); + + return Math.round(totalTax * 100) / 100; + }; +}; diff --git a/modules/order/back/methods/order/getVolumes.js b/modules/order/back/methods/order/getVolumes.js new file mode 100644 index 000000000..de3f87912 --- /dev/null +++ b/modules/order/back/methods/order/getVolumes.js @@ -0,0 +1,25 @@ +module.exports = Self => { + Self.remoteMethod('getVolumes', { + description: 'Returns the volumes of a order', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'order id', + http: {source: 'path'} + }], + returns: { + arg: 'volumes' + }, + http: { + path: `/:id/getVolumes`, + verb: 'GET' + } + }); + + Self.getVolumes = async orderFk => { + let [volume] = await Self.rawSql(`CALL vn.orderListVolume(?)`, [orderFk]); + return volume; + }; +}; diff --git a/modules/order/back/methods/order/isEditable.js b/modules/order/back/methods/order/isEditable.js new file mode 100644 index 000000000..5f1fc7872 --- /dev/null +++ b/modules/order/back/methods/order/isEditable.js @@ -0,0 +1,45 @@ +module.exports = Self => { + Self.remoteMethod('isEditable', { + description: 'Check if an order is editable', + accessType: 'READ', + accepts: [{ + arg: 'orderId', + type: 'number', + required: true, + description: 'orderId', + http: {source: 'path'} + }], + returns: { + type: 'boolean', + root: true + }, + http: { + path: `/:orderId/isEditable`, + verb: 'get' + } + }); + + Self.isEditable = async orderId => { + let exists = await Self.app.models.Order.findOne({ + where: {id: orderId}, + fields: ['isConfirmed', 'clientFk'], + include: [ + {relation: 'client', + scope: { + include: { + relation: 'type' + } + } + } + ] + }); + + if (exists && exists.client().type().code !== 'normal') + return true; + + if (!exists || exists.isConfirmed === 1) + return false; + + return true; + }; +}; diff --git a/modules/order/back/methods/order/new.js b/modules/order/back/methods/order/new.js new file mode 100644 index 000000000..4f1f2c3aa --- /dev/null +++ b/modules/order/back/methods/order/new.js @@ -0,0 +1,65 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethod('new', { + description: 'Create a new order and returns the new ID', + accessType: 'WRITE', + accepts: [ + { + arg: 'landed', + description: 'The landed for the order', + type: 'date', + required: true + }, { + arg: 'addressId', + description: 'The address for the order', + type: 'number', + required: true + }, { + arg: 'agencyModeId', + description: 'The agencyMode for the order', + type: 'number', + required: true + } + ], + returns: { + type: 'number', + root: true + }, + http: { + path: `/new`, + verb: 'post' + } + }); + + Self.new = async(landed, addressId, agencyModeId) => { + let address = await Self.app.models.Address.findOne({ + where: {id: addressId}, + fields: ['clientFk'], + include: [ + {relation: 'client', + scope: { + include: { + relation: 'type' + } + } + } + ] + }); + + if (address.client().type().code === 'normal') { + if (!address.client().isActive) + throw new UserError(`You can't create an order for a inactive client`); + } + + query = `CALL vn.orderListCreate(?, ?, ?, ?);`; + [result] = await Self.rawSql(query, [ + landed, + agencyModeId, + addressId, + 'SALIX' + ]); + + return result[0].vOrderId; + }; +}; diff --git a/modules/order/back/methods/order/newFromTicket.js b/modules/order/back/methods/order/newFromTicket.js new file mode 100644 index 000000000..285f60ee8 --- /dev/null +++ b/modules/order/back/methods/order/newFromTicket.js @@ -0,0 +1,34 @@ +module.exports = Self => { + Self.remoteMethod('newFromTicket', { + description: 'Create a new order and returns the new ID', + accessType: 'WRITE', + accepts: [{ + arg: 'ticketFk', + type: 'number', + description: 'The ticket id', + required: true + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/newFromTicket`, + verb: 'post' + } + }); + + Self.newFromTicket = async ticketFk => { + let ticket = await Self.app.models.Ticket.findOne({ + where: {id: ticketFk} + }); + + let landed = ticket.landed; + let addressFk = ticket.addressFk; + let agencyModeFk = ticket.agencyModeFk; + + let orderID = await Self.app.models.Order.new(landed, addressFk, agencyModeFk); + + return orderID; + }; +}; diff --git a/modules/order/back/methods/order/specs/catalogFilter.spec.js b/modules/order/back/methods/order/specs/catalogFilter.spec.js new file mode 100644 index 000000000..12cafa5b7 --- /dev/null +++ b/modules/order/back/methods/order/specs/catalogFilter.spec.js @@ -0,0 +1,39 @@ +const app = require('vn-loopback/server/server'); + +describe('order catalogFilter()', () => { + it('should return an array of items', async() => { + let filter = { + where: { + categoryFk: 1, + typeFk: 2 + } + }; + let tags = []; + let orderFk = 11; + let orderBy = {field: 'relevancy DESC, name', way: 'DESC'}; + let result = await app.models.Order.catalogFilter(orderFk, orderBy, filter, tags); + let firstItemId = result[0].id; + + expect(result.length).toEqual(4); + expect(firstItemId).toEqual(1); + }); + + it('should now return an array of items based on tag filter', async() => { + let filter = { + where: { + categoryFk: 1, + typeFk: 2 + } + }; + + let tags = [{tagFk: 56, value: 'Melee Reinforced weapon'}]; + let orderFk = 11; + let orderBy = {field: 'relevancy DESC, name', way: 'DESC'}; + let result = await app.models.Order.catalogFilter(orderFk, orderBy, filter, tags); + + let firstItemId = result[0].id; + + expect(result.length).toEqual(1); + expect(firstItemId).toEqual(9); + }); +}); diff --git a/modules/order/back/methods/order/specs/filter.spec.js b/modules/order/back/methods/order/specs/filter.spec.js new file mode 100644 index 000000000..fc987613a --- /dev/null +++ b/modules/order/back/methods/order/specs/filter.spec.js @@ -0,0 +1,32 @@ +const app = require('vn-loopback/server/server'); + +describe('order filter()', () => { + let ctx = { + req: {accessToken: {userId: 9}}, + args: {}, + params: {} + }; + + it('should call the filter method with a basic search', async() => { + let filter = {where: {'o.id': 2}}; + let result = await app.models.Order.filter(ctx, filter); + let orderId = result[0].id; + + expect(orderId).toEqual(2); + }); + + it('should call the filter method with a single advanced search', async() => { + let filter = {where: {'o.confirmed': false}}; + let result = await app.models.Order.filter(ctx, filter); + + expect(result.length).toEqual(16); + }); + + it('should call the filter method with a complex advanced search', async() => { + let filter = {where: {'o.confirmed': false, 'c.salesPersonFk': 19}}; + let result = await app.models.Order.filter(ctx, filter); + + expect(result.length).toEqual(7); + expect(result[0].id).toEqual(16); + }); +}); diff --git a/modules/order/back/methods/order/specs/getItemTypeAvailable.spec.js b/modules/order/back/methods/order/specs/getItemTypeAvailable.spec.js new file mode 100644 index 000000000..66be6462a --- /dev/null +++ b/modules/order/back/methods/order/specs/getItemTypeAvailable.spec.js @@ -0,0 +1,19 @@ +const app = require('vn-loopback/server/server'); + +describe('order getItemTypeAvailable()', () => { + it('should call the getItemTypeAvailable method with a valid order and item category', async() => { + let orderId = 11; + let itemCategoryId = 1; + let result = await app.models.Order.getItemTypeAvailable(orderId, itemCategoryId); + + expect(result.length).toEqual(1); + }); + + it('should call the getItemTypeAvailable method with the same order and different item category', async() => { + let orderId = 11; + let itemCategoryId = 4;// + let result = await app.models.Order.getItemTypeAvailable(orderId, itemCategoryId); + + expect(result.length).toEqual(0); + }); +}); diff --git a/modules/order/back/methods/order/specs/getTaxes.spec.js b/modules/order/back/methods/order/specs/getTaxes.spec.js new file mode 100644 index 000000000..303b72050 --- /dev/null +++ b/modules/order/back/methods/order/specs/getTaxes.spec.js @@ -0,0 +1,31 @@ +const app = require('vn-loopback/server/server'); + +describe('order getTaxes()', () => { + it('should call the getTaxes method and return undefined if its called with a string', async() => { + let result = await app.models.Order.getTaxes('string'); + + expect(result.length).toEqual(0); + }); + + it('should call the getTaxes method and return undefined if its called with unknown id', async() => { + let result = await app.models.Order.getTaxes(99999999999999999999999); + + expect(result.length).toEqual(0); + }); + + it('should call the getTaxes method and return the taxes splited if different type of taxes', async() => { + let result = await app.models.Order.getTaxes(1); + + const expectedResult = result[0].tax + result[1].tax; + + expect(expectedResult).toEqual(20.29); + expect(result.length).toEqual(2); + }); + + it('should call the getTaxes method and return the taxes for them same type', async() => { + let result = await app.models.Order.getTaxes(2); + + expect(result[0].tax).toEqual(9.1); + expect(result.length).toEqual(1); + }); +}); diff --git a/modules/order/back/methods/order/specs/getTotal.spec.js b/modules/order/back/methods/order/specs/getTotal.spec.js new file mode 100644 index 000000000..613f00241 --- /dev/null +++ b/modules/order/back/methods/order/specs/getTotal.spec.js @@ -0,0 +1,9 @@ +const app = require('vn-loopback/server/server'); + +describe('order getTotal()', () => { + it('should return the order total', async() => { + let result = await app.models.Order.getTotal(1); + + expect(result).toEqual(155.89); + }); +}); diff --git a/modules/order/back/methods/order/specs/getTotalVolume.spec.js b/modules/order/back/methods/order/specs/getTotalVolume.spec.js new file mode 100644 index 000000000..7cd9c9e64 --- /dev/null +++ b/modules/order/back/methods/order/specs/getTotalVolume.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('order getTotalVolume()', () => { + it('should return the total', async() => { + let result = await app.models.Order.getTotalVolume(1); + + expect(result.totalVolume).toEqual(1.568); + expect(result.totalBoxes).toEqual(11.1); + }); +}); diff --git a/modules/order/back/methods/order/specs/getVAT.spec.js b/modules/order/back/methods/order/specs/getVAT.spec.js new file mode 100644 index 000000000..5306535d2 --- /dev/null +++ b/modules/order/back/methods/order/specs/getVAT.spec.js @@ -0,0 +1,9 @@ +const app = require('vn-loopback/server/server'); + +describe('order getVAT()', () => { + it('should return the order VAT', async() => { + const result = await app.models.Order.getVAT(1); + + expect(result).toEqual(20.29); + }); +}); diff --git a/modules/order/back/methods/order/specs/getVolumes.spec.js b/modules/order/back/methods/order/specs/getVolumes.spec.js new file mode 100644 index 000000000..4113a8e07 --- /dev/null +++ b/modules/order/back/methods/order/specs/getVolumes.spec.js @@ -0,0 +1,9 @@ +const app = require('vn-loopback/server/server'); + +describe('order getVolumes()', () => { + it('should return the volumes of a given order id', async() => { + let [result] = await app.models.Order.getVolumes(1); + + expect(result.volume).toEqual(1.09); + }); +}); diff --git a/modules/order/back/methods/order/specs/isEditable.spec.js b/modules/order/back/methods/order/specs/isEditable.spec.js new file mode 100644 index 000000000..2a7b54225 --- /dev/null +++ b/modules/order/back/methods/order/specs/isEditable.spec.js @@ -0,0 +1,21 @@ +const app = require('vn-loopback/server/server'); + +describe('order isEditable()', () => { + it('should return false when the given order is not editable', async() => { + let isEditable = await app.models.Order.isEditable(2); + + expect(isEditable).toBeFalsy(); + }); + + it('should return false when the given order doesnt exists', async() => { + let isEditable = await app.models.Order.isEditable(99999); + + expect(isEditable).toBeFalsy(); + }); + + it('should return true when the given order is editable', async() => { + let isEditable = await app.models.Order.isEditable(16); + + expect(isEditable).toBeTruthy(); + }); +}); diff --git a/modules/order/back/methods/order/specs/new.spec.js b/modules/order/back/methods/order/specs/new.spec.js new file mode 100644 index 000000000..1cd3e8ce8 --- /dev/null +++ b/modules/order/back/methods/order/specs/new.spec.js @@ -0,0 +1,38 @@ +const app = require('vn-loopback/server/server'); +let UserError = require('vn-loopback/util/user-error'); + +describe('order new()', () => { + let orderId; + + afterAll(async done => { + await app.models.Order.destroyById(orderId); + + done(); + }); + + it('should throw an error if the client isnt active', async() => { + let error; + let landed = new Date(); + let addressFk = 6; + let agencyModeFk = 1; + + await app.models.Order.new(landed, addressFk, agencyModeFk) + .catch(e => { + error = e; + }); + + expect(error).toEqual(new UserError(`You can't create an order for a inactive client`)); + }); + + it('should create a new order a user when all conditions are met', async() => { + let landed = new Date(); + let addressFk = 121; + let agencyModeFk = 1; + + orderId = await app.models.Order.new(landed, addressFk, agencyModeFk); + + let highestOrderIdInFixtures = 3; + + expect(orderId).toBeGreaterThan(highestOrderIdInFixtures); + }); +}); diff --git a/modules/order/back/methods/order/specs/summary.spec.js b/modules/order/back/methods/order/specs/summary.spec.js new file mode 100644 index 000000000..f6f917ede --- /dev/null +++ b/modules/order/back/methods/order/specs/summary.spec.js @@ -0,0 +1,36 @@ +const app = require('vn-loopback/server/server'); + +describe('order summary()', () => { + it('should return a summary object containing data from 1 order', async() => { + let result = await app.models.Order.summary(1); + + expect(result.id).toEqual(1); + expect(result.clientFk).toEqual(101); + }); + + it('should return a summary object containing sales from 1 order', async() => { + let result = await app.models.Order.summary(1); + + expect(result.rows.length).toEqual(3); + }); + + it('should return a summary object containing subTotal for 1 order', async() => { + let result = await app.models.Order.summary(1); + + expect(Math.round(result.subTotal * 100) / 100).toEqual(135.60); + }); + + it('should return a summary object containing VAT for 1 order', async() => { + let result = await app.models.Order.summary(1); + + expect(Math.round(result.VAT * 100) / 100).toEqual(20.29); + }); + + it('should return a summary object containing total for 1 order', async() => { + let result = await app.models.Order.summary(1); + let total = result.subTotal + result.VAT; + let expectedTotal = Math.round(total * 100) / 100; + + expect(result.total).toEqual(expectedTotal); + }); +}); diff --git a/modules/order/back/methods/order/specs/updateBasicData.spec.js b/modules/order/back/methods/order/specs/updateBasicData.spec.js new file mode 100644 index 000000000..5e83d69a0 --- /dev/null +++ b/modules/order/back/methods/order/specs/updateBasicData.spec.js @@ -0,0 +1,63 @@ +const app = require('vn-loopback/server/server'); + +describe('Order updateBasicData', () => { + const orderId = 21; + afterAll(async done => { + let validparams = {note: null}; + + await app.models.Order.updateBasicData(orderId, validparams); + + done(); + }); + + it('should return an error if the order is confirmed', async() => { + let error; + + let params = []; + let orderConfirmed = 1; + + await app.models.Order.updateBasicData(orderConfirmed, params) + .catch(e => { + error = e; + }); + + expect(error.toString()).toContain(`You can't make changes on the basic data of an confirmed order or with rows`); + }); + + it('should return an error if the order has rows', async() => { + let error; + + let params = []; + let orderWithRows = 16; + + await app.models.Order.updateBasicData(orderWithRows, params) + .catch(e => { + error = e; + }); + + expect(error.toString()).toContain(`You can't make changes on the basic data of an confirmed order or with rows`); + }); + + it('should skip invalid params', async() => { + let success; + + let invalidparams = {invalid: 'param for update'}; + + await app.models.Order.updateBasicData(orderId, invalidparams) + .then(() => success = true); + + expect(success).toBeTruthy(); + }); + + it('should update the client fiscal data and return the count if changes made', async() => { + let validparams = {note: 'test note'}; + + let order = await app.models.Order.findById(orderId); + + expect(order.note).toEqual(null); + + let result = await app.models.Order.updateBasicData(orderId, validparams); + + expect(result.note).toEqual('test note'); + }); +}); diff --git a/modules/order/back/methods/order/summary.js b/modules/order/back/methods/order/summary.js new file mode 100644 index 000000000..5acc5fb2e --- /dev/null +++ b/modules/order/back/methods/order/summary.js @@ -0,0 +1,81 @@ +module.exports = Self => { + Self.remoteMethod('summary', { + description: 'Returns a summary for a given order id', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'order id', + http: {source: 'path'} + }], + returns: { + type: [this.modelName], + root: true + }, + http: { + path: `/:id/summary`, + verb: 'GET' + } + }); + + Self.summary = async orderId => { + let models = Self.app.models; + let summary = await getOrderData(Self, orderId); + summary.subTotal = getSubTotal(summary.rows); + summary.VAT = await models.Order.getVAT(orderId); + summary.total = await models.Order.getTotal(orderId); + return summary; + }; + + async function getOrderData(Self, orderId) { + let filter = { + include: [ + {relation: 'agencyMode', scope: {fields: ['name']}}, + { + relation: 'client', + scope: { + fields: ['salesPersonFk', 'name'], + include: { + relation: 'salesPerson', + fields: ['firstName', 'name'] + } + } + }, + { + relation: 'address', + scope: { + fields: ['street', 'city', 'provinceFk', 'phone', 'nickname'], + include: { + relation: 'province', + scope: { + fields: ['name'] + } + } + } + }, + { + relation: 'rows', + scope: { + include: { + relation: 'item' + } + } + } + ], + where: {id: orderId} + }; + + return await Self.findOne(filter); + } + + function getSubTotal(rows) { + let subTotal = 0.00; + + rows().forEach(row => { + subTotal += row.quantity * row.price; + }); + + return subTotal; + } +}; diff --git a/modules/order/back/methods/order/updateBasicData.js b/modules/order/back/methods/order/updateBasicData.js new file mode 100644 index 000000000..8f4393c04 --- /dev/null +++ b/modules/order/back/methods/order/updateBasicData.js @@ -0,0 +1,55 @@ +let UserError = require('vn-loopback/util/user-error'); +let pick = require('object.pick'); + +module.exports = Self => { + Self.remoteMethod('updateBasicData', { + description: 'Updates basic data of an order', + accessType: 'WRITE', + accepts: [ + { + arg: 'id', + type: 'string', + required: true, + description: 'Model id', + http: {source: 'path'} + }, { + arg: 'data', + type: 'Object', + required: true, + description: 'Params to update', + http: {source: 'body'} + } + ], + returns: { + arg: 'order', + type: 'Object', + root: true + }, + http: { + path: `/:id/updateBasicData`, + verb: 'PATCH' + } + }); + + Self.updateBasicData = async(id, params) => { + let models = Self.app.models; + + let order = await models.Order.findById(id); + let orderRows = await models.OrderRow.find({where: {orderFk: id}}); + + if (order.isConfirmed || orderRows.length != 0) + throw new UserError(`You can't make changes on the basic data of an confirmed order or with rows`); + + let updateParams = pick(params, [ + 'clientFk', + 'addressFk', + 'landed', + 'agencyModeFk', + 'note', + ]); + if (Object.keys(updateParams).length) + await order.updateAttributes(updateParams); + + return await order; + }; +}; diff --git a/modules/order/back/model-config.json b/modules/order/back/model-config.json new file mode 100644 index 000000000..389c97e46 --- /dev/null +++ b/modules/order/back/model-config.json @@ -0,0 +1,11 @@ +{ + "Order": { + "dataSource": "vn" + }, + "OrderRow": { + "dataSource": "vn" + }, + "OrderTicket": { + "dataSource": "vn" + } +} diff --git a/modules/order/back/models/order-row.js b/modules/order/back/models/order-row.js new file mode 100644 index 000000000..248bc020e --- /dev/null +++ b/modules/order/back/models/order-row.js @@ -0,0 +1,4 @@ +module.exports = Self => { + require('../methods/order-row/addToOrder')(Self); + require('../methods/order-row/removes')(Self); +}; diff --git a/modules/order/back/models/order-row.json b/modules/order/back/models/order-row.json new file mode 100644 index 000000000..44d5a103a --- /dev/null +++ b/modules/order/back/models/order-row.json @@ -0,0 +1,60 @@ +{ + "name": "OrderRow", + "base": "VnModel", + "options": { + "mysql": { + "table": "hedera.orderRow" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "warehouseFk": { + "type": "Number" + }, + "shipped": { + "type": "date", + "mysql": { + "columnName": "shipment" + } + }, + "quantity": { + "type": "Number", + "mysql": { + "columnName": "amount" + } + }, + "price": { + "type": "Number" + }, + "rate": { + "type": "Number" + }, + "created": { + "type": "date" + }, + "saleFk": { + "type": "Number" + } + }, + "relations": { + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk" + }, + "order": { + "type": "belongsTo", + "model": "Order", + "foreignKey": "orderFk" + }, + "warehouse": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseFk" + } + } +} diff --git a/modules/order/back/models/order-ticket.json b/modules/order/back/models/order-ticket.json new file mode 100644 index 000000000..2875ebdfc --- /dev/null +++ b/modules/order/back/models/order-ticket.json @@ -0,0 +1,31 @@ +{ + "name": "OrderTicket", + "base": "VnModel", + "options": { + "mysql": { + "table": "orderTicket" + } + }, + "properties": { + "orderFk": { + "id": true, + "type": "Number" + }, + "ticketFk": { + "id": true, + "type": "Number" + } + }, + "relations": { + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk" + }, + "order": { + "type": "belongsTo", + "model": "Order", + "foreignKey": "orderFk" + } + } +} diff --git a/modules/order/back/models/order.js b/modules/order/back/models/order.js new file mode 100644 index 000000000..330019941 --- /dev/null +++ b/modules/order/back/models/order.js @@ -0,0 +1,26 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + require('../methods/order/new')(Self); + require('../methods/order/getTotalVolume')(Self); + require('../methods/order/getVolumes')(Self); + require('../methods/order/getTaxes')(Self); + require('../methods/order/isEditable')(Self); + require('../methods/order/getTotal')(Self); + require('../methods/order/catalogFilter')(Self); + require('../methods/order/summary')(Self); + require('../methods/order/getVAT')(Self); + require('../methods/order/getSourceValues')(Self); + require('../methods/order/newFromTicket')(Self); + require('../methods/order/updateBasicData')(Self); + require('../methods/order/confirm')(Self); + require('../methods/order/filter')(Self); + require('../methods/order/getItemTypeAvailable')(Self); + + Self.beforeRemote('deleteById', async function(ctx) { + const targetOrder = await Self.findById(ctx.args.id); + + if (targetOrder.isConfirmed === 1) + throw new UserError(`You can't delete a confirmed order`); + }); +}; diff --git a/modules/order/back/models/order.json b/modules/order/back/models/order.json new file mode 100644 index 000000000..ab10ad194 --- /dev/null +++ b/modules/order/back/models/order.json @@ -0,0 +1,116 @@ +{ + "name": "Order", + "base": "VnModel", + "options": { + "mysql": { + "table": "hedera.order" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "landed": { + "type": "Date", + "required": true, + "mysql": { + "columnName": "date_send" + } + }, + "clientFk": { + "type": "Number", + "required": true, + "mysql": { + "columnName": "customer_id" + } + }, + "addressFk": { + "type": "Number", + "required": true, + "mysql": { + "columnName": "address_id" + } + }, + "agencyModeFk": { + "type": "Number", + "required": true, + "mysql": { + "columnName": "agency_id" + } + }, + "companyFk": { + "type": "Number", + "required": true, + "mysql": { + "columnName": "company_id" + } + }, + "note": { + "type": "String" + }, + "sourceApp": { + "type": "String", + "mysql": { + "columnName": "source_app" + } + }, + "isConfirmed": { + "type": "Number", + "mysql": { + "columnName": "confirmed" + } + }, + "created": { + "type": "Date", + "mysql": { + "columnName": "date_make" + } + }, + "firstRowStamp": { + "type": "Date", + "mysql": { + "columnName": "first_row_stamp" + } + }, + "confirmed": { + "type": "Date", + "mysql": { + "columnName": "confirm_date" + } + } + }, + "relations": { + "agencyMode": { + "type": "belongsTo", + "model": "AgencyMode", + "foreignKey": "agency_id" + }, + "address": { + "type": "belongsTo", + "model": "Address", + "foreignKey": "address_id" + }, + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "customer_id" + }, + "deliveryMethod": { + "type": "belongsTo", + "model": "DeliveryMethod", + "foreignKey": "delivery_method_id" + }, + "rows": { + "type": "hasMany", + "model": "OrderRow", + "foreignKey": "orderFk" + }, + "company": { + "type": "belongsTo", + "model": "Company", + "foreignKey": "company_id" + } + } +} diff --git a/modules/order/front/basic-data/index.html b/modules/order/front/basic-data/index.html new file mode 100644 index 000000000..eaa73a25c --- /dev/null +++ b/modules/order/front/basic-data/index.html @@ -0,0 +1,72 @@ + + + + + +
    + + + + {{::id}}: {{::name}} + + + {{::nickname}} + + + + + + + {{::id}}: {{::name}} + + + + + + + + + + + +
    diff --git a/modules/order/front/basic-data/index.js b/modules/order/front/basic-data/index.js new file mode 100644 index 000000000..81aef8304 --- /dev/null +++ b/modules/order/front/basic-data/index.js @@ -0,0 +1,31 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope) { + let isDirty = false; + $scope.$watch('$ctrl.selection', newValue => { + if (newValue) { + $scope.addressModel.where = {clientFk: newValue.id}; + $scope.addressModel.refresh(); + if (isDirty) + this.order.addressFk = newValue.defaultAddressFk; + isDirty = true; + } else { + $scope.addressModel.clear(); + if (isDirty) + this.order.addressFk = null; + } + }); + } +} + +Controller.$inject = ['$scope']; + +ngModule.component('vnOrderBasicData', { + controller: Controller, + template: require('./index.html'), + bindings: { + order: '<' + } +}); diff --git a/modules/order/front/basic-data/index.spec.js b/modules/order/front/basic-data/index.spec.js new file mode 100644 index 000000000..0150bd3b3 --- /dev/null +++ b/modules/order/front/basic-data/index.spec.js @@ -0,0 +1,40 @@ +import './index.js'; + +describe('Order', () => { + describe('Component vnOrderBasicData', () => { + let $httpBackend; + let controller; + let $scope; + + beforeEach(ngModule('order')); + + beforeEach(angular.mock.inject(($compile, _$httpBackend_, $rootScope) => { + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + + $httpBackend.whenRoute('GET', 'Addresses') + .respond([{id: 2, nickname: 'address 2'}]); + $httpBackend.whenRoute('GET', 'Clients') + .respond([{id: 1, defaultAddressFk: 1}]); + $scope.order = {clientFk: 1, addressFk: 1}; + + let $element = $compile('')($scope); + $httpBackend.flush(); + controller = $element.controller('vnOrderBasicData'); + })); + + afterAll(() => { + $scope.$destroy(); + $element.remove(); + }); + + describe('constructor()', () => { + it('should update the address after the client changes', async() => { + controller.selection = {id: 2, defaultAddressFk: 2}; + $scope.$digest(); + + expect(controller.order.addressFk).toEqual(2); + }); + }); + }); +}); diff --git a/modules/order/front/basic-data/locale/es.yml b/modules/order/front/basic-data/locale/es.yml new file mode 100644 index 000000000..5c6014c9c --- /dev/null +++ b/modules/order/front/basic-data/locale/es.yml @@ -0,0 +1 @@ +This form has been disabled because there are lines in this order or it's confirmed: Este formulario ha sido deshabilitado por que esta orden contiene líneas o está confirmada \ No newline at end of file diff --git a/modules/order/front/basic-data/style.scss b/modules/order/front/basic-data/style.scss new file mode 100644 index 000000000..34d6c2931 --- /dev/null +++ b/modules/order/front/basic-data/style.scss @@ -0,0 +1,9 @@ +vn-order-basic-data { + .disabledForm { + text-align: center; + color: red; + span { + margin: 0 auto; + } + } +} \ No newline at end of file diff --git a/modules/order/front/card/index.html b/modules/order/front/card/index.html new file mode 100644 index 000000000..4f10c1728 --- /dev/null +++ b/modules/order/front/card/index.html @@ -0,0 +1,5 @@ + + + + + diff --git a/modules/order/front/card/index.js b/modules/order/front/card/index.js new file mode 100644 index 000000000..e79167761 --- /dev/null +++ b/modules/order/front/card/index.js @@ -0,0 +1,64 @@ +import ngModule from '../module'; +import ModuleCard from 'salix/components/module-card'; + +class Controller extends ModuleCard { + reload() { + let filter = { + include: [ + { + relation: 'agencyMode', + scope: { + fields: ['name'] + } + }, { + relation: 'address', + scope: { + fields: ['nickname'] + } + }, { + relation: 'rows', + scope: { + fields: ['id'] + } + }, { + relation: 'client', + scope: { + fields: [ + 'salesPersonFk', + 'name', + 'isActive', + 'isFreezed', + 'isTaxDataChecked' + ], + include: { + relation: 'salesPerson', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + } + } + } + ] + }; + + this.$q.all([ + this.$http.get(`Orders/${this.$params.id}`, {filter}) + .then(res => this.order = res.data), + this.$http.get(`Orders/${this.$params.id}/getTotal`) + .then(res => ({total: res.data})) + ]).then(res => { + this.order = Object.assign.apply(null, res); + }); + } +} + +ngModule.component('vnOrderCard', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/order/front/card/index.spec.js b/modules/order/front/card/index.spec.js new file mode 100644 index 000000000..19d070920 --- /dev/null +++ b/modules/order/front/card/index.spec.js @@ -0,0 +1,31 @@ +import './index.js'; + +describe('Order', () => { + describe('Component vnOrderCard', () => { + let controller; + let $httpBackend; + let data = {id: 1, name: 'fooName'}; + let total = 10.5; + + beforeEach(ngModule('order')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_, $stateParams) => { + $httpBackend = _$httpBackend_; + + let $element = angular.element('
    '); + controller = $componentController('vnOrderCard', {$element}); + + $stateParams.id = data.id; + $httpBackend.whenRoute('GET', 'Orders/:id').respond(data); + $httpBackend.whenRoute('GET', 'Orders/:id/getTotal').respond(200, total); + })); + + it('should request data and total, merge them, and set it on the controller', () => { + controller.reload(); + $httpBackend.flush(); + + expect(controller.order).toEqual(Object.assign({}, data, {total})); + }); + }); +}); + diff --git a/modules/order/front/catalog-search-panel/index.html b/modules/order/front/catalog-search-panel/index.html new file mode 100644 index 000000000..3bd0ba3e2 --- /dev/null +++ b/modules/order/front/catalog-search-panel/index.html @@ -0,0 +1,25 @@ +
    +
    + + + {{name}} + + + + + + + + + +
    +
    diff --git a/modules/order/front/catalog-search-panel/index.js b/modules/order/front/catalog-search-panel/index.js new file mode 100644 index 000000000..7d5f1bfd1 --- /dev/null +++ b/modules/order/front/catalog-search-panel/index.js @@ -0,0 +1,10 @@ +import ngModule from '../module'; +import SearchPanel from 'core/components/searchbar/search-panel'; + +ngModule.component('vnOrderCatalogSearchPanel', { + template: require('./index.html'), + controller: SearchPanel, + bindings: { + onSubmit: '&?' + } +}); diff --git a/modules/order/front/catalog/index.html b/modules/order/front/catalog/index.html new file mode 100644 index 000000000..8002c2b10 --- /dev/null +++ b/modules/order/front/catalog/index.html @@ -0,0 +1,72 @@ + + + + +
    + +
    + +
    +
    +

    + {{::item.name}} +

    +

    + {{::item.subName}} +

    +
    + + + + + + +
    + +
    +
    +
    +
    +
    + + + + + diff --git a/modules/order/front/catalog/index.js b/modules/order/front/catalog/index.js new file mode 100644 index 000000000..adb66171e --- /dev/null +++ b/modules/order/front/catalog/index.js @@ -0,0 +1,134 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $state) { + this.$scope = $scope; + this.$state = $state; + this.$stateParams = $state.params; + + // Static autocomplete data + this.orderWays = [ + {way: 'ASC', name: 'Ascendant'}, + {way: 'DESC', name: 'Descendant'}, + ]; + this.defaultOrderFields = [ + {field: 'relevancy DESC, name', name: 'Relevancy'}, + {field: 'showOrder, price', name: 'Color'}, + {field: 'name', name: 'Name'}, + {field: 'price', name: 'Price'} + ]; + this.orderFields = [].concat(this.defaultOrderFields); + this._orderWay = this.orderWays[0].way; + this._orderField = this.orderFields[0].field; + } + + /** + * Fills order autocomplete with tags + * obtained from last filtered + */ + onDataChange() { + const items = this.$scope.model.data; + const newFilterList = []; + if (!items) return; + + items.forEach(item => { + // Add new tag filters + item.tags.forEach(itemTag => { + const alreadyAdded = newFilterList.findIndex(filter => { + return filter.field == itemTag.tagFk; + }); + + if (alreadyAdded == -1) { + newFilterList.push({ + name: itemTag.name, + field: itemTag.tagFk, + isTag: true + }); + } + }); + }); + + // Add default filters - Replaces tags with same name + this.defaultOrderFields.forEach(orderField => { + const index = newFilterList.findIndex(newfield => { + return newfield.name == orderField.name; + }); + + if (index > -1) + newFilterList[index] = orderField; + else + newFilterList.push(orderField); + }); + + this.orderFields = newFilterList; + } + + /** + * Get order way ASC/DESC + */ + get orderWay() { + return this._orderWay; + } + + set orderWay(value) { + this._orderWay = value; + if (value) this.applyOrder(); + } + + /** + * Get order fields + */ + get orderField() { + return this._orderField; + } + + set orderField(value) { + this._orderField = value; + if (value) this.applyOrder(); + } + + /** + * Returns order param + * + * @return {Object} - Order param + */ + getOrderBy() { + return { + field: this.orderField, + way: this.orderWay, + isTag: !!(this.orderSelection && this.orderSelection.isTag) + }; + } + + /** + * Apply order to model + */ + applyOrder() { + this.$scope.model.addFilter(null, {orderBy: this.getOrderBy()}); + } + + preview(event, item) { + event.preventDefault(); + this.$scope.pricesPopover.show(event, item); + } + + onDescriptorLoad() { + this.$scope.popover.relocate(); + } + + $onChanges() { + if (this.order && this.order.isConfirmed) + this.$state.go('order.card.line'); + } +} + +Controller.$inject = ['$scope', '$state']; + +ngModule.component('vnOrderCatalog', { + template: require('./index.html'), + controller: Controller, + bindings: { + order: '<', + } +}); diff --git a/modules/order/front/catalog/index.spec.js b/modules/order/front/catalog/index.spec.js new file mode 100644 index 000000000..b6e70bb4a --- /dev/null +++ b/modules/order/front/catalog/index.spec.js @@ -0,0 +1,64 @@ +import './index.js'; +import crudModel from 'core/mocks/crud-model'; + +describe('Order', () => { + describe('Component vnOrderCatalog', () => { + let $scope; + let controller; + + beforeEach(ngModule('order')); + + beforeEach(angular.mock.inject(($componentController, $rootScope) => { + $scope = $rootScope.$new(); + $scope.model = crudModel; + $scope.field = {}; + controller = $componentController('vnOrderCatalog', {$scope: $scope}); + })); + + describe('onDataChange()', () => { + it(`should return an object with order params`, () => { + $scope.model.data = [{id: 1, name: 'My Item', tags: [ + {tagFk: 4, name: 'Length'}, + {tagFk: 5, name: 'Color'} + ]}]; + let expectedResult = [{field: 'showOrder, price', name: 'Color'}]; + let unexpectedResult = [{tagFk: 5, name: 'Color'}]; + controller.onDataChange(); + + expect(controller.orderFields.length).toEqual(5); + expect(controller.orderFields).toEqual(jasmine.arrayContaining(expectedResult)); + expect(controller.orderFields).not.toEqual(jasmine.arrayContaining(unexpectedResult)); + }); + }); + + describe('getOrderBy()', () => { + it(`should return an object with order params`, () => { + controller.orderField = 'relevancy DESC, name'; + controller.orderWay = 'DESC'; + let expectedResult = { + field: 'relevancy DESC, name', + way: 'DESC', + isTag: false + }; + let result = controller.getOrderBy(); + + expect(result).toEqual(expectedResult); + }); + }); + + describe('applyOrder()', () => { + it(`should apply order param to model calling getOrderBy()`, () => { + controller.field = 'relevancy DESC, name'; + controller.way = 'ASC'; + let expectedOrder = {orderBy: controller.getOrderBy()}; + spyOn(controller, 'getOrderBy').and.callThrough(); + spyOn(controller.$scope.model, 'addFilter'); + controller.applyOrder(); + + expect(controller.getOrderBy).toHaveBeenCalledWith(); + expect(controller.$scope.model.addFilter).toHaveBeenCalledWith(null, expectedOrder); + }); + }); + }); +}); + diff --git a/modules/order/front/catalog/locale/es.yml b/modules/order/front/catalog/locale/es.yml new file mode 100644 index 000000000..82fe5e9e8 --- /dev/null +++ b/modules/order/front/catalog/locale/es.yml @@ -0,0 +1 @@ +Order created: Orden creada diff --git a/modules/order/front/catalog/style.scss b/modules/order/front/catalog/style.scss new file mode 100644 index 000000000..18dc51bb0 --- /dev/null +++ b/modules/order/front/catalog/style.scss @@ -0,0 +1,31 @@ +@import "variables"; + +vn-order-catalog { + .catalog-header { + border-bottom: $border-thin; + padding: $spacing-md; + align-items: center; + + & > vn-one { + display: flex; + flex: 1; + + span { + color: $color-font-secondary + } + } + & > vn-auto { + width: 28em; + display: flex; + overflow: hidden; + + & > * { + padding-left: $spacing-md; + } + } + } + .catalog-list { + padding-top: $spacing-sm; + } +} + diff --git a/modules/order/front/create/card.html b/modules/order/front/create/card.html new file mode 100644 index 000000000..d252d680f --- /dev/null +++ b/modules/order/front/create/card.html @@ -0,0 +1,34 @@ + + {{id}}: {{name}} + + + {{nickname}}: {{street}}, {{city}} + + + + + diff --git a/modules/order/front/create/card.js b/modules/order/front/create/card.js new file mode 100644 index 000000000..7f1bb6133 --- /dev/null +++ b/modules/order/front/create/card.js @@ -0,0 +1,119 @@ +import ngModule from '../module'; + +class Controller { + constructor($http, vnApp, $translate, $state, $stateParams) { + this.$stateParams = $stateParams; + this.$http = $http; + this.translate = $translate; + this.vnApp = vnApp; + this.order = {}; + this.$state = $state; + this.clientFk = $stateParams.clientFk; + } + + $onInit() { + if (this.$stateParams && this.$stateParams.clientFk) + this.clientFk = this.$stateParams.clientFk; + } + + set order(value) { + if (value) + this._order = value; + } + + get order() { + return this._order; + } + + set clientFk(value) { + this.order.clientFk = value; + + if (value) { + let filter = { + include: { + relation: 'defaultAddress', + scope: { + fields: 'id' + } + }, + where: {id: value} + }; + filter = encodeURIComponent(JSON.stringify(filter)); + let query = `Clients?filter=${filter}`; + this.$http.get(query).then(res => { + if (res.data) { + let client = res.data[0]; + let defaultAddress = client.defaultAddress; + this.addressFk = defaultAddress.id; + } + }); + } else + this.addressFk = null; + } + + get clientFk() { + return this.order.clientFk; + } + + set addressFk(value) { + this.order.addressFk = value; + this.getAvailableAgencies(); + } + + get addressFk() { + return this.order.addressFk; + } + + set landed(value) { + this.order.landed = value; + this.getAvailableAgencies(); + } + + get landed() { + return this.order.landed; + } + + get warehouseFk() { + return this.order.warehouseFk; + } + + getAvailableAgencies() { + let order = this.order; + order.agencyModeFk = null; + + let params = { + addressFk: order.addressFk, + landed: order.landed + }; + if (params.landed && params.addressFk) { + this.$http.get(`Agencies/landsThatDay`, {params}) + .then(res => this._availableAgencies = res.data); + } + } + + onSubmit() { + this.createOrder(); + } + + createOrder() { + let params = { + landed: this.order.landed, + addressId: this.order.addressFk, + agencyModeId: this.order.agencyModeFk + }; + this.$http.post(`Orders/new`, params).then(res => { + this.vnApp.showSuccess(this.translate.instant('Data saved!')); + this.$state.go('order.card.catalog', {id: res.data}); + }); + } +} + +Controller.$inject = ['$http', 'vnApp', '$translate', '$state', '$stateParams']; + +ngModule.component('vnOrderCreateCard', { + template: require('./card.html'), + controller: Controller, + bindings: { + order: ' { + describe('Component vnOrderCreateCard', () => { + let controller; + let $httpBackend; + + beforeEach(ngModule('order')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_, _vnApp_) => { + $httpBackend = _$httpBackend_; + controller = $componentController('vnOrderCreateCard'); + controller.item = {id: 3}; + })); + + describe('set order', () => { + it(`should set order if the value given is not null`, () => { + controller.order = 1; + + expect(controller.order).toEqual(1); + }); + }); + + describe('set clientFk', () => { + it(`should set addressFk to null and clientFk to a value and set addressFk to a value given`, () => { + let filter = { + include: { + relation: 'defaultAddress', + scope: { + fields: 'id' + } + }, + where: {id: 2} + }; + filter = encodeURIComponent(JSON.stringify(filter)); + let response = [ + { + defaultAddress: {id: 1} + } + ]; + $httpBackend.whenGET(`Clients?filter=${filter}`).respond(response); + $httpBackend.expectGET(`Clients?filter=${filter}`); + + controller.clientFk = 2; + $httpBackend.flush(); + + expect(controller.clientFk).toEqual(2); + expect(controller.order.addressFk).toBe(1); + }); + }); + + describe('set addressFk', () => { + it(`should set agencyModeFk property to null and addressFk to a value`, () => { + controller.addressFk = 101; + + expect(controller.addressFk).toEqual(101); + expect(controller.order.agencyModeFk).toBe(null); + }); + }); + + describe('getAvailableAgencies()', () => { + it(`should make a query if landed and addressFk exists`, () => { + controller.order.addressFk = 101; + controller.order.landed = 101; + + $httpBackend.whenRoute('GET', 'Agencies/landsThatDay') + .respond({data: 1}); + + controller.getAvailableAgencies(); + $httpBackend.flush(); + }); + }); + + describe('onSubmit()', () => { + it(`should call createOrder()`, () => { + spyOn(controller, 'createOrder'); + controller.onSubmit(); + + expect(controller.createOrder).toHaveBeenCalledWith(); + }); + }); + + describe('createOrder()', () => { + it(`should make a query, call vnApp.showSuccess and $state.go if the response is defined`, () => { + controller.order.landed = 101; + controller.order.addressFk = 101; + controller.order.agencyModeFk = 101; + + spyOn(controller.vnApp, 'showSuccess'); + spyOn(controller.$state, 'go'); + $httpBackend.when('POST', 'Orders/new', {landed: 101, addressId: 101, agencyModeId: 101}).respond(200, 1); + $httpBackend.expect('POST', 'Orders/new', {landed: 101, addressId: 101, agencyModeId: 101}); + controller.createOrder(); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + expect(controller.$state.go).toHaveBeenCalledWith('order.card.catalog', {id: 1}); + }); + }); + }); +}); + diff --git a/modules/order/front/create/index.html b/modules/order/front/create/index.html new file mode 100644 index 000000000..11de7ff6c --- /dev/null +++ b/modules/order/front/create/index.html @@ -0,0 +1,9 @@ +
    + + + + + + + +
    \ No newline at end of file diff --git a/modules/order/front/create/index.js b/modules/order/front/create/index.js new file mode 100644 index 000000000..9c8d7ce6b --- /dev/null +++ b/modules/order/front/create/index.js @@ -0,0 +1,20 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $http, $state) { + this.$ = $scope; + this.$http = $http; + this.$state = $state; + } + + async onSubmit() { + let newOrderID = await this.$.card.createOrder(); + this.$state.go('order.card.summary', {id: newOrderID}); + } +} +Controller.$inject = ['$scope', '$http', '$state']; + +ngModule.component('vnOrderCreate', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/order/front/create/index.spec.js b/modules/order/front/create/index.spec.js new file mode 100644 index 000000000..6c1714004 --- /dev/null +++ b/modules/order/front/create/index.spec.js @@ -0,0 +1,33 @@ +import './index.js'; + +describe('Order', () => { + describe('Component vnOrderCreate', () => { + let $scope; + let controller; + + beforeEach(ngModule('order')); + + beforeEach(angular.mock.inject(($componentController, $rootScope) => { + $scope = $rootScope.$new(); + $scope.card = {createOrder: () => {}}; + controller = $componentController('vnOrderCreate', {$scope}); + })); + + describe('onSubmit()', () => { + it(`should call createOrder()`, () => { + spyOn(controller.$.card, 'createOrder'); + controller.onSubmit(); + + expect(controller.$.card.createOrder).toHaveBeenCalledWith(); + }); + + it(`should call go()`, async() => { + spyOn(controller.$state, 'go'); + await controller.onSubmit(); + + expect(controller.$state.go).toHaveBeenCalledWith('order.card.summary', {id: undefined}); + }); + }); + }); +}); + diff --git a/modules/order/front/create/locale/es.yml b/modules/order/front/create/locale/es.yml new file mode 100644 index 000000000..df21d09f4 --- /dev/null +++ b/modules/order/front/create/locale/es.yml @@ -0,0 +1,6 @@ +You can't create an order for a frozen client: No puedes crear una orden a un cliente congelado +You can't create an order for a inactive client: No puedes crear una orden a un cliente inactivo +You can't create an order for a client that doesn't has tax data verified: + No puedes crear una orden a un cliente cuyos datos fiscales no han sido verificados +You can't create an order for a client that has a debt: No puedes crear una orden a un cliente que tiene deuda +New order: Nueva orden \ No newline at end of file diff --git a/modules/order/front/descriptor/index.html b/modules/order/front/descriptor/index.html new file mode 100644 index 000000000..0a9e2ee38 --- /dev/null +++ b/modules/order/front/descriptor/index.html @@ -0,0 +1,59 @@ +
    +
    + + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + \ No newline at end of file diff --git a/modules/order/front/descriptor/index.js b/modules/order/front/descriptor/index.js new file mode 100644 index 000000000..0d8a1e14a --- /dev/null +++ b/modules/order/front/descriptor/index.js @@ -0,0 +1,70 @@ +import ngModule from '../module'; + +class Controller { + constructor($translate, $scope, vnApp, $http, $state) { + this.$state = $state; + this.$scope = $scope; + this.vnApp = vnApp; + this.$http = $http; + this.$translate = $translate; + this.moreOptions = [ + {name: 'Delete order', callback: () => this.showDeleteOrderDialog()} + ]; + } + + set order(value) { + this._order = value; + if (!value) return; + + if (value.isConfirmed) { + this._quicklinks = { + btnOne: { + icon: 'icon-ticket', + state: `ticket.index({q: '{"orderFk": ${value.id}}'})`, + tooltip: 'Order ticket list' + }, + btnTwo: { + icon: 'person', + state: `client.card.summary({id: ${value.clientFk}})`, + tooltip: 'Client card' + } + }; + } + } + + get order() { + return this._order; + } + + set quicklinks(value = {}) { + this._quicklinks = Object.assign(value, this._quicklinks); + } + + get quicklinks() { + return this._quicklinks; + } + + deleteOrder(response) { + if (response === 'accept') { + const params = {id: this.order.id}; + this.$http.delete(`Orders/${params.id}`).then(() => { + this.$state.go('order.index'); + this.vnApp.showSuccess(this.$translate.instant('Order deleted')); + }); + } + } + + showDeleteOrderDialog() { + this.$scope.deleteOrderConfirmation.show(); + } +} + +Controller.$inject = ['$translate', '$scope', 'vnApp', '$http', '$state']; + +ngModule.component('vnOrderDescriptor', { + template: require('./index.html'), + bindings: { + order: '<' + }, + controller: Controller +}); diff --git a/modules/order/front/descriptor/index.spec.js b/modules/order/front/descriptor/index.spec.js new file mode 100644 index 000000000..a0818ebe7 --- /dev/null +++ b/modules/order/front/descriptor/index.spec.js @@ -0,0 +1,42 @@ +import './index.js'; + +describe('Order Component vnOrderDescriptor', () => { + let $httpBackend; + let controller; + + beforeEach(ngModule('order')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + controller = $componentController('vnOrderDescriptor'); + controller.order = {id: 1}; + })); + + describe('deleteOrder()', () => { + it(`should do nothing if the response isn't accept`, () => { + let response = 'WAGH!'; + + spyOn(controller.vnApp, 'showSuccess'); + spyOn(controller.$state, 'go'); + controller.deleteOrder(response); + + expect(controller.vnApp.showSuccess).not.toHaveBeenCalledWith('Order deleted!'); + expect(controller.$state.go).not.toHaveBeenCalledWith('order.index'); + }); + + it(`should perform a DELETE query if the response was accept`, () => { + let response = 'accept'; + + spyOn(controller.vnApp, 'showSuccess'); + spyOn(controller.$state, 'go'); + $httpBackend.when('DELETE', `Orders/${controller.order.id}`).respond(200); + $httpBackend.expect('DELETE', `Orders/${controller.order.id}`); + controller.deleteOrder(response); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Order deleted'); + expect(controller.$state.go).toHaveBeenCalledWith('order.index'); + }); + }); +}); + diff --git a/modules/order/front/descriptor/locale/es.yml b/modules/order/front/descriptor/locale/es.yml new file mode 100644 index 000000000..0734d7638 --- /dev/null +++ b/modules/order/front/descriptor/locale/es.yml @@ -0,0 +1,12 @@ +Client: Cliente +Confirmed: Confirmado +Not confirmed: Sin confirmar +State: Estado +Landed: F. entrega +Items: Articulos +Agency: Agencia +Sales person: Comercial +Order ticket list: Ticket del pedido +Delete order: Eliminar pedido +You are going to delete this order: El pedido se eliminará +continue anyway?: ¿Continuar de todos modos? \ No newline at end of file diff --git a/modules/order/front/filter/index.html b/modules/order/front/filter/index.html new file mode 100644 index 000000000..68691e0a7 --- /dev/null +++ b/modules/order/front/filter/index.html @@ -0,0 +1,125 @@ + + +
    + + + + + + + + + + + + + + + + + + +
    + More than {{model.limit}} results +
    +
    + + + + + + + + + + + + + + + + + + + + +
    + + {{$ctrl.category.value}} + + + {{$ctrl.type.value}} + + + {{::tag.value}} + +
    +
    \ No newline at end of file diff --git a/modules/order/front/filter/index.js b/modules/order/front/filter/index.js new file mode 100644 index 000000000..03dd0fa33 --- /dev/null +++ b/modules/order/front/filter/index.js @@ -0,0 +1,190 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($element, $http, $scope, $state, $compile, $transitions) { + this.$element = $element; + this.$http = $http; + this.$ = $scope; + this.$state = $state; + this.$stateParams = $state.params; + this.$compile = $compile; + this.$transitions = $transitions; + this.itemTypes = []; + this.tags = []; + } + + get order() { + return this._order; + } + + /** + * Sets filter values from state params + * + * @param {Object} value - Order data + */ + set order(value) { + if (!value || !value.id || this._order) return; + this._order = value; + + this.$.$applyAsync(() => { + let category; + let type; + + if (this.$stateParams.category) + category = JSON.parse(this.$stateParams.category); + + if (this.$stateParams.type) + type = JSON.parse(this.$stateParams.type); + + if (category && category.id) + this.category = category; + + if (type && type.id) + this.type = type; + }); + } + + get category() { + return this._category; + } + + set category(value) { + this.catalog.$scope.model.data = []; + this.itemTypes = []; + this.type = null; + + if (!value || (this.category && this.category.id == value.id)) + this._category = null; + else + this._category = value; + + this.updateStateParams(); + + if (this.tags.length > 0) + this.applyFilters(); + + if (this._category) + this.updateItemTypes(); + } + + get type() { + return this._type; + } + + set type(value) { + if (value && this.type && this.type.id == value.id) return; + + this._type = value; + + if (!value || !value.id) + this._type = null; + + this.updateStateParams(); + + if ((value && value.id) || this.tags.length > 0) + this.applyFilters(); + } + + /** + * Refreshes item type dropdown data + */ + updateItemTypes() { + let params = { + itemCategoryId: this.category.id + }; + + const query = `Orders/${this.order.id}/getItemTypeAvailable`; + this.$http.get(query, {params}).then(res => { + this.itemTypes = res.data; + }); + } + + onSearchById(event) { + if (event.key === 'Enter' && (this.tags.length > 0 || this.itemFk || this.type)) + this.applyFilters(); + } + + onSearchByTag(event) { + if (event.key !== 'Enter' || !this.value) return; + this.tags.push({ + value: this.value, + }); + this.$.search.value = null; + this.applyFilters(); + } + + remove(index) { + this.tags.splice(index, 1); + + if (this.tags.length >= 0 || this.itemFk || this.type) + this.applyFilters(); + } + + applyFilters() { + let newParams = {}; + let newFilter = {}; + const model = this.catalog.$scope.model; + + if (this.category) + newFilter.categoryFk = this.category.id; + + if (this.type) + newFilter.typeFk = this.type.id; + + if (this.itemFk) + newFilter = {'i.id': this.itemFk}; + + newParams = { + orderFk: this.order.id, + orderBy: this.catalog.getOrderBy(), + tags: this.tags, + }; + + model.applyFilter({where: newFilter}, newParams); + } + + openPanel(event) { + if (event.defaultPrevented) return; + event.preventDefault(); + + this.panelFilter = {}; + this.$.popover.show(this.$.search.element); + } + + onPanelSubmit(filter) { + this.$.popover.hide(); + this.tags.push(filter); + this.applyFilters(); + } + + /** + * Updates url state params from filter values + */ + updateStateParams() { + const params = {}; + + if (this.category) + params.category = JSON.stringify(this.category); + + if (this.type) + params.type = JSON.stringify(this.type); + else + params.type = undefined; + + this.$state.go(this.$state.current.name, params); + } +} + +Controller.$inject = ['$element', '$http', '$scope', '$state', '$compile', '$transitions']; + +ngModule.component('vnCatalogFilter', { + template: require('./index.html'), + controller: Controller, + require: { + catalog: '^vnOrderCatalog' + }, + bindings: { + order: '<' + } +}); diff --git a/modules/order/front/filter/index.spec.js b/modules/order/front/filter/index.spec.js new file mode 100644 index 000000000..8fb4baeca --- /dev/null +++ b/modules/order/front/filter/index.spec.js @@ -0,0 +1,172 @@ +import './index.js'; +import crudModel from 'core/mocks/crud-model'; + +describe('Order', () => { + describe('Component vnCatalogFilter', () => { + let $scope; + let $state; + let controller; + let $httpBackend; + + beforeEach(ngModule('order')); + + beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_, $rootScope) => { + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + $scope.model = crudModel; + $scope.search = {}; + $state = _$state_; + $state.params.category = '{"id": 1, "value": "My Category"}'; + $state.params.type = '{"id": 1, "value": "My type"}'; + $state.current.name = 'my.current.state'; + controller = $componentController('vnCatalogFilter', {$element: null, $scope, $state}); + controller.catalog = { + $scope: $scope, + getOrderBy: () => { + return {field: 'relevancy DESC, name', way: 'DESC'}; + } + }; + })); + + describe('order() setter', () => { + it(`should call scope $applyAsync() method and apply filters from state params`, () => { + $httpBackend.expect('GET', `Orders/4/getItemTypeAvailable?itemCategoryId=1`).respond(); + controller.order = {id: 4}; + + $scope.$apply(); + + expect(controller.category).toEqual({id: 1, value: 'My Category'}); + expect(controller.type).toEqual({id: 1, value: 'My type'}); + }); + }); + + describe('category() setter', () => { + it(`should set category property to null, call updateStateParams() method and not call applyFilters()`, () => { + spyOn(controller, 'updateStateParams'); + controller.category = null; + + expect(controller.updateStateParams).toHaveBeenCalledWith(); + }); + + it(`should set category property and then call updateStateParams() and applyFilters() methods`, () => { + spyOn(controller, 'updateStateParams'); + controller._order = {id: 4}; + controller.category = {id: 2, value: 'My category'}; + + expect(controller.updateStateParams).toHaveBeenCalledWith(); + }); + }); + + describe('type() setter', () => { + it(`should set type property to null, call updateStateParams() method and not call applyFilters()`, () => { + spyOn(controller, 'updateStateParams'); + spyOn(controller, 'applyFilters'); + controller.type = null; + + expect(controller.updateStateParams).toHaveBeenCalledWith(); + expect(controller.applyFilters).not.toHaveBeenCalledWith(); + }); + + it(`should set category property and then call updateStateParams() and applyFilters() methods`, () => { + spyOn(controller, 'updateStateParams'); + spyOn(controller, 'applyFilters'); + controller.type = {id: 2, value: 'My type'}; + + expect(controller.updateStateParams).toHaveBeenCalledWith(); + expect(controller.applyFilters).toHaveBeenCalledWith(); + }); + }); + + describe('onSearchByTag()', () => { + it(`should not add a new tag if the event key code doesn't equals to 'Enter'`, () => { + spyOn(controller, 'applyFilters'); + controller.order = {id: 4}; + controller.value = 'Color'; + controller.onSearchByTag({key: 'Tab'}); + + expect(controller.applyFilters).not.toHaveBeenCalledWith(); + }); + + it(`should add a new tag if the event key code equals to 'Enter' an then call applyFilters()`, () => { + spyOn(controller, 'applyFilters'); + controller.order = {id: 4}; + controller.value = 'Color'; + + controller.onSearchByTag({key: 'Enter'}); + + expect(controller.applyFilters).toHaveBeenCalledWith(); + }); + }); + + describe('onSearchById()', () => { + it(`should not filter by id if the event key code doesn't equals to 'Enter'`, () => { + spyOn(controller, 'applyFilters'); + controller.itemFk = 1; + controller.onSearchById({key: 'Tab'}); + + expect(controller.applyFilters).not.toHaveBeenCalledWith(); + }); + + it(`should filter by id if the event key code equals to 'Enter' an then call applyFilters()`, () => { + spyOn(controller, 'applyFilters'); + controller.itemFk = 1; + + controller.onSearchById({key: 'Enter'}); + + expect(controller.applyFilters).toHaveBeenCalledWith(); + }); + }); + + describe('applyFilters()', () => { + it(`should call model applyFilter() method with a new filter`, () => { + let model = controller.catalog.$scope.model; + spyOn(model, 'applyFilter'); + controller._category = {id: 1, value: 'My Category'}; + controller._type = {id: 1, value: 'My type'}; + controller._order = {id: 4}; + + controller.applyFilters(); + + expect(model.applyFilter).toHaveBeenCalledWith( + {where: {categoryFk: 1, typeFk: 1}}, + {orderFk: 4, orderBy: controller.catalog.getOrderBy(), tags: []}); + }); + }); + + describe('remove()', () => { + it(`should remove a tag from tags property`, () => { + spyOn(controller, 'applyFilters'); + controller.tags = [{tagFk: 1, value: 'Blue'}, {tagFk: 2, value: '70'}]; + controller.remove(0); + + expect(controller.tags.length).toEqual(1); + expect(controller.tags[0].tagFk).toEqual(2); + expect(controller.applyFilters).toHaveBeenCalledWith(); + }); + + it(`should remove a tag from tags property and call applyFilters() if there's no more tags`, () => { + spyOn(controller, 'applyFilters'); + controller._category = {id: 1, value: 'My Category'}; + controller._type = {id: 1, value: 'My type'}; + controller.tags = [{tagFk: 1, value: 'Blue'}]; + controller.remove(0); + + expect(controller.tags.length).toEqual(0); + expect(controller.applyFilters).toHaveBeenCalledWith(); + }); + }); + + describe('updateStateParams()', () => { + it(`should call state go() method passing category and type state params`, () => { + spyOn(controller.$state, 'go'); + controller._category = {id: 1, value: 'My Category'}; + controller._type = {id: 1, value: 'My type'}; + let result = {category: '{"id":1,"value":"My Category"}', type: '{"id":1,"value":"My type"}'}; + controller.updateStateParams(); + + expect(controller.$state.go).toHaveBeenCalledWith('my.current.state', result); + }); + }); + }); +}); + diff --git a/modules/order/front/filter/style.scss b/modules/order/front/filter/style.scss new file mode 100644 index 000000000..0cac5765f --- /dev/null +++ b/modules/order/front/filter/style.scss @@ -0,0 +1,51 @@ +@import "variables"; +@import "variables"; + +vn-catalog-filter > div { + & > .input { + padding-left: $spacing-md; + padding-right: $spacing-md; + border-color: $color-spacer; + border-bottom: $border-thin; + } + .item-category { + padding: $spacing-sm; + justify-content: flex-start; + align-items: flex-start; + flex-wrap: wrap; + + & > vn-one { + padding: $spacing-sm; + min-width: 33.33%; + text-align: center; + box-sizing: border-box; + + & > vn-icon { + padding: $spacing-sm; + background-color: $color-font-secondary; + border-radius: 50%; + cursor: pointer; + + &.active { + background-color: $color-main; + color: #FFF + } + & > i:before { + font-size: 32pt; + width: 1em; + height: 1em; + } + } + } + } + .chips { + display: flex; + flex-wrap: wrap; + padding: $spacing-md; + overflow: hidden; + max-width: 100%; + } + vn-autocomplete[vn-id="type"] .list { + max-height: 20em + } +} \ No newline at end of file diff --git a/modules/order/front/index.js b/modules/order/front/index.js new file mode 100644 index 000000000..0d8d0d686 --- /dev/null +++ b/modules/order/front/index.js @@ -0,0 +1,17 @@ +export * from './module'; + +import './main'; +import './index/'; +import './card'; +import './descriptor'; +import './search-panel'; +import './catalog-search-panel'; +import './filter'; +import './summary'; +import './catalog'; +import './line'; +import './prices-popover'; +import './volume'; +import './create'; +import './create/card'; +import './basic-data'; diff --git a/modules/order/front/index/index.html b/modules/order/front/index/index.html new file mode 100644 index 000000000..20dd4a231 --- /dev/null +++ b/modules/order/front/index/index.html @@ -0,0 +1,85 @@ + + + + + + + + + + Id + Client + Sales person + Confirmed + Created from + Created + Landed + Company + Total + + + + + {{::order.id}} + + + {{::order.clientName}} + + + + + {{::order.workerNickname | dashIfEmpty}} + + + + + + + {{::order.sourceApp}} + {{::order.created | date: 'dd/MM/yyyy HH:mm'}} + {{::order.landed | date:'dd/MM/yyyy'}} + {{::order.companyCode}} + {{::order.total | currency: 'EUR': 2 | dashIfEmpty}} + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/order/front/index/index.js b/modules/order/front/index/index.js new file mode 100644 index 000000000..8cf289796 --- /dev/null +++ b/modules/order/front/index/index.js @@ -0,0 +1,51 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($scope, $state, $stateParams) { + this.$stateParams = $stateParams; + this.$state = $state; + this.$ = $scope; + this.ticketSelected = null; + } + + onSearch(params) { + if (params) + this.$.model.applyFilter(null, params); + else + this.$.model.clear(); + } + + showClientDescriptor(event, clientFk) { + this.$.clientDescriptor.clientFk = clientFk; + this.$.clientDescriptor.parent = event.target; + this.$.clientDescriptor.show(); + event.preventDefault(); + event.stopImmediatePropagation(); + } + + showWorkerDescriptor(event, workerFk) { + event.preventDefault(); + event.stopImmediatePropagation(); + this.selectedWorker = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } + + onDescriptorLoad() { + this.$.popover.relocate(); + } + + preview(event, order) { + event.preventDefault(); + event.stopImmediatePropagation(); + this.selectedOrder = order; + this.$.summary.show(); + } +} + +Controller.$inject = ['$scope', '$state', '$stateParams']; + +ngModule.component('vnOrderIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/order/front/line/index.html b/modules/order/front/line/index.html new file mode 100644 index 000000000..72d019fe9 --- /dev/null +++ b/modules/order/front/line/index.html @@ -0,0 +1,90 @@ + + +
    + Subtotal + {{$ctrl.subtotal | currency: 'EUR':2}} +
    +
    + VAT + {{$ctrl.VAT | currency: 'EUR':2}} +
    +
    + Total + {{$ctrl.order.total | currency: 'EUR':2}} +
    +
    + + + + + + Id + Description + Warehouse + Shipped + Quantity + Price + Amount + + + + + + + + + + + {{::row.itemFk | zeroFill:6}} + + + + + + + {{::row.warehouse.name}} + {{::row.shipped | date: 'dd/MM/yyyy'}} + {{::row.quantity}} + + {{::row.price | currency: 'EUR':2}} + + + {{::row.price * row.quantity | currency: 'EUR':2}} + + + + + + + + + +
    + + + + + + \ No newline at end of file diff --git a/modules/order/front/line/index.js b/modules/order/front/line/index.js new file mode 100644 index 000000000..149251c87 --- /dev/null +++ b/modules/order/front/line/index.js @@ -0,0 +1,78 @@ +import ngModule from '../module'; +import Section from 'salix/components/section'; +import './style.scss'; + +class Controller extends Section { + $onInit() { + this.getRows(); + } + + set order(value) { + this._order = value; + this.getVAT(); + } + + get order() { + return this._order; + } + + get subtotal() { + return this.order ? this.order.total - this.VAT : 0; + } + + getRows() { + let filter = { + where: {orderFk: this.$params.id}, + include: [ + {relation: 'item'}, + {relation: 'warehouse'} + ] + }; + this.$http.get(`OrderRows`, {filter}) + .then(res => this.rows = res.data); + } + + getVAT() { + this.$http.get(`Orders/${this.$params.id}/getVAT`) + .then(res => this.VAT = res.data); + } + + deleteRow(index) { + let [row] = this.rows.splice(index, 1); + let params = { + rows: [row.id], + actualOrderId: this.$params.id + }; + return this.$http.post(`OrderRows/removes`, params).then(() => { + this.card.reload(); + this.vnApp.showSuccess(this.$t('Data saved!')); + }); + } + + showDescriptor(event, itemFk) { + let descriptor = this.$.descriptor; + descriptor.itemFk = itemFk; + descriptor.parent = event.target; + descriptor.show(); + } + + save() { + this.$http.post(`Orders/${this.$params.id}/confirm`).then(() => { + this.vnApp.showSuccess(this.$t('Order confirmed')); + this.$state.go(`ticket.index`, { + q: JSON.stringify({clientFk: this.order.clientFk}) + }); + }); + } +} + +ngModule.component('vnOrderLine', { + template: require('./index.html'), + controller: Controller, + bindings: { + order: '<' + }, + require: { + card: '^vnOrderCard' + } +}); diff --git a/modules/order/front/line/index.spec.js b/modules/order/front/line/index.spec.js new file mode 100644 index 000000000..543ffeedc --- /dev/null +++ b/modules/order/front/line/index.spec.js @@ -0,0 +1,66 @@ +import './index.js'; + +describe('Order', () => { + describe('Component vnOrderLine', () => { + let $state; + let controller; + let $httpBackend; + + let rows = [ + { + quantity: 4, + price: 10.5 + }, { + quantity: 3, + price: 2.4 + } + ]; + + beforeEach(ngModule('order')); + + beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_) => { + $state = _$state_; + $httpBackend = _$httpBackend_; + + $state.params.id = 1; + $httpBackend.whenRoute('GET', `OrderRows`).respond(rows); + $httpBackend.whenRoute('GET', `Orders/:id/getVAT`).respond(200, 10.5); + + let $element = angular.element('
    '); + controller = $componentController('vnOrderLine', {$element}); + })); + + describe('getRows()', () => { + it('should make a query to get the rows of a given order', () => { + controller.getRows(); + $httpBackend.flush(); + + expect(controller.rows).toBeDefined(); + }); + }); + + describe('getVAT()', () => { + it('should make a query to get the VAT of a given order', () => { + controller.getVAT(); + $httpBackend.flush(); + + expect(controller.VAT).toBeDefined(); + }); + }); + + describe('deleteRow()', () => { + it('should remove a row from rows and add save the data if the response is accept', () => { + controller.getRows(); + $httpBackend.flush(); + + controller.card = {reload: jasmine.createSpy('reload')}; + $httpBackend.expectPOST(`OrderRows/removes`).respond(); + controller.deleteRow(0); + $httpBackend.flush(); + + expect(controller.rows.length).toBe(1); + expect(controller.card.reload).toHaveBeenCalledWith(); + }); + }); + }); +}); diff --git a/modules/order/front/line/locale/es.yml b/modules/order/front/line/locale/es.yml new file mode 100644 index 000000000..d1368d369 --- /dev/null +++ b/modules/order/front/line/locale/es.yml @@ -0,0 +1,3 @@ +Delete row: Eliminar linea +Order confirmed: Pedido confirmado +Are you sure you want to delete this row?: ¿Estas seguro de que quieres eliminar esta línea? \ No newline at end of file diff --git a/modules/order/front/line/style.scss b/modules/order/front/line/style.scss new file mode 100644 index 000000000..4da941a2c --- /dev/null +++ b/modules/order/front/line/style.scss @@ -0,0 +1,18 @@ +@import "./variables"; + +vn-order-line { + vn-table { + img { + border-radius: 50%; + width: 50px; + height: 50px; + } + } + .header { + text-align: right; + + & > div { + margin-bottom: $spacing-xs; + } + } +} \ No newline at end of file diff --git a/modules/order/front/locale/es.yml b/modules/order/front/locale/es.yml new file mode 100644 index 000000000..0ada37bfd --- /dev/null +++ b/modules/order/front/locale/es.yml @@ -0,0 +1,22 @@ +Address: Consignatario +Catalog: Catálogo +from: desde +results: resultados +More than: Más de +Plant: Planta +Flower: Flor +Handmade: Confección +Fruit: Fruta +Green: Verde +Lines: Lineas +Accessories: Complemento +Category: Reino +Search tag: Buscar etiqueta +Item id: Id de artículo +Order by: Ordenar por +Order: Orden +Price: Precio +Ascendant: Ascendente +Descendant: Descendente +Created from: Creado desde +Search orders by id: Buscar en la cesta por identificador \ No newline at end of file diff --git a/modules/order/front/main/index.html b/modules/order/front/main/index.html new file mode 100644 index 000000000..09d498599 --- /dev/null +++ b/modules/order/front/main/index.html @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/modules/order/front/main/index.js b/modules/order/front/main/index.js new file mode 100644 index 000000000..7513d2144 --- /dev/null +++ b/modules/order/front/main/index.js @@ -0,0 +1,9 @@ +import ngModule from '../module'; +import ModuleMain from 'salix/components/module-main'; + +export default class Order extends ModuleMain {} + +ngModule.vnComponent('vnOrder', { + controller: Order, + template: require('./index.html') +}); diff --git a/modules/order/front/module.js b/modules/order/front/module.js new file mode 100644 index 000000000..9956e2703 --- /dev/null +++ b/modules/order/front/module.js @@ -0,0 +1,3 @@ +import {ng} from 'core/vendor'; + +export default ng.module('order', ['vnCore']); diff --git a/modules/order/front/prices-popover/index.html b/modules/order/front/prices-popover/index.html new file mode 100644 index 000000000..2a6f978fb --- /dev/null +++ b/modules/order/front/prices-popover/index.html @@ -0,0 +1,79 @@ + +
    +
    + + + + + +
    +
    +
    +
    {{$ctrl.item.name}}
    + + + + + + +
    + + +
    +
    + + + + + + {{::price.warehouse}} + + + +
    + + {{::price.grouping}} + + x {{::price.price | currency: 'EUR': 2}} +
    +
    + {{price.priceKg | currency: 'EUR'}}/Kg +
    +
    + + + + +
    +
    +
    + +
    +
    +
    diff --git a/modules/order/front/prices-popover/index.js b/modules/order/front/prices-popover/index.js new file mode 100644 index 000000000..40590b8bb --- /dev/null +++ b/modules/order/front/prices-popover/index.js @@ -0,0 +1,156 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + constructor($element, $) { + super($element, $); + this.totalBasquet = 0; + } + + set prices(value) { + this._prices = value; + if (value && value[0].grouping) + this.calculateTotal(); + } + + get prices() { + return this._prices; + } + + getTags() { + let filter = { + where: {itemFk: this.item.id, + priority: {gte: 4}}, + order: 'priority ASC', + include: {relation: 'tag'} + }; + this.quicklinks = { + btnOne: { + icon: 'icon-transaction', + state: `item.card.diary({id: ${this.item.id}})`, + tooltip: 'Diary' + } + }; + this.$http.get(`ItemTags?filter=${JSON.stringify(filter)}`).then(response => { + this.tags = response.data; + this.$.$applyAsync(() => { + this.$.popover.relocate(); + }); + }); + } + + show(event, item) { + this.item = JSON.parse(JSON.stringify(item)); + this.prices = this.item.prices; + this.getTags(); + this.$.popover.parent = event.target; + this.$.popover.show(); + this.$.popover.relocate(); + } + + clear() { + this.item = {}; + this.tags = {}; + this._prices = {}; + this.total = 0; + } + + calculateMax() { + this.max = this.item.available - this.total; + } + + calculateTotal() { + this.total = 0; + + this.prices.forEach(price => { + if (!price.quantity) price.quantity = 0; + this.total += price.quantity; + }); + this.calculateMax(); + } + + addQuantity(price) { + if (this.total + price.grouping <= this.max) + price.quantity += price.grouping; + + this.validate(); + } + + validate() { + /* + this.$timeout(() => { + this.calculateTotal(); + let inputs = this.$element[0].querySelectorAll('vn-input-number[name="quantity"] div.infix:not(.validated)'); + + inputs.forEach(input => { + if (this.total > this.item.available) + input.classList.add('invalid'); + else + input.classList.remove('invalid'); + }); + let wrongInputs = this.$element[0].querySelectorAll('vn-input-number[name="quantity"] div.infix.invalid'); + + if (wrongInputs.length > 0) + this.$element[0].querySelector('vn-vertical.prices').classList.add('invalid'); + else + this.$element[0].querySelector('vn-vertical.prices').classList.remove('invalid'); + }); + */ + } + + getFilledLines() { + let filledLines = []; + let match; + this.prices.forEach(price => { + if (price.quantity && price.quantity > 0) { + match = filledLines.find(element => { + return element.warehouseFk == price.warehouseFk; + }); + + if (!match) { + filledLines.push(Object.assign({}, price)); + return; + } + match.quantity += price.quantity; + } + }); + return filledLines; + } + + submit() { + this.calculateTotal(); + let filledLines = this.getFilledLines(); + + if (filledLines.length <= 0) { + this.vnApp.showError(this.$translate.instant('First you must add some quantity')); + return; + } + + setTimeout(() => { + let params = { + orderFk: this.order.id, + items: filledLines + }; + + this.$http.post(`OrderRows/addToOrder`, params).then(res => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$.popover.hide(); + + if (this.card) + this.card.reload(); + }); + }); + } +} + +ngModule.component('vnOrderPricesPopover', { + template: require('./index.html'), + controller: Controller, + bindings: { + order: '<' + }, + require: { + card: '?^vnOrderCard' + } +}); diff --git a/modules/order/front/prices-popover/locale/es.yml b/modules/order/front/prices-popover/locale/es.yml new file mode 100644 index 000000000..b1a26e0f3 --- /dev/null +++ b/modules/order/front/prices-popover/locale/es.yml @@ -0,0 +1,4 @@ +Last entries: Últimas entradas +Qty.: Cant. +Wrong quantity: Cantidad errónea +First you must add some quantity: Primero debes agregar alguna cantidad \ No newline at end of file diff --git a/modules/order/front/prices-popover/style.scss b/modules/order/front/prices-popover/style.scss new file mode 100644 index 000000000..150c2296a --- /dev/null +++ b/modules/order/front/prices-popover/style.scss @@ -0,0 +1,44 @@ +@import "variables"; + +.vn-order-prices-popover { + display: block; + + img[ng-src] { + height: 100%; + width: 100%; + } + vn-vertical.data { + padding-right: 16px; + border-right: 1px solid $color-main; + } + .prices { + vn-table { + .warehouse { + width: 3em; + max-width: 3em; + } + .price-kg { + color: $color-font-secondary; + font-size: .8em + } + .vn-input-number { + width: 3.5em; + } + } + .footer { + text-align: center; + + .error { + display: none; + } + &.invalid { + .error { + display: block; + padding-top: 10px; + color: $color-alert; + text-align: center; + } + } + } + } +} \ No newline at end of file diff --git a/modules/order/front/routes.json b/modules/order/front/routes.json new file mode 100644 index 000000000..86eda488f --- /dev/null +++ b/modules/order/front/routes.json @@ -0,0 +1,82 @@ +{ + "module": "order", + "name": "Orders", + "icon": "icon-basket", + "validations": true, + "dependencies": ["worker", "item", "ticket"], + "menus": { + "main": [ + {"state": "order.index", "icon": "icon-basket"} + ], + "card": [ + {"state": "order.card.basicData", "icon": "settings"}, + {"state": "order.card.catalog", "icon": "icon-basket"}, + {"state": "order.card.volume", "icon": "icon-volume"}, + {"state": "order.card.line", "icon": "icon-lines"} + ] + }, + "routes": [ + { + "url": "/order", + "state": "order", + "abstract": true, + "component": "vn-order", + "description": "Orders" + }, { + "url": "/index?q", + "state": "order.index", + "component": "vn-order-index", + "description": "Orders" + }, { + "url": "/:id", + "state": "order.card", + "abstract": true, + "component": "vn-order-card" + }, { + "url": "/summary", + "state": "order.card.summary", + "component": "vn-order-summary", + "description": "Summary", + "params": { + "order": "$ctrl.order" + } + }, { + "url": "/catalog?category&type", + "state": "order.card.catalog", + "component": "vn-order-catalog", + "description": "Catalog", + "params": { + "order": "$ctrl.order" + } + }, { + "url": "/volume", + "state": "order.card.volume", + "component": "vn-order-volume", + "description": "Volume", + "params": { + "order": "$ctrl.order" + } + }, { + "url": "/line", + "state": "order.card.line", + "component": "vn-order-line", + "description": "Lines", + "params": { + "order": "$ctrl.order" + } + }, { + "url": "/create?clientFk", + "state": "order.create", + "component": "vn-order-create", + "description": "New order" + }, { + "url": "/basic-data", + "state": "order.card.basicData", + "component": "vn-order-basic-data", + "description": "Basic data", + "params": { + "order": "$ctrl.order" + } + } + ] +} \ No newline at end of file diff --git a/modules/order/front/search-panel/index.html b/modules/order/front/search-panel/index.html new file mode 100644 index 000000000..cb65e83c0 --- /dev/null +++ b/modules/order/front/search-panel/index.html @@ -0,0 +1,89 @@ +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    \ No newline at end of file diff --git a/modules/order/front/search-panel/index.js b/modules/order/front/search-panel/index.js new file mode 100644 index 000000000..1ab4c15cf --- /dev/null +++ b/modules/order/front/search-panel/index.js @@ -0,0 +1,7 @@ +import ngModule from '../module'; +import SearchPanel from 'core/components/searchbar/search-panel'; + +ngModule.component('vnOrderSearchPanel', { + template: require('./index.html'), + controller: SearchPanel +}); diff --git a/modules/order/front/search-panel/locale/es.yml b/modules/order/front/search-panel/locale/es.yml new file mode 100644 index 000000000..1e2d139f6 --- /dev/null +++ b/modules/order/front/search-panel/locale/es.yml @@ -0,0 +1,9 @@ +Order id: Id pedido +Client id: Id cliente +From landed: Desde f. entrega +To landed: Hasta f. entrega +To: Hasta +Agency: Agencia +Application: Aplicación +SalesPerson: Comercial +Order confirmed: Pedido confirmado \ No newline at end of file diff --git a/modules/order/front/summary/index.html b/modules/order/front/summary/index.html new file mode 100644 index 000000000..c7ee5b4b6 --- /dev/null +++ b/modules/order/front/summary/index.html @@ -0,0 +1,90 @@ + +
    {{$ctrl.summary.id}} - {{$ctrl.summary.client.name}} - {{$ctrl.summary.client.salesPerson.id}}
    + + + + + + + + + + + + + + + + + + + + + + + + + +

    Subtotal {{$ctrl.summary.subTotal | currency: 'EUR':2}}

    +

    VAT {{$ctrl.summary.VAT | currency: 'EUR':2}}

    +

    Total {{$ctrl.summary.total | currency: 'EUR':2}}

    +
    + + + + + + Item + Description + Quantity + Price + Amount + + + + + + + + + + + + {{::row.itemFk | zeroFill:6}} + + + + + + + {{::row.quantity}} + {{::row.price | currency: 'EUR':2}} + {{::row.quantity * row.price | currency: 'EUR':2}} + + + + +
    +
    + + diff --git a/modules/order/front/summary/index.js b/modules/order/front/summary/index.js new file mode 100644 index 000000000..42b71d90e --- /dev/null +++ b/modules/order/front/summary/index.js @@ -0,0 +1,52 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $http, $state) { + this.$scope = $scope; + this.$http = $http; + this.$state = $state; + this.order = {}; + } + + setSummary() { + this.$http.get(`Orders/${this.order.id}/summary`).then(res => { + if (res && res.data) + this.summary = res.data; + }); + } + + get formattedAddress() { + if (!this.summary) return; + + let address = this.summary.address; + let province = address.province ? `(${address.province.name})` : ''; + + return `${address.street} - ${address.city} ${province}`; + } + + $onChanges() { + if (this.order && this.order.id) + this.setSummary(); + } + + showDescriptor(event, itemFk) { + this.$scope.descriptor.itemFk = itemFk; + this.$scope.descriptor.parent = event.target; + this.$scope.descriptor.show(); + } + + onDescriptorLoad() { + this.$scope.popover.relocate(); + } +} + +Controller.$inject = ['$scope', '$http', '$state']; + +ngModule.component('vnOrderSummary', { + template: require('./index.html'), + controller: Controller, + bindings: { + order: '<' + } +}); diff --git a/modules/order/front/summary/index.spec.js b/modules/order/front/summary/index.spec.js new file mode 100644 index 000000000..ba412cc90 --- /dev/null +++ b/modules/order/front/summary/index.spec.js @@ -0,0 +1,45 @@ +import './index'; + +describe('Order', () => { + describe('Component vnOrderSummary', () => { + let controller; + let $httpBackend; + + beforeEach(ngModule('order')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + controller = $componentController('vnOrderSummary'); + controller.order = {id: 1}; + })); + + describe('getSummary()', () => { + it('should perform a GET query and define summary property', () => { + let res = {id: 1, nickname: 'Batman'}; + $httpBackend.when('GET', `Orders/1/summary`).respond(200, res); + $httpBackend.expect('GET', `Orders/1/summary`); + controller.setSummary(); + $httpBackend.flush(); + + expect(controller.summary).toBeDefined(); + expect(controller.summary.nickname).toEqual('Batman'); + }); + }); + + describe('formattedAddress()', () => { + it('should return a full fromatted address with city and province', () => { + controller.summary = { + address: { + province: { + name: 'Gotham' + }, + street: '1007 Mountain Drive', + city: 'Gotham' + } + }; + + expect(controller.formattedAddress).toEqual('1007 Mountain Drive - Gotham (Gotham)'); + }); + }); + }); +}); diff --git a/modules/order/front/summary/style.scss b/modules/order/front/summary/style.scss new file mode 100644 index 000000000..c225b4b49 --- /dev/null +++ b/modules/order/front/summary/style.scss @@ -0,0 +1,20 @@ +@import "./variables"; + +vn-order-summary .summary{ + max-width: $width-lg; + + & > div > vn-horizontal > vn-one { + min-width: 10em !important; + + &.taxes { + border: $border-thin-light; + text-align: right; + padding: .5em !important; + + & > p { + font-size: 1.2em; + margin: .2em; + } + } + } +} \ No newline at end of file diff --git a/modules/order/front/volume/index.html b/modules/order/front/volume/index.html new file mode 100644 index 000000000..9dc1b811f --- /dev/null +++ b/modules/order/front/volume/index.html @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + Item + Description + Quantity + m³ per quantity + + + + + + + {{::row.itemFk}} + + + + + + + {{::row.quantity}} + {{::row.volume | number:3}} + + + + + + + + diff --git a/modules/order/front/volume/index.js b/modules/order/front/volume/index.js new file mode 100644 index 000000000..ef5232366 --- /dev/null +++ b/modules/order/front/volume/index.js @@ -0,0 +1,50 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $http, $stateParams) { + this.$scope = $scope; + this.$http = $http; + this.$stateParams = $stateParams; + this.filter = { + include: [{ + relation: 'item' + }] + }; + this.order = {}; + this.ticketVolumes = []; + } + + onDataChange() { + this.$http.get(`Orders/${this.$stateParams.id}/getVolumes`) + .then(response => { + if (response.data) + this.$scope.model.data.forEach(order => { + response.data.volumes.forEach(volume => { + if (order.itemFk === volume.itemFk) + order.volume = volume.volume; + }); + }); + }); + } + + showDescriptor(event, itemFk) { + this.$scope.descriptor.itemFk = itemFk; + this.$scope.descriptor.parent = event.target; + this.$scope.descriptor.show(); + } + + onDescriptorLoad() { + this.$scope.popover.relocate(); + } +} + +Controller.$inject = ['$scope', '$http', '$stateParams']; + +ngModule.component('vnOrderVolume', { + template: require('./index.html'), + controller: Controller, + bindings: { + order: '<' + } +}); diff --git a/modules/order/front/volume/index.spec.js b/modules/order/front/volume/index.spec.js new file mode 100644 index 000000000..ba597c6e7 --- /dev/null +++ b/modules/order/front/volume/index.spec.js @@ -0,0 +1,60 @@ +import './index'; + +describe('Order', () => { + describe('Component vnOrderVolume', () => { + let controller; + let $httpBackend; + let $state; + let $scope; + + beforeEach(ngModule('order')); + + beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_, $rootScope) => { + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + $scope.model = {data: [{itemFk: 1}, {itemFk: 2}], accept: () => { + return { + then: () => {} + }; + }}; + $scope.descriptor = {show: () => {}}; + $scope.popover = {relocate: () => {}}; + $state = _$state_; + $state.params.id = 1; + controller = $componentController('vnOrderVolume', {$scope}, {$httpBackend}, {$state}); + })); + + it('should join the sale volumes to its respective sale', () => { + let response = {volumes: [{itemFk: 1, volume: 0.008}, {itemFk: 2, volume: 0.003}]}; + $httpBackend.whenGET(`Orders/1/getVolumes`).respond(response); + $httpBackend.expectGET(`Orders/1/getVolumes`); + controller.onDataChange(); + $httpBackend.flush(); + + expect(controller.$scope.model.data[0].volume).toBe(0.008); + expect(controller.$scope.model.data[1].volume).toBe(0.003); + }); + + describe('showDescriptor()', () => { + it('should set $scope.descriptor.itemFk, $scope.descriptor.parent and call $scope.descriptor.show()', () => { + let event = {target: 1}; + let itemFk = 1; + spyOn(controller.$scope.descriptor, 'show'); + controller.showDescriptor(event, itemFk); + + expect(controller.$scope.descriptor.itemFk).toBe(1); + expect(controller.$scope.descriptor.parent).toBe(1); + expect(controller.$scope.descriptor.show).toHaveBeenCalledWith(); + }); + }); + + describe('onDescriptorLoad()', () => { + it('should call $scope.popover.relocate()', () => { + spyOn(controller.$scope.popover, 'relocate'); + controller.onDescriptorLoad(); + + expect(controller.$scope.popover.relocate).toHaveBeenCalledWith(); + }); + }); + }); +}); diff --git a/modules/order/front/volume/style.scss b/modules/order/front/volume/style.scss new file mode 100644 index 000000000..da13eca0d --- /dev/null +++ b/modules/order/front/volume/style.scss @@ -0,0 +1,12 @@ + +@import "./variables"; + +vn-order-volume { + .header { + text-align: right; + + & > div { + margin-bottom: $spacing-xs; + } + } +} diff --git a/modules/route/back/methods/route/filter.js b/modules/route/back/methods/route/filter.js new file mode 100644 index 000000000..eeeef1dac --- /dev/null +++ b/modules/route/back/methods/route/filter.js @@ -0,0 +1,140 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const buildFilter = require('vn-loopback/util/filter').buildFilter; +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethodCtx('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accessType: 'READ', + accepts: [ + { + arg: 'filter', + type: 'Object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + http: {source: 'query'} + }, { + arg: 'search', + type: 'String', + description: 'Searchs the route by id', + http: {source: 'query'} + }, { + arg: 'workerFk', + type: 'Integer', + description: 'The worker id', + http: {source: 'query'} + }, { + arg: 'agencyModeFk', + type: 'Integer', + description: 'The agencyMode id', + http: {source: 'query'} + }, { + arg: 'to', + type: 'Date', + description: 'The to date filter', + http: {source: 'query'} + }, { + arg: 'from', + type: 'Date', + description: 'The to date filter', + http: {source: 'query'} + }, { + arg: 'vehicleFk', + type: 'Integer', + description: 'The vehicle id', + http: {source: 'query'} + }, { + arg: 'm3', + type: 'Number', + description: 'The m3 filter', + http: {source: 'query'} + }, { + arg: 'warehouseFk', + type: 'Number', + description: 'The warehouse filter', + http: {source: 'query'} + }, { + arg: 'description', + type: 'String', + description: 'The description filter', + http: {source: 'query'} + } + ], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/filter`, + verb: 'GET' + } + }); + + Self.filter = async(ctx, filter) => { + let conn = Self.dataSource.connector; + + let where = buildFilter(ctx.args, (param, value) => { + switch (param) { + case 'search': + return {'r.id': value}; + case 'from': + return {'r.created': {gte: value}}; + case 'to': + return {'r.created': {lte: value}}; + case 'm3': + return {'r.m3': value}; + case 'description': + return {'r.description': {like: `%${value}%`}}; + case 'warehouseFk': + param = `v.${param}`; + return {[param]: value}; + case 'workerFk': + case 'vehicleFk': + case 'agencyModeFk': + param = `r.${param}`; + return {[param]: value}; + } + }); + + filter = mergeFilters(ctx.args.filter, {where}); + + let stmts = []; + let stmt; + + stmt = new ParameterizedSQL( + `SELECT + r.id, + r.workerFk, + r.created, + r.vehicleFk, + r.agencyModeFk, + r.time, + r.isOk, + r.kmStart, + r.kmEnd, + r.started, + r.finished, + r.gestdocFk, + r.cost, + r.m3, + r.description, + am.name agencyName, + u.nickname AS workerNickname, + v.numberPlate AS vehiclePlateNumber + FROM route r + LEFT JOIN agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vehicle v ON v.id = r.vehicleFk + LEFT JOIN worker w ON w.id = r.workerFk + LEFT JOIN account.user u ON u.id = w.userFk` + ); + + + stmt.merge(conn.makeSuffix(filter)); + let itemsIndex = stmts.push(stmt) - 1; + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + return itemsIndex === 0 ? result : result[itemsIndex]; + }; +}; + diff --git a/modules/route/back/methods/route/getDeliveryPoint.js b/modules/route/back/methods/route/getDeliveryPoint.js new file mode 100644 index 000000000..59b22904f --- /dev/null +++ b/modules/route/back/methods/route/getDeliveryPoint.js @@ -0,0 +1,29 @@ +module.exports = Self => { + Self.remoteMethod('getDeliveryPoint', { + description: 'get the deliveryPoint address ', + accessType: 'WRITE', + accepts: { + arg: 'vehicleId', + type: 'number', + required: true, + description: 'vehicle id asigned in the route', + http: {source: 'path'} + }, + returns: { + type: 'String', + root: true + }, + http: { + path: `/:vehicleId/getDeliveryPoint` + } + }); + + Self.getDeliveryPoint = async vehicleId => { + let vehicle = await Self.app.models.Vehicle.findById(vehicleId); + + let deliveryPoint = await Self.app.models.DeliveryPoint.findById(vehicle.deliveryPointFk); + + + return deliveryPoint.ubication; + }; +}; diff --git a/modules/route/back/methods/route/getTickets.js b/modules/route/back/methods/route/getTickets.js new file mode 100644 index 000000000..a0014a60d --- /dev/null +++ b/modules/route/back/methods/route/getTickets.js @@ -0,0 +1,101 @@ +module.exports = Self => { + Self.remoteMethod('getTickets', { + description: 'Return the tickets information displayed on the route module', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The route id', + http: {source: 'path'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/getTickets`, + verb: 'GET' + } + }); + + Self.getTickets = async id => { + let filter = { + where: {id: id}, + include: [ + {relation: 'ticket', + scope: { + fields: ['id', 'packages', 'warehouseFk', 'nickname', 'clientFk', 'priority', 'addressFk'], + order: 'priority', + include: [ + { + relation: 'state', + scope: { + fields: ['id', 'stateFk'], + include: [{relation: 'state'}] + } + }, + { + relation: 'warehouse', + scope: { + fields: ['id', 'name'] + } + }, + { + relation: 'notes', + scope: { + where: {observationTypeFk: 3} + } + }, + { + relation: 'address', + scope: { + fields: ['id', 'street', 'postalCode', 'city'], + } + }, + + ] + } + }, { + relation: 'agencyMode', + scope: { + fields: ['id', 'name'] + } + }, { + relation: 'worker', + scope: { + fields: ['id', 'userFk'], + include: [ + { + relation: 'user', + scope: { + fields: ['id', 'nickname'] + } + } + ] + } + }, { + relation: 'vehicle', + scope: { + fields: ['id', 'm3', 'numberPlate'] + } + } + ], + }; + + route = await Self.app.models.Route.findOne(filter); + + for (let i = 0; i < route.ticket().length; i++) { + let ticket = route.ticket()[i]; + let query = ` + SELECT vn.ticketTotalVolume(?) AS m3`; + + let options = [ticket.id]; + let [volume] = await Self.rawSql(query, options); + + ticket.volume = volume.m3; + } + + return route.ticket(); + }; +}; diff --git a/modules/route/back/methods/route/guessPriority.js b/modules/route/back/methods/route/guessPriority.js new file mode 100644 index 000000000..bb5b34ca3 --- /dev/null +++ b/modules/route/back/methods/route/guessPriority.js @@ -0,0 +1,28 @@ +module.exports = Self => { + Self.remoteMethod('guessPriority', { + description: 'Changes automatically the priority of the tickets in a route', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'Route Id ', + http: {source: 'path'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/guessPriority`, + verb: 'GET' + } + }); + + Self.guessPriority = async id => { + let query = `CALL vn.routeGuessPriority(?)`; + + let options = [id]; + return await Self.rawSql(query, options); + }; +}; diff --git a/modules/route/back/methods/route/specs/filter.spec.js b/modules/route/back/methods/route/specs/filter.spec.js new file mode 100644 index 000000000..a4742c128 --- /dev/null +++ b/modules/route/back/methods/route/specs/filter.spec.js @@ -0,0 +1,122 @@ +const app = require('vn-loopback/server/server'); + +describe('Route filter()', () => { + let today = new Date(); + today.setHours(2, 0, 0, 0); + + it('should return the routes matching "search"', async() => { + let ctx = { + args: { + search: 1, + } + }; + + let result = await app.models.Route.filter(ctx); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(1); + }); + + // #1428 cuadrar formato de horas + xit('should return the routes matching "from"', async() => { + let ctx = { + args: { + from: today, + } + }; + + let result = await app.models.Route.filter(ctx); + + expect(result.length).toEqual(7); + }); + + it('should return the routes matching "to"', async() => { + let ctx = { + args: { + to: today, + } + }; + + let result = await app.models.Route.filter(ctx); + + expect(result.length).toEqual(7); + }); + + it('should return the routes matching "m3"', async() => { + let ctx = { + args: { + m3: 0.1, + } + }; + + let result = await app.models.Route.filter(ctx); + + expect(result.length).toEqual(1); + }); + + it('should return the routes matching "description"', async() => { + let ctx = { + args: { + description: 'third route', + } + }; + + let result = await app.models.Route.filter(ctx); + + expect(result.length).toEqual(1); + }); + + it('should return the routes matching "workerFk"', async() => { + let ctx = { + args: { + workerFk: 56, + } + }; + + let result = await app.models.Route.filter(ctx); + + expect(result.length).toEqual(5); + }); + + it('should return the routes matching "warehouseFk"', async() => { + let ctx = { + args: { + warehouseFk: 1, + } + }; + + let result = await app.models.Route.filter(ctx); + + expect(result.length).toEqual(7); + + ctx.args.warehouseFk = 2; + + result = await app.models.Route.filter(ctx); + + expect(result.length).toEqual(0); + }); + + it('should return the routes matching "vehicleFk"', async() => { + let ctx = { + args: { + vehicleFk: 2, + } + }; + + let result = await app.models.Route.filter(ctx); + + expect(result.length).toEqual(1); + }); + + it('should return the routes matching "agencyModeFk"', async() => { + let ctx = { + args: { + agencyModeFk: 7, + } + }; + + let result = await app.models.Route.filter(ctx); + + expect(result.length).toEqual(1); + }); +}); diff --git a/modules/route/back/methods/route/specs/getDeliveryPoint.spec.js b/modules/route/back/methods/route/specs/getDeliveryPoint.spec.js new file mode 100644 index 000000000..4025b04d6 --- /dev/null +++ b/modules/route/back/methods/route/specs/getDeliveryPoint.spec.js @@ -0,0 +1,13 @@ +const app = require('vn-loopback/server/server'); + +describe('route getDeliveryPoint()', () => { + const routeId = 1; + const deliveryPointAddress = '46460 Av Espioca 100-Silla'; + + it('should get the delivery point addres of a route with assigned vehicle', async() => { + let route = await app.models.Route.findById(routeId); + let address = await app.models.Route.getDeliveryPoint(route.vehicleFk); + + expect(address).toEqual(deliveryPointAddress); + }); +}); diff --git a/modules/route/back/methods/route/specs/getTickets.spec.js b/modules/route/back/methods/route/specs/getTickets.spec.js new file mode 100644 index 000000000..15028309f --- /dev/null +++ b/modules/route/back/methods/route/specs/getTickets.spec.js @@ -0,0 +1,9 @@ +const app = require('vn-loopback/server/server'); + +describe('route getTickets()', () => { + it('should return the tickets for a given route', async() => { + let result = await app.models.Route.getTickets(2); + + expect(result.length).toEqual(1); + }); +}); diff --git a/modules/route/back/methods/route/specs/guessPriority.spec.js b/modules/route/back/methods/route/specs/guessPriority.spec.js new file mode 100644 index 000000000..075ea05c8 --- /dev/null +++ b/modules/route/back/methods/route/specs/guessPriority.spec.js @@ -0,0 +1,39 @@ +const app = require('vn-loopback/server/server'); + +describe('route guessPriority()', () => { + const targetRouteId = 7; + let routeTicketsToRestore; + + afterAll(async done => { + let restoreFixtures = []; + routeTicketsToRestore.forEach(ticket => { + restoreFixtures.push(ticket.updateAttribute('priority', null)); + }); + await Promise.all(restoreFixtures); + + done(); + }); + + it('should confirm the tickets in the target route have no priority yet', async() => { + routeTicketsToRestore = await app.models.Ticket.find({where: {routeFk: targetRouteId}}); + + expect(routeTicketsToRestore.length).toEqual(2); + + expect(routeTicketsToRestore[0].id).toEqual(23); + expect(routeTicketsToRestore[0].priority).toBeNull(); + expect(routeTicketsToRestore[1].id).toEqual(24); + expect(routeTicketsToRestore[1].priority).toBeNull(); + }); + + it('should call guessPriority() and then check the tickets in the target route now have their priorities defined', async() => { + await app.models.Route.guessPriority(targetRouteId); + let routeTickets = await app.models.Ticket.find({where: {routeFk: targetRouteId}, fields: ['id', 'priority']}); + + expect(routeTickets.length).toEqual(2); + + expect(routeTickets[0].id).toEqual(23); + expect(routeTickets[0].priority).toEqual(3); + expect(routeTickets[1].id).toEqual(24); + expect(routeTickets[1].priority).toEqual(1); + }); +}); diff --git a/modules/route/back/methods/route/specs/summary.spec.js b/modules/route/back/methods/route/specs/summary.spec.js new file mode 100644 index 000000000..ba976ae94 --- /dev/null +++ b/modules/route/back/methods/route/specs/summary.spec.js @@ -0,0 +1,36 @@ +const app = require('vn-loopback/server/server'); + +describe('route summary()', () => { + it('should return a summary object containing data from one route', async() => { + const result = await app.models.Route.summary(1); + + expect(result.route.id).toEqual(1); + }); + + it(`should return a summary object containing it's agency`, async() => { + const result = await app.models.Route.summary(1); + const agency = result.route.agencyMode(); + + expect(agency.name).toEqual('inhouse pickup'); + }); + + it(`should return a summary object containing it's vehicle`, async() => { + const result = await app.models.Route.summary(1); + const vehicle = result.route.vehicle(); + + expect(vehicle.numberPlate).toEqual('3333-BAT'); + }); + + it(`should return a summary object containing it's worker`, async() => { + const result = await app.models.Route.summary(1); + const worker = result.route.worker().user(); + + expect(worker.nickname).toEqual('deliveryNick'); + }); + + it(`should return a summary object containing data from the tickets`, async() => { + const result = await app.models.Route.summary(2); + + expect(result.tickets.length).toEqual(1); + }); +}); diff --git a/modules/route/back/methods/route/specs/updateVolume.spec.js b/modules/route/back/methods/route/specs/updateVolume.spec.js new file mode 100644 index 000000000..a1ff67acc --- /dev/null +++ b/modules/route/back/methods/route/specs/updateVolume.spec.js @@ -0,0 +1,47 @@ +const app = require('vn-loopback/server/server'); + +describe('route updateVolume()', () => { + const routeId = 1; + const workerFk = 9; + const ctx = {req: {accessToken: {userId: workerFk}}}; + let originalRoute; + let ticketToRestore; + let logIdToDestroy; + + + afterAll(async done => { + await originalRoute.updateAttributes({m3: 1.8}); + await ticketToRestore.updateAttributes({routeFk: null}); + await app.models.RouteLog.destroyById(logIdToDestroy); + done(); + }); + + it('should confirm the original volume of the route is the expected', async() => { + originalRoute = await app.models.Route.findById(routeId); + + expect(originalRoute.m3).toEqual(1.8); + }); + + it('should confirm the route volume is updated when a ticket is added', async() => { + ticketToRestore = await app.models.Ticket.findById(14); + let updatedTicket = await app.models.Ticket.findById(14); + + await updatedTicket.updateAttributes({routeFk: routeId}); + await app.models.Route.updateVolume(ctx, routeId); + + let updatedRoute = await app.models.Route.findById(routeId); + + expect(updatedRoute.m3).not.toEqual(originalRoute.m3); + }); + + it('should confirm the change is logged', async() => { + let logs = await app.models.RouteLog.find({fields: ['id', 'newInstance']}); + + let m3Log = logs.filter(log => { + return log.newInstance.m3 === 1.9; + }); + logIdToDestroy = m3Log[0].id; + + expect(m3Log.length).toEqual(1); + }); +}); diff --git a/modules/route/back/methods/route/summary.js b/modules/route/back/methods/route/summary.js new file mode 100644 index 000000000..0a8710e88 --- /dev/null +++ b/modules/route/back/methods/route/summary.js @@ -0,0 +1,60 @@ +module.exports = Self => { + Self.remoteMethod('summary', { + description: 'Returns the information of a route showed in the route summary', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The route id', + http: {source: 'path'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/summary`, + verb: 'GET' + } + }); + + Self.summary = async id => { + let summary = {}; + + let filter = { + where: {id: id}, + include: [ + { + relation: 'agencyMode', + scope: { + fields: ['id', 'name'] + } + }, { + relation: 'worker', + scope: { + fields: ['id', 'userFk'], + include: [ + { + relation: 'user', + scope: { + fields: ['id', 'nickname'] + } + } + ] + } + }, { + relation: 'vehicle', + scope: { + fields: ['id', 'm3', 'numberPlate'] + } + } + ], + }; + + summary.route = await Self.app.models.Route.findOne(filter); + summary.tickets = await Self.app.models.Route.getTickets(id); + + return summary; + }; +}; diff --git a/modules/route/back/methods/route/updateVolume.js b/modules/route/back/methods/route/updateVolume.js new file mode 100644 index 000000000..27e96ebab --- /dev/null +++ b/modules/route/back/methods/route/updateVolume.js @@ -0,0 +1,42 @@ +module.exports = Self => { + Self.remoteMethodCtx('updateVolume', { + description: 'Update the volume in a route', + accessType: 'WRITE', + accepts: { + arg: 'id', + type: 'number', + required: true, + description: 'Route id', + http: {source: 'path'} + }, + returns: { + type: 'number', + root: true + }, + http: { + path: `/:id/updateVolume`, + verb: 'POST' + } + }); + + Self.updateVolume = async(ctx, id) => { + let query = `CALL vn.routeUpdateM3(?)`; + let userId = ctx.req.accessToken.userId; + let originalRoute = await Self.app.models.Route.findById(id); + + await Self.rawSql(query, [id]); + let updatedRoute = await Self.app.models.Route.findById(id); + + let logRecord = { + originFk: id, + userFk: userId, + action: 'update', + changedModel: 'Route', + changedModelId: id, + oldInstance: {m3: originalRoute.m3}, + newInstance: {m3: updatedRoute.m3} + }; + + return await Self.app.models.RouteLog.create(logRecord); + }; +}; diff --git a/modules/route/back/model-config.json b/modules/route/back/model-config.json new file mode 100644 index 000000000..0dfe1d02a --- /dev/null +++ b/modules/route/back/model-config.json @@ -0,0 +1,16 @@ +{ + "Route": { + "dataSource": "vn" + }, + "Vehicle": { + "dataSource": "vn" + }, + "RouteLog": { + "dataSource": "vn" + }, + "DeliveryPoint": { + "dataSource": "vn" + } +} + + diff --git a/modules/route/back/models/deliveryPoint.json b/modules/route/back/models/deliveryPoint.json new file mode 100644 index 000000000..c6c0a2116 --- /dev/null +++ b/modules/route/back/models/deliveryPoint.json @@ -0,0 +1,22 @@ +{ + "name": "DeliveryPoint", + "base": "VnModel", + "options": { + "mysql": { + "table": "deliveryPoint" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "name": { + "type": "String" + }, + "ubication": { + "type": "String" + } + } +} diff --git a/modules/route/back/models/route-log.json b/modules/route/back/models/route-log.json new file mode 100644 index 000000000..abaeeb722 --- /dev/null +++ b/modules/route/back/models/route-log.json @@ -0,0 +1,58 @@ +{ + "name": "RouteLog", + "base": "VnModel", + "options": { + "mysql": { + "table": "routeLog" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "forceId": false + }, + "originFk": { + "type": "Number", + "required": true + }, + "userFk": { + "type": "Number" + }, + "action": { + "type": "String", + "required": true + }, + "changedModel": { + "type": "String" + }, + "oldInstance": { + "type": "Object" + }, + "newInstance": { + "type": "Object" + }, + "creationDate": { + "type": "Date" + }, + "changedModelId": { + "type": "Number" + }, + "changedModelValue": { + "type": "String" + }, + "description": { + "type": "String" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + } + }, + "scope": { + "order": ["creationDate DESC", "id DESC"] + } +} diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js new file mode 100644 index 000000000..4dd9f3dc0 --- /dev/null +++ b/modules/route/back/models/route.js @@ -0,0 +1,8 @@ +module.exports = Self => { + require('../methods/route/filter')(Self); + require('../methods/route/summary')(Self); + require('../methods/route/getTickets')(Self); + require('../methods/route/guessPriority')(Self); + require('../methods/route/updateVolume')(Self); + require('../methods/route/getDeliveryPoint')(Self); +}; diff --git a/modules/route/back/models/route.json b/modules/route/back/models/route.json new file mode 100644 index 000000000..bdb641096 --- /dev/null +++ b/modules/route/back/models/route.json @@ -0,0 +1,79 @@ +{ + "name": "Route", + "base": "Loggable", + "log": { + "model":"RouteLog" + }, + "options": { + "mysql": { + "table": "route" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "created": { + "type": "date" + }, + "time": { + "type": "date" + }, + "kmStart": { + "type": "Number" + }, + "kmEnd": { + "type": "Number" + }, + "started": { + "type": "date" + }, + "finished": { + "type": "date" + }, + "gestdoc": { + "type": "date", + "mysql": { + "columnName": "gestdocFk" + } + }, + "cost": { + "type": "Number" + }, + "m3": { + "type": "Number" + }, + "description": { + "type": "String" + } + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "vehicle": { + "type": "belongsTo", + "model": "Vehicle", + "foreignKey": "vehicleFk" + }, + "agencyMode": { + "type": "belongsTo", + "model": "AgencyMode", + "foreignKey": "agencyModeFk" + }, + "ticket": { + "type": "hasMany", + "model": "Ticket", + "foreignKey": "routeFk" + }, + "zone": { + "type": "belongsTo", + "model": "Zone", + "foreignKey": "zoneFk" + } + } +} diff --git a/modules/route/back/models/vehicle.json b/modules/route/back/models/vehicle.json new file mode 100644 index 000000000..399480c98 --- /dev/null +++ b/modules/route/back/models/vehicle.json @@ -0,0 +1,64 @@ +{ + "name": "Vehicle", + "base": "VnModel", + "options": { + "mysql": { + "table": "vehicle" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "numberPlate": { + "type": "String" + }, + "tradeMark": { + "type": "String" + }, + "model": { + "type": "String" + }, + "m3": { + "type": "Number" + }, + "description": { + "type": "String" + }, + "isActive": { + "type": "Number" + } + }, + "relations": { + "company": { + "type": "belongsTo", + "model": "Company", + "foreignKey": "companyFk" + }, + "warehouse": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseFk" + }, + "deliveryPoint": { + "type": "belongsTo", + "model": "DeliveryPoint", + "foreignKey": "deliveryPointFk" + } + }, + "scope": { + "where": { + "isActive": true + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/modules/route/front/basic-data/index.html b/modules/route/front/basic-data/index.html new file mode 100644 index 000000000..dcdfd37d7 --- /dev/null +++ b/modules/route/front/basic-data/index.html @@ -0,0 +1,83 @@ + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/modules/route/front/basic-data/index.js b/modules/route/front/basic-data/index.js new file mode 100644 index 000000000..810fd7511 --- /dev/null +++ b/modules/route/front/basic-data/index.js @@ -0,0 +1,25 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope) { + this.$ = $scope; + } + + onSubmit() { + this.$.watcher.submit().then(() => { + this.card.reload(); + }); + } +} +Controller.$inject = ['$scope']; + +ngModule.component('vnRouteBasicData', { + template: require('./index.html'), + controller: Controller, + bindings: { + route: '<' + }, + require: { + card: '^vnRouteCard' + } +}); diff --git a/modules/route/front/basic-data/locale/es.yml b/modules/route/front/basic-data/locale/es.yml new file mode 100644 index 000000000..442a4fa82 --- /dev/null +++ b/modules/route/front/basic-data/locale/es.yml @@ -0,0 +1,5 @@ +Date finished: Fecha fin +Date started: Fecha inicio +Km start: Km de inicio +Km end: Km de fin +Description: Descripción \ No newline at end of file diff --git a/modules/route/front/card/index.html b/modules/route/front/card/index.html new file mode 100644 index 000000000..051d8714f --- /dev/null +++ b/modules/route/front/card/index.html @@ -0,0 +1,5 @@ + + + + + diff --git a/modules/route/front/card/index.js b/modules/route/front/card/index.js new file mode 100644 index 000000000..0760259d3 --- /dev/null +++ b/modules/route/front/card/index.js @@ -0,0 +1,70 @@ +import ngModule from '../module'; +import ModuleCard from 'salix/components/module-card'; + +class Controller extends ModuleCard { + reload() { + let filter = { + fields: [ + 'id', + 'workerFk', + 'agencyModeFk', + 'created', + 'm3', + 'warehouseFk', + 'description', + 'vehicleFk', + 'kmStart', + 'kmEnd', + 'started', + 'finished', + 'cost', + 'zoneFk' + ], + include: [ + { + relation: 'agencyMode', + scope: { + fields: ['id', 'name'] + } + }, { + relation: 'vehicle', + scope: { + fields: ['id', 'm3'] + } + }, { + relation: 'zone', + scope: { + fields: ['id', 'name'] + } + }, + { + relation: 'worker', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['id'], + include: { + relation: 'emailUser', + scope: { + fields: ['email'] + } + } + } + } + } + } + ] + }; + + this.$http.get(`Routes/${this.$params.id}`, {filter}) + .then(res => this.route = res.data); + } +} + +ngModule.component('vnRouteCard', { + template: require('./index.html'), + controller: Controller +}); + diff --git a/modules/route/front/create/index.html b/modules/route/front/create/index.html new file mode 100644 index 000000000..7f6a1f600 --- /dev/null +++ b/modules/route/front/create/index.html @@ -0,0 +1,58 @@ + + + +
    + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/modules/route/front/create/index.js b/modules/route/front/create/index.js new file mode 100644 index 000000000..03fe574fc --- /dev/null +++ b/modules/route/front/create/index.js @@ -0,0 +1,20 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($scope, $state) { + this.$scope = $scope; + this.$state = $state; + } + + onSubmit() { + this.$scope.watcher.submit().then( + res => this.$state.go('route.card.summary', {id: res.data.id}) + ); + } +} +Controller.$inject = ['$scope', '$state']; + +ngModule.component('vnRouteCreate', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/route/front/descriptor/index.html b/modules/route/front/descriptor/index.html new file mode 100644 index 000000000..f04632244 --- /dev/null +++ b/modules/route/front/descriptor/index.html @@ -0,0 +1,58 @@ +
    +
    + + + + + + + + +
    +
    +
    +
    {{$ctrl.route.name}}
    + + + + + + + + + + + + +
    +
    + + +
    + + +
    +
    + + \ No newline at end of file diff --git a/modules/route/front/descriptor/index.js b/modules/route/front/descriptor/index.js new file mode 100644 index 000000000..cfa718855 --- /dev/null +++ b/modules/route/front/descriptor/index.js @@ -0,0 +1,91 @@ +import ngModule from '../module'; + +class Controller { + constructor($, $http, vnApp, $translate, aclService, $httpParamSerializer) { + this.$http = $http; + this.vnApp = vnApp; + this.$translate = $translate; + this.$ = $; + this.aclService = aclService; + this.$httpParamSerializer = $httpParamSerializer; + this.moreOptions = [ + {callback: this.showRouteReport, name: 'Show route report'}, + {callback: this.sendRouteReport, name: 'Send route report'}, + {callback: this.showUpdateVolumeDialog, name: 'Update volume', acl: 'deliveryBoss'} + ]; + } + + onMoreOpen() { + let options = this.moreOptions.filter(option => { + const hasAclProperty = Object.hasOwnProperty.call(option, 'acl'); + + return !hasAclProperty || (hasAclProperty && this.aclService.hasAny([option.acl])); + }); + this.$.moreButton.data = options; + } + + set quicklinks(value = {}) { + this._quicklinks = Object.assign(value, this._quicklinks); + } + + get quicklinks() { + return this._quicklinks; + } + + onMoreChange(callback) { + callback.call(this); + } + + showRouteReport() { + const user = this.route.worker.user; + const params = { + clientId: user.id, + routeId: this.route.id + }; + const serializedParams = this.$httpParamSerializer(params); + let url = `api/report/driver-route?${serializedParams}`; + window.open(url); + } + + sendRouteReport() { + const user = this.route.worker.user; + const params = { + recipient: user.emailUser.email, + clientId: user.id, + routeId: this.route.id + }; + const serializedParams = this.$httpParamSerializer(params); + const url = `email/driver-route?${serializedParams}`; + this.$http.get(url).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Report sent')); + }); + } + + showUpdateVolumeDialog() { + this.$.updateVolumeConfirmation.show(); + } + + updateVolume(response) { + if (response === 'accept') { + let url = `Routes/${this.route.id}/updateVolume`; + this.$http.post(url).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Volume updated')); + if (this.card) this.card.reload(); + }); + } + } +} + +Controller.$inject = ['$scope', '$http', 'vnApp', '$translate', 'aclService', '$httpParamSerializer']; + +ngModule.component('vnRouteDescriptor', { + template: require('./index.html'), + bindings: { + route: '<', + quicklinks: '<' + }, + require: { + card: '^?vnRouteCard' + }, + controller: Controller +}); diff --git a/modules/route/front/descriptor/locale/es.yml b/modules/route/front/descriptor/locale/es.yml new file mode 100644 index 000000000..63fa7202b --- /dev/null +++ b/modules/route/front/descriptor/locale/es.yml @@ -0,0 +1,7 @@ +Volume exceded: Volumen excedido +Volume: Volumen +Send route report: Enviar informe de ruta +Show route report: Ver informe de ruta +Update volume: Actualizar volumen +Volume updated: Volumen actualizado +Are you sure you want to update the volume?: Estas seguro que quieres actualizar el volumen? \ No newline at end of file diff --git a/modules/route/front/index.js b/modules/route/front/index.js new file mode 100644 index 000000000..ce8e80e95 --- /dev/null +++ b/modules/route/front/index.js @@ -0,0 +1,12 @@ +export * from './module'; + +import './main'; +import './index/'; +import './search-panel'; +import './descriptor'; +import './summary'; +import './card'; +import './create'; +import './basic-data'; +import './log'; +import './tickets'; diff --git a/modules/route/front/index/index.html b/modules/route/front/index/index.html new file mode 100644 index 000000000..c01112928 --- /dev/null +++ b/modules/route/front/index/index.html @@ -0,0 +1,73 @@ + + + + + + + + + + Id + Worker + Agency + Vehicle + Date + + Description + + + + + + {{::route.id | dashIfEmpty}} + + + {{::route.workerNickname}} + + + {{::route.agencyName | dashIfEmpty}} + {{::route.vehiclePlateNumber | dashIfEmpty}} + {{::route.created | date:'dd/MM/yyyy' | dashIfEmpty}} + {{::route.m3 | dashIfEmpty}} + {{::route.description | dashIfEmpty}} + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/route/front/index/index.js b/modules/route/front/index/index.js new file mode 100644 index 000000000..8fdde810c --- /dev/null +++ b/modules/route/front/index/index.js @@ -0,0 +1,40 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($scope, vnToken) { + this.$ = $scope; + this.accessToken = vnToken.token; + } + + showWorkerDescriptor(event, workerFk) { + if (event.defaultPrevented) return; + event.preventDefault(); + event.stopPropagation(); + + this.selectedWorker = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } + + preview(event, route) { + if (event.defaultPrevented) return; + event.preventDefault(); + event.stopPropagation(); + + this.routeSelected = route; + this.$.summary.show(); + } + + onSearch(params) { + if (params) + this.$.model.applyFilter(null, params); + else + this.$.model.clear(); + } +} +Controller.$inject = ['$scope', 'vnToken']; + +ngModule.component('vnRouteIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/route/front/index/locale/es.yml b/modules/route/front/index/locale/es.yml new file mode 100644 index 000000000..5a21565b5 --- /dev/null +++ b/modules/route/front/index/locale/es.yml @@ -0,0 +1 @@ +Vehicle: Vehículo diff --git a/modules/route/front/locale/es.yml b/modules/route/front/locale/es.yml new file mode 100644 index 000000000..421d40923 --- /dev/null +++ b/modules/route/front/locale/es.yml @@ -0,0 +1,3 @@ +Routes: Rutas +Search routes by id: Buscar rutas por identificador +New route: Nueva ruta \ No newline at end of file diff --git a/modules/route/front/log/index.html b/modules/route/front/log/index.html new file mode 100644 index 000000000..6a6adf250 --- /dev/null +++ b/modules/route/front/log/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/modules/route/front/log/index.js b/modules/route/front/log/index.js new file mode 100644 index 000000000..ff0a2a9d1 --- /dev/null +++ b/modules/route/front/log/index.js @@ -0,0 +1,15 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $stateParams) { + this.$scope = $scope; + this.$stateParams = $stateParams; + } +} + +Controller.$inject = ['$scope', '$stateParams']; + +ngModule.component('vnRouteLog', { + template: require('./index.html'), + controller: Controller, +}); diff --git a/modules/route/front/main/index.html b/modules/route/front/main/index.html new file mode 100644 index 000000000..f6e097b24 --- /dev/null +++ b/modules/route/front/main/index.html @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/modules/route/front/main/index.js b/modules/route/front/main/index.js new file mode 100644 index 000000000..618989748 --- /dev/null +++ b/modules/route/front/main/index.js @@ -0,0 +1,26 @@ +import ngModule from '../module'; +import ModuleMain from 'salix/components/module-main'; + +export default class Route extends ModuleMain { + constructor($element, $, vnConfig) { + super($element, $); + this.vnConfig = vnConfig; + } + + $postLink() { + let to = new Date(); + to.setDate(to.getDate() + 1); + to.setHours(0, 0, 0, 0); + + let from = new Date(); + from.setHours(0, 0, 0, 0); + + this.filter = {from, to, warehouseFk: this.vnConfig.warehouseFk}; + } +} +Route.$inject = ['$element', '$scope', 'vnConfig']; + +ngModule.vnComponent('vnRoute', { + controller: Route, + template: require('./index.html') +}); diff --git a/modules/route/front/module.js b/modules/route/front/module.js new file mode 100644 index 000000000..bd7b1516b --- /dev/null +++ b/modules/route/front/module.js @@ -0,0 +1,3 @@ +import {ng} from 'core/vendor'; + +export default ng.module('route', ['vnCore']); diff --git a/modules/route/front/routes.json b/modules/route/front/routes.json new file mode 100644 index 000000000..beb444abc --- /dev/null +++ b/modules/route/front/routes.json @@ -0,0 +1,74 @@ +{ + "module": "route", + "name": "Routes", + "icon": "icon-delivery", + "validations" : true, + "dependencies": ["client", "worker", "ticket"], + "menus": { + "main": [ + {"state": "route.index", "icon": "icon-delivery"} + ], + "card": [ + {"state": "route.card.basicData", "icon": "settings"}, + {"state": "route.card.tickets", "icon": "icon-ticket"}, + {"state": "route.card.log", "icon": "history"} + ] + }, + "routes": [ + { + "url": "/route", + "state": "route", + "abstract": true, + "component": "vn-route", + "description": "Routes", + "acl": ["employee"] + }, { + "url": "/index?q", + "state": "route.index", + "component": "vn-route-index", + "description": "Routes" + }, { + "url": "/create", + "state": "route.create", + "component": "vn-route-create", + "description": "New route" + }, { + "url": "/:id", + "state": "route.card", + "abstract": true, + "component": "vn-route-card" + }, { + "url": "/summary", + "state": "route.card.summary", + "component": "vn-route-summary", + "description": "Summary", + "params": { + "route": "$ctrl.route" + } + }, { + "url": "/basic-data", + "state": "route.card.basicData", + "component": "vn-route-basic-data", + "description": "Basic data", + "params": { + "route": "$ctrl.route" + }, + "acl": ["delivery"] + }, { + "url" : "/log", + "state": "route.card.log", + "component": "vn-route-log", + "description": "Log", + "acl": ["delivery"] + }, { + "url": "/tickets", + "state": "route.card.tickets", + "component": "vn-route-tickets", + "description": "Tickets", + "params": { + "route": "$ctrl.route" + }, + "acl": ["delivery"] + } + ] +} \ No newline at end of file diff --git a/modules/route/front/search-panel/index.html b/modules/route/front/search-panel/index.html new file mode 100644 index 000000000..2c7dd93b2 --- /dev/null +++ b/modules/route/front/search-panel/index.html @@ -0,0 +1,78 @@ +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    diff --git a/modules/route/front/search-panel/index.js b/modules/route/front/search-panel/index.js new file mode 100644 index 000000000..6226236f2 --- /dev/null +++ b/modules/route/front/search-panel/index.js @@ -0,0 +1,7 @@ +import ngModule from '../module'; +import SearchPanel from 'core/components/searchbar/search-panel'; + +ngModule.component('vnRouteSearchPanel', { + template: require('./index.html'), + controller: SearchPanel +}); diff --git a/modules/route/front/summary/index.html b/modules/route/front/summary/index.html new file mode 100644 index 000000000..0ec6c47fe --- /dev/null +++ b/modules/route/front/summary/index.html @@ -0,0 +1,107 @@ + +
    {{$ctrl.summary.route.id}} - {{$ctrl.summary.route.description}}
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

    Ticket

    + + + + Order + Ticket id + Alias + Packages + + Warehouse + PC + Street + + + + + + {{ticket.priority | dashIfEmpty}} + + + {{ticket.id | zeroFill:6}} + + + + + {{ticket.nickname}} + + + {{ticket.packages}} + {{ticket.volume}} + {{ticket.warehouse.name}} + {{ticket.client.postcode}} + {{ticket.client.street}} + + + + + + + +
    +
    +
    + + + + \ No newline at end of file diff --git a/modules/route/front/summary/index.js b/modules/route/front/summary/index.js new file mode 100644 index 000000000..b1d42e6f1 --- /dev/null +++ b/modules/route/front/summary/index.js @@ -0,0 +1,58 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $http) { + this.$http = $http; + this.$ = $scope; + } + + set route(value) { + this._route = value; + if (value && value.id) + this.getSummary(); + } + + sumPackages() { + this.packagesTotal = 0; + this.summary.tickets.forEach(ticket => { + this.packagesTotal += ticket.packages; + }); + } + + showTicketDescriptor(event, ticketFk) { + this.$.ticketDescriptor.ticketFk = ticketFk; + this.$.ticketDescriptor.parent = event.target; + this.$.ticketDescriptor.show(); + event.preventDefault(); + } + + showClientDescriptor(event, clientFk) { + this.$.clientDescriptor.clientFk = clientFk; + this.$.clientDescriptor.parent = event.target; + this.$.clientDescriptor.show(); + event.preventDefault(); + } + + get route() { + return this._route; + } + + getSummary() { + this.$http.get(`Routes/${this.route.id}/summary`).then(response => { + this.summary = response.data; + if (response.data && response.data.tickets) + this.sumPackages(); + }); + } +} + +Controller.$inject = ['$scope', '$http']; + +ngModule.component('vnRouteSummary', { + template: require('./index.html'), + controller: Controller, + bindings: { + route: '<' + } +}); diff --git a/modules/route/front/summary/index.spec.js b/modules/route/front/summary/index.spec.js new file mode 100644 index 000000000..0dfc016b4 --- /dev/null +++ b/modules/route/front/summary/index.spec.js @@ -0,0 +1,41 @@ +import './index.js'; + +describe('Route', () => { + describe('Component summary', () => { + let controller; + let $httpBackend; + + beforeEach(ngModule('route')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + controller = $componentController('vnRouteSummary'); + controller.route = {id: 1}; + })); + + describe('getSummary()', () => { + it('should perform a query to set summary', () => { + $httpBackend.when('GET', `Routes/1/summary`).respond(200, 24); + $httpBackend.expect('GET', `Routes/1/summary`); + controller.getSummary(); + $httpBackend.flush(); + + expect(controller.summary).toEqual(24); + }); + }); + + describe('sumPackages()', () => { + it('should calculate the packages total', () => { + controller.summary = { + tickets: [ + {packages: 3}, + {packages: 1} + ] + }; + controller.sumPackages(); + + expect(controller.packagesTotal).toEqual(4); + }); + }); + }); +}); diff --git a/modules/route/front/summary/locale/es.yml b/modules/route/front/summary/locale/es.yml new file mode 100644 index 000000000..2c7a87f51 --- /dev/null +++ b/modules/route/front/summary/locale/es.yml @@ -0,0 +1,8 @@ +Driver: Conductor +Vehicle: Vehículo +Packages: Bultos +Starting time: H. Inicio +Finishing time: H. Fin +Km Start: Km de inicio +Km End: Km de fin +PC: CP \ No newline at end of file diff --git a/modules/route/front/summary/style.scss b/modules/route/front/summary/style.scss new file mode 100644 index 000000000..b41512f32 --- /dev/null +++ b/modules/route/front/summary/style.scss @@ -0,0 +1,10 @@ +@import "variables"; + + +vn-route-summary .summary { + max-width: $width-lg; + + vn-icon[icon=insert_drive_file]{ + color: $color-font-secondary; + } +} \ No newline at end of file diff --git a/modules/route/front/tickets/__snapshots__/index.spec.js.snap b/modules/route/front/tickets/__snapshots__/index.spec.js.snap new file mode 100644 index 000000000..9476a8e09 --- /dev/null +++ b/modules/route/front/tickets/__snapshots__/index.spec.js.snap @@ -0,0 +1,18 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Route getSelectedItems() should return the selected items 1`] = ` +Array [ + Object { + "checked": true, + "id": 1, + }, + Object { + "checked": true, + "id": 3, + }, + Object { + "checked": true, + "id": 5, + }, +] +`; diff --git a/modules/route/front/tickets/index.html b/modules/route/front/tickets/index.html new file mode 100644 index 000000000..4a0e58112 --- /dev/null +++ b/modules/route/front/tickets/index.html @@ -0,0 +1,179 @@ + + + +
    + + + + + + + + + + + + + + + + + Order + Ticket + Client + Packages + + Warehouse + Postcode + Street + + + + + + + + + + + + + + + + + {{ticket.id}} + + + + + {{ticket.nickname}} + + + {{ticket.packages}} + {{ticket.volume}} + {{ticket.warehouse.name}} + {{ticket.address.postalCode}} + {{ticket.address.street}} + + + + + + + + + + + + +
    +
    + + + + + + + + + + +
    +
    Tickets to add
    +
    + + + + + + + + + Ticket + Client + Packages + Warehouse + Postcode + Address + + + + + + + + + {{ticket.id}} + + + {{ticket.nickname}} + + + {{ticket.packages}} + {{ticket.warehouse.name}} + {{ticket.address.postalCode}} + {{ticket.address.street}} + + + + +
    + + + + +
    + + \ No newline at end of file diff --git a/modules/route/front/tickets/index.js b/modules/route/front/tickets/index.js new file mode 100644 index 000000000..e516a5fa6 --- /dev/null +++ b/modules/route/front/tickets/index.js @@ -0,0 +1,187 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($stateParams, $scope, $translate, $http, vnApp, $filter) { + this.$translate = $translate; + this.$stateParams = $stateParams; + this.$ = $scope; + this.$http = $http; + this.vnApp = vnApp; + this.$filter = $filter; + } + + set route(value) { + this._route = value; + if (value) + this.buildPossibleTicketsFilter(); + } + + get route() { + return this._route; + } + + get isChecked() { + if (this.tickets) { + for (let instance of this.tickets) + if (instance.checked) return true; + } + + return false; + } + + buildPossibleTicketsFilter() { + let minDate = new Date(this.route.finished); + minDate.setHours(0, 0, 0, 0); + + let maxDate = new Date(this.route.finished); + maxDate.setHours(23, 59, 59, 59); + + this.possibleTicketsFilter = { + where: { + zoneFk: this.route.zoneFk, + routeFk: null, + landed: {between: [minDate, maxDate]}, + }, + include: [ + { + relation: 'warehouse', + scope: { + fields: ['name'] + }, + }, { + relation: 'address' + } + ] + }; + } + + getHighestPriority() { + let highestPriority = Math.max(...this.$.model.data.map(tag => { + return tag.priority; + })); + return highestPriority + 1; + } + + setPriority(id, priority) { + let params = {priority: priority}; + let query = `Tickets/${id}/`; + this.$http.patch(query, params).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$.model.refresh(); + }); + } + + getSelectedItems(items) { + const selectedItems = []; + + if (items) { + for (let i = 0; i < items.length; i++) { + if (items[i].checked) + selectedItems.push(items[i]); + } + } + return selectedItems; + } + + goToBuscaman() { + let query = `Routes/${this.route.vehicleFk}/getDeliveryPoint`; + let deliveryPointAddress; + let addresses; + + this.$http.get(query).then(response => { + deliveryPointAddress = response.data; + }).then(() => { + addresses = deliveryPointAddress; + let lines = this.getSelectedItems(this.tickets); + + let url = 'http://gps.buscalia.com/usuario/localizar.aspx?bmi=true&addr='; + lines.forEach(line => { + addresses = addresses + '+to:' + line.address.postalCode + ' ' + line.address.city + ' ' + line.address.street; + }); + + window.open(url + addresses, '_blank'); + }); + } + + + showDeleteConfirm(id) { + this.selectedTicket = id; + this.$.confirm.show(); + } + + removeTicketFromRoute(response) { + if (response === 'accept') { + let params = {routeFk: null}; + let query = `Tickets/${this.selectedTicket}/`; + this.$http.patch(query, params).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Ticket removed from route')); + this.updateVolume(); + }); + } + } + + updateVolume() { + let url = `Routes/${this.$stateParams.id}/updateVolume`; + this.$http.post(url).then(() => { + this.card.reload(); + this.$.model.refresh(); + }); + } + + guessPriority() { + let query = `Routes/${this.$stateParams.id}/guessPriority/`; + this.$http.get(query).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Order changed')); + this.$.model.refresh(); + }); + } + + showTicketDescriptor(event, ticketFk) { + this.$.ticketDescriptor.ticketFk = ticketFk; + this.$.ticketDescriptor.parent = event.target; + this.$.ticketDescriptor.show(); + event.preventDefault(); + } + + showClientDescriptor(event, clientFk) { + this.$.clientDescriptor.clientFk = clientFk; + this.$.clientDescriptor.parent = event.target; + this.$.clientDescriptor.show(); + event.preventDefault(); + } + + openPossibleTicketsDialog() { + this.$.possibleTicketsModel.refresh(); + this.$.possibleTicketsDialog.show(); + } + + setTicketsRoute(response) { + if (response === 'accept') { + let tickets = this.getSelectedItems(this.possibleTickets); + + for (let i = 0; i < tickets.length; i++) { + delete tickets[i].checked; + tickets[i].routeFk = this.route.id; + } + + return this.$.possibleTicketsModel.save().then(() => { + this.$.model.data = this.$.model.data.concat(tickets); + }); + } + return Promise.resolve(); + } +} + +Controller.$inject = ['$stateParams', '$scope', '$translate', '$http', 'vnApp', '$filter']; + +ngModule.component('vnRouteTickets', { + template: require('./index.html'), + controller: Controller, + require: { + card: '^vnRouteCard' + }, + bindings: { + route: '<' + } +}); diff --git a/modules/route/front/tickets/index.spec.js b/modules/route/front/tickets/index.spec.js new file mode 100644 index 000000000..36e0b9687 --- /dev/null +++ b/modules/route/front/tickets/index.spec.js @@ -0,0 +1,291 @@ +import './index.js'; + +describe('Route', () => { + let controller; + let $httpBackend; + + beforeEach(ngModule('route')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + controller = $componentController('vnRouteTickets'); + })); + + describe('route setter/getter', () => { + it('should return the route id', () => { + controller.route = 2; + + expect(controller.route).toEqual(2); + }); + }); + + describe('isChecked getter', () => { + it('should return false if none of the tickets is checked or there are no tickets', () => { + expect(controller.isChecked).toBeFalsy(); + }); + + it('should return true if any of the tickets is checked', () => { + controller.tickets = [{checked: true}]; + + expect(controller.isChecked).toBeTruthy(); + }); + }); + + describe('buildPossibleTicketsFilter()', () => { + it('should build the possible tickets filter', () => { + let expectedFilter = { + include: [ + { + relation: 'warehouse', + scope: { + fields: ['name'] + } + }, { + relation: 'address' + } + ], + where: { + landed: { + between: [ + jasmine.any(Date), + jasmine.any(Date) + ] + }, + routeFk: null, + zoneFk: 67 + } + }; + controller.route = { + finished: new Date(), + routeFk: null, + zoneFk: 67 + }; + + controller.buildPossibleTicketsFilter(); + + expect(controller.possibleTicketsFilter).toEqual(expectedFilter); + }); + }); + + describe('getHighestPriority()', () => { + it('should return the highest value found in priorities plus 1', () => { + controller.$.model = {data: [ + {priority: 99}, + {priority: 1}, + {priority: 2}, + {priority: 3}, + {priority: 4}, + {priority: 5}, + ]}; + + let result = controller.getHighestPriority(); + + expect(result).toEqual(100); + }); + }); + + describe('setPriority()', () => { + it('should set a ticket priority', () => { + controller.$.model = {refresh: () => {}}; + spyOn(controller.$.model, 'refresh'); + spyOn(controller.vnApp, 'showSuccess'); + const ticketId = 1; + const priority = 999; + + $httpBackend.expectPATCH(`Tickets/${ticketId}/`).respond('ok'); + controller.setPriority(ticketId, priority); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + expect(controller.$.model.refresh).toHaveBeenCalledWith(); + }); + }); + + describe('getSelectedItems()', () => { + it('should return the selected items', () => { + let items = [ + {id: 1, checked: true}, + {id: 2, checked: false}, + {id: 3, checked: true}, + {id: 4, checked: false}, + {id: 5, checked: true}, + ]; + + let selectedItems = controller.getSelectedItems(items); + + expect(selectedItems).toMatchSnapshot(); + }); + }); + + describe('goToBuscaman()', () => { + it('should open buscaman with the given arguments', () => { + spyOn(window, 'open'); + const expectedUrl = 'http://gps.buscalia.com/usuario/localizar.aspx?bmi=true&addr=46460 Av Espioca 100+to:n19 London my street'; + controller.route = {vehicleFk: 1}; + const url = `Routes/${controller.route.vehicleFk}/getDeliveryPoint`; + $httpBackend.expectGET(url).respond('46460 Av Espioca 100'); + + controller.tickets = [ + { + id: 1, + checked: true, + address: { + street: 'my street', + postalCode: 'n19', + city: 'London' + } + }, + ]; + + controller.goToBuscaman(); + $httpBackend.flush(); + + expect(window.open).toHaveBeenCalledWith(expectedUrl, '_blank'); + }); + }); + + describe('showDeleteConfirm()', () => { + it('should open a confirm dialog after setting the selected ticket into the controller', () => { + controller.$.confirm = {show: () => {}}; + spyOn(controller.$.confirm, 'show'); + let ticketId = 1; + + controller.showDeleteConfirm(ticketId); + + expect(controller.selectedTicket).toEqual(ticketId); + expect(controller.$.confirm.show).toHaveBeenCalledWith(); + }); + }); + + describe('removeTicketFromRoute()', () => { + it('should perform a patch query then call showSuccess and updateVolume methods', () => { + spyOn(controller, 'updateVolume'); + spyOn(controller.vnApp, 'showSuccess'); + let ticketId = 1; + controller.selectedTicket = ticketId; + + $httpBackend.expectPATCH(`Tickets/${ticketId}/`).respond('ok'); + controller.removeTicketFromRoute('accept'); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Ticket removed from route'); + expect(controller.updateVolume).toHaveBeenCalledWith(); + }); + }); + + describe('updateVolume()', () => { + it('should perform a POST query then call both reload and refresh methods', () => { + controller.$.model = {refresh: () => {}}; + controller.card = {reload: () => {}}; + controller.$stateParamds = {id: 999}; + spyOn(controller.$.model, 'refresh'); + spyOn(controller.card, 'reload'); + + let ticketId = 1; + controller.selectedTicket = ticketId; + + const url = `Routes/${controller.$stateParams.id}/updateVolume`; + $httpBackend.expectPOST(url).respond('ok'); + controller.updateVolume(); + $httpBackend.flush(); + + expect(controller.$.model.refresh).toHaveBeenCalledWith(); + expect(controller.card.reload).toHaveBeenCalledWith(); + }); + }); + + describe('guessPriority()', () => { + it('should perform a GET query then call both refresh and showSuccess methods', () => { + controller.$.model = {refresh: () => {}}; + spyOn(controller.$.model, 'refresh'); + spyOn(controller.vnApp, 'showSuccess'); + controller.$stateParams = {id: 99}; + + const url = `Routes/${controller.$stateParams.id}/guessPriority/`; + $httpBackend.expectGET(url).respond('ok'); + controller.guessPriority(); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Order changed'); + expect(controller.$.model.refresh).toHaveBeenCalledWith(); + }); + }); + + describe('showTicketDescriptor()', () => { + it('should call the descriptor show function after setting the parent and the ticket id', () => { + controller.$.ticketDescriptor = {show: () => {}}; + spyOn(controller.$.ticketDescriptor, 'show'); + const event = {target: {}, preventDefault: () => {}}; + spyOn(event, 'preventDefault'); + const ticketId = 999; + controller.showTicketDescriptor(event, ticketId); + + expect(controller.$.ticketDescriptor.ticketFk).toEqual(ticketId); + expect(controller.$.ticketDescriptor.show).toHaveBeenCalledWith(); + expect(event.preventDefault).toHaveBeenCalledWith(); + }); + }); + + describe('showClientDescriptor()', () => { + it('should call the descriptor show method after setting the parent and the client id', () => { + controller.$.clientDescriptor = {show: () => {}}; + spyOn(controller.$.clientDescriptor, 'show'); + const event = {target: {}, preventDefault: () => {}}; + spyOn(event, 'preventDefault'); + const clientId = 999; + controller.showClientDescriptor(event, clientId); + + expect(controller.$.clientDescriptor.clientFk).toEqual(clientId); + expect(controller.$.clientDescriptor.show).toHaveBeenCalledWith(); + expect(event.preventDefault).toHaveBeenCalledWith(); + }); + }); + + describe('openPossibleTicketsDialog()', () => { + it('should call both refresh and show methods in posible tickets model and dialog', () => { + controller.$.possibleTicketsModel = {refresh: () => {}}; + spyOn(controller.$.possibleTicketsModel, 'refresh'); + controller.$.possibleTicketsDialog = {show: () => {}}; + spyOn(controller.$.possibleTicketsDialog, 'show'); + + controller.openPossibleTicketsDialog(); + + expect(controller.$.possibleTicketsModel.refresh).toHaveBeenCalledWith(); + expect(controller.$.possibleTicketsDialog.show).toHaveBeenCalledWith(); + }); + }); + + describe('setTicketsRoute()', () => { + it('should perform a POST query to add tickets to the route', done => { + controller.$.possibleTicketsModel = {save: () => {}}; + spyOn(controller.$.possibleTicketsModel, 'save').and.returnValue(Promise.resolve()); + controller.$.model = {data: [ + {id: 1, checked: false} + ]}; + + controller.route = {id: 111}; + + controller.possibleTickets = [ + {id: 2, checked: false}, + {id: 3, checked: true}, + {id: 4, checked: false}, + {id: 5, checked: true}, + ]; + + let expectedResult = [ + {checked: false, id: 1}, + {id: 3, routeFk: 111}, + {id: 5, routeFk: 111} + ]; + + controller.setTicketsRoute('accept').then(() => { + expect(controller.$.model.data).toEqual(expectedResult); + done(); + }).catch(done.fail); + }); + + it('should just return a promise', () => { + expect(controller.setTicketsRoute('cancel')).toEqual(jasmine.any(Promise)); + }); + }); +}); diff --git a/modules/route/front/tickets/locale/es.yml b/modules/route/front/tickets/locale/es.yml new file mode 100644 index 000000000..02f9eed08 --- /dev/null +++ b/modules/route/front/tickets/locale/es.yml @@ -0,0 +1,8 @@ +Remove ticket: Eliminar ticket +Open buscaman: Abrir buscaman +Ticket removed from route: Ticket quitado de la ruta +Order changed: Orden cambiado +Delete ticket from route?: ¿Quitar el ticket de la ruta? +Sort routes: Ordenar rutas +Add ticket: Añadir ticket +Tickets to add: Tickets a añadir \ No newline at end of file diff --git a/modules/route/front/tickets/style.scss b/modules/route/front/tickets/style.scss new file mode 100644 index 000000000..2c287ed9d --- /dev/null +++ b/modules/route/front/tickets/style.scss @@ -0,0 +1,6 @@ +@import "variables"; + +vn-route-tickets form{ + margin: 0 auto; + max-width: $width-lg; +} \ No newline at end of file diff --git a/modules/ticket/back/methods/expedition/filter.js b/modules/ticket/back/methods/expedition/filter.js new file mode 100644 index 000000000..3ff2fcb59 --- /dev/null +++ b/modules/ticket/back/methods/expedition/filter.js @@ -0,0 +1,51 @@ +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accessType: 'READ', + accepts: [ + { + arg: 'filter', + type: 'Object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + http: {source: 'query'}, + }, + ], + returns: { + type: ['Object'], + root: true, + }, + http: { + path: `/filter`, + verb: 'GET', + }, + }); + + Self.filter = async filter => { + const stmt = new ParameterizedSQL( + `SELECT + e.id, + e.ticketFk, + e.isBox, + e.workerFk, + i1.name namePackage, + e.counter, + e.checked, + i2.name nameBox, + e.itemFk, + u.nickname userNickname, + e.created, + e.externalId + FROM + vn.expedition e + LEFT JOIN vn.item i2 ON i2.id = e.itemFk + INNER JOIN vn.item i1 ON i1.id = e.isBox + LEFT JOIN vn.worker w ON w.id = e.workerFk + LEFT JOIN account.user u ON u.id = w.userFk + `); + stmt.merge(Self.buildSuffix(filter, 'e')); + + return await Self.rawStmt(stmt); + }; +}; diff --git a/modules/ticket/back/methods/packaging/listPackaging.js b/modules/ticket/back/methods/packaging/listPackaging.js new file mode 100644 index 000000000..174630f29 --- /dev/null +++ b/modules/ticket/back/methods/packaging/listPackaging.js @@ -0,0 +1,38 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('listPackaging', { + description: 'Returns all packages including item', + accessType: 'READ', + accepts: [{ + arg: 'filter', + type: 'Object', + required: false, + description: 'Filter defining where and paginated data', + http: {source: 'query'} + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/listPackaging`, + verb: 'get' + } + }); + + Self.listPackaging = async filter => { + let conn = Self.dataSource.connector; + let stmt = new ParameterizedSQL( + `SELECT name, itemFk, packagingFk + FROM (SELECT i.name, i.id itemFk, p.id packagingFk + FROM item i + JOIN packaging p ON i.id = p.itemFk + WHERE i.name <> '' AND p.isPackageReturnable) p` + ); + + stmt.merge(conn.makeSuffix(filter)); + return conn.executeStmt(stmt); + }; +}; diff --git a/modules/ticket/back/methods/packaging/specs/listPackaging.spec.js b/modules/ticket/back/methods/packaging/specs/listPackaging.spec.js new file mode 100644 index 000000000..048d16c04 --- /dev/null +++ b/modules/ticket/back/methods/packaging/specs/listPackaging.spec.js @@ -0,0 +1,12 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket listPackaging()', () => { + it('should call the listPackaging method and return the response', async() => { + let filter = {where: {packagingFk: 1}}; + let response = await app.models.Packaging.listPackaging(filter); + + expect(response[0].name).toBeDefined(); + expect(response[0].name).toEqual('Container ammo box 1m'); + }); +}); + diff --git a/modules/ticket/back/methods/sale-tracking/listSaleTracking.js b/modules/ticket/back/methods/sale-tracking/listSaleTracking.js new file mode 100644 index 000000000..8d3e0c248 --- /dev/null +++ b/modules/ticket/back/methods/sale-tracking/listSaleTracking.js @@ -0,0 +1,66 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('listSaleTracking', { + description: 'Returns all ticket sale trackings', + accessType: 'READ', + accepts: [{ + arg: 'filter', + type: 'Object', + description: 'Filter defining where and paginated data' + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/listSaleTracking`, + verb: 'get' + } + }); + + Self.listSaleTracking = async filter => { + let stmt = new ParameterizedSQL(` + SELECT + st.id, + s.ticketFk, + s.quantity, + s.concept, + s.itemFk, + st.originalQuantity, + st.created, + st.workerFk, + u.nickname userNickname, + ste.name AS state + FROM saleTracking st + JOIN sale s ON s.id = st.saleFk + JOIN worker w ON w.id = st.workerFk + JOIN account.user u ON u.id = w.userFk + JOIN state ste ON ste.id = st.stateFk`); + + stmt.merge(Self.makeSuffix(filter)); + + let trackings = await Self.rawStmt(stmt); + + let salesFilter = { + include: [ + { + relation: 'item' + } + ], + where: {ticketFk: filter.where.ticketFk} + }; + + let sales = await Self.app.models.Sale.find(salesFilter); + + trackings.forEach(tracking => { + sales.forEach(sale => { + if (tracking.itemFk == sale.itemFk) + tracking.item = sale.item(); + }); + }); + + return trackings; + }; +}; diff --git a/modules/ticket/back/methods/sale-tracking/specs/listSaleTracking.spec.js b/modules/ticket/back/methods/sale-tracking/specs/listSaleTracking.spec.js new file mode 100644 index 000000000..0d9937f89 --- /dev/null +++ b/modules/ticket/back/methods/sale-tracking/specs/listSaleTracking.spec.js @@ -0,0 +1,17 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket listSaleTracking()', () => { + it('should call the listSaleTracking method and return the response', async() => { + let filter = {where: {ticketFk: 1}}; + let result = await app.models.SaleTracking.listSaleTracking(filter); + + expect(result[0].concept).toEqual('Ranged weapon longbow 2m'); + }); + + it(`should call the listSaleTracking method and return zero if doesn't have lines`, async() => { + let filter = {where: {ticketFk: 2}}; + let result = await app.models.SaleTracking.listSaleTracking(filter); + + expect(result.length).toEqual(0); + }); +}); diff --git a/modules/ticket/back/methods/sale/getClaimableFromTicket.js b/modules/ticket/back/methods/sale/getClaimableFromTicket.js new file mode 100644 index 000000000..adfb91710 --- /dev/null +++ b/modules/ticket/back/methods/sale/getClaimableFromTicket.js @@ -0,0 +1,44 @@ +module.exports = Self => { + Self.remoteMethod('getClaimableFromTicket', { + description: 'Gets the claimable sales for a client', + accessType: 'READ', + accepts: [{ + arg: 'ticketFk', + type: 'Number', + required: true, + description: 'ticketFk' + }], + returns: { + type: 'string', + root: true + }, + http: { + path: `/getClaimableFromTicket`, + verb: 'GET' + } + }); + + Self.getClaimableFromTicket = async ticketFk => { + let query = `SELECT + s.id AS saleFk, + t.id AS ticketFk, + t.landed, + s.concept, + s.itemFk, + s.quantity, + s.price, + s.discount, + t.nickname + FROM vn.ticket t + INNER JOIN vn.sale s ON s.ticketFk = t.id + LEFT JOIN vn.claimBeginning cb ON cb.saleFk = s.id + + WHERE (t.landed) >= TIMESTAMPADD(DAY, -7, CURDATE()) + AND t.id = ? AND cb.id IS NULL + ORDER BY t.landed DESC, t.id DESC`; + + let claimableSales = await Self.rawSql(query, [ticketFk]); + + return claimableSales; + }; +}; diff --git a/modules/ticket/back/methods/sale/recalculatePrice.js b/modules/ticket/back/methods/sale/recalculatePrice.js new file mode 100644 index 000000000..9ad7e68e7 --- /dev/null +++ b/modules/ticket/back/methods/sale/recalculatePrice.js @@ -0,0 +1,34 @@ +const UserError = require('vn-loopback/util/user-error'); +module.exports = Self => { + Self.remoteMethodCtx('recalculatePrice', { + description: 'Calculates the price of a sale and its components', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + description: 'The sale id', + type: 'number', + required: true, + http: {source: 'path'} + }], + returns: { + type: 'Number', + root: true + }, + http: { + path: `/:id/recalculatePrice`, + verb: 'post' + } + }); + + Self.recalculatePrice = async(ctx, id) => { + const models = Self.app.models; + + const sale = await Self.findById(id); + const isEditable = await models.Ticket.isEditable(ctx, sale.ticketFk); + + if (!isEditable) + throw new UserError(`The sales of this ticket can't be modified`); + + return Self.rawSql('CALL vn.sale_calculateComponent(?, null)', [id]); + }; +}; diff --git a/modules/ticket/back/methods/sale/removes.js b/modules/ticket/back/methods/sale/removes.js new file mode 100644 index 000000000..f4385072f --- /dev/null +++ b/modules/ticket/back/methods/sale/removes.js @@ -0,0 +1,35 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('removes', { + description: 'Change the state of a ticket', + accessType: 'WRITE', + accepts: [{ + arg: 'params', + type: 'object', + required: true, + description: '[sales IDs], actualTicketFk', + http: {source: 'body'} + }], + returns: { + type: 'string', + root: true + }, + http: { + path: `/removes`, + verb: 'post' + } + }); + + Self.removes = async(ctx, params) => { + let thisTicketIsEditable = await Self.app.models.Ticket.isEditable(ctx, params.actualTicketFk); + if (!thisTicketIsEditable) + throw new UserError(`The sales of this ticket can't be modified`); + + let promises = []; + for (let i = 0; i < params.sales.length; i++) + promises.push(Self.app.models.Sale.destroyById(params.sales[i].id)); + + return Promise.all(promises); + }; +}; diff --git a/modules/ticket/back/methods/sale/reserve.js b/modules/ticket/back/methods/sale/reserve.js new file mode 100644 index 000000000..7e6a6bb3a --- /dev/null +++ b/modules/ticket/back/methods/sale/reserve.js @@ -0,0 +1,33 @@ + +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('reserve', { + description: 'Change the state of a ticket', + accessType: 'WRITE', + accepts: [{ + arg: 'params', + type: 'object', + required: true, + description: '[sales IDs], ticketFk, reserved', + http: {source: 'body'} + }], + returns: { + type: 'string', + root: true + }, + http: { + path: `/reserve`, + verb: 'post' + } + }); + + Self.reserve = async(ctx, params) => { + let thisTicketIsEditable = await Self.app.models.Ticket.isEditable(ctx, params.ticketFk); + if (!thisTicketIsEditable) + throw new UserError(`The sales of this ticket can't be modified`); + + for (let i = 0; i < params.sales.length; i++) + await Self.app.models.Sale.update({id: params.sales[i].id}, {reserved: params.reserved}); + }; +}; diff --git a/modules/ticket/back/methods/sale/specs/getClaimableFromTicket.spec.js b/modules/ticket/back/methods/sale/specs/getClaimableFromTicket.spec.js new file mode 100644 index 000000000..b12c22084 --- /dev/null +++ b/modules/ticket/back/methods/sale/specs/getClaimableFromTicket.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('sale getClaimableFromTicket()', () => { + it('should return the claimable sales of a given ticket', async() => { + let claimableFromTicket = await app.models.Sale.getClaimableFromTicket(16); + + expect(claimableFromTicket[0].concept).toBe('Ranged weapon longbow 2m'); + expect(claimableFromTicket.length).toBe(3); + }); +}); diff --git a/modules/ticket/back/methods/sale/specs/recalculatePrice.spec.js b/modules/ticket/back/methods/sale/specs/recalculatePrice.spec.js new file mode 100644 index 000000000..23d7d721b --- /dev/null +++ b/modules/ticket/back/methods/sale/specs/recalculatePrice.spec.js @@ -0,0 +1,24 @@ +const app = require('vn-loopback/server/server'); + +describe('sale recalculatePrice()', () => { + const saleId = 7; + + it('should update the sale price', async() => { + const ctx = {req: {accessToken: {userId: 9}}}; + const response = await app.models.Sale.recalculatePrice(ctx, saleId); + + expect(response.affectedRows).toBeDefined(); + }); + + it('should throw an error if the ticket is not editable', async() => { + const ctx = {req: {accessToken: {userId: 9}}}; + const immutableSaleId = 1; + await app.models.Sale.recalculatePrice(ctx, immutableSaleId) + .catch(response => { + expect(response).toEqual(new Error(`The sales of this ticket can't be modified`)); + error = response; + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/modules/ticket/back/methods/sale/specs/removes.spec.js b/modules/ticket/back/methods/sale/specs/removes.spec.js new file mode 100644 index 000000000..a12bc54ee --- /dev/null +++ b/modules/ticket/back/methods/sale/specs/removes.spec.js @@ -0,0 +1,44 @@ +const app = require('vn-loopback/server/server'); + +describe('sale removes()', () => { + let sale; + let newsale; + + beforeAll(async done => { + sale = await app.models.Sale.findOne({where: {id: 9}}); + sale.id = null; + newsale = await app.models.Sale.create(sale); + + done(); + }); + + it('should throw an error if the ticket of the given sales is not editable', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let error; + + let params = { + sales: [{id: 1, instance: 0}, {id: 2, instance: 1}], + actualTicketFk: 2 + }; + + try { + await app.models.Sale.removes(ctx, params); + } catch (e) { + error = e; + } + + expect(error).toEqual(new Error(`The sales of this ticket can't be modified`)); + }); + + it('should delete the sales', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let params = { + sales: [{id: newsale.id, instance: 0}], + actualTicketFk: 16 + }; + + let res = await app.models.Sale.removes(ctx, params); + + expect(res).toEqual([{count: 1}]); + }); +}); diff --git a/modules/ticket/back/methods/sale/specs/reserve.spec.js b/modules/ticket/back/methods/sale/specs/reserve.spec.js new file mode 100644 index 000000000..a86d357a8 --- /dev/null +++ b/modules/ticket/back/methods/sale/specs/reserve.spec.js @@ -0,0 +1,57 @@ +const app = require('vn-loopback/server/server'); + +describe('sale reserve()', () => { + afterAll(async done => { + let ctx = {req: {accessToken: {userId: 9}}}; + let params = { + sales: [ + {id: 7}, + {id: 8}], + ticketFk: 11, + reserved: false + }; + + await app.models.Sale.reserve(ctx, params); + + done(); + }); + + it('should throw an error if the ticket can not be modified', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let error; + let params = {ticketFk: 2, + sales: [{id: 5}], + reserved: false}; + + await app.models.Sale.reserve(ctx, params) + .catch(response => { + expect(response).toEqual(new Error(`The sales of this ticket can't be modified`)); + error = response; + }); + + expect(error).toBeDefined(); + }); + + it('should update the given sales of a ticket to reserved', async() => { + originalTicketSales = await app.models.Ticket.getSales(11); + + expect(originalTicketSales[0].reserved).toEqual(0); + expect(originalTicketSales[1].reserved).toEqual(0); + + let ctx = {req: {accessToken: {userId: 9}}}; + let params = { + sales: [ + {id: 7}, + {id: 8}], + ticketFk: 11, + reserved: true + }; + + await app.models.Sale.reserve(ctx, params); + + let reservedTicketSales = await app.models.Ticket.getSales(11); + + expect(reservedTicketSales[0].reserved).toEqual(1); + expect(reservedTicketSales[1].reserved).toEqual(1); + }); +}); diff --git a/modules/ticket/back/methods/sale/specs/updateConcept.spec.js b/modules/ticket/back/methods/sale/specs/updateConcept.spec.js new file mode 100644 index 000000000..d383cc948 --- /dev/null +++ b/modules/ticket/back/methods/sale/specs/updateConcept.spec.js @@ -0,0 +1,39 @@ +const app = require('vn-loopback/server/server'); + +describe('sale updateConcept()', () => { + const saleId = 1; + let originalSale; + + beforeAll(async done => { + originalSale = await app.models.Sale.findById(saleId); + + done(); + }); + + afterAll(async done => { + await originalSale.save(); + + done(); + }); + + it('should throw if ID was undefined', async() => { + let err; + const newConcept = 'I am he new concept'; + + try { + await app.models.Sale.updateConcept(undefined, newConcept); + } catch (e) { + err = e; + } + + expect(err).toBeDefined(); + }); + + it('should update the sale concept', async() => { + const newConcept = 'I am the new concept'; + + let response = await app.models.Sale.updateConcept(saleId, newConcept); + + expect(response.concept).toEqual(newConcept); + }); +}); diff --git a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js new file mode 100644 index 000000000..37930f1b3 --- /dev/null +++ b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js @@ -0,0 +1,79 @@ +const app = require('vn-loopback/server/server'); + +describe('sale updatePrice()', () => { + let originalSale; + let originalSalesPersonMana; + let createdSaleComponent; + let saleId = 7; + let manaComponentId; + + beforeAll(async done => { + let componentRate = await app.models.ComponentRate.findOne({where: {code: 'mana'}}); + manaComponentId = componentRate.id; + originalSale = await app.models.Sale.findById(saleId); + originalSalesPersonMana = await app.models.WorkerMana.findById(18); + + done(); + }); + + afterAll(async done => { + await originalSale.save(); + await app.models.SaleComponent.updateAll({componentFk: manaComponentId, saleFk: saleId}, {value: 0}); + await originalSalesPersonMana.save(); + + done(); + }); + + + it('should throw an error if the ticket is not editable', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let immutableSaleId = 1; + let price = 5; + + await app.models.Sale.updatePrice(ctx, immutableSaleId, price) + .catch(response => { + expect(response).toEqual(new Error(`The sales of this ticket can't be modified`)); + error = response; + }); + + expect(error).toBeDefined(); + }); + + it('should return 0 if the price is an empty string', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let price = ''; + + await app.models.Sale.updatePrice(ctx, saleId, price); + let saleUpdated = await app.models.Sale.findById(saleId); + + expect(saleUpdated.price).toEqual(0); + }); + + it('should now set price as a decimal number in a string', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let price = '8'; + + await app.models.Sale.updatePrice(ctx, saleId, price); + let saleUpdated = await app.models.Sale.findById(saleId); + + expect(saleUpdated.price).toEqual(8); + }); + + it('should set price as a decimal number and check the sale has the mana component', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let price = 5.4; + + await app.models.Sale.updatePrice(ctx, saleId, price); + let saleUpdated = await app.models.Sale.findById(saleId); + createdSaleComponent = await app.models.SaleComponent.findOne({where: {saleFk: saleId, componentFk: manaComponentId}}); + + expect(saleUpdated.price).toBe(price); + expect(createdSaleComponent.value).toEqual(-2.04); + }); + + it('should check that the mana of salesPerson changed', async() => { + let updatedSalesPersonMana = await app.models.WorkerMana.findById(18); + + expect(updatedSalesPersonMana.amount).not.toEqual(originalSalesPersonMana.amount); + }); +}); diff --git a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js new file mode 100644 index 000000000..ccb73d779 --- /dev/null +++ b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js @@ -0,0 +1,45 @@ +const app = require('vn-loopback/server/server'); + +describe('sale updateQuantity()', () => { + it('should throw an error if the quantity is not a number', async() => { + let error; + + await app.models.Sale.updateQuantity(1, 'wrong quantity!') + .catch(response => { + expect(response).toEqual(new Error('The value should be a number')); + error = response; + }); + + expect(error).toBeDefined(); + }); + + it('should throw an error if the quantity is greater than it should be', async() => { + let error; + + await app.models.Sale.updateQuantity(1, 99) + .catch(response => { + expect(response).toEqual(new Error('The new quantity should be smaller than the old one')); + error = response; + }); + + expect(error).toBeDefined(); + }); + + it('should update the quantity of a given sale current line', async() => { + let originalLineData = await app.models.Sale.findOne({where: {id: 1}, fields: ['quantity']}); + + expect(originalLineData.quantity).toEqual(5); + + await app.models.Sale.updateQuantity(1, 4); + + let modifiedLineData = await app.models.Sale.findOne({where: {id: 1}, fields: ['quantity']}); + + expect(modifiedLineData.quantity).toEqual(4); + + await app.models.Sale.update({id: 1}, {quantity: 5}); + + let resetLineDataValues = await app.models.Sale.findOne({where: {id: 1}, fields: ['quantity']}); + + expect(resetLineDataValues.quantity).toEqual(5); + }); +}); diff --git a/modules/ticket/back/methods/sale/updateConcept.js b/modules/ticket/back/methods/sale/updateConcept.js new file mode 100644 index 000000000..d95cf1202 --- /dev/null +++ b/modules/ticket/back/methods/sale/updateConcept.js @@ -0,0 +1,32 @@ +module.exports = Self => { + Self.remoteMethod('updateConcept', { + description: 'Updates the concept of a sale', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'sale ID', + http: {source: 'path'} + }, { + arg: 'newConcept', + type: 'any', + required: true, + description: 'new concept' + }], + returns: { + type: 'string', + root: true + }, + http: { + path: `/:id/updateConcept`, + verb: 'post' + } + }); + + Self.updateConcept = async(id, newConcept) => { + let currentLine = await Self.app.models.Sale.findById(id); + + return await currentLine.updateAttributes({concept: newConcept}); + }; +}; diff --git a/modules/ticket/back/methods/sale/updatePrice.js b/modules/ticket/back/methods/sale/updatePrice.js new file mode 100644 index 000000000..60a171e17 --- /dev/null +++ b/modules/ticket/back/methods/sale/updatePrice.js @@ -0,0 +1,97 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('updatePrice', { + description: 'Changes the price of a sale', + accessType: 'WRITE', + accepts: [ + { + arg: 'id', + description: 'The sale id', + type: 'number', + required: true, + http: {source: 'path'} + }, { + arg: 'newPrice', + description: 'The new price', + type: 'number', + required: true + } + ], + returns: { + type: 'Number', + root: true + }, + http: { + path: `/:id/updatePrice`, + verb: 'post' + } + }); + + Self.updatePrice = async(ctx, id, newPrice) => { + let models = Self.app.models; + let tx = await Self.beginTransaction({}); + + try { + let options = {transaction: tx}; + + let filter = { + include: { + relation: 'ticket', + scope: { + include: { + relation: 'client', + scope: { + fields: ['salesPersonFk'] + } + }, + fields: ['id', 'clientFk'] + } + } + }; + let sale = await models.Sale.findById(id, filter, options); + + let isEditable = await models.Ticket.isEditable(ctx, sale.ticketFk); + if (!isEditable) + throw new UserError(`The sales of this ticket can't be modified`); + + let salesPerson = sale.ticket().client().salesPersonFk; + let usesMana = await models.WorkerMana.findOne({where: {workerFk: salesPerson}, fields: 'amount'}, options); + let componentCode = usesMana ? 'mana' : 'buyerDiscount'; + + let discount = await models.ComponentRate.findOne({where: {code: componentCode}}, options); + let componentId = discount.id; + let componentValue = newPrice - sale.price; + + let where = { + componentFk: componentId, + saleFk: id + }; + let saleComponent = await models.SaleComponent.findOne({where}, options); + + if (saleComponent) { + await models.SaleComponent.updateAll(where, { + value: saleComponent.value + componentValue + }, options); + } else { + await models.SaleComponent.create({ + saleFk: id, + componentFk: componentId, + value: componentValue + }, options); + } + + await sale.updateAttributes({price: newPrice}, options); + + query = `call vn.manaSpellersRequery(?)`; + await Self.rawSql(query, [salesPerson], options); + + await tx.commit(); + + return sale; + } catch (error) { + await tx.rollback(); + throw error; + } + }; +}; diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js new file mode 100644 index 000000000..c25aa9007 --- /dev/null +++ b/modules/ticket/back/methods/sale/updateQuantity.js @@ -0,0 +1,39 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethod('updateQuantity', { + description: 'Changes the quantity of a sale', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'sale ID', + http: {source: 'path'} + }, { + arg: 'quantity', + type: 'number', + required: true, + description: 'newQuantity' + }], + returns: { + type: 'string', + root: true + }, + http: { + path: `/:id/updateQuantity`, + verb: 'post' + } + }); + + Self.updateQuantity = async(id, quantity) => { + if (isNaN(quantity)) + throw new UserError(`The value should be a number`); + + let currentLine = await Self.app.models.Sale.findOne({where: {id: id}}); + if (quantity > currentLine.quantity) + throw new UserError('The new quantity should be smaller than the old one'); + + return await currentLine.updateAttributes({quantity: quantity}); + }; +}; diff --git a/modules/ticket/back/methods/state/editableStates.js b/modules/ticket/back/methods/state/editableStates.js new file mode 100644 index 000000000..4979f4819 --- /dev/null +++ b/modules/ticket/back/methods/state/editableStates.js @@ -0,0 +1,36 @@ + +module.exports = Self => { + Self.remoteMethodCtx('editableStates', { + description: 'Gets the editable states according the user role ', + accessType: 'READ', + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/editableStates`, + verb: 'GET' + } + }); + + Self.editableStates = async ctx => { + let userId = ctx.req.accessToken.userId; + let models = Self.app.models; + let statesList = await models.State.find(); + + let isProduction = await models.Account.hasRole(userId, 'production'); + let isSalesPerson = await models.Account.hasRole(userId, 'salesPerson'); + let isAdministrative = await models.Account.hasRole(userId, 'administrative'); + + if (isProduction || isAdministrative) + return statesList; + + if (isSalesPerson) { + return statesList = statesList.filter(stateList => + stateList.alertLevel === 0 || stateList.code === 'PICKER_DESIGNED' + ); + } + + return statesList.filter(stateList => stateList.alertLevel === 0); + }; +}; diff --git a/modules/ticket/back/methods/state/isEditable.js b/modules/ticket/back/methods/state/isEditable.js new file mode 100644 index 000000000..00b4f4c4f --- /dev/null +++ b/modules/ticket/back/methods/state/isEditable.js @@ -0,0 +1,37 @@ +module.exports = Self => { + Self.remoteMethodCtx('isEditable', { + description: 'Check if the ticket state is editable', + accessType: 'READ', + accepts: [{ + arg: 'stateId', + type: 'number', + required: true, + http: {source: 'path'} + }], + returns: { + type: 'boolean', + root: true + }, + http: { + path: `/:stateId/isEditable`, + verb: 'get' + } + }); + + Self.isEditable = async(ctx, stateId) => { + const accessToken = ctx.req.accessToken; + const models = Self.app.models; + const userId = accessToken.userId; + + let isProduction = await models.Account.hasRole(userId, 'production'); + let isSalesPerson = await models.Account.hasRole(userId, 'salesPerson'); + let isAdministrative = await models.Account.hasRole(userId, 'administrative'); + let state = await models.State.findById(stateId); + + + let salesPersonAllowed = (isSalesPerson && state.code == 'PICKER_DESIGNED'); + + let isAllowed = isProduction || isAdministrative || salesPersonAllowed || state.alertLevel == 0; + return isAllowed; + }; +}; diff --git a/modules/ticket/back/methods/state/specs/editableState.spec.js b/modules/ticket/back/methods/state/specs/editableState.spec.js new file mode 100644 index 000000000..54dbdfcae --- /dev/null +++ b/modules/ticket/back/methods/state/specs/editableState.spec.js @@ -0,0 +1,32 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket editableStates()', () => { + it('should return the expected state for the given role', async() => { + const productionRole = 49; + const ctx = {req: {accessToken: {userId: productionRole}}}; + let result = await app.models.State.editableStates(ctx); + let deliveredState = result.some(state => state.code == 'DELIVERED'); + + expect(deliveredState).toBeTruthy(); + }); + + it(`should returns the expected states by a specific role`, async() => { + const productionRole = 18; + const ctx = {req: {accessToken: {userId: productionRole}}}; + let result = await app.models.State.editableStates(ctx); + let deliveredState = result.some(state => state.code == 'DELIVERED'); + let pickerDesignedState = result.some(state => state.code == 'PICKER_DESIGNED'); + + expect(deliveredState).toBeFalsy(); + expect(pickerDesignedState).toBeTruthy(); + }); + + it(`should return again the expected state by a specific role`, async() => { + const employeeRole = 1; + const ctx = {req: {accessToken: {userId: employeeRole}}}; + let result = await app.models.State.editableStates(ctx); + let pickerDesignedState = result.some(state => state.code == 'PICKER_DESIGNED'); + + expect(pickerDesignedState).toBeFalsy(); + }); +}); diff --git a/modules/ticket/back/methods/state/specs/isEditable.spec.js b/modules/ticket/back/methods/state/specs/isEditable.spec.js new file mode 100644 index 000000000..b90cc8eee --- /dev/null +++ b/modules/ticket/back/methods/state/specs/isEditable.spec.js @@ -0,0 +1,48 @@ +const app = require('vn-loopback/server/server'); + +describe('state isEditable()', () => { + it('should return false if the given state is not editable by a specific role', async() => { + const salesPersonRole = 18; + const onDeliveryState = 13; + let ctx = {req: {accessToken: {userId: salesPersonRole}}}; + let result = await app.models.State.isEditable(ctx, onDeliveryState); + + expect(result).toBeFalsy(); + }); + + it('should return true if the given state is editable by a specific role', async() => { + const salesPersonRole = 18; + const asignedState = 20; + let ctx = {req: {accessToken: {userId: salesPersonRole}}}; + let result = await app.models.State.isEditable(ctx, asignedState); + + expect(result).toBeTruthy(); + }); + + it('should return true again if the given state is editable by a specific role', async() => { + const employeeRole = 1; + const fixingState = 1; + let ctx = {req: {accessToken: {userId: employeeRole}}}; + let result = await app.models.State.isEditable(ctx, fixingState); + + expect(result).toBeTruthy(); + }); + + it('should return false if the given state is not editable for the given role', async() => { + const employeeRole = 1; + const asignedState = 20; + let ctx = {req: {accessToken: {userId: employeeRole}}}; + let result = await app.models.State.isEditable(ctx, asignedState); + + expect(result).toBeFalsy(); + }); + + it('should return true if the given state is editable for the given role', async() => { + const productionRole = 49; + const checkedState = 13; + let ctx = {req: {accessToken: {userId: productionRole}}}; + let result = await app.models.State.isEditable(ctx, checkedState); + + expect(result).toBeTruthy(); + }); +}); diff --git a/modules/ticket/back/methods/ticket-dms/allowedContentTypes.js b/modules/ticket/back/methods/ticket-dms/allowedContentTypes.js new file mode 100644 index 000000000..2f5183f92 --- /dev/null +++ b/modules/ticket/back/methods/ticket-dms/allowedContentTypes.js @@ -0,0 +1,23 @@ +module.exports = Self => { + Self.remoteMethodCtx('allowedContentTypes', { + description: 'Returns a list of allowed contentTypes', + accessType: 'READ', + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/allowedContentTypes`, + verb: 'GET' + } + }); + + Self.allowedContentTypes = async() => { + const storageConnector = Self.app.dataSources.storage.connector; + const allowedContentTypes = storageConnector.allowedContentTypes; + const modelAllowedContentTypes = Self.definition.settings.allowedContentTypes; + + return modelAllowedContentTypes || allowedContentTypes; + }; +}; + diff --git a/modules/ticket/back/methods/ticket-dms/removeFile.js b/modules/ticket/back/methods/ticket-dms/removeFile.js new file mode 100644 index 000000000..52a0c524f --- /dev/null +++ b/modules/ticket/back/methods/ticket-dms/removeFile.js @@ -0,0 +1,33 @@ +module.exports = Self => { + Self.remoteMethodCtx('removeFile', { + description: 'Removes a ticket document', + accessType: 'WRITE', + accepts: { + arg: 'id', + type: 'Number', + description: 'The document id', + http: {source: 'path'} + }, + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/removeFile`, + verb: 'POST' + } + }); + + Self.removeFile = async(ctx, id) => { + const models = Self.app.models; + const targetTicketDms = await models.TicketDms.findById(id); + const targetDms = await models.Dms.findById(targetTicketDms.dmsFk); + const trashDmsType = await models.DmsType.findOne({where: {code: 'trash'}}); + + await models.Dms.removeFile(ctx, targetTicketDms.dmsFk); + await targetTicketDms.destroy(); + + return targetDms.updateAttribute('dmsTypeFk', trashDmsType.id); + }; +}; + diff --git a/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js b/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js new file mode 100644 index 000000000..b1cd5686a --- /dev/null +++ b/modules/ticket/back/methods/ticket-dms/specs/removeFile.spec.js @@ -0,0 +1,18 @@ +const app = require('vn-loopback/server/server'); + +describe('TicketDms removeFile()', () => { + const ticketDmsId = 1; + it(`should return an error for a user without enough privileges`, async() => { + let clientId = 101; + let ctx = {req: {accessToken: {userId: clientId}}}; + + let error; + await app.models.TicketDms.removeFile(ctx, ticketDmsId).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`You don't have enough privileges`); + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/modules/ticket/back/methods/ticket-request/confirm.js b/modules/ticket/back/methods/ticket-request/confirm.js new file mode 100644 index 000000000..72c41737a --- /dev/null +++ b/modules/ticket/back/methods/ticket-request/confirm.js @@ -0,0 +1,100 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('confirm', { + description: '', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'Integer', + required: true, + description: 'The request ID', + }, { + arg: 'itemFk', + type: 'Integer', + required: true, + description: 'The requested item ID', + }, { + arg: 'quantity', + type: 'Integer', + required: true, + description: 'The requested item quantity', + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/confirm`, + verb: 'post' + } + }); + + Self.confirm = async ctx => { + const models = Self.app.models; + let sale; + let tx = await Self.beginTransaction({}); + + try { + let options = {transaction: tx}; + + let item = await models.Item.findById(ctx.args.itemFk, null, options); + if (!item) + throw new UserError(`That item doesn't exists`); + + let request = await models.TicketRequest.findById(ctx.args.id, { + include: {relation: 'ticket'} + }, options); + + let [[stock]] = await Self.rawSql(`CALL vn.item_getVisibleAvailable(?,?,?,?)`, [ + ctx.args.itemFk, + request.ticket().shipped, + request.ticket().warehouseFk, + false + ], options); + + if (stock.available < 0) + throw new UserError(`This item is not available`); + + + if (request.saleFk) { + sale = await models.Sale.findById(request.saleFk, null, options); + sale.updateAttributes({ + itemFk: ctx.args.itemFk, + quantity: ctx.args.quantity, + concept: item.name, + }, options); + } else { + sale = await models.Sale.create({ + ticketFk: request.ticketFk, + itemFk: ctx.args.itemFk, + quantity: ctx.args.quantity, + concept: item.name + }, options); + request.updateAttributes({ + saleFk: sale.id, + itemFk: sale.itemFk, + isOk: true + }, options); + } + + query = `CALL vn.ticketCalculateSale(?)`; + await Self.rawSql(query, [sale.id], options); + + const message = `Se ha comprado ${sale.quantity} unidades de "${sale.concept}" (#${sale.itemFk}) ` + + `para el ticket #${sale.ticketFk}`; + + await models.Message.send(ctx, { + recipientFk: request.requesterFk, + message: message + }, options); + + await tx.commit(); + + return sale; + } catch (error) { + await tx.rollback(); + throw error; + } + }; +}; diff --git a/modules/ticket/back/methods/ticket-request/deny.js b/modules/ticket/back/methods/ticket-request/deny.js new file mode 100644 index 000000000..e663ef1bc --- /dev/null +++ b/modules/ticket/back/methods/ticket-request/deny.js @@ -0,0 +1,39 @@ +module.exports = Self => { + Self.remoteMethodCtx('deny', { + description: 'sets a ticket request to denied and returns the changes', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'Integer', + required: true, + description: 'The request ID', + }, { + arg: 'observation', + type: 'String', + required: true, + description: 'The request observation', + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/:id/deny`, + verb: 'post' + } + }); + + Self.deny = async ctx => { + let userId = ctx.req.accessToken.userId; + let worker = await Self.app.models.Worker.findOne({where: {userFk: userId}}); + + let params = { + isOk: false, + attenderFk: worker.id, + response: ctx.args.observation, + }; + + let request = await Self.app.models.TicketRequest.findById(ctx.args.id); + return request.updateAttributes(params); + }; +}; diff --git a/modules/ticket/back/methods/ticket-request/filter.js b/modules/ticket/back/methods/ticket-request/filter.js new file mode 100644 index 000000000..8f1f837d2 --- /dev/null +++ b/modules/ticket/back/methods/ticket-request/filter.js @@ -0,0 +1,142 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const buildFilter = require('vn-loopback/util/filter').buildFilter; +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethod('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accepts: [ + { + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + }, { + arg: 'filter', + type: 'Object', + description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string` + }, { + arg: 'search', + type: 'String', + description: `If it's and integer searchs by id, otherwise it searchs by nickname` + }, { + arg: 'ticketFk', + type: 'Number', + description: `Searchs by ticketFk` + }, { + arg: 'warehouseFk', + type: 'Number', + description: `Search by warehouse` + }, { + arg: 'attenderFk', + type: 'Number', + description: `Search requests atended by the given worker` + }, { + arg: 'mine', + type: 'Boolean', + description: `Search requests attended by the connected worker` + }, { + arg: 'from', + type: 'Date', + description: `Date from` + }, { + arg: 'to', + type: 'Date', + description: `Date to` + }, { + arg: 'isOk', + type: 'Boolean', + description: `Search request by request state` + } + ], + returns: { + type: ['Object'], + root: true + }, + http: { + path: '/filter', + verb: 'GET' + } + }); + + Self.filter = async(ctx, filter) => { + let conn = Self.dataSource.connector; + let userId = ctx.req.accessToken.userId; + let worker = await Self.app.models.Worker.findOne({where: {userFk: userId}}); + + if (ctx.args.mine) + ctx.args.attenderFk = worker.id; + + let where = buildFilter(ctx.args, (param, value) => { + switch (param) { + case 'search': + return /^\d+$/.test(value) + ? {'tr.ticketFk': {inq: value}} + : {'t.nickname': {like: `%${value}%`}}; + case 'ticketFk': + return {'t.id': value}; + case 'attenderFk': + return {'tr.attenderFk': value}; + case 'isOk': + return {'tr.isOk': value}; + case 'clientFk': + return {'t.clientFk': value}; + case 'from': + return {'t.shipped': {gte: value}}; + case 'to': + return {'t.shipped': {lte: value}}; + case 'warehouse': + return {'w.id': value}; + case 'salesPersonFk': + return {'c.salesPersonFk': value}; + } + }); + + if (!where) + where = {}; + where['tw.ticketFk'] = null; + + filter = mergeFilters(filter, {where}); + + let stmt; + + stmt = new ParameterizedSQL( + `SELECT + tr.id, + tr.ticketFk, + tr.quantity, + tr.price, + tr.attenderFk, + tr.description, + tr.response, + tr.saleFk, + tr.isOk, + s.quantity AS saleQuantity, + s.itemFk, + i.name AS itemDescription, + t.shipped, + t.nickname, + t.warehouseFk, + t.clientFk, + w.name AS warehouse, + u.nickname AS salesPersonNickname, + ua.nickname AS atenderNickname, + c.salesPersonFk + FROM ticketRequest tr + LEFT JOIN ticketWeekly tw on tw.ticketFk = tr.ticketFk + LEFT JOIN ticket t ON t.id = tr.ticketFk + LEFT JOIN warehouse w ON w.id = t.warehouseFk + LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN item i ON i.id = tr.itemFk + LEFT JOIN sale s ON s.id = tr.saleFk + LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN account.user u ON u.id = wk.userFk + LEFT JOIN worker wka ON wka.id = tr.attenderFk + LEFT JOIN account.user ua ON ua.id = wka.userFk`); + stmt.merge(conn.makeSuffix(filter)); + + let result = await conn.executeStmt(stmt); + + return result; + }; +}; diff --git a/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js b/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js new file mode 100644 index 000000000..2383fe560 --- /dev/null +++ b/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js @@ -0,0 +1,99 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket-request confirm()', () => { + let originalRequest; + let originalSale; + let createdSaleId; + + afterAll(async done => { + await originalRequest.updateAttributes(originalRequest); + await originalSale.updateAttributes(originalSale); + await app.models.Sale.destroyById(createdSaleId); + done(); + }); + + it(`should throw an error if the item doesn't exist`, async() => { + let ctx = {req: {accessToken: {userId: 9}}, args: {itemFk: 999}}; + let error; + + try { + await app.models.TicketRequest.confirm(ctx); + } catch (err) { + error = err; + } + + expect(error.message).toEqual(`That item doesn't exists`); + }); + + it(`should throw an error if the item is not available`, async() => { + const requestId = 5; + const itemId = 4; + const quantity = 99999; + + let ctx = {req: {accessToken: {userId: 9}}, args: { + itemFk: itemId, + id: requestId, + quantity: quantity + }}; + let error; + + try { + await app.models.TicketRequest.confirm(ctx); + } catch (err) { + error = err; + } + + expect(error.message).toEqual(`This item is not available`); + }); + + it(`should update the sale details if the request already contains a sale id`, async() => { + const requestId = 4; + const saleId = 11; + const itemId = 1; + const quantity = 10; + + originalRequest = await app.models.TicketRequest.findById(requestId); + originalSale = await app.models.Sale.findById(saleId); + + const request = await app.models.TicketRequest.findById(requestId); + await request.updateAttributes({saleFk: saleId}); + + let ctx = {req: {accessToken: {userId: 9}}, args: { + itemFk: itemId, + id: requestId, + quantity: quantity + }}; + + await app.models.TicketRequest.confirm(ctx); + + let updatedSale = await app.models.Sale.findById(saleId); + + expect(updatedSale.itemFk).toEqual(itemId); + expect(updatedSale.quantity).toEqual(quantity); + }); + + it(`should create a new sale for the the request if there's no sale id`, async() => { + const requestId = 4; + const itemId = 1; + const quantity = 10; + + const request = await app.models.TicketRequest.findById(requestId); + await request.updateAttributes({saleFk: null}); + + let ctx = {req: {accessToken: {userId: 9}}, args: { + itemFk: itemId, + id: requestId, + quantity: quantity, + ticketFk: 1 + }}; + + await app.models.TicketRequest.confirm(ctx); + + let updatedRequest = await app.models.TicketRequest.findById(requestId); + createdSaleId = updatedRequest.saleFk; + + expect(updatedRequest.saleFk).toEqual(createdSaleId); + expect(updatedRequest.isOk).toEqual(true); + expect(updatedRequest.itemFk).toEqual(itemId); + }); +}); diff --git a/modules/ticket/back/methods/ticket-request/specs/deny.spec.js b/modules/ticket/back/methods/ticket-request/specs/deny.spec.js new file mode 100644 index 000000000..04152fa21 --- /dev/null +++ b/modules/ticket/back/methods/ticket-request/specs/deny.spec.js @@ -0,0 +1,25 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket-request deny()', () => { + let request; + afterAll(async done => { + let params = { + isOk: null, + attenderFk: request.attenderFk, + response: null, + }; + + await request.updateAttributes(params); + done(); + }); + + it('should return all ticket requests', async() => { + let ctx = {req: {accessToken: {userId: 9}}, args: {id: 4, observation: 'my observation'}}; + + request = await app.models.TicketRequest.findById(ctx.args.id); + + let result = await app.models.TicketRequest.deny(ctx); + + expect(result.id).toEqual(4); + }); +}); diff --git a/modules/ticket/back/methods/ticket-request/specs/filter.spec.js b/modules/ticket/back/methods/ticket-request/specs/filter.spec.js new file mode 100644 index 000000000..329688866 --- /dev/null +++ b/modules/ticket/back/methods/ticket-request/specs/filter.spec.js @@ -0,0 +1,83 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket-request filter()', () => { + it('should return all ticket requests', async() => { + let ctx = {req: {accessToken: {userId: 9}}, args: {}}; + + let result = await app.models.TicketRequest.filter(ctx); + + expect(result.length).toEqual(2); + }); + + it('should return the ticket request matching a generic search value which is the ticket ID', async() => { + let ctx = {req: {accessToken: {userId: 9}}, args: {search: 11}}; + + let result = await app.models.TicketRequest.filter(ctx); + let requestId = result[0].id; + + expect(requestId).toEqual(4); + }); + + it('should return the ticket request matching a generic search value which is the client address alias', async() => { + let ctx = {req: {accessToken: {userId: 9}}, args: {search: 'NY roofs'}}; + + let result = await app.models.TicketRequest.filter(ctx); + let requestId = result[0].id; + + expect(requestId).toEqual(4); + }); + + it('should return the ticket request matching the ticket ID', async() => { + let ctx = {req: {accessToken: {userId: 9}}, args: {ticketFk: 11}}; + + let result = await app.models.TicketRequest.filter(ctx); + let requestId = result[0].id; + + expect(requestId).toEqual(4); + }); + + it('should return the ticket request matching the atender ID', async() => { + let ctx = {req: {accessToken: {userId: 9}}, args: {attenderFk: 35}}; + + let result = await app.models.TicketRequest.filter(ctx); + let requestId = result[0].id; + + expect(requestId).toEqual(4); + }); + + it('should return the ticket request matching the isOk triple-state', async() => { + let ctx = {req: {accessToken: {userId: 9}}, args: {isOk: null}}; + + let result = await app.models.TicketRequest.filter(ctx); + let requestId = result[0].id; + + expect(requestId).toEqual(4); + }); + + it('should return the ticket request matching the client ID', async() => { + let ctx = {req: {accessToken: {userId: 9}}, args: {clientFk: 102}}; + + let result = await app.models.TicketRequest.filter(ctx); + let requestId = result[0].id; + + expect(requestId).toEqual(4); + }); + + it('should return the ticket request matching the warehouse ID', async() => { + let ctx = {req: {accessToken: {userId: 9}}, args: {warehouse: 1}}; + + let result = await app.models.TicketRequest.filter(ctx); + let requestId = result[0].id; + + expect(requestId).toEqual(4); + }); + + it('should return the ticket request matching the salesPerson ID', async() => { + let ctx = {req: {accessToken: {userId: 9}}, args: {salesPersonFk: 18}}; + + let result = await app.models.TicketRequest.filter(ctx); + let requestId = result[0].id; + + expect(requestId).toEqual(4); + }); +}); diff --git a/modules/ticket/back/methods/ticket-tracking/changeState.js b/modules/ticket/back/methods/ticket-tracking/changeState.js new file mode 100644 index 000000000..065692137 --- /dev/null +++ b/modules/ticket/back/methods/ticket-tracking/changeState.js @@ -0,0 +1,58 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('changeState', { + description: 'Change the state of a ticket', + accessType: 'WRITE', + accepts: [ + { + arg: 'data', + description: 'Model instance data', + type: 'Object', + required: true, + http: {source: 'body'} + } + ], + returns: { + type: 'string', + root: true + }, + http: { + path: `/changeState`, + verb: 'POST' + } + }); + + Self.changeState = async(ctx, params) => { + let userId = ctx.req.accessToken.userId; + let models = Self.app.models; + + if (!params.stateFk && !params.code) + throw new UserError('State cannot be blank'); + + if (params.code) { + let state = await models.State.findOne({where: {code: params.code}, fields: ['id']}); + params.stateFk = state.id; + } + + if (!params.workerFk) { + let worker = await models.Worker.findOne({where: {userFk: userId}}); + params.workerFk = worker.id; + } + + let ticket = await models.TicketState.findById( + params.ticketFk, + {fields: ['stateFk']} + ); + + let oldStateAllowed = await models.State.isEditable(ctx, ticket.stateFk); + let newStateAllowed = await models.State.isEditable(ctx, params.stateFk); + + let isAllowed = oldStateAllowed && newStateAllowed; + + if (!isAllowed) + throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED'); + + return await models.TicketTracking.create(params); + }; +}; diff --git a/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js b/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js new file mode 100644 index 000000000..3c6c51252 --- /dev/null +++ b/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js @@ -0,0 +1,84 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket changeState()', () => { + let ticket; + + beforeAll(async done => { + let originalTicket = await app.models.Ticket.findOne({where: {id: 16}}); + originalTicket.id = null; + ticket = await app.models.Ticket.create(originalTicket); + + done(); + }); + + afterAll(async done => { + await app.models.Ticket.destroyById(ticket.id); + + done(); + }); + + it('should throw if the ticket is not editable and the user isnt production', async() => { + let ctx = {req: {accessToken: {userId: 18}}}; + let params = {ticketFk: 2, stateFk: 3}; + + let errCode; + try { + await app.models.TicketTracking.changeState(ctx, params); + } catch (e) { + errCode = e.code; + } + + expect(errCode).toBe('ACCESS_DENIED'); + }); + + it('should throw an error if a worker with employee role attemps to a forbidden state', async() => { + let ctx = {req: {accessToken: {userId: 1}}}; + let params = {ticketFk: 11, stateFk: 13}; + + let errCode; + try { + await app.models.TicketTracking.changeState(ctx, params); + } catch (e) { + errCode = e.code; + } + + expect(errCode).toBe('ACCESS_DENIED'); + }); + + it('should be able to create a ticket tracking line for a not editable ticket if the user has the production role', async() => { + let ctx = {req: {accessToken: {userId: 49}}}; + let params = {ticketFk: ticket.id, stateFk: 3}; + + let res = await app.models.TicketTracking.changeState(ctx, params); + + expect(res.__data.ticketFk).toBe(params.ticketFk); + expect(res.__data.stateFk).toBe(params.stateFk); + expect(res.__data.workerFk).toBe(49); + expect(res.__data.id).toBeDefined(); + }); + + it('should return an array with the created ticket tracking line', async() => { + let ctx = {req: {accessToken: {userId: 49}}}; + let params = {ticketFk: ticket.id, stateFk: 3}; + let res = await app.models.TicketTracking.changeState(ctx, params); + + expect(res.__data.ticketFk).toBe(params.ticketFk); + expect(res.__data.stateFk).toBe(params.stateFk); + expect(res.__data.workerFk).toBe(49); + expect(res.__data.id).toBeDefined(); + }); + + it('should return an array with the created ticket tracking line when the user is salesperson, uses the state assigned and thes a workerFk given', async() => { + let ctx = {req: {accessToken: {userId: 18}}}; + let assignedState = await app.models.State.findOne({where: {code: 'PICKER_DESIGNED'}}); + let params = {ticketFk: ticket.id, stateFk: assignedState.id, workerFk: 1}; + let res = await app.models.TicketTracking.changeState(ctx, params); + + expect(res.__data.ticketFk).toBe(params.ticketFk); + expect(res.__data.stateFk).toBe(params.stateFk); + expect(res.__data.workerFk).toBe(params.workerFk); + expect(res.__data.workerFk).toBe(1); + expect(res.__data.id).toBeDefined(); + }); +}); + diff --git a/modules/ticket/back/methods/ticket-weekly/filter.js b/modules/ticket/back/methods/ticket-weekly/filter.js new file mode 100644 index 000000000..d249242a9 --- /dev/null +++ b/modules/ticket/back/methods/ticket-weekly/filter.js @@ -0,0 +1,70 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const buildFilter = require('vn-loopback/util/filter').buildFilter; +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethodCtx('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accessType: 'READ', + accepts: [ + { + arg: 'filter', + type: 'Object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + http: {source: 'query'} + }, { + arg: 'search', + type: 'String', + description: `If it's and integer searchs by id, otherwise it searchs by client id`, + http: {source: 'query'} + } + ], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/filter`, + verb: 'GET' + } + }); + + Self.filter = async(ctx, filter) => { + let conn = Self.dataSource.connector; + + let where = buildFilter(ctx.args, (param, value) => { + switch (param) { + case 'search': + return {or: [ + {'t.id': value}, + {'c.id': value} + ]}; + } + }); + + filter = mergeFilters(ctx.args.filter, {where}); + + let stmts = []; + let stmt; + + stmt = new ParameterizedSQL( + `SELECT t.id AS ticketFk, c.id AS clientFk, c.name AS clientName, tw.weekDay, + wh.name AS warehouseName, w.id AS workerFk, u.nickName + FROM ticketWeekly tw + JOIN ticket t ON t.id = tw.ticketFk + JOIN client c ON c.id = t.clientFk + JOIN worker w ON w.id = c.salesPersonFk + JOIN account.user u ON u.id = w.userFk + JOIN warehouse wh ON wh.id = t.warehouseFk` + ); + + + stmt.merge(conn.makeSuffix(filter)); + let itemsIndex = stmts.push(stmt) - 1; + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + return itemsIndex === 0 ? result : result[itemsIndex]; + }; +}; diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js new file mode 100644 index 000000000..bb833709e --- /dev/null +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -0,0 +1,71 @@ + +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('addSale', { + description: 'Inserts a new sale for the current ticket', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'Number', + required: true, + description: 'The ticket id', + http: {source: 'path'} + }, + { + arg: 'itemId', + type: 'Number', + required: true + }, + { + arg: 'quantity', + type: 'Number', + required: true + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/addSale`, + verb: 'POST' + } + }); + + Self.addSale = async(ctx, id, itemId, quantity) => { + const models = Self.app.models; + + const isEditable = await models.Ticket.isEditable(ctx, id); + if (!isEditable) + throw new UserError(`The sales of this ticket can't be modified`); + + const item = await models.Item.findById(itemId); + const ticket = await models.Ticket.findById(id); + + const shouldRefresh = false; + const [[stock]] = await Self.rawSql(`CALL vn.item_getVisibleAvailable(?, ?, ?, ?)`, [ + itemId, + ticket.shipped, + ticket.warehouseFk, + shouldRefresh + ]); + + if (stock.available < quantity) + throw new UserError(`This item is not available`); + + const newSale = await models.Sale.create({ + ticketFk: id, + itemFk: item.id, + concept: item.name, + quantity: quantity + }); + + await Self.rawSql('CALL vn.ticketCalculateSale(?)', [newSale.id]); + + return models.Sale.findById(newSale.id, { + include: { + relation: 'item' + } + }); + }; +}; diff --git a/modules/ticket/back/methods/ticket/canBeInvoiced.js b/modules/ticket/back/methods/ticket/canBeInvoiced.js new file mode 100644 index 000000000..3b588c32e --- /dev/null +++ b/modules/ticket/back/methods/ticket/canBeInvoiced.js @@ -0,0 +1,41 @@ +module.exports = function(Self) { + Self.remoteMethodCtx('canBeInvoiced', { + description: 'Change property isEqualizated in all client addresses', + accessType: 'READ', + accepts: [ + { + arg: 'id', + type: 'string', + required: true, + description: 'Client id', + http: {source: 'path'} + } + ], + returns: { + arg: 'data', + type: 'boolean', + root: true + }, + http: { + path: `/:id/canBeInvoiced`, + verb: 'get' + } + }); + + Self.canBeInvoiced = async id => { + let ticket = await Self.app.models.Ticket.findById(id, {fields: ['id', 'refFk', 'shipped']}); + let ticketTotal = await Self.app.models.Ticket.getTotal(id); + + let query = `SELECT vn.hasSomeNegativeBase(?) AS hasSomeNegativeBase`; + let [result] = await Self.rawSql(query, [id]); + let hasSomeNegativeBase = result.hasSomeNegativeBase; + + let today = new Date(); + let shipped = new Date(ticket.shipped); + + if (ticket.refFk || ticketTotal == 0 || shipped.getTime() > today.getTime() || hasSomeNegativeBase) + return false; + + return true; + }; +}; diff --git a/modules/ticket/back/methods/ticket/canHaveStowaway.js b/modules/ticket/back/methods/ticket/canHaveStowaway.js new file mode 100644 index 000000000..bbc6cf4b3 --- /dev/null +++ b/modules/ticket/back/methods/ticket/canHaveStowaway.js @@ -0,0 +1,39 @@ + +module.exports = Self => { + Self.remoteMethod('canHaveStowaway', { + description: 'Returns if a ticket can have stowaway', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'ticket id', + http: {source: 'path'} + }], + returns: { + root: true + }, + http: { + path: `/:id/canHaveStowaway`, + verb: 'GET' + } + }); + + Self.canHaveStowaway = async id => { + const models = Self.app.models; + const ticket = await models.Ticket.findById(id, { + include: { + relation: 'ship', + scope: { + fields: ['id'] + } + } + }); + const warehouse = await models.Warehouse.findById(ticket.warehouseFk); + const hasStowaway = ticket.ship() ? true : false; + if (warehouse && warehouse.hasStowaway && !hasStowaway) + return true; + + return false; + }; +}; diff --git a/services/loopback/common/methods/ticket/change-worker.js b/modules/ticket/back/methods/ticket/changeWorker.js similarity index 100% rename from services/loopback/common/methods/ticket/change-worker.js rename to modules/ticket/back/methods/ticket/changeWorker.js diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js new file mode 100644 index 000000000..2cba62540 --- /dev/null +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -0,0 +1,110 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('componentUpdate', { + description: 'Save ticket sale components', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'Number', + required: true, + description: 'The ticket id', + http: {source: 'path'} + }, { + arg: 'clientId', + type: 'Number', + description: 'The client id', + required: true + }, { + arg: 'agencyModeId', + type: 'Number', + description: 'The agencyMode id', + required: true + }, { + arg: 'addressId', + type: 'Number', + description: 'The address id', + required: true + }, { + arg: 'zoneId', + type: 'Number', + description: 'The zone id', + required: true + }, { + arg: 'warehouseId', + type: 'Number', + description: 'The warehouse id', + required: true + }, { + arg: 'companyId', + type: 'Number', + description: 'The company id', + required: true + }, { + arg: 'shipped', + type: 'Date', + description: 'The shipped date', + required: true + }, { + arg: 'landed', + type: 'Date', + description: 'The landing date', + required: true + }, { + arg: 'isDeleted', + type: 'Boolean', + description: 'Ticket is deleted', + required: true + }, { + arg: 'option', + type: 'Number', + description: 'Action id', + required: true + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/:id/componentUpdate`, + verb: 'post' + } + }); + + Self.componentUpdate = async(ctx, id, clientId, agencyModeId, addressId, zoneId, warehouseId, + companyId, shipped, landed, isDeleted, option) => { + const userId = ctx.req.accessToken.userId; + const models = Self.app.models; + const isEditable = await models.Ticket.isEditable(ctx, id); + + if (!isEditable) + throw new UserError(`The sales of this ticket can't be modified`); + + const isProductionBoss = await models.Account.hasRole(userId, 'productionBoss'); + if (!isProductionBoss) { + const zoneShipped = await models.Agency.getShipped(landed, addressId, agencyModeId, warehouseId); + + if (!zoneShipped || zoneShipped.zoneFk != zoneId) + throw new UserError(`You don't have privileges to change the zone`); + } + + // Force unroute + const hasToBeUnrouted = true; + let query = 'CALL vn.ticket_componentMakeUpdate(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; + let res = await Self.rawSql(query, [ + id, + clientId, + agencyModeId, + addressId, + zoneId, + warehouseId, + companyId, + shipped, + landed, + isDeleted, + hasToBeUnrouted, + option + ]); + return res; + }; +}; diff --git a/modules/ticket/back/methods/ticket/deleteStowaway.js b/modules/ticket/back/methods/ticket/deleteStowaway.js new file mode 100644 index 000000000..6f3a1760f --- /dev/null +++ b/modules/ticket/back/methods/ticket/deleteStowaway.js @@ -0,0 +1,39 @@ + +module.exports = Self => { + Self.remoteMethod('deleteStowaway', { + description: 'Deletes an stowaway', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The ticket id', + http: {source: 'path'} + }], + returns: { + root: true + }, + http: { + path: `/:id/deleteStowaway`, + verb: 'POST' + } + }); + + Self.deleteStowaway = async id => { + const ticket = await Self.findById(id, { + include: [{ + relation: 'ship' + }, { + relation: 'stowaway' + }] + }); + + let params; + if (ticket.stowaway()) + params = [ticket.stowaway().shipFk, ticket.stowaway().id]; + else if (ticket.ship()) + params = [ticket.ship().shipFk, ticket.ship().id]; + + return Self.rawSql(`CALL vn.stowaway_unboarding(?, ?)`, params); + }; +}; diff --git a/modules/ticket/back/methods/ticket/filter.js b/modules/ticket/back/methods/ticket/filter.js new file mode 100644 index 000000000..a3c17ecc4 --- /dev/null +++ b/modules/ticket/back/methods/ticket/filter.js @@ -0,0 +1,257 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const buildFilter = require('vn-loopback/util/filter').buildFilter; +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethod('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accepts: [ + { + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + }, { + arg: 'filter', + type: 'Object', + description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string` + }, { + arg: 'search', + type: 'String', + description: `If it's and integer searchs by id, otherwise it searchs by nickname` + }, { + arg: 'from', + type: 'Date', + description: `The from date filter` + }, { + arg: 'to', + type: 'Date', + description: `The to date filter` + }, { + arg: 'nickname', + type: 'String', + description: `The nickname filter` + }, { + arg: 'id', + type: 'Integer', + description: `The ticket id filter` + }, { + arg: 'clientFk', + type: 'Integer', + description: `The client id filter` + }, { + arg: 'agencyModeFk', + type: 'Integer', + description: `The agency mode id filter` + }, { + arg: 'warehouseFk', + type: 'Integer', + description: `The warehouse id filter` + }, { + arg: 'salesPersonFk', + type: 'Integer', + description: `The salesperson id filter` + }, { + arg: 'provinceFk', + type: 'Integer', + description: `The province id filter` + }, { + arg: 'stateFk', + type: 'Number', + description: `The state id filter` + }, { + arg: 'myTeam', + type: 'Boolean', + description: `Whether to show only tickets for the current logged user team (For now it shows only the current user tickets)` + }, { + arg: 'mine', + type: 'Boolean', + description: `Whether to show only tickets for the current logged user` + }, { + arg: 'orderFk', + type: 'Number', + description: `The order id filter` + }, { + arg: 'refFk', + type: 'string', + description: `The invoice reference filter` + }, { + arg: 'alertLevel', + type: 'Number', + description: `The alert level of the tickets` + } + ], + returns: { + type: ['Object'], + root: true + }, + http: { + path: '/filter', + verb: 'GET' + } + }); + + Self.filter = async(ctx, filter) => { + let conn = Self.dataSource.connector; + + let worker = await Self.app.models.Worker.findOne({ + where: {userFk: ctx.req.accessToken.userId}, + include: [ + {relation: 'collegues'} + ] + }); + + let teamIds = []; + + if (worker.collegues().length && ctx.args.myTeam) { + worker.collegues().forEach(collegue => { + teamIds.push(collegue.collegueFk); + }); + } + + if (ctx.args.mine || (worker.collegues().length === 0 && ctx.args.myTeam)) { + worker = await Self.app.models.Worker.findOne({ + fields: ['id'], + where: {userFk: ctx.req.accessToken.userId} + }); + teamIds = [worker && worker.id]; + } + + if (ctx.args && (ctx.args.mine || ctx.args.myTeam)) + ctx.args.teamIds = teamIds; + + if (ctx.args && ctx.args.to) { + const dateTo = ctx.args.to; + dateTo.setHours(23, 59, 0, 0); + } + + let orderTickets = []; + if (ctx.args && ctx.args.orderFk) { + let ticketsToSearch = await Self.app.models.OrderTicket.find({where: {orderFk: ctx.args.orderFk}}); + ticketsToSearch.forEach(ticket => { + orderTickets.push(ticket.ticketFk); + }); + ctx.args.search = orderTickets; + } + + let where = buildFilter(ctx.args, (param, value) => { + switch (param) { + case 'search': + return /^\d+$/.test(value) + ? {'t.id': {inq: value}} + : {'t.nickname': {like: `%${value}%`}}; + case 'from': + return {'t.shipped': {gte: value}}; + case 'to': + return {'t.shipped': {lte: value}}; + case 'nickname': + return {'t.nickname': {like: `%${value}%`}}; + case 'refFk': + return {'t.refFk': value}; + case 'salesPersonFk': + return {'c.salesPersonFk': value}; + case 'provinceFk': + return {'a.provinceFk': value}; + case 'stateFk': + return {'ts.stateFk': value}; + case 'mine': + case 'myTeam': + return {'c.salesPersonFk': {inq: teamIds}}; + case 'alertLevel': + return {'ts.alertLevel': value}; + case 'id': + case 'clientFk': + case 'agencyModeFk': + case 'warehouseFk': + param = `t.${param}`; + return {[param]: value}; + } + }); + + filter = mergeFilters(filter, {where}); + + let stmts = []; + let stmt; + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.filter'); + + stmt = new ParameterizedSQL( + `CREATE TEMPORARY TABLE tmp.filter + (INDEX (id)) + ENGINE = MEMORY + SELECT + t.id, + t.shipped, + t.nickname, + t.refFk, + t.routeFk, + t.warehouseFk, + t.clientFk, + p.name AS province, + w.name AS warehouse, + am.name AS agencyMode, + st.name AS state, + wk.lastName AS salesPerson, + ts.stateFk as stateFk, + ts.alertLevel as alertLevel, + ts.code as alertLevelCode, + u.nickname userNickname, + c.salesPersonFk, + z.hour zoneLanding, + HOUR(z.hour) zoneHour, + MINUTE(z.hour) zoneMinute + FROM ticket t + LEFT JOIN zone z ON z.id = t.zoneFk + LEFT JOIN address a ON a.id = t.addressFk + LEFT JOIN province p ON p.id = a.provinceFk + LEFT JOIN warehouse w ON w.id = t.warehouseFk + LEFT JOIN agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + LEFT JOIN state st ON st.id = ts.stateFk + LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN account.user u ON u.id = wk.userFk`); + stmt.merge(conn.makeSuffix(filter)); + stmts.push(stmt); + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.ticketGetProblems'); + stmts.push(` + CREATE TEMPORARY TABLE tmp.ticketGetProblems + (INDEX (ticketFk)) + ENGINE = MEMORY + SELECT id ticketFk, clientFk, warehouseFk, shipped + FROM tmp.filter + WHERE alertLevel = 0 OR alertLevel IS NULL`); + stmts.push('CALL ticketGetProblems()'); + + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.ticket'); + stmts.push(` + CREATE TEMPORARY TABLE tmp.ticket + (INDEX (ticketFk)) ENGINE = MEMORY + SELECT id ticketFk FROM tmp.filter`); + stmts.push('CALL ticketGetTotal()'); + + stmt = new ParameterizedSQL(` + SELECT + f.*, + tt.total, + tp.* + FROM tmp.filter f + LEFT JOIN tmp.ticketProblems tp ON tp.ticketFk = f.id + LEFT JOIN tmp.ticketTotal tt ON tt.ticketFk = f.id`); + stmt.merge(conn.makeOrderBy(filter.order)); + let ticketsIndex = stmts.push(stmt); + + stmts.push( + `DROP TEMPORARY TABLE + tmp.filter, + tmp.ticket, + tmp.ticketTotal, + tmp.ticketGetProblems`); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + + return result[ticketsIndex]; + }; +}; diff --git a/modules/ticket/back/methods/ticket/getPossibleStowaways.js b/modules/ticket/back/methods/ticket/getPossibleStowaways.js new file mode 100644 index 000000000..3565d64ab --- /dev/null +++ b/modules/ticket/back/methods/ticket/getPossibleStowaways.js @@ -0,0 +1,70 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethod('getPossibleStowaways', { + description: 'Returns a list of allowed tickets for a stowaway ticket', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'ticket id', + http: {source: 'path'} + }], + returns: { + root: true + }, + http: { + path: `/:id/getPossibleStowaways`, + verb: 'GET' + } + }); + + Self.getPossibleStowaways = async ticketFk => { + const models = Self.app.models; + const canHaveStowaway = await models.Ticket.canHaveStowaway(ticketFk); + + if (!canHaveStowaway) + throw new UserError(`Can't create stowaway for this ticket`); + + let ship = await models.Ticket.findById(ticketFk); + + if (!ship || !ship.shipped) + return []; + + let lowestDate = new Date(ship.shipped.getTime()); + lowestDate.setHours(0, 0, -1, 0); + + let highestDate = new Date(ship.shipped.getTime()); + highestDate.setHours(23, 59, 59); + + + let possibleStowaways = await models.Ticket.find({ + where: { + id: {neq: ticketFk}, + clientFk: ship.clientFk, + addressFk: ship.addressFk, + agencyModeFk: ship.agencyModeFk, + warehouseFk: {neq: ship.warehouseFk}, + shipped: { + between: [lowestDate.toJSON(), highestDate.toJSON()] + } + }, + include: [ + {relation: 'agencyMode'}, + {relation: 'warehouse'}, + {relation: 'state', + scope: { + fields: ['stateFk'], + include: { + relation: 'state', + fields: ['id', 'name'], + } + }, + }, + ] + }); + + return possibleStowaways; + }; +}; diff --git a/modules/ticket/back/methods/ticket/getSales.js b/modules/ticket/back/methods/ticket/getSales.js new file mode 100644 index 000000000..b59d678f2 --- /dev/null +++ b/modules/ticket/back/methods/ticket/getSales.js @@ -0,0 +1,59 @@ +module.exports = Self => { + Self.remoteMethod('getSales', { + description: 'New filter', + accessType: 'READ', + accepts: [{ + arg: 'ticketFk', + type: 'number', + required: true, + description: 'ticket id', + http: {source: 'path'} + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/:ticketFk/getSales`, + verb: 'get' + } + }); + + Self.getSales = async ticketFk => { + let query = `CALL vn.ticketGetVisibleAvailable(?)`; + let [lines] = await Self.rawSql(query, [ticketFk]); + let ids = []; + let salesIds = []; + + for (line of lines) { + ids.push(line.itemFk); + salesIds.push(line.id); + } + + let filter = { + fields: ['id', 'name', 'tag5', 'value5', 'tag6', 'value6', 'tag7', 'value7', 'tag8', 'value8', 'tag9', 'value9', 'tag10', 'value10'], + where: {id: {inq: ids}} + }; + let items = await Self.app.models.Item.find(filter); + + filter = { + fields: ['claimFk', 'saleFk'], + where: {saleFk: {inq: salesIds}}, + }; + let claims = await Self.app.models.ClaimBeginning.find(filter); + + let map = {}; + for (item of items) + map[item.id] = item; + + let claimMap = {}; + for (claim of claims) + claimMap[claim.saleFk] = claim; + + for (line of lines) { + line.item = map[line.itemFk]; + line.claim = claimMap[line.id]; + } + return lines; + }; +}; diff --git a/modules/ticket/back/methods/ticket/getSalesPersonMana.js b/modules/ticket/back/methods/ticket/getSalesPersonMana.js new file mode 100644 index 000000000..8ac1d7a38 --- /dev/null +++ b/modules/ticket/back/methods/ticket/getSalesPersonMana.js @@ -0,0 +1,39 @@ +module.exports = Self => { + Self.remoteMethod('getSalesPersonMana', { + description: 'Returns mana of a salesperson of a ticket', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'ticket id', + http: {source: 'path'} + }], + returns: { + root: true + }, + http: { + path: `/:id/getSalesPersonMana`, + verb: 'GET' + } + }); + + Self.getSalesPersonMana = async ticketFk => { + let ticket = await Self.app.models.Ticket.findById(ticketFk, { + include: [{ + relation: 'client', + scope: { + fields: ['salesPersonFk'] + } + }], + fields: ['id', 'clientFk'] + }); + + if (!ticket) + return 0; + + let mana = await Self.app.models.WorkerMana.findOne({where: {workerFk: ticket.client().salesPersonFk}, fields: 'amount'}); + + return mana ? mana.amount : 0; + }; +}; diff --git a/modules/ticket/back/methods/ticket/getTaxes.js b/modules/ticket/back/methods/ticket/getTaxes.js new file mode 100644 index 000000000..151866eff --- /dev/null +++ b/modules/ticket/back/methods/ticket/getTaxes.js @@ -0,0 +1,28 @@ +module.exports = Self => { + Self.remoteMethod('getTaxes', { + description: 'Returns ticket taxes', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'ticket id', + http: {source: 'path'} + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/:id/getTaxes`, + verb: 'GET' + } + }); + + Self.getTaxes = async ticketFk => { + let query = `CALL vn.ticketGetTaxAdd(?)`; + let [taxes] = await Self.rawSql(query, [ticketFk]); + + return taxes; + }; +}; diff --git a/modules/ticket/back/methods/ticket/getTotal.js b/modules/ticket/back/methods/ticket/getTotal.js new file mode 100644 index 000000000..8e342cf5d --- /dev/null +++ b/modules/ticket/back/methods/ticket/getTotal.js @@ -0,0 +1,28 @@ +module.exports = Self => { + Self.remoteMethod('getTotal', { + description: 'Returns the total of a ticket', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'ticket id', + http: {source: 'path'} + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/:id/getTotal`, + verb: 'GET' + } + }); + + Self.getTotal = async ticketFk => { + let query = `SELECT vn.ticketGetTotal(?) AS amount`; + let [total] = await Self.rawSql(query, [ticketFk]); + + return total.amount ? total.amount : 0.00; + }; +}; diff --git a/modules/ticket/back/methods/ticket/getTotalVolume.js b/modules/ticket/back/methods/ticket/getTotalVolume.js new file mode 100644 index 000000000..117c3c62f --- /dev/null +++ b/modules/ticket/back/methods/ticket/getTotalVolume.js @@ -0,0 +1,24 @@ +module.exports = Self => { + Self.remoteMethod('getTotalVolume', { + description: 'Returns the total volume of a ticket', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'ticket id', + http: {source: 'path'} + }], + returns: { + root: true + }, + http: { + path: `/:id/getTotalVolume`, + verb: 'GET' + } + }); + + Self.getTotalVolume = async ticketFk => { + return (await Self.rawSql(`SELECT vn.ticketTotalVolume(?) totalVolume, vn.ticketTotalVolumeBoxes(?) totalBoxes`, [ticketFk, ticketFk]))[0]; + }; +}; diff --git a/modules/ticket/back/methods/ticket/getVAT.js b/modules/ticket/back/methods/ticket/getVAT.js new file mode 100644 index 000000000..087697b0c --- /dev/null +++ b/modules/ticket/back/methods/ticket/getVAT.js @@ -0,0 +1,32 @@ +module.exports = Self => { + Self.remoteMethod('getVAT', { + description: 'Returns ticket total VAT', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'ticket id', + http: {source: 'path'} + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/:id/getVAT`, + verb: 'GET' + } + }); + + Self.getVAT = async ticketFk => { + let totalTax = 0.00; + let taxes = await Self.app.models.Ticket.getTaxes(ticketFk); + + taxes.forEach(tax => { + totalTax += tax.tax; + }); + + return Math.round(totalTax * 100) / 100; + }; +}; diff --git a/modules/ticket/back/methods/ticket/getVolume.js b/modules/ticket/back/methods/ticket/getVolume.js new file mode 100644 index 000000000..9b4d28edc --- /dev/null +++ b/modules/ticket/back/methods/ticket/getVolume.js @@ -0,0 +1,26 @@ +module.exports = Self => { + Self.remoteMethod('getVolume', { + description: 'Returns the volumes of a ticket', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'ticket id', + http: {source: 'path'} + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/:id/getVolume`, + verb: 'GET' + } + }); + + Self.getVolume = async ticketFk => { + let [volume] = await Self.rawSql(`CALL vn.ticketListVolume(?)`, [ticketFk]); + return volume; + }; +}; diff --git a/modules/ticket/back/methods/ticket/isEditable.js b/modules/ticket/back/methods/ticket/isEditable.js new file mode 100644 index 000000000..3ebf15bf0 --- /dev/null +++ b/modules/ticket/back/methods/ticket/isEditable.js @@ -0,0 +1,56 @@ +module.exports = Self => { + Self.remoteMethodCtx('isEditable', { + description: 'Check if a ticket is editable', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'the ticket id', + http: {source: 'path'} + }], + returns: { + type: 'boolean', + root: true + }, + http: { + path: `/:id/isEditable`, + verb: 'get' + } + }); + + Self.isEditable = async(ctx, id) => { + const userId = ctx.req.accessToken.userId; + + let state = await Self.app.models.TicketState.findOne({ + where: {ticketFk: id} + }); + + const isSalesAssistant = await Self.app.models.Account.hasRole(userId, 'salesAssistant'); + const isProductionBoss = await Self.app.models.Account.hasRole(userId, 'productionBoss'); + const isValidRole = isSalesAssistant || isProductionBoss; + + let alertLevel = state ? state.alertLevel : null; + let ticket = await Self.app.models.Ticket.findById(id, { + fields: ['isDeleted', 'clientFk', 'refFk'], + include: [{ + relation: 'client', + scope: { + include: { + relation: 'type' + } + } + }] + }); + + const isDeleted = ticket && ticket.isDeleted; + const isOnDelivery = (alertLevel && alertLevel > 0); + const isNormalClient = ticket && ticket.client().type().code == 'normal'; + const isInvoiced = ticket && ticket.refFk; + + if (!ticket || isInvoiced || isDeleted || (isOnDelivery && isNormalClient && !isValidRole)) + return false; + + return true; + }; +}; diff --git a/modules/ticket/back/methods/ticket/isEmpty.js b/modules/ticket/back/methods/ticket/isEmpty.js new file mode 100644 index 000000000..0465589e6 --- /dev/null +++ b/modules/ticket/back/methods/ticket/isEmpty.js @@ -0,0 +1,52 @@ +module.exports = function(Self) { + Self.remoteMethod('isEmpty', { + description: 'Checks if the ticket has no packages, componenets and purchase requests', + accessType: 'READ', + accepts: [ + { + arg: 'id', + type: 'number', + required: true, + description: 'Ticket id', + http: {source: 'path'} + } + ], + returns: { + type: 'Boolean', + root: true + }, + http: { + path: `/:id/isEmpty`, + verb: 'GET' + } + }); + + Self.isEmpty = async(id, options) => { + const models = Self.app.models; + + if ((typeof options) != 'object') + options = {}; + + const hasSales = await models.Sale.count({ + ticketFk: id + }, options); + + const hasPackages = await models.TicketPackaging.count({ + ticketFk: id + }, options); + + const hasServices = await models.TicketService.count({ + ticketFk: id + }, options); + + const hasPurchaseRequests = await models.TicketRequest.count({ + ticketFk: id, + isOk: true + }, options); + + const isEmpty = !hasSales && !hasPackages && + !hasServices && !hasPurchaseRequests; + + return isEmpty; + }; +}; diff --git a/modules/ticket/back/methods/ticket/makeInvoice.js b/modules/ticket/back/methods/ticket/makeInvoice.js new file mode 100644 index 000000000..226eebf97 --- /dev/null +++ b/modules/ticket/back/methods/ticket/makeInvoice.js @@ -0,0 +1,83 @@ +const UserError = require('vn-loopback/util/user-error'); +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = function(Self) { + Self.remoteMethodCtx('makeInvoice', { + description: 'Make out an invoice from a ticket id', + accessType: 'WRITE', + accepts: [ + { + arg: 'id', + type: 'string', + required: true, + description: 'Ticket id', + http: {source: 'path'} + } + ], + returns: { + arg: 'data', + type: 'boolean', + root: true + }, + http: { + path: `/:id/makeInvoice`, + verb: 'POST' + } + }); + + Self.makeInvoice = async(ctx, id) => { + const conn = Self.dataSource.connector; + let userId = ctx.req.accessToken.userId; + let models = Self.app.models; + let tx = await Self.beginTransaction({}); + + try { + let options = {transaction: tx}; + + let filter = {fields: ['id', 'clientFk', 'companyFk']}; + let ticket = await models.Ticket.findById(id, filter, options); + + let clientCanBeInvoiced = await models.Client.canBeInvoiced(ticket.clientFk); + if (!clientCanBeInvoiced) + throw new UserError(`This client can't be invoiced`); + + let ticketCanBeInvoiced = await models.Ticket.canBeInvoiced(ticket.id); + if (!ticketCanBeInvoiced) + throw new UserError(`This ticket can't be invoiced`); + + + let query = `SELECT vn.invoiceSerial(?, ?, ?) AS serial`; + let [result] = await Self.rawSql(query, [ticket.clientFk, ticket.companyFk, 'R'], options); + let serial = result.serial; + let stmts = []; + + stmt = new ParameterizedSQL('CALL vn.invoiceOut_newFromTicket(?, ?, ?, @invoiceId)', [ + ticket.id, + serial, + null + ]); + stmts.push(stmt); + + let invoiceIndex = stmts.push(`SELECT @invoiceId AS invoiceId`) - 1; + + let sql = ParameterizedSQL.join(stmts, ';'); + result = await conn.executeStmt(sql); + let invoiceId = result[invoiceIndex][0].invoiceId; + if (serial != 'R' && invoiceId) { + query = `CALL vn.invoiceOutBooking(?)`; + await Self.rawSql(query, [invoiceId], options); + } + + let user = await models.Worker.findOne({where: {userFk: userId}}, options); + + query = `INSERT INTO printServerQueue(reportFk, param1, workerFk) VALUES (?, ?, ?)`; + await Self.rawSql(query, [3, invoiceId, user.id], options); + await tx.commit(); + + return {invoiceFk: invoiceId, serial}; + } catch (e) { + await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/ticket/back/methods/ticket/new.js b/modules/ticket/back/methods/ticket/new.js new file mode 100644 index 000000000..7ddde8785 --- /dev/null +++ b/modules/ticket/back/methods/ticket/new.js @@ -0,0 +1,119 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('new', { + description: 'Create a newticket and returns the new ID', + accessType: 'WRITE', + accepts: [{ + arg: 'params', + type: 'object', + required: true, + description: 'ClientFk, Shipped, WarehouseFk, CompanyFk, AddressFk, AgencyModeFk, RouteFk, Landed, userId', + http: {source: 'body'} + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/new`, + verb: 'post' + } + }); + + Self.new = async(ctx, params, options) => { + let models = Self.app.models; + let address = await models.Address.findOne({ + where: {id: params.addressFk}, + fields: ['id', 'clientFk'], + include: { + relation: 'client', + scope: { + include: { + relation: 'type' + } + } + } + }); + + // FIXME: #1953 Params should be declared with it's correct argument type + if (params.shipped) + params.shipped = new Date(params.shipped); + if (params.landed) + params.landed = new Date(params.landed); + + if (!address) + throw new UserError(`This address doesn't exist`); + + let agencyMode; + if (params && params.agencyModeFk) + agencyMode = await models.AgencyMode.findById(params.agencyModeFk); + + if (address.client().type().code === 'normal' && (!agencyMode || agencyMode.code != 'refund')) { + if (!address.client().isActive) + throw new UserError(`You can't create a ticket for a inactive client`); + } + + let tx; + + if ((typeof options) != 'object') + options = {}; + + if (!options.transaction) { + tx = await Self.beginTransaction({}); + options.transaction = tx; + } + + try { + if (!params.shipped && params.landed) { + const shippedResult = await models.Agency.getShipped(params.landed, + address.id, params.agencyModeFk, params.warehouseFk); + params.shipped = shippedResult && shippedResult.shipped; + } + + if (params.shipped && !params.landed) { + const landedResult = await models.Agency.getLanded(params.shipped, + address.id, params.agencyModeFk, params.warehouseFk); + params.landed = landedResult && landedResult.landed; + } + + if (!params.userId && ctx.req && ctx.req.accessToken.userId) + params.userId = ctx.req.accessToken.userId; + + query = `CALL vn.ticketCreateWithUser(?, ?, ?, ?, ?, ?, ?, ?, ?, @result); + SELECT @result newTicketId;`; + let result = await Self.rawSql(query, [ + params.clientFk, + params.shipped, + params.warehouseFk, + params.companyFk || 442, + params.addressFk, + params.agencyModeFk || null, + params.routeFk || null, + params.landed, + params.userId + ], options); + + let ticket = await models.Ticket.findById(result[1][0].newTicketId, null, options); + let cleanInstance = JSON.parse(JSON.stringify(ticket)); + + let logRecord = { + originFk: cleanInstance.id, + userFk: params.userId, + action: 'create', + changedModel: 'Ticket', + changedModelId: cleanInstance.id, + oldInstance: {}, + newInstance: cleanInstance + }; + + await models.TicketLog.create(logRecord, options); + + if (tx) await tx.commit(); + return await ticket; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/ticket/back/methods/ticket/priceDifference.js b/modules/ticket/back/methods/ticket/priceDifference.js new file mode 100644 index 000000000..a303412fe --- /dev/null +++ b/modules/ticket/back/methods/ticket/priceDifference.js @@ -0,0 +1,117 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('priceDifference', { + description: 'Returns sales with price difference if the ticket is editable', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'Number', + required: true, + description: 'The ticket id', + http: {source: 'path'} + }, + { + arg: 'landed', + type: 'Date', + description: 'The landing date', + required: true + }, + { + arg: 'addressId', + type: 'Number', + description: 'The address id', + required: true + }, + { + arg: 'agencyModeId', + type: 'Number', + description: 'The agencyMode id', + required: true + }, + { + arg: 'zoneId', + type: 'Number', + description: 'The zone id', + required: true + }, + { + arg: 'warehouseId', + type: 'Number', + description: 'The warehouse id', + required: true + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/:id/priceDifference`, + verb: 'POST' + } + }); + + Self.priceDifference = async(ctx, id, landed, addressId, agencyModeId, zoneId, warehouseId) => { + const models = Self.app.models; + const isEditable = await Self.isEditable(ctx, id); + const userId = ctx.req.accessToken.userId; + + if (!isEditable) + throw new UserError(`The sales of this ticket can't be modified`); + + const isProductionBoss = await models.Account.hasRole(userId, 'productionBoss'); + if (!isProductionBoss) { + const zoneShipped = await models.Agency.getShipped(landed, addressId, agencyModeId, warehouseId); + + if (!zoneShipped || zoneShipped.zoneFk != zoneId) + throw new UserError(`You don't have privileges to change the zone`); + } + + let salesObj = { + items: await models.Sale.find({ + where: { + ticketFk: id + }, + order: 'concept ASC', + include: 'item' + }), + totalUnitPrice: 0.00, + totalNewPrice: 0.00, + totalDifference: 0.00, + }; + + const query = `CALL vn.ticket_priceDifference(?, ?, ?, ?, ?)`; + const args = [id, landed, addressId, zoneId, warehouseId]; + const [difComponents] = await Self.rawSql(query, args); + + const map = new Map(); + + // Sale price component, one per sale + difComponents.forEach(difComponent => { + map.set(difComponent.saleFk, difComponent); + }); + + function round(value) { + return Math.round(value * 100) / 100; + } + + salesObj.items.forEach(sale => { + const difComponent = map.get(sale.id); + + if (difComponent) { + sale.component = difComponent; + + salesObj.totalDifference += difComponent.difference; + salesObj.totalDifference = round(salesObj.totalDifference); + + salesObj.totalNewPrice += difComponent.newPrice; + salesObj.totalNewPrice = round(salesObj.totalNewPrice); + } + + salesObj.totalUnitPrice += sale.price; + salesObj.totalUnitPrice = round(salesObj.totalUnitPrice); + }); + + return salesObj; + }; +}; diff --git a/modules/ticket/back/methods/ticket/recalculateComponents.js b/modules/ticket/back/methods/ticket/recalculateComponents.js new file mode 100644 index 000000000..81fee4d70 --- /dev/null +++ b/modules/ticket/back/methods/ticket/recalculateComponents.js @@ -0,0 +1,31 @@ +const UserError = require('vn-loopback/util/user-error'); +module.exports = Self => { + Self.remoteMethodCtx('recalculateComponents', { + description: 'Calculates the price of a sale and its components', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + description: 'The ticket id', + type: 'number', + required: true, + http: {source: 'path'} + }], + returns: { + type: 'Number', + root: true + }, + http: { + path: `/:id/recalculateComponents`, + verb: 'POST' + } + }); + + Self.recalculateComponents = async(ctx, id) => { + const isEditable = await Self.isEditable(ctx, id); + + if (!isEditable) + throw new UserError(`The current ticket can't be modified`); + + return Self.rawSql('CALL vn.ticket_recalcComponents(?)', [id]); + }; +}; diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js new file mode 100644 index 000000000..fb72c7dbc --- /dev/null +++ b/modules/ticket/back/methods/ticket/setDeleted.js @@ -0,0 +1,102 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('setDeleted', { + description: 'Sets true the isDeleted value of a ticket', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'Number', + required: true, + description: 'The ticket id', + http: {source: 'path'} + }], + returns: { + type: 'string', + root: true + }, + http: { + path: `/:id/setDeleted`, + verb: 'post' + } + }); + + Self.setDeleted = async(ctx, id) => { + const models = Self.app.models; + const isEditable = await Self.isEditable(ctx, id); + const $t = ctx.req.__; // $translate + + if (!isEditable) + throw new UserError(`The sales of this ticket can't be modified`); + + // Check if has sales with shelving + const sales = await models.Sale.find({ + include: {relation: 'itemShelving'}, + where: {ticketFk: id} + }); + const hasItemShelvingSales = sales.some(sale => { + return sale.itemShelving(); + }); + if (hasItemShelvingSales) + throw new UserError(`You cannot delete a ticket that part of it is being prepared`); + + // Check for existing claim + const claimOfATicket = await models.Claim.findOne({where: {ticketFk: id}}); + if (claimOfATicket) + throw new UserError('You must delete the claim id %d first', 'DELETE_CLAIM_FIRST', claimOfATicket.id); + + // Check for existing purchase requests + const hasPurchaseRequests = await models.TicketRequest.count({ + ticketFk: id, + isOk: true + }); + + if (hasPurchaseRequests) + throw new UserError('You must delete all the buy requests first'); + + // Remove ticket greuges + const ticketGreuges = await models.Greuge.find({where: {ticketFk: id}}); + const ownGreuges = ticketGreuges.every(greuge => { + return greuge.ticketFk = id; + }); + if (ownGreuges) { + for (const greuge of ticketGreuges) { + const instance = await models.Greuge.findById(greuge.id); + + await instance.destroy(); + } + } + + const ticket = await models.Ticket.findById(id, { + include: { + relation: 'client', + scope: { + fields: ['id', 'salesPersonFk'], + include: { + relation: 'salesPerson', + scope: { + fields: ['id', 'userFk'], + include: { + relation: 'user' + } + } + } + } + } + }); + + // Send notification to salesPerson + const salesPerson = ticket.client().salesPerson(); + if (salesPerson) { + const salesPersonUser = salesPerson.user().name; + const origin = ctx.req.headers.origin; + const message = $t(`Has deleted the ticket id`, { + id: id, + url: `${origin}/#!/ticket/${id}/summary` + }); + await models.Chat.sendMessage(ctx, `@${salesPersonUser}`, message); + } + + return ticket.updateAttribute('isDeleted', true); + }; +}; diff --git a/modules/ticket/back/methods/ticket/specs/addSale.spec.js b/modules/ticket/back/methods/ticket/specs/addSale.spec.js new file mode 100644 index 000000000..c2650bf4b --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/addSale.spec.js @@ -0,0 +1,52 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket addSale()', () => { + const ticketId = 13; + let newSale; + + afterAll(async done => { + const sale = await app.models.Sale.findById(newSale.id); + await sale.destroy(); + + done(); + }); + + it('should create a new sale for the ticket with id 13', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + const itemId = 4; + const quantity = 10; + newSale = await app.models.Ticket.addSale(ctx, ticketId, itemId, quantity); + + expect(newSale.itemFk).toEqual(4); + }); + + it('should not be able to add a sale if the item quantity is not available', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + const itemId = 11; + const quantity = 10; + + let error; + await app.models.Ticket.addSale(ctx, ticketId, itemId, quantity).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`This item is not available`); + }); + + expect(error).toBeDefined(); + }); + + it('should not be able to add a sale if the ticket is not editable', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + const notEditableTicketId = 1; + const itemId = 4; + const quantity = 10; + let error; + await app.models.Ticket.addSale(ctx, notEditableTicketId, itemId, quantity).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`The sales of this ticket can't be modified`); + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/canHaveStowaway.spec.js b/modules/ticket/back/methods/ticket/specs/canHaveStowaway.spec.js new file mode 100644 index 000000000..231f2581b --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/canHaveStowaway.spec.js @@ -0,0 +1,17 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket canHaveStowaway()', () => { + it('should return true if the ticket warehouse have hasStowaway equal 1', async() => { + const ticketId = 16; + let canStowaway = await app.models.Ticket.canHaveStowaway(ticketId); + + expect(canStowaway).toBeTruthy(); + }); + + it('should return false if the ticket warehouse dont have hasStowaway equal 0', async() => { + const ticketId = 10; + let canStowaway = await app.models.Ticket.canHaveStowaway(ticketId); + + expect(canStowaway).toBeFalsy(); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js new file mode 100644 index 000000000..25ce90946 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js @@ -0,0 +1,82 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket componentUpdate()', () => { + const ticketId = 11; + const today = new Date(); + const tomorrow = new Date(); + tomorrow.setDate(tomorrow.getDate() + 1); + + let deliveryComponentId; + let firstvalueBeforeChange; + let secondvalueBeforeChange; + let componentOfSaleSeven; + let componentOfSaleEight; + + beforeAll(async done => { + let deliveryComponenet = await app.models.ComponentRate.findOne({where: {code: 'delivery'}}); + deliveryComponentId = deliveryComponenet.id; + componentOfSaleSeven = `SELECT value FROM vn.saleComponent WHERE saleFk = 7 AND componentFk = ${deliveryComponentId}`; + componentOfSaleEight = `SELECT value FROM vn.saleComponent WHERE saleFk = 8 AND componentFk = ${deliveryComponentId}`; + + [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleSeven); + firstvalueBeforeChange = componentValue.value; + + [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleEight); + secondvalueBeforeChange = componentValue.value; + + done(); + }); + + it('should change the agencyMode to modify the sale components value', async() => { + const clientId = 102; + const addressId = 122; + const agencyModeId = 8; + const warehouseId = 1; + const zoneId = 5; + const shipped = today; + const companyId = 442; + const isDeleted = false; + const landed = tomorrow; + const option = 1; + + let ctx = {req: {accessToken: {userId: 101}}}; + + await app.models.Ticket.componentUpdate(ctx, ticketId, clientId, agencyModeId, addressId, + zoneId, warehouseId, companyId, shipped, landed, isDeleted, option); + + [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleSeven); + let firstvalueAfterChange = componentValue.value; + + [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleEight); + let secondvalueAfterChange = componentValue.value; + + expect(firstvalueBeforeChange).not.toEqual(firstvalueAfterChange); + expect(secondvalueBeforeChange).not.toEqual(secondvalueAfterChange); + }); + + it('should change the agencyMode to go back to the originals sale components value', async() => { + const clientId = 102; + const addressId = 122; + const agencyModeId = 7; + const warehouseId = 1; + const zoneId = 3; + const shipped = today; + const companyId = 442; + const isDeleted = false; + const landed = tomorrow; + const option = 1; + + let ctx = {req: {accessToken: {userId: 101}}}; + await app.models.Ticket.componentUpdate(ctx, ticketId, clientId, agencyModeId, addressId, + zoneId, warehouseId, companyId, shipped, landed, isDeleted, option); + + [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleSeven); + let firstvalueAfterChange = componentValue.value; + + [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleEight); + let secondvalueAfterChange = componentValue.value; + + expect(firstvalueBeforeChange).toEqual(firstvalueAfterChange); + expect(secondvalueBeforeChange).toEqual(secondvalueAfterChange); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js new file mode 100644 index 000000000..3c8097e37 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js @@ -0,0 +1,42 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket deleteStowaway()', () => { + const shipId = 16; + const stowawayId = 17; + + it('should create an stowaway', async() => { + await app.models.Stowaway.rawSql(` + INSERT INTO stowaway (id, shipFk) VALUES (?, ?) + `, [stowawayId, shipId]); + + const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + + expect(stowawayExists).toEqual(1); + }); + + it('should delete the stowaway from the ship ticket', async() => { + await app.models.Ticket.deleteStowaway(shipId); + + const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + + expect(stowawayExists).toEqual(0); + }); + + it('should create again an stowaway', async() => { + await app.models.Stowaway.rawSql(` + INSERT INTO stowaway (id, shipFk) VALUES (?, ?) + `, [stowawayId, shipId]); + + const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + + expect(stowawayExists).toEqual(1); + }); + + it('should delete the stowaway from the stowaway ticket', async() => { + await app.models.Ticket.deleteStowaway(stowawayId); + + const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + + expect(stowawayExists).toEqual(0); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/filter.spec.js b/modules/ticket/back/methods/ticket/specs/filter.spec.js new file mode 100644 index 000000000..357ef2bdb --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/filter.spec.js @@ -0,0 +1,13 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket filter()', () => { + it('should return the tickets matching the filter', async() => { + let ctx = {req: {accessToken: {userId: 9}}, args: {}}; + + let filter = {order: 'id DESC'}; + let result = await app.models.Ticket.filter(ctx, filter); + let ticketId = result[0].id; + + expect(ticketId).toEqual(24); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/getPossibleStowaways.spec.js b/modules/ticket/back/methods/ticket/specs/getPossibleStowaways.spec.js new file mode 100644 index 000000000..7e667ad36 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/getPossibleStowaways.spec.js @@ -0,0 +1,30 @@ +const app = require('vn-loopback/server/server'); +let UserError = require('vn-loopback/util/user-error'); + +describe('ticket getPossibleStowaways()', () => { + it(`should throw an error if Can't create stowaway for this ticket`, async() => { + let error; + let ticketId = 10; + + await app.models.Ticket.getPossibleStowaways(ticketId) + .catch(e => { + error = e; + }); + + expect(error).toEqual(new UserError(`Can't create stowaway for this ticket`)); + }); + + it('should return an empty list of tickets for a valid ticket', async() => { + let ticketId = 12; + let possibleStowaways = await app.models.Ticket.getPossibleStowaways(ticketId); + + expect(possibleStowaways.length).toEqual(0); + }); + + it('should return allowed list of tickets for a valid ticket', async() => { + let ticketId = 16; + let possibleStowaways = await app.models.Ticket.getPossibleStowaways(ticketId); + + expect(possibleStowaways.length).toEqual(1); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/getSales.spec.js b/modules/ticket/back/methods/ticket/specs/getSales.spec.js new file mode 100644 index 000000000..4e57f570f --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/getSales.spec.js @@ -0,0 +1,14 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket getSales()', () => { + it('should return the sales of a ticket', async() => { + let sales = await app.models.Ticket.getSales(16); + + expect(sales.length).toEqual(4); + expect(sales[0].item).toBeDefined(); + expect(sales[1].item).toBeDefined(); + expect(sales[2].item).toBeDefined(); + expect(sales[3].item).toBeDefined(); + expect(sales[0].claim).toBeDefined(); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js b/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js new file mode 100644 index 000000000..84e958dfa --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js @@ -0,0 +1,15 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket getSalesPersonMana()', () => { + it('should get the mana of a salesperson of a given ticket', async() => { + let mana = await app.models.Ticket.getSalesPersonMana(1); + + expect(mana).toEqual(124); + }); + + it('should return 0 if the given ticket does not exist', async() => { + let mana = await app.models.Ticket.getSalesPersonMana(99); + + expect(mana).toEqual(0); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/getTaxes.spec.js b/modules/ticket/back/methods/ticket/specs/getTaxes.spec.js new file mode 100644 index 000000000..74f336bbd --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/getTaxes.spec.js @@ -0,0 +1,9 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket getTaxes()', () => { + it('should return the tax of a given ticket', async() => { + let result = await app.models.Ticket.getTaxes(1); + + expect(result[0].tax).toEqual(77.54); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/getTotal.spec.js b/modules/ticket/back/methods/ticket/specs/getTotal.spec.js new file mode 100644 index 000000000..c3494bba9 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/getTotal.spec.js @@ -0,0 +1,15 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket getTotal()', () => { + it('should return the total of a ticket', async() => { + let result = await app.models.Ticket.getTotal(1); + + expect(result).toEqual(893.87); + }); + + it(`should return zero if the ticket doesn't have lines`, async() => { + let result = await app.models.Ticket.getTotal(21); + + expect(result).toEqual(0); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/getTotalVolume.spec.js b/modules/ticket/back/methods/ticket/specs/getTotalVolume.spec.js new file mode 100644 index 000000000..1901e2cb2 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/getTotalVolume.spec.js @@ -0,0 +1,13 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket getTotalVolume()', () => { + it('should return the total volume of a ticket', async() => { + let ticketFk = 1; + + let expectedResult = 1.568; + + let result = await app.models.Ticket.getTotalVolume(ticketFk); + + expect(result.totalVolume).toEqual(expectedResult); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/getVAT.spec.js b/modules/ticket/back/methods/ticket/specs/getVAT.spec.js new file mode 100644 index 000000000..8ba2a3285 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/getVAT.spec.js @@ -0,0 +1,10 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket getVAT()', () => { + it('should return the ticket VAT', async() => { + await app.models.Ticket.getVAT(1) + .then(response => { + expect(response).toEqual(84.64); + }); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/getVolume.spec.js b/modules/ticket/back/methods/ticket/specs/getVolume.spec.js new file mode 100644 index 000000000..8acf673af --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/getVolume.spec.js @@ -0,0 +1,11 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket getVolume()', () => { + it('should call the getVolume method', async() => { + let ticketFk = 1; + await app.models.Ticket.getVolume(ticketFk) + .then(response => { + expect(response[0].m3).toEqual(1.09); + }); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/isEditable.spec.js b/modules/ticket/back/methods/ticket/specs/isEditable.spec.js new file mode 100644 index 000000000..a40128954 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/isEditable.spec.js @@ -0,0 +1,52 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket isEditable()', () => { + it('should return false if the given ticket is not editable', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let result = await app.models.Ticket.isEditable(ctx, 2); + + expect(result).toEqual(false); + }); + + it('should return false if the given ticket does not exist', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let result = await app.models.Ticket.isEditable(ctx, 99999); + + expect(result).toEqual(false); + }); + + it('should return false if the given ticket isDeleted', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let result = await app.models.Ticket.isEditable(ctx, 19); + + expect(result).toEqual(false); + }); + + it('should return true if the given ticket is editable', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let result = await app.models.Ticket.isEditable(ctx, 16); + + expect(result).toEqual(true); + }); + + it('should be able to edit a deleted or invoiced ticket if the role is salesAssistant', async() => { + let ctx = {req: {accessToken: {userId: 21}}}; + let result = await app.models.Ticket.isEditable(ctx, 8); + + expect(result).toEqual(true); + }); + + it('should be able to edit a deleted or invoiced ticket if the role is productionBoss', async() => { + let ctx = {req: {accessToken: {userId: 50}}}; + let result = await app.models.Ticket.isEditable(ctx, 8); + + expect(result).toEqual(true); + }); + + it('should not be able to edit a deleted or invoiced ticket if the role is salesPerson', async() => { + let ctx = {req: {accessToken: {userId: 18}}}; + let result = await app.models.Ticket.isEditable(ctx, 8); + + expect(result).toEqual(false); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/isEmpty.spec.js b/modules/ticket/back/methods/ticket/specs/isEmpty.spec.js new file mode 100644 index 000000000..df8818261 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/isEmpty.spec.js @@ -0,0 +1,27 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket isEmpty()', () => { + it('should return false if the ticket contains any packages', async() => { + let result = await app.models.Ticket.isEmpty(3); + + expect(result).toBeFalsy(); + }); + + it('should return false if the ticket contains any services', async() => { + let result = await app.models.Ticket.isEmpty(8); + + expect(result).toBeFalsy(); + }); + + it('should return false if the ticket contains any purchase request', async() => { + let result = await app.models.Ticket.isEmpty(11); + + expect(result).toBeFalsy(); + }); + + it('should return false if the ticket contains any sale', async() => { + let result = await app.models.Ticket.isEmpty(4); + + expect(result).toBeFalsy(); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js b/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js new file mode 100644 index 000000000..247e7e621 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js @@ -0,0 +1,38 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket makeInvoice()', () => { + let invoice; + let ticketId = 11; + + afterAll(async done => { + let ticket = await app.models.Ticket.findById(11); + await ticket.updateAttributes({refFk: null}); + + let ticketTracking = await app.models.TicketTracking.findOne({order: 'id DESC', limit: 1}); + await ticketTracking.destroy(); + + let invoiceOut = await app.models.InvoiceOut.findById(invoice.invoiceFk); + await invoiceOut.destroy(); + + done(); + }); + + it('should invoice a ticket', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + invoice = await app.models.Ticket.makeInvoice(ctx, ticketId); + + expect(invoice.invoiceFk).toBeDefined(); + expect(invoice.serial).toEqual('T'); + }); + + it('should not invoice an already invoiced ticket', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let error; + + await app.models.Ticket.makeInvoice(ctx, ticketId).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`This ticket can't be invoiced`); + }); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/new.spec.js b/modules/ticket/back/methods/ticket/specs/new.spec.js new file mode 100644 index 000000000..80147c2f2 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/new.spec.js @@ -0,0 +1,59 @@ +const app = require('vn-loopback/server/server'); +let UserError = require('vn-loopback/util/user-error'); + + +describe('ticket new()', () => { + let ticket; + let today = new Date(); + let ctx = {req: {accessToken: {userId: 1}}}; + + afterAll(async done => { + await app.models.Ticket.destroyById(ticket.id); + + done(); + }); + + it('should throw an error if the client isnt frozen and isnt active', async() => { + let error; + let params = {addressFk: 6}; + + await app.models.Ticket.new(ctx, params) + .catch(e => { + error = e; + }); + + expect(error).toEqual(new UserError(`You can't create a ticket for a inactive client`)); + }); + + it('should throw an error if the address doesnt exist', async() => { + let error; + let params = {addressFk: 'invalid address', clientFk: 104}; + + await app.models.Ticket.new(ctx, params) + .catch(response => { + expect(response.message).toEqual(`This address doesn't exist`); + error = response; + }); + + expect(error).toBeDefined(); + }); + + it('should return the id of the created ticket', async() => { + let params = { + warehouseFk: 1, + clientFk: 104, + companyFk: 442, + addressFk: 4, + agencyModeFk: 1, + userId: 9, + shipped: today, + landed: today + }; + + ticket = await app.models.Ticket.new(ctx, params); + + let newestTicketIdInFixtures = 21; + + expect(ticket.id).toBeGreaterThan(newestTicketIdInFixtures); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js b/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js new file mode 100644 index 000000000..61060c9a2 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js @@ -0,0 +1,41 @@ +const app = require('vn-loopback/server/server'); +let UserError = require('vn-loopback/util/user-error'); + +describe('sale priceDifference()', () => { + it('should return ticket price differences', async() => { + let tomorrow = new Date(); + tomorrow.setDate(tomorrow.getDate() + 1); + + const ticketId = 16; + const landed = tomorrow; + const addressId = 126; + const agencyModeId = 7; + const zoneId = 3; + const warehouseId = 1; + + const httpCtx = {req: {accessToken: {userId: 106}}}; + let result = await app.models.Ticket.priceDifference(httpCtx, ticketId, landed, + addressId, agencyModeId, zoneId, warehouseId); + + expect(result.totalUnitPrice).toEqual(215.77); + expect(result.totalNewPrice).toEqual(215.77); + expect(result.totalDifference).toEqual(0); + }); + + it('should return an error if the ticket is not editable', async() => { + const ticketId = 1; + const landed = new Date(); + const addressId = 121; + const zoneId = 3; + const warehouseId = 1; + let error; + const httpCtx = {req: {accessToken: {userId: 106}}}; + await app.models.Ticket.priceDifference(httpCtx, ticketId, landed, addressId, zoneId, warehouseId) + .catch(e => { + error = e; + }); + + + expect(error).toEqual(new UserError(`The sales of this ticket can't be modified`)); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js b/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js new file mode 100644 index 000000000..72be4c3b4 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js @@ -0,0 +1,24 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket recalculateComponents()', () => { + const ticketId = 11; + + it('should update the ticket components', async() => { + const ctx = {req: {accessToken: {userId: 9}}}; + const response = await app.models.Ticket.recalculateComponents(ctx, ticketId); + + expect(response.affectedRows).toBeDefined(); + }); + + it('should throw an error if the ticket is not editable', async() => { + const ctx = {req: {accessToken: {userId: 9}}}; + const immutableTicketId = 1; + await app.models.Ticket.recalculateComponents(ctx, immutableTicketId) + .catch(response => { + expect(response).toEqual(new Error(`The current ticket can't be modified`)); + error = response; + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js new file mode 100644 index 000000000..890fc6c45 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js @@ -0,0 +1,56 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket deleted()', () => { + let ticket; + let ctx; + + beforeAll(async done => { + let originalTicket = await app.models.Ticket.findOne({where: {id: 16}}); + originalTicket.id = null; + ticket = await app.models.Ticket.create(originalTicket); + + ctx = { + req: { + accessToken: {userId: 106}, + headers: { + origin: 'http://localhost:5000' + }, + __: () => {} + } + }; + + done(); + }); + + afterAll(async done => { + await app.models.Ticket.destroyById(ticket.id); + + done(); + }); + + it('should make sure the ticket is not deleted yet', async() => { + expect(ticket.isDeleted).toEqual(false); + }); + + it('should set a ticket to deleted', async() => { + await app.models.Ticket.setDeleted(ctx, ticket.id); + + let deletedTicket = await app.models.Ticket.findOne({where: {id: ticket.id}, fields: ['isDeleted']}); + + expect(deletedTicket.isDeleted).toEqual(true); + }); + + it('should throw an error if the given ticket has a claim', async() => { + let ticketId = 16; + let error; + + try { + await app.models.Ticket.setDeleted(ctx, ticketId); + } catch (e) { + error = e; + } + + expect(error.translateArgs[0]).toEqual(2); + expect(error.message).toEqual('You must delete the claim id %d first'); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/subtotal.spec.js b/modules/ticket/back/methods/ticket/specs/subtotal.spec.js new file mode 100644 index 000000000..bd706b6b5 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/subtotal.spec.js @@ -0,0 +1,15 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket subtotal()', () => { + it('should return the subtotal of a ticket', async() => { + let result = await app.models.Ticket.subtotal(1); + + expect(result).toEqual(809.23); + }); + + it(`should return 0 if the ticket doesn't have lines`, async() => { + let result = await app.models.Ticket.subtotal(21); + + expect(result).toEqual(0.00); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/summary.spec.js b/modules/ticket/back/methods/ticket/specs/summary.spec.js new file mode 100644 index 000000000..c67db0520 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/summary.spec.js @@ -0,0 +1,36 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket summary()', () => { + it('should return a summary object containing data from 1 ticket', async() => { + let result = await app.models.Ticket.summary(1); + + expect(result.id).toEqual(1); + expect(result.nickname).toEqual('Bat cave'); + }); + + it('should return a summary object containing sales from 1 ticket', async() => { + let result = await app.models.Ticket.summary(1); + + expect(result.sales.length).toEqual(4); + }); + + it('should return a summary object containing subtotal for 1 ticket', async() => { + let result = await app.models.Ticket.summary(1); + + expect(Math.round(result.subtotal * 100) / 100).toEqual(809.23); + }); + + it('should return a summary object containing VAT for 1 ticket', async() => { + let result = await app.models.Ticket.summary(1); + + expect(Math.round(result.vat * 100) / 100).toEqual(84.64); + }); + + it('should return a summary object containing total for 1 ticket', async() => { + let result = await app.models.Ticket.summary(1); + let total = result.subtotal + result.vat; + let expectedTotal = Math.round(total * 100) / 100; + + expect(result.total).toEqual(expectedTotal); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/transferSales.spec.js b/modules/ticket/back/methods/ticket/specs/transferSales.spec.js new file mode 100644 index 000000000..63f2034bb --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/transferSales.spec.js @@ -0,0 +1,162 @@ +const app = require('vn-loopback/server/server'); + +describe('sale transferSales()', () => { + let createdTicketId; + let createdTicketsIds = []; + + afterAll(async done => { + createdTicketsIds.forEach(async createdTicketId => { + await app.models.Ticket.destroyById(createdTicketId); + }); + done(); + }); + + it('should throw an error as the ticket is not editable', async() => { + const ctx = {req: {accessToken: {userId: 101}}}; + let error; + + const currentTicketId = 1; + const receiverTicketId = undefined; + const sales = []; + + await app.models.Ticket.transferSales(ctx, currentTicketId, receiverTicketId, sales) + .catch(response => { + expect(response.message).toEqual(`The sales of this ticket can't be modified`); + error = response; + }); + + expect(error).toBeDefined(); + }); + + it('should throw an error if the receiving ticket is not editable', async() => { + const ctx = {req: {accessToken: {userId: 101}}}; + let error; + + const currentTicketId = 16; + const receiverTicketId = 1; + const sales = []; + + await app.models.Ticket.transferSales(ctx, currentTicketId, receiverTicketId, sales) + .catch(response => { + expect(response.message).toEqual(`The sales of the receiver ticket can't be modified`); + error = response; + }); + + expect(error).toBeDefined(); + }); + + it('should transfer the sales from one ticket to a new one', async() => { + const ctx = {req: {accessToken: {userId: 101}}}; + let currentTicket = await app.models.Ticket.findById(11); + let originalTicketSales = await app.models.Ticket.getSales(currentTicket.id); + salesToRestone = originalTicketSales; + + expect(originalTicketSales.length).toEqual(2); + + const currentTicketId = currentTicket.id; + const receiverTicketId = undefined; + + let createdTicket = await app.models.Ticket.transferSales( + ctx, currentTicketId, receiverTicketId, originalTicketSales); + createdTicketId = createdTicket.id; + createdTicketsIds.push(createdTicket.id); + + originalTicketSales = await app.models.Ticket.getSales(currentTicket.id); + receiverTicketSales = await app.models.Ticket.getSales(createdTicket.id); + + expect(originalTicketSales.length).toEqual(0); + expect(receiverTicketSales.length).toEqual(2); + }); + + it('should transfer back the sales and set the created ticket as deleted', async() => { + const ctx = {req: {accessToken: {userId: 101}}}; + const currentTicket = await app.models.Ticket.findById(createdTicketId); + const receiverTicketId = 11; + + let createdTicket = await app.models.Ticket.findById(createdTicketId); + let createdTicketSales = await app.models.Ticket.getSales(createdTicketId); + let receiverTicketSales = await app.models.Ticket.getSales(receiverTicketId); + + const currentTicketId = currentTicket.id; + const sales = createdTicketSales; + + expect(createdTicket.isDeleted).toBeFalsy(); + expect(createdTicketSales.length).toEqual(2); + expect(receiverTicketSales.length).toEqual(0); + + await app.models.Ticket.transferSales( + ctx, currentTicketId, receiverTicketId, sales); + + createdTicket = await app.models.Ticket.findById(createdTicketId); + createdTicketSales = await app.models.Ticket.getSales(createdTicketId); + receiverTicketSales = await app.models.Ticket.getSales(receiverTicketId); + + expect(createdTicket.isDeleted).toBeTruthy(); + expect(createdTicketSales.length).toEqual(0); + expect(receiverTicketSales.length).toEqual(2); + }); + + describe('sale transferPartialSales()', () => { + it('should throw an error in the quantity to transfer exceeds the amount from the original sale', async() => { + const ctx = {req: {accessToken: {userId: 101}}}; + let error; + let currentTicket = await app.models.Ticket.findById(11); + let currentTicketSales = await app.models.Ticket.getSales(currentTicket.id); + + const currentTicketId = currentTicket.id; + const receiverTicketId = undefined; + + currentTicketSales[0].quantity = 99; + + await app.models.Ticket.transferSales( + ctx, currentTicketId, receiverTicketId, currentTicketSales) + .catch(response => { + expect(response.message).toEqual(`Invalid quantity`); + error = response; + }); + + expect(error).toBeDefined(); + }); + + it('should transfer two sales to a new ticket but one shall be partial', async() => { + const ctx = {req: {accessToken: {userId: 101}}}; + const originalTicketId = 11; + const receiverTicketId = undefined; + + let currentTicketSales = await app.models.Ticket.getSales(originalTicketId); + + const originalPartialSaleId = currentTicketSales[0].id; + const originalCompleteSaleId = currentTicketSales[1].id; + let originalQuantity = currentTicketSales[0].quantity; + currentTicketSales[0].quantity = 1; + + let createdTicket = await app.models.Ticket.transferSales( + ctx, originalTicketId, receiverTicketId, currentTicketSales); + + createdTicketId = createdTicket.id; + createdTicketsIds.push(createdTicket.id); + + currentTicketSales = await app.models.Ticket.getSales(originalTicketId); + receiverTicketSales = await app.models.Ticket.getSales(createdTicketId); + + const [createdPartialSale] = receiverTicketSales.filter(sale => { + return sale.id != originalCompleteSaleId; + }); + + expect(currentTicketSales.length).toEqual(1); + expect(currentTicketSales[0].quantity).toEqual(originalQuantity -= 1); + expect(receiverTicketSales.length).toEqual(2); + expect(createdPartialSale.quantity).toEqual(1); + + let saleToRestore = await app.models.Sale.findById(originalPartialSaleId); + await saleToRestore.updateAttribute('quantity', originalQuantity); + + let saleToReturnToTicket = await app.models.Sale.findById(originalCompleteSaleId); + await saleToReturnToTicket.updateAttribute('ticketFk', originalTicketId); + + currentTicketSales = await app.models.Ticket.getSales(originalTicketId); + + expect(currentTicketSales.length).toEqual(2); + }); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js new file mode 100644 index 000000000..75de1f538 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js @@ -0,0 +1,97 @@ +const app = require('vn-loopback/server/server'); + +describe('sale updateDiscount()', () => { + const originalSaleId = 8; + let componentId; + let originalSale; + let salesPersonMana; + + beforeAll(async done => { + originalSale = await app.models.Sale.findById(originalSaleId); + let manaDiscount = await app.models.ComponentRate.findOne({where: {code: 'mana'}}); + componentId = manaDiscount.id; + + let ticket = await app.models.Ticket.findById(originalSale.ticketFk); + let client = await app.models.Client.findById(ticket.clientFk); + salesPersonMana = await app.models.WorkerMana.findById(client.salesPersonFk); + + done(); + }); + + afterAll(async done => { + await originalSale.save(); + await app.models.SaleComponent.updateAll({componentFk: componentId, saleFk: originalSaleId}, {value: 0}); + await salesPersonMana.save(); + + done(); + }); + + + it('should throw an error if no sales were selected', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let error; + const ticketId = 11; + const sales = []; + const newDiscount = 10; + + try { + await app.models.Ticket.updateDiscount(ctx, ticketId, sales, newDiscount); + } catch (err) { + error = err; + } + + expect(error.message).toEqual('Please select at least one sale'); + }); + + it('should throw an error if no sales belong to different tickets', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let error; + const ticketId = 11; + const sales = [1, 14]; + const newDiscount = 10; + + try { + await app.models.Ticket.updateDiscount(ctx, ticketId, sales, newDiscount); + } catch (err) { + error = err; + } + + expect(error.message).toEqual('All sales must belong to the same ticket'); + }); + + it('should throw an error if the ticket is invoiced already', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let error; + const ticketId = 1; + const sales = [1]; + const newDiscount = 100; + + try { + await app.models.Ticket.updateDiscount(ctx, ticketId, sales, newDiscount); + } catch (err) { + error = err; + } + + expect(error.message).toEqual(`The sales of this ticket can't be modified`); + }); + + it('should update the discount if the salesPerson has mana', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + const ticketId = 11; + const sales = [originalSaleId]; + const newDiscount = 100; + + await app.models.Ticket.updateDiscount(ctx, ticketId, sales, newDiscount); + + let updatedSale = await app.models.Sale.findById(originalSaleId); + let createdSaleComponent = await app.models.SaleComponent.findOne({ + where: { + componentFk: componentId, + saleFk: originalSaleId + } + }); + + expect(createdSaleComponent.componentFk).toEqual(componentId); + expect(updatedSale.discount).toEqual(100); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/updateEditableTicket.spec.js b/modules/ticket/back/methods/ticket/specs/updateEditableTicket.spec.js new file mode 100644 index 000000000..16d8d1edb --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/updateEditableTicket.spec.js @@ -0,0 +1,39 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket updateEditableTicket()', () => { + const validTicketId = 12; + const invalidTicketId = 1; + const data = {addressFk: 1}; + const originalData = {addressFk: 123}; + + afterAll(async done => { + let ctx = {req: {accessToken: {userId: 9}}}; + await app.models.Ticket.updateEditableTicket(ctx, validTicketId, originalData); + + done(); + }); + + it('should now throw an error if the ticket is not editable', async() => { + let error; + let ctx = {req: {accessToken: {userId: 9}}}; + + await app.models.Ticket.updateEditableTicket(ctx, invalidTicketId, data).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual('This ticket can not be modified'); + }); + + expect(error).toBeDefined(); + }); + + + it('should edit the ticket address', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + + await app.models.Ticket.updateEditableTicket(ctx, validTicketId, data); + + let updatedTicket = await app.models.Ticket.findById(validTicketId); + + expect(updatedTicket.addressFk).toEqual(1); + }); +}); diff --git a/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js b/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js new file mode 100644 index 000000000..78b935ab5 --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/uploadFile.spec.js @@ -0,0 +1,19 @@ +const app = require('vn-loopback/server/server'); + +describe('Ticket uploadFile()', () => { + it(`should return an error for a user without enough privileges`, async() => { + let ticketId = 15; + let currentUserId = 101; + let ticketTypeId = 14; + let ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: ticketTypeId}}; + + let error; + await app.models.Ticket.uploadFile(ctx, ticketId).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`You don't have enough privileges`); + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/modules/ticket/back/methods/ticket/subtotal.js b/modules/ticket/back/methods/ticket/subtotal.js new file mode 100644 index 000000000..0fd16fbdd --- /dev/null +++ b/modules/ticket/back/methods/ticket/subtotal.js @@ -0,0 +1,39 @@ +module.exports = Self => { + Self.remoteMethod('subtotal', { + description: 'Returns the total of a ticket', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'ticket id', + http: {source: 'path'} + }], + returns: { + type: 'number', + root: true + }, + http: { + path: `/:id/subtotal`, + verb: 'GET' + } + }); + + Self.subtotal = async ticketFk => { + const sale = Self.app.models.Sale; + const ticketSales = await sale.find({where: {ticketFk}}); + const ticketService = Self.app.models.TicketService; + const ticketServices = await ticketService.find({where: {ticketFk}}); + + let subtotal = 0.00; + ticketSales.forEach(sale => { + subtotal += sale.price * sale.quantity * ((100 - sale.discount) / 100); + }); + + ticketServices.forEach(service => { + subtotal += service.price * service.quantity; + }); + + return Math.round(subtotal * 100) / 100; + }; +}; diff --git a/modules/ticket/back/methods/ticket/summary.js b/modules/ticket/back/methods/ticket/summary.js new file mode 100644 index 000000000..2b1d8711c --- /dev/null +++ b/modules/ticket/back/methods/ticket/summary.js @@ -0,0 +1,152 @@ +module.exports = Self => { + Self.remoteMethod('summary', { + description: 'Returns a ticket summary', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'ticket id', + http: {source: 'path'} + }], + returns: { + type: [this.modelName], + root: true + }, + http: { + path: `/:id/summary`, + verb: 'GET' + } + }); + + Self.summary = async ticketFk => { + let models = Self.app.models; + let summaryObj = await getTicketData(Self, ticketFk); + summaryObj.sales = await getSales(models.Sale, ticketFk); + summaryObj.subtotal = await models.Ticket.subtotal(ticketFk); + summaryObj.vat = await models.Ticket.getVAT(ticketFk); + summaryObj.total = summaryObj.subtotal + summaryObj.vat; + summaryObj.packagings = await models.TicketPackaging.find({ + where: {ticketFk: ticketFk}, + include: [{relation: 'packaging', + scope: { + fields: ['itemFk', 'name'], + include: { + relation: 'item' + } + } + }] + }); + summaryObj.requests = await getRequests(Self, ticketFk); + summaryObj.services = await models.TicketService.find({ + where: {ticketFk: ticketFk}, + include: [{relation: 'taxClass'}] + }); + + return summaryObj; + }; + + async function getTicketData(Self, ticketFk) { + let filter = { + include: [ + {relation: 'warehouse', scope: {fields: ['name']}}, + {relation: 'agencyMode', scope: {fields: ['name']}}, + { + relation: 'client', + scope: { + fields: ['salesPersonFk', 'name'], + include: { + relation: 'salesPerson', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + } + } + }, + { + relation: 'address', + scope: { + fields: ['street', 'city', 'provinceFk', 'phone'], + include: { + relation: 'province', + scope: { + fields: ['name'] + } + } + } + }, + { + relation: 'notes', + scope: { + fields: ['id', 'observationTypeFk', 'description'], + include: { + relation: 'observationType', + fields: ['description'] + } + } + }, + { + relation: 'state', + scope: { + fields: ['stateFk'], + include: { + relation: 'state', + fields: ['name'] + } + } + } + ], + where: {id: ticketFk} + }; + + return await Self.findOne(filter); + } + + async function getSales(Sale, ticketFk) { + let filter = { + where: { + ticketFk: ticketFk + }, + order: 'concept', + include: [ + {relation: 'item'}, + {relation: 'claimBeginning'} + ] + }; + return await Sale.find(filter); + } + + async function getRequests(Self, ticketFk) { + let filter = { + where: { + ticketFk: ticketFk + }, + include: [ + { + relation: 'requester', + scope: { + include: { + relation: 'user' + } + } + }, { + relation: 'atender', + scope: { + include: { + relation: 'user' + } + } + }, { + relation: 'sale' + } + ] + }; + return await Self.app.models.TicketRequest.find(filter); + } +}; diff --git a/modules/ticket/back/methods/ticket/transferSales.js b/modules/ticket/back/methods/ticket/transferSales.js new file mode 100644 index 000000000..9d39453be --- /dev/null +++ b/modules/ticket/back/methods/ticket/transferSales.js @@ -0,0 +1,174 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('transferSales', { + description: 'Transfer sales to a new or a given ticket', + accepts: [{ + arg: 'id', + type: 'Number', + required: true, + description: 'Origin ticket id', + http: {source: 'path'} + }, + { + arg: 'ticketId', + type: 'Number', + description: 'Destination ticket id', + required: false + }, + { + arg: 'sales', + type: ['Object'], + description: 'The sales to transfer', + required: true + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/transferSales`, + verb: 'POST' + } + }); + + Self.transferSales = async(ctx, id, ticketId, sales) => { + let userId = ctx.req.accessToken.userId; + const models = Self.app.models; + + const isEditable = await models.Ticket.isEditable(ctx, id); + if (!isEditable) + throw new UserError(`The sales of this ticket can't be modified`); + + if (ticketId) { + const isReceiverEditable = await models.Ticket.isEditable(ctx, ticketId); + if (!isReceiverEditable) + throw new UserError(`The sales of the receiver ticket can't be modified`); + } + + let tx = await Self.beginTransaction({}); + + try { + const options = {transaction: tx}; + const originalTicket = await models.Ticket.findById(id, null, options); + const originalSales = await models.Sale.find({ + where: {ticketFk: id} + }, options); + + if (!ticketId) + ticketId = await cloneTicket(originalTicket, options); + + const map = new Map(); + for (const sale of originalSales) + map.set(sale.id, sale); + + + for (const sale of sales) { + const originalSale = map.get(sale.id); + + let originalSaleQuantity = originalSale.quantity; + + if (sale.quantity == originalSale.quantity) { + await models.Sale.updateAll({ + id: sale.id + }, {ticketFk: ticketId}, options); + } else if (sale.quantity != originalSale.quantity) { + await transferPartialSale( + ticketId, originalSale, sale, options); + } + + let logTicketOrigin = { + originFk: id, + userFk: userId, + action: 'update', + changedModel: 'Ticket', + changedModelId: ticketId, + oldInstance: {item: sale.itemFk, + quantity: 0, + concept: sale.concept, + ticket: ticketId}, + newInstance: {item: sale.itemFk, + quantity: sale.quantity, + concept: sale.concept, + ticket: ticketId} + }; + await models.TicketLog.create(logTicketOrigin, options); + + let logTicketDestination = { + originFk: ticketId, + userFk: userId, + action: 'update', + changedModel: 'Ticket', + changedModelId: ticketId, + oldInstance: {item: sale.itemFk, + quantity: originalSaleQuantity, + concept: sale.concept, + ticket: id}, + newInstance: {item: sale.itemFk, + quantity: originalSaleQuantity - sale.quantity, + concept: sale.concept, + ticket: id} + }; + await models.TicketLog.create(logTicketDestination, options); + } + + const isTicketEmpty = await models.Ticket.isEmpty(id, options); + if (isTicketEmpty) { + await originalTicket.updateAttributes({ + isDeleted: true + }, options); + } + + await tx.commit(); + + return {id: ticketId}; + } catch (error) { + await tx.rollback(); + throw error; + } + }; + + async function cloneTicket(ticket, options) { + query = `CALL vn.ticket_Clone(?, @result); + SELECT @result newTicketId;`; + let result = await Self.rawSql(query, [ + ticket.id + ], options); + + return result[1][0].newTicketId; + } + + async function transferPartialSale(ticketId, originalSale, sale, options) { + const models = Self.app.models; + + if (sale.quantity > originalSale.quantity) + throw new UserError('Invalid quantity'); + + // Update original sale + const rest = originalSale.quantity - sale.quantity; + const updatedSale = await models.Sale.updateAll({ + id: sale.id + }, {quantity: rest}, options); + // Clone sale with new quantity + const newSale = originalSale; + newSale.id = undefined; + newSale.ticketFk = ticketId; + newSale.quantity = sale.quantity; + + const createdSale = await models.Sale.create(newSale, options); + + // Clone sale components + const saleComponents = await models.SaleComponent.find({ + where: {saleFk: sale.id} + }, options); + const newComponents = saleComponents.map(component => { + component.saleFk = createdSale.id; + + return component; + }); + + await models.SaleComponent.create(newComponents, options); + + return updatedSale; + } +}; diff --git a/modules/ticket/back/methods/ticket/updateDiscount.js b/modules/ticket/back/methods/ticket/updateDiscount.js new file mode 100644 index 000000000..94ada046f --- /dev/null +++ b/modules/ticket/back/methods/ticket/updateDiscount.js @@ -0,0 +1,120 @@ +let UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('updateDiscount', { + description: 'Changes the discount of a sale', + accessType: 'WRITE', + accepts: [ + { + arg: 'id', + description: 'The ticket id', + type: 'number', + required: true, + http: {source: 'path'} + }, + { + arg: 'salesIds', + description: 'The sales id', + type: ['number'], + required: true, + }, { + arg: 'newDiscount', + description: 'The new discount', + type: 'number', + required: true + } + ], + returns: { + type: 'string', + root: true + }, + http: { + path: `/:id/updateDiscount`, + verb: 'post' + } + }); + + Self.updateDiscount = async(ctx, id, salesIds, newDiscount) => { + const models = Self.app.models; + const tx = await Self.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const filter = { + where: { + id: {inq: salesIds} + }, + include: { + relation: 'ticket', + scope: { + include: { + relation: 'client', + scope: { + fields: ['salesPersonFk'] + } + }, + fields: ['id', 'clientFk'] + } + } + }; + + let sales = await models.Sale.find(filter, options); + + if (sales.length === 0) + throw new UserError('Please select at least one sale'); + + const allFromSameTicket = sales.every(sale => sale.ticketFk === id); + if (!allFromSameTicket) + throw new UserError('All sales must belong to the same ticket'); + + const isEditable = await models.Ticket.isEditable(ctx, id); + if (!isEditable) + throw new UserError(`The sales of this ticket can't be modified`); + + const ticket = await models.Ticket.findById(id, { + include: { + relation: 'client', + scope: { + fields: ['salesPersonFk'] + } + }, + }, options); + const salesPersonId = ticket.client().salesPersonFk; + const usesMana = await models.WorkerMana.findOne({ + where: { + workerFk: salesPersonId + }, + fields: 'amount'}, options); + + const componentCode = usesMana ? 'mana' : 'buyerDiscount'; + const discountComponent = await models.ComponentRate.findOne({ + where: {code: componentCode}}, options); + + const componentId = discountComponent.id; + + let promises = []; + for (let sale of sales) { + const value = ((-sale.price * newDiscount) / 100); + const newComponent = models.SaleComponent.upsert({ + saleFk: sale.id, + value: value, + componentFk: componentId}, options); + + const updatedSale = sale.updateAttribute('discount', newDiscount, options); + + promises.push(newComponent, updatedSale); + } + + await Promise.all(promises); + + query = `call vn.manaSpellersRequery(?)`; + await Self.rawSql(query, [salesPersonId], options); + + await tx.commit(); + } catch (error) { + await tx.rollback(); + throw error; + } + }; +}; diff --git a/modules/ticket/back/methods/ticket/updateEditableTicket.js b/modules/ticket/back/methods/ticket/updateEditableTicket.js new file mode 100644 index 000000000..39143f8a2 --- /dev/null +++ b/modules/ticket/back/methods/ticket/updateEditableTicket.js @@ -0,0 +1,41 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('updateEditableTicket', { + description: 'Change data of a ticket', + accessType: 'WRITE', + accepts: [ + { + arg: 'id', + type: 'number', + required: true, + description: 'Ticket id', + http: {source: 'path'} + }, + { + arg: 'data', + description: 'Model instance data', + type: 'Object', + required: true, + http: {source: 'body'} + } + ], + returns: { + type: 'object', + root: true + }, + http: { + path: '/:id/updateEditableTicket', + verb: 'POST' + } + + }); + Self.updateEditableTicket = async(ctx, id, data) => { + let ticketIsEditable = await Self.app.models.Ticket.isEditable(ctx, id); + if (!ticketIsEditable) + throw new UserError('This ticket can not be modified'); + + let ticket = await Self.app.models.Ticket.findById(id); + await ticket.updateAttributes(data); + }; +}; diff --git a/modules/ticket/back/methods/ticket/uploadFile.js b/modules/ticket/back/methods/ticket/uploadFile.js new file mode 100644 index 000000000..e5ea465cb --- /dev/null +++ b/modules/ticket/back/methods/ticket/uploadFile.js @@ -0,0 +1,76 @@ +module.exports = Self => { + Self.remoteMethodCtx('uploadFile', { + description: 'Upload and attach a document', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'Number', + description: 'The ticket id', + http: {source: 'path'} + }, { + arg: 'warehouseId', + type: 'Number', + description: 'The warehouse id', + required: true + }, { + arg: 'companyId', + type: 'Number', + description: 'The company id', + required: true + }, { + arg: 'dmsTypeId', + type: 'Number', + description: 'The dms type id', + required: true + }, { + arg: 'reference', + type: 'String', + required: true + }, { + arg: 'description', + type: 'String', + required: true + }, { + arg: 'hasFile', + type: 'Boolean', + description: 'True if has an attached file', + required: true + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/uploadFile`, + verb: 'POST' + } + }); + + Self.uploadFile = async(ctx, id) => { + const models = Self.app.models; + const promises = []; + const tx = await Self.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const uploadedFiles = await models.Dms.uploadFile(ctx, options); + uploadedFiles.forEach(dms => { + const newTicketDms = models.TicketDms.create({ + ticketFk: id, + dmsFk: dms.id + }, options); + + promises.push(newTicketDms); + }); + const resolvedPromises = await Promise.all(promises); + + await tx.commit(); + + return resolvedPromises; + } catch (err) { + await tx.rollback(); + throw err; + } + }; +}; diff --git a/modules/ticket/back/model-config.json b/modules/ticket/back/model-config.json new file mode 100644 index 000000000..3b38f1a16 --- /dev/null +++ b/modules/ticket/back/model-config.json @@ -0,0 +1,77 @@ +{ + "AlertLevel": { + "dataSource": "vn" + }, + "AnnualAverageInvoiced": { + "dataSource": "vn" + }, + "ComponentRate": { + "dataSource": "vn" + }, + "ComponentTypeRate": { + "dataSource": "vn" + }, + "Expedition": { + "dataSource": "vn" + }, + "Packaging": { + "dataSource": "vn" + }, + "Sale": { + "dataSource": "vn" + }, + "SaleChecked": { + "dataSource": "vn" + }, + "SaleComponent": { + "dataSource": "vn" + }, + "SaleTracking": { + "dataSource": "vn" + }, + "State":{ + "dataSource": "vn" + }, + "Stowaway": { + "dataSource": "vn" + }, + "Ticket": { + "dataSource": "vn" + }, + "TicketDms": { + "dataSource": "vn" + }, + "TicketLog": { + "dataSource": "vn" + }, + "TicketObservation": { + "dataSource": "vn" + }, + "TicketPackaging": { + "dataSource": "vn" + }, + "TicketRequest": { + "dataSource": "vn" + }, + "TicketState":{ + "dataSource": "vn" + }, + "TicketService":{ + "dataSource": "vn" + }, + "TicketServiceType":{ + "dataSource": "vn" + }, + "TicketTracking": { + "dataSource": "vn" + }, + "TicketUpdateAction": { + "dataSource": "vn" + }, + "TicketWeekly": { + "dataSource": "vn" + }, + "TicketConfig": { + "dataSource": "vn" + } +} diff --git a/modules/ticket/back/models/alert-level.json b/modules/ticket/back/models/alert-level.json new file mode 100644 index 000000000..75b5a9c46 --- /dev/null +++ b/modules/ticket/back/models/alert-level.json @@ -0,0 +1,29 @@ +{ + "name": "AlertLevel", + "description": "Alert levels of a ticket", + "base": "VnModel", + "options": { + "mysql": { + "table": "alertLevel" + } + }, + "properties": { + "code": { + "type": "String", + "id": true, + "description": "Identifier" + }, + "alertLevel": { + "type": "Number", + "id": true + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] + } \ No newline at end of file diff --git a/modules/ticket/back/models/annual-average-invoiced.json b/modules/ticket/back/models/annual-average-invoiced.json new file mode 100644 index 000000000..d1f582011 --- /dev/null +++ b/modules/ticket/back/models/annual-average-invoiced.json @@ -0,0 +1,24 @@ +{ + "name": "AnnualAverageInvoiced", + "base": "VnModel", + "options": { + "mysql": { + "table": "annualAverageInvoiced" + } + }, + "properties": { + "invoiced": { + "type": "Number" + }, + "clientFk": { + "id": true + } + }, + "relations": { + "client": { + "type": "belongsTo", + "model": "client", + "foreignKey": "clientFk" + } + } +} \ No newline at end of file diff --git a/modules/ticket/back/models/component-rate.json b/modules/ticket/back/models/component-rate.json new file mode 100644 index 000000000..535b6086f --- /dev/null +++ b/modules/ticket/back/models/component-rate.json @@ -0,0 +1,49 @@ +{ + "name": "ComponentRate", + "base": "VnModel", + "options": { + "mysql": { + "table": "component" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "name": { + "type": "String" + }, + "classRate": { + "type": "Number" + }, + "tax": { + "type": "Number" + }, + "isRenewable": { + "type": "Number" + }, + "typeFk": { + "type": "Number" + }, + "code": { + "type": "String" + } + }, + "relations": { + "componentType": { + "type": "belongsTo", + "model": "ComponentTypeRate", + "foreignKey": "typeFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} diff --git a/modules/ticket/back/models/component-type-rate.json b/modules/ticket/back/models/component-type-rate.json new file mode 100644 index 000000000..c9b80f45c --- /dev/null +++ b/modules/ticket/back/models/component-type-rate.json @@ -0,0 +1,25 @@ +{ + "name": "ComponentTypeRate", + "base": "VnModel", + "options": { + "mysql": { + "table": "componentType" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "type": { + "type": "String" + }, + "isBase":{ + "type":"String", + "mysql": { + "columnName": "base" + } + } + } +} diff --git a/modules/ticket/back/models/expedition.js b/modules/ticket/back/models/expedition.js new file mode 100644 index 000000000..9d6564373 --- /dev/null +++ b/modules/ticket/back/models/expedition.js @@ -0,0 +1,3 @@ +module.exports = function(Self) { + require('../methods/expedition/filter')(Self); +}; diff --git a/modules/ticket/back/models/expedition.json b/modules/ticket/back/models/expedition.json new file mode 100644 index 000000000..4a9682e03 --- /dev/null +++ b/modules/ticket/back/models/expedition.json @@ -0,0 +1,68 @@ +{ + "name": "Expedition", + "base": "Loggable", + "log": { + "model": "TicketLog", + "relation": "ticket" + }, + "options": { + "mysql": { + "table": "expedition" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "isBox": { + "type": "Number" + }, + "created": { + "type": "Date" + }, + "counter": { + "type": "Number" + }, + "checked": { + "type": "Number" + }, + "externalId": { + "type": "Number" + } + }, + "relations": { + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk" + }, + "agencyMode": { + "type": "belongsTo", + "model": "agency-mode", + "foreignKey": "agencyModeFk" + }, + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "packages": { + "type": "hasMany", + "model": "TicketPackaging", + "foreignKey": "ticketFk" + }, + "box": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "isBox" + } + } + } + \ No newline at end of file diff --git a/modules/ticket/back/models/packaging.js b/modules/ticket/back/models/packaging.js new file mode 100644 index 000000000..c252d02ce --- /dev/null +++ b/modules/ticket/back/models/packaging.js @@ -0,0 +1,3 @@ +module.exports = function(Self) { + require('../methods/packaging/listPackaging')(Self); +}; diff --git a/services/ticket/common/models/packaging.json b/modules/ticket/back/models/packaging.json similarity index 86% rename from services/ticket/common/models/packaging.json rename to modules/ticket/back/models/packaging.json index e05de2c93..9d5c098df 100644 --- a/services/ticket/common/models/packaging.json +++ b/modules/ticket/back/models/packaging.json @@ -9,19 +9,19 @@ "properties": { "id": { "id": true, - "type": "Number", + "type": "String", "description": "Identifier" }, "volume": { "type": "Number" }, - "X": { + "width": { "type": "Date" }, - "Y": { + "height": { "type": "Number" }, - "Z": { + "depth": { "type": "Number" }, "isPackageReturnable": { @@ -37,7 +37,7 @@ "relations": { "item": { "type": "belongsTo", - "model": "Iicket", + "model": "Item", "foreignKey": "itemFk" } } diff --git a/modules/ticket/back/models/sale-checked.json b/modules/ticket/back/models/sale-checked.json new file mode 100644 index 000000000..8ac52d598 --- /dev/null +++ b/modules/ticket/back/models/sale-checked.json @@ -0,0 +1,24 @@ +{ + "name": "SaleChecked", + "base": "VnModel", + "options": { + "mysql": { + "table": "saleChecked" + } + }, + "properties": { + "isChecked": { + "type": "Number" + }, + "saleFk": { + "id": true + } + }, + "relations": { + "sale": { + "type": "belongsTo", + "model": "Sale", + "foreignKey": "saleFk" + } + } +} \ No newline at end of file diff --git a/modules/ticket/back/models/sale-component.json b/modules/ticket/back/models/sale-component.json new file mode 100644 index 000000000..49edab2ae --- /dev/null +++ b/modules/ticket/back/models/sale-component.json @@ -0,0 +1,34 @@ +{ + "name": "SaleComponent", + "base": "VnModel", + "options": { + "mysql": { + "table": "saleComponent" + } + }, + "properties": { + "value": { + "type": "Number" + }, + "saleFk": { + "type": "Number", + "id": 2 + }, + "componentFk": { + "type": "Number", + "id": 1 + } + }, + "relations": { + "sale": { + "type": "belongsTo", + "model": "Sale", + "foreignKey": "saleFk" + }, + "componentRate": { + "type": "belongsTo", + "model": "ComponentRate", + "foreignKey": "componentFk" + } + } +} \ No newline at end of file diff --git a/modules/ticket/back/models/sale-tracking.js b/modules/ticket/back/models/sale-tracking.js new file mode 100644 index 000000000..4a46dd6b7 --- /dev/null +++ b/modules/ticket/back/models/sale-tracking.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/sale-tracking/listSaleTracking')(Self); +}; diff --git a/modules/ticket/back/models/sale-tracking.json b/modules/ticket/back/models/sale-tracking.json new file mode 100644 index 000000000..7936f827f --- /dev/null +++ b/modules/ticket/back/models/sale-tracking.json @@ -0,0 +1,38 @@ +{ + "name": "SaleTracking", + "base": "VnModel", + "options": { + "mysql": { + "table": "saleTracking" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "forceId": false + }, + "isChecked": { + "type": "boolean" + }, + "created": { + "type": "Date" + }, + "originalQuantity": { + "type": "Number" + } + }, + "relations": { + "sale": { + "type": "belongsTo", + "model": "Sale", + "foreignKey": "saleFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + } + } +} + \ No newline at end of file diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js new file mode 100644 index 000000000..4ffde08b3 --- /dev/null +++ b/modules/ticket/back/models/sale.js @@ -0,0 +1,13 @@ +module.exports = Self => { + require('../methods/sale/getClaimableFromTicket')(Self); + require('../methods/sale/reserve')(Self); + require('../methods/sale/removes')(Self); + require('../methods/sale/updatePrice')(Self); + require('../methods/sale/updateQuantity')(Self); + require('../methods/sale/updateConcept')(Self); + require('../methods/sale/recalculatePrice')(Self); + + Self.validatesPresenceOf('concept', { + message: `Concept cannot be blank` + }); +}; diff --git a/modules/ticket/back/models/sale.json b/modules/ticket/back/models/sale.json new file mode 100644 index 000000000..1f2ea4bbf --- /dev/null +++ b/modules/ticket/back/models/sale.json @@ -0,0 +1,82 @@ +{ + "name": "Sale", + "base": "Loggable", + "log": { + "model": "TicketLog", + "relation": "ticket", + "showField": "concept" + }, + "options": { + "mysql": { + "table": "sale" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "concept": { + "type": "String", + "required": true + }, + "quantity": { + "type": "Number" + }, + "price": { + "type": "Number" + }, + "discount": { + "type": "Number" + }, + "reserved": { + "type": "boolean" + }, + "isPicked": { + "type": "Number" + }, + "created": { + "type": "date" + } + }, + "relations": { + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk", + "required": true + }, + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk", + "required": true + }, + "isChecked": { + "type": "hasOne", + "model": "SaleChecked", + "foreignKey": "saleFk" + }, + "components": { + "type": "hasMany", + "model": "SaleComponent", + "foreignKey": "saleFk" + }, + "claimBeginning": { + "type": "hasOne", + "model": "ClaimBeginning", + "foreignKey": "saleFk" + }, + "saleTracking": { + "type": "hasOne", + "model": "SaleTracking", + "foreignKey": "saleFk" + }, + "itemShelving": { + "type": "hasOne", + "model": "ItemShelvingSale", + "foreignKey": "saleFk" + } + } +} diff --git a/modules/ticket/back/models/specs/state.spec.js b/modules/ticket/back/models/specs/state.spec.js new file mode 100644 index 000000000..e6239c8bc --- /dev/null +++ b/modules/ticket/back/models/specs/state.spec.js @@ -0,0 +1,17 @@ +const app = require('vn-loopback/server/server'); + +describe('loopback model State', () => { + describe('isAlertLevelZero()', () => { + it('should return true if the alerLevel is 0', async() => { + let result = await app.models.State.isAlertLevelZero(1); + + expect(result).toBeTruthy(); + }); + + it('should do nothing if the alertLevel isnt 0', async() => { + let result = await app.models.State.isAlertLevelZero(8); + + expect(result).toBeFalsy(); + }); + }); +}); diff --git a/modules/ticket/back/models/specs/ticket-packaging.spec.js b/modules/ticket/back/models/specs/ticket-packaging.spec.js new file mode 100644 index 000000000..893e0fb96 --- /dev/null +++ b/modules/ticket/back/models/specs/ticket-packaging.spec.js @@ -0,0 +1,40 @@ +const app = require('vn-loopback/server/server'); + +describe('ticket model TicketTracking', () => { + let ticketTrackingId; + + afterAll(async done => { + await app.models.TicketPackaging.destroyById(ticketTrackingId); + + done(); + }); + + it('should save a ticketTraing as the quantity is greater than 0', async() => { + let result = await app.models.TicketPackaging.create({ticketFk: 1, quantity: 1, packagingFk: 1}); + + expect(result).toBeTruthy(); + ticketTrackingId = result.id; + }); + + it('should return an error as the quantity is 0', async() => { + let error; + try { + await app.models.TicketPackaging.create({ticketFk: 1, quantity: 0, packagingFk: 1}); + } catch (e) { + error = e; + } + + expect(error.message).toContain('Enter an integer different to zero'); + }); + + it('should return an error as the quantity isnt a number', async() => { + let error; + try { + await app.models.TicketPackaging.create({ticketFk: 1, quantity: 'random string', packagingFk: 1}); + } catch (e) { + error = e; + } + + expect(error.message).toContain('Enter an integer different to zero'); + }); +}); diff --git a/modules/ticket/back/models/state.js b/modules/ticket/back/models/state.js new file mode 100644 index 000000000..5aa0ffabc --- /dev/null +++ b/modules/ticket/back/models/state.js @@ -0,0 +1,20 @@ +module.exports = Self => { + require('../methods/state/editableStates')(Self); + require('../methods/state/isEditable')(Self); + + /** + * Checks if the alertLevel of a state is 0. + * + * @param {Integer} stateId The user id + * @return {Boolean} %true if user has the role, %false otherwise + */ + Self.isAlertLevelZero = async function(stateId) { + let result = await Self.rawSql( + `SELECT alertLevel + FROM vn.state + WHERE id = ?`, + [stateId] + ); + return result[0].alertLevel == 0; + }; +}; diff --git a/modules/ticket/back/models/state.json b/modules/ticket/back/models/state.json new file mode 100644 index 000000000..efa56abee --- /dev/null +++ b/modules/ticket/back/models/state.json @@ -0,0 +1,32 @@ +{ + "name": "State", + "base": "VnModel", + "options": { + "mysql": { + "table": "state" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "forceId": false + }, + "name": { + "type": "String", + "required": false + }, + "order": { + "type": "Number", + "required": false + }, + "alertLevel": { + "type": "Number", + "required": false + }, + "code": { + "type": "String", + "required": false + } + } +} diff --git a/modules/ticket/back/models/stowaway.js b/modules/ticket/back/models/stowaway.js new file mode 100644 index 000000000..780b6b31c --- /dev/null +++ b/modules/ticket/back/models/stowaway.js @@ -0,0 +1,24 @@ +const LoopBackContext = require('loopback-context'); +const UserError = require('vn-loopback/util/user-error'); + +module.exports = function(Self) { + Self.observe('before save', async function(ctx) { + const models = Self.app.models; + const canHaveStowaway = await models.Ticket.canHaveStowaway(ctx.instance.shipFk); + + if (!canHaveStowaway) + throw new UserError(`Can't create stowaway for this ticket`); + + if (ctx.isNewInstance) { + let where = { + code: 'BOARDING' + }; + let state = await models.State.findOne({where}); + let params = {ticketFk: ctx.instance.shipFk, stateFk: state.id}; + const loopBackContext = LoopBackContext.getCurrentContext(); + + let httpCtx = {req: loopBackContext.active}; + await models.TicketTracking.changeState(httpCtx, params); + } + }); +}; diff --git a/modules/ticket/back/models/stowaway.json b/modules/ticket/back/models/stowaway.json new file mode 100644 index 000000000..5a925cd20 --- /dev/null +++ b/modules/ticket/back/models/stowaway.json @@ -0,0 +1,36 @@ +{ + "name": "Stowaway", + "base": "VnModel", + "options": { + "mysql": { + "table": "stowaway" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "forceId": false + }, + "shipFk": { + "type": "Number", + "required": false + }, + "created":{ + "type": "Date", + "required": false + } + }, + "relations": { + "ship": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "shipFk" + }, + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "id" + } + } +} diff --git a/modules/ticket/back/models/ticket-config.json b/modules/ticket/back/models/ticket-config.json new file mode 100644 index 000000000..ff6818bb5 --- /dev/null +++ b/modules/ticket/back/models/ticket-config.json @@ -0,0 +1,19 @@ +{ + "name": "TicketConfig", + "base": "VnModel", + "options": { + "mysql": { + "table": "ticketConfig" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "scopeDays": { + "type": "Number" + } + } +} diff --git a/modules/ticket/back/models/ticket-dms.js b/modules/ticket/back/models/ticket-dms.js new file mode 100644 index 000000000..8a6d03434 --- /dev/null +++ b/modules/ticket/back/models/ticket-dms.js @@ -0,0 +1,4 @@ +module.exports = Self => { + require('../methods/ticket-dms/removeFile')(Self); + require('../methods/ticket-dms/allowedContentTypes')(Self); +}; diff --git a/modules/ticket/back/models/ticket-dms.json b/modules/ticket/back/models/ticket-dms.json new file mode 100644 index 000000000..b7b24dce0 --- /dev/null +++ b/modules/ticket/back/models/ticket-dms.json @@ -0,0 +1,32 @@ +{ + "name": "TicketDms", + "base": "Loggable", + "log": { + "model": "TicketLog", + "relation": "ticket" + }, + "options": { + "mysql": { + "table": "ticketDms" + } + }, + "properties": { + "dmsFk": { + "type": "Number", + "id": true, + "required": true + } + }, + "relations": { + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk" + }, + "dms": { + "type": "belongsTo", + "model": "Dms", + "foreignKey": "dmsFk" + } + } +} \ No newline at end of file diff --git a/modules/ticket/back/models/ticket-log.json b/modules/ticket/back/models/ticket-log.json new file mode 100644 index 000000000..950742e98 --- /dev/null +++ b/modules/ticket/back/models/ticket-log.json @@ -0,0 +1,58 @@ +{ + "name": "TicketLog", + "base": "VnModel", + "options": { + "mysql": { + "table": "ticketLog" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "forceId": false + }, + "originFk": { + "type": "Number", + "required": true + }, + "userFk": { + "type": "Number" + }, + "action": { + "type": "String", + "required": true + }, + "changedModel": { + "type": "String" + }, + "oldInstance": { + "type": "Object" + }, + "newInstance": { + "type": "Object" + }, + "creationDate": { + "type": "Date" + }, + "changedModelId": { + "type": "Number" + }, + "changedModelValue": { + "type": "String" + }, + "description": { + "type": "String" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + } + }, + "scope": { + "order": ["creationDate DESC", "id DESC"] + } +} diff --git a/modules/ticket/back/models/ticket-observation.js b/modules/ticket/back/models/ticket-observation.js new file mode 100644 index 000000000..77d15d85c --- /dev/null +++ b/modules/ticket/back/models/ticket-observation.js @@ -0,0 +1,9 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError(`The observation type can't be repeated`); + return err; + }); +}; diff --git a/modules/ticket/back/models/ticket-observation.json b/modules/ticket/back/models/ticket-observation.json new file mode 100644 index 000000000..51469c7a6 --- /dev/null +++ b/modules/ticket/back/models/ticket-observation.json @@ -0,0 +1,38 @@ +{ + "name": "TicketObservation", + "base": "Loggable", + "log": { + "model": "TicketLog", + "relation": "ticket" + }, + "options": { + "mysql": { + "table": "ticketObservation" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "description": { + "type": "String", + "required": true + } + }, + "relations": { + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk", + "required": true + }, + "observationType": { + "type": "belongsTo", + "model": "ObservationType", + "foreignKey": "observationTypeFk", + "required": true + } + } +} diff --git a/modules/ticket/back/models/ticket-packaging.js b/modules/ticket/back/models/ticket-packaging.js new file mode 100644 index 000000000..801e35351 --- /dev/null +++ b/modules/ticket/back/models/ticket-packaging.js @@ -0,0 +1,13 @@ +module.exports = function(Self) { + Self.validateBinded('quantity', validateQuantity, { + message: 'Enter an integer different to zero', + allowNull: false, + allowBlank: false + }); + + function validateQuantity(quantity) { + return !isNaN(quantity) && quantity != 0; + } + + Self.validatesPresenceOf('packagingFk', {message: 'Package cannot be blank'}); +}; diff --git a/modules/ticket/back/models/ticket-packaging.json b/modules/ticket/back/models/ticket-packaging.json new file mode 100644 index 000000000..feea541fa --- /dev/null +++ b/modules/ticket/back/models/ticket-packaging.json @@ -0,0 +1,41 @@ +{ + "name": "TicketPackaging", + "base": "Loggable", + "log": { + "model": "TicketLog", + "relation": "ticket" + }, + "options": { + "mysql": { + "table": "ticketPackaging" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "quantity": { + "type": "Number" + }, + "created": { + "type": "Date" + }, + "pvp": { + "type": "Number" + } + }, + "relations": { + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk" + }, + "packaging": { + "type": "belongsTo", + "model": "Packaging", + "foreignKey": "packagingFk" + } + } +} diff --git a/modules/ticket/back/models/ticket-request.js b/modules/ticket/back/models/ticket-request.js new file mode 100644 index 000000000..f711ed23e --- /dev/null +++ b/modules/ticket/back/models/ticket-request.js @@ -0,0 +1,17 @@ +const LoopBackContext = require('loopback-context'); + +module.exports = function(Self) { + require('../methods/ticket-request/filter')(Self); + require('../methods/ticket-request/deny')(Self); + require('../methods/ticket-request/confirm')(Self); + + Self.observe('before save', async function(ctx) { + if (ctx.isNewInstance) { + const loopBackContext = LoopBackContext.getCurrentContext(); + let filter = {where: {userFk: loopBackContext.active.accessToken.userId}}; + let worker = await Self.app.models.Worker.findOne(filter); + + ctx.instance.requesterFk = worker.id; + } + }); +}; diff --git a/modules/ticket/back/models/ticket-request.json b/modules/ticket/back/models/ticket-request.json new file mode 100644 index 000000000..f216cd531 --- /dev/null +++ b/modules/ticket/back/models/ticket-request.json @@ -0,0 +1,67 @@ +{ + "name": "TicketRequest", + "base": "Loggable", + "log": { + "model": "TicketLog", + "relation": "ticket" + }, + "options": { + "mysql": { + "table": "ticketRequest" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "description": { + "type": "String", + "required": true + }, + "created": { + "type": "Date" + }, + "quantity": { + "type": "Number", + "required": true + }, + "price": { + "type": "Number" + }, + "isOk": { + "type": "Boolean" + }, + "response": { + "type": "String" + } + }, + "relations": { + "sale": { + "type": "belongsTo", + "model": "Sale", + "foreignKey": "saleFk" + }, + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk" + }, + "atender": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "attenderFk" + }, + "requester": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "requesterFk" + }, + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk" + } + } +} \ No newline at end of file diff --git a/modules/ticket/back/models/ticket-service-type.json b/modules/ticket/back/models/ticket-service-type.json new file mode 100644 index 000000000..9912c7952 --- /dev/null +++ b/modules/ticket/back/models/ticket-service-type.json @@ -0,0 +1,33 @@ +{ + "name": "TicketServiceType", + "options": { + "mysql": { + "table": "ticketServiceType" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "name": { + "type": "String", + "required": true + }, + "expenseFk": { + "type": "Number", + "required": true, + "mysql": { + "columnName": "expenceFk" + } + } + }, + "relations": { + "expenditure": { + "type": "belongsTo", + "model": "Expense", + "foreignKey": "expenseFk" + } + } +} \ No newline at end of file diff --git a/modules/ticket/back/models/ticket-service.js b/modules/ticket/back/models/ticket-service.js new file mode 100644 index 000000000..cdb57650a --- /dev/null +++ b/modules/ticket/back/models/ticket-service.js @@ -0,0 +1,33 @@ +const UserError = require('vn-loopback/util/user-error'); +const LoopBackContext = require('loopback-context'); + +module.exports = Self => { + Self.observe('before save', async ctx => { + const loopBackContext = LoopBackContext.getCurrentContext(); + const httpCtx = {req: loopBackContext.active}; + const models = Self.app.models; + let changes = ctx.currentInstance || ctx.instance; + if (changes) { + let ticketId = changes.ticketFk; + let isEditable = await models.Ticket.isEditable(httpCtx, ticketId); + if (!isEditable) + throw new UserError(`The current ticket can't be modified`); + + if (changes.ticketServiceTypeFk) { + const ticketServiceType = await models.TicketServiceType.findById(changes.ticketServiceTypeFk); + changes.description = ticketServiceType.name; + } + } + }); + + Self.observe('before delete', async ctx => { + const loopBackContext = LoopBackContext.getCurrentContext(); + const httpCtx = {req: loopBackContext.active}; + const models = Self.app.models; + const service = await models.TicketService.findById(ctx.where.id); + const isEditable = await models.Ticket.isEditable(httpCtx, service.ticketFk); + + if (!isEditable) + throw new UserError(`The current ticket can't be modified`); + }); +}; diff --git a/modules/ticket/back/models/ticket-service.json b/modules/ticket/back/models/ticket-service.json new file mode 100644 index 000000000..8b0c490a8 --- /dev/null +++ b/modules/ticket/back/models/ticket-service.json @@ -0,0 +1,62 @@ +{ + "name": "TicketService", + "base": "Loggable", + "log": { + "model": "TicketLog", + "relation": "ticket", + "showField": "description" + }, + "options": { + "mysql": { + "table": "ticketService" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "ticketFk": { + "type": "Number", + "required": true + }, + "description": { + "type": "String", + "required": true + }, + "quantity": { + "type": "Number", + "required": true + }, + "price": { + "type": "Number", + "required": true + }, + "taxClassFk": { + "type": "Number", + "required": true + }, + "ticketServiceTypeFk": { + "type": "Number", + "required": true + } + }, + "relations": { + "taxClass": { + "type": "belongsTo", + "model": "TaxClass", + "foreignKey": "taxClassFk" + }, + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk" + }, + "ticketService": { + "type": "belongsTo", + "model": "TicketServiceType", + "foreignKey": "ticketServiceTypeFk" + } + } +} \ No newline at end of file diff --git a/modules/ticket/back/models/ticket-state.json b/modules/ticket/back/models/ticket-state.json new file mode 100644 index 000000000..e53c4d0f5 --- /dev/null +++ b/modules/ticket/back/models/ticket-state.json @@ -0,0 +1,39 @@ +{ + "name": "TicketState", + "base": "VnModel", + "options": { + "mysql": { + "table": "ticketState" + } + }, + "properties": { + "ticketFk": { + "id": true, + "type": "Number", + "forceId": false + }, + "updated": { + "type": "Date" + }, + "alertLevel": { + "type": "Number" + } + }, + "relations": { + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk" + }, + "state": { + "type": "belongsTo", + "model": "State", + "foreignKey": "stateFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + } + } +} diff --git a/modules/ticket/back/models/ticket-tracking.js b/modules/ticket/back/models/ticket-tracking.js new file mode 100644 index 000000000..2b2a93536 --- /dev/null +++ b/modules/ticket/back/models/ticket-tracking.js @@ -0,0 +1,6 @@ +module.exports = function(Self) { + require('../methods/ticket-tracking/changeState')(Self); + + Self.validatesPresenceOf('stateFk', {message: 'State cannot be blank'}); + Self.validatesPresenceOf('workerFk', {message: 'Worker cannot be blank'}); +}; diff --git a/modules/ticket/back/models/ticket-tracking.json b/modules/ticket/back/models/ticket-tracking.json new file mode 100644 index 000000000..550df7d9c --- /dev/null +++ b/modules/ticket/back/models/ticket-tracking.json @@ -0,0 +1,43 @@ +{ + "name": "TicketTracking", + "base": "Loggable", + "log": { + "model": "TicketLog", + "relation": "ticket", + "showField": "stateFk" + }, + "options": { + "mysql": { + "table": "ticketTracking" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "forceId": false + }, + "created": { + "type": "Date", + "required": false + } + }, + "relations": { + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk" + }, + "state": { + "type": "belongsTo", + "model": "State", + "foreignKey": "stateFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + } + } +} + \ No newline at end of file diff --git a/modules/ticket/back/models/ticket-update-action.json b/modules/ticket/back/models/ticket-update-action.json new file mode 100644 index 000000000..c4a4ce8df --- /dev/null +++ b/modules/ticket/back/models/ticket-update-action.json @@ -0,0 +1,28 @@ +{ + "name": "TicketUpdateAction", + "base": "VnModel", + "options": { + "mysql": { + "table": "ticketUpdateAction" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "description": { + "type": "String", + "required": true + } +}, +"acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } +] +} diff --git a/modules/ticket/back/models/ticket-weekly.js b/modules/ticket/back/models/ticket-weekly.js new file mode 100644 index 000000000..733f1483a --- /dev/null +++ b/modules/ticket/back/models/ticket-weekly.js @@ -0,0 +1,19 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + require('../methods/ticket-weekly/filter')(Self); + + Self.validatesPresenceOf('ticketFk', { + message: `Ticket id cannot be blank` + }); + + Self.validatesPresenceOf('weekDay', { + message: `Weekday cannot be blank` + }); + + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError(`This ticket is already on weekly tickets`); + return err; + }); +}; diff --git a/modules/ticket/back/models/ticket-weekly.json b/modules/ticket/back/models/ticket-weekly.json new file mode 100644 index 000000000..c19e79bc1 --- /dev/null +++ b/modules/ticket/back/models/ticket-weekly.json @@ -0,0 +1,30 @@ +{ + "name": "TicketWeekly", + "base": "Loggable", + "log": { + "model": "TicketLog", + "relation": "ticket", + "showField": "ticketFk" + }, + "options": { + "mysql": { + "table": "ticketWeekly" + } + }, + "properties": { + "ticketFk": { + "id": true, + "type": "Number" + }, + "weekDay": { + "type": "Number" + } + }, + "relations": { + "ticket": { + "type": "belongsTo", + "model": "Ticket", + "foreignKey": "ticketFk" + } + } +} \ No newline at end of file diff --git a/modules/ticket/back/models/ticket.js b/modules/ticket/back/models/ticket.js new file mode 100644 index 000000000..8ba2bfb0d --- /dev/null +++ b/modules/ticket/back/models/ticket.js @@ -0,0 +1,51 @@ + +module.exports = Self => { + require('../methods/ticket/changeWorker')(Self); + require('../methods/ticket/getVolume')(Self); + require('../methods/ticket/getTotalVolume')(Self); + require('../methods/ticket/summary')(Self); + require('../methods/ticket/getTotal')(Self); + require('../methods/ticket/getTaxes')(Self); + require('../methods/ticket/subtotal')(Self); + require('../methods/ticket/priceDifference')(Self); + require('../methods/ticket/componentUpdate')(Self); + require('../methods/ticket/new')(Self); + require('../methods/ticket/isEditable')(Self); + require('../methods/ticket/setDeleted')(Self); + require('../methods/ticket/getVAT')(Self); + require('../methods/ticket/getSales')(Self); + require('../methods/ticket/getSalesPersonMana')(Self); + require('../methods/ticket/filter')(Self); + require('../methods/ticket/getPossibleStowaways')(Self); + require('../methods/ticket/canBeInvoiced')(Self); + require('../methods/ticket/makeInvoice')(Self); + require('../methods/ticket/updateEditableTicket')(Self); + require('../methods/ticket/isEmpty')(Self); + require('../methods/ticket/updateDiscount')(Self); + require('../methods/ticket/uploadFile')(Self); + require('../methods/ticket/addSale')(Self); + require('../methods/ticket/transferSales')(Self); + require('../methods/ticket/canHaveStowaway')(Self); + require('../methods/ticket/recalculateComponents')(Self); + require('../methods/ticket/deleteStowaway')(Self); + + Self.observe('before save', async function(ctx) { + if (ctx.isNewInstance) return; + + let changes = ctx.data || ctx.instance; + + if (changes.routeFk === null && ctx.currentInstance.routeFk != null) { + let instance = JSON.parse(JSON.stringify(ctx.currentInstance)); + let userId = ctx.options.accessToken.userId; + let logRecord = { + originFk: ctx.currentInstance.routeFk, + userFk: userId, + action: 'delete', + changedModel: 'Route', + oldInstance: {ticket: instance.id}, + newInstance: null + }; + await Self.app.models.RouteLog.create(logRecord); + } + }); +}; diff --git a/modules/ticket/back/models/ticket.json b/modules/ticket/back/models/ticket.json new file mode 100644 index 000000000..113e6a75f --- /dev/null +++ b/modules/ticket/back/models/ticket.json @@ -0,0 +1,121 @@ +{ + "name": "Ticket", + "base": "Loggable", + "log": { + "model":"TicketLog" + }, + "options": { + "mysql": { + "table": "ticket" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "shipped": { + "type": "Date", + "required": true + }, + "landed": { + "type": "Date" + }, + "nickname": { + "type": "String" + }, + "location": { + "type": "String" + }, + "solution": { + "type": "String" + }, + "packages": { + "type": "Number" + }, + "created": { + "type": "Date" + }, + "isDeleted": { + "type": "boolean" + }, + "priority": { + "type": "Number" + } + }, + "relations": { + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "clientFk" + }, + "ship": { + "type": "hasOne", + "model": "Stowaway", + "foreignKey": "shipFk" + }, + "stowaway": { + "type": "hasOne", + "model": "Stowaway", + "foreignKey": "id" + }, + "warehouse": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseFk" + }, + "invoiceOut": { + "type": "belongsTo", + "model": "InvoiceOut", + "foreignKey": "refFk", + "primaryKey": "ref" + }, + "address": { + "type": "belongsTo", + "model": "Address", + "foreignKey": "addressFk" + }, + "route": { + "type": "belongsTo", + "model": "Route", + "foreignKey": "routeFk" + }, + "company": { + "type": "belongsTo", + "model": "Company", + "foreignKey": "companyFk" + }, + "agencyMode": { + "type": "belongsTo", + "model": "AgencyMode", + "foreignKey": "agencyModeFk", + "required": true + }, + "packages": { + "type": "hasMany", + "model": "TicketPackaging", + "foreignKey": "ticketFk" + }, + "tracking": { + "type": "hasMany", + "model": "TicketTracking", + "foreignKey": "ticketFk" + }, + "notes": { + "type": "hasMany", + "model": "TicketObservation", + "foreignKey": "ticketFk" + }, + "state": { + "type": "hasOne", + "model": "TicketState", + "foreignKey": "ticketFk" + }, + "zone": { + "type": "belongsTo", + "model": "Zone", + "foreignKey": "zoneFk" + } + } +} \ No newline at end of file diff --git a/modules/ticket/front/basic-data/index.html b/modules/ticket/front/basic-data/index.html new file mode 100644 index 000000000..f313110b3 --- /dev/null +++ b/modules/ticket/front/basic-data/index.html @@ -0,0 +1,12 @@ + + + + + diff --git a/modules/ticket/front/basic-data/index.js b/modules/ticket/front/basic-data/index.js new file mode 100644 index 000000000..1afe6f9aa --- /dev/null +++ b/modules/ticket/front/basic-data/index.js @@ -0,0 +1,36 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $state) { + this.$scope = $scope; + this.$state = $state; + } + + set ticket(data) { + if (!data) return; + + this.data = Object.assign({}, data); + } + + registerChild(child) { + this.child = child; + } + + onStepChange(state) { + return this.child.onStepChange(state); + } + + onSubmit() { + this.child.onSubmit(); + } +} + +Controller.$inject = ['$scope', '$state']; + +ngModule.component('vnTicketBasicData', { + template: require('./index.html'), + bindings: { + ticket: '<' + }, + controller: Controller +}); diff --git a/modules/ticket/front/basic-data/step-one/index.html b/modules/ticket/front/basic-data/step-one/index.html new file mode 100644 index 000000000..ccdf8a15f --- /dev/null +++ b/modules/ticket/front/basic-data/step-one/index.html @@ -0,0 +1,93 @@ + + +
    + + + + + + + {{::!isActive ? '(Inactive)' : ''}} + {{::nickname}} + + , {{::street}}, {{::city}}, {{::province.name}} - {{::agencyMode.name}} + + + + + + + + + + + + + + + + + + + + + + {{::name}} - Max. {{::hour | date: 'HH:mm'}} h. + + + + +
    diff --git a/modules/ticket/front/basic-data/step-one/index.js b/modules/ticket/front/basic-data/step-one/index.js new file mode 100644 index 000000000..820d3d2c6 --- /dev/null +++ b/modules/ticket/front/basic-data/step-one/index.js @@ -0,0 +1,251 @@ +import ngModule from '../../module'; +import './style.scss'; + +class Controller { + constructor($scope, $http, $translate, vnApp) { + this.$scope = $scope; + this.$http = $http; + this.$translate = $translate; + this.vnApp = vnApp; + } + + $onInit() { + this.basicData.registerChild(this); + } + + get ticket() { + return this._ticket; + } + + set ticket(value) { + this._ticket = value; + + if (!value || !value.id) return; + + this.onChangeClient(value.clientFk); + } + + get clientId() { + return this.ticket && this.ticket.clientFk; + } + + set clientId(value) { + this.ticket.clientFk = value; + this.ticket.addressFk = null; + + this.onChangeClient(value); + } + + get addressId() { + return this.ticket && this.ticket.addressFk; + } + + set addressId(value) { + if (value != this.ticket.addressFk) { + this.ticket.addressFk = value; + this.getShipped({ + landed: this.ticket.landed, + addressFk: value, + agencyModeFk: this.ticket.agencyModeFk, + warehouseFk: this.ticket.warehouseFk + }); + } + } + + get warehouseId() { + return this.ticket && this.ticket.warehouseFk; + } + + set warehouseId(value) { + if (value != this.ticket.warehouseFk) { + this.ticket.warehouseFk = value; + this.getShipped({ + landed: this.ticket.landed, + addressFk: this.ticket.addressFk, + agencyModeFk: this.ticket.agencyModeFk, + warehouseFk: value + }); + } + } + + + get shipped() { + return this.ticket && this.ticket.shipped; + } + + set shipped(value) { + this.ticket.shipped = value; + this.getLanded({ + shipped: value, + addressFk: this.ticket.addressFk, + agencyModeFk: this.ticket.agencyModeFk, + warehouseFk: this.ticket.warehouseFk + }); + } + + get landed() { + return this.ticket && this.ticket.landed; + } + + set landed(value) { + this.ticket.landed = value; + this.getShipped({ + landed: value, + addressFk: this.ticket.addressFk, + agencyModeFk: this.ticket.agencyModeFk, + warehouseFk: this.ticket.warehouseFk + }); + } + + get agencyModeId() { + return this.ticket && this.ticket.agencyModeFk; + } + + set agencyModeId(value) { + if (value != this.ticket.agencyModeFk) { + this.ticket.agencyModeFk = value; + this.getLanded({ + shipped: this.ticket.shipped, + addressFk: this.ticket.addressFk, + agencyModeFk: value, + warehouseFk: this.ticket.warehouseFk + }); + } + } + + get zoneId() { + return this.ticket && this.ticket.zoneFk; + } + + set zoneId(value) { + if (value != this.ticket.zoneFk) { + this.ticket.zoneFk = value; + this.onChangeZone(value); + } + } + + /* + * Autocompletes address on client change + */ + onChangeClient(value) { + let filter = { + include: [ + { + relation: 'province', + scope: { + fields: ['name'] + } + }, + { + relation: 'agencyMode', + scope: { + fields: ['name'] + } + } + ] + }; + filter = encodeURIComponent(JSON.stringify(filter)); + + let query = `Clients/${value}/addresses?filter=${filter}`; + this.$http.get(query).then(res => { + if (res.data) + this.addresses = res.data; + }); + } + + /* + * Gets an agency from an specified zone + */ + onChangeZone(zoneId) { + this.ticket.agencyModeFk = null; + const query = `Zones/${zoneId}`; + this.$http.get(query).then(res => { + this.ticket.agencyModeFk = res.data.agencyModeFk; + }); + } + + async onStepChange() { + if (this.isFormInvalid()) { + return this.vnApp.showError( + this.$translate.instant('Some fields are invalid') + ); + } + + let query = `tickets/${this.ticket.id}/priceDifference`; + let params = { + landed: this.ticket.landed, + addressId: this.ticket.addressFk, + agencyModeId: this.ticket.agencyModeFk, + zoneId: this.ticket.zoneFk, + warehouseId: this.ticket.warehouseFk + }; + + return this.$http.post(query, params).then(res => { + if (res.data) + this.ticket.sale = res.data; + + return true; + }, err => { + this.vnApp.showError( + this.$translate.instant(err.data.error.message) + ); + }); + } + + /* + * Returns a landing date + */ + getLanded(params) { + this.ticket.zoneFk = null; + const query = `Agencies/getLanded`; + this.$http.get(query, {params}).then(res => { + if (res.data) { + this.ticket.zoneFk = res.data.zoneFk; + this.ticket.landed = res.data.landed; + this.ticket.shipped = params.shipped; + } else { + return this.vnApp.showError( + this.$translate.instant(`No delivery zone available for this landing date`) + ); + } + }); + } + + /* + * Returns a shipment date + */ + getShipped(params) { + this.ticket.zoneFk = null; + const query = `Agencies/getShipped`; + this.$http.get(query, {params}).then(res => { + if (res.data) { + this.ticket.zoneFk = res.data.zoneFk; + this.ticket.landed = params.landed; + this.ticket.shipped = res.data.shipped; + } else { + return this.vnApp.showError( + this.$translate.instant(`No delivery zone available for this landing date`) + ); + } + }); + } + + isFormInvalid() { + return !this.ticket.clientFk || !this.ticket.addressFk || !this.ticket.agencyModeFk + || !this.ticket.companyFk || !this.ticket.shipped || !this.ticket.landed + || !this.ticket.zoneFk; + } +} + +Controller.$inject = ['$scope', '$http', '$translate', 'vnApp']; + +ngModule.component('vnTicketBasicDataStepOne', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<' + }, + require: { + basicData: '^vnTicketBasicData' + } +}); diff --git a/modules/ticket/front/basic-data/step-one/index.spec.js b/modules/ticket/front/basic-data/step-one/index.spec.js new file mode 100644 index 000000000..690399131 --- /dev/null +++ b/modules/ticket/front/basic-data/step-one/index.spec.js @@ -0,0 +1,361 @@ +import './index.js'; + +describe('Ticket', () => { + describe('Component vnTicketBasicDataStepOne', () => { + let $state; + let controller; + let $httpBackend; + let $httpParamSerializer; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_, _$httpParamSerializer_) => { + $state = _$state_; + $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; + controller = $componentController('vnTicketBasicDataStepOne', {$state}); + controller.ticket = { + addressFk: 121, + agencyModeFk: 7, + warehouseFk: 1 + }; + })); + + describe('ticket() setter', () => { + it('should set ticket property and call onChangeClient() method', () => { + spyOn(controller, 'onChangeClient'); + controller.ticket = {id: 1, clientFk: 101}; + + expect(controller.onChangeClient).toHaveBeenCalledWith(101); + }); + + it(`should not call onChangeClient() method as the ticket doesn't have an ID`, () => { + spyOn(controller, 'onChangeClient'); + controller.ticket = {}; + + expect(controller.onChangeClient).not.toHaveBeenCalledWith(); + }); + }); + + describe('clientId() getter', () => { + it('should return the clientFk property', () => { + controller.ticket = {id: 1, clientFk: 102}; + + expect(controller.clientId).toEqual(102); + }); + }); + + describe('clientId() setter', () => { + it('should set clientId property and call onChangeClient() method ', () => { + spyOn(controller, 'onChangeClient'); + controller.ticket = {id: 1, clientId: 101}; + controller.clientId = 102; + + expect(controller.onChangeClient).toHaveBeenCalledWith(102); + }); + }); + + describe('adressId() getter', () => { + it('should return the addressFk property', () => { + controller.ticket = {id: 1, addressFk: 99}; + + expect(controller.addressId).toEqual(99); + }); + }); + + describe('addressId() setter', () => { + it('should set addressId property and call getShipped() method ', () => { + spyOn(controller, 'getShipped'); + controller.ticket.addressFk = 99; + controller.addressId = 100; + const landed = new Date(); + const expectedResult = { + landed: landed, + addressFk: 100, + agencyModeFk: 7, + warehouseFk: 1 + }; + controller.landed = landed; + + expect(controller.getShipped).toHaveBeenCalledWith(expectedResult); + expect(controller.ticket.addressFk).toEqual(100); + }); + }); + + describe('warehouseId() getter', () => { + it('should return the warehouseId property', () => { + controller.ticket.warehouseFk = 2; + + expect(controller.warehouseId).toEqual(2); + }); + }); + + describe('warehouseId() setter', () => { + it('should set warehouseId property and call getShipped() method ', () => { + spyOn(controller, 'getShipped'); + controller.ticket.warehouseId = 1; + controller.warehouseId = 2; + const landed = new Date(); + const expectedResult = { + landed: landed, + addressFk: 121, + agencyModeFk: 7, + warehouseFk: 2 + }; + controller.landed = landed; + + expect(controller.getShipped).toHaveBeenCalledWith(expectedResult); + expect(controller.ticket.warehouseFk).toEqual(2); + }); + }); + + describe('shipped() getter', () => { + it('should return the shipped property', () => { + const shipped = new Date(); + controller.ticket.shipped = shipped; + + expect(controller.shipped).toEqual(shipped); + }); + }); + + describe('shipped() setter', () => { + it('should set shipped property and call getLanded() method ', () => { + spyOn(controller, 'getLanded'); + const shipped = new Date(); + const expectedResult = { + shipped: shipped, + addressFk: 121, + agencyModeFk: 7, + warehouseFk: 1 + }; + controller.shipped = shipped; + + expect(controller.getLanded).toHaveBeenCalledWith(expectedResult); + }); + }); + + describe('landed() getter', () => { + it('should return the landed property', () => { + const landed = new Date(); + controller.ticket.landed = landed; + + expect(controller.landed).toEqual(landed); + }); + }); + + describe('landed() setter', () => { + it('should set shipped property and call getShipped() method ', () => { + spyOn(controller, 'getShipped'); + const landed = new Date(); + const expectedResult = { + landed: landed, + addressFk: 121, + agencyModeFk: 7, + warehouseFk: 1 + }; + controller.landed = landed; + + + expect(controller.getShipped).toHaveBeenCalledWith(expectedResult); + }); + }); + + describe('agencyModeId() getter', () => { + it('should return the agencyModeFk property', () => { + controller.ticket.agencyModeFk = 66; + + expect(controller.agencyModeId).toEqual(66); + }); + }); + + describe('agencyModeId() setter', () => { + it('should set agencyModeId property and call getLanded() method', () => { + spyOn(controller, 'getLanded'); + const shipped = new Date(); + const agencyModeId = 8; + const expectedResult = { + shipped: shipped, + addressFk: 121, + agencyModeFk: agencyModeId, + warehouseFk: 1 + }; + controller.ticket.shipped = shipped; + controller.agencyModeId = 8; + + expect(controller.getLanded).toHaveBeenCalledWith(expectedResult); + }); + + it('should do nothing if attempting to set the same agencyMode id', () => { + spyOn(controller, 'getShipped'); + const landed = new Date(); + const agencyModeId = 7; + const expectedResult = { + landed: landed, + addressFk: 121, + agencyModeFk: agencyModeId, + warehouseFk: 1 + }; + controller.ticket.landed = landed; + controller.agencyModeId = 7; + + expect(controller.getShipped).not.toHaveBeenCalledWith(expectedResult); + }); + }); + + describe('zoneId() getter', () => { + it('should return the zoneFk property', () => { + controller.ticket.zoneFk = 10; + + expect(controller.zoneId).toEqual(10); + }); + }); + + describe('zoneId() setter', () => { + it('should set zoneId property and call onChangeZone() method ', () => { + const zoneId = 5; + spyOn(controller, 'onChangeZone'); + controller.ticket = {id: 1}; + controller.zoneId = 5; + + expect(controller.onChangeZone).toHaveBeenCalledWith(zoneId); + }); + + it('should do nothing if attempting to set the same zone id', () => { + const zoneId = 5; + spyOn(controller, 'onChangeZone'); + controller.ticket = {id: 1, zoneFk: zoneId}; + controller.zoneId = zoneId; + + expect(controller.onChangeZone).not.toHaveBeenCalledWith(zoneId); + }); + }); + + describe('onChangeClient()', () => { + it('should return a list of addresses from choosed client', async() => { + const clientId = 102; + let filter = { + include: [ + { + relation: 'province', + scope: { + fields: ['name'] + } + }, + { + relation: 'agencyMode', + scope: { + fields: ['name'] + } + } + ] + }; + filter = encodeURIComponent(JSON.stringify(filter)); + + $httpBackend.when('GET', `Clients/${clientId}/addresses?filter=${filter}`).respond(200); + $httpBackend.expect('GET', `Clients/${clientId}/addresses?filter=${filter}`); + controller.onChangeClient(clientId); + $httpBackend.flush(); + }); + }); + + describe('onChangeZone()', () => { + it('should return an available zone', async() => { + const zoneId = 5; + const agencyModeFk = 8; + $httpBackend.when('GET', `Zones/${zoneId}`).respond(200, {agencyModeFk}); + $httpBackend.expect('GET', `Zones/${zoneId}`); + controller.onChangeZone(zoneId); + $httpBackend.flush(); + + expect(controller.ticket.agencyModeFk).toEqual(agencyModeFk); + }); + }); + + describe('isFormInvalid()', () => { + it('should check if all form fields are valid', () => { + controller.ticket = { + clientFk: 1, + addressFk: 121, + zoneFk: 3, + agencyModeFk: 1, + companyFk: 442, + warehouseFk: 1, + shipped: new Date(), + landed: new Date() + }; + + expect(controller.isFormInvalid()).toBeFalsy(); + }); + }); + + describe('onStepChange()', () => { + it('should call onStepChange method and return a NO_AGENCY_AVAILABLE signal error', async() => { + let landed = new Date(); + landed.setHours(0, 0, 0, 0); + + controller._ticket = { + id: 1, + clientFk: 1, + addressFk: 121, + zoneFk: 3, + agencyModeFk: 1, + companyFk: 442, + warehouseFk: 1, + shipped: new Date(), + landed: landed + }; + + let response = {error: new Error('NO_AGENCY_AVAILABLE')}; + + $httpBackend.whenPOST(`tickets/1/priceDifference`).respond(400, response); + $httpBackend.expectPOST(`tickets/1/priceDifference`); + controller.onStepChange(); + $httpBackend.flush(); + }); + }); + + describe('getLanded()', () => { + it('should return an available landed date', async() => { + const shipped = new Date(); + const expectedResult = {landed: new Date()}; + const params = { + shipped: shipped, + addressFk: 121, + agencyModeFk: 7, + warehouseFk: 1 + }; + const serializedParams = $httpParamSerializer(params); + + $httpBackend.when('GET', `Agencies/getLanded?${serializedParams}`).respond(200, expectedResult); + $httpBackend.expect('GET', `Agencies/getLanded?${serializedParams}`); + controller.getLanded(params); + $httpBackend.flush(); + + expect(controller.shipped).toEqual(shipped); + expect(controller.landed).toEqual(expectedResult.landed); + }); + }); + + describe('getShipped()', () => { + it('should return an available shipped date', async() => { + const landed = new Date(); + const expectedResult = {shipped: new Date()}; + const params = { + landed: landed, + addressFk: 121, + agencyModeFk: 7, + warehouseFk: 1 + }; + const serializedParams = $httpParamSerializer(params); + + $httpBackend.when('GET', `Agencies/getShipped?${serializedParams}`).respond(200, expectedResult); + $httpBackend.expect('GET', `Agencies/getShipped?${serializedParams}`); + controller.getShipped(params); + $httpBackend.flush(); + + expect(controller.shipped).toEqual(expectedResult.shipped); + expect(controller.landed).toEqual(landed); + }); + }); + }); +}); diff --git a/modules/ticket/front/basic-data/step-one/locale/es.yml b/modules/ticket/front/basic-data/step-one/locale/es.yml new file mode 100644 index 000000000..ab804aea5 --- /dev/null +++ b/modules/ticket/front/basic-data/step-one/locale/es.yml @@ -0,0 +1,5 @@ +No delivery zone available for this landing date: No hay una zona de reparto disponible para la fecha de envío seleccionada +No delivery zone available for this shipping date: No hay una zona de reparto disponible para la fecha de preparación seleccionada +No delivery zone available for this parameters: No hay una zona de reparto disponible con estos parámetros +Deleted: Eliminado +Zone: Zona \ No newline at end of file diff --git a/modules/ticket/front/basic-data/step-one/style.scss b/modules/ticket/front/basic-data/step-one/style.scss new file mode 100644 index 000000000..756d662fd --- /dev/null +++ b/modules/ticket/front/basic-data/step-one/style.scss @@ -0,0 +1,8 @@ +@import "variables"; + +.vn-popover { + .address.inactive { + color: $color-font-secondary; + width: 100%; + } +} diff --git a/modules/ticket/front/basic-data/step-three/index.html b/modules/ticket/front/basic-data/step-three/index.html new file mode 100644 index 000000000..300b8f6d3 --- /dev/null +++ b/modules/ticket/front/basic-data/step-three/index.html @@ -0,0 +1,14 @@ +
    + + + + + + +
    diff --git a/modules/ticket/front/basic-data/step-three/index.js b/modules/ticket/front/basic-data/step-three/index.js new file mode 100644 index 000000000..1cd643dd2 --- /dev/null +++ b/modules/ticket/front/basic-data/step-three/index.js @@ -0,0 +1,73 @@ +import ngModule from '../../module'; + +class Controller { + constructor($http, $scope, $state, $translate, vnApp) { + this.$http = $http; + this.$scope = $scope; + this.$state = $state; + this.$translate = $translate; + this.vnApp = vnApp; + } + + $onInit() { + this.data.registerChild(this); + } + + get ticket() { + return this._ticket; + } + + set ticket(value) { + this._ticket = value; + + if (value) this.ticket.option = 1; + } + + onStepChange(state) { + return true; + } + + onSubmit() { + if (!this.ticket.option) { + return this.vnApp.showError( + this.$translate.instant('Choose an option') + ); + } + + let query = `tickets/${this.ticket.id}/componentUpdate`; + let params = { + clientId: this.ticket.clientFk, + agencyModeId: this.ticket.agencyModeFk, + addressId: this.ticket.addressFk, + zoneId: this.ticket.zoneFk, + warehouseId: this.ticket.warehouseFk, + companyId: this.ticket.companyFk, + shipped: this.ticket.shipped, + landed: this.ticket.landed, + isDeleted: this.ticket.isDeleted, + option: this.ticket.option + }; + + this.$http.post(query, params).then(res => { + this.vnApp.showMessage( + this.$translate.instant(`The ticket has been unrouted`) + ); + this.card.reload(); + this.$state.go('ticket.card.summary', {id: this.$state.params.id}); + }); + } +} + +Controller.$inject = ['$http', '$scope', '$state', '$translate', 'vnApp']; + +ngModule.component('vnTicketBasicDataStepThree', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<' + }, + require: { + card: '^vnTicketCard', + data: '^vnTicketBasicData' + } +}); diff --git a/modules/ticket/front/basic-data/step-three/index.spec.js b/modules/ticket/front/basic-data/step-three/index.spec.js new file mode 100644 index 000000000..6843caec1 --- /dev/null +++ b/modules/ticket/front/basic-data/step-three/index.spec.js @@ -0,0 +1,67 @@ +import './index.js'; + +describe('ticket', () => { + describe('Component vnTicketBasicDataStepThree', () => { + let now = Date.now(); + let $state; + let controller; + let $httpBackend; + let vnApp; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_, _vnApp_) => { + $state = _$state_; + spyOn($state, 'go'); + vnApp = _vnApp_; + spyOn(vnApp, 'showError'); + $httpBackend = _$httpBackend_; + controller = $componentController('vnTicketBasicDataStepThree', {$state}); + })); + + describe('onSubmit()', () => { + it(`should return an error if the item doesn't have option property in the controller`, () => { + controller._ticket = {id: 1}; + controller.onSubmit(); + + expect(vnApp.showError).toHaveBeenCalledWith('Choose an option'); + }); + + it('should perform a post query correctly then call two functions()', () => { + spyOn(controller.vnApp, 'showMessage'); + controller.card = {reload: () => {}}; + spyOn(controller.card, 'reload'); + + controller.ticket = { + id: 1, + agencyModeFk: 1, + addressFk: 121, + zoneFk: 3, + warehouseFk: 1, + shipped: now, + landed: now, + option: 1 + }; + + let data = { + agencyModeId: 1, + addressId: 121, + zoneId: 3, + warehouseId: 1, + shipped: now, + landed: now, + option: 1 + }; + + $httpBackend.whenPOST(`tickets/1/componentUpdate`, data).respond('ok'); + $httpBackend.expectPOST(`tickets/1/componentUpdate`, data); + controller.onSubmit(); + $httpBackend.flush(); + + expect(controller.vnApp.showMessage).toHaveBeenCalledWith('The ticket has been unrouted'); + expect(controller.card.reload).toHaveBeenCalledWith(); + expect(controller.$state.go).toHaveBeenCalledWith('ticket.card.summary', jasmine.any(Object)); + }); + }); + }); +}); diff --git a/modules/ticket/front/basic-data/step-three/locale/es.yml b/modules/ticket/front/basic-data/step-three/locale/es.yml new file mode 100644 index 000000000..185534c34 --- /dev/null +++ b/modules/ticket/front/basic-data/step-three/locale/es.yml @@ -0,0 +1,4 @@ +Charge: Cargo +Choose an option: Selecciona una opción +Charge difference to: Diferencia a cargo de +The ticket has been unrouted: El ticket ha sido desenrutado \ No newline at end of file diff --git a/modules/ticket/front/basic-data/step-two/index.html b/modules/ticket/front/basic-data/step-two/index.html new file mode 100644 index 000000000..04cb7f212 --- /dev/null +++ b/modules/ticket/front/basic-data/step-two/index.html @@ -0,0 +1,40 @@ + + + + + Item + Description + Quantity + Price (PPU) + New price (PPU) + Price difference + + + + + {{("000000"+sale.itemFk).slice(-6)}} + + + + + {{::sale.quantity}} + {{::sale.price | currency: 'EUR': 2}} + {{::sale.component.newPrice | currency: 'EUR': 2}} + {{::sale.component.difference | currency: 'EUR': 2}} + + + + + + + + {{$ctrl.totalPrice | currency: 'EUR': 2}} + {{$ctrl.totalNewPrice | currency: 'EUR': 2}} + {{$ctrl.totalPriceDifference | currency: 'EUR': 2}} + + + + diff --git a/modules/ticket/front/basic-data/step-two/index.js b/modules/ticket/front/basic-data/step-two/index.js new file mode 100644 index 000000000..a481afefc --- /dev/null +++ b/modules/ticket/front/basic-data/step-two/index.js @@ -0,0 +1,69 @@ +import ngModule from '../../module'; + +class Controller { + constructor($http) { + this.$http = $http; + } + + $onInit() { + this.data.registerChild(this); + } + + get ticket() { + return this._ticket; + } + + set ticket(value) { + this._ticket = value; + + if (!value) return; + + this.getTotalPrice(); + this.getTotalNewPrice(); + this.getTotalDifferenceOfPrice(); + } + + onStepChange(state) { + return true; + } + + getTotalPrice() { + let totalPrice = 0; + this.ticket.sale.items.forEach(item => { + let itemTotalPrice = item.quantity * item.price; + totalPrice += itemTotalPrice; + }); + this.totalPrice = totalPrice; + } + + getTotalNewPrice() { + let totalNewPrice = 0; + this.ticket.sale.items.forEach(item => { + if (item.component) + totalNewPrice += item.quantity * item.component.newPrice; + }); + this.totalNewPrice = totalNewPrice; + } + + getTotalDifferenceOfPrice() { + let totalPriceDifference = 0; + this.ticket.sale.items.forEach(item => { + if (item.component) + totalPriceDifference += item.component.difference; + }); + this.totalPriceDifference = totalPriceDifference; + } +} + +Controller.$inject = ['$http']; + +ngModule.component('vnTicketBasicDataStepTwo', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<' + }, + require: { + data: '^vnTicketBasicData' + } +}); diff --git a/modules/ticket/front/basic-data/step-two/index.spec.js b/modules/ticket/front/basic-data/step-two/index.spec.js new file mode 100644 index 000000000..1ca89fd90 --- /dev/null +++ b/modules/ticket/front/basic-data/step-two/index.spec.js @@ -0,0 +1,67 @@ +import './index.js'; + +describe('Ticket', () => { + describe('Component vnTicketBasicDataStepTwo', () => { + let controller; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject($componentController => { + controller = $componentController('vnTicketBasicDataStepTwo'); + })); + + describe('getTotalPrice()', () => { + it('should calculate the total price of the sale based on the data received', () => { + controller.ticket = { + sale: { + items: [{ + quantity: 10, + price: 0.1, + component: {newPrice: 0.2, difference: 0.3} + }] + } + }; + + controller.getTotalPrice(); + + expect(controller.totalPrice).toEqual(1); + }); + }); + + describe('getTotalNewPrice()', () => { + it('should calculate the total new price of the sale based on the data received', () => { + controller.ticket = { + sale: { + items: [{ + quantity: 10, + price: 0.1, + component: {newPrice: 0.2, difference: 0.3} + }] + } + }; + + controller.getTotalNewPrice(); + + expect(controller.totalNewPrice).toEqual(2); + }); + }); + + describe('getTotalDifferenceOfPrice()', () => { + it('should calculate the total price difference of the sale based on the data received', () => { + controller.ticket = { + sale: { + items: [{ + quantity: 10, + price: 0.1, + component: {newPrice: 0.2, difference: 0.3} + }] + } + }; + + controller.getTotalDifferenceOfPrice(); + + expect(controller.totalPriceDifference).toEqual(0.3); + }); + }); + }); +}); diff --git a/modules/ticket/front/basic-data/step-two/locale/es.yml b/modules/ticket/front/basic-data/step-two/locale/es.yml new file mode 100644 index 000000000..2cb66b38b --- /dev/null +++ b/modules/ticket/front/basic-data/step-two/locale/es.yml @@ -0,0 +1,3 @@ +Price (PPU): Precio (Ud.) +New price (PPU): Nuevo precio (Ud.) +Price difference: Diferencia de precio \ No newline at end of file diff --git a/modules/ticket/front/card/index.html b/modules/ticket/front/card/index.html new file mode 100644 index 000000000..a7c70c484 --- /dev/null +++ b/modules/ticket/front/card/index.html @@ -0,0 +1,5 @@ + + + + + diff --git a/modules/ticket/front/card/index.js b/modules/ticket/front/card/index.js new file mode 100644 index 000000000..131968d65 --- /dev/null +++ b/modules/ticket/front/card/index.js @@ -0,0 +1,72 @@ +import ngModule from '../module'; +import ModuleCard from 'salix/components/module-card'; + +class Controller extends ModuleCard { + reload() { + let filter = { + include: [ + {relation: 'address'}, + {relation: 'ship'}, + {relation: 'stowaway'}, + { + relation: 'warehouse', + scope: {fields: ['name']} + }, { + relation: 'invoiceOut', + scope: {fields: ['id']} + }, { + relation: 'agencyMode', + scope: {fields: ['name']} + }, { + relation: 'client', + scope: { + fields: [ + 'salesPersonFk', + 'name', + 'isActive', + 'isFreezed', + 'isTaxDataChecked', + 'credit', + 'email' + ], + include: { + relation: 'salesPerson', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + }, + }, + }, { + relation: 'state', + scope: { + fields: ['stateFk'], + include: { + relation: 'state', + fields: ['id', 'name'], + } + }, + }, + ], + }; + + this.$http.get(`Tickets/${this.$params.id}`, {filter}) + .then(res => this.onData(res.data)); + } + + onData(data) { + this.ticket = data; + this.$http.get(`Clients/${data.client.id}/getDebt`) + .then(res => this.ticket.client.debt = res.data.debt); + } +} + +ngModule.component('vnTicketCard', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/ticket/front/card/index.spec.js b/modules/ticket/front/card/index.spec.js new file mode 100644 index 000000000..33757860c --- /dev/null +++ b/modules/ticket/front/card/index.spec.js @@ -0,0 +1,33 @@ +import './index'; + +describe('Ticket', () => { + describe('Component vnTicketCard', () => { + let controller; + let $httpBackend; + let data = { + id: 1, + client: {name: 'fooName'} + }; + let client = {debt: 10.5}; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_, $stateParams) => { + $httpBackend = _$httpBackend_; + + let $element = angular.element('
    '); + controller = $componentController('vnTicketCard', {$element}); + + $stateParams.id = data.id; + $httpBackend.whenRoute('GET', 'Tickets/:id').respond(data); + $httpBackend.whenRoute('GET', 'Clients/:id/getDebt').respond(client); + })); + + it('should request data and set it on the controller', () => { + controller.reload(); + $httpBackend.flush(); + + expect(controller.ticket).toMatchObject(data); + }); + }); +}); diff --git a/modules/ticket/front/component/index.html b/modules/ticket/front/component/index.html new file mode 100644 index 000000000..2a70baa9d --- /dev/null +++ b/modules/ticket/front/component/index.html @@ -0,0 +1,70 @@ + + + + + Base to commission {{$ctrl.base() | currency: 'EUR':3}} + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ItemDescriptionQuantitySerieComponentsImportTotal
    + + {{sale.itemFk | zeroFill:6}} + + + + + + {{::sale.quantity}} +
    + {{::component.componentRate.componentType.type}} + + {{::component.componentRate.name}} + + {{::component.value | currency: 'EUR':3}} + + {{::sale.quantity * component.value | currency: 'EUR':3}} +
    +
    +
    + + \ No newline at end of file diff --git a/modules/ticket/front/component/index.js b/modules/ticket/front/component/index.js new file mode 100644 index 000000000..9854305f6 --- /dev/null +++ b/modules/ticket/front/component/index.js @@ -0,0 +1,80 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $stateParams) { + this.$stateParams = $stateParams; + this.$scope = $scope; + this.filter = { + order: 'concept ASC', + include: [{ + relation: 'item', + }, + { + relation: 'components', + scope: { + fields: ['componentFk', 'value'], + include: { + relation: 'componentRate', + scope: { + fields: ['typeFk', 'name'], + include: { + relation: 'componentType', + scope: { + fields: ['type', 'isBase'] + } + } + } + } + } + }] + }; + } + + base() { + let sales = this.$scope.model.data; + let sum = 0; + + if (!sales) return; + + for (let sale of sales) { + for (let component of sale.components) { + if (component.componentRate.componentType.isBase) + sum += sale.quantity * component.value; + } + } + + return sum; + } + + showDescriptor(event, itemFk) { + this.quicklinks = { + btnThree: { + icon: 'icon-transaction', + state: `item.card.diary({ + id: ${itemFk}, + warehouseFk: ${this.ticket.warehouseFk}, + ticketFk: ${this.ticket.id} + })`, + tooltip: 'Item diary' + } + }; + this.$scope.descriptor.itemFk = itemFk; + this.$scope.descriptor.parent = event.target; + this.$scope.descriptor.show(); + } + + onDescriptorLoad() { + this.$scope.popover.relocate(); + } +} + +Controller.$inject = ['$scope', '$stateParams']; + +ngModule.component('vnTicketComponents', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<' + } +}); diff --git a/modules/ticket/front/component/index.spec.js b/modules/ticket/front/component/index.spec.js new file mode 100644 index 000000000..e75bf2bdb --- /dev/null +++ b/modules/ticket/front/component/index.spec.js @@ -0,0 +1,89 @@ +import './index.js'; +import crudModel from 'core/mocks/crud-model'; + +describe('ticket', () => { + describe('Component vnTicketComponents', () => { + let controller; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, $state) => { + $state.params.id = '1'; + let $scope = $rootScope.$new(); + $scope.model = crudModel; + $scope.model.data = [{ + components: [ + { + componentRate: { + name: 'valor de compra', + componentType: { + isBase: 1 + } + }, + value: 5 + }, + { + componentRate: { + name: 'reparto', + componentType: { + isBase: 0 + } + }, + value: 5 + }, + { + componentRate: { + name: 'recobro', + componentType: { + isBase: 0 + } + }, + value: 5 + } + ], + quantity: 1 + }, + { + components: [ + { + componentRate: { + name: 'valor de compra', + componentType: { + isBase: 1 + } + }, + value: 1 + }, + { + componentRate: { + name: 'reparto', + componentType: { + isBase: 0 + } + }, + value: 1 + }, + { + componentRate: { + name: 'recobro', + componentType: { + isBase: 0 + } + }, + value: 1 + }, + ], + quantity: 5 + }]; + controller = $componentController('vnTicketComponents', {$scope}); + })); + + describe('base()', () => { + it(`should return the sum from all componenets base in each sale`, () => { + let result = controller.base(); + + expect(result).toEqual(10); + }); + }); + }); +}); diff --git a/modules/ticket/front/component/style.scss b/modules/ticket/front/component/style.scss new file mode 100644 index 000000000..c20b8f720 --- /dev/null +++ b/modules/ticket/front/component/style.scss @@ -0,0 +1,27 @@ +@import "variables"; + +vn-ticket-components { + .vn-table > tbody { + &:not(:last-child) { + border-bottom: .1em solid $color-spacer-light; + } + & > tr { + border-bottom: none; + + &.components { + height: 1em; + + & > td { + padding-top: .1em; + padding-bottom: .1em; + } + &:nth-child(2) > td { + padding-top: 1em; + } + &:last-child > td { + padding-bottom: 1em; + } + } + } + } +} diff --git a/modules/ticket/front/create/card.html b/modules/ticket/front/create/card.html new file mode 100644 index 000000000..cd26f21e7 --- /dev/null +++ b/modules/ticket/front/create/card.html @@ -0,0 +1,42 @@ + + {{id}}: {{name}} + + + {{nickname}}: {{street}}, {{city}} + + + + + + + \ No newline at end of file diff --git a/modules/ticket/front/create/card.js b/modules/ticket/front/create/card.js new file mode 100644 index 000000000..629647416 --- /dev/null +++ b/modules/ticket/front/create/card.js @@ -0,0 +1,131 @@ +import ngModule from '../module'; + +class Controller { + constructor($http, vnApp, $translate, $state, $stateParams, vnConfig) { + this.$stateParams = $stateParams; + this.$http = $http; + this.translate = $translate; + this.vnApp = vnApp; + this.vnConfig = vnConfig; + this.ticket = {}; + this.$state = $state; + this.clientFk = $stateParams.clientFk; + } + + $onInit() { + if (this.$stateParams && this.$stateParams.clientFk) + this.clientFk = this.$stateParams.clientFk; + + this.warehouseFk = this.vnConfig.warehouseFk; + } + + set ticket(value) { + if (value) + this._ticket = value; + } + + get ticket() { + return this._ticket; + } + + set clientFk(value) { + this.ticket.clientFk = value; + + if (value) { + let filter = { + include: { + relation: 'defaultAddress', + scope: { + fields: 'id' + } + }, + where: {id: value} + }; + filter = encodeURIComponent(JSON.stringify(filter)); + let query = `Clients?filter=${filter}`; + this.$http.get(query).then(res => { + if (res.data) { + let client = res.data[0]; + let defaultAddress = client.defaultAddress; + this.addressFk = defaultAddress.id; + } + }); + } else + this.addressFk = null; + this.getAvailableAgencies(); + } + + get clientFk() { + return this.ticket.clientFk; + } + + set addressFk(value) { + this.ticket.addressFk = value; + this.getAvailableAgencies(); + } + + get addressFk() { + return this.ticket.addressFk; + } + + set landed(value) { + this.ticket.landed = value; + this.getAvailableAgencies(); + } + + get landed() { + return this.ticket.landed; + } + + set warehouseFk(value) { + this.ticket.warehouseFk = value; + this.getAvailableAgencies(); + } + get warehouseFk() { + return this.ticket.warehouseFk; + } + + getAvailableAgencies() { + let ticket = this.ticket; + let params = { + warehouseFk: ticket.warehouseFk, + addressFk: ticket.addressFk, + landed: ticket.landed + }; + + if (params.warehouseFk && params.addressFk && params.landed) { + ticket.agencyModeFk = null; + + this.$http.get(`Agencies/getAgenciesWithWarehouse`, {params}) + .then(res => this._availableAgencies = res.data); + } + } + + onSubmit() { + this.createTicket(); + } + + createTicket() { + let params = { + clientFk: this.ticket.clientFk, + landed: this.ticket.landed, + addressFk: this.ticket.addressFk, + agencyModeFk: this.ticket.agencyModeFk, + warehouseFk: this.ticket.warehouseFk, + }; + this.$http.post(`Tickets/new`, params).then(res => { + this.vnApp.showSuccess(this.translate.instant('Data saved!')); + this.$state.go('ticket.card.summary', {id: res.data.id}); + }); + } +} + +Controller.$inject = ['$http', 'vnApp', '$translate', '$state', '$stateParams', 'vnConfig']; + +ngModule.component('vnTicketCreateCard', { + template: require('./card.html'), + controller: Controller, + bindings: { + ticket: ' + + + + + + + +
    \ No newline at end of file diff --git a/modules/ticket/front/create/index.js b/modules/ticket/front/create/index.js new file mode 100644 index 000000000..bb9b4c76e --- /dev/null +++ b/modules/ticket/front/create/index.js @@ -0,0 +1,20 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $http, $state) { + this.$ = $scope; + this.$http = $http; + this.$state = $state; + } + + async onSubmit() { + let newTicketID = await this.$.card.createTicket(); + this.$state.go('ticket.card.summary', {id: newTicketID}); + } +} +Controller.$inject = ['$scope', '$http', '$state']; + +ngModule.component('vnTicketCreate', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/ticket/front/create/locale/es.yml b/modules/ticket/front/create/locale/es.yml new file mode 100644 index 000000000..19f3f4ddd --- /dev/null +++ b/modules/ticket/front/create/locale/es.yml @@ -0,0 +1 @@ +New ticket: Nueva ticket \ No newline at end of file diff --git a/modules/ticket/front/descriptor-popover/index.html b/modules/ticket/front/descriptor-popover/index.html new file mode 100644 index 000000000..00d387f73 --- /dev/null +++ b/modules/ticket/front/descriptor-popover/index.html @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/modules/ticket/front/descriptor-popover/index.js b/modules/ticket/front/descriptor-popover/index.js new file mode 100644 index 000000000..5b94f3c14 --- /dev/null +++ b/modules/ticket/front/descriptor-popover/index.js @@ -0,0 +1,118 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + constructor($element, $scope, $http, $timeout, $q) { + super($element, $scope); + this.$timeout = $timeout; + this.$http = $http; + this.$q = $q; + this.ticket = null; + this._quicklinks = {}; + } + + set ticketFk(id) { + if (id == this._ticketFk) return; + + this._ticketFk = id; + this.ticket = null; + this.getCard(); + } + + set ticket(value) { + this._ticket = value; + this.$timeout(() => this.$.popover.relocate()); + } + + get ticket() { + return this._ticket; + } + + get quicklinks() { + return this._quicklinks; + } + + set quicklinks(value = {}) { + Object.keys(value).forEach(key => { + this._quicklinks[key] = value[key]; + }); + } + + show() { + this.$.popover.parent = this.parent; + this.$.popover.show(); + } + + getCard() { + if (this.canceler) + this.canceler.resolve(); + + this.canceler = this.$q.defer(); + + let options = {timeout: this.canceler.promise}; + + let filter = { + include: [ + { + relation: 'warehouse', + scope: { + fields: ['name'] + } + }, + { + relation: 'agencyMode', + scope: { + fields: ['name'] + } + }, + { + relation: 'client', + scope: { + fields: ['salesPersonFk', 'name', 'isActive', 'isFreezed', 'isTaxDataChecked'], + include: { + relation: 'salesPerson', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + } + } + }, + { + relation: 'state', + scope: { + fields: ['stateFk'], + include: { + relation: 'state', + fields: ['id', 'name'], + } + } + } + ] + }; + let json = encodeURIComponent(JSON.stringify(filter)); + let query = `Tickets/${this._ticketFk}?filter=${json}`; + this.$http.get(query, options).then( + response => { + this.ticket = response.data; + this.canceler = null; + } + ); + } +} +Controller.$inject = ['$element', '$scope', '$http', '$timeout', '$q']; + +ngModule.component('vnTicketDescriptorPopover', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticketFk: '<', + quicklinks: '<' + } +}); diff --git a/modules/ticket/front/descriptor-popover/index.spec.js b/modules/ticket/front/descriptor-popover/index.spec.js new file mode 100644 index 000000000..2fd94f668 --- /dev/null +++ b/modules/ticket/front/descriptor-popover/index.spec.js @@ -0,0 +1,125 @@ +import './index.js'; + +describe('ticket Component vnTicketDescriptorPopover', () => { + let $httpBackend; + let $scope; + let controller; + let $element; + let $timeout; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_, _$timeout_) => { + $httpBackend = _$httpBackend_; + $timeout = _$timeout_; + $element = angular.element(`
    `); + $scope = $rootScope.$new(); + $scope.popover = {relocate: () => {}, show: () => {}}; + controller = $componentController('vnTicketDescriptorPopover', {$scope, $element}); + })); + + describe('ticketFk()', () => { + it(`should not apply any changes if the received id is the same stored in _ticketFk`, () => { + controller.ticket = 'I exist!'; + controller._ticketFk = 1; + spyOn(controller, 'getCard'); + controller.ticketFk = 1; + + expect(controller.ticket).toEqual('I exist!'); + expect(controller._ticketFk).toEqual(1); + expect(controller.getCard).not.toHaveBeenCalled(); + }); + + it(`should set the received id into _ticketFk, set the ticket to null and then call getCard()`, () => { + controller.ticket = `Please don't`; + controller._ticketFk = 1; + spyOn(controller, 'getCard'); + controller.ticketFk = 999; + + expect(controller.ticket).toBeNull(); + expect(controller._ticketFk).toEqual(999); + expect(controller.getCard).toHaveBeenCalledWith(); + }); + }); + + describe('ticket()', () => { + it(`should save the ticket into _ticket and then call relocate()`, () => { + spyOn(controller.$.popover, 'relocate'); + controller.ticket = `i'm the ticket!`; + $timeout.flush(); + + expect(controller._ticket).toEqual(`i'm the ticket!`); + expect(controller.$.popover.relocate).toHaveBeenCalledWith(); + }); + }); + + describe('show()', () => { + it(`should call the show()`, () => { + spyOn(controller.$.popover, 'show'); + controller.show(); + + expect(controller.$.popover.show).toHaveBeenCalledWith(); + }); + }); + + describe('getCard()', () => { + it(`should perform a get query to store the ticket data into the controller`, () => { + controller.ticketFk = 1; + controller.canceler = null; + let response = {}; + + let filter = { + include: [ + { + relation: 'warehouse', + scope: { + fields: ['name'] + } + }, + { + relation: 'agencyMode', + scope: { + fields: ['name'] + } + }, + { + relation: 'client', + scope: { + fields: ['salesPersonFk', 'name', 'isActive', 'isFreezed', 'isTaxDataChecked'], + include: { + relation: 'salesPerson', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + } + } + }, + { + relation: 'state', + scope: { + fields: ['stateFk'], + include: { + relation: 'state', + fields: ['id', 'name'], + } + } + } + ] + }; + let json = encodeURIComponent(JSON.stringify(filter)); + $httpBackend.when('GET', `Tickets/${controller._ticketFk}?filter=${json}`).respond(response); + $httpBackend.expect('GET', `Tickets/${controller._ticketFk}?filter=${json}`); + controller.getCard(); + $httpBackend.flush(); + + expect(controller.ticket).toEqual(response); + }); + }); +}); + diff --git a/modules/ticket/front/descriptor-popover/style.scss b/modules/ticket/front/descriptor-popover/style.scss new file mode 100644 index 000000000..58e65d320 --- /dev/null +++ b/modules/ticket/front/descriptor-popover/style.scss @@ -0,0 +1,11 @@ +vn-ticket-descriptor-popover { + vn-ticket-descriptor { + display: block; + width: 16em; + max-height: 28em; + + & > vn-card { + margin: 0!important; + } + } +} \ No newline at end of file diff --git a/modules/ticket/front/descriptor/addStowaway.html b/modules/ticket/front/descriptor/addStowaway.html new file mode 100644 index 000000000..ec7005e79 --- /dev/null +++ b/modules/ticket/front/descriptor/addStowaway.html @@ -0,0 +1,38 @@ + + + + +
    +
    Stowaways to add
    +
    + + + + + + Ticket id + Shipped + Agency + Warehouse + State + + + + + {{ticket.id}} + {{ticket.landed | date: 'dd/MM/yyyy'}} + {{ticket.agencyMode.name}} + {{ticket.warehouse.name}} + {{ticket.state.state.name}} + + + + + +
    +
    \ No newline at end of file diff --git a/modules/ticket/front/descriptor/addStowaway.js b/modules/ticket/front/descriptor/addStowaway.js new file mode 100644 index 000000000..7a5670576 --- /dev/null +++ b/modules/ticket/front/descriptor/addStowaway.js @@ -0,0 +1,41 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($stateParams, $, $http, vnApp, $translate) { + this.vnApp = vnApp; + this.$translate = $translate; + this.$ = $; + this.$stateParams = $stateParams; + this.$http = $http; + } + + addStowaway(stowaway) { + let params = {id: stowaway.id, shipFk: this.ticket.id}; + this.$http.post(`Stowaways/`, params) + .then(() => { + this.cardReload(); + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$.dialog.hide(); + }); + } + + show() { + this.$.dialog.show(); + } + + hide() { + this.$.dialog.hide(); + } +} + +Controller.$inject = ['$stateParams', '$scope', '$http', 'vnApp', '$translate']; + +ngModule.component('vnAddStowaway', { + template: require('./addStowaway.html'), + controller: Controller, + bindings: { + ticket: '<', + cardReload: '&?' + } +}); diff --git a/modules/ticket/front/descriptor/index.html b/modules/ticket/front/descriptor/index.html new file mode 100644 index 000000000..3632d37f1 --- /dev/null +++ b/modules/ticket/front/descriptor/index.html @@ -0,0 +1,211 @@ +
    +
    + + + + + + + + +
    +
    +
    +
    {{::$ctrl.client.name}}
    + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + +
    + + +
    + + +
    +
    +
    + +
    +
    + In which day you want to add the ticket? +
    + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + +
    +
    + Change shipped hour +
    + + +
    +
    + + + + +
    + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/ticket/front/descriptor/index.js b/modules/ticket/front/descriptor/index.js new file mode 100644 index 000000000..ef64bf84e --- /dev/null +++ b/modules/ticket/front/descriptor/index.js @@ -0,0 +1,338 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; + +class Controller extends Component { + constructor($element, $, aclService, $httpParamSerializer) { + super($element, $); + this.aclService = aclService; + this.$httpParamSerializer = $httpParamSerializer; + this.moreOptions = [ + {name: 'Add turn', callback: this.showAddTurnDialog}, + {name: 'Show Delivery Note', callback: this.showDeliveryNote}, + {name: 'Send Delivery Note', callback: this.confirmDeliveryNote}, + {name: 'Delete ticket', callback: this.showDeleteTicketDialog}, + {name: 'Change shipped hour', callback: this.showChangeShipped}, + {name: 'Send SMS', callback: this.showSMSDialog}, + { + name: 'Add stowaway', + callback: this.showAddStowaway, + show: () => this.canShowStowaway + }, + { + name: 'Delete stowaway', + callback: this.showDeleteStowaway, + show: () => this.shouldShowDeleteStowaway() + }, + { + name: 'Make invoice', + acl: 'invoicing', + callback: this.showMakeInvoiceDialog, + show: () => !this.hasInvoice() + }, + { + name: 'Regenerate invoice', + acl: 'invoicing', + callback: this.showRegenerateInvoiceDialog, + show: () => this.hasInvoice() + }, + { + name: 'Recalculate components', + callback: this.comfirmRecalculateComponents, + show: () => this.isEditable + }, + ]; + } + + get ticket() { + return this._ticket; + } + + set ticket(value) { + this._ticket = value; + + if (!value) return; + + if (this.$params.sendSMS) + this.showSMSDialog(); + + this.canStowaway(); + + let links = { + btnOne: { + icon: 'person', + state: `client.card.summary({id: ${value.clientFk}})`, + tooltip: 'Client card' + }}; + + if (value.stowaway) { + links.btnTwo = { + icon: 'icon-stowaway', + state: `ticket.card.summary({id: ${value.stowaway.shipFk}})`, + tooltip: 'Ship stowaways' + }; + } + + if (value.ship) { + links.btnThree = { + icon: 'icon-stowaway', + state: `ticket.card.summary({id: ${value.ship.id}})`, + tooltip: 'Stowaway' + }; + } + + this._quicklinks = links; + } + + get quicklinks() { + return this._quicklinks; + } + + set quicklinks(value = {}) { + this._quicklinks = Object.assign(value, this._quicklinks); + } + + showChangeShipped() { + if (!this.isEditable) { + this.vnApp.showError(this.$translate.instant(`This ticket can't be modified`)); + return; + } + this.newShipped = this.ticket.shipped; + this.$.changeShippedDialog.show(); + } + + changeShipped(response) { + if (response === 'accept') { + let data = {shipped: this.newShipped}; + let query = `Tickets/${this.ticket.id}/updateEditableTicket`; + this.$http.post(query, data).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Shipped hour updated')); + this.cardReload(); + }); + } + } + + isTicketModule() { + let path = this.$state.getCurrentPath(); + const isTicket = path[1].state.name === 'ticket'; + if (isTicket) + return true; + + return false; + } + + onMoreChange(callback) { + callback.call(this); + } + + goToTicket(ticketID) { + this.$state.go('ticket.card.sale', {id: ticketID}, {absolute: true}); + } + + onMoreOpen() { + let options = this.moreOptions.filter(option => { + const hasShowProperty = Object.hasOwnProperty.call(option, 'show'); + const hasAclProperty = Object.hasOwnProperty.call(option, 'acl'); + const hasAcl = !hasAclProperty || (hasAclProperty && this.aclService.hasAny([option.acl])); + + return (!hasShowProperty || option.show === true || + typeof option.show === 'function' && option.show()) && hasAcl; + }); + this.$.moreButton.data = options; + } + + get isEditable() { + try { + return !this.ticket.tracking.state.alertLevel; + } catch (e) {} + + return true; + } + + showAddTurnDialog() { + this.$.addTurn.show(); + } + + addTurn(day) { + let params = {ticketFk: this.ticket.id, weekDay: day}; + this.$http.patch(`TicketWeeklies`, params).then(() => { + this.$.addTurn.hide(); + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }); + } + + showDeleteTicketDialog() { + if (!this.isEditable) { + this.vnApp.showError(this.$translate.instant('This ticket cant be deleted')); + return; + } + + this.$.deleteConfirmation.show(); + } + + deleteTicket(response) { + if (response === 'accept') { + const query = `Tickets/${this.ticket.id}/setDeleted`; + this.$http.post(query).then(() => { + this.$state.go('ticket.index'); + this.vnApp.showSuccess(this.$translate.instant('Ticket deleted')); + }); + } + } + + canStowaway() { + if (!this.isTicketModule()) return; + + this.$http.get(`Tickets/${this.ticket.id}/canHaveStowaway`).then(response => { + if (response.data === true) + return this.canShowStowaway = true; + + return this.canShowStowaway = false; + }); + } + + shouldShowDeleteStowaway() { + if (!this._ticket || !this.isTicketModule()) + return false; + + return this._ticket.stowaway || this._ticket.ship; + } + + showAddStowaway() { + this.$.addStowaway.show(); + } + + showDeleteStowaway() { + this.$.deleteStowaway.show(); + } + + deleteStowaway() { + const query = `Tickets/${this.ticket.id}/deleteStowaway`; + this.$http.post(query).then(res => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.cardReload(); + }); + } + + showDeliveryNote() { + const params = { + clientId: this.ticket.client.id, + ticketId: this.ticket.id + }; + const serializedParams = this.$httpParamSerializer(params); + let url = `api/report/delivery-note?${serializedParams}`; + window.open(url); + } + + sendDeliveryNote() { + const params = { + recipient: this.ticket.client.email, + clientId: this.ticket.client.id, + ticketId: this.ticket.id + }; + const serializedParams = this.$httpParamSerializer(params); + this.$http.get(`email/delivery-note?${serializedParams}`).then( + () => this.vnApp.showMessage(this.$translate.instant('Notification sent!')) + ); + } + + showSMSDialog() { + const address = this.ticket.address; + const phone = this.$params.phone || address.mobile; + const message = this.$params.message || this.$translate.instant('SMSPayment'); + this.newSMS = { + destinationFk: this.ticket.clientFk, + destination: phone, + message: message + }; + this.$.sms.open(); + } + + /** + * Shows an invoice confirmation + */ + showMakeInvoiceDialog() { + this.$.makeInvoiceConfirmation.show(); + } + + /** + * Makes an invoice + * from current ticket + * + * @param {String} response - Response result + */ + makeInvoice(response) { + if (response === 'accept') { + const query = `Tickets/${this.ticket.id}/makeInvoice`; + this.$http.post(query).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Ticket invoiced')); + this.$state.reload(); + }); + } + } + + /** + * Shows an invoice confirmation + */ + showRegenerateInvoiceDialog() { + this.$.regenerateInvoiceConfirmation.show(); + } + + /** + * Sends an invoice to a regeneration queue + * for the current ticket + * + * @param {String} response - Response result + */ + regenerateInvoice(response) { + if (response === 'accept') { + const invoiceId = this.ticket.invoiceOut.id; + const query = `InvoiceOuts/${invoiceId}/regenerate`; + this.$http.post(query).then(() => { + const snackbarMessage = this.$translate.instant( + `Invoice sent for a regeneration, will be available in a few minutes`); + this.vnApp.showSuccess(snackbarMessage); + }); + } + } + + /** + * Returns if the current ticket + * is already invoiced + * @return {Boolean} - True if invoiced + */ + hasInvoice() { + return this.ticket.refFk !== null; + } + + /** + * Shows a delivery-note send confirmation + */ + confirmDeliveryNote() { + this.$.confirmDeliveryNote.show(); + } + + /** + * Shows an invoice confirmation + */ + comfirmRecalculateComponents() { + this.$.recalculateComponentsConfirmation.show(); + } + + recalculateComponents() { + const query = `Tickets/${this.ticket.id}/recalculateComponents`; + this.$http.post(query).then(res => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }); + } +} + +Controller.$inject = ['$element', '$scope', 'aclService', '$httpParamSerializer']; + +ngModule.component('vnTicketDescriptor', { + template: require('./index.html'), + bindings: { + ticket: '<', + cardReload: '&' + }, + controller: Controller +}); diff --git a/modules/ticket/front/descriptor/index.spec.js b/modules/ticket/front/descriptor/index.spec.js new file mode 100644 index 000000000..eb554218e --- /dev/null +++ b/modules/ticket/front/descriptor/index.spec.js @@ -0,0 +1,226 @@ +import './index.js'; + +describe('Ticket Component vnTicketDescriptor', () => { + let $httpParamSerializer; + let $httpBackend; + let controller; + let $state; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_, $rootScope, $compile, _$state_, _$httpParamSerializer_) => { + let $element = $compile(``)($rootScope); + $state = _$state_; + $state.getCurrentPath = () => { + return [ + {state: {}}, + {state: {name: 'ticket'}} + ]; + }; + $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; + controller = $componentController('vnTicketDescriptor', {$element}); + controller._ticket = {id: 2, invoiceOut: {id: 1}, client: {id: 101, email: 'client@email'}}; + controller.cardReload = ()=> { + return true; + }; + })); + + describe('showAddTurnDialog()', () => { + it('should call controller.$.addTurn.show()', () => { + controller.$.addTurn = {show: () => {}}; + spyOn(controller.$.addTurn, 'show'); + controller.showAddTurnDialog(); + + expect(controller.$.addTurn.show).toHaveBeenCalledWith(); + }); + }); + + describe('addTurn()', () => { + it('should make a query and call $.addTurn.hide() and vnApp.showSuccess()', () => { + controller.$.addTurn = {hide: () => {}}; + spyOn(controller.$.addTurn, 'hide'); + + $httpBackend.expectPATCH(`TicketWeeklies`).respond(); + controller.addTurn(1); + $httpBackend.flush(); + + expect(controller.$.addTurn.hide).toHaveBeenCalledWith(); + }); + }); + + describe('showDeleteTicketDialog()', () => { + it('should call vnApp.showError() if the ticket isnt editable', () => { + controller.ticket.tracking = {state: {alertLevel: 3}}; + spyOn(controller.vnApp, 'showError'); + controller.showDeleteTicketDialog(); + + expect(controller.vnApp.showError).toHaveBeenCalledWith('This ticket cant be deleted'); + }); + + it('should call deleteConfirmation.show() if the ticket is editable', () => { + controller.ticket.tracking = {state: {alertLevel: 0}}; + controller.$.deleteConfirmation = {show: () => {}}; + spyOn(controller.$.deleteConfirmation, 'show'); + controller.showDeleteTicketDialog(); + + expect(controller.$.deleteConfirmation.show).toHaveBeenCalledWith(); + }); + }); + + describe('deleteTicket()', () => { + it('should make a query and call vnApp.showSuccess() if the response is accept', () => { + spyOn(controller.$state, 'go'); + spyOn(controller.vnApp, 'showSuccess'); + + $httpBackend.expectPOST(`Tickets/2/setDeleted`).respond(); + controller.deleteTicket('accept'); + $httpBackend.flush(); + + expect(controller.$state.go).toHaveBeenCalledWith('ticket.index'); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Ticket deleted'); + }); + }); + + describe('showDeliveryNote()', () => { + it('should open a new window showing a delivery note PDF document', () => { + const params = { + clientId: controller.ticket.client.id, + ticketId: controller.ticket.id + }; + const serializedParams = $httpParamSerializer(params); + let expectedPath = `api/report/delivery-note?${serializedParams}`; + spyOn(window, 'open'); + controller.showDeliveryNote(); + + expect(window.open).toHaveBeenCalledWith(expectedPath); + }); + }); + + describe('sendDeliveryNote()', () => { + it('should make a query and call vnApp.showMessage()', () => { + spyOn(controller.vnApp, 'showMessage'); + + const params = { + recipient: 'client@email', + clientId: controller.ticket.client.id, + ticketId: controller.ticket.id + }; + const serializedParams = $httpParamSerializer(params); + + $httpBackend.when('GET', `email/delivery-note?${serializedParams}`).respond(); + $httpBackend.expect('GET', `email/delivery-note?${serializedParams}`).respond(); + controller.sendDeliveryNote(); + $httpBackend.flush(); + + expect(controller.vnApp.showMessage).toHaveBeenCalledWith('Notification sent!'); + }); + }); + + describe('makeInvoice()', () => { + it('should make a query and call $state.reload() method if the response is accept', () => { + spyOn(controller.$state, 'reload'); + spyOn(controller.vnApp, 'showSuccess'); + + $httpBackend.when('POST', 'Tickets/2/makeInvoice').respond(); + $httpBackend.expect('POST', 'Tickets/2/makeInvoice').respond(); + controller.makeInvoice('accept'); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Ticket invoiced'); + expect(controller.$state.reload).toHaveBeenCalledWith(); + }); + }); + + describe('regenerateInvoice()', () => { + it('should make a query and show a success snackbar if the response is accept', () => { + spyOn(controller.vnApp, 'showSuccess'); + + $httpBackend.when('POST', 'InvoiceOuts/1/regenerate').respond(); + $httpBackend.expect('POST', 'InvoiceOuts/1/regenerate').respond(); + controller.regenerateInvoice('accept'); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Invoice sent for a regeneration, will be available in a few minutes'); + }); + }); + + describe('changeShipped()', () => { + it('should make a query and change the shipped hour if the response is accept', () => { + controller.ticket.id = 12; + spyOn(controller.vnApp, 'showSuccess'); + spyOn(controller, 'cardReload'); + + $httpBackend.when('POST', 'Tickets/12/updateEditableTicket').respond(); + $httpBackend.expect('POST', 'Tickets/12/updateEditableTicket').respond(); + controller.changeShipped('accept'); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Shipped hour updated'); + expect(controller.cardReload).toHaveBeenCalledWith(); + }); + }); + + + describe('showAddStowaway()', () => { + it('should show a dialog with a list of tickets available for an stowaway', () => { + controller.$.addStowaway = {}; + controller.$.addStowaway.show = jasmine.createSpy('show'); + controller.showAddStowaway(); + + expect(controller.$.addStowaway.show).toHaveBeenCalledWith(); + }); + }); + + describe('showRemoveStowaway()', () => { + it('should show a dialog for an stowaway removal', () => { + controller.$.deleteStowaway = {}; + controller.$.deleteStowaway.show = jasmine.createSpy('show'); + controller.showDeleteStowaway(); + + expect(controller.$.deleteStowaway.show).toHaveBeenCalledWith(); + }); + }); + + describe('canStowaway()', () => { + it('should make a query and return if the ticket can be stowawayed', () => { + controller.ticket.id = 16; + spyOn(controller, 'isTicketModule').and.callThrough(); + $httpBackend.when('GET', 'Tickets/16/canHaveStowaway').respond(true); + $httpBackend.expect('GET', 'Tickets/16/canHaveStowaway').respond(true); + controller.canStowaway(); + $httpBackend.flush(); + + expect(controller.canShowStowaway).toBeTruthy(); + expect(controller.isTicketModule).toHaveBeenCalledWith(); + }); + + it('should not make a query if is not on the ticket module', () => { + controller.ticket.id = 16; + $state.getCurrentPath = () => { + return [ + {state: {}}, + {state: {name: 'client'}} + ]; + }; + spyOn(controller, 'isTicketModule').and.callThrough(); + controller.canStowaway(); + + expect(controller.canShowStowaway).toBeUndefined(); + expect(controller.isTicketModule).toHaveBeenCalledWith(); + }); + }); + + describe('recalculateComponents()', () => { + it('should make a query and show a success snackbar', () => { + spyOn(controller.vnApp, 'showSuccess'); + + $httpBackend.when('POST', 'Tickets/2/recalculateComponents').respond(); + $httpBackend.expect('POST', 'Tickets/2/recalculateComponents').respond(); + controller.recalculateComponents(); + $httpBackend.flush(); + + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + }); + }); +}); diff --git a/modules/ticket/front/descriptor/locale/en.yml b/modules/ticket/front/descriptor/locale/en.yml new file mode 100644 index 000000000..4dca75a51 --- /dev/null +++ b/modules/ticket/front/descriptor/locale/en.yml @@ -0,0 +1,3 @@ +SMSPayment: >- + Verdnatura communicates: Your order is pending of payment. + Please, enter the web page and make the payment with card. Thank you. \ No newline at end of file diff --git a/modules/ticket/front/descriptor/locale/es.yml b/modules/ticket/front/descriptor/locale/es.yml new file mode 100644 index 000000000..947377e19 --- /dev/null +++ b/modules/ticket/front/descriptor/locale/es.yml @@ -0,0 +1,30 @@ +Ship: Barco +Stowaway: Polizón +Cliente: Client +Ship stowaways: Polizones del barco +Stowaways to add: Polizones a añadir +Stowaways of the ticket: Polizones del ticket +Add stowaway: Añadir polizón +Delete stowaway: Eliminar polizón +Are you sure you want to delete this stowaway?: ¿Seguro que quieres eliminar este polizón? +Are you sure you want to send it?: ¿Seguro que quieres enviarlo? +Show Delivery Note: Ver albarán +Send Delivery Note: Enviar albarán +Show pallet report: Ver hoja de pallet +Change shipped hour: Cambiar hora de envío +Shipped hour: Hora de envío +SMSPayment: >- + Verdnatura le comunica: Su pedido está pendiente de pago. + Por favor, entre en la página web y efectue el pago con tarjeta. Muchas gracias. +Ticket invoiced: Ticket facturado +Make invoice: Crear factura +Regenerate invoice: Regenerar factura +You are going to invoice this ticket: Vas a facturar este ticket +Are you sure you want to invoice this ticket?: ¿Seguro que quieres facturar este ticket? +You are going to regenerate the invoice: Vas a regenerar la factura +Are you sure you want to regenerate the invoice?: ¿Seguro que quieres regenerar la factura? +Invoice sent for a regeneration, will be available in a few minutes: La factura ha sido enviada para ser regenerada, estará disponible en unos minutos +Shipped hour updated: Hora de envio modificada +Deleted ticket: Ticket eliminado +Recalculate components: Recalcular componentes +Are you sure you want to recalculate the components?: ¿Seguro que quieres recalcular los componentes? \ No newline at end of file diff --git a/modules/ticket/front/descriptor/style.scss b/modules/ticket/front/descriptor/style.scss new file mode 100644 index 000000000..4becf9789 --- /dev/null +++ b/modules/ticket/front/descriptor/style.scss @@ -0,0 +1,38 @@ +@import "variables"; + +.add-stowaway { + vn-data-viewer { + width: 40em + } +} + +vn-dialog.modal-form { + section.header { + background-color: $color-main; + color: $color-font-dark; + text-align: center; + + h5 { + color: inherit; + margin: 0 auto; + } + } + & > div { + padding: 0 !important; + } + .vn-textfield { + width: 100%; + } + .buttons { + margin-top: 0 !important; + } + p { + display: none; + } + button.close > vn-icon { + color: white !important; + } + vn-ticket-sale-edit-discount > div { + padding-bottom: 0 !important; + } +} \ No newline at end of file diff --git a/modules/ticket/front/dms/create/index.html b/modules/ticket/front/dms/create/index.html new file mode 100644 index 000000000..8e6af2b87 --- /dev/null +++ b/modules/ticket/front/dms/create/index.html @@ -0,0 +1,81 @@ + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    diff --git a/modules/ticket/front/dms/create/index.js b/modules/ticket/front/dms/create/index.js new file mode 100644 index 000000000..cb39be7dc --- /dev/null +++ b/modules/ticket/front/dms/create/index.js @@ -0,0 +1,115 @@ +import ngModule from '../../module'; + +class Controller { + constructor($scope, $http, $state, $translate, vnApp, vnConfig) { + this.$ = $scope; + this.$http = $http; + this.$state = $state; + this.$translate = $translate; + this.vnApp = vnApp; + this.vnConfig = vnConfig; + this.dms = { + files: [], + hasFile: false, + hasFileAttached: false + }; + } + + get ticket() { + return this._ticket; + } + + set ticket(value) { + this._ticket = value; + + if (value) { + this.setDefaultParams(); + this.getAllowedContentTypes(); + } + } + + getAllowedContentTypes() { + this.$http.get('ticketDms/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + + get contentTypesInfo() { + return this.$translate.instant('ContentTypesInfo', { + allowedContentTypes: this.allowedContentTypes + }); + } + + setDefaultParams() { + const params = {filter: { + where: {code: 'ticket'} + }}; + this.$http.get('DmsTypes/findOne', {params}).then(res => { + const dmsTypeId = res.data && res.data.id; + const companyId = this.vnConfig.companyFk; + const warehouseId = this.vnConfig.warehouseFk; + const defaultParams = { + reference: this.ticket.id, + warehouseId: warehouseId, + companyId: companyId, + dmsTypeId: dmsTypeId, + description: this.$translate.instant('FileDescription', { + ticketId: this.ticket.id, + clientId: this.ticket.client.id, + clientName: this.ticket.client.name + }).toUpperCase() + }; + + this.dms = Object.assign(this.dms, defaultParams); + }); + } + + onSubmit() { + const query = `tickets/${this.ticket.id}/uploadFile`; + const options = { + method: 'POST', + url: query, + params: this.dms, + headers: { + 'Content-Type': undefined + }, + transformRequest: files => { + const formData = new FormData(); + + for (let i = 0; i < files.length; i++) + formData.append(files[i].name, files[i]); + + return formData; + }, + data: this.dms.files + }; + this.$http(options).then(res => { + if (res) { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$.watcher.updateOriginalData(); + this.$state.go('ticket.card.dms.index'); + } + }); + } + + onFileChange(files) { + let hasFileAttached = false; + if (files.length > 0) + hasFileAttached = true; + + this.$.$applyAsync(() => { + this.dms.hasFileAttached = hasFileAttached; + }); + } +} + +Controller.$inject = ['$scope', '$http', '$state', '$translate', 'vnApp', 'vnConfig']; + +ngModule.component('vnTicketDmsCreate', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<' + } +}); diff --git a/modules/ticket/front/dms/create/index.spec.js b/modules/ticket/front/dms/create/index.spec.js new file mode 100644 index 000000000..c8b63358f --- /dev/null +++ b/modules/ticket/front/dms/create/index.spec.js @@ -0,0 +1,80 @@ +import './index'; + +describe('Ticket', () => { + describe('Component vnTicketDmsCreate', () => { + let controller; + let $scope; + let $httpBackend; + let $httpParamSerializer; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_) => { + $scope = $rootScope.$new(); + $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; + controller = $componentController('vnTicketDmsCreate', {$scope}); + controller._ticket = { + id: 15, + client: {id: 101, name: 'Bruce wayne'}, + warehouseFk: 1, + companyFk: 1 + }; + })); + + describe('client() setter', () => { + it('should set the ticket data and then call setDefaultParams() and getAllowedContentTypes()', () => { + spyOn(controller, 'setDefaultParams'); + spyOn(controller, 'getAllowedContentTypes'); + controller.ticket = { + id: 15, + name: 'Bruce wayne' + }; + + expect(controller.ticket).toBeDefined(); + expect(controller.setDefaultParams).toHaveBeenCalledWith(); + expect(controller.getAllowedContentTypes).toHaveBeenCalledWith(); + }); + }); + + describe('setDefaultParams()', () => { + it('should perform a GET query and define the dms property on controller', () => { + const params = {filter: { + where: {code: 'ticket'} + }}; + let serializedParams = $httpParamSerializer(params); + $httpBackend.when('GET', `DmsTypes/findOne?${serializedParams}`).respond({id: 14, code: 'ticket'}); + $httpBackend.expect('GET', `DmsTypes/findOne?${serializedParams}`); + controller.setDefaultParams(); + $httpBackend.flush(); + + expect(controller.dms).toBeDefined(); + expect(controller.dms.reference).toEqual(15); + expect(controller.dms.dmsTypeId).toEqual(14); + }); + }); + + describe('onFileChange()', () => { + it('should set dms hasFileAttached property to true if has any files', () => { + const files = [{id: 1, name: 'MyFile'}]; + controller.onFileChange(files); + $scope.$apply(); + + expect(controller.dms.hasFileAttached).toBeTruthy(); + }); + }); + + describe('getAllowedContentTypes()', () => { + it('should make an HTTP GET request to get the allowed content types', () => { + const expectedResponse = ['image/png', 'image/jpg']; + $httpBackend.when('GET', `ticketDms/allowedContentTypes`).respond(expectedResponse); + $httpBackend.expect('GET', `ticketDms/allowedContentTypes`); + controller.getAllowedContentTypes(); + $httpBackend.flush(); + + expect(controller.allowedContentTypes).toBeDefined(); + expect(controller.allowedContentTypes).toEqual('image/png, image/jpg'); + }); + }); + }); +}); diff --git a/modules/ticket/front/dms/edit/index.html b/modules/ticket/front/dms/edit/index.html new file mode 100644 index 000000000..cf9af46d0 --- /dev/null +++ b/modules/ticket/front/dms/edit/index.html @@ -0,0 +1,82 @@ + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    diff --git a/modules/ticket/front/dms/edit/index.js b/modules/ticket/front/dms/edit/index.js new file mode 100644 index 000000000..9ff967816 --- /dev/null +++ b/modules/ticket/front/dms/edit/index.js @@ -0,0 +1,103 @@ +import ngModule from '../../module'; + +class Controller { + constructor($scope, $http, $state, $translate, vnApp) { + this.$ = $scope; + this.$http = $http; + this.$state = $state; + this.$stateParams = $state.params; + this.$translate = $translate; + this.vnApp = vnApp; + } + + get ticket() { + return this._ticket; + } + + set ticket(value) { + this._ticket = value; + + if (value) { + this.setDefaultParams(); + this.getAllowedContentTypes(); + } + } + + getAllowedContentTypes() { + this.$http.get('ticketDms/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + + get contentTypesInfo() { + return this.$translate.instant('ContentTypesInfo', { + allowedContentTypes: this.allowedContentTypes + }); + } + + setDefaultParams() { + const path = `Dms/${this.$stateParams.dmsId}`; + this.$http.get(path).then(res => { + const dms = res.data && res.data; + this.dms = { + reference: dms.reference, + warehouseId: dms.warehouseFk, + companyId: dms.companyFk, + dmsTypeId: dms.dmsTypeFk, + description: dms.description, + hasFile: dms.hasFile, + hasFileAttached: false, + files: [] + }; + }); + } + + onSubmit() { + const query = `dms/${this.$stateParams.dmsId}/updateFile`; + const options = { + method: 'POST', + url: query, + params: this.dms, + headers: { + 'Content-Type': undefined + }, + transformRequest: files => { + const formData = new FormData(); + + for (let i = 0; i < files.length; i++) + formData.append(files[i].name, files[i]); + + return formData; + }, + data: this.dms.files + }; + this.$http(options).then(res => { + if (res) { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$.watcher.updateOriginalData(); + this.$state.go('ticket.card.dms.index'); + } + }); + } + + onFileChange(files) { + let hasFileAttached = false; + if (files.length > 0) + hasFileAttached = true; + + this.$.$applyAsync(() => { + this.dms.hasFileAttached = hasFileAttached; + }); + } +} + +Controller.$inject = ['$scope', '$http', '$state', '$translate', 'vnApp']; + +ngModule.component('vnTicketDmsEdit', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<' + } +}); diff --git a/modules/ticket/front/dms/edit/index.spec.js b/modules/ticket/front/dms/edit/index.spec.js new file mode 100644 index 000000000..493deae77 --- /dev/null +++ b/modules/ticket/front/dms/edit/index.spec.js @@ -0,0 +1,83 @@ +import './index'; + +describe('Ticket', () => { + describe('Component vnTicketDmsEdit', () => { + let controller; + let $scope; + let $httpBackend; + let $state; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_) => { + $scope = $rootScope.$new(); + $httpBackend = _$httpBackend_; + $state = {params: {dmsId: 1}}; + controller = $componentController('vnTicketDmsEdit', {$scope, $state}); + controller._ticket = {id: 1, ticketFk: 16}; + })); + + describe('ticket() setter', () => { + it('should set the ticket data and then call setDefaultParams() and getAllowedContentTypes()', () => { + spyOn(controller, 'setDefaultParams'); + spyOn(controller, 'getAllowedContentTypes'); + controller._ticket = undefined; + controller.ticket = { + id: 15 + }; + + expect(controller.setDefaultParams).toHaveBeenCalledWith(); + expect(controller.ticket).toBeDefined(); + expect(controller.getAllowedContentTypes).toHaveBeenCalledWith(); + }); + }); + + describe('setDefaultParams()', () => { + it('should perform a GET query and define the dms property on controller', () => { + const dmsId = 1; + const expectedResponse = { + reference: 101, + warehouseFk: 1, + companyFk: 442, + dmsTypeFk: 14, + description: 'Test', + hasFile: false, + hasFileAttached: false + }; + + $httpBackend.when('GET', `Dms/${dmsId}`).respond(expectedResponse); + $httpBackend.expect('GET', `Dms/${dmsId}`).respond(expectedResponse); + controller.setDefaultParams(); + $httpBackend.flush(); + + expect(controller.dms).toBeDefined(); + expect(controller.dms.reference).toEqual(101); + expect(controller.dms.dmsTypeId).toEqual(14); + }); + }); + + describe('onFileChange()', () => { + it('should set dms hasFileAttached property to true if has any files', () => { + const files = [{id: 1, name: 'MyFile'}]; + controller.dms = {hasFileAttached: false}; + controller.onFileChange(files); + $scope.$apply(); + + expect(controller.dms.hasFileAttached).toBeTruthy(); + }); + }); + + describe('getAllowedContentTypes()', () => { + it('should make an HTTP GET request to get the allowed content types', () => { + const expectedResponse = ['image/png', 'image/jpg']; + $httpBackend.when('GET', `ticketDms/allowedContentTypes`).respond(expectedResponse); + $httpBackend.expect('GET', `ticketDms/allowedContentTypes`); + controller.getAllowedContentTypes(); + $httpBackend.flush(); + + expect(controller.allowedContentTypes).toBeDefined(); + expect(controller.allowedContentTypes).toEqual('image/png, image/jpg'); + }); + }); + }); +}); diff --git a/modules/ticket/front/dms/index/index.html b/modules/ticket/front/dms/index/index.html new file mode 100644 index 000000000..ae2844c73 --- /dev/null +++ b/modules/ticket/front/dms/index/index.html @@ -0,0 +1,115 @@ + + + + + + + + Id + Type + Order + Reference + Description + Original + File + Employee + Created + + + + + + + + {{::document.dmsFk}} + + + {{::document.dms.dmsType.name}} + + + + + {{::document.dms.hardCopyNumber}} + + + + + {{::document.dms.reference}} + + + + + {{::document.dms.description}} + + + + + + + + + {{::document.dms.file}} + + + + + {{::document.dms.worker.user.nickname | dashIfEmpty}} + + + {{::document.dms.created | date:'dd/MM/yyyy HH:mm'}} + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/ticket/front/dms/index/index.js b/modules/ticket/front/dms/index/index.js new file mode 100644 index 000000000..c6ceb6b0d --- /dev/null +++ b/modules/ticket/front/dms/index/index.js @@ -0,0 +1,79 @@ +import ngModule from '../../module'; +import './style.scss'; + +class Controller { + constructor($stateParams, $scope, $http, $translate, vnToken, vnApp) { + this.$stateParams = $stateParams; + this.$ = $scope; + this.$http = $http; + this.$translate = $translate; + this.accessToken = vnToken.token; + this.vnApp = vnApp; + this.filter = { + include: { + relation: 'dms', + scope: { + fields: [ + 'dmsTypeFk', + 'workerFk', + 'hardCopyNumber', + 'reference', + 'description', + 'hasFile', + 'file', + 'created', + ], + include: [{ + relation: 'dmsType', + scope: { + fields: ['name'] + } + }, + { + relation: 'worker', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + }, + } + }] + }, + } + }; + } + + showWorkerDescriptor(event, workerFk) { + event.preventDefault(); + event.stopImmediatePropagation(); + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.workerFk = workerFk; + this.$.workerDescriptor.show(); + } + + showDeleteConfirm(index) { + this.dmsIndex = index; + this.$.confirm.show(); + } + + deleteDms(response) { + if (response === 'accept') { + const dmsFk = this.ticketDms[this.dmsIndex].dmsFk; + const query = `ticketDms/${dmsFk}/removeFile`; + this.$http.post(query).then(() => { + this.$.model.remove(this.dmsIndex); + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }); + } + } +} + +Controller.$inject = ['$stateParams', '$scope', '$http', '$translate', 'vnToken', 'vnApp']; + +ngModule.component('vnTicketDmsIndex', { + template: require('./index.html'), + controller: Controller, +}); diff --git a/modules/ticket/front/dms/index/index.spec.js b/modules/ticket/front/dms/index/index.spec.js new file mode 100644 index 000000000..ab28d750d --- /dev/null +++ b/modules/ticket/front/dms/index/index.spec.js @@ -0,0 +1,40 @@ +import './index'; +import crudModel from 'core/mocks/crud-model'; + +describe('Ticket', () => { + describe('Component vnTicketDmsIndex', () => { + let $componentController; + let $scope; + let $httpBackend; + let controller; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_) => { + $componentController = _$componentController_; + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + controller = $componentController('vnTicketDmsIndex', {$: $scope}); + controller.$.model = crudModel; + })); + + describe('deleteDms()', () => { + it('should make an HTTP Post query', () => { + const dmsId = 1; + const dmsIndex = 0; + spyOn(controller.vnApp, 'showSuccess'); + spyOn(controller.$.model, 'remove'); + controller.ticketDms = [{dmsFk: 1}]; + controller.dmsIndex = dmsIndex; + + $httpBackend.when('POST', `ticketDms/${dmsId}/removeFile`).respond({}); + $httpBackend.expect('POST', `ticketDms/${dmsId}/removeFile`); + controller.deleteDms('accept'); + $httpBackend.flush(); + + expect(controller.$.model.remove).toHaveBeenCalledWith(dmsIndex); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + }); + }); + }); +}); diff --git a/modules/ticket/front/dms/index/style.scss b/modules/ticket/front/dms/index/style.scss new file mode 100644 index 000000000..a6758e2e6 --- /dev/null +++ b/modules/ticket/front/dms/index/style.scss @@ -0,0 +1,6 @@ +vn-client-risk-index { + .totalBox { + display: table; + float: right; + } +} \ No newline at end of file diff --git a/modules/ticket/front/dms/locale/en.yml b/modules/ticket/front/dms/locale/en.yml new file mode 100644 index 000000000..a202e8bf2 --- /dev/null +++ b/modules/ticket/front/dms/locale/en.yml @@ -0,0 +1,2 @@ +FileDescription: Ticket id {{ticketId}} from client {{clientName}} id {{clientId}} +ContentTypesInfo: Allowed file types {{allowedContentTypes}} \ No newline at end of file diff --git a/modules/ticket/front/dms/locale/es.yml b/modules/ticket/front/dms/locale/es.yml new file mode 100644 index 000000000..998960a8e --- /dev/null +++ b/modules/ticket/front/dms/locale/es.yml @@ -0,0 +1,9 @@ +Upload file: Subir fichero +Edit file: Editar fichero +Upload: Subir +File: Fichero +FileDescription: Ticket id {{ticketId}} del cliente {{clientName}} id {{clientId}} +Generate identifier for original file: Generar identificador para archivo original +ContentTypesInfo: 'Tipos de archivo permitidos: {{allowedContentTypes}}' +Are you sure you want to continue?: ¿Seguro que quieres continuar? +File management: Gestión documental \ No newline at end of file diff --git a/modules/ticket/front/expedition/index.html b/modules/ticket/front/expedition/index.html new file mode 100644 index 000000000..b2e859970 --- /dev/null +++ b/modules/ticket/front/expedition/index.html @@ -0,0 +1,74 @@ + + + + + + + + + Expedition + Envialia + Item + Name + Package type + Counter + Checked + Worker + Created + + + + + + + + + {{expedition.id | zeroFill:6}} + {{expedition.externalId | zeroFill:6}} + + + {{expedition.itemFk | zeroFill:6}} + + + {{::expedition.namePackage}} + {{::expedition.nameBox}} + {{::expedition.counter}} + {{::expedition.checked}} + + + {{::expedition.userNickname | dashIfEmpty}} + + + {{::expedition.created | date:'dd/MM/yyyy HH:mm'}} + + + + + + + + + + + \ No newline at end of file diff --git a/modules/ticket/front/expedition/index.js b/modules/ticket/front/expedition/index.js new file mode 100644 index 000000000..5b8a71581 --- /dev/null +++ b/modules/ticket/front/expedition/index.js @@ -0,0 +1,62 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $stateParams, $http) { + this.$ = $scope; + this.$stateParams = $stateParams; + this.$http = $http; + } + + deleteExpedition(expedition) { + this.expeditionId = expedition.id; + this.$.deleteExpedition.show(); + } + + returnDialog(response) { + if (response === 'accept') { + this.$http.delete(`Expeditions/${this.expeditionId}`).then( + () => this.$.model.refresh() + ); + } + } + + showItemDescriptor(event, itemFk) { + if (!itemFk) return; + this.quicklinks = { + btnThree: { + icon: 'icon-transaction', + state: `item.card.diary({ + id: ${itemFk}, + warehouseFk: ${this.ticket.warehouseFk}, + ticketFk: ${this.ticket.id} + })`, + tooltip: 'Item diary', + }, + }; + this.$.itemDescriptor.itemFk = itemFk; + this.$.itemDescriptor.parent = event.target; + this.$.itemDescriptor.show(); + } + + showWorkerDescriptor(event, workerFk) { + event.preventDefault(); + event.stopImmediatePropagation(); + this.selectedWorker = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } + + onDescriptorLoad() { + this.$.popover.relocate(); + } +} + +Controller.$inject = ['$scope', '$stateParams', '$http']; + +ngModule.component('vnTicketExpedition', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<', + }, +}); diff --git a/modules/ticket/front/expedition/index.spec.js b/modules/ticket/front/expedition/index.spec.js new file mode 100644 index 000000000..843c4fff3 --- /dev/null +++ b/modules/ticket/front/expedition/index.spec.js @@ -0,0 +1,38 @@ +import './index'; + +describe('Ticket', () => { + describe('Component vnTicketExpedition', () => { + let controller; + let $scope; + let $state; + let $httpBackend; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$state_, _$httpBackend_) => { + $state = _$state_; + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + $scope.model = { + refresh: () => {} + }; + controller = $componentController('vnTicketExpedition', {$state, $scope}); + })); + + describe('returnDialog()', () => { + it('should perform a DELETE query', () => { + spyOn($scope.model, 'refresh'); + + let response = 'accept'; + controller.expeditionId = 1; + + $httpBackend.when('DELETE', `Expeditions/1`).respond(200); + $httpBackend.expect('DELETE', `Expeditions/1`); + controller.returnDialog(response); + $httpBackend.flush(); + + expect($scope.model.refresh).toHaveBeenCalledWith(); + }); + }); + }); +}); diff --git a/modules/ticket/front/index.js b/modules/ticket/front/index.js new file mode 100644 index 000000000..58ee9136e --- /dev/null +++ b/modules/ticket/front/index.js @@ -0,0 +1,36 @@ +export * from './module'; + +import './main'; +import './index/'; +import './search-panel'; +import './card'; +import './descriptor'; +import './descriptor/addStowaway'; +import './descriptor-popover'; +import './create/card'; +import './create/index'; +import './summary'; +import './basic-data'; +import './basic-data/step-one'; +import './basic-data/step-two'; +import './basic-data/step-three'; +import './note'; +import './expedition'; +import './volume'; +import './package/index'; +import './sale'; +import './sale/editDiscount'; +import './tracking/index'; +import './tracking/edit'; +import './sale-checked'; +import './services'; +import './component'; +import './sale-tracking'; +import './picture'; +import './request/index'; +import './request/create'; +import './log'; +import './weekly'; +import './dms/index'; +import './dms/create'; +import './dms/edit'; diff --git a/modules/ticket/front/index/index.html b/modules/ticket/front/index/index.html new file mode 100644 index 000000000..b303c3ae7 --- /dev/null +++ b/modules/ticket/front/index/index.html @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + + + + + Id + Salesperson + Date + Hour + Alias + Province + State + Agency + Warehouse + Invoice + Closure + Total + + + + + + + + + + + + + + + + + + + + {{::ticket.id}} + + + {{::ticket.userNickname | dashIfEmpty}} + + + + + {{::ticket.shipped | date: 'dd/MM/yyyy'}} + + + {{::ticket.shipped | date: 'HH:mm'}} + + + {{::ticket.nickname}} + + + {{::ticket.province}} + + + {{::ticket.state}} + + + {{::ticket.agencyMode}} + {{::ticket.warehouse}} + {{::ticket.refFk | dashIfEmpty}} + {{::ticket.zoneLanding | date: 'HH:mm'}} + + + {{::ticket.total | currency: 'EUR': 2}} + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/ticket/front/index/index.js b/modules/ticket/front/index/index.js new file mode 100644 index 000000000..9cf1c5483 --- /dev/null +++ b/modules/ticket/front/index/index.js @@ -0,0 +1,143 @@ +import ngModule from '../module'; +import './style.scss'; + +export default class Controller { + constructor($scope, $state, $stateParams, $translate, $http) { + this.$ = $scope; + this.$http = $http; + this.$translate = $translate; + this.$stateParams = $stateParams; + this.$state = $state; + this.selectedTicket = null; + this.moreOptions = [ + { + name: 'Payment on account...', + always: true, + callback: () => { + this.setBalanceCreateDialog(); + this.$.balanceCreateDialog.show(); + } + } + ]; + } + + setBalanceCreateDialog() { + let data = this.$.tickets; + let description = []; + this.$.balanceCreateDialog.amountPaid = 0; + if (data) { + for (let i = 0; i < data.length; i++) { + if (data[i].checked) { + this.$.balanceCreateDialog.amountPaid += data[i].total; + this.$.balanceCreateDialog.clientFk = data[i].clientFk; + description.push(`${data[i].id}`); + } + } + } + this.$.balanceCreateDialog.description = 'Albaran: '; + this.$.balanceCreateDialog.description += description.join(', '); + } + + getScopeDates(days) { + const today = new Date(); + today.setHours(0, 0, 0, 0); + + const daysOnward = new Date(today); + daysOnward.setDate(today.getDate() + days); + daysOnward.setHours(23, 59, 59, 999); + + return {from: today, to: daysOnward}; + } + + onSearch(params) { + if (params) { + let newParams = params; + if (params.scopeDays) { + const scopeDates = this.getScopeDates(params.scopeDays); + Object.assign(newParams, scopeDates); + } else if (Object.entries(params).length == 0) + newParams = this.getScopeDates(1); + + this.$.model.applyFilter(null, newParams); + } else + this.$.model.clear(); + } + + goToLines(event, ticketFk) { + this.preventDefault(event); + let url = this.$state.href('ticket.card.sale', {id: ticketFk}, {absolute: true}); + window.open(url, '_blank'); + } + + onMoreOpen() { + let options = this.moreOptions.filter(o => o.always || this.isChecked); + this.$.moreButton.data = options; + } + + onMoreChange(callback) { + callback.call(this); + } + + compareDate(date) { + let today = new Date(); + today.setHours(0, 0, 0, 0); + let timeTicket = new Date(date); + timeTicket.setHours(0, 0, 0, 0); + + let comparation = today - timeTicket; + + if (comparation == 0) + return 'warning'; + if (comparation < 0) + return 'success'; + } + + stateColor(ticket) { + if (ticket.alertLevelCode === 'OK') + return 'success'; + else if (ticket.alertLevelCode === 'FREE') + return 'notice'; + else if (ticket.alertLevel === 1) + return 'warning'; + else if (ticket.alertLevel === 0) + return 'alert'; + } + + totalPriceColor(ticket) { + const total = parseInt(ticket.total); + if (total > 0 && total < 50) + return 'warning'; + } + + showClientDescriptor(event, clientFk) { + this.preventDefault(event); + this.$.clientDescriptor.clientFk = clientFk; + this.$.clientDescriptor.parent = event.target; + this.$.clientDescriptor.show(); + } + + showWorkerDescriptor(event, workerFk) { + this.preventDefault(event); + this.selectedWorker = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } + + preview(event, ticket) { + this.preventDefault(event); + this.selectedTicket = ticket; + this.$.summary.show(); + } + + preventDefault(event) { + event.preventDefault(); + event.stopImmediatePropagation(); + } +} + +Controller.$inject = ['$scope', '$state', '$stateParams', '$translate', '$http']; + +ngModule.component('vnTicketIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/ticket/front/index/index.spec.js b/modules/ticket/front/index/index.spec.js new file mode 100644 index 000000000..dd1e3009e --- /dev/null +++ b/modules/ticket/front/index/index.spec.js @@ -0,0 +1,99 @@ +import './index.js'; +describe('Component vnTicketIndex', () => { + let controller; + let $window; + let tickets = [{ + id: 1, + clientFk: 1, + total: 10.5, + checked: false + }, { + id: 2, + clientFk: 1, + total: 20.5, + checked: true + }, { + id: 3, + clientFk: 1, + total: 30, + checked: true + }]; + + beforeEach(ngModule('ticket')); + + beforeEach(inject(($componentController, _$window_) => { + $window = _$window_; + controller = $componentController('vnTicketIndex'); + })); + + describe('compareDate()', () => { + it('should return warning when the date is the present', () => { + let curDate = new Date(); + let result = controller.compareDate(curDate); + + expect(result).toEqual('warning'); + }); + + it('should return sucess when the date is in the future', () => { + let futureDate = new Date(); + futureDate = futureDate.setDate(futureDate.getDate() + 10); + let result = controller.compareDate(futureDate); + + expect(result).toEqual('success'); + }); + + it('should return undefined when the date is in the past', () => { + let pastDate = new Date(); + pastDate = pastDate.setDate(pastDate.getDate() - 10); + let result = controller.compareDate(pastDate); + + expect(result).toEqual(undefined); + }); + }); + + describe('showClientDescriptor()', () => { + it('should show the client descriptor popover', () => { + controller.$.clientDescriptor = {show: () => {}}; + controller.$.clientDescriptor.show = jasmine.createSpy('show'); + let event = new MouseEvent('click', { + view: $window, + bubbles: true, + cancelable: true + }); + controller.showClientDescriptor(event, tickets[0].clientFk); + + expect(controller.$.clientDescriptor.show).toHaveBeenCalledWith(); + }); + }); + + describe('preview()', () => { + it('should show the dialog summary', () => { + controller.$.summary = {show: () => {}}; + spyOn(controller.$.summary, 'show'); + + let event = new MouseEvent('click', { + view: $window, + bubbles: true, + cancelable: true + }); + controller.preview(event, tickets[0]); + + expect(controller.$.summary.show).toHaveBeenCalledWith(); + }); + }); + + describe('setBalanceCreateDialog()', () => { + it('should fill the object for the component balanceCreateDialog', () => { + controller.$.tickets = tickets; + controller.$.balanceCreateDialog = {}; + controller.$.balanceCreateDialog.amountPaid = 0; + controller.setBalanceCreateDialog(); + + let description = controller.$.balanceCreateDialog.description; + let amountPaid = controller.$.balanceCreateDialog.amountPaid; + + expect(description).toEqual('Albaran: 2, 3'); + expect(amountPaid).toEqual(50.5); + }); + }); +}); diff --git a/modules/ticket/front/index/locale/es.yml b/modules/ticket/front/index/locale/es.yml new file mode 100644 index 000000000..b29c7399d --- /dev/null +++ b/modules/ticket/front/index/locale/es.yml @@ -0,0 +1,5 @@ +Weekly tickets: Tickets programados +Go to lines: Ir a lineas +Not available: No disponible +Payment on account...: Pago a cuenta... +Closure: Cierre \ No newline at end of file diff --git a/modules/ticket/front/index/style.scss b/modules/ticket/front/index/style.scss new file mode 100644 index 000000000..30d7c11ca --- /dev/null +++ b/modules/ticket/front/index/style.scss @@ -0,0 +1,9 @@ +@import "variables"; + +vn-ticket-index { + @media screen and (max-width: 1440px) { + .expendable { + display: none; + } + } +} \ No newline at end of file diff --git a/modules/ticket/front/locale/es.yml b/modules/ticket/front/locale/es.yml new file mode 100644 index 000000000..b26a6d6fa --- /dev/null +++ b/modules/ticket/front/locale/es.yml @@ -0,0 +1,80 @@ +#Ordenar alfabeticamente +Address: Consignatario +Agency: Agencia +Amount: Importe +Base to commission: Base comisionable +Boxes: Cajas +by: por +Checked: Comprobado +Client: Cliente +Client card: Ficha del cliente +Code 100: Código 100 +Company: Empresa +Counter: Contador +Created : Añadido +Date : Fecha +Delay: Retraso +Delete: Eliminar +Delete expedition: Eliminar expedición +Description: Descripción +Discount: Descuento +Employee : Empleado +Import: Importe +Is checked: Comprobado +Item: Articulo +Landing: Llegada +Landed: F. entrega +More: Más +Mark as reserved: Marcar como reservado +Unmark as reserved: Desmarcar como reservado +m³ per unit: m³ por unidad +m³ per quantity: m³ por cantidad +Name: Nombre +New price: Nuevo precio +New : Nuevo +Next: Siguiente +Observation type: Tipo de observación +Original: Original +Package size: Bultos +Package type: Tipo de porte +Phone: Teléfono +PPU: Ud. +Price: Precio +Price gap: Diferencia de precio +Quantity: Cantidad +Remove lines: Eliminar lineas +Route: Ruta +SET OK: PONER OK +Shipment: Salida +Shipped: F. envío +Some fields are invalid: Algunos campos no son válidos +State: Estado +Tickets: Tickets +Warehouse: Almacén +Worker: Trabajador +VAT: IVA +Hour: Hora +The quantity do not match: Las cantidades no coinciden +Freezed: Congelado +Risk: Riesgo +Invoice: Factura +You are going to delete this ticket: Vas a eliminar este ticket +Ticket deleted: Ticket borrado +Search ticket by id or alias: Buscar tickets por identificador o alias + +#sections +List: Listado +Summary: Vista previa +Basic data: Datos básicos +Sale: Lineas del pedido +Notes: Notas +Volume: Volumen +Expedition: Expedición +New state: Nuevo estado +Packages: Embalajes +Tracking: Estados +Sale checked: Control clientes +Components: Componentes +Sale tracking: Líneas preparadas +Photos: Fotos +Log: Historial \ No newline at end of file diff --git a/modules/ticket/front/log/index.html b/modules/ticket/front/log/index.html new file mode 100644 index 000000000..4fe26c871 --- /dev/null +++ b/modules/ticket/front/log/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/modules/ticket/front/log/index.js b/modules/ticket/front/log/index.js new file mode 100644 index 000000000..6a486d3d0 --- /dev/null +++ b/modules/ticket/front/log/index.js @@ -0,0 +1,15 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $stateParams) { + this.$scope = $scope; + this.$stateParams = $stateParams; + } +} + +Controller.$inject = ['$scope', '$stateParams']; + +ngModule.component('vnTicketLog', { + template: require('./index.html'), + controller: Controller, +}); diff --git a/modules/ticket/front/main/index.html b/modules/ticket/front/main/index.html new file mode 100644 index 000000000..7e058f45d --- /dev/null +++ b/modules/ticket/front/main/index.html @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/modules/ticket/front/main/index.js b/modules/ticket/front/main/index.js new file mode 100644 index 000000000..d6100daa3 --- /dev/null +++ b/modules/ticket/front/main/index.js @@ -0,0 +1,9 @@ +import ngModule from '../module'; +import ModuleMain from 'salix/components/module-main'; + +export default class Ticket extends ModuleMain {} + +ngModule.vnComponent('vnTicket', { + controller: Ticket, + template: require('./index.html') +}); diff --git a/modules/ticket/front/module.js b/modules/ticket/front/module.js new file mode 100644 index 000000000..34f7f953e --- /dev/null +++ b/modules/ticket/front/module.js @@ -0,0 +1,3 @@ +import {ng} from 'core/vendor'; + +export default ng.module('ticket', ['vnCore']); diff --git a/modules/ticket/front/note/index.html b/modules/ticket/front/note/index.html new file mode 100644 index 000000000..617cf2f7d --- /dev/null +++ b/modules/ticket/front/note/index.html @@ -0,0 +1,62 @@ + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/modules/ticket/front/note/index.js b/modules/ticket/front/note/index.js new file mode 100644 index 000000000..4a74b3b98 --- /dev/null +++ b/modules/ticket/front/note/index.js @@ -0,0 +1,26 @@ +import ngModule from '../module'; + +class Controller { + constructor($stateParams, $scope) { + this.$stateParams = $stateParams; + this.$scope = $scope; + } + + onSubmit() { + this.$scope.watcher.check(); + this.$scope.model.save().then(() => { + this.$scope.watcher.notifySaved(); + this.$scope.model.refresh(); + }); + } +} + +Controller.$inject = ['$stateParams', '$scope']; + +ngModule.component('vnTicketObservation', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<' + } +}); diff --git a/modules/ticket/front/package/index.html b/modules/ticket/front/package/index.html new file mode 100644 index 000000000..87c424ff1 --- /dev/null +++ b/modules/ticket/front/package/index.html @@ -0,0 +1,61 @@ + + + + +
    + + + + {{itemFk}} : {{name}} + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/modules/ticket/front/package/index.js b/modules/ticket/front/package/index.js new file mode 100644 index 000000000..d73c000c7 --- /dev/null +++ b/modules/ticket/front/package/index.js @@ -0,0 +1,32 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $stateParams) { + this.$scope = $scope; + this.$stateParams = $stateParams; + } + + add() { + this.$scope.model.insert({ + packagingFk: null, + quantity: null, + created: new Date(), + ticketFk: this.$stateParams.id + }); + } + + onSubmit() { + this.$scope.watcher.check(); + this.$scope.model.save().then(() => { + this.$scope.watcher.notifySaved(); + this.$scope.model.refresh(); + }); + } +} + +Controller.$inject = ['$scope', '$stateParams']; + +ngModule.component('vnTicketPackage', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/ticket/front/package/locale/es.yml b/modules/ticket/front/package/locale/es.yml new file mode 100644 index 000000000..b03fb2153 --- /dev/null +++ b/modules/ticket/front/package/locale/es.yml @@ -0,0 +1,5 @@ +Package: Embalaje +Quantity: Cantidad +Added: Añadido +Add package: Añadir embalaje +Remove package: Quitar embalaje \ No newline at end of file diff --git a/modules/ticket/front/picture/index.html b/modules/ticket/front/picture/index.html new file mode 100644 index 000000000..67ce5464e --- /dev/null +++ b/modules/ticket/front/picture/index.html @@ -0,0 +1,65 @@ + + + + + No results + + +
    + +
    + +
    +
    +

    + + {{::sale.item.name}} + +

    +

    + {{::sale.item.subName}} +

    +
    + + + + + + +
    + +
    +
    +
    +
    + +
    + diff --git a/modules/ticket/front/picture/index.js b/modules/ticket/front/picture/index.js new file mode 100644 index 000000000..a68e69d52 --- /dev/null +++ b/modules/ticket/front/picture/index.js @@ -0,0 +1,34 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $stateParams, $http) { + this.$scope = $scope; + this.$stateParams = $stateParams; + this.$http = $http; + this.filter = { + include: { + relation: 'item', + scope: { + field: ['name', 'image'] + } + } + }; + } + + showDescriptor(event, itemFk) { + this.$scope.descriptor.itemFk = itemFk; + this.$scope.descriptor.parent = event.target; + this.$scope.descriptor.show(); + } + + onDescriptorLoad() { + this.$scope.popover.relocate(); + } +} + +Controller.$inject = ['$scope', '$stateParams', '$http']; + +ngModule.component('vnTicketPicture', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/ticket/front/request/create/index.html b/modules/ticket/front/request/create/index.html new file mode 100644 index 000000000..46d96ca44 --- /dev/null +++ b/modules/ticket/front/request/create/index.html @@ -0,0 +1,53 @@ + + + +
    +
    + + + + + + + + + + + + + + + + + + +
    +
    diff --git a/modules/ticket/front/request/create/index.js b/modules/ticket/front/request/create/index.js new file mode 100644 index 000000000..fac89be8b --- /dev/null +++ b/modules/ticket/front/request/create/index.js @@ -0,0 +1,25 @@ +import ngModule from '../../module'; +import './style.scss'; + +class Controller { + constructor($state, $scope) { + this.$ = $scope; + this.$state = $state; + this.ticketRequest = { + ticketFk: $state.params.id + }; + } + + onSubmit() { + this.$.watcher.submit().then( + json => this.$state.go('ticket.card.request.index', {id: this.$state.params.id}) + ); + } +} + +Controller.$inject = ['$state', '$scope']; + +ngModule.component('vnTicketRequestCreate', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/ticket/front/request/create/locale/es.yml b/modules/ticket/front/request/create/locale/es.yml new file mode 100644 index 000000000..ded6fc65b --- /dev/null +++ b/modules/ticket/front/request/create/locale/es.yml @@ -0,0 +1,4 @@ +Purchase request: Petición de compra +Atender: Comprador +Remove request: Eliminar petición +New request: Crear petición \ No newline at end of file diff --git a/modules/ticket/front/request/create/style.scss b/modules/ticket/front/request/create/style.scss new file mode 100644 index 000000000..73f136fc1 --- /dev/null +++ b/modules/ticket/front/request/create/style.scss @@ -0,0 +1,7 @@ +vn-ticket-request { + .vn-textfield { + margin: 0!important; + max-width: 100px; + } +} + diff --git a/modules/ticket/front/request/index/index.html b/modules/ticket/front/request/index/index.html new file mode 100644 index 000000000..a5ccb7d82 --- /dev/null +++ b/modules/ticket/front/request/index/index.html @@ -0,0 +1,95 @@ + + + + + + + + + + Id + Description + Created + Requester + Atender + Quantity + Price + Sale id + Ok + + + + + {{::request.id}} + {{::request.description}} + {{::request.created | date: 'dd/MM/yyyy'}} + + + {{::request.requester.user.nickname | dashIfEmpty}} + + + + + {{::request.atender.user.nickname | dashIfEmpty}} + + + {{::request.quantity}} + {{::request.price | currency: 'EUR': 2}} + + + {{request.saleFk | zeroFill:6}} + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/ticket/front/request/index/index.js b/modules/ticket/front/request/index/index.js new file mode 100644 index 000000000..2c8996760 --- /dev/null +++ b/modules/ticket/front/request/index/index.js @@ -0,0 +1,88 @@ +import ngModule from '../../module'; + +class Controller { + constructor($scope, $stateParams) { + this.$stateParams = $stateParams; + this.$ = $scope; + this.filter = { + include: [ + { + relation: 'atender', + scope: { + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + }, + { + relation: 'requester', + scope: { + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + }, + { + relation: 'sale' + } + ] + }; + } + + removeLine(index) { + this.$.model.remove(index); + this.$.watcher.check(); + this.$.model.save().then(() => { + this.$.watcher.notifySaved(); + this.$.watcher.updateOriginalData(); + }); + } + + showItemDescriptor(event, itemFk) { + this.quicklinks = { + btnThree: { + icon: 'icon-transaction', + state: `item.card.diary({ + id: ${itemFk}, + ticketFk: ${this.$stateParams.id} + })`, + tooltip: 'Item diary' + } + }; + this.$.itemDescriptor.itemFk = itemFk; + this.$.itemDescriptor.parent = event.target; + this.$.itemDescriptor.show(); + } + + showWorkerDescriptor(event, workerFk) { + event.preventDefault(); + event.stopImmediatePropagation(); + this.selectedWorker = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } + + getRequestState(state) { + switch (state) { + case null: + return 'New'; + case false: + return 'Denied'; + case true: + return 'Acepted'; + } + } +} + +Controller.$inject = ['$scope', '$stateParams']; + +ngModule.component('vnTicketRequestIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/ticket/front/request/index/locale/es.yml b/modules/ticket/front/request/index/locale/es.yml new file mode 100644 index 000000000..65442cde1 --- /dev/null +++ b/modules/ticket/front/request/index/locale/es.yml @@ -0,0 +1,6 @@ +Purchase request: Petición de compra +Atender: Comprador +Remove request: Eliminar petición +New request: Crear petición +Sale id: Id linea +Requester: Solicitante \ No newline at end of file diff --git a/modules/ticket/front/routes.json b/modules/ticket/front/routes.json new file mode 100644 index 000000000..be142a2ac --- /dev/null +++ b/modules/ticket/front/routes.json @@ -0,0 +1,259 @@ +{ + "module": "ticket", + "name": "Tickets", + "icon": "icon-ticket", + "validations": true, + "dependencies": ["worker", "item", "client"], + "menus": { + "main": [ + {"state": "ticket.index", "icon": "icon-ticket"}, + {"state": "ticket.weekly.index", "icon": "schedule"} + ], + "card": [ + {"state": "ticket.card.basicData.stepOne", "icon": "settings"}, + {"state": "ticket.card.sale", "icon": "icon-lines"}, + {"state": "ticket.card.observation", "icon": "insert_drive_file"}, + {"state": "ticket.card.volume", "icon": "icon-volume"}, + {"state": "ticket.card.expedition", "icon": "icon-package"}, + {"state": "ticket.card.service", "icon": "icon-services"}, + {"state": "ticket.card.package", "icon": "icon-bucket"}, + {"state": "ticket.card.tracking.index", "icon": "remove_red_eye"}, + {"state": "ticket.card.saleChecked", "icon": "assignment"}, + {"state": "ticket.card.components", "icon": "icon-components"}, + {"state": "ticket.card.saleTracking", "icon": "assignment"}, + {"state": "ticket.card.picture", "icon": "image"}, + {"state": "ticket.card.log", "icon": "history"}, + {"state": "ticket.card.request.index", "icon": "icon-100"}, + {"state": "ticket.card.dms.index", "icon": "cloud_download"} + ] + }, + "keybindings": [ + {"key": "t", "state": "ticket.index"} + ], + "routes": [ + { + "url": "/ticket", + "state": "ticket", + "abstract": true, + "component": "vn-ticket", + "description": "Tickets" + }, { + "url": "/index?q", + "state": "ticket.index", + "component": "vn-ticket-index", + "description": "Tickets" + }, { + "url": "/:id?sendSMS&phone&message", + "state": "ticket.card", + "abstract": true, + "component": "vn-ticket-card" + }, { + "url": "/summary", + "state": "ticket.card.summary", + "component": "vn-ticket-summary", + "description": "Summary", + "params": { + "ticket": "$ctrl.ticket" + } + }, { + "url" : "/basic-data", + "state": "ticket.card.basicData", + "component": "vn-ticket-basic-data", + "abstract": true, + "params": { + "ticket": "$ctrl.ticket" + } + }, { + "url" : "/step-one", + "state": "ticket.card.basicData.stepOne", + "component": "vn-ticket-basic-data-step-one", + "description": "Basic data", + "params": { + "ticket": "$ctrl.data" + } + }, { + "url" : "/step-two", + "state": "ticket.card.basicData.stepTwo", + "component": "vn-ticket-basic-data-step-two", + "description": "Price difference", + "params": { + "ticket": "$ctrl.data" + } + }, { + "url" : "/step-three", + "state": "ticket.card.basicData.stepThree", + "component": "vn-ticket-basic-data-step-three", + "description": "Charge", + "params": { + "ticket": "$ctrl.data" + } + }, { + "url" : "/sale", + "state": "ticket.card.sale", + "component": "vn-ticket-sale", + "description": "Sale", + "params": { + "ticket": "$ctrl.ticket" + } + }, { + "url": "/observation", + "state": "ticket.card.observation", + "component": "vn-ticket-observation", + "description": "Notes", + "params": { + "ticket": "$ctrl.ticket" + } + }, { + "url": "/volume", + "state": "ticket.card.volume", + "component": "vn-ticket-volume", + "description": "Volume", + "params": { + "ticket": "$ctrl.ticket" + } + }, { + "url": "/expedition", + "state": "ticket.card.expedition", + "component": "vn-ticket-expedition", + "description": "Expedition", + "params": { + "ticket": "$ctrl.ticket" + } + }, { + "url" : "/package", + "state": "ticket.card.package", + "component": "vn-ticket-package", + "description": "Packages", + "params": { + "ticket": "$ctrl.ticket" + } + }, { + "url": "/tracking", + "state": "ticket.card.tracking", + "abstract": true, + "component": "ui-view" + }, { + "url" : "/index", + "state": "ticket.card.tracking.index", + "component": "vn-ticket-tracking-index", + "description": "Tracking", + "params": { + "ticket": "$ctrl.ticket" + } + }, { + "url": "/edit", + "state": "ticket.card.tracking.edit", + "component": "vn-ticket-tracking-edit", + "description": "New state", + "params": { + "ticket": "$ctrl.ticket" + }, + "acl": ["production", "administrative", "salesPerson"] + }, { + "url" : "/sale-checked", + "state": "ticket.card.saleChecked", + "component": "vn-ticket-sale-checked", + "description": "Sale checked", + "params": { + "ticket": "$ctrl.ticket" + } + }, { + "url" : "/components", + "state": "ticket.card.components", + "component": "vn-ticket-components", + "description": "Components", + "params": { + "ticket": "$ctrl.ticket" + } + }, { + "url" : "/sale-tracking", + "state": "ticket.card.saleTracking", + "component": "vn-ticket-sale-tracking", + "description": "Sale tracking", + "params": { + "ticket": "$ctrl.ticket" + } + }, { + "url" : "/picture", + "state": "ticket.card.picture", + "component": "vn-ticket-picture", + "description": "Pictures", + "params": { + "ticket": "$ctrl.ticket" + } + }, { + "url" : "/log", + "state": "ticket.card.log", + "component": "vn-ticket-log", + "description": "Log" + }, { + "url": "/weekly", + "state": "ticket.weekly", + "abstract": true, + "component": "ui-view", + "description": "Weekly" + }, { + "url": "/index?q", + "state": "ticket.weekly.index", + "component": "vn-ticket-weekly-index", + "description": "Weekly tickets" + }, { + "url": "/request", + "state": "ticket.card.request", + "abstract": true, + "component": "ui-view" + }, { + "url": "/service", + "state": "ticket.card.service", + "component": "vn-ticket-service", + "description": "Service" + }, { + "url" : "/index", + "state": "ticket.card.request.index", + "component": "vn-ticket-request-index", + "description": "Purchase request", + "acl": ["salesPerson"] + }, { + "url" : "/create", + "state": "ticket.card.request.create", + "component": "vn-ticket-request-create", + "description": "New purchase request", + "acl": ["salesPerson"] + }, { + "url": "/create?clientFk", + "state": "ticket.create", + "component": "vn-ticket-create", + "description": "New ticket" + }, + { + "url": "/dms", + "state": "ticket.card.dms", + "abstract": true, + "component": "ui-view" + }, + { + "url": "/index", + "state": "ticket.card.dms.index", + "component": "vn-ticket-dms-index", + "description": "File management" + }, + { + "url": "/create", + "state": "ticket.card.dms.create", + "component": "vn-ticket-dms-create", + "description": "Upload file", + "params": { + "ticket": "$ctrl.ticket" + } + }, + { + "url": "/:dmsId/edit", + "state": "ticket.card.dms.edit", + "component": "vn-ticket-dms-edit", + "description": "Edit file", + "params": { + "ticket": "$ctrl.ticket" + } + } + ] +} \ No newline at end of file diff --git a/modules/ticket/front/sale-checked/index.html b/modules/ticket/front/sale-checked/index.html new file mode 100644 index 000000000..c7e060e4e --- /dev/null +++ b/modules/ticket/front/sale-checked/index.html @@ -0,0 +1,54 @@ + + + + + + + + Is checked + Item + Description + Quantity + + + + + + + + + + + {{::sale.itemFk | zeroFill:6}} + + + + + + + {{::sale.quantity}} + + + + + + + diff --git a/modules/ticket/front/sale-checked/index.js b/modules/ticket/front/sale-checked/index.js new file mode 100644 index 000000000..08157bc9d --- /dev/null +++ b/modules/ticket/front/sale-checked/index.js @@ -0,0 +1,50 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $stateParams) { + this.$scope = $scope; + this.$stateParams = $stateParams; + this.filter = { + include: [{ + relation: 'item' + }, + { + relation: 'isChecked', + scope: { + fields: ['isChecked'] + } + }] + }; + } + + showDescriptor(event, itemFk) { + this.quicklinks = { + btnThree: { + icon: 'icon-transaction', + state: `item.card.diary({ + id: ${itemFk}, + warehouseFk: ${this.ticket.warehouseFk}, + ticketFk: ${this.ticket.id} + })`, + tooltip: 'Item diary' + } + }; + this.$scope.descriptor.itemFk = itemFk; + this.$scope.descriptor.parent = event.target; + this.$scope.descriptor.show(); + } + + onDescriptorLoad() { + this.$scope.popover.relocate(); + } +} + +Controller.$inject = ['$scope', '$stateParams']; + +ngModule.component('vnTicketSaleChecked', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<' + } +}); diff --git a/modules/ticket/front/sale-tracking/index.html b/modules/ticket/front/sale-tracking/index.html new file mode 100644 index 000000000..0186fb935 --- /dev/null +++ b/modules/ticket/front/sale-tracking/index.html @@ -0,0 +1,72 @@ + + + + + + + + + Item + Description + Quantity + Original + Worker + State + Created + + + + + + + + + + + {{sale.itemFk | zeroFill:6}} + + + + + + + {{::sale.quantity}} + {{::sale.originalQuantity}} + + + {{::sale.userNickname | dashIfEmpty}} + + + {{::sale.state}} + {{::sale.created | date: 'dd/MM/yyyy HH:mm'}} + + + + + + + + + \ No newline at end of file diff --git a/modules/ticket/front/sale-tracking/index.js b/modules/ticket/front/sale-tracking/index.js new file mode 100644 index 000000000..41ff12a4a --- /dev/null +++ b/modules/ticket/front/sale-tracking/index.js @@ -0,0 +1,47 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $stateParams) { + this.$ = $scope; + this.$stateParams = $stateParams; + } + + showItemDescriptor(event, itemFk) { + this.quicklinks = { + btnThree: { + icon: 'icon-transaction', + state: `item.card.diary({ + id: ${itemFk}, + warehouseFk: ${this.ticket.warehouseFk}, + ticketFk: ${this.ticket.id} + })`, + tooltip: 'Item diary', + }, + }; + this.$.itemDescriptor.itemFk = itemFk; + this.$.itemDescriptor.parent = event.target; + this.$.itemDescriptor.show(); + } + + showWorkerDescriptor(event, workerFk) { + event.preventDefault(); + event.stopImmediatePropagation(); + this.selectedWorker = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } + + onDescriptorLoad() { + this.$.popover.relocate(); + } +} + +Controller.$inject = ['$scope', '$stateParams']; + +ngModule.component('vnTicketSaleTracking', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<', + }, +}); diff --git a/modules/ticket/front/sale/editDiscount.html b/modules/ticket/front/sale/editDiscount.html new file mode 100644 index 000000000..c23645784 --- /dev/null +++ b/modules/ticket/front/sale/editDiscount.html @@ -0,0 +1,16 @@ +
    +
    MANÁ: {{$ctrl.mana | currency: 'EUR':0}}
    +
    +
    + + +
    +

    New price

    +

    {{$ctrl.newPrice | currency: 'EUR':2}}

    +
    +
    \ No newline at end of file diff --git a/modules/ticket/front/sale/editDiscount.js b/modules/ticket/front/sale/editDiscount.js new file mode 100644 index 000000000..6011f77bf --- /dev/null +++ b/modules/ticket/front/sale/editDiscount.js @@ -0,0 +1,93 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $http, $state, vnApp, $translate) { + this.$scope = $scope; + this.$http = $http; + this.$state = $state; + this.vnApp = vnApp; + this.$translate = $translate; + } + + set edit(value) { + this._edit = value; + this.clearDiscount(); + this.setNewDiscount(); + } + + get edit() { + return this._edit; + } + + set bulk(value) { + this._bulk = value; + this.setNewDiscount(); + } + + get bulk() { + return this._bulk; + } + + get newDiscount() { + return this._newDiscount; + } + + set newDiscount(value) { + this._newDiscount = value; + this.updateNewPrice(); + } + + updateNewPrice() { + if (this.newDiscount && this.edit[0]) + this.newPrice = (this.edit[0].quantity * this.edit[0].price) - ((this.newDiscount * (this.edit[0].quantity * this.edit[0].price)) / 100); + } + + setNewDiscount() { + if (!this.newDiscount && this.edit[0]) + this.newDiscount = this.edit[0].discount; + } + + updateDiscount() { + let salesIds = []; + let modified = false; + for (let i = 0; i < this.edit.length; i++) { + if (this.newDiscount != this.edit[0].discount || this.bulk || !this.newDiscount) { + salesIds.push(this.edit[i].id); + modified = true; + } + } + + if (modified) { + const params = {salesIds: salesIds, newDiscount: this.newDiscount}; + const query = `Tickets/${this.$state.params.id}/updateDiscount`; + this.$http.post(query, params).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.clearDiscount(); + modified = false; + // this.vnTicketSale.$scope.model.refresh(); + }).catch(e => { + this.vnApp.showError(e.message); + }); + + this.onHide(); + } else + this.vnApp.showError(this.$translate.instant('There are no changes to save')); + } + + clearDiscount() { + this.newDiscount = null; + } +} + +Controller.$inject = ['$scope', '$http', '$state', 'vnApp', '$translate']; + +ngModule.component('vnTicketSaleEditDiscount', { + template: require('./editDiscount.html'), + controller: Controller, + bindings: { + edit: ' + + + + + + + + + + + + + + + + + + + + +

    Subtotal {{$ctrl.subtotal | currency: 'EUR':2}}

    +

    VAT {{$ctrl.VAT | currency: 'EUR':2}}

    +

    Total {{$ctrl.total | currency: 'EUR':2}}

    +
    +
    + + + + + + + + + + Id + Quantity + Item + Price + Disc + Amount + + + + + + + + + + + + + + + + + + + + + + + + {{sale.itemFk | zeroFill:6}} + + + + {{id}} - {{name}} + + + + + {{sale.quantity}} + + + + + + + + + + + + + + + + + + + + + + {{sale.price | currency: 'EUR':2}} + + + + + {{sale.discount | percentage}} + + + + {{$ctrl.getSaleTotal(sale) | currency: 'EUR':2}} + + + + + + + + +
    +
    + + + + + + + + +
    + + +
    +
    +
    MANÁ: {{$ctrl.mana | currency: 'EUR':0}}
    +
    +
    + + +
    +

    New price

    +

    {{$ctrl.newPrice | currency: 'EUR':2}}

    +
    +
    +
    +
    +
    + + + +
    + + + + +
    +
    + + + +
    + + +

    Sales to transfer

    + + + + Id + Item + Quantity + + + + + {{::sale.itemFk | zeroFill:6}} + + {{::sale.concept}} + + + {{sale.quantity}} + + + + + + + + +
    + + +

    Destination ticket

    + + +
    + + + + + + + + + + + + + + + + + + + + +
    IdF. envioAgenciaAlmacen
    No results
    {{::ticket.id}}{{::ticket.shipped | date: 'dd/MM/yyyy'}}{{::ticket.agencyName}}{{::ticket.warehouseName}}
    + + + + + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/ticket/front/sale/index.js b/modules/ticket/front/sale/index.js new file mode 100644 index 000000000..d0854c996 --- /dev/null +++ b/modules/ticket/front/sale/index.js @@ -0,0 +1,567 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $state, $http, vnApp, $translate) { + this.$scope = $scope; + this.vnApp = vnApp; + this.$translate = $translate; + this.$state = $state; + this.$stateParams = $state.params; + this.$http = $http; + this.edit = {}; + this.moreOptions = [ + { + name: 'Send SMS', + callback: this.showSMSDialog + }, { + name: 'Mark as reserved', + callback: this.markAsReserved, + show: () => this.isEditable + }, { + name: 'Unmark as reserved', + callback: this.unmarkAsReserved, + show: () => this.isEditable + }, { + name: 'Update discount', + callback: this.showEditDialog, + show: () => this.isEditable + }, { + name: 'Add claim', + callback: this.createClaim + }, { + name: 'Recalculate price', + callback: this.calculateSalePrice, + show: () => this.hasOneSaleSelected() + }, + ]; + this._sales = []; + this.imagesPath = '//verdnatura.es/vn-image-data/catalog'; + } + + get ticket() { + return this._ticket; + } + + set ticket(value) { + this._ticket = value; + this.isTicketEditable(); + } + + get sales() { + return this._sales; + } + + set sales(value) { + this._sales = value; + this.refreshTotal(); + } + + get editedPrice() { + return this._editedPrice; + } + + set editedPrice(value) { + this._editedPrice = value; + this.updateNewPrice(); + } + + refreshTotal() { + this.loadSubTotal(); + this.loadVAT(); + } + + loadSubTotal() { + if (!this.$stateParams.id || !this.sales) return; + this.$http.get(`Tickets/${this.$stateParams.id}/subtotal`).then(res => { + this.subtotal = res.data || 0.0; + }); + } + + getSaleTotal(sale) { + if (!sale.quantity || !sale.price) + return; + + return sale.quantity * sale.price * ((100 - sale.discount) / 100); + } + + loadVAT() { + this.VAT = 0.0; + if (!this.$stateParams.id || !this.sales) return; + this.$http.get(`Tickets/${this.$stateParams.id}/getVAT`).then(res => { + this.VAT = res.data || 0.0; + }); + } + + get total() { + return this.subtotal + this.VAT; + } + + onMoreOpen() { + let options = this.moreOptions.filter(option => { + const hasShowProperty = Object.hasOwnProperty.call(option, 'show'); + const shouldShow = !hasShowProperty || option.show === true || + typeof option.show === 'function' && option.show(); + + return (shouldShow && (option.always || this.isChecked)); + }); + this.$scope.moreButton.data = options; + } + + onMoreChange(callback) { + callback.call(this); + } + + get isChecked() { + if (this.sales) { + for (let instance of this.sales) + if (instance.checked) return true; + } + + return false; + } + + /** + * Returns checked instances + * + * @return {Array} Checked instances + */ + checkedLines() { + if (!this.sales) return; + + return this.sales.filter(sale => { + return sale.checked; + }); + } + + /** + * Returns new instances + * + * @return {Array} New instances + */ + newInstances() { + if (!this.sales) return; + + return this.sales.filter(sale => { + return !sale.id; + }); + } + + /** + * Returns an array of indexes + * from checked instances + * + * @return {Array} Indexes of checked instances + */ + checkedLinesIndex() { + if (!this.sales) return; + + let indexes = []; + this.sales.forEach((sale, index) => { + if (sale.checked) indexes.push(index); + }); + + return indexes; + } + + firstCheckedLine() { + const checkedLines = this.checkedLines(); + if (checkedLines) + return checkedLines[0]; + } + + /** + * Returns the total of checked instances + * + * @return {Number} Total checked instances + */ + totalCheckedLines() { + const checkedLines = this.checkedLines(); + if (checkedLines) + return checkedLines.length; + } + + + removeCheckedLines() { + const sales = this.checkedLines(); + + sales.forEach(sale => { + const index = this.sales.indexOf(sale); + this.sales.splice(index, 1); + }); + + if (this.newInstances().length === 0) + this.$scope.watcher.updateOriginalData(); + + this.refreshTotal(); + } + + onStateOkClick() { + let filter = {where: {code: 'OK'}, fields: ['id']}; + let json = encodeURIComponent(JSON.stringify(filter)); + return this.$http.get(`States?filter=${json}`).then(res => { + this.onStateChange(res.data[0].id); + }); + } + + onStateChange(value) { + let params = {ticketFk: this.$state.params.id, stateFk: value}; + this.$http.post(`TicketTrackings/changeState`, params).then(() => { + this.card.reload(); + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }).finally(() => { + if (this.newInstances().length === 0) + this.$scope.watcher.updateOriginalData(); + }); + } + + onRemoveLinesClick(response) { + if (response === 'accept') { + let sales = this.checkedLines(); + + // Remove unsaved instances + sales.forEach((sale, index) => { + if (!sale.id) sales.splice(index); + }); + + let params = {sales: sales, actualTicketFk: this.ticket.id}; + let query = `Sales/removes`; + this.$http.post(query, params).then(() => { + this.removeCheckedLines(); + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }); + } + } + + showRemoveLinesDialog() { + this.$scope.deleteLines.show(); + } + + showTransferPopover(event) { + this.setTransferParams(); + this.$scope.transfer.parent = event.target; + this.$scope.transfer.show(); + } + + setTransferParams() { + const checkedSales = JSON.stringify(this.checkedLines()); + const sales = JSON.parse(checkedSales); + this.transfer = { + lastActiveTickets: [], + sales: sales + }; + + const params = {ticketId: this.ticket.id}; + const query = `clients/${this.ticket.clientFk}/lastActiveTickets`; + this.$http.get(query, {params}).then(res => { + this.transfer.lastActiveTickets = res.data; + }); + } + + transferSales(ticketId) { + const params = { + ticketId: ticketId, + sales: this.transfer.sales + }; + + this.$scope.watcher.updateOriginalData(); + + const query = `tickets/${this.ticket.id}/transferSales`; + this.$http.post(query, params).then(res => { + this.goToTicket(res.data.id); + }); + } + + createClaim() { + const claim = { + ticketFk: this.ticket.id, + clientFk: this.ticket.clientFk, + ticketCreated: this.ticket.shipped + }; + const sales = this.checkedLines(); + + if (this.newInstances().length === 0) + this.$scope.watcher.updateOriginalData(); + + this.$http.post(`Claims/createFromSales`, {claim: claim, sales: sales}).then(res => { + this.$state.go('claim.card.basicData', {id: res.data.id}); + }); + } + + goToTicket(ticketId) { + this.$state.go('ticket.card.sale', {id: ticketId}); + } + + // Slesperson Mana + getManaSalespersonMana() { + this.$http.get(`Tickets/${this.$state.params.id}/getSalesPersonMana`).then(res => { + this.mana = res.data; + }); + } + + // Item Descriptor + showDescriptor(event, itemFk) { + this.quicklinks = { + btnThree: { + icon: 'icon-transaction', + state: `item.card.diary({ + id: ${itemFk}, + warehouseFk: ${this.ticket.warehouseFk}, + ticketFk: ${this.ticket.id} + })`, + tooltip: 'Item diary' + } + }; + this.$scope.descriptor.itemFk = itemFk; + this.$scope.descriptor.parent = event.target; + this.$scope.descriptor.show(); + } + + onDescriptorLoad() { + this.$scope.popover.relocate(); + } + + showEditPricePopover(event, sale) { + if (!this.isEditable) return; + this.sale = sale; + this.editedPrice = this.sale.price; + this.edit = { + ticketFk: this.ticket.id, + id: sale.id, + quantity: sale.quantity + }; + this.$scope.editPricePopover.parent = event.target; + this.$scope.editPricePopover.show(); + } + + updatePrice() { + if (this.editedPrice != this.sale.price) { + this.$http.post(`Sales/${this.edit.id}/updatePrice`, {newPrice: this.editedPrice}).then(res => { + this.sale.price = res.data.price; + + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }).finally(() => { + if (this.newInstances().length === 0) + this.$scope.watcher.updateOriginalData(); + }); + } + + this.$scope.editPricePopover.hide(); + } + + updateNewPrice() { + this.newPrice = this.sale.quantity * this.editedPrice - ((this.sale.discount * (this.sale.quantity * this.editedPrice)) / 100); + } + + showEditDiscountPopover(event, sale) { + if (!this.isEditable) return; + + this.sale = sale; + this.edit = [{ + ticketFk: this.ticket.id, + id: sale.id, + quantity: sale.quantity, + price: sale.price, + discount: sale.discount + }]; + this.$scope.editPopover.parent = event.target; + this.$scope.editPopover.show(); + } + + showEditDialog() { + this.edit = this.checkedLines(); + this.$scope.editDialog.show(); + } + + hideEditDialog() { + this.$scope.model.refresh(); + this.$scope.editDialog.hide(); + } + + hideEditPopover() { + this.$scope.model.refresh(); + this.$scope.editPopover.hide(); + } + + /* + * Unmark sale as reserved + */ + unmarkAsReserved() { + this.setReserved(false); + } + + /* + * Mark sale as reserved + */ + markAsReserved() { + this.setReserved(true); + } + + setReserved(reserved) { + let selectedSales = this.checkedLines(); + let params = {sales: selectedSales, ticketFk: this.ticket.id, reserved: reserved}; + + let reservedSales = new Map(); + this.$http.post(`Sales/reserve`, params).then(res => { + let isReserved = res.config.data.reserved; + + res.config.data.sales.forEach(sale => { + reservedSales.set(sale.id, {reserved: isReserved}); + }); + + this.sales.forEach(sale => { + const reservedSale = reservedSales.get(sale.id); + if (reservedSale) + sale.reserved = reservedSale.reserved; + }); + }).finally(() => { + if (this.newInstances().length === 0) + this.$scope.watcher.updateOriginalData(); + }); + } + + newOrderFromTicket() { + this.$http.post(`Orders/newFromTicket`, {ticketFk: this.ticket.id}).then(res => { + const path = this.$state.href('order.card.catalog', {id: res.data}); + window.open(path, '_blank'); + + this.vnApp.showSuccess(this.$translate.instant('Order created')); + }); + } + + showSMSDialog() { + const address = this.ticket.address; + const sales = this.checkedLines(); + const items = sales.map(sale => { + return `${sale.quantity} ${sale.concept}`; + }); + const notAvailables = items.join(', '); + const params = { + ticketFk: this.ticket.id, + created: this.ticket.created, + notAvailables + }; + this.newSMS = { + destinationFk: this.ticket.clientFk, + destination: address.mobile || null, + message: this.$translate.instant('SMSAvailability', params) + }; + this.$scope.sms.open(); + } + + /** + * Inserts a new instance + */ + add() { + this.$scope.model.insert({}); + } + + /* + * Creates a new sale if it's a new instance + * Updates the sale quantity for existing instance + */ + onChangeQuantity(sale) { + if (!sale.id) + this.addSale(sale); + else + this.updateQuantity(sale); + } + + /* + * Updates a sale quantity + */ + updateQuantity(sale) { + const data = {quantity: parseInt(sale.quantity)}; + const query = `Sales/${sale.id}/updateQuantity`; + this.$http.post(query, data).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }).catch(e => { + this.$scope.model.refresh(); + throw e; + }).finally(() => { + if (this.newInstances().length === 0) + this.$scope.watcher.updateOriginalData(); + }); + } + + /* + * Updates a sale concept + */ + updateConcept(sale) { + const data = {newConcept: sale.concept}; + const query = `Sales/${sale.id}/updateConcept`; + this.$http.post(query, data).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }).catch(e => { + this.$scope.model.refresh(); + throw e; + }).finally(() => { + if (this.newInstances().length === 0) + this.$scope.watcher.updateOriginalData(); + }); + } + + /* + * Adds a new sale + */ + addSale(sale) { + const data = { + itemId: sale.itemFk, + quantity: sale.quantity + }; + const query = `tickets/${this.ticket.id}/addSale`; + this.$http.post(query, data).then(res => { + if (!res.data) return; + + const newSale = res.data; + + sale.id = newSale.id; + sale.image = newSale.item.image; + sale.subName = newSale.item.subName; + sale.concept = newSale.concept; + sale.quantity = newSale.quantity; + sale.discount = newSale.discount; + sale.price = newSale.price; + sale.item = newSale.item; + + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }).finally(() => { + if (this.newInstances().length === 0) + this.$scope.watcher.updateOriginalData(); + }); + } + + isTicketEditable() { + this.$http.get(`Tickets/${this.$state.params.id}/isEditable`).then(res => { + this.isEditable = res.data; + }); + } + + hasOneSaleSelected() { + if (this.totalCheckedLines() === 1) + return true; + return false; + } + + calculateSalePrice() { + const sale = this.checkedLines()[0]; + const query = `Sales/${sale.id}/recalculatePrice`; + this.$http.post(query).then(res => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$scope.model.refresh(); + }); + } +} + +Controller.$inject = ['$scope', '$state', '$http', 'vnApp', '$translate']; + +ngModule.component('vnTicketSale', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<' + }, + require: { + card: '?^vnTicketCard' + } +}); diff --git a/modules/ticket/front/sale/locale/en.yml b/modules/ticket/front/sale/locale/en.yml new file mode 100644 index 000000000..469e2a04e --- /dev/null +++ b/modules/ticket/front/sale/locale/en.yml @@ -0,0 +1,3 @@ +SMSAvailability: >- + Verdnatura communicates: Your order {{ticketFk}} created on {{created | date: "dd/MM/yyyy"}}. + {{notAvailables}} not available. Sorry for the inconvenience. \ No newline at end of file diff --git a/modules/ticket/front/sale/locale/es.yml b/modules/ticket/front/sale/locale/es.yml new file mode 100644 index 000000000..3ccdd528e --- /dev/null +++ b/modules/ticket/front/sale/locale/es.yml @@ -0,0 +1,33 @@ +New price: Nuevo precio +Add item: Añadir artículo +Add turn: Añadir a turno +Delete ticket: Eliminar ticket +Mark as reserved: Marcar como reservado +Unmark as reserved: Desmarcar como reservado +Update discount: Actualizar descuento +There is no changes to save: No hay cambios que guardar +Edit discount: Editar descuento +Transfer to ticket: Transferir a ticket +New ticket: Nuevo ticket +Edit price: Editar precio +You are going to delete lines of the ticket: Vas a eliminar lineas del ticket +This ticket will be removed from current route! Continue anyway?: ¡Se eliminará el ticket de la ruta actual! ¿Continuar de todas formas? +You have to allow pop-ups in your web browser to use this functionality: + Debes permitir los pop-pups en tu navegador para que esta herramienta funcione correctamente +Disc: Dto +Available: Disponible +In which day you want to add the ticket?: ¿A que dia quieres añadir el ticket? +Add claim: Crear reclamación +Claim: Reclamación +Transfer lines: Transferir líneas +Sales to transfer: Líneas a transferir +Destination ticket: Ticket destinatario +Change ticket state to 'Ok': Cambiar estado del ticket a 'Ok' +Reserved: Reservado +SMSAvailability: >- + Verdnatura le comunica: Pedido {{ticketFk}} día {{created | date: "dd/MM/yyyy"}}. + {{notAvailables}} no disponible/s. Disculpe las molestias. +Continue anyway?: ¿Continuar de todas formas? +This ticket is now empty: El ticket ha quedado vacio +Do you want to delete it?: ¿Quieres eliminarlo? +Recalculate price: Recalcular precio \ No newline at end of file diff --git a/modules/ticket/front/sale/specs/editDiscount.spec.js b/modules/ticket/front/sale/specs/editDiscount.spec.js new file mode 100644 index 000000000..97fe4771d --- /dev/null +++ b/modules/ticket/front/sale/specs/editDiscount.spec.js @@ -0,0 +1,86 @@ +import '../editDiscount.js'; + +describe('Ticket', () => { + describe('Component vnTicketSaleEditDiscount', () => { + let controller; + let $httpBackend; + let $state; + let $scope; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_, $rootScope) => { + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + $scope.index = {model: {instances: [{id: 1}, {id: 2}]}, accept: () => { + return { + then: () => {} + }; + }}; + $state = _$state_; + $state.params.id = 11; + controller = $componentController('vnTicketSaleEditDiscount', {$scope, $state}); + controller._edit = [{id: 3}]; + controller.onHide = () => {}; + })); + + describe('edit() setter', () => { + it('should set _edit value and call setNewDiscount', () => { + spyOn(controller, 'setNewDiscount'); + controller.edit = {id: 1}; + + expect(controller.edit).toEqual({id: 1}); + expect(controller.setNewDiscount).toHaveBeenCalledWith(); + }); + }); + + describe('bulk() setter', () => { + it('should set _bulk value and call setNewDiscount', () => { + spyOn(controller, 'setNewDiscount'); + controller.bulk = true; + + expect(controller.bulk).toEqual(true); + expect(controller.setNewDiscount).toHaveBeenCalledWith(); + }); + }); + + describe('setNewDiscount()', () => { + it('should set NewDiscount to edit[0].discount value if it doesnt exists', () => { + controller.edit = [{discount: 1}]; + controller.setNewDiscount(); + + expect(controller.newDiscount).toEqual(1); + }); + }); + + describe('updateDiscount()', () => { + it('should make a query if the discount value has been modified or the bulk value is true', () => { + controller.bulk = true; + controller.newDiscount = 15; + + $httpBackend.expectPOST(`Tickets/11/updateDiscount`).respond(); + controller.updateDiscount(); + + $httpBackend.flush(); + }); + + it(`should throw if there's no changes on discount and it isn't bulk`, () => { + controller.bulk = false; + controller.newDiscount = 15; + controller.edit = [{discount: 15}]; + spyOn(controller.vnApp, 'showError'); + controller.updateDiscount(); + + expect(controller.vnApp.showError).toHaveBeenCalledWith('There are no changes to save'); + }); + }); + + describe('clearDiscount()', () => { + it('should set newDiscount to null', () => { + controller.clearDiscount(); + + expect(controller.newDiscount).toEqual(null); + }); + }); + }); +}); diff --git a/modules/ticket/front/sale/specs/index.spec.js b/modules/ticket/front/sale/specs/index.spec.js new file mode 100644 index 000000000..a23c6f204 --- /dev/null +++ b/modules/ticket/front/sale/specs/index.spec.js @@ -0,0 +1,362 @@ +import '../index.js'; +import watcher from 'core/mocks/watcher'; +import crudModel from 'core/mocks/crud-model'; + +describe('Ticket', () => { + describe('Component vnTicketSale', () => { + let controller; + let $scope; + let $state; + let $httpBackend; + + const ticket = { + id: 1, + clientFk: 101, + shipped: 1, + created: new Date(), + client: {salesPersonFk: 1}, + address: {mobile: 111111111} + }; + const sales = [ + { + id: 1, + concept: 'Item 1', + quantity: 5, + price: 23.5, + discount: 0, + }, { + id: 4, + concept: 'Item 2', + quantity: 20, + price: 5.5, + discount: 0, + } + ]; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$state_, _$httpBackend_) => { + $state = _$state_; + $scope = $rootScope.$new(); + $scope.watcher = watcher; + $scope.sms = {open: () => {}}; + $scope.ticket = ticket; + $scope.model = crudModel; + $httpBackend = _$httpBackend_; + Object.defineProperties($state.params, { + id: { + value: ticket.id, + writable: true + }, + go: { + value: () => {}, + writable: false + } + }); + controller = $componentController('vnTicketSale', {$scope, $state}); + controller.card = {reload: () => {}}; + controller.ticket = ticket; + controller.sales = sales; + })); + + describe('createClaim()', () => { + it('should perform a query and call windows open', () => { + spyOn(controller.$state, 'go'); + + const claim = {id: 1}; + const sales = [{id: 1}, {id: 2}]; + + $httpBackend.whenGET(`Tickets/1/getVAT`).respond(200, 10.5); + $httpBackend.whenGET(`Tickets/1/subtotal`).respond(200, 227.5); + $httpBackend.whenGET(`Tickets/1/isEditable`).respond(); + $httpBackend.when('POST', `Claims/createFromSales`, {claim: claim, sales: sales}).respond(claim); + $httpBackend.expect('POST', `Claims/createFromSales`).respond(claim); + controller.createClaim(); + $httpBackend.flush(); + + expect(controller.subtotal).toEqual(227.5); + expect(controller.VAT).toEqual(10.5); + expect(controller.total).toEqual(238); + expect(controller.$state.go).toHaveBeenCalledWith('claim.card.basicData', {id: 1}); + }); + }); + + describe('isChecked() getter', () => { + it('should set isChecked value to true when one of the instances has the value checked to true', () => { + controller.sales[0].checked = true; + + expect(controller.isChecked).toBeTruthy(); + }); + }); + + describe('checkedLines()', () => { + it('should make an array of the instances with the property checked true()', () => { + let sale = controller.sales[0]; + sale.checked = true; + let expectedResult = [sale]; + + $httpBackend.whenGET(`Tickets/1/subtotal`).respond(200, 227.5); + $httpBackend.whenGET(`Tickets/1/getVAT`).respond(200, 10.5); + $httpBackend.whenGET(`Tickets/1/isEditable`).respond(); + let result = controller.checkedLines(); + $httpBackend.flush(); + + expect(result).toEqual(expectedResult); + }); + }); + + describe('onStateOkClick()', () => { + it('should perform a get and then call a function', () => { + let filter = {where: {code: 'OK'}, fields: ['id']}; + filter = encodeURIComponent(JSON.stringify(filter)); + let res = [{id: 3}]; + spyOn(controller, 'onStateChange'); + + $httpBackend.whenGET(`States?filter=${filter}`).respond(res); + $httpBackend.expectGET(`Tickets/1/subtotal`).respond(200, 227.5); + $httpBackend.expectGET(`Tickets/1/getVAT`).respond(200, 10.5); + $httpBackend.whenGET(`Tickets/1/isEditable`).respond(); + controller.onStateOkClick(); + $httpBackend.flush(); + + expect(controller.onStateChange).toHaveBeenCalledWith(3); + }); + }); + + describe('onStateChange()', () => { + it('should perform a post and then call a function', () => { + $httpBackend.expectPOST(`TicketTrackings/changeState`).respond(); + $httpBackend.whenGET(`Tickets/1/subtotal`).respond(200, 227.5); + $httpBackend.whenGET(`Tickets/1/getVAT`).respond(200, 10.5); + $httpBackend.whenGET(`Tickets/1/isEditable`).respond(); + controller.onStateChange(3); + $httpBackend.flush(); + }); + }); + + describe('onRemoveLinesClick()', () => { + it('should call getCheckedLines, call removeInstances, and make a query', () => { + controller.sales[0].checked = true; + + $httpBackend.whenPOST(`Sales/removes`).respond(); + $httpBackend.whenGET(`Tickets/1/subtotal`).respond(200, 227.5); + $httpBackend.whenGET(`Tickets/1/getVAT`).respond(200, 10.5); + $httpBackend.whenGET(`Tickets/1/isEditable`).respond(); + controller.onRemoveLinesClick('accept'); + $httpBackend.flush(); + + expect(controller.sales.length).toEqual(1); + }); + }); + + describe('unmarkAsReserved()', () => { + it('should call setReserved with false', () => { + spyOn(controller, 'setReserved'); + + controller.unmarkAsReserved(false); + + expect(controller.setReserved).toHaveBeenCalledWith(false); + }); + }); + + describe('markAsReserved()', () => { + it('should call setReserved with true', () => { + spyOn(controller, 'setReserved'); + + controller.markAsReserved(true); + + expect(controller.setReserved).toHaveBeenCalledWith(true); + }); + }); + + describe('setReserved()', () => { + it('should call getCheckedLines, $.index.accept and make a query ', () => { + const sale = controller.sales[0]; + sale.checked = true; + let expectedRequest = { + sales: [sale], + ticketFk: ticket.id, + reserved: false + }; + + $httpBackend.expectPOST(`Sales/reserve`, expectedRequest).respond(); + $httpBackend.whenGET(`Tickets/1/subtotal`).respond(200, 227.5); + $httpBackend.whenGET(`Tickets/1/getVAT`).respond(200, 10.5); + $httpBackend.whenGET(`Tickets/1/isEditable`).respond(); + controller.unmarkAsReserved(false); + $httpBackend.flush(); + }); + }); + + describe('showSMSDialog()', () => { + it('should open an SMS dialog with specified data', () => { + spyOn(controller.$scope.sms, 'open'); + + controller.sales[0].checked = true; + controller.showSMSDialog(); + + expect(controller.$scope.sms.open).toHaveBeenCalledWith(); + expect(controller.newSMS.destination).toEqual(111111111); + expect(controller.newSMS.message).not.toEqual(''); + }); + }); + + describe('updateQuantity()', () => { + it('should make a POST query saving sale quantity', () => { + spyOn(controller.$scope.watcher, 'updateOriginalData'); + const data = {quantity: 10}; + const sale = sales[0]; + sale.quantity = 10; + + $httpBackend.when('POST', `Sales/4/updateQuantity`, data).respond(); + $httpBackend.expect('POST', `Sales/4/updateQuantity`, data).respond(); + $httpBackend.whenGET(`Tickets/1/subtotal`).respond(200, 227.5); + $httpBackend.whenGET(`Tickets/1/getVAT`).respond(200, 10.5); + $httpBackend.whenGET(`Tickets/1/isEditable`).respond(); + controller.updateQuantity(sale); + $httpBackend.flush(); + + expect(controller.$scope.watcher.updateOriginalData).toHaveBeenCalledWith(); + }); + }); + + describe('updateConcept()', () => { + it('should make a POST query saving sale concept', () => { + spyOn(controller.$scope.watcher, 'updateOriginalData'); + const data = {newConcept: 'My new weapon'}; + const sale = sales[0]; + sale.concept = 'My new weapon'; + + $httpBackend.when('POST', `Sales/4/updateConcept`, data).respond(); + $httpBackend.expect('POST', `Sales/4/updateConcept`, data).respond(); + $httpBackend.whenGET(`Tickets/1/subtotal`).respond(200, 227.5); + $httpBackend.whenGET(`Tickets/1/getVAT`).respond(200, 10.5); + $httpBackend.whenGET(`Tickets/1/isEditable`).respond(); + controller.updateConcept(sale); + $httpBackend.flush(); + + expect(controller.$scope.watcher.updateOriginalData).toHaveBeenCalledWith(); + }); + }); + + describe('addSale()', () => { + it('should make a POST query adding a new sale', () => { + spyOn(controller.$scope.watcher, 'updateOriginalData'); + const newSale = {itemFk: 4, quantity: 10}; + const params = {itemId: 4, quantity: 10}; + + const expectedResult = { + id: 30, + quantity: 10, + discount: 0, + price: 0, + itemFk: 4, + item: { + subName: 'Item subName', + image: '30.png' + } + }; + + $httpBackend.when('POST', `tickets/1/addSale`, params).respond(expectedResult); + $httpBackend.expect('POST', `tickets/1/addSale`, params).respond(expectedResult); + $httpBackend.whenGET(`Tickets/1/subtotal`).respond(200, 227.5); + $httpBackend.whenGET(`Tickets/1/getVAT`).respond(200, 10.5); + $httpBackend.whenGET(`Tickets/1/isEditable`).respond(); + controller.addSale(newSale); + $httpBackend.flush(); + + expect(controller.$scope.watcher.updateOriginalData).toHaveBeenCalledWith(); + }); + }); + + describe('transferSales()', () => { + it('should transfer sales to a ticket', () => { + spyOn(controller, 'goToTicket'); + controller.transfer = { + sales: [{id: 1, itemFk: 1}, {id: 2, itemFk: 4}] + }; + + const expectedResponse = {id: 13}; + const params = { + ticketId: 13, + sales: controller.transfer.sales + }; + + $httpBackend.when('POST', `tickets/1/transferSales`, params).respond(expectedResponse); + $httpBackend.expect('POST', `tickets/1/transferSales`, params).respond(expectedResponse); + $httpBackend.whenGET(`Tickets/1/subtotal`).respond(200, 227.5); + $httpBackend.whenGET(`Tickets/1/getVAT`).respond(200, 10.5); + $httpBackend.whenGET(`Tickets/1/isEditable`).respond(); + controller.transferSales(13); + $httpBackend.flush(); + + expect(controller.goToTicket).toHaveBeenCalledWith(13); + }); + }); + + describe('setTransferParams()', () => { + it('should define the transfer object on the controller and its default properties', () => { + let sale = controller.sales[0]; + sale.checked = true; + const expectedResponse = [sale]; + + $httpBackend.when('GET', `clients/101/lastActiveTickets?ticketId=1`).respond(expectedResponse); + $httpBackend.expect('GET', `clients/101/lastActiveTickets?ticketId=1`).respond(expectedResponse); + $httpBackend.whenGET(`Tickets/1/subtotal`).respond(200, 227.5); + $httpBackend.whenGET(`Tickets/1/getVAT`).respond(200, 10.5); + $httpBackend.whenGET(`Tickets/1/isEditable`).respond(); + controller.setTransferParams(); + $httpBackend.flush(); + + const lastActiveTickets = controller.transfer.lastActiveTickets; + + expect(controller.transfer).toBeDefined(); + expect(lastActiveTickets).toBeDefined(); + expect(lastActiveTickets[0].id).toEqual(4); + }); + }); + + describe('newOrderFromTicket()', () => { + it('should make an HTTP post query and then open the new order on a new tab', () => { + const params = {ticketFk: 1}; + const expectedResponse = {id: 123}; + + window.open = jasmine.createSpy('open'); + controller.$state.href = jasmine.createSpy('href') + .and.returnValue('/somePath'); + + $httpBackend.when('POST', `Orders/newFromTicket`, params).respond(expectedResponse); + $httpBackend.expect('POST', `Orders/newFromTicket`, params).respond(expectedResponse); + $httpBackend.whenGET(`Tickets/1/subtotal`).respond(200, 227.5); + $httpBackend.whenGET(`Tickets/1/getVAT`).respond(200, 10.5); + $httpBackend.whenGET(`Tickets/1/isEditable`).respond(); + controller.newOrderFromTicket(); + $httpBackend.flush(); + + expect(window.open).toHaveBeenCalledWith('/somePath', '_blank'); + }); + }); + + describe('hasOneSaleSelected()', () => { + it('should return true if just one sale is selected', () => { + controller.sales[0].checked = true; + + expect(controller.hasOneSaleSelected()).toBeTruthy(); + }); + }); + + describe('calculateSalePrice()', () => { + it('should make an HTTP post query ', () => { + controller.sales[0].checked = true; + + $httpBackend.when('POST', `Sales/4/recalculatePrice`).respond(200); + $httpBackend.whenGET(`Tickets/1/subtotal`).respond(200, 227.5); + $httpBackend.whenGET(`Tickets/1/getVAT`).respond(200, 10.5); + $httpBackend.whenGET(`Tickets/1/isEditable`).respond(); + + controller.calculateSalePrice(); + $httpBackend.flush(); + }); + }); + }); +}); diff --git a/modules/ticket/front/sale/style.scss b/modules/ticket/front/sale/style.scss new file mode 100644 index 000000000..1eb7556e9 --- /dev/null +++ b/modules/ticket/front/sale/style.scss @@ -0,0 +1,109 @@ +@import "variables"; + +vn-ticket-sale { + .header { + justify-content: space-between !important; + align-items: center; + } + vn-table { + img { + border-radius: 50%; + width: 50px; + height: 50px; + } + } + .taxes { + max-width: 10em; + border: $border-thin-light; + text-align: right; + padding: .5em !important; + + & > p { + font-size: 1.2em; + margin: .2em; + } + } + vn-dialog.edit { + @extend .edit-price; + + &>div{ + padding: 0!important; + } + .vn-textfield { + width: 100%; + } + .buttons{ + margin-top: 0!important; + } + p { + display: none; + } + button.close > vn-icon{ + color: white!important; + } + vn-ticket-sale-edit-discount > div { + padding-bottom: 0!important; + } + } + vn-dialog.ticket-create { + vn-button[label=Cancel] { + display: none; + } + vn-card.vn-ticket-create { + padding: 0!important; + } + } +} +.vn-popover .transfer { + .vn-textfield { + margin: 0 + } + vn-horizontal { + & > vn-one:nth-child(1) { + border-right: 1px solid $color-bg; + padding-right: 1em; + } + + & > vn-one:nth-child(2) { + margin-left: 1em + } + } + vn-table, table { + margin-bottom: 10px + } + vn-table { + overflow-x: hidden; + overflow-y: auto; + max-height: 25em; + width: 30em; + } + table { + width: 25em + } +} +.edit-price { + min-width: 200px; + + section.header { + background-color: $color-main; + color: $color-font-dark; + text-align: center; + + h5 { + color: inherit; + margin: 0 auto; + } + } + + p.simulatorTitle { + margin-bottom: 0px; + font-size: 12px; + color: $color-main; + } + vn-label-value { + padding-bottom: 20px; + } + div.simulator { + text-align: center; + } +} \ No newline at end of file diff --git a/modules/ticket/front/search-panel/index.html b/modules/ticket/front/search-panel/index.html new file mode 100644 index 000000000..27b8cbe99 --- /dev/null +++ b/modules/ticket/front/search-panel/index.html @@ -0,0 +1,117 @@ +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + {{firstName}} {{name}} + + + + + + + + + + + + + + + + + + + + + + + +
    +
    diff --git a/modules/ticket/front/search-panel/index.js b/modules/ticket/front/search-panel/index.js new file mode 100644 index 000000000..5c3c44107 --- /dev/null +++ b/modules/ticket/front/search-panel/index.js @@ -0,0 +1,7 @@ +import ngModule from '../module'; +import SearchPanel from 'core/components/searchbar/search-panel'; + +ngModule.component('vnTicketSearchPanel', { + template: require('./index.html'), + controller: SearchPanel +}); diff --git a/modules/ticket/front/search-panel/locale/es.yml b/modules/ticket/front/search-panel/locale/es.yml new file mode 100644 index 000000000..0fcfdaa58 --- /dev/null +++ b/modules/ticket/front/search-panel/locale/es.yml @@ -0,0 +1,13 @@ +Ticket id: Id ticket +Client id: Id cliente +Nickname: Alias +From: Desde +To: Hasta +Agency: Agencia +Warehouse: Almacén +Sales person: Comercial +Province: Provincia +My team: Mi equipo +Order id: Id pedido +Grouped States: Estado agrupado +Days onward: Días adelante \ No newline at end of file diff --git a/modules/ticket/front/services/index.html b/modules/ticket/front/services/index.html new file mode 100644 index 000000000..0cbcbe5df --- /dev/null +++ b/modules/ticket/front/services/index.html @@ -0,0 +1,102 @@ + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + +
    New service type
    + + + + + + + + +
    + + + + +
    \ No newline at end of file diff --git a/modules/ticket/front/services/index.js b/modules/ticket/front/services/index.js new file mode 100644 index 000000000..fca4cd070 --- /dev/null +++ b/modules/ticket/front/services/index.js @@ -0,0 +1,73 @@ +import ngModule from '../module'; +import UserError from 'core/lib/user-error'; + +class Controller { + constructor($http, $scope, $stateParams, vnApp, $translate, $element) { + this.$http = $http; + this.$scope = $scope; + this.$stateParams = $stateParams; + this.vnApp = vnApp; + this.$translate = $translate; + this.$element = $element; + this.services = []; + } + + $onInit() { + this.getDefaultTaxClass(); + } + + getDefaultTaxClass() { + let filter = { + where: {code: 'G'} + }; + this.$http.get('TaxClasses/findOne', {filter}) + .then(res => this.defaultTaxClass = res.data); + } + + add() { + if (this.defaultTaxClass) { + this.$scope.model.insert({ + taxClassFk: this.defaultTaxClass.id, + quantity: 1, + ticketFk: this.$stateParams.id + }); + } + } + + onNewServiceTypeOpen() { + this.newServiceType = {}; + } + + newServiceTypeDialog(elementIndex, event) { + event.preventDefault(); + this.$scope.createServiceTypeDialog.show(); + this.currentServiceIndex = elementIndex; + } + + onNewServiceTypeResponse(response) { + if (response == 'accept') { + if (!this.newServiceType.name) + throw new UserError(`Name can't be empty`); + + this.$http.post(`TicketServiceTypes`, this.newServiceType).then(response => { + this.services[this.currentServiceIndex].ticketServiceTypeFk = response.data.id; + }); + } + } + + onSubmit() { + this.$scope.watcher.check(); + + this.$scope.model.save().then(() => { + this.$scope.watcher.notifySaved(); + this.$scope.model.refresh(); + }); + } +} + +Controller.$inject = ['$http', '$scope', '$stateParams', 'vnApp', '$translate', '$element']; + +ngModule.component('vnTicketService', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/ticket/front/services/index.spec.js b/modules/ticket/front/services/index.spec.js new file mode 100644 index 000000000..30bcd821a --- /dev/null +++ b/modules/ticket/front/services/index.spec.js @@ -0,0 +1,64 @@ +import './index.js'; + +describe('Ticket component vnTicketService', () => { + let controller; + let $httpBackend; + let $httpParamSerializer; + let $scope; + let $element; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_, _$httpParamSerializer_, $rootScope) => { + $element = angular.element(`
    `); + $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; + $scope = $rootScope.$new(); + controller = $componentController('vnTicketService', {$scope, $element}); + })); + + describe('getDefaultTaxClass', () => { + it('should set the default tax class in the controller', () => { + $httpBackend.whenRoute('GET', `TaxClasses/findOne`) + .respond({ + id: 4000, + name: 'Whatever', + code: 'GG' + }); + controller.getDefaultTaxClass(); + $httpBackend.flush(); + + expect(controller.defaultTaxClass.code).toEqual('GG'); + }); + }); + + describe('onNewServiceTypeResponse', () => { + it(`should throw an error if the new service description is empty`, () => { + controller.newServiceType = {name: undefined}; + + let error; + try { + controller.onNewServiceTypeResponse('accept'); + } catch (e) { + error = e.message; + } + + expect(error).toBe(`Name can't be empty`); + }); + + it('should set the description of the selected service upon service type creation', () => { + controller.services = [ + {id: 1, description: 'not too great service'} + ]; + + controller.newServiceType = {name: 'totally new stuff'}; + controller.currentServiceIndex = 0; + + $httpBackend.when('POST', 'TicketServiceTypes').respond({id: 4001, name: 'totally new stuff'}); + controller.onNewServiceTypeResponse('accept'); + $httpBackend.flush(); + + expect(controller.services[0].ticketServiceTypeFk).toEqual(4001); + }); + }); +}); diff --git a/modules/ticket/front/services/locale/es.yml b/modules/ticket/front/services/locale/es.yml new file mode 100644 index 000000000..08788fc09 --- /dev/null +++ b/modules/ticket/front/services/locale/es.yml @@ -0,0 +1,5 @@ +Service: Servicios +Tax class: Tipo IVA +Add service: Añadir servicio +Remove service: Quitar servicio +New service type: Nuevo tipo de servicio \ No newline at end of file diff --git a/modules/ticket/front/summary/index.html b/modules/ticket/front/summary/index.html new file mode 100644 index 000000000..9ef27d093 --- /dev/null +++ b/modules/ticket/front/summary/index.html @@ -0,0 +1,216 @@ + +
    + + Ticket #{{$ctrl.summary.id}} - {{$ctrl.summary.client.name}} + ({{$ctrl.summary.client.id}}) - {{$ctrl.summary.nickname}} + + + +
    + + + + + + + + + + + + + + + + + + + + + + + {{$ctrl.summary.routeFk}} + + + + + + + + + + + + +

    Subtotal {{$ctrl.summary.subtotal | currency: 'EUR':2}}

    +

    VAT {{$ctrl.summary.vat | currency: 'EUR':2}}

    +

    Total {{$ctrl.summary.total | currency: 'EUR':2}}

    +
    + +

    Sale

    + + + + + Item + Quantity + Description + Price + Discount + Amount + + + + + + + + + + + + + + + + {{sale.itemFk | zeroFill:6}} + + + {{::sale.quantity}} + + + + + {{::sale.price | currency: 'EUR':2}} + {{::sale.discount}} % + {{::sale.quantity * sale.price * ((100 - sale.discount) / 100) | currency: 'EUR':2}} + + + +
    + +

    Packages

    + + + + Created + Package + Quantity + + + + + {{package.created | date: 'dd/MM/yyyy'}} + {{package.packaging.item.name}} + {{package.quantity}} + + + +
    + +

    Service

    + + + + + Id + Quantity + Description + Price + Tax class + + + + + + {{::service.id}} + {{::service.quantity}} + {{::service.description}} + {{::service.price}} + {{::service.taxClass.description}} + + + +
    + +

    Purchase request

    + + + + Description + Created + Requester + Atender + Quantity + Price + Item + Ok + + + + + {{::request.description}} + {{::request.created | date: 'dd/MM/yyyy'}} + {{::request.requester.user.name}} + {{::request.atender.user.name}} + {{::request.quantity}} + {{::request.price}} + + + {{request.sale.itemFk | zeroFill:6}} + + + + + + + + + + +
    +
    +
    + + diff --git a/modules/ticket/front/summary/index.js b/modules/ticket/front/summary/index.js new file mode 100644 index 000000000..5b5f9fb90 --- /dev/null +++ b/modules/ticket/front/summary/index.js @@ -0,0 +1,111 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $state, $http, vnApp, $translate) { + this.$scope = $scope; + this.vnApp = vnApp; + this.$translate = $translate; + this.$http = $http; + this.$state = $state; + } + + get ticket() { + return this._ticket; + } + + set ticket(value) { + this._ticket = value; + + if (value) this.getSummary(); + } + + get formattedAddress() { + if (!this.summary) return; + + let address = this.summary.address; + let province = address.province ? `(${address.province.name})` : ''; + + return `${address.street} - ${address.city} ${province}`; + } + + getSummary() { + this.$http.get(`Tickets/${this.ticket.id}/summary`).then(res => { + if (res && res.data) + this.summary = res.data; + }); + } + + showDescriptor(event, itemFk) { + this.quicklinks = { + btnThree: { + icon: 'icon-transaction', + state: `item.card.diary({ + id: ${itemFk}, + warehouseFk: ${this.ticket.warehouseFk}, + ticketFk: ${this.ticket.id} + })`, + tooltip: 'Item diary' + } + }; + this.$scope.descriptor.itemFk = itemFk; + this.$scope.descriptor.parent = event.target; + this.$scope.descriptor.show(); + } + + onDescriptorLoad() { + this.$scope.popover.relocate(); + } + + get isEditable() { + try { + return !this.ticket.state.state.alertLevel; + } catch (e) {} + + return true; + } + + setOkState() { + let params = {}; + + if (this.$state.params.id) + params = {ticketFk: this.$state.params.id}; + + if (!this.$state.params.id) + params = {ticketFk: this.ticket.id}; + + params.code = 'OK'; + + this.$http.post(`TicketTrackings/changeState`, params).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + if (this.card) + this.card.reload(); + else + this.getSummary(); + }); + } + + getRequestState(state) { + switch (state) { + case null: + return 'New'; + case false: + return 'Denied'; + case true: + return 'Acepted'; + } + } +} + +Controller.$inject = ['$scope', '$state', '$http', 'vnApp', '$translate']; + +ngModule.component('vnTicketSummary', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<' + }, + require: { + card: '?^vnTicketCard' + } +}); diff --git a/modules/ticket/front/summary/index.spec.js b/modules/ticket/front/summary/index.spec.js new file mode 100644 index 000000000..86b154b72 --- /dev/null +++ b/modules/ticket/front/summary/index.spec.js @@ -0,0 +1,45 @@ +import './index'; + +describe('Ticket', () => { + describe('Component vnTicketSummary', () => { + let controller; + let $httpBackend; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + controller = $componentController('vnTicketSummary'); + controller.ticket = {id: 1}; + })); + + describe('ticket()', () => { + it('should perform a GET query and define summary property', () => { + let res = {id: 1, nickname: 'Batman'}; + $httpBackend.when('GET', `Tickets/1/summary`).respond(200, res); + $httpBackend.expect('GET', `Tickets/1/summary`); + controller.ticket = {id: 1}; + $httpBackend.flush(); + + expect(controller.summary).toBeDefined(); + expect(controller.summary.nickname).toEqual('Batman'); + }); + }); + + describe('formattedAddress()', () => { + it('should return a full fromatted address with city and province', () => { + controller.summary = { + address: { + province: { + name: 'Gotham' + }, + street: '1007 Mountain Drive', + city: 'Gotham' + } + }; + + expect(controller.formattedAddress).toEqual('1007 Mountain Drive - Gotham (Gotham)'); + }); + }); + }); +}); diff --git a/modules/ticket/front/summary/style.scss b/modules/ticket/front/summary/style.scss new file mode 100644 index 000000000..4502c5dca --- /dev/null +++ b/modules/ticket/front/summary/style.scss @@ -0,0 +1,66 @@ +@import "./variables"; + +vn-ticket-summary .summary { + max-width: $width-lg; + + h5 { + display: flex; + justify-content: space-between; + align-items: center; + align-content: center; + + + span { + flex: 1; + } + + vn-button { + flex: none + } + } + + vn-button { + max-height: 27px; + button { + box-shadow: none; + height: inherit; + line-height: inherit; + &:active, &:focus { + box-shadow: none !important; + } + } + } + + & > vn-horizontal > vn-one { + min-width: 10em; + + &.taxes { + border: $border-thin-light; + text-align: right; + padding: .5em; + + & > p { + font-size: 1.2em; + margin: .2em; + } + } + + &.services { + .vn-table > vn-thead .identifier, + .vn-table > vn-tbody .identifier { + min-width: 3.5em + } + + .vn-table > vn-thead .tax-class, + .vn-table > vn-tbody .tax-class { + min-width: 11em; + width: 1px + } + + .vn-table > vn-tbody vn-td:first-child { + min-width: 24px; + + } + } + } +} \ No newline at end of file diff --git a/modules/ticket/front/tracking/edit/index.html b/modules/ticket/front/tracking/edit/index.html new file mode 100644 index 000000000..3a1b13e50 --- /dev/null +++ b/modules/ticket/front/tracking/edit/index.html @@ -0,0 +1,34 @@ + + + +
    + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/modules/ticket/front/tracking/edit/index.js b/modules/ticket/front/tracking/edit/index.js new file mode 100644 index 000000000..03c5c6c0f --- /dev/null +++ b/modules/ticket/front/tracking/edit/index.js @@ -0,0 +1,75 @@ +import ngModule from '../../module'; + +class Controller { + constructor($scope, $state, vnApp, $translate, $http) { + this.$http = $http; + this.$ = $scope; + this.$state = $state; + this.vnApp = vnApp; + this.$translate = $translate; + this.ticket = { + ticketFk: $state.params.id + }; + this.params = {ticketFk: $state.params.id}; + } + + $onInit() { + this.getPickerDesignedState(); + } + + set stateFk(value) { + this.params.stateFk = value; + this.isPickerDesignedState = this.getIsPickerDesignedState(value); + this.workerFk = window.localStorage.currentUserWorkerId; + } + + get stateFk() { + return this.params.stateFk; + } + + set workerFk(value) { + this.params.workerFk = value; + } + + get workerFk() { + return this.params.workerFk; + } + + getPickerDesignedState() { + let filter = { + where: { + code: 'PICKER_DESIGNED' + } + }; + let json = encodeURIComponent(JSON.stringify(filter)); + this.$http.get(`States?filter=${json}`).then(res => { + if (res && res.data) + this.pickerDesignedState = res.data[0].id; + }); + } + + getIsPickerDesignedState(value) { + if (value == this.pickerDesignedState) + return true; + + return false; + } + + onSubmit() { + this.$http.post(`TicketTrackings/changeState`, this.params).then(() => { + this.$.watcher.updateOriginalData(); + this.card.reload(); + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$state.go('ticket.card.tracking.index'); + }); + } +} +Controller.$inject = ['$scope', '$state', 'vnApp', '$translate', '$http']; + +ngModule.component('vnTicketTrackingEdit', { + template: require('./index.html'), + controller: Controller, + require: { + card: '^vnTicketCard' + } +}); diff --git a/modules/ticket/front/tracking/edit/index.spec.js b/modules/ticket/front/tracking/edit/index.spec.js new file mode 100644 index 000000000..979be07be --- /dev/null +++ b/modules/ticket/front/tracking/edit/index.spec.js @@ -0,0 +1,74 @@ +import './index'; + +describe('Ticket', () => { + describe('Component vnTicketTrackingEdit', () => { + let controller; + let $httpBackend; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_, $translate, vnApp) => { + $httpBackend = _$httpBackend_; + controller = $componentController('vnTicketTrackingEdit'); + controller.ticket = {id: 1}; + controller.$ = {watcher: {updateOriginalData: () => {}}}; + controller.card = {reload: () => {}}; + controller.vnApp = {showSuccess: () => {}}; + controller.$translate = $translate; + controller.vnApp = vnApp; + })); + + describe('stateFk setter/getter', () => { + it('should set params.stateFk and set isPickerDesignedState', () => { + let stateFk = {id: 1}; + controller.stateFk = stateFk; + + expect(controller.params.stateFk).toEqual(stateFk); + expect(controller.isPickerDesignedState).toEqual(false); + }); + }); + + describe('workerFk setter', () => { + it('should set params.workerFk', () => { + controller.workerFk = 1; + + expect(controller.params.workerFk).toEqual(1); + }); + }); + + describe('getPickerDesignedState()', () => { + it('should get the state that has the code PICKER_DESIGNED', () => { + let filter = { + where: { + code: 'PICKER_DESIGNED' + } + }; + let json = encodeURIComponent(JSON.stringify(filter)); + $httpBackend.expectGET(`States?filter=${json}`).respond([{id: 22}]); + controller.getPickerDesignedState(); + $httpBackend.flush(); + + expect(controller.pickerDesignedState).toEqual(22); + }); + }); + + describe('onSubmit()', () => { + it('should POST the data, call updateOriginalData, reload, showSuccess and go functions', () => { + controller.params = {stateFk: 22, workerFk: 101}; + spyOn(controller.card, 'reload'); + spyOn(controller.$.watcher, 'updateOriginalData'); + spyOn(controller.vnApp, 'showSuccess'); + spyOn(controller.$state, 'go'); + + $httpBackend.expectPOST(`TicketTrackings/changeState`, controller.params).respond({}); + controller.onSubmit(); + $httpBackend.flush(); + + expect(controller.card.reload).toHaveBeenCalledWith(); + expect(controller.$.watcher.updateOriginalData).toHaveBeenCalledWith(); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith(controller.$translate.instant('Data saved!')); + expect(controller.$state.go).toHaveBeenCalledWith('ticket.card.tracking.index'); + }); + }); + }); +}); diff --git a/modules/ticket/front/tracking/index/index.html b/modules/ticket/front/tracking/index/index.html new file mode 100644 index 000000000..8398a0602 --- /dev/null +++ b/modules/ticket/front/tracking/index/index.html @@ -0,0 +1,43 @@ + + + + + + + + State + Worker + Created + + + + + {{::tracking.state.name}} + + + {{::tracking.worker.user.nickname | dashIfEmpty}} + + + {{::tracking.created | date:'dd/MM/yyyy HH:mm'}} + + + + + + + + + + \ No newline at end of file diff --git a/modules/ticket/front/tracking/index/index.js b/modules/ticket/front/tracking/index/index.js new file mode 100644 index 000000000..adc1ac5a2 --- /dev/null +++ b/modules/ticket/front/tracking/index/index.js @@ -0,0 +1,45 @@ +import ngModule from '../../module'; + +class Controller { + constructor($scope, $stateParams) { + this.$ = $scope; + this.$stateParams = $stateParams; + this.filter = { + include: [ + { + relation: 'worker', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + } + } + }, + { + relation: 'state', + scope: { + fields: ['name'] + } + } + ] + }; + } + + showWorkerDescriptor(event, workerFk) { + event.preventDefault(); + event.stopImmediatePropagation(); + this.selectedWorker = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } +} + +Controller.$inject = ['$scope', '$stateParams']; + +ngModule.component('vnTicketTrackingIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/ticket/front/volume/index.html b/modules/ticket/front/volume/index.html new file mode 100644 index 000000000..0006b8854 --- /dev/null +++ b/modules/ticket/front/volume/index.html @@ -0,0 +1,64 @@ + + + + + + + + +
    + + + + +
    +
    + + + + + Item + Description + Quantity + m³ per quantity + + + + + + + {{sale.itemFk | zeroFill:6}} + + + + + + {{::sale.quantity}} + {{::sale.volume.m3 | number:3}} + + + + + +
    +
    + + + diff --git a/modules/ticket/front/volume/index.js b/modules/ticket/front/volume/index.js new file mode 100644 index 000000000..914c9819d --- /dev/null +++ b/modules/ticket/front/volume/index.js @@ -0,0 +1,79 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $http, $stateParams) { + this.$scope = $scope; + this.$http = $http; + this.$stateParams = $stateParams; + this.filter = { + include: [{ + relation: 'item' + }] + }; + + this.ticketVolumes = []; + } + + get sales() { + return this._sales; + } + + set sales(value) { + this._sales = value; + + if (value) this.applyVolumes(); + } + + get volumes() { + return this._volumes; + } + + set volumes(value) { + this._volumes = value; + + if (value) this.applyVolumes(); + } + + + applyVolumes() { + if (!this.sales || !this.volumes) return; + + this.sales.forEach(sale => { + this.volumes.forEach(volume => { + if (sale.id === volume.saleFk) + sale.volume = volume; + }); + }); + } + + showDescriptor(event, itemFk) { + this.quicklinks = { + btnThree: { + icon: 'icon-transaction', + state: `item.card.diary({ + id: ${itemFk}, + warehouseFk: ${this.ticket.warehouseFk}, + ticketFk: ${this.ticket.id} + })`, + tooltip: 'Item diary' + } + }; + this.$scope.descriptor.itemFk = itemFk; + this.$scope.descriptor.parent = event.target; + this.$scope.descriptor.show(); + } + + onDescriptorLoad() { + this.$scope.popover.relocate(); + } +} + +Controller.$inject = ['$scope', '$http', '$stateParams']; + +ngModule.component('vnTicketVolume', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<' + } +}); diff --git a/modules/ticket/front/volume/index.spec.js b/modules/ticket/front/volume/index.spec.js new file mode 100644 index 000000000..7f40c53d1 --- /dev/null +++ b/modules/ticket/front/volume/index.spec.js @@ -0,0 +1,80 @@ +import './index'; + +describe('ticket', () => { + describe('Component vnTicketVolume', () => { + let controller; + let $httpBackend; + let $state; + let $scope; + + beforeEach(ngModule('ticket')); + + beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_, $rootScope) => { + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + $scope.model = {data: [{id: 1}, {id: 2}], accept: () => { + return { + then: () => {} + }; + }}; + $state = _$state_; + $state.params.id = 101; + controller = $componentController('vnTicketVolume', {$scope, $httpBackend, $state}); + })); + + describe('sales() setter', () => { + it('should set sales property on controller an then call applyVolumes() method', () => { + spyOn(controller, 'applyVolumes'); + + controller.sales = [{id: 1}]; + + expect(controller.applyVolumes).toHaveBeenCalledWith(); + }); + }); + + describe('volumes() setter', () => { + it('should set volumes property on controller an then call applyVolumes() method', () => { + spyOn(controller, 'applyVolumes'); + + controller.volumes = [{id: 1}]; + + expect(controller.applyVolumes).toHaveBeenCalledWith(); + }); + }); + + describe('applyVolumes()', () => { + it(`should not apply volumes to the sales if sales property is not defined on controller`, () => { + controller.sales = [{id: 1, name: 'Sale one'}, {id: 2, name: 'Sale two'}]; + + expect(controller.sales[0].volume).toBeUndefined(); + expect(controller.sales[1].volume).toBeUndefined(); + }); + + it(`should not apply volumes to the sales if sales property is not defined on controller`, () => { + controller.volumes = [{saleFk: 1, m3: 0.012}, {saleFk: 2, m3: 0.015}]; + + expect(controller.sales).toBeUndefined(); + }); + + it(`should apply volumes to the sales if sales and volumes properties are defined on controller`, () => { + controller.sales = [{id: 1, name: 'Sale one'}, {id: 2, name: 'Sale two'}]; + controller.volumes = [{saleFk: 1, m3: 0.012}, {saleFk: 2, m3: 0.015}]; + + expect(controller.sales[0].volume.m3).toEqual(0.012); + expect(controller.sales[1].volume.m3).toEqual(0.015); + }); + }); + + /* it('should join the sale volumes to its respective sale', () => { + controller.ticket = {id: 1}; + let response = {volumes: [{saleFk: 1, m3: 0.008}, {saleFk: 2, m3: 0.003}]}; + $httpBackend.whenGET(`tickets/1/getVolume`).respond(response); + $httpBackend.expectGET(`tickets/1/getVolume`); + controller.onDataChange(); + $httpBackend.flush(); + + expect($scope.model.data[0].volume.m3).toBe(0.008); + expect($scope.model.data[1].volume.m3).toBe(0.003); + }); */ + }); +}); diff --git a/modules/ticket/front/weekly/index.html b/modules/ticket/front/weekly/index.html new file mode 100644 index 000000000..552179ced --- /dev/null +++ b/modules/ticket/front/weekly/index.html @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + Ticket ID + Client + Weekday + Warehouse + Salesperson + + + + + + + + {{weekly.ticketFk}} + + + + + {{::weekly.clientName}} + + + + + + + {{::weekly.warehouseName}} + + + {{::weekly.nickName}} + + + + + + + + + + + + + + + + + + + diff --git a/modules/ticket/front/weekly/index.js b/modules/ticket/front/weekly/index.js new file mode 100644 index 000000000..7668264f6 --- /dev/null +++ b/modules/ticket/front/weekly/index.js @@ -0,0 +1,94 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($scope, vnApp, $translate, $http) { + this.$ = $scope; + this.vnApp = vnApp; + this.$translate = $translate; + this.$http = $http; + + this.ticketSelected = null; + + this.weekdays = [ + {id: 0, name: 'Monday'}, + {id: 1, name: 'Tuesday'}, + {id: 2, name: 'Wednesday'}, + {id: 3, name: 'Thursday'}, + {id: 4, name: 'Friday'}, + {id: 5, name: 'Saturday'}, + {id: 6, name: 'Sunday'} + ]; + } + + onWeekdayUpdate(ticketFk, weekDay) { + const params = {ticketFk, weekDay}; + this.$http.patch('TicketWeeklies/', params).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }); + } + + deleteWeekly(index) { + this.ticketIndex = index; + this.$.deleteWeekly.show(); + event.stopImmediatePropagation(); + } + + onSearch(params) { + if (params) + this.$.model.applyFilter(null, params); + else + this.$.model.clear(); + } + + + showClientDescriptor(event, clientFk) { + this.$.clientDescriptor.clientFk = clientFk; + this.$.clientDescriptor.parent = event.target; + this.$.clientDescriptor.show(); + event.preventDefault(); + event.stopImmediatePropagation(); + } + + showTicketDescriptor(event, ticketFk) { + this.$.ticketDescriptor.ticketFk = ticketFk; + this.$.ticketDescriptor.parent = event.target; + this.$.ticketDescriptor.show(); + event.preventDefault(); + event.stopImmediatePropagation(); + } + + showWorkerDescriptor(event, workerFk) { + this.$.workerDescriptor.workerFk = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + event.preventDefault(); + event.stopImmediatePropagation(); + } + + onDescriptorLoad() { + this.$.popover.relocate(); + } + + preventNavigation(event) { + event.preventDefault(); + event.stopImmediatePropagation(); + } + + returnDialog(response) { + const ticket = this.$.model.data[this.ticketIndex]; + if (response === 'accept') { + this.$http.delete(`TicketWeeklies/${ticket.ticketFk}`).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$.model.remove(this.ticketIndex); + }); + } + } +} + + +Controller.$inject = ['$scope', 'vnApp', '$translate', '$http']; + +ngModule.component('vnTicketWeeklyIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/ticket/front/weekly/locale/es.yml b/modules/ticket/front/weekly/locale/es.yml new file mode 100644 index 000000000..fa40fe96b --- /dev/null +++ b/modules/ticket/front/weekly/locale/es.yml @@ -0,0 +1,5 @@ +Ticket ID: ID Ticket +Weekly tickets: Tickets programados +You are going to delete this weekly ticket: Vas a eliminar este ticket programado +This ticket will be removed from weekly tickets! Continue anyway?: Este ticket se eliminará de tickets programados! ¿Continuar de todas formas? +Search weekly ticket by id or client id: Busca tickets programados por el identificador o el identificador del cliente \ No newline at end of file diff --git a/modules/travel/back/methods/travel/getEntries.js b/modules/travel/back/methods/travel/getEntries.js new file mode 100644 index 000000000..ae7c7a53b --- /dev/null +++ b/modules/travel/back/methods/travel/getEntries.js @@ -0,0 +1,57 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +module.exports = Self => { + Self.remoteMethod('getEntries', { + description: 'Return the entries of a travel', + accessType: 'READ', + accepts: { + arg: 'id', + type: 'number', + required: true, + description: 'The travel id', + http: {source: 'path'} + }, + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/getEntries`, + verb: 'GET' + } + }); + + Self.getEntries = async id => { + let stmt; + + stmt = new ParameterizedSQL(` + SELECT e.travelFk, e.id, e.isConfirmed, e.ref, e.notes, e.evaNotes AS observation, + s.name AS supplierName, + CAST((SUM(IF(p.volume > 0,p.volume,p.width * p.depth * IF(p.height, p.height, i.size + pconfig.upperGap)) + * b.stickers)/1000000)/((pcc.width*pcc.depth*pcc.height)/1000000) AS DECIMAL(10,2)) cc, + CAST((SUM(IF(p.volume > 0,p.volume,p.width * p.depth * IF(p.height, p.height, i.size + pconfig.upperGap)) + * b.stickers)/1000000)/((ppallet.width*ppallet.depth*ppallet.height)/1000000) AS DECIMAL(10,2)) pallet, + CAST((SUM(IF(p.volume > 0,p.volume,p.width * p.depth * IF(p.height, p.height, i.size + pconfig.upperGap)) + * b.stickers)/1000000) AS DECIMAL(10,2)) m3, + TRUNCATE(SUM(b.stickers)/(COUNT( b.id) / COUNT( DISTINCT b.id)),0) hb, + CAST(SUM(b.freightValue*b.quantity) AS DECIMAL(10,2)) freightValue, + CAST(SUM(b.packageValue*b.quantity) AS DECIMAL(10,2)) packageValue + FROM vn.travel t + LEFT JOIN vn.entry e ON t.id = e.travelFk + LEFT JOIN vn.buy b ON b.entryFk = e.id + LEFT JOIN vn.supplier s ON e.supplierFk = s.id + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN vn.packaging p ON p.id = b.packageFk + JOIN vn.packaging pcc ON pcc.id = 'cc' + JOIN vn.packaging ppallet ON ppallet.id = 'pallet 100' + JOIN vn.packagingConfig pconfig + WHERE t.id = ? + GROUP BY e.id;`, [ + id + ]); + + let result = await Self.rawStmt(stmt); + + return result; + }; +}; diff --git a/modules/travel/back/methods/travel/getTravel.js b/modules/travel/back/methods/travel/getTravel.js new file mode 100644 index 000000000..171b64db1 --- /dev/null +++ b/modules/travel/back/methods/travel/getTravel.js @@ -0,0 +1,50 @@ +module.exports = Self => { + Self.remoteMethod('getTravel', { + description: 'Returns the travel', + accessType: 'READ', + accepts: { + arg: 'id', + type: 'number', + required: true, + description: 'The travel id', + http: {source: 'path'} + }, + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/getTravel`, + verb: 'GET' + } + }); + + Self.getTravel = async id => { + let filter = { + where: {id: id}, + include: [ + { + relation: 'agency', + scope: { + fields: ['id', 'name'] + } + }, + { + relation: 'warehouseIn', + scope: { + fields: ['id', 'name'] + } + }, + { + relation: 'warehouseOut', + scope: { + fields: ['id', 'name'] + } + } + ], + }; + + let travel = await Self.app.models.Travel.findOne(filter); + return travel; + }; +}; diff --git a/modules/travel/back/methods/travel/specs/getEntries.spec.js b/modules/travel/back/methods/travel/specs/getEntries.spec.js new file mode 100644 index 000000000..9b5c4fe49 --- /dev/null +++ b/modules/travel/back/methods/travel/specs/getEntries.spec.js @@ -0,0 +1,29 @@ +const app = require('vn-loopback/server/server'); + +describe('travel getEntries()', () => { + const travelId = 1; + it('should check the response contains the id', async() => { + const entries = await app.models.Travel.getEntries(travelId); + + expect(entries.length).toEqual(1); + expect(entries[0].id).toEqual(1); + }); + + it('should check the response contains the travelFk', async() => { + const entries = await app.models.Travel.getEntries(travelId); + + expect(entries[0].travelFk).toEqual(1); + }); + + it('should check the response contains the ref', async() => { + const entries = await app.models.Travel.getEntries(travelId); + + expect(entries[0].ref).toEqual('Movement 1'); + }); + + it('should check the response contains the m3', async() => { + const entries = await app.models.Travel.getEntries(travelId); + + expect(entries[0].m3).toEqual(0.22); + }); +}); diff --git a/modules/travel/back/methods/travel/specs/getTravel.spec.js b/modules/travel/back/methods/travel/specs/getTravel.spec.js new file mode 100644 index 000000000..7820077f5 --- /dev/null +++ b/modules/travel/back/methods/travel/specs/getTravel.spec.js @@ -0,0 +1,30 @@ +const app = require('vn-loopback/server/server'); + +describe('travel getTravel()', () => { + const travelId = 1; + it('should check travel contains the id', async() => { + const travel = await app.models.Travel.getTravel(travelId); + + expect(travel.id).toEqual(1); + }); + + it('should check travel contains the agency', async() => { + const travel = await app.models.Travel.getTravel(travelId); + const agencyName = travel.agency().name; + + expect(agencyName).toEqual('inhouse pickup'); + }); + + it('should check travel contains the receiver warehouse name', async() => { + const travel = await app.models.Travel.getTravel(travelId); + const receiverWarehouseName = travel.warehouseIn().name; + + expect(receiverWarehouseName).toEqual('Warehouse One'); + }); + + it('should check travel contains the totalEntries', async() => { + const travel = await app.models.Travel.getTravel(travelId); + + expect(travel.totalEntries).toEqual(1); + }); +}); diff --git a/modules/travel/back/model-config.json b/modules/travel/back/model-config.json new file mode 100644 index 000000000..ceea6bceb --- /dev/null +++ b/modules/travel/back/model-config.json @@ -0,0 +1,11 @@ +{ + "Travel": { + "dataSource": "vn" + },"Entry": { + "dataSource": "vn" + },"TravelLog": { + "dataSource": "vn" + },"Currency": { + "dataSource": "vn" + } +} diff --git a/modules/travel/back/models/currency.json b/modules/travel/back/models/currency.json new file mode 100644 index 000000000..036da89f1 --- /dev/null +++ b/modules/travel/back/models/currency.json @@ -0,0 +1,25 @@ +{ + "name": "Currency", + "base": "VnModel", + "options": { + "mysql": { + "table": "currency" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "code": { + "type": "String" + }, + "name": { + "type": "String" + }, + "ratio": { + "type": "Number" + } + } +} diff --git a/modules/travel/back/models/entry.json b/modules/travel/back/models/entry.json new file mode 100644 index 000000000..a2eef4cd2 --- /dev/null +++ b/modules/travel/back/models/entry.json @@ -0,0 +1,80 @@ +{ + "name": "Entry", + "base": "VnModel", + "options": { + "mysql": { + "table": "entry" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "dated": { + "type": "date" + }, + "ref": { + "type": "String" + }, + "isBooked": { + "type": "Boolean" + }, + "isInventory": { + "type": "Boolean" + }, + "notes": { + "type": "Number" + }, + "isConfirmed": { + "type": "Boolean" + }, + "isVirtual": { + "type": "Boolean", + "mysql": { + "columnName": "isRaid" + } + }, + "commission": { + "type": "Number" + }, + "created": { + "type": "date" + }, + "observation": { + "type": "String", + "mysql": { + "columnName": "evaNotes" + } + }, + "isBlocked": { + "type": "Boolean" + }, + "loadPriority": { + "type": "Number" + } + }, + "relations": { + "supplier": { + "type": "belongsTo", + "model": "Supplier", + "foreignKey": "supplierFk" + }, + "travel": { + "type": "belongsTo", + "model": "Travel", + "foreignKey": "travelFk" + }, + "company": { + "type": "belongsTo", + "model": "Company", + "foreignKey": "companyFk" + }, + "currency": { + "type": "belongsTo", + "model": "Currency", + "foreignKey": "currencyFk" + } + } +} diff --git a/modules/travel/back/models/travel-log.json b/modules/travel/back/models/travel-log.json new file mode 100644 index 000000000..d21821127 --- /dev/null +++ b/modules/travel/back/models/travel-log.json @@ -0,0 +1,58 @@ +{ + "name": "TravelLog", + "base": "VnModel", + "options": { + "mysql": { + "table": "travelLog" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number", + "forceId": false + }, + "originFk": { + "type": "Number", + "required": true + }, + "userFk": { + "type": "Number" + }, + "action": { + "type": "String", + "required": true + }, + "changedModel": { + "type": "String" + }, + "oldInstance": { + "type": "Object" + }, + "newInstance": { + "type": "Object" + }, + "creationDate": { + "type": "Date" + }, + "changedModelId": { + "type": "Number" + }, + "changedModelValue": { + "type": "String" + }, + "description": { + "type": "String" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + } + }, + "scope": { + "order": ["creationDate DESC", "id DESC"] + } +} diff --git a/modules/travel/back/models/travel.js b/modules/travel/back/models/travel.js new file mode 100644 index 000000000..936b68cd9 --- /dev/null +++ b/modules/travel/back/models/travel.js @@ -0,0 +1,4 @@ +module.exports = Self => { + require('../methods/travel/getTravel')(Self); + require('../methods/travel/getEntries')(Self); +}; diff --git a/modules/travel/back/models/travel.json b/modules/travel/back/models/travel.json new file mode 100644 index 000000000..b4f154525 --- /dev/null +++ b/modules/travel/back/models/travel.json @@ -0,0 +1,63 @@ +{ + "name": "Travel", + "base": "Loggable", + "log": { + "model":"TravelLog" + }, + "options": { + "mysql": { + "table": "travel" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "shipped": { + "type": "date" + }, + "landed": { + "type": "date" + }, + "isDelivered": { + "type": "Boolean" + }, + "isReceived": { + "type": "Boolean" + }, + "ref": { + "type": "String" + }, + "totalEntries": { + "type": "Number" + }, + "m3": { + "type": "Number" + }, + "agencyModeFk": { + "type": "Number", + "mysql": { + "columnName": "agencyFk" + } + } + }, + "relations": { + "agency": { + "type": "belongsTo", + "model": "AgencyMode", + "foreignKey": "agencyFk" + }, + "warehouseIn": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseInFk" + }, + "warehouseOut": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseOutFk" + } + } +} diff --git a/modules/travel/front/basic-data/index.html b/modules/travel/front/basic-data/index.html new file mode 100644 index 000000000..85a5fad2b --- /dev/null +++ b/modules/travel/front/basic-data/index.html @@ -0,0 +1,72 @@ + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/modules/travel/front/basic-data/index.js b/modules/travel/front/basic-data/index.js new file mode 100644 index 000000000..7406598b0 --- /dev/null +++ b/modules/travel/front/basic-data/index.js @@ -0,0 +1,25 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope) { + this.$ = $scope; + } + + onSubmit() { + return this.$.watcher.submit().then(() => { + this.card.reload(); + }); + } +} +Controller.$inject = ['$scope']; + +ngModule.component('vnTravelBasicData', { + template: require('./index.html'), + controller: Controller, + bindings: { + travel: '<' + }, + require: { + card: '^vnTravelCard' + } +}); diff --git a/modules/travel/front/basic-data/index.spec.js b/modules/travel/front/basic-data/index.spec.js new file mode 100644 index 000000000..ed5c287b1 --- /dev/null +++ b/modules/travel/front/basic-data/index.spec.js @@ -0,0 +1,28 @@ +import './index.js'; + +describe('Travel Component vnTravelBasicData', () => { + let controller; + let $scope; + beforeEach(angular.mock.module('travel', $translateProvider => { + $translateProvider.translations('en', {}); + })); + + beforeEach(angular.mock.inject(($componentController, $rootScope) => { + $scope = $rootScope.$new(); + controller = $componentController('vnTravelBasicData', $scope); + controller.card = {reload: () => {}}; + controller.$.watcher = {submit: () => {}}; + })); + + describe('onSubmit()', () => { + it('should call the card reload method after the watcher submits', done => { + spyOn(controller.card, 'reload'); + spyOn(controller.$.watcher, 'submit').and.returnValue(Promise.resolve()); + + controller.onSubmit().then(() => { + expect(controller.card.reload).toHaveBeenCalledWith(); + done(); + }).catch(done.fail); + }); + }); +}); diff --git a/modules/travel/front/basic-data/locale/es.yml b/modules/travel/front/basic-data/locale/es.yml new file mode 100644 index 000000000..d95675612 --- /dev/null +++ b/modules/travel/front/basic-data/locale/es.yml @@ -0,0 +1 @@ +Undo changes: Deshacer cambios diff --git a/modules/travel/front/card/index.html b/modules/travel/front/card/index.html new file mode 100644 index 000000000..91964be21 --- /dev/null +++ b/modules/travel/front/card/index.html @@ -0,0 +1,5 @@ + + + + + diff --git a/modules/travel/front/card/index.js b/modules/travel/front/card/index.js new file mode 100644 index 000000000..c3ad41702 --- /dev/null +++ b/modules/travel/front/card/index.js @@ -0,0 +1,31 @@ +import ngModule from '../module'; +import ModuleCard from 'salix/components/module-card'; + +class Controller extends ModuleCard { + reload() { + let filter = { + include: [ + { + relation: 'warehouseIn', + scope: { + fields: ['id', 'name'] + } + }, { + relation: 'warehouseOut', + scope: { + fields: ['id', 'name'] + } + } + ] + }; + + this.$http.get(`Travels/${this.$params.id}`, {filter}) + .then(response => this.travel = response.data); + } +} + +ngModule.component('vnTravelCard', { + template: require('./index.html'), + controller: Controller +}); + diff --git a/modules/travel/front/create/index.html b/modules/travel/front/create/index.html new file mode 100644 index 000000000..586689ff7 --- /dev/null +++ b/modules/travel/front/create/index.html @@ -0,0 +1,60 @@ + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/modules/travel/front/create/index.js b/modules/travel/front/create/index.js new file mode 100644 index 000000000..02be34ca7 --- /dev/null +++ b/modules/travel/front/create/index.js @@ -0,0 +1,15 @@ +import ngModule from '../module'; +import Section from 'salix/components/section'; + +class Controller extends Section { + onSubmit() { + return this.$.watcher.submit().then( + res => this.$state.go('travel.card.summary', {id: res.data.id}) + ); + } +} + +ngModule.component('vnTravelCreate', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/travel/front/create/index.spec.js b/modules/travel/front/create/index.spec.js new file mode 100644 index 000000000..88152120e --- /dev/null +++ b/modules/travel/front/create/index.spec.js @@ -0,0 +1,30 @@ +import './index'; +import watcher from 'core/mocks/watcher'; + +describe('Travel Component vnTravelCreate', () => { + let $element; + let $scope; + let $state; + let controller; + + beforeEach(ngModule('travel')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$state_) => { + $scope = $rootScope.$new(); + $state = _$state_; + $scope.watcher = watcher; + $element = angular.element('
    '); + controller = $componentController('vnTravelCreate', {$element, $scope}); + })); + + describe('onSubmit()', () => { + it(`should call submit() on the watcher then expect a callback`, () => { + spyOn($state, 'go'); + + controller.onSubmit(); + + expect(controller.$state.go).toHaveBeenCalledWith('travel.card.summary', {id: 1234}); + }); + }); +}); + diff --git a/modules/travel/front/descriptor/index.html b/modules/travel/front/descriptor/index.html new file mode 100644 index 000000000..3b932ef53 --- /dev/null +++ b/modules/travel/front/descriptor/index.html @@ -0,0 +1,36 @@ +
    +
    + + + + + + + +
    +
    +
    + + + + + + + + + + + + + + +
    +
    +
    diff --git a/modules/travel/front/descriptor/index.js b/modules/travel/front/descriptor/index.js new file mode 100644 index 000000000..187a7ed8f --- /dev/null +++ b/modules/travel/front/descriptor/index.js @@ -0,0 +1,20 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope) { + this.$ = $scope; + } +} + +Controller.$inject = ['$scope']; + +ngModule.component('vnTravelDescriptor', { + template: require('./index.html'), + bindings: { + travel: '<' + }, + require: { + card: '^?vnTravelCard' + }, + controller: Controller +}); diff --git a/modules/travel/front/descriptor/locale/es.yml b/modules/travel/front/descriptor/locale/es.yml new file mode 100644 index 000000000..1f51a0132 --- /dev/null +++ b/modules/travel/front/descriptor/locale/es.yml @@ -0,0 +1,6 @@ +Reference: Referencia +Wh. In: Warehouse entrada +Wh. Out: Warehouse salida +Shipped: F. envío +Landed: F. entrega +Total entries: Entradas totales \ No newline at end of file diff --git a/modules/travel/front/index.js b/modules/travel/front/index.js new file mode 100644 index 000000000..02bbb997b --- /dev/null +++ b/modules/travel/front/index.js @@ -0,0 +1,11 @@ +export * from './module'; + +import './main'; +import './index/'; +import './search-panel'; +import './descriptor'; +import './card'; +import './summary'; +import './basic-data'; +import './log'; +import './create'; diff --git a/modules/travel/front/index/index.html b/modules/travel/front/index/index.html new file mode 100644 index 000000000..044f1ca8f --- /dev/null +++ b/modules/travel/front/index/index.html @@ -0,0 +1,68 @@ + + + + + + + + + + Id + Reference + Agency + Warehouse Out + Shipped + Delivered + Warehouse In + Landed + Received + + + + + + {{::travel.id}} + {{::travel.ref}} + {{::travel.agency.name}} + {{::travel.warehouseOut.name}} + {{::travel.shipped | date:'dd/MM/yyyy'}} + + {{::travel.warehouseIn.name}} + {{::travel.landed | date:'dd/MM/yyyy'}} + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/travel/front/index/index.js b/modules/travel/front/index/index.js new file mode 100644 index 000000000..a4dd60d77 --- /dev/null +++ b/modules/travel/front/index/index.js @@ -0,0 +1,60 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($scope) { + this.$ = $scope; + this.ticketSelected = null; + + this.filter = { + include: [ + { + relation: 'agency', + scope: {fields: ['name']} + }, { + relation: 'warehouseIn', + scope: {fields: ['name']} + }, { + relation: 'warehouseOut', + scope: {fields: ['name']} + } + ] + }; + } + + exprBuilder(param, value) { + switch (param) { + case 'search': + return {id: value}; + case 'ref': + return {[param]: {regexp: value}}; + case 'shippedFrom': + return {shipped: {gte: value}}; + case 'shippedTo': + return {shipped: {lte: value}}; + case 'landedFrom': + return {landed: {gte: value}}; + case 'landedTo': + return {landed: {lte: value}}; + case 'id': + case 'agencyModeFk': + case 'warehouseOutFk': + case 'warehouseInFk': + case 'totalEntries': + return {[param]: value}; + } + } + + preview(event, travel) { + this.travelSelected = travel; + this.$.summary.show(); + event.preventDefault(); + event.stopImmediatePropagation(); + } +} + +Controller.$inject = ['$scope']; + +ngModule.component('vnTravelIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/travel/front/index/index.spec.js b/modules/travel/front/index/index.spec.js new file mode 100644 index 000000000..321109003 --- /dev/null +++ b/modules/travel/front/index/index.spec.js @@ -0,0 +1,33 @@ +import './index.js'; + +describe('Travel Component vnTravelIndex', () => { + let $componentController; + let controller; + + beforeEach(angular.mock.module('travel', $translateProvider => { + $translateProvider.translations('en', {}); + })); + + beforeEach(angular.mock.inject(_$componentController_ => { + $componentController = _$componentController_; + controller = $componentController('vnTravelIndex'); + })); + + describe('exprBuilder()', () => { + it('should return a formated object with the travel id in case of search', () => { + let param = 'search'; + let value = 2; + let result = controller.exprBuilder(param, value); + + expect(result).toEqual({id: 2}); + }); + + it('should return a formated object with the warehouseInFk in case of warehouseInFk', () => { + let param = 'warehouseInFk'; + let value = 3; + let result = controller.exprBuilder(param, value); + + expect(result).toEqual({warehouseInFk: 3}); + }); + }); +}); diff --git a/modules/travel/front/locale/es.yml b/modules/travel/front/locale/es.yml new file mode 100644 index 000000000..0986729f8 --- /dev/null +++ b/modules/travel/front/locale/es.yml @@ -0,0 +1,18 @@ +#Ordenar alfabeticamente +Reference: Referencia +Warehouse Out: Almacén salida +Warehouse In: Almacén llegada +Shipped from: Salida desde +Shipped to: Salida hasta +Landed from: Llegada desde +Landed to: Llegada hasta +Shipped: F. salida +Landed: F. llegada +Delivered: Enviado +Received: Recibido +Travel id: Id envío +Search travels by id: Buscar envíos por identificador +New travel: Nuevo envío +# Sections +Travels: Envíos +Log: Historial \ No newline at end of file diff --git a/modules/travel/front/log/index.html b/modules/travel/front/log/index.html new file mode 100644 index 000000000..8b442f671 --- /dev/null +++ b/modules/travel/front/log/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/modules/travel/front/log/index.js b/modules/travel/front/log/index.js new file mode 100644 index 000000000..a9a07aaf6 --- /dev/null +++ b/modules/travel/front/log/index.js @@ -0,0 +1,15 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $stateParams) { + this.$scope = $scope; + this.$stateParams = $stateParams; + } +} + +Controller.$inject = ['$scope', '$stateParams']; + +ngModule.component('vnTravelLog', { + template: require('./index.html'), + controller: Controller, +}); diff --git a/modules/travel/front/main/index.html b/modules/travel/front/main/index.html new file mode 100644 index 000000000..71b9462fe --- /dev/null +++ b/modules/travel/front/main/index.html @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/modules/travel/front/main/index.js b/modules/travel/front/main/index.js new file mode 100644 index 000000000..3be713973 --- /dev/null +++ b/modules/travel/front/main/index.js @@ -0,0 +1,9 @@ +import ngModule from '../module'; +import ModuleMain from 'salix/components/module-main'; + +export default class Travel extends ModuleMain {} + +ngModule.vnComponent('vnTravel', { + controller: Travel, + template: require('./index.html') +}); diff --git a/modules/travel/front/module.js b/modules/travel/front/module.js new file mode 100644 index 000000000..f6c04ba29 --- /dev/null +++ b/modules/travel/front/module.js @@ -0,0 +1,3 @@ +import {ng} from 'core/vendor'; + +export default ng.module('travel', ['vnCore']); diff --git a/modules/travel/front/routes.json b/modules/travel/front/routes.json new file mode 100644 index 000000000..d9b520816 --- /dev/null +++ b/modules/travel/front/routes.json @@ -0,0 +1,62 @@ +{ + "module": "travel", + "name": "Travels", + "icon": "local_airport", + "validations": true, + "dependencies": ["worker"], + "menus": { + "main": [ + {"state": "travel.index", "icon": "local_airport"} + ], + "card": [ + {"state": "travel.card.basicData", "icon": "settings"}, + {"state": "travel.card.log", "icon": "history"} + ] + }, + "routes": [ + { + "url": "/travel", + "state": "travel", + "abstract": true, + "component": "vn-travel", + "description": "Travels" + }, { + "url": "/index?q", + "state": "travel.index", + "component": "vn-travel-index", + "description": "Travels" + }, { + "url": "/:id", + "state": "travel.card", + "abstract": true, + "component": "vn-travel-card" + }, { + "url": "/summary", + "state": "travel.card.summary", + "component": "vn-travel-summary", + "description": "Summary", + "params": { + "travel": "$ctrl.travel" + } + }, { + "url": "/basic-data", + "state": "travel.card.basicData", + "component": "vn-travel-basic-data", + "description": "Basic data", + "acl": ["buyer","logistic"], + "params": { + "travel": "$ctrl.travel" + } + }, { + "url" : "/log", + "state": "travel.card.log", + "component": "vn-travel-log", + "description": "Log" + }, { + "url": "/create", + "state": "travel.create", + "component": "vn-travel-create", + "description": "New travel" + } + ] +} \ No newline at end of file diff --git a/modules/travel/front/search-panel/index.html b/modules/travel/front/search-panel/index.html new file mode 100644 index 000000000..bd68fd151 --- /dev/null +++ b/modules/travel/front/search-panel/index.html @@ -0,0 +1,82 @@ +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    \ No newline at end of file diff --git a/modules/travel/front/search-panel/index.js b/modules/travel/front/search-panel/index.js new file mode 100644 index 000000000..d7b2a6eff --- /dev/null +++ b/modules/travel/front/search-panel/index.js @@ -0,0 +1,7 @@ +import ngModule from '../module'; +import SearchPanel from 'core/components/searchbar/search-panel'; + +ngModule.component('vnTravelSearchPanel', { + template: require('./index.html'), + controller: SearchPanel +}); diff --git a/modules/travel/front/search-panel/locale/es.yml b/modules/travel/front/search-panel/locale/es.yml new file mode 100644 index 000000000..1f892a742 --- /dev/null +++ b/modules/travel/front/search-panel/locale/es.yml @@ -0,0 +1,7 @@ +Ticket id: Id ticket +Client id: Id cliente +Nickname: Alias +From: Desde +To: Hasta +Agency: Agencia +Warehouse: Almacén \ No newline at end of file diff --git a/modules/travel/front/summary/index.html b/modules/travel/front/summary/index.html new file mode 100644 index 000000000..0ce4517f2 --- /dev/null +++ b/modules/travel/front/summary/index.html @@ -0,0 +1,100 @@ + +
    {{$ctrl.travelData.id}} - {{$ctrl.travelData.ref}}
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

    Entries

    + + + + Confirmed + Entry Id + Supplier + Reference + HB + Freight cost + Package cost + CC + Pallet + m3 + + + + + + + + {{entry.id}} + {{entry.supplierName}} + {{entry.ref}} + {{entry.hb}} + {{entry.freightValue}} + {{entry.packageValue}} + {{entry.cc}} + {{entry.pallet}} + {{entry.m3}} + + + + + + + + + +
    +
    +
    + + + + \ No newline at end of file diff --git a/modules/travel/front/summary/index.js b/modules/travel/front/summary/index.js new file mode 100644 index 000000000..20946ed3b --- /dev/null +++ b/modules/travel/front/summary/index.js @@ -0,0 +1,44 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($scope, $http) { + this.$ = $scope; + this.$http = $http; + } + + get travel() { + return this._travel; + } + + set travel(value) { + this._travel = value; + + if (value && value.id) { + this.getTravel(); + this.getEntries(); + } + } + + getTravel() { + return this.$http.get(`/api/Travels/${this.travel.id}/getTravel`).then(response => { + this.travelData = response.data; + }); + } + + getEntries() { + return this.$http.get(`/api/Travels/${this.travel.id}/getEntries`).then(response => { + this.entries = response.data; + }); + } +} + +Controller.$inject = ['$scope', '$http']; + +ngModule.component('vnTravelSummary', { + template: require('./index.html'), + controller: Controller, + bindings: { + travel: '<' + } +}); diff --git a/modules/travel/front/summary/index.spec.js b/modules/travel/front/summary/index.spec.js new file mode 100644 index 000000000..dc6e4b23a --- /dev/null +++ b/modules/travel/front/summary/index.spec.js @@ -0,0 +1,61 @@ +import './index'; + +describe('component vnTravelSummary', () => { + let controller; + let $httpBackend; + + + beforeEach(angular.mock.module('travel', $translateProvider => { + $translateProvider.translations('en', {}); + })); + + beforeEach(angular.mock.inject(($componentController, _$httpBackend_) => { + $httpBackend = _$httpBackend_; + controller = $componentController('vnTravelSummary'); + })); + + describe('travel setter/getter', () => { + it('should return the travel', () => { + controller.travel = {id: null}; + + expect(controller.travel).toEqual(jasmine.any(Object)); + }); + + it('should return the travel and then call both getTravel() and getEntries()', () => { + spyOn(controller, 'getTravel'); + spyOn(controller, 'getEntries'); + controller.travel = {id: 99}; + + + expect(controller._travel.id).toEqual(99); + expect(controller.getTravel).toHaveBeenCalledWith(); + expect(controller.getEntries).toHaveBeenCalledWith(); + }); + }); + + describe('getTravel()', () => { + it('should perform a get and then store data on the controller', () => { + controller._travel = {id: 999}; + + const query = `/api/Travels/${controller._travel.id}/getTravel`; + $httpBackend.expectGET(query).respond('I am the travelData'); + controller.getTravel(); + $httpBackend.flush(); + + expect(controller.travelData).toEqual('I am the travelData'); + }); + }); + + describe('getEntries()', () => { + it('should call the getEntries method to get the entries data', () => { + controller._travel = {id: 999}; + + const query = `/api/Travels/${controller._travel.id}/getEntries`; + $httpBackend.expectGET(query).respond('I am the entries'); + controller.getEntries(); + $httpBackend.flush(); + + expect(controller.entries).toEqual('I am the entries'); + }); + }); +}); diff --git a/modules/travel/front/summary/locale/es.yml b/modules/travel/front/summary/locale/es.yml new file mode 100644 index 000000000..16f21fdde --- /dev/null +++ b/modules/travel/front/summary/locale/es.yml @@ -0,0 +1,17 @@ +Reference: Referencia +Warehouse In: Almacen entrada +Warehouse Out: Almacen salida +Shipped: F. envío +Landed: F. entrega +Total entries: Entradas totales +Delivered: Enviada +Received: Recibida +Agency: Agencia +Entries: Entradas +Confirmed: Confirmada +Entry Id: Entrada Id +Supplier: Proveedor +Pallet: Pallet +Freight cost: Coste porte +Package cost: Coste embalaje +Half box: Media caja diff --git a/modules/travel/front/summary/style.scss b/modules/travel/front/summary/style.scss new file mode 100644 index 000000000..922b36ad8 --- /dev/null +++ b/modules/travel/front/summary/style.scss @@ -0,0 +1,10 @@ +@import "variables"; + + +vn-travel-summary .summary { + max-width: $width-lg; + + vn-icon[icon=insert_drive_file]{ + color: $color-font-secondary; + } +} \ No newline at end of file diff --git a/modules/worker/back/methods/department/createChild.js b/modules/worker/back/methods/department/createChild.js new file mode 100644 index 000000000..57bcbe5be --- /dev/null +++ b/modules/worker/back/methods/department/createChild.js @@ -0,0 +1,40 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethod('createChild', { + description: 'Creates a new child department', + accessType: 'WRITE', + accepts: [{ + arg: 'parentId', + type: 'Number' + }, + { + arg: 'name', + type: 'String', + required: true, + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/createChild`, + verb: 'POST' + } + }); + + Self.createChild = async(parentId = null, name) => { + const models = Self.app.models; + const nameExists = await models.Department.count({name}); + + if (nameExists) + throw new UserError(`The department name can't be repeated`); + + const newDep = await models.Department.create({ + parentFk: parentId, + name: name + }); + + return newDep; + }; +}; diff --git a/modules/worker/back/methods/department/getLeaves.js b/modules/worker/back/methods/department/getLeaves.js new file mode 100644 index 000000000..614f3388e --- /dev/null +++ b/modules/worker/back/methods/department/getLeaves.js @@ -0,0 +1,49 @@ +module.exports = Self => { + Self.remoteMethod('getLeaves', { + description: 'Returns the nodes for a department', + accepts: [{ + arg: 'parentId', + type: 'Number', + description: 'Get the children of the specified father', + }, { + arg: 'search', + type: 'String', + description: 'Filter nodes whose name starts with', + }], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getLeaves`, + verb: 'GET' + } + }); + + Self.getLeaves = async(parentId = null, search) => { + let [res] = await Self.rawSql( + `CALL department_getLeaves(?, ?)`, + [parentId, search] + ); + + let map = new Map(); + for (let node of res) { + if (!map.has(node.parentFk)) + map.set(node.parentFk, []); + map.get(node.parentFk).push(node); + } + + function setLeaves(nodes) { + if (!nodes) return; + for (let node of nodes) { + node.childs = map.get(node.id); + setLeaves(node.childs); + } + } + + let leaves = map.get(parentId); + setLeaves(leaves); + + return leaves || []; + }; +}; diff --git a/modules/worker/back/methods/department/moveChild.js b/modules/worker/back/methods/department/moveChild.js new file mode 100644 index 000000000..97206f198 --- /dev/null +++ b/modules/worker/back/methods/department/moveChild.js @@ -0,0 +1,42 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethod('moveChild', { + description: 'Changes the parent of a child department', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'Number', + description: 'The department id', + http: {source: 'path'} + }, { + arg: 'parentId', + type: 'Number', + description: 'New parent id', + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/moveChild`, + verb: 'POST' + } + }); + + Self.moveChild = async(id, parentId = null) => { + const models = Self.app.models; + const child = await models.Department.findById(id); + + if (id == parentId) return; + + if (parentId) { + const parent = await models.Department.findById(parentId); + + if (child.lft < parent.lft && child.rgt > parent.rgt) + throw new UserError('You cannot move a parent to its own sons'); + } + + return child.updateAttribute('parentFk', parentId); + }; +}; diff --git a/modules/worker/back/methods/department/removeChild.js b/modules/worker/back/methods/department/removeChild.js new file mode 100644 index 000000000..00115ec34 --- /dev/null +++ b/modules/worker/back/methods/department/removeChild.js @@ -0,0 +1,27 @@ +module.exports = Self => { + Self.remoteMethod('removeChild', { + description: 'Removes a child department', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'Number', + description: 'The department id', + http: {source: 'path'} + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/removeChild`, + verb: 'POST' + } + }); + + Self.removeChild = async id => { + const models = Self.app.models; + const department = await models.Department.findById(id); + + return await department.destroy(); + }; +}; diff --git a/modules/worker/back/methods/department/specs/createChild.spec.js b/modules/worker/back/methods/department/specs/createChild.spec.js new file mode 100644 index 000000000..305732f58 --- /dev/null +++ b/modules/worker/back/methods/department/specs/createChild.spec.js @@ -0,0 +1,18 @@ +const app = require('vn-loopback/server/server'); + +describe('department createChild()', () => { + let createdChild; + + afterAll(async done => { + await createdChild.destroy(); + done(); + }); + + it('should create a new child', async() => { + const parentId = null; + createdChild = await app.models.Department.createChild(parentId, 'My new department'); + + expect(createdChild.name).toEqual('My new department'); + expect(createdChild.parentFk).toBeNull(); + }); +}); diff --git a/modules/worker/back/methods/department/specs/moveChild.spec.js b/modules/worker/back/methods/department/specs/moveChild.spec.js new file mode 100644 index 000000000..3358ebf77 --- /dev/null +++ b/modules/worker/back/methods/department/specs/moveChild.spec.js @@ -0,0 +1,23 @@ +const app = require('vn-loopback/server/server'); + +describe('department moveChild()', () => { + let updatedChild; + + afterAll(async done => { + const child = await app.models.Department.findById(updatedChild.id); + await child.updateAttribute('parentFk', null); + done(); + }); + + it('should move a child department to a new parent', async() => { + const childId = 22; + const parentId = 1; + + const child = await app.models.Department.findById(childId); + + expect(child.parentFk).toBeNull(); + updatedChild = await app.models.Department.moveChild(childId, parentId); + + expect(updatedChild.parentFk).toEqual(1); + }); +}); diff --git a/modules/worker/back/methods/department/specs/removeChild.spec.js b/modules/worker/back/methods/department/specs/removeChild.spec.js new file mode 100644 index 000000000..1fe3d10ef --- /dev/null +++ b/modules/worker/back/methods/department/specs/removeChild.spec.js @@ -0,0 +1,21 @@ +const app = require('vn-loopback/server/server'); + +describe('department removeChild()', () => { + let removedChild; + + afterAll(async done => { + await app.models.Department.create(removedChild); + done(); + }); + + it('should remove a child department', async() => { + const childId = 1; + + removedChild = await app.models.Department.findById(childId); + const result = await app.models.Department.removeChild(childId); + const existsChild = await app.models.Department.findById(childId); + + expect(result.count).toEqual(1); + expect(existsChild).toBeNull(); + }); +}); diff --git a/modules/worker/back/methods/holiday/getByWarehouse.js b/modules/worker/back/methods/holiday/getByWarehouse.js new file mode 100644 index 000000000..a56b5166e --- /dev/null +++ b/modules/worker/back/methods/holiday/getByWarehouse.js @@ -0,0 +1,40 @@ +module.exports = Self => { + Self.remoteMethod('getByWarehouse', { + description: 'Returns an array of labour holidays from an specified warehouse', + accepts: [{ + arg: 'warehouseFk', + type: 'Number', + required: true, + }], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getByWarehouse`, + verb: 'GET' + } + }); + + Self.getByWarehouse = async warehouseFk => { + let beginningYear = new Date(); + beginningYear.setMonth(0); + beginningYear.setDate(1); + beginningYear.setHours(0, 0, 0, 0); + + let holidays = await Self.rawSql( + `SELECT lh.dated, lhl.description, lht.name, w.id + FROM vn.holiday lh + JOIN vn.workCenter w ON w.id = lh.workcenterFk + LEFT JOIN vn.holidayDetail lhl ON lhl.id = lh.holidayDetailFk + LEFT JOIN vn.holidayType lht ON lht.id = lh.holidayTypeFk + WHERE w.warehouseFk = ? AND lh.dated >= ?`, [warehouseFk, beginningYear]); + + return holidays.map(holiday => { + holiday.dated = new Date(holiday.dated); + holiday.dated.setHours(0, 0, 0, 0); + + return holiday; + }); + }; +}; diff --git a/modules/worker/back/methods/worker-calendar/absences.js b/modules/worker/back/methods/worker-calendar/absences.js new file mode 100644 index 000000000..2cef07ec5 --- /dev/null +++ b/modules/worker/back/methods/worker-calendar/absences.js @@ -0,0 +1,146 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('absences', { + description: 'Returns an array of absences from an specified worker', + accepts: [{ + arg: 'workerFk', + type: 'Number', + required: true, + }, + { + arg: 'started', + type: 'Date', + required: true, + }, + { + arg: 'ended', + type: 'Date', + required: true, + }], + returns: [{ + arg: 'calendar' + }, + { + arg: 'absences', + type: 'Number' + }, + { + arg: 'holidays', + type: 'Number' + }], + http: { + path: `/absences`, + verb: 'GET' + } + }); + + Self.absences = async(ctx, workerFk, yearStarted, yearEnded) => { + const models = Self.app.models; + const isSubordinate = await models.Worker.isSubordinate(ctx, workerFk); + + if (!isSubordinate) + throw new UserError(`You don't have enough privileges`); + + const calendar = {totalHolidays: 0, holidaysEnjoyed: 0}; + const holidays = []; + + // Get absences of year + let absences = await Self.find({ + include: { + relation: 'absenceType' + }, + where: { + workerFk: workerFk, + dated: {between: [yearStarted, yearEnded]} + } + }); + + absences.forEach(absence => { + const isHoliday = absence.absenceType().code === 'holiday'; + const isHalfHoliday = absence.absenceType().code === 'halfHoliday'; + + if (isHoliday) + calendar.holidaysEnjoyed += 1; + if (isHalfHoliday) + calendar.holidaysEnjoyed += 0.5; + + absence.dated = new Date(absence.dated); + absence.dated.setHours(0, 0, 0, 0); + }); + + // Get active contracts on current year + const year = yearStarted.getFullYear(); + const contracts = await models.WorkerLabour.find({ + include: [{ + relation: 'holidays', + scope: { + where: {year} + } + }, + { + relation: 'workCenter', + scope: { + include: { + relation: 'holidays', + scope: { + include: [{ + relation: 'detail' + }, + { + relation: 'type' + }], + where: { + dated: {between: [yearStarted, yearEnded]} + } + } + } + } + }], + where: { + and: [ + {workerFk: workerFk}, + {or: [{ + ended: {gte: [yearStarted]} + }, {ended: null}]} + ], + + } + }); + + // Get number of worked days + let workedDays = 0; + contracts.forEach(contract => { + const started = contract.started; + const ended = contract.ended; + const startedTime = started.getTime(); + const endedTime = ended && ended.getTime() || yearEnded; + const dayTimestamp = 1000 * 60 * 60 * 24; + + workedDays += Math.floor((endedTime - startedTime) / dayTimestamp); + + // Workcenter holidays + let holidayList = contract.workCenter().holidays(); + for (let day of holidayList) { + day.dated = new Date(day.dated); + day.dated.setHours(0, 0, 0, 0); + + holidays.push(day); + } + }); + const currentContract = contracts.find(contract => { + return contract.started <= new Date() + && (contract.ended >= new Date() || contract.ended == null); + }); + + if (currentContract) { + const maxHolidays = currentContract.holidays().days; + calendar.totalHolidays = maxHolidays; + + if (workedDays < 365) + calendar.totalHolidays = Math.round(2 * maxHolidays * (workedDays) / 365) / 2; + } + + return [calendar, absences, holidays]; + }; +}; diff --git a/modules/worker/back/methods/worker-calendar/specs/absences.spec.js b/modules/worker/back/methods/worker-calendar/specs/absences.spec.js new file mode 100644 index 000000000..aebe5a24b --- /dev/null +++ b/modules/worker/back/methods/worker-calendar/specs/absences.spec.js @@ -0,0 +1,168 @@ +const app = require('vn-loopback/server/server'); + +// #1924 - Fix hours +xdescribe('Worker absences()', () => { + it('should get the absence calendar for a full year contract', async() => { + let ctx = {req: {accessToken: {userId: 106}}}; + let workerFk = 106; + + const started = new Date(); + started.setHours(0, 0, 0, 0); + started.setMonth(0); + started.setDate(1); + + const monthIndex = 11; + const ended = new Date(); + ended.setHours(0, 0, 0, 0); + ended.setMonth(monthIndex + 1); + ended.setDate(0); + + let result = await app.models.WorkerCalendar.absences(ctx, workerFk, started, ended); + let calendar = result[0]; + let absences = result[1]; + + expect(calendar.totalHolidays).toEqual(27.5); + expect(calendar.holidaysEnjoyed).toEqual(5); + + let firstType = absences[0].absenceType().name; + let sixthType = absences[5].absenceType().name; + + expect(firstType).toEqual('Leave of absence'); + expect(sixthType).toEqual('Holidays'); + }); + + it('should get the absence calendar for a permanent contract', async() => { + let workerFk = 106; + let worker = await app.models.WorkerLabour.findById(workerFk); + let endedDate = worker.ended; + + await app.models.WorkerLabour.rawSql( + `UPDATE postgresql.business SET date_end = ? WHERE business_id = ?`, + [null, worker.businessFk] + ); + + let ctx = {req: {accessToken: {userId: 9}}}; + + const started = new Date(); + started.setHours(0, 0, 0, 0); + started.setMonth(0); + started.setDate(1); + + const monthIndex = 11; + const ended = new Date(); + ended.setHours(0, 0, 0, 0); + ended.setMonth(monthIndex + 1); + ended.setDate(0); + + let result = await app.models.WorkerCalendar.absences(ctx, workerFk, started, ended); + let calendar = result[0]; + let absences = result[1]; + + expect(calendar.totalHolidays).toEqual(27.5); + expect(calendar.holidaysEnjoyed).toEqual(5); + + let firstType = absences[0].absenceType().name; + let sixthType = absences[5].absenceType().name; + + expect(firstType).toEqual('Leave of absence'); + expect(sixthType).toEqual('Holidays'); + + // restores the contract end date + await app.models.WorkerLabour.rawSql( + `UPDATE postgresql.business SET date_end = ? WHERE business_id = ?`, + [endedDate, worker.businessFk] + ); + }); + + it('should give the same holidays as worked days since the holidays amount matches the amount of days in a year', async() => { + const today = new Date(); + + // getting how many days in a year + const yearStart = new Date(); + yearStart.setHours(0, 0, 0, 0); + yearStart.setMonth(0); + yearStart.setDate(1); + + const yearEnd = new Date(); + yearEnd.setHours(23, 59, 59, 59); + yearEnd.setMonth(11); + yearEnd.setDate(31); + const startedTime = yearStart.getTime(); + const endedTime = yearEnd.getTime(); + const dayTimestamp = 1000 * 60 * 60 * 24; + + const daysInYear = Math.floor((endedTime - startedTime) / dayTimestamp); + + // sets the holidays per year to the amount of days in the current year + let holidaysConfig = await app.models.WorkCenterHoliday.findOne({ + where: { + workCenterFk: 1, + year: today.getFullYear() + }}); + + let originalHolidaysValue = holidaysConfig.days; + + await app.models.WorkCenterHoliday.updateAll( + { + workCenterFk: 1, + year: today.getFullYear() + }, + { + days: daysInYear + } + ); + // normal test begins + const contract = await app.models.WorkerLabour.findById(106); + const contractStartDate = contract.started; + + const startingContract = new Date(); + startingContract.setHours(0, 0, 0, 0); + startingContract.setMonth(today.getMonth()); + startingContract.setDate(1); + + await app.models.WorkerLabour.rawSql( + `UPDATE postgresql.business SET date_start = ? WHERE business_id = ?`, + [startingContract, contract.businessFk] + ); + + let ctx = {req: {accessToken: {userId: 106}}}; + let workerFk = 106; + + let result = await app.models.WorkerCalendar.absences(ctx, workerFk, yearStart, yearEnd); + let calendar = result[0]; + let absences = result[1]; + + let remainingDays = 0; + for (let i = today.getMonth(); i < 12; i++) { + today.setMonth(i + 1); + today.setDate(0); + + remainingDays += today.getDate(); + } + + expect(calendar.totalHolidays).toEqual(remainingDays); + expect(calendar.holidaysEnjoyed).toEqual(5); + + let firstType = absences[0].absenceType().name; + let sixthType = absences[5].absenceType().name; + + expect(firstType).toEqual('Leave of absence'); + expect(sixthType).toEqual('Holidays'); + + // resets the holidays per year with originalHolidaysValue and the contract starting date + await app.models.WorkCenterHoliday.updateAll( + { + workCenterFk: 1, + year: today.getFullYear() + }, + { + days: originalHolidaysValue + } + ); + + await app.models.WorkerLabour.rawSql( + `UPDATE postgresql.business SET date_start = ? WHERE business_id = ?`, + [contractStartDate, contract.businessFk] + ); + }); +}); diff --git a/modules/worker/back/methods/worker-dms/allowedContentTypes.js b/modules/worker/back/methods/worker-dms/allowedContentTypes.js new file mode 100644 index 000000000..2f5183f92 --- /dev/null +++ b/modules/worker/back/methods/worker-dms/allowedContentTypes.js @@ -0,0 +1,23 @@ +module.exports = Self => { + Self.remoteMethodCtx('allowedContentTypes', { + description: 'Returns a list of allowed contentTypes', + accessType: 'READ', + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/allowedContentTypes`, + verb: 'GET' + } + }); + + Self.allowedContentTypes = async() => { + const storageConnector = Self.app.dataSources.storage.connector; + const allowedContentTypes = storageConnector.allowedContentTypes; + const modelAllowedContentTypes = Self.definition.settings.allowedContentTypes; + + return modelAllowedContentTypes || allowedContentTypes; + }; +}; + diff --git a/modules/worker/back/methods/worker-dms/removeFile.js b/modules/worker/back/methods/worker-dms/removeFile.js new file mode 100644 index 000000000..d0116c3c2 --- /dev/null +++ b/modules/worker/back/methods/worker-dms/removeFile.js @@ -0,0 +1,30 @@ +module.exports = Self => { + Self.remoteMethodCtx('removeFile', { + description: 'Removes a worker document', + accessType: 'WRITE', + accepts: { + arg: 'id', + type: 'Number', + description: 'The document id', + http: {source: 'path'} + }, + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/removeFile`, + verb: 'POST' + } + }); + + Self.removeFile = async(ctx, id) => { + const models = Self.app.models; + const workerDms = await Self.findById(id); + + await models.Dms.removeFile(ctx, workerDms.dmsFk); + + return workerDms.destroy(); + }; +}; + diff --git a/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js b/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js new file mode 100644 index 000000000..7039d4f3e --- /dev/null +++ b/modules/worker/back/methods/worker-dms/specs/removeFile.spec.js @@ -0,0 +1,18 @@ +const app = require('vn-loopback/server/server'); + +describe('WorkerDms removeFile()', () => { + const workerDmsFk = 1; + it(`should return an error for a user without enough privileges`, async() => { + let clientId = 101; + let ctx = {req: {accessToken: {userId: clientId}}}; + + let error; + await app.models.WorkerDms.removeFile(ctx, workerDmsFk).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`You don't have enough privileges`); + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/modules/worker/back/methods/worker-mana/getCurrentWorkerMana.js b/modules/worker/back/methods/worker-mana/getCurrentWorkerMana.js new file mode 100644 index 000000000..7be2312e6 --- /dev/null +++ b/modules/worker/back/methods/worker-mana/getCurrentWorkerMana.js @@ -0,0 +1,29 @@ +module.exports = Self => { + Self.remoteMethodCtx('getCurrentWorkerMana', { + description: 'Returns the mana of the logged worker', + accessType: 'READ', + accepts: [], + returns: { + type: 'number', + root: true + }, + http: { + path: `/getCurrentWorkerMana`, + verb: 'GET' + } + }); + + Self.getCurrentWorkerMana = async ctx => { + let currentClientId = ctx.req.accessToken.userId; + let currentWorker = await Self.app.models.Worker.findOne({ + where: {userFk: currentClientId}, + fields: 'id' + }); + let currentWorkerMana = await Self.app.models.WorkerMana.findOne({ + where: {workerFk: currentWorker.id}, + fields: 'amount' + }); + + return currentWorkerMana ? currentWorkerMana.amount : 0; + }; +}; diff --git a/modules/worker/back/methods/worker-mana/specs/getCurrentWorkerMana.spec.js b/modules/worker/back/methods/worker-mana/specs/getCurrentWorkerMana.spec.js new file mode 100644 index 000000000..8d626e720 --- /dev/null +++ b/modules/worker/back/methods/worker-mana/specs/getCurrentWorkerMana.spec.js @@ -0,0 +1,15 @@ +const app = require('vn-loopback/server/server'); + +describe('workerMana getCurrentWorkerMana()', () => { + it('should get the mana of the logged worker', async() => { + let mana = await app.models.WorkerMana.getCurrentWorkerMana({req: {accessToken: {userId: 18}}}); + + expect(mana).toEqual(124); + }); + + it('should return 0 if the user doesnt uses mana', async() => { + let mana = await app.models.WorkerMana.getCurrentWorkerMana({req: {accessToken: {userId: 9}}}); + + expect(mana).toEqual(0); + }); +}); diff --git a/modules/worker/back/methods/worker-time-control/addTimeEntry.js b/modules/worker/back/methods/worker-time-control/addTimeEntry.js new file mode 100644 index 000000000..86030d713 --- /dev/null +++ b/modules/worker/back/methods/worker-time-control/addTimeEntry.js @@ -0,0 +1,42 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('addTimeEntry', { + description: 'Adds a new hour registry', + accessType: 'WRITE', + accepts: [{ + arg: 'data', + type: 'object', + required: true, + description: 'workerFk, timed', + http: {source: 'body'} + }], + returns: [{ + type: 'Object', + root: true + }], + http: { + path: `/addTimeEntry`, + verb: 'POST' + } + }); + + Self.addTimeEntry = async(ctx, data) => { + const Worker = Self.app.models.Worker; + const myUserId = ctx.req.accessToken.userId; + const myWorker = await Worker.findOne({where: {userFk: myUserId}}); + const isSubordinate = await Worker.isSubordinate(ctx, data.workerFk); + const isTeamBoss = await Self.app.models.Account.hasRole(myUserId, 'teamBoss'); + + if (isSubordinate === false || (isSubordinate && myWorker.id == data.workerFk && !isTeamBoss)) + throw new UserError(`You don't have enough privileges`); + + const subordinate = await Worker.findById(data.workerFk); + const timed = new Date(data.timed); + + let [result] = await Self.rawSql('SELECT vn.workerTimeControl_add(?, ?, ?, ?) AS id', [ + subordinate.userFk, null, timed, true]); + + return result; + }; +}; diff --git a/modules/worker/back/methods/worker-time-control/deleteTimeEntry.js b/modules/worker/back/methods/worker-time-control/deleteTimeEntry.js new file mode 100644 index 000000000..540a7ab8e --- /dev/null +++ b/modules/worker/back/methods/worker-time-control/deleteTimeEntry.js @@ -0,0 +1,41 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('deleteTimeEntry', { + description: 'Deletes a manual time entry for a worker if the user role is above the worker', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The time entry id', + http: {source: 'path'} + }], + returns: { + type: 'boolean', + root: true + }, + http: { + path: `/:id/deleteTimeEntry`, + verb: 'POST' + } + }); + + Self.deleteTimeEntry = async(ctx, id) => { + const currentUserId = ctx.req.accessToken.userId; + const workerModel = Self.app.models.Worker; + + const targetTimeEntry = await Self.findById(id); + + const isSubordinate = await workerModel.isSubordinate(ctx, targetTimeEntry.userFk); + const isHHRR = await Self.app.models.Account.hasRole(currentUserId, 'hr'); + + const notAllowed = isSubordinate === false || (isSubordinate && currentUserId == targetTimeEntry.userFk && !isHHRR); + + if (notAllowed) + throw new UserError(`You don't have enough privileges`); + + return Self.rawSql('CALL vn.workerTimeControl_remove(?, ?)', [ + targetTimeEntry.userFk, targetTimeEntry.timed]); + }; +}; diff --git a/modules/worker/back/methods/worker-time-control/filter.js b/modules/worker/back/methods/worker-time-control/filter.js new file mode 100644 index 000000000..041c6cbfb --- /dev/null +++ b/modules/worker/back/methods/worker-time-control/filter.js @@ -0,0 +1,46 @@ +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethod('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accessType: 'READ', + accepts: [{ + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + }, { + arg: 'filter', + type: 'Object', + description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string` + }, { + arg: 'workerFk', + type: 'Number', + required: true, + description: `The worker id` + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: '/filter', + verb: 'GET' + } + }); + + Self.filter = async(ctx, filter) => { + const Worker = Self.app.models.Worker; + const isSubordinate = await Worker.isSubordinate(ctx, ctx.args.workerFk); + + if (isSubordinate === false) + throw new UserError(`You don't have enough privileges`); + + const subordinate = await Worker.findById(ctx.args.workerFk); + filter = mergeFilters(filter, {where: { + userFk: subordinate.userFk + }}); + + return Self.find(filter); + }; +}; diff --git a/modules/worker/back/methods/worker-time-control/specs/filter.spec.js b/modules/worker/back/methods/worker-time-control/specs/filter.spec.js new file mode 100644 index 000000000..913dfb355 --- /dev/null +++ b/modules/worker/back/methods/worker-time-control/specs/filter.spec.js @@ -0,0 +1,45 @@ +const app = require('vn-loopback/server/server'); + +describe('workerTimeControl filter()', () => { + it('should return 1 result filtering by id', async() => { + let ctx = {req: {accessToken: {userId: 106}}, args: {workerFk: 106}}; + const firstHour = new Date(); + firstHour.setHours(7, 0, 0, 0); + const lastHour = new Date(); + lastHour.setDate(lastHour.getDate() + 1); + lastHour.setHours(15, 0, 0, 0); + + const filter = { + where: { + timed: {between: [firstHour, lastHour]} + } + }; + let result = await app.models.WorkerTimeControl.filter(ctx, filter); + + expect(result.length).toEqual(4); + }); + + it('should return a privilege error for a non subordinate worker', async() => { + let ctx = {req: {accessToken: {userId: 107}}, args: {workerFk: 106}}; + const firstHour = new Date(); + firstHour.setHours(7, 0, 0, 0); + const lastHour = new Date(); + lastHour.setDate(lastHour.getDate() + 1); + lastHour.setHours(15, 0, 0, 0); + + const filter = { + where: { + timed: {between: [firstHour, lastHour]} + } + }; + + let error; + await app.models.WorkerTimeControl.filter(ctx, filter).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`You don't have enough privileges`); + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js b/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js new file mode 100644 index 000000000..ff5e13a2d --- /dev/null +++ b/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js @@ -0,0 +1,92 @@ +const app = require('vn-loopback/server/server'); + +describe('workerTimeControl addTimeEntry()', () => { + let timeEntry; + let createdTimeEntry; + + it('should fail to add a time entry if the target user is not a subordinate', async() => { + let error; + let ctx = {req: {accessToken: {userId: 1}}}; + let data = { + workerFk: 2, + timed: new Date() + }; + + try { + await app.models.WorkerTimeControl.addTimeEntry(ctx, data); + } catch (e) { + error = e; + } + + expect(error).toBeDefined(); + expect(error.statusCode).toBe(400); + expect(error.message).toBe(`You don't have enough privileges`); + }); + + it('should fail to add if the current and the target user are the same and is not team boss', async() => { + let error; + let ctx = {req: {accessToken: {userId: 1}}}; + let data = { + workerFk: 1, + timed: new Date() + }; + + try { + await app.models.WorkerTimeControl.addTimeEntry(ctx, data); + } catch (e) { + error = e; + } + + expect(error).toBeDefined(); + expect(error.statusCode).toBe(400); + expect(error.message).toBe(`You don't have enough privileges`); + }); + + it('should add if the current user is team boss and the target user is a subordinate', async() => { + todayAtSix = new Date(); + todayAtSix.setHours(18, 30, 0, 0); + + let teamBossId = 13; + let ctx = {req: {accessToken: {userId: teamBossId}}}; + let data = { + workerFk: teamBossId, + timed: todayAtSix + }; + + timeEntry = await app.models.WorkerTimeControl.addTimeEntry(ctx, data); + + createdTimeEntry = await app.models.WorkerTimeControl.findById(timeEntry.id); + + expect(createdTimeEntry).toBeDefined(); + }); + + it('should try but fail to delete the created time entry for the team boss as team boss', async() => { + let error; + let teamBossId = 13; + let ctx = {req: {accessToken: {userId: teamBossId}}}; + + try { + await app.models.WorkerTimeControl.deleteTimeEntry(ctx, createdTimeEntry.id); + } catch (e) { + error = e; + } + + expect(error).toBeDefined(); + expect(error.statusCode).toBe(400); + expect(error.message).toBe(`You don't have enough privileges`); + }); + + it('should delete the created time entry for the team boss as HHRR', async() => { + let HHRRId = 37; + let ctx = {req: {accessToken: {userId: HHRRId}}}; + + expect(createdTimeEntry).toBeDefined(); + + ctx.req.accessToken.userId = HHRRId; + await app.models.WorkerTimeControl.deleteTimeEntry(ctx, timeEntry.id); + + createdTimeEntry = await app.models.WorkerTimeControl.findById(timeEntry.id); + + expect(createdTimeEntry).toBeNull(); + }); +}); diff --git a/modules/worker/back/methods/worker/filter.js b/modules/worker/back/methods/worker/filter.js new file mode 100644 index 000000000..21462eb42 --- /dev/null +++ b/modules/worker/back/methods/worker/filter.js @@ -0,0 +1,136 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const buildFilter = require('vn-loopback/util/filter').buildFilter; +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethodCtx('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accessType: 'READ', + accepts: [ + { + arg: 'filter', + type: 'Object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + http: {source: 'query'} + }, { + arg: 'tags', + type: ['Object'], + description: 'List of tags to filter with', + http: {source: 'query'} + }, { + arg: 'search', + type: 'String', + description: `If it's and integer searchs by id, otherwise it searchs by name`, + http: {source: 'query'} + }, { + arg: 'id', + type: 'Integer', + description: 'The worker id', + http: {source: 'query'} + }, { + arg: 'userFk', + type: 'Integer', + description: 'The user id', + http: {source: 'query'} + }, { + arg: 'fi', + type: 'String', + description: 'The worker fi', + http: {source: 'query'} + }, { + arg: 'departmentFk', + type: 'Integer', + description: 'The worker department id', + http: {source: 'query'} + }, { + arg: 'extension', + type: 'Integer', + description: 'The worker extension id', + http: {source: 'query'} + }, { + arg: 'firstName', + type: 'String', + description: 'The worker firstName', + http: {source: 'query'} + }, { + arg: 'name', + type: 'String', + description: 'The worker name', + http: {source: 'query'} + }, { + arg: 'nickname', + type: 'String', + description: 'The worker nickname', + http: {source: 'query'} + } + ], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/filter`, + verb: 'GET' + } + }); + + Self.filter = async(ctx, filter) => { + let conn = Self.dataSource.connector; + + let where = buildFilter(ctx.args, (param, value) => { + switch (param) { + case 'search': + return /^\d+$/.test(value) + ? {'w.id': value} + : {or: [ + {'w.firstName': {like: `%${value}%`}}, + {'w.lastName': {like: `%${value}%`}}, + {'u.name': {like: `%${value}%`}}, + {'u.nickname': {like: `%${value}%`}} + ]}; + case 'id': + return {'w.id': value}; + case 'userFk': + return {'w.userFk': value}; + case 'name': + return {'w.lastName': {like: `%${value}%`}}; + case 'firstName': + return {'w.firstName': {like: `%${value}%`}}; + case 'extension': + return {'p.extension': value}; + case 'fi': + return {'c.fi': value}; + case 'departmentFk': + return {'d.id': value}; + case 'userName': + return {'u.name': {like: `%${value}%`}}; + } + }); + + filter = mergeFilters(ctx.args.filter, {where}); + + let stmts = []; + let stmt; + + stmt = new ParameterizedSQL( + `SELECT w.id, u.email, p.extension, u.name as userName, + d.name AS department, w.lastName, u.nickname, mu.email + FROM worker w + LEFT JOIN workerDepartment wd ON wd.workerFk = w.id + LEFT JOIN department d ON d.id = wd.departmentFk + LEFT JOIN client c ON c.id = w.userFk + LEFT JOIN account.user u ON u.id = w.userFk + LEFT JOIN pbx.sip p ON p.user_id = u.id + LEFT JOIN account.emailUser mu ON mu.userFk = u.id` + ); + + + stmt.merge(conn.makeSuffix(filter)); + let itemsIndex = stmts.push(stmt) - 1; + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + return itemsIndex === 0 ? result : result[itemsIndex]; + }; +}; diff --git a/modules/worker/back/methods/worker/getWorkedHours.js b/modules/worker/back/methods/worker/getWorkedHours.js new file mode 100644 index 000000000..e96d30f8d --- /dev/null +++ b/modules/worker/back/methods/worker/getWorkedHours.js @@ -0,0 +1,67 @@ +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('getWorkedHours', { + description: 'returns the total worked hours per day for a given range of dates in format YYYY-mm-dd hh:mm:ss', + accessType: 'READ', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The worker id', + http: {source: 'path'} + }, + { + arg: 'from', + type: 'Date', + required: true, + description: `The from date` + }, + { + arg: 'to', + type: 'Date', + required: true, + description: `The to date` + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/:id/getWorkedHours`, + verb: 'GET' + } + }); + + Self.getWorkedHours = async(id, from, to) => { + const conn = Self.dataSource.connector; + const stmts = []; + + let worker = await Self.app.models.Worker.findById(id); + let userId = worker.userFk; + + stmts.push(` + DROP TEMPORARY TABLE IF EXISTS + tmp.timeControlCalculate, + tmp.timeBusinessCalculate + `); + + stmts.push(new ParameterizedSQL('CALL vn.timeControl_calculateByUser(?, ?, ?)', [userId, from, to])); + stmts.push(new ParameterizedSQL('CALL vn.timeBusiness_calculateByUser(?, ?, ?)', [userId, from, to])); + let resultIndex = stmts.push(` + SELECT tbc.dated, tbc.timeWorkSeconds expectedHours, tcc.timeWorkSeconds workedHours + FROM tmp.timeBusinessCalculate tbc + LEFT JOIN tmp.timeControlCalculate tcc ON tcc.dated = tbc.dated + `) - 1; + stmts.push(` + DROP TEMPORARY TABLE IF EXISTS + tmp.timeControlCalculate, + tmp.timeBusinessCalculate + `); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + + return result[resultIndex]; + }; +}; diff --git a/modules/worker/back/methods/worker/isSubordinate.js b/modules/worker/back/methods/worker/isSubordinate.js new file mode 100644 index 000000000..a85484668 --- /dev/null +++ b/modules/worker/back/methods/worker/isSubordinate.js @@ -0,0 +1,41 @@ +module.exports = Self => { + Self.remoteMethod('isSubordinate', { + description: 'Check if an employee is subordinate', + accessType: 'READ', + accepts: [{ + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + }, { + arg: 'id', + type: 'number', + required: true, + description: 'The worker id', + http: {source: 'path'} + }], + returns: { + type: 'boolean', + root: true + }, + http: { + path: `/:id/isSubordinate`, + verb: 'GET' + } + }); + + Self.isSubordinate = async(ctx, id) => { + const models = Self.app.models; + const myUserId = ctx.req.accessToken.userId; + + const mySubordinates = await Self.mySubordinates(ctx); + const isSubordinate = mySubordinates.find(subordinate => { + return subordinate.workerFk === id; + }); + + const isHr = await models.Account.hasRole(myUserId, 'hr'); + if (isHr || isSubordinate) + return true; + + return false; + }; +}; diff --git a/modules/worker/back/methods/worker/mySubordinates.js b/modules/worker/back/methods/worker/mySubordinates.js new file mode 100644 index 000000000..bf1cd1be8 --- /dev/null +++ b/modules/worker/back/methods/worker/mySubordinates.js @@ -0,0 +1,41 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('mySubordinates', { + description: 'Returns a list of a subordinate workers', + accessType: 'READ', + accepts: [{ + arg: 'ctx', + type: 'Object', + http: {source: 'context'} + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/mySubordinates`, + verb: 'GET' + } + }); + + Self.mySubordinates = async ctx => { + const conn = Self.dataSource.connector; + const myUserId = ctx.req.accessToken.userId; + const myWorker = await Self.app.models.Worker.findOne({ + where: {userFk: myUserId} + }); + const stmts = []; + + stmts.push(new ParameterizedSQL('CALL vn.subordinateGetList(?)', [myWorker.id])); + stmts.push('SELECT * FROM tmp.subordinate'); + stmts.push('DROP TEMPORARY TABLE tmp.subordinate'); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + + + return result[1]; + }; +}; diff --git a/modules/worker/back/methods/worker/specs/filter.spec.js b/modules/worker/back/methods/worker/specs/filter.spec.js new file mode 100644 index 000000000..c1bc05ae8 --- /dev/null +++ b/modules/worker/back/methods/worker/specs/filter.spec.js @@ -0,0 +1,25 @@ +const app = require('vn-loopback/server/server'); + +describe('worker filter()', () => { + it('should return 1 result filtering by id', async() => { + let result = await app.models.Worker.filter({args: {filter: {}, search: 1}}); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(1); + }); + + it('should return 1 result filtering by string', async() => { + let result = await app.models.Worker.filter({args: {filter: {}, search: 'administrativeNick'}}); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(5); + }); + + it('should return 2 results filtering by name', async() => { + let result = await app.models.Worker.filter({args: {filter: {}, name: 'agency'}}); + + expect(result.length).toEqual(2); + expect(result[0].nickname).toEqual('agencyNick'); + expect(result[1].nickname).toEqual('agencyBossNick'); + }); +}); diff --git a/modules/worker/back/methods/worker/specs/isSubordinate.spec.js b/modules/worker/back/methods/worker/specs/isSubordinate.spec.js new file mode 100644 index 000000000..53a620fcc --- /dev/null +++ b/modules/worker/back/methods/worker/specs/isSubordinate.spec.js @@ -0,0 +1,27 @@ +const app = require('vn-loopback/server/server'); + +describe('worker isSubordinate()', () => { + it('should return truthy if a worker is a subordinate', async() => { + let ctx = {req: {accessToken: {userId: 19}}}; + let workerFk = 106; + let result = await app.models.Worker.isSubordinate(ctx, workerFk); + + expect(result).toBeTruthy(); + }); + + it('should return truthy for an hr person', async() => { + let ctx = {req: {accessToken: {userId: 37}}}; + let workerFk = 106; + let result = await app.models.Worker.isSubordinate(ctx, workerFk); + + expect(result).toBeTruthy(); + }); + + it('should return truthy if the current user is himself', async() => { + let ctx = {req: {accessToken: {userId: 106}}}; + let workerFk = 106; + let result = await app.models.Worker.isSubordinate(ctx, workerFk); + + expect(result).toBeTruthy(); + }); +}); diff --git a/modules/worker/back/methods/worker/specs/mySubordinates.spec.js b/modules/worker/back/methods/worker/specs/mySubordinates.spec.js new file mode 100644 index 000000000..5a458a1bc --- /dev/null +++ b/modules/worker/back/methods/worker/specs/mySubordinates.spec.js @@ -0,0 +1,19 @@ +const app = require('vn-loopback/server/server'); + +describe('worker mySubordinates()', () => { + it('should return an array of subordinates greather than 1', async() => { + let ctx = {req: {accessToken: {userId: 9}}}; + let result = await app.models.Worker.mySubordinates(ctx); + + expect(result.length).toBeGreaterThan(1); + }); + + it('should return an array of one subordinate', async() => { + let ctx = {req: {accessToken: {userId: 106}}}; + let result = await app.models.Worker.mySubordinates(ctx); + const workerFk = 106; + + expect(result.length).toEqual(1); + expect(result[0].workerFk).toEqual(workerFk); + }); +}); diff --git a/modules/worker/back/methods/worker/specs/uploadFile.spec.js b/modules/worker/back/methods/worker/specs/uploadFile.spec.js new file mode 100644 index 000000000..26a50252d --- /dev/null +++ b/modules/worker/back/methods/worker/specs/uploadFile.spec.js @@ -0,0 +1,19 @@ +const app = require('vn-loopback/server/server'); + +describe('Worker uploadFile()', () => { + it(`should return an error for a user without enough privileges`, async() => { + let workerId = 106; + let currentUserId = 102; + let hhrrDataId = 3; + let ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: hhrrDataId}}; + + let error; + await app.models.Worker.uploadFile(ctx, workerId).catch(e => { + error = e; + }).finally(() => { + expect(error.message).toEqual(`You don't have enough privileges`); + }); + + expect(error).toBeDefined(); + }); +}); diff --git a/modules/worker/back/methods/worker/timeControl.js b/modules/worker/back/methods/worker/timeControl.js new file mode 100644 index 000000000..bc88197fe --- /dev/null +++ b/modules/worker/back/methods/worker/timeControl.js @@ -0,0 +1,50 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; + +module.exports = Self => { + Self.remoteMethod('timeControl', { + description: 'Returns a range of worked hours for a given worker id', + accessType: 'READ', + accepts: [ + { + arg: 'id', + type: 'number', + required: true, + description: 'The worker id', + http: {source: 'path'} + }, + { + arg: 'dateFrom', + type: 'datetime', + required: true, + description: 'the date from the time control begins in format YYYY-mm-dd-hh:mm:ss' + }, + { + arg: 'dateTo', + type: 'datetime', + required: true, + description: 'the date when the time control finishes in format YYYY-mm-dd-hh:mm:ss' + }], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/:id/timeControl`, + verb: 'GET' + } + }); + + Self.timeControl = async(id, from, to) => { + const conn = Self.dataSource.connector; + const stmts = []; + + stmts.push(new ParameterizedSQL('CALL vn.timeControl_calculateByUser(?, ?, ?)', [id, from, to])); + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + + + return result[0]; + }; +}; diff --git a/modules/worker/back/methods/worker/uploadFile.js b/modules/worker/back/methods/worker/uploadFile.js new file mode 100644 index 000000000..588cfe4bd --- /dev/null +++ b/modules/worker/back/methods/worker/uploadFile.js @@ -0,0 +1,76 @@ +module.exports = Self => { + Self.remoteMethodCtx('uploadFile', { + description: 'Upload and attach a file to a client', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'Number', + description: 'The worker id', + http: {source: 'path'} + }, { + arg: 'warehouseId', + type: 'Number', + description: 'The warehouse id', + required: true + }, { + arg: 'companyId', + type: 'Number', + description: 'The company id', + required: true + }, { + arg: 'dmsTypeId', + type: 'Number', + description: 'The dms type id', + required: true + }, { + arg: 'reference', + type: 'String', + required: true + }, { + arg: 'description', + type: 'String', + required: true + }, { + arg: 'hasFile', + type: 'Boolean', + description: 'True if has an attached file', + required: true + }], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/:id/uploadFile`, + verb: 'POST' + } + }); + + Self.uploadFile = async(ctx, id) => { + const models = Self.app.models; + const promises = []; + const tx = await Self.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const uploadedFiles = await models.Dms.uploadFile(ctx, options); + uploadedFiles.forEach(dms => { + const newWorkerDms = models.WorkerDms.create({ + workerFk: id, + dmsFk: dms.id + }, options); + + promises.push(newWorkerDms); + }); + const resolvedPromises = await Promise.all(promises); + + await tx.commit(); + + return resolvedPromises; + } catch (err) { + await tx.rollback(); + throw err; + } + }; +}; diff --git a/modules/worker/back/model-config.json b/modules/worker/back/model-config.json new file mode 100644 index 000000000..4948231b9 --- /dev/null +++ b/modules/worker/back/model-config.json @@ -0,0 +1,56 @@ +{ + "AbsenceType": { + "dataSource": "vn" + }, + "Department": { + "dataSource": "vn" + }, + "Holiday": { + "dataSource": "vn" + }, + "HolidayDetail": { + "dataSource": "vn" + }, + "HolidayType": { + "dataSource": "vn" + }, + "WorkCenter": { + "dataSource": "vn" + }, + "WorkCenterHoliday": { + "dataSource": "vn" + }, + "WorkerDms": { + "dataSource": "vn" + }, + "Worker": { + "dataSource": "vn" + }, + "WorkerLabour": { + "dataSource": "vn" + }, + "WorkerMana": { + "dataSource": "vn" + }, + "WorkerTeam": { + "dataSource": "vn" + }, + "WorkerTeamCollegues": { + "dataSource": "vn" + }, + "WorkerMedia": { + "dataSource": "vn" + }, + "WorkerDepartment": { + "dataSource": "vn" + }, + "WorkerCalendar": { + "dataSource": "vn" + }, + "WorkerTimeControl": { + "dataSource": "vn" + }, + "Device": { + "dataSource": "vn" + } +} diff --git a/modules/worker/back/models/absence-type.json b/modules/worker/back/models/absence-type.json new file mode 100644 index 000000000..a2fc2469d --- /dev/null +++ b/modules/worker/back/models/absence-type.json @@ -0,0 +1,32 @@ +{ + "name": "AbsenceType", + "base": "VnModel", + "options": { + "mysql": { + "table": "absenceType" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "name": { + "type": "String" + }, + "rgb": { + "type": "String" + }, + "code": { + "type": "String" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/modules/worker/back/models/department.js b/modules/worker/back/models/department.js new file mode 100644 index 000000000..5a927fc64 --- /dev/null +++ b/modules/worker/back/models/department.js @@ -0,0 +1,6 @@ +module.exports = Self => { + require('../methods/department/getLeaves')(Self); + require('../methods/department/createChild')(Self); + require('../methods/department/removeChild')(Self); + require('../methods/department/moveChild')(Self); +}; diff --git a/modules/worker/back/models/department.json b/modules/worker/back/models/department.json new file mode 100644 index 000000000..7de76e039 --- /dev/null +++ b/modules/worker/back/models/department.json @@ -0,0 +1,30 @@ +{ + "name": "Department", + "base": "VnModel", + "options": { + "mysql": { + "table": "department" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "name": { + "type": "String" + }, + "parentFk": { + "type": "Number" + }, + "lft": { + "type": "Number" + }, + "rgt": { + "type": "Number" + }, + "sons": { + "type": "Number" + } + } +} diff --git a/modules/worker/back/models/device.js b/modules/worker/back/models/device.js new file mode 100644 index 000000000..cda7a958f --- /dev/null +++ b/modules/worker/back/models/device.js @@ -0,0 +1,9 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError(``); + return err; + }); +}; diff --git a/modules/worker/back/models/device.json b/modules/worker/back/models/device.json new file mode 100644 index 000000000..5367faedf --- /dev/null +++ b/modules/worker/back/models/device.json @@ -0,0 +1,28 @@ +{ + "name": "Device", + "base": "VnModel", + "options": { + "mysql": { + "table": "device" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "sn": { + "type": "String" + }, + "model": { + "type": "String" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + } + } +} diff --git a/modules/worker/back/models/holiday-detail.json b/modules/worker/back/models/holiday-detail.json new file mode 100644 index 000000000..86874a02e --- /dev/null +++ b/modules/worker/back/models/holiday-detail.json @@ -0,0 +1,26 @@ +{ + "name": "HolidayDetail", + "base": "VnModel", + "options": { + "mysql": { + "table": "holidayDetail" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "description": { + "type": "String" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/modules/worker/back/models/holiday-type.json b/modules/worker/back/models/holiday-type.json new file mode 100644 index 000000000..6e40a62c7 --- /dev/null +++ b/modules/worker/back/models/holiday-type.json @@ -0,0 +1,29 @@ +{ + "name": "HolidayType", + "base": "VnModel", + "options": { + "mysql": { + "table": "holidayType" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "name": { + "type": "String" + }, + "rgb": { + "type": "String" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/modules/worker/back/models/holiday.js b/modules/worker/back/models/holiday.js new file mode 100644 index 000000000..107452dd5 --- /dev/null +++ b/modules/worker/back/models/holiday.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/holiday/getByWarehouse')(Self); +}; diff --git a/modules/worker/back/models/holiday.json b/modules/worker/back/models/holiday.json new file mode 100644 index 000000000..678910f0a --- /dev/null +++ b/modules/worker/back/models/holiday.json @@ -0,0 +1,45 @@ +{ + "name": "Holiday", + "base": "VnModel", + "options": { + "mysql": { + "table": "holiday" + } + }, + "properties": { + "holidayDetailFk": { + "id": true, + "type": "Number" + }, + "holidayTypeFk": { + "id": true, + "type": "Number" + }, + "dated": { + "type": "Date" + } + }, + "relations": { + "detail": { + "type": "belongsTo", + "model": "HolidayDetail", + "foreignKey": "holidayDetailFk" + }, + "type": { + "type": "belongsTo", + "model": "HolidayType", + "foreignKey": "holidayTypeFk" + }, + "workCenter": { + "type": "belongsTo", + "model": "WorkCenter", + "foreignKey": "workCenterFk" + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} \ No newline at end of file diff --git a/modules/worker/back/models/work-center-holiday.json b/modules/worker/back/models/work-center-holiday.json new file mode 100644 index 000000000..eddfd7af1 --- /dev/null +++ b/modules/worker/back/models/work-center-holiday.json @@ -0,0 +1,34 @@ +{ + "name": "WorkCenterHoliday", + "base": "VnModel", + "options": { + "mysql": { + "table": "workCenterHoliday" + } + }, + "properties": { + "workCenterFk": { + "id": true, + "type": "Number" + }, + "days": { + "type": "Number" + }, + "year": { + "type": "Number" + } + }, + "relations": { + "workCenter": { + "type": "belongsTo", + "model": "WorkCenter", + "foreignKey": "workCenterFk" + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} \ No newline at end of file diff --git a/modules/worker/back/models/work-center.json b/modules/worker/back/models/work-center.json new file mode 100644 index 000000000..03a335022 --- /dev/null +++ b/modules/worker/back/models/work-center.json @@ -0,0 +1,36 @@ +{ + "name": "WorkCenter", + "base": "VnModel", + "options": { + "mysql": { + "table": "workCenter" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "name": { + "type": "String" + } + }, + "relations": { + "warehouse": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseFk" + }, + "holidays": { + "type": "hasMany", + "model": "Holiday", + "foreignKey": "workCenterFk" + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} \ No newline at end of file diff --git a/modules/worker/back/models/worker-calendar.js b/modules/worker/back/models/worker-calendar.js new file mode 100644 index 000000000..ea603af41 --- /dev/null +++ b/modules/worker/back/models/worker-calendar.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/worker-calendar/absences')(Self); +}; diff --git a/modules/worker/back/models/worker-calendar.json b/modules/worker/back/models/worker-calendar.json new file mode 100644 index 000000000..569d4d1ba --- /dev/null +++ b/modules/worker/back/models/worker-calendar.json @@ -0,0 +1,35 @@ +{ + "name": "WorkerCalendar", + "base": "VnModel", + "options": { + "mysql": { + "table": "workerCalendar" + } + }, + "properties": { + "businessFk": { + "id": 1, + "type": "Number" + }, + "workerFk": { + "id": 2, + "type": "Number" + }, + "dated": { + "id": 3, + "type": "Date" + } + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "absenceType": { + "type": "belongsTo", + "model": "AbsenceType", + "foreignKey": "absenceTypeFk" + } + } +} diff --git a/modules/worker/back/models/worker-department.json b/modules/worker/back/models/worker-department.json new file mode 100644 index 000000000..0eeca50e7 --- /dev/null +++ b/modules/worker/back/models/worker-department.json @@ -0,0 +1,30 @@ +{ + "name": "WorkerDepartment", + "base": "VnModel", + "options": { + "mysql": { + "table": "workerDepartment" + } + }, + "properties": { + "workerFk": { + "id": true, + "type": "Number" + }, + "departmentFk": { + "type": "Number" + } + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "department": { + "type": "belongsTo", + "model": "Department", + "foreignKey": "departmentFk" + } + } +} diff --git a/modules/worker/back/models/worker-dms.js b/modules/worker/back/models/worker-dms.js new file mode 100644 index 000000000..4504b4ed4 --- /dev/null +++ b/modules/worker/back/models/worker-dms.js @@ -0,0 +1,4 @@ +module.exports = Self => { + require('../methods/worker-dms/removeFile')(Self); + require('../methods/worker-dms/allowedContentTypes')(Self); +}; diff --git a/modules/worker/back/models/worker-dms.json b/modules/worker/back/models/worker-dms.json new file mode 100644 index 000000000..56cad65a6 --- /dev/null +++ b/modules/worker/back/models/worker-dms.json @@ -0,0 +1,47 @@ +{ + "name": "WorkerDms", + "base": "Loggable", + "log": { + "model":"ClientLog", + "relation": "worker", + "showField": "dmsFk" + }, + "options": { + "mysql": { + "table": "workerDocument" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true + }, + "dmsFk": { + "type": "Number", + "required": true, + "mysql": { + "columnName": "document" + } + }, + "workerFk": { + "type": "Number", + "required": true, + "mysql": { + "columnName": "worker" + } + } + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "dms": { + "type": "belongsTo", + "model": "Dms", + "foreignKey": "dmsFk" + } + } +} + diff --git a/modules/worker/back/models/worker-labour.json b/modules/worker/back/models/worker-labour.json new file mode 100644 index 000000000..eae28cf89 --- /dev/null +++ b/modules/worker/back/models/worker-labour.json @@ -0,0 +1,43 @@ +{ + "name": "WorkerLabour", + "base": "VnModel", + "options": { + "mysql": { + "table": "workerLabour" + } + }, + "properties": { + "businessFk": { + "id": true, + "type": "Number" + }, + "started": { + "type": "Date" + }, + "ended": { + "type": "Date" + } + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "department": { + "type": "belongsTo", + "model": "Department", + "foreignKey": "departmentFk" + }, + "workCenter": { + "type": "belongsTo", + "model": "WorkCenter", + "foreignKey": "workCenterFk" + }, + "holidays": { + "type": "belongsTo", + "model": "WorkCenterHoliday", + "foreignKey": "workCenterFk" + } + } +} diff --git a/modules/worker/back/models/worker-mana.js b/modules/worker/back/models/worker-mana.js new file mode 100644 index 000000000..99a0f7694 --- /dev/null +++ b/modules/worker/back/models/worker-mana.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/worker-mana/getCurrentWorkerMana')(Self); +}; diff --git a/modules/worker/back/models/worker-mana.json b/modules/worker/back/models/worker-mana.json new file mode 100644 index 000000000..8de7c1fe1 --- /dev/null +++ b/modules/worker/back/models/worker-mana.json @@ -0,0 +1,25 @@ +{ + "name": "WorkerMana", + "base": "VnModel", + "options": { + "mysql": { + "table": "bs.workerMana" + } + }, + "properties": { + "amount": { + "type": "Number" + }, + "workerFk": { + "id": true, + "type": "Number" + } + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + } + } +} diff --git a/modules/worker/back/models/worker-media.json b/modules/worker/back/models/worker-media.json new file mode 100644 index 000000000..805ff383b --- /dev/null +++ b/modules/worker/back/models/worker-media.json @@ -0,0 +1,25 @@ +{ + "name": "WorkerMedia", + "base": "VnModel", + "options": { + "mysql": { + "table": "workerMedia" + } + }, + "properties": { + "workerFk": { + "id": true, + "type": "Number" + }, + "mediaValue": { + "type": "String" + } + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + } + } +} diff --git a/modules/worker/back/models/worker-team-collegues.json b/modules/worker/back/models/worker-team-collegues.json new file mode 100644 index 000000000..2e4a0a4f8 --- /dev/null +++ b/modules/worker/back/models/worker-team-collegues.json @@ -0,0 +1,26 @@ +{ + "name": "WorkerTeamCollegues", + "base": "VnModel", + "options": { + "mysql": { + "table": "workerTeamCollegues" + } + }, + "properties": { + "workerFk": { + "id": true, + "type": "Number" + }, + "collegueFk": { + "id": true, + "type": "Number" + } + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + } + } +} \ No newline at end of file diff --git a/modules/worker/back/models/worker-team.json b/modules/worker/back/models/worker-team.json new file mode 100644 index 000000000..4cd4b1244 --- /dev/null +++ b/modules/worker/back/models/worker-team.json @@ -0,0 +1,31 @@ +{ + "name": "WorkerTeam", + "base": "VnModel", + "options": { + "mysql": { + "table": "workerTeam" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "team": { + "type": "Number" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "Id_Trabajador" + } + } +} \ No newline at end of file diff --git a/modules/worker/back/models/worker-time-control.js b/modules/worker/back/models/worker-time-control.js new file mode 100644 index 000000000..f0191c36f --- /dev/null +++ b/modules/worker/back/models/worker-time-control.js @@ -0,0 +1,13 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + require('../methods/worker-time-control/filter')(Self); + require('../methods/worker-time-control/addTimeEntry')(Self); + require('../methods/worker-time-control/deleteTimeEntry')(Self); + + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError(`The introduced hour already exists`); + return err; + }); +}; diff --git a/modules/worker/back/models/worker-time-control.json b/modules/worker/back/models/worker-time-control.json new file mode 100644 index 000000000..5212222bd --- /dev/null +++ b/modules/worker/back/models/worker-time-control.json @@ -0,0 +1,44 @@ +{ + "name": "WorkerTimeControl", + "base": "VnModel", + "options": { + "mysql": { + "table": "workerTimeControl" + } + }, + "properties": { + "id": { + "id": true, + "type": "Number" + }, + "timed": { + "type": "Date" + }, + "manual": { + "type": "Boolean" + }, + "order": { + "type": "Number" + }, + "direction": { + "type": "string" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + }, + "worker": { + "type": "hasOne", + "model": "Worker", + "foreignKey": "userFk" + }, + "warehouse": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseFk" + } + } +} diff --git a/modules/worker/back/models/worker.js b/modules/worker/back/models/worker.js new file mode 100644 index 000000000..692c8c735 --- /dev/null +++ b/modules/worker/back/models/worker.js @@ -0,0 +1,7 @@ +module.exports = Self => { + require('../methods/worker/filter')(Self); + require('../methods/worker/mySubordinates')(Self); + require('../methods/worker/isSubordinate')(Self); + require('../methods/worker/getWorkedHours')(Self); + require('../methods/worker/uploadFile')(Self); +}; diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json new file mode 100644 index 000000000..c5c770fcd --- /dev/null +++ b/modules/worker/back/models/worker.json @@ -0,0 +1,65 @@ +{ + "name": "Worker", + "description": "Company employees", + "base": "VnModel", + "options": { + "mysql": { + "table": "worker" + } + }, + "properties": { + "id": { + "type": "Number", + "id": true, + "description": "Identifier" + }, + "firstName": { + "type": "string", + "required": true + }, + "lastName": { + "type": "string", + "required": true + }, + "phone": { + "type" : "String" + }, + "userFk": { + "type" : "Number", + "required": true + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "Account", + "foreignKey": "userFk" + }, + "client": { + "type": "belongsTo", + "model": "Client", + "foreignKey": "userFk" + }, + "sip": { + "type": "belongsTo", + "model": "Sip", + "foreignKey": "userFk" + }, + "department": { + "type": "belongsTo", + "model": "WorkerDepartment", + "foreignKey": "id" + }, + "collegues": { + "type": "hasMany", + "model": "WorkerTeamCollegues", + "foreignKey": "workerFk" + }, + "phones": { + "type": "hasMany", + "model": "UserPhone", + "foreignKey": "userFk", + "primaryKey": "userFk" + } + } +} \ No newline at end of file diff --git a/modules/worker/front/account/index.html b/modules/worker/front/account/index.html new file mode 100644 index 000000000..f51876a07 --- /dev/null +++ b/modules/worker/front/account/index.html @@ -0,0 +1,33 @@ + + + + +
    + + + + + + + + + + + + + +
    diff --git a/modules/worker/front/basic-data/index.html b/modules/worker/front/basic-data/index.html new file mode 100644 index 000000000..1d0d705e7 --- /dev/null +++ b/modules/worker/front/basic-data/index.html @@ -0,0 +1,32 @@ + + +
    + + + + + + + + + + + + + + +
    diff --git a/modules/worker/front/basic-data/index.js b/modules/worker/front/basic-data/index.js new file mode 100644 index 000000000..28107dc12 --- /dev/null +++ b/modules/worker/front/basic-data/index.js @@ -0,0 +1,24 @@ +import ngModule from '../module'; + +class Controller { + constructor($) { + Object.assign(this, {$}); + } + + onSubmit() { + this.$.watcher.submit() + .then(() => this.card.reload()); + } +} +Controller.$inject = ['$scope']; + +ngModule.component('vnWorkerBasicData', { + template: require('./index.html'), + controller: Controller, + bindings: { + worker: '<' + }, + require: { + card: '^vnWorkerCard' + } +}); diff --git a/modules/worker/front/calendar/index.html b/modules/worker/front/calendar/index.html new file mode 100644 index 000000000..08b3f469c --- /dev/null +++ b/modules/worker/front/calendar/index.html @@ -0,0 +1,37 @@ + + +
    + + + + +
    + +
    +
    +
    Holidays
    +
    + {{'Used' | translate}} {{$ctrl.calendar.holidaysEnjoyed}} + {{'of' | translate}} {{$ctrl.calendar.totalHolidays}} {{'days' | translate}} +
    +
    +
    + + + + {{absenceType.name}} + +
    +
    +
    \ No newline at end of file diff --git a/modules/worker/front/calendar/index.js b/modules/worker/front/calendar/index.js new file mode 100644 index 000000000..1860f6bdd --- /dev/null +++ b/modules/worker/front/calendar/index.js @@ -0,0 +1,114 @@ +import ngModule from '../module'; +import './style.scss'; + +class Controller { + constructor($element, $http) { + this.element = $element[0]; + this.$http = $http; + this.date = new Date(); + this.events = {}; + } + + get date() { + return this._date; + } + + set date(value) { + this._date = value; + value.setHours(0, 0, 0, 0); + + const started = new Date(value.getTime()); + started.setMonth(0); + started.setDate(1); + this.started = started; + + const ended = new Date(value.getTime()); + ended.setMonth(12); + ended.setDate(0); + this.ended = ended; + + this.months = new Array(12); + + for (let i = 0; i < this.months.length; i++) { + const now = new Date(value.getTime()); + now.setDate(1); + now.setMonth(i); + this.months[i] = now; + } + } + + get worker() { + return this._worker; + } + + set worker(value) { + this._worker = value; + if (!value) return; + + let params = { + workerFk: this.worker.id, + started: this.started, + ended: this.ended + }; + this.$http.get(`WorkerCalendars/absences`, {params}) + .then(res => this.onData(res.data)); + } + + onData(data) { + this.events = {}; + this.calendar = data.calendar; + + let addEvent = (day, event) => { + this.events[new Date(day).getTime()] = event; + }; + + if (data.holidays) { + data.holidays.forEach(holiday => { + const holidayDetail = holiday.detail && holiday.detail.description; + const holidayType = holiday.type && holiday.type.name; + const holidayName = holidayDetail || holidayType; + + addEvent(holiday.dated, { + name: holidayName, + color: '#ff0' + }); + }); + } + if (data.absences) { + data.absences.forEach(absence => { + let type = absence.absenceType; + addEvent(absence.dated, { + name: type.name, + color: type.rgb + }); + }); + } + + this.repaint(); + } + + repaint() { + let calendars = this.element.querySelectorAll('vn-calendar'); + for (let calendar of calendars) + calendar.$ctrl.repaint(); + } + + formatDay(day, element) { + let event = this.events[day.getTime()]; + if (!event) return; + + let dayNumber = element.firstElementChild; + dayNumber.title = event.name; + dayNumber.style.backgroundColor = event.color; + dayNumber.style.color = 'rgba(0, 0, 0, 0.7)'; + } +} +Controller.$inject = ['$element', '$http']; + +ngModule.component('vnWorkerCalendar', { + template: require('./index.html'), + controller: Controller, + bindings: { + worker: '<' + } +}); diff --git a/modules/worker/front/calendar/index.spec.js b/modules/worker/front/calendar/index.spec.js new file mode 100644 index 000000000..2f85e3a1a --- /dev/null +++ b/modules/worker/front/calendar/index.spec.js @@ -0,0 +1,109 @@ +import './index'; + +describe('Worker', () => { + describe('Component vnWorkerCalendar', () => { + let $httpBackend; + let $scope; + let $element; + let controller; + let year = new Date().getFullYear(); + + beforeEach(ngModule('worker')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_) => { + $scope = $rootScope.$new(); + $httpBackend = _$httpBackend_; + $element = angular.element('
    '); + controller = $componentController('vnWorkerCalendar', {$element, $scope}); + })); + + afterEach(() => { + $element.remove(); + $scope.$destroy(); + }); + + describe('started property', () => { + it(`should return first day and month of current year`, () => { + let started = new Date(year, 0, 1); + + expect(controller.started).toEqual(started); + }); + }); + + describe('ended property', () => { + it(`should return last day and month of current year`, () => { + let ended = new Date(year, 11, 31); + + expect(controller.ended).toEqual(ended); + }); + }); + + describe('months property', () => { + it(`should return an array of twelve months length`, () => { + const ended = new Date(year, 11, 1); + + expect(controller.months.length).toEqual(12); + expect(controller.months[0]).toEqual(controller.started); + expect(controller.months[11]).toEqual(ended); + }); + }); + + describe('worker() setter', () => { + it(`should perform a get query and set the reponse data on the model`, () => { + let today = new Date(); + + let tomorrow = new Date(today.getTime()); + tomorrow.setDate(tomorrow.getDate() + 1); + + let yesterday = new Date(today.getTime()); + yesterday.setDate(yesterday.getDate() - 1); + + $httpBackend.whenRoute('GET', 'WorkerCalendars/absences') + .respond({ + holidays: [ + {dated: today, detail: {description: 'New year'}}, + {dated: tomorrow, detail: {description: 'Easter'}} + ], + absences: [ + {dated: today, absenceType: {name: 'Holiday', rgb: '#aaa'}}, + {dated: yesterday, absenceType: {name: 'Leave', rgb: '#bbb'}} + ] + }); + + controller.worker = {id: 1}; + $httpBackend.flush(); + + let events = controller.events; + + expect(events[today.getTime()].name).toEqual('Holiday'); + expect(events[tomorrow.getTime()].name).toEqual('Easter'); + expect(events[yesterday.getTime()].name).toEqual('Leave'); + expect(events[yesterday.getTime()].color).toEqual('#bbb'); + }); + }); + + describe('formatDay()', () => { + it(`should set the day element style`, () => { + let today = new Date(); + + $httpBackend.whenRoute('GET', 'WorkerCalendars/absences') + .respond({ + absences: [ + {dated: today, absenceType: {name: 'Holiday', rgb: '#000'}} + ] + }); + + controller.worker = {id: 1}; + $httpBackend.flush(); + + let dayElement = angular.element('
    ')[0]; + let dayNumber = dayElement.firstElementChild; + + controller.formatDay(today, dayElement); + + expect(dayNumber.title).toEqual('Holiday'); + expect(dayNumber.style.backgroundColor).toEqual('rgb(0, 0, 0)'); + }); + }); + }); +}); diff --git a/modules/worker/front/calendar/locale/es.yml b/modules/worker/front/calendar/locale/es.yml new file mode 100644 index 000000000..82939ce91 --- /dev/null +++ b/modules/worker/front/calendar/locale/es.yml @@ -0,0 +1,5 @@ +Calendar: Calendario +Holidays: Vacaciones +Used: Utilizados +of: de +days: días \ No newline at end of file diff --git a/modules/worker/front/calendar/style.scss b/modules/worker/front/calendar/style.scss new file mode 100644 index 000000000..e622dda64 --- /dev/null +++ b/modules/worker/front/calendar/style.scss @@ -0,0 +1,19 @@ +@import "variables"; + +vn-worker-calendar { + .calendars { + display: flex; + flex-wrap: wrap; + justify-content: center; + align-items: center; + box-sizing: border-box; + padding: $spacing-md; + + & > vn-calendar { + border: 1px solid #ddd; + margin: $spacing-md; + padding: $spacing-xs; + max-width: 18em; + } + } +} diff --git a/modules/worker/front/card/index.html b/modules/worker/front/card/index.html new file mode 100644 index 000000000..ba9c8ec53 --- /dev/null +++ b/modules/worker/front/card/index.html @@ -0,0 +1,5 @@ + + + + + diff --git a/modules/worker/front/card/index.js b/modules/worker/front/card/index.js new file mode 100644 index 000000000..dd2a24448 --- /dev/null +++ b/modules/worker/front/card/index.js @@ -0,0 +1,49 @@ +import ngModule from '../module'; +import ModuleCard from 'salix/components/module-card'; + +class Controller extends ModuleCard { + reload() { + let filter = { + include: [ + { + relation: 'user', + scope: { + fields: ['name'], + include: { + relation: 'emailUser', + scope: { + fields: ['email'] + } + } + } + }, { + relation: 'sip', + scope: { + fields: ['extension', 'secret'] + } + }, { + relation: 'department', + scope: { + include: { + relation: 'department' + } + } + }, { + relation: 'phones', + scope: { + fields: ['phone'], + order: 'typeFk ASC' + } + } + ] + }; + + this.$http.get(`Workers/${this.$params.id}`, {filter}) + .then(res => this.worker = res.data); + } +} + +ngModule.component('vnWorkerCard', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/worker/front/department/index.html b/modules/worker/front/department/index.html new file mode 100644 index 000000000..d50d33ace --- /dev/null +++ b/modules/worker/front/department/index.html @@ -0,0 +1,45 @@ + + +
    + + + {{::item.name}} + + +
    + + + + + +
    New department
    + + + + +
    + + + + +
    diff --git a/modules/worker/front/department/index.js b/modules/worker/front/department/index.js new file mode 100644 index 000000000..28c2cfa99 --- /dev/null +++ b/modules/worker/front/department/index.js @@ -0,0 +1,95 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope, $http, vnApp, $translate) { + this.$ = $scope; + this.$http = $http; + this.vnApp = vnApp; + this.$translate = $translate; + } + + $postLink() { + this.$.treeview.fetch(); + } + + onFetch(item) { + const params = item ? {parentId: item.id} : null; + return this.$.model.applyFilter({}, params).then(() => { + return this.$.model.data; + }); + } + + onSort(a, b) { + return a.name.localeCompare(b.name); + } + + onDrop(dropped, dragged) { + const params = dropped ? {parentId: dropped.id} : null; + const query = `departments/${dragged.id}/moveChild`; + this.$http.post(query, params).then(() => { + this.$.treeview.move(dragged, dropped); + }); + } + + onCreate(parent) { + this.newChild = { + parent: parent, + name: '' + }; + + this.$.createNode.show(); + } + + onCreateDialogOpen() { + this.newChild.name = ''; + } + + onCreateResponse(response) { + if (response == 'accept') { + try { + if (!this.newChild.name) + throw new Error(`Name can't be empty`); + + const params = {name: this.newChild.name}; + const parent = this.newChild.parent; + + if (parent && parent.id) + params.parentId = parent.id; + + const query = `departments/createChild`; + this.$http.post(query, params).then(res => { + const item = res.data; + item.parent = parent; + + this.$.treeview.create(item); + }); + } catch (e) { + this.vnApp.showError(this.$translate.instant(e.message)); + return false; + } + } + return true; + } + + onRemove(item) { + this.removedChild = item; + this.$.deleteNode.show(); + } + + onRemoveResponse(response) { + if (response === 'accept') { + const childId = this.removedChild.id; + const path = `departments/${childId}/removeChild`; + this.$http.post(path).then(() => { + this.$.treeview.remove(this.removedChild); + }); + } + } +} + +Controller.$inject = ['$scope', '$http', 'vnApp', '$translate']; + +ngModule.component('vnWorkerDepartment', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/worker/front/department/locale/es.yml b/modules/worker/front/department/locale/es.yml new file mode 100644 index 000000000..c481bf4a9 --- /dev/null +++ b/modules/worker/front/department/locale/es.yml @@ -0,0 +1,3 @@ +New department: Nuevo departamento +Delete department: Eliminar departamento +Are you sure you want to delete it?: ¿Seguro que quieres eliminarlo? \ No newline at end of file diff --git a/modules/worker/front/descriptor-popover/index.html b/modules/worker/front/descriptor-popover/index.html new file mode 100644 index 000000000..21f32f0c2 --- /dev/null +++ b/modules/worker/front/descriptor-popover/index.html @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/modules/worker/front/descriptor-popover/index.js b/modules/worker/front/descriptor-popover/index.js new file mode 100644 index 000000000..b648e8bd2 --- /dev/null +++ b/modules/worker/front/descriptor-popover/index.js @@ -0,0 +1,97 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + constructor($element, $scope, $http, $timeout, $q) { + super($element, $scope); + this.$timeout = $timeout; + this.$http = $http; + this.$q = $q; + this.worker = null; + this._quicklinks = {}; + } + + set workerFk(workerFk) { + if (workerFk == this._workerFk) return; + + this._workerFk = workerFk; + this.worker = null; + this.loadData(); + } + + get workerFk() { + return this._workerFk; + } + + get quicklinks() { + return this._quicklinks; + } + + set quicklinks(value = {}) { + Object.keys(value).forEach(key => { + this._quicklinks[key] = value[key]; + }); + } + + show() { + this.$.popover.parent = this.parent; + this.$.popover.show(); + } + + loadData() { + let query = `Workers/findOne`; + let filter = { + where: { + id: this._workerFk + }, + include: [ + { + relation: 'user', + scope: { + fields: ['name'], + include: { + relation: 'emailUser', + scope: { + fields: ['email'] + } + } + } + }, + { + relation: 'client', + scope: {fields: ['fi']} + }, + { + relation: 'sip', + scope: {fields: ['extension']} + }, + { + relation: 'department', + scope: { + include: { + relation: 'department' + } + } + } + ] + }; + + this.$http.get(query, {params: {filter}}).then(res => { + this.worker = res.data; + this.$.$applyAsync(() => { + this.$.popover.relocate(); + }); + }); + } +} +Controller.$inject = ['$element', '$scope', '$http', '$timeout', '$q']; + +ngModule.component('vnWorkerDescriptorPopover', { + template: require('./index.html'), + controller: Controller, + bindings: { + workerFk: '<', + quicklinks: '<' + } +}); diff --git a/modules/worker/front/descriptor-popover/index.spec.js b/modules/worker/front/descriptor-popover/index.spec.js new file mode 100644 index 000000000..14fe07ee1 --- /dev/null +++ b/modules/worker/front/descriptor-popover/index.spec.js @@ -0,0 +1,105 @@ +import './index.js'; + +describe('worker Component vnWorkerDescriptorPopover', () => { + let $httpBackend; + let $httpParamSerializer; + let $scope; + let controller; + let $element; + + beforeEach(ngModule('worker')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_) => { + $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; + $element = angular.element(`
    `); + $scope = $rootScope.$new(); + $scope.popover = {relocate: () => {}, show: () => {}}; + controller = $componentController('vnWorkerDescriptorPopover', {$scope, $element}); + })); + + describe('workerFk()', () => { + it(`should not apply any changes if the received id is the same stored in _workerFk`, () => { + controller.worker = 'I exist!'; + controller._workerFk = 1; + spyOn(controller, 'loadData'); + controller.workerFk = 1; + + expect(controller.worker).toEqual('I exist!'); + expect(controller._workerFk).toEqual(1); + expect(controller.loadData).not.toHaveBeenCalled(); + }); + + it(`should set the received id into _workerFk, set the worker to null and then call loadData()`, () => { + controller.worker = `Please don't`; + controller._workerFk = 1; + spyOn(controller, 'loadData'); + controller.workerFk = 999; + + expect(controller.worker).toBeNull(); + expect(controller._workerFk).toEqual(999); + expect(controller.loadData).toHaveBeenCalledWith(); + }); + }); + + describe('show()', () => { + it(`should call the show()`, () => { + spyOn(controller.$.popover, 'show'); + controller.show(); + + expect(controller.$.popover.show).toHaveBeenCalledWith(); + }); + }); + + describe('loadData()', () => { + it(`should perform a get query to store the worker data into the controller`, () => { + controller.workerFk = 1; + controller.canceler = null; + let response = {}; + + let config = { + filter: { + where: { + id: controller.workerFk + }, + include: [ + { + relation: 'user', + scope: { + fields: ['name'], + include: { + relation: 'emailUser', + scope: { + fields: ['email'] + } + } + } + }, { + relation: 'client', + scope: {fields: ['fi']} + }, { + relation: 'sip', + scope: {fields: ['extension']} + }, { + relation: 'department', + scope: { + include: { + relation: 'department' + } + } + } + ] + } + }; + + let json = $httpParamSerializer(config); + + $httpBackend.whenGET(`Workers/findOne?${json}`).respond(response); + $httpBackend.expectGET(`Workers/findOne?${json}`); + controller.loadData(); + $httpBackend.flush(); + + expect(controller.worker).toEqual(response); + }); + }); +}); diff --git a/modules/worker/front/descriptor-popover/style.scss b/modules/worker/front/descriptor-popover/style.scss new file mode 100644 index 000000000..58e65d320 --- /dev/null +++ b/modules/worker/front/descriptor-popover/style.scss @@ -0,0 +1,11 @@ +vn-ticket-descriptor-popover { + vn-ticket-descriptor { + display: block; + width: 16em; + max-height: 28em; + + & > vn-card { + margin: 0!important; + } + } +} \ No newline at end of file diff --git a/modules/worker/front/descriptor/index.html b/modules/worker/front/descriptor/index.html new file mode 100644 index 000000000..26c2f193e --- /dev/null +++ b/modules/worker/front/descriptor/index.html @@ -0,0 +1,41 @@ +
    + + + + + + + + + +
    +
    +
    + {{$ctrl.worker.firstName}} {{$ctrl.worker.lastName}} +
    + + + + + + + + + + + + +
    + + +
    +
    \ No newline at end of file diff --git a/modules/worker/front/descriptor/index.js b/modules/worker/front/descriptor/index.js new file mode 100644 index 000000000..6dab06958 --- /dev/null +++ b/modules/worker/front/descriptor/index.js @@ -0,0 +1,45 @@ +import ngModule from '../module'; + +class Controller { + constructor($http, $state) { + this.$state = $state; + this.$http = $http; + } + + get worker() { + return this._worker; + } + + set worker(value) { + this._worker = value; + + if (!value) return; + + this._quicklinks = { + btnOne: { + icon: 'person', + state: `client.card.summary({id: ${value.userFk}})`, + tooltip: 'Go to client' + } + }; + } + + set quicklinks(value = {}) { + this._quicklinks = Object.assign(value, this._quicklinks); + } + + get quicklinks() { + return this._quicklinks; + } +} + +Controller.$inject = ['$http', '$state']; + + +ngModule.component('vnWorkerDescriptor', { + template: require('./index.html'), + controller: Controller, + bindings: { + worker: '<' + } +}); diff --git a/modules/worker/front/dms/create/index.html b/modules/worker/front/dms/create/index.html new file mode 100644 index 000000000..dcafa5986 --- /dev/null +++ b/modules/worker/front/dms/create/index.html @@ -0,0 +1,83 @@ + + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    diff --git a/modules/worker/front/dms/create/index.js b/modules/worker/front/dms/create/index.js new file mode 100644 index 000000000..e7bfe7bfd --- /dev/null +++ b/modules/worker/front/dms/create/index.js @@ -0,0 +1,114 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + constructor($element, $, vnConfig) { + super($element, $); + this.vnConfig = vnConfig; + this.dms = { + files: [], + hasFile: false, + hasFileAttached: false + }; + } + + get worker() { + return this._worker; + } + + set worker(value) { + this._worker = value; + + if (value) { + this.setDefaultParams(); + this.getAllowedContentTypes(); + } + } + + getAllowedContentTypes() { + this.$http.get('workerDms/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + + get contentTypesInfo() { + return this.$translate.instant('ContentTypesInfo', { + allowedContentTypes: this.allowedContentTypes + }); + } + + setDefaultParams() { + const params = {filter: { + where: {code: 'hhrrData'} + }}; + this.$http.get('DmsTypes/findOne', {params}).then(res => { + const dmsType = res.data && res.data; + const companyId = this.vnConfig.companyFk; + const warehouseId = this.vnConfig.warehouseFk; + const defaultParams = { + reference: this.worker.id, + warehouseId: warehouseId, + companyId: companyId, + dmsTypeId: dmsType.id, + description: this.$translate.instant('WorkerFileDescription', { + dmsTypeName: dmsType.name, + workerId: this.worker.id, + workerName: this.worker.name + }).toUpperCase() + }; + + this.dms = Object.assign(this.dms, defaultParams); + }); + } + + onSubmit() { + const query = `Workers/${this.worker.id}/uploadFile`; + const options = { + method: 'POST', + url: query, + params: this.dms, + headers: { + 'Content-Type': undefined + }, + transformRequest: files => { + const formData = new FormData(); + + for (let i = 0; i < files.length; i++) + formData.append(files[i].name, files[i]); + + return formData; + }, + data: this.dms.files + }; + this.$http(options).then(res => { + if (res) { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$.watcher.updateOriginalData(); + this.$state.go('worker.card.dms.index'); + } + }); + } + + onFileChange(files) { + let hasFileAttached = false; + + if (files.length > 0) + hasFileAttached = true; + + this.$.$applyAsync(() => { + this.dms.hasFileAttached = hasFileAttached; + }); + } +} + +Controller.$inject = ['$element', '$scope', 'vnConfig']; + +ngModule.component('vnWorkerDmsCreate', { + template: require('./index.html'), + controller: Controller, + bindings: { + worker: '<' + } +}); diff --git a/modules/worker/front/dms/create/index.spec.js b/modules/worker/front/dms/create/index.spec.js new file mode 100644 index 000000000..41fe0e0ca --- /dev/null +++ b/modules/worker/front/dms/create/index.spec.js @@ -0,0 +1,77 @@ +import './index'; + +describe('Client', () => { + describe('Component vnWorkerDmsCreate', () => { + let $element; + let controller; + let $scope; + let $httpBackend; + let $httpParamSerializer; + + beforeEach(ngModule('worker')); + + beforeEach(angular.mock.inject(($compile, $rootScope, _$httpBackend_, _$httpParamSerializer_) => { + $scope = $rootScope.$new(); + $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; + $element = $compile(``)($rootScope); + controller = $element.controller('vnWorkerDmsCreate'); + controller._worker = {id: 101, name: 'Bruce wayne'}; + })); + + describe('worker() setter', () => { + it('should set the worker data and then call setDefaultParams() and getAllowedContentTypes()', () => { + spyOn(controller, 'setDefaultParams'); + spyOn(controller, 'getAllowedContentTypes'); + controller.worker = { + id: 15, + name: 'Bruce wayne' + }; + + expect(controller.worker).toBeDefined(); + expect(controller.setDefaultParams).toHaveBeenCalledWith(); + expect(controller.getAllowedContentTypes).toHaveBeenCalledWith(); + }); + }); + + describe('setDefaultParams()', () => { + it('should perform a GET query and define the dms property on controller', () => { + $httpBackend.whenRoute('GET', `DmsTypes`).respond({id: 12, code: 'hhrrData'}); + const params = {filter: { + where: {code: 'hhrrData'} + }}; + let serializedParams = $httpParamSerializer(params); + $httpBackend.when('GET', `DmsTypes/findOne?${serializedParams}`).respond({id: 12, code: 'hhrrData'}); + controller.setDefaultParams(); + $httpBackend.flush(); + + expect(controller.dms).toBeDefined(); + expect(controller.dms.reference).toEqual(101); + expect(controller.dms.dmsTypeId).toEqual(12); + }); + }); + + describe('onFileChange()', () => { + it('should set dms hasFileAttached property to true if has any files', () => { + const files = [{id: 1, name: 'MyFile'}]; + controller.onFileChange(files); + $scope.$apply(); + + expect(controller.dms.hasFileAttached).toBeTruthy(); + }); + }); + + describe('getAllowedContentTypes()', () => { + it('should make an HTTP GET request to get the allowed content types', () => { + const expectedResponse = ['image/png', 'image/jpg']; + $httpBackend.when('GET', `workerDms/allowedContentTypes`).respond(expectedResponse); + $httpBackend.expect('GET', `workerDms/allowedContentTypes`); + controller.getAllowedContentTypes(); + $httpBackend.flush(); + + expect(controller.allowedContentTypes).toBeDefined(); + expect(controller.allowedContentTypes).toEqual('image/png, image/jpg'); + }); + }); + }); +}); diff --git a/modules/worker/front/dms/create/style.scss b/modules/worker/front/dms/create/style.scss new file mode 100644 index 000000000..73f136fc1 --- /dev/null +++ b/modules/worker/front/dms/create/style.scss @@ -0,0 +1,7 @@ +vn-ticket-request { + .vn-textfield { + margin: 0!important; + max-width: 100px; + } +} + diff --git a/modules/worker/front/dms/edit/index.html b/modules/worker/front/dms/edit/index.html new file mode 100644 index 000000000..13bf6f953 --- /dev/null +++ b/modules/worker/front/dms/edit/index.html @@ -0,0 +1,82 @@ + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    diff --git a/modules/worker/front/dms/edit/index.js b/modules/worker/front/dms/edit/index.js new file mode 100644 index 000000000..1a593414a --- /dev/null +++ b/modules/worker/front/dms/edit/index.js @@ -0,0 +1,94 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + get worker() { + return this._worker; + } + + set worker(value) { + this._worker = value; + + if (value) { + this.setDefaultParams(); + this.getAllowedContentTypes(); + } + } + + getAllowedContentTypes() { + this.$http.get('WorkerDms/allowedContentTypes').then(res => { + const contentTypes = res.data.join(', '); + this.allowedContentTypes = contentTypes; + }); + } + + get contentTypesInfo() { + return this.$translate.instant('ContentTypesInfo', { + allowedContentTypes: this.allowedContentTypes + }); + } + + setDefaultParams() { + const path = `Dms/${this.$params.dmsId}`; + this.$http.get(path).then(res => { + const dms = res.data && res.data; + this.dms = { + reference: dms.reference, + warehouseId: dms.warehouseFk, + companyId: dms.companyFk, + dmsTypeId: dms.dmsTypeFk, + description: dms.description, + hasFile: dms.hasFile, + hasFileAttached: false, + files: [] + }; + }); + } + + onSubmit() { + const query = `dms/${this.$params.dmsId}/updateFile`; + const options = { + method: 'POST', + url: query, + params: this.dms, + headers: { + 'Content-Type': undefined + }, + transformRequest: files => { + const formData = new FormData(); + + for (let i = 0; i < files.length; i++) + formData.append(files[i].name, files[i]); + + return formData; + }, + data: this.dms.files + }; + this.$http(options).then(res => { + if (res) { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.$.watcher.updateOriginalData(); + this.$state.go('worker.card.dms.index'); + } + }); + } + + onFileChange(files) { + let hasFileAttached = false; + if (files.length > 0) + hasFileAttached = true; + + this.$.$applyAsync(() => { + this.dms.hasFileAttached = hasFileAttached; + }); + } +} + +ngModule.component('vnWorkerDmsEdit', { + template: require('./index.html'), + controller: Controller, + bindings: { + worker: '<' + } +}); diff --git a/modules/worker/front/dms/edit/index.spec.js b/modules/worker/front/dms/edit/index.spec.js new file mode 100644 index 000000000..b883d4472 --- /dev/null +++ b/modules/worker/front/dms/edit/index.spec.js @@ -0,0 +1,84 @@ +import './index'; + +describe('Worker', () => { + describe('Component vnClientDmsEdit', () => { + let controller; + let $scope; + let $element; + let $httpBackend; + + beforeEach(ngModule('worker')); + + beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_) => { + $scope = $rootScope.$new(); + $httpBackend = _$httpBackend_; + $element = angular.element(` { + it('should set the worker data and then call setDefaultParams() and getAllowedContentTypes()', () => { + spyOn(controller, 'setDefaultParams'); + spyOn(controller, 'getAllowedContentTypes'); + controller._worker = undefined; + controller.worker = { + id: 106 + }; + + expect(controller.setDefaultParams).toHaveBeenCalledWith(); + expect(controller.worker).toBeDefined(); + expect(controller.getAllowedContentTypes).toHaveBeenCalledWith(); + }); + }); + + describe('setDefaultParams()', () => { + it('should perform a GET query and define the dms property on controller', () => { + const dmsId = 4; + const expectedResponse = { + reference: 101, + warehouseFk: 1, + companyFk: 442, + dmsTypeFk: 3, + description: 'Test', + hasFile: false, + hasFileAttached: false + }; + + $httpBackend.when('GET', `Dms/${dmsId}`).respond(expectedResponse); + $httpBackend.expect('GET', `Dms/${dmsId}`).respond(expectedResponse); + controller.setDefaultParams(); + $httpBackend.flush(); + + expect(controller.dms).toBeDefined(); + expect(controller.dms.reference).toEqual(101); + expect(controller.dms.dmsTypeId).toEqual(3); + }); + }); + + describe('onFileChange()', () => { + it('should set dms hasFileAttached property to true if has any files', () => { + const files = [{id: 1, name: 'MyFile'}]; + controller.dms = {hasFileAttached: false}; + controller.onFileChange(files); + $scope.$apply(); + + expect(controller.dms.hasFileAttached).toBeTruthy(); + }); + }); + + describe('getAllowedContentTypes()', () => { + it('should make an HTTP GET request to get the allowed content types', () => { + const expectedResponse = ['image/png', 'image/jpg']; + $httpBackend.when('GET', `WorkerDms/allowedContentTypes`).respond(expectedResponse); + $httpBackend.expect('GET', `WorkerDms/allowedContentTypes`); + controller.getAllowedContentTypes(); + $httpBackend.flush(); + + expect(controller.allowedContentTypes).toBeDefined(); + expect(controller.allowedContentTypes).toEqual('image/png, image/jpg'); + }); + }); + }); +}); diff --git a/modules/worker/front/dms/edit/style.scss b/modules/worker/front/dms/edit/style.scss new file mode 100644 index 000000000..73f136fc1 --- /dev/null +++ b/modules/worker/front/dms/edit/style.scss @@ -0,0 +1,7 @@ +vn-ticket-request { + .vn-textfield { + margin: 0!important; + max-width: 100px; + } +} + diff --git a/modules/worker/front/dms/index/index.html b/modules/worker/front/dms/index/index.html new file mode 100644 index 000000000..7859a50a4 --- /dev/null +++ b/modules/worker/front/dms/index/index.html @@ -0,0 +1,117 @@ + + + + + + + + Id + Type + Order + Reference + Description + Original + File + Employee + Created + + + + + + + + {{::document.dmsFk}} + + + {{::document.dms.dmsType.name}} + + + + + {{::document.dms.hardCopyNumber}} + + + + + {{::document.dms.reference}} + + + + + {{::document.dms.description}} + + + + + + + + {{::document.dms.file}} + + + + + {{::document.dms.worker.user.nickname | dashIfEmpty}} + + + {{::document.dms.created | date:'dd/MM/yyyy HH:mm'}} + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/worker/front/dms/index/index.js b/modules/worker/front/dms/index/index.js new file mode 100644 index 000000000..907047f97 --- /dev/null +++ b/modules/worker/front/dms/index/index.js @@ -0,0 +1,76 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; +import './style.scss'; + +class Controller extends Component { + constructor($element, $, vnToken) { + super($element, $); + this.accessToken = vnToken.token; + this.filter = { + include: { + relation: 'dms', + scope: { + fields: [ + 'dmsTypeFk', + 'reference', + 'hardCopyNumber', + 'workerFk', + 'description', + 'hasFile', + 'file', + 'created', + ], + include: [{ + relation: 'dmsType', + scope: { + fields: ['name'] + } + }, + { + relation: 'worker', + scope: { + fields: ['userFk'], + include: { + relation: 'user', + scope: { + fields: ['nickname'] + } + }, + } + }] + }, + } + }; + } + + showWorkerDescriptor(event, workerFk) { + event.preventDefault(); + event.stopImmediatePropagation(); + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.workerFk = workerFk; + this.$.workerDescriptor.show(); + } + + showDeleteConfirm(index) { + this.dmsIndex = index; + this.$.confirm.show(); + } + + deleteDms(response) { + if (response === 'accept') { + const dmsFk = this.workerDms[this.dmsIndex].dmsFk; + const query = `WorkerDms/${dmsFk}/removeFile`; + this.$http.post(query).then(() => { + this.$.model.remove(this.dmsIndex); + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + }); + } + } +} + +Controller.$inject = ['$element', '$scope', 'vnToken']; + +ngModule.component('vnWorkerDmsIndex', { + template: require('./index.html'), + controller: Controller, +}); diff --git a/modules/worker/front/dms/index/index.spec.js b/modules/worker/front/dms/index/index.spec.js new file mode 100644 index 000000000..6220d051c --- /dev/null +++ b/modules/worker/front/dms/index/index.spec.js @@ -0,0 +1,42 @@ +import './index'; +import crudModel from 'core/mocks/crud-model'; + +describe('Worker', () => { + describe('Component vnWorkerDmsIndex', () => { + let $componentController; + let $scope; + let $element; + let $httpBackend; + let controller; + + beforeEach(ngModule('worker')); + + beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_) => { + $componentController = _$componentController_; + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + $element = angular.element(` { + it('should make an HTTP Post query', () => { + const dmsId = 4; + const dmsIndex = 0; + spyOn(controller.vnApp, 'showSuccess'); + spyOn(controller.$.model, 'remove'); + controller.workerDms = [{dmsFk: 4}]; + controller.dmsIndex = dmsIndex; + + $httpBackend.when('POST', `WorkerDms/${dmsId}/removeFile`).respond({}); + $httpBackend.expect('POST', `WorkerDms/${dmsId}/removeFile`); + controller.deleteDms('accept'); + $httpBackend.flush(); + + expect(controller.$.model.remove).toHaveBeenCalledWith(dmsIndex); + expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); + }); + }); + }); +}); diff --git a/modules/worker/front/dms/index/locale/es.yml b/modules/worker/front/dms/index/locale/es.yml new file mode 100644 index 000000000..0994c7d86 --- /dev/null +++ b/modules/worker/front/dms/index/locale/es.yml @@ -0,0 +1,9 @@ +Type: Tipo +File management: Gestión documental +File: Fichero +Hard copy: Copia +This file will be deleted: Este fichero va a ser borrado +Are you sure?: Estas seguro? +File deleted: Fichero eliminado +Remove file: Eliminar fichero +Download file: Descargar fichero \ No newline at end of file diff --git a/modules/worker/front/dms/index/style.scss b/modules/worker/front/dms/index/style.scss new file mode 100644 index 000000000..a6758e2e6 --- /dev/null +++ b/modules/worker/front/dms/index/style.scss @@ -0,0 +1,6 @@ +vn-client-risk-index { + .totalBox { + display: table; + float: right; + } +} \ No newline at end of file diff --git a/modules/worker/front/dms/locale/en.yml b/modules/worker/front/dms/locale/en.yml new file mode 100644 index 000000000..766853fca --- /dev/null +++ b/modules/worker/front/dms/locale/en.yml @@ -0,0 +1,2 @@ +ClientFileDescription: "{{dmsTypeName}} from client {{clientName}} id {{clientId}}" +ContentTypesInfo: Allowed file types {{allowedContentTypes}} \ No newline at end of file diff --git a/modules/worker/front/dms/locale/es.yml b/modules/worker/front/dms/locale/es.yml new file mode 100644 index 000000000..fa4178d35 --- /dev/null +++ b/modules/worker/front/dms/locale/es.yml @@ -0,0 +1,20 @@ +Reference: Referencia +Description: Descripción +Company: Empresa +Upload file: Subir fichero +Edit file: Editar fichero +Upload: Subir +File: Fichero +WorkerFileDescription: "{{dmsTypeName}} del empleado {{workerName}} id {{workerId}}" +ContentTypesInfo: "Tipos de archivo permitidos: {{allowedContentTypes}}" +Generate identifier for original file: Generar identificador para archivo original +Are you sure you want to continue?: ¿Seguro que quieres continuar? +File management: Gestión documental +Hard copy: Copia +This file will be deleted: Este fichero va a ser borrado +Are you sure?: ¿Seguro? +File deleted: Fichero eliminado +Remove file: Eliminar fichero +Download file: Descargar fichero +Created: Creado +Employee: Empleado \ No newline at end of file diff --git a/modules/worker/front/index.js b/modules/worker/front/index.js new file mode 100644 index 000000000..775524a3d --- /dev/null +++ b/modules/worker/front/index.js @@ -0,0 +1,19 @@ +export * from './module'; + +import './main'; +import './index/'; +import './summary'; +import './card'; +import './descriptor'; +import './descriptor-popover'; +import './search-panel'; +import './basic-data'; +import './pbx'; +import './department'; +import './calendar'; +import './time-control'; +import './log'; +import './phones'; +import './dms/index'; +import './dms/create'; +import './dms/edit'; diff --git a/modules/worker/front/index/index.html b/modules/worker/front/index/index.html new file mode 100644 index 000000000..c5f9239f1 --- /dev/null +++ b/modules/worker/front/index/index.html @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/worker/front/index/index.js b/modules/worker/front/index/index.js new file mode 100644 index 000000000..81e9070bd --- /dev/null +++ b/modules/worker/front/index/index.js @@ -0,0 +1,37 @@ +import ngModule from '../module'; + +export default class Controller { + constructor($, $state) { + this.$state = $state; + Object.assign(this, { + $, + selectedWorker: null, + }); + } + + onSearch(params) { + if (params) + this.$.model.applyFilter(null, params); + else + this.$.model.clear(); + } + + preview(event, worker) { + if (event.defaultPrevented) return; + event.preventDefault(); + event.stopPropagation(); + + this.selectedWorker = worker; + this.$.preview.show(); + } + + onMoreChange(callback) { + callback.call(this); + } +} +Controller.$inject = ['$scope', '$state']; + +ngModule.component('vnWorkerIndex', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/worker/front/locale/es.yml b/modules/worker/front/locale/es.yml new file mode 100644 index 000000000..3fa727801 --- /dev/null +++ b/modules/worker/front/locale/es.yml @@ -0,0 +1,20 @@ +Workers: Trabajadores +Last name: Apellidos +User data: Datos de usuario +Fiscal identifier: NIF +Email: E-mail +Department: Departamento +User id: Id de usuario +Role: Rol +Extension: Extensión +Go to client: Ir al cliente +Private Branch Exchange: Centralita +View worker: Ver trabajador +Worker id: Id trabajador +Fiscal Identifier: NIF +User name: Usuario +Departments: Departamentos +Calendar: Calendario +Search workers by id, firstName, lastName or user name: Buscar trabajadores por el identificador, nombre, apellidos o nombre de usuario +Time control: Control de horario +Data saved! User must access web: ¡Datos guardados! El usuario deberá acceder con su contraseña a la web para que los cambios surtan efecto. diff --git a/modules/worker/front/log/index.html b/modules/worker/front/log/index.html new file mode 100644 index 000000000..9fb96ec10 --- /dev/null +++ b/modules/worker/front/log/index.html @@ -0,0 +1,104 @@ + + + + + + + + Date + Author + Model + Action + Name + Before + After + + + + + + {{::log.creationDate | date:'dd/MM/yyyy HH:mm'}} +
    +
    + Changed by: + {{::log.user.name | dashIfEmpty}} + +
    +
    + Model: + {{::log.changedModel | dashIfEmpty}} +
    +
    + Action: + {{::$ctrl.actionsText[log.action] | dashIfEmpty}} +
    +
    + Name: + {{::log.changedModelValue | dashIfEmpty}} +
    +
    +
    + + {{::log.user.name | dashIfEmpty}} + + + + {{::log.changedModel}} + + + {{::$ctrl.actionsText[log.action]}} + + + {{::log.changedModelValue}} + + + +
    + {{::old.key}}: + {{::old.value}} +
    +
    +
    + + +
    + {{::new.key}}: + {{::new.value}} +
    +
    + +
    + {{::log.description}} +
    +
    +
    +
    +
    +
    + +
    +
    + + diff --git a/modules/worker/front/log/index.js b/modules/worker/front/log/index.js new file mode 100644 index 000000000..4a577658b --- /dev/null +++ b/modules/worker/front/log/index.js @@ -0,0 +1,83 @@ +import ngModule from '../module'; +import './style.scss'; + +export default class Controller { + constructor($scope) { + this.$ = $scope; + this.actionsText = { + 'insert': 'Creates', + 'update': 'Updates', + 'delete': 'Deletes', + 'select': 'Views' + }; + this.filter = { + include: [{ + relation: 'user', + scope: { + fields: ['name'], + include: { + relation: 'worker', + scope: { + fields: ['id'] + } + } + }, + }], + }; + } + + get logs() { + return this._logs; + } + + set logs(value) { + this._logs = value; + + if (this.logs) { + this.logs.forEach(log => { + log.oldProperties = this.getInstance(log.oldInstance); + log.newProperties = this.getInstance(log.newInstance); + }); + } + } + + showWorkerDescriptor(event, workerFk) { + if (event.defaultPrevented) return; + if (!workerFk) return; + + event.preventDefault(); + event.stopPropagation(); + + this.selectedWorker = workerFk; + this.$.workerDescriptor.parent = event.target; + this.$.workerDescriptor.show(); + } + + getInstance(instance) { + const properties = []; + let validDate = /^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$/; + + if (typeof instance == 'object' && instance != null) { + Object.keys(instance).forEach(property => { + if (validDate.test(instance[property])) + instance[property] = new Date(instance[property]).toLocaleString('es-ES'); + + properties.push({key: property, value: instance[property]}); + }); + return properties; + } + return null; + } +} + +Controller.$inject = ['$scope']; + +ngModule.component('vnLog', { + controller: Controller, + template: require('./index.html'), + bindings: { + model: '<', + originId: '<', + url: '@' + } +}); diff --git a/modules/worker/front/log/locale/es.yml b/modules/worker/front/log/locale/es.yml new file mode 100644 index 000000000..d9c204e55 --- /dev/null +++ b/modules/worker/front/log/locale/es.yml @@ -0,0 +1,11 @@ +Model: Modelo +Action: Acción +Author: Autor +Before: Antes +After: Despues +History: Historial +Name: Nombre +Creates: Crea +Updates: Actualiza +Deletes: Elimina +Views: Visualiza \ No newline at end of file diff --git a/modules/worker/front/log/style.scss b/modules/worker/front/log/style.scss new file mode 100644 index 000000000..bf5e763d7 --- /dev/null +++ b/modules/worker/front/log/style.scss @@ -0,0 +1,30 @@ +@import "variables"; + +vn-log { + vn-td { + vertical-align: initial !important; + } + .changes { + display: none; + } + .label { + color: $color-font-secondary; + } + .value { + color: $color-font; + } + + .after, .before { + max-width: 250px; + } + + @media screen and (max-width: 1570px) { + .expendable { + display: none; + } + .changes { + padding-top: 10px; + display: block; + } + } +} \ No newline at end of file diff --git a/modules/worker/front/main/index.html b/modules/worker/front/main/index.html new file mode 100644 index 000000000..826a7905f --- /dev/null +++ b/modules/worker/front/main/index.html @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/modules/worker/front/main/index.js b/modules/worker/front/main/index.js new file mode 100644 index 000000000..d97a2d636 --- /dev/null +++ b/modules/worker/front/main/index.js @@ -0,0 +1,9 @@ +import ngModule from '../module'; +import ModuleMain from 'salix/components/module-main'; + +export default class Worker extends ModuleMain {} + +ngModule.vnComponent('vnWorker', { + controller: Worker, + template: require('./index.html') +}); diff --git a/modules/worker/front/module.js b/modules/worker/front/module.js new file mode 100644 index 000000000..938d46892 --- /dev/null +++ b/modules/worker/front/module.js @@ -0,0 +1,3 @@ +import {ng} from 'core/vendor'; + +export default ng.module('worker', ['vnCore']); diff --git a/modules/worker/front/pbx/index.html b/modules/worker/front/pbx/index.html new file mode 100644 index 000000000..5118d38ed --- /dev/null +++ b/modules/worker/front/pbx/index.html @@ -0,0 +1,24 @@ + + +
    + + + + + + + + + + + + + +
    diff --git a/modules/worker/front/pbx/index.js b/modules/worker/front/pbx/index.js new file mode 100644 index 000000000..aa869b895 --- /dev/null +++ b/modules/worker/front/pbx/index.js @@ -0,0 +1,25 @@ +import ngModule from '../module'; +import Component from 'core/lib/component'; + +class Controller extends Component { + onSubmit() { + const sip = this.worker.sip; + const params = { + userFk: this.worker.userFk, + extension: sip.extension + }; + this.$.watcher.check(); + this.$http.patch('Sips', params).then(() => { + this.$.watcher.updateOriginalData(); + this.vnApp.showSuccess(this.$t('Data saved! User must access web')); + }); + } +} + +ngModule.component('vnWorkerPbx', { + template: require('./index.html'), + controller: Controller, + bindings: { + worker: '<' + } +}); diff --git a/modules/worker/front/phones/index.html b/modules/worker/front/phones/index.html new file mode 100644 index 000000000..95e0366c1 --- /dev/null +++ b/modules/worker/front/phones/index.html @@ -0,0 +1,54 @@ + + + + + + +
    + + + + + + + + + + + + + + + + + + + +
    diff --git a/modules/worker/front/phones/index.js b/modules/worker/front/phones/index.js new file mode 100644 index 000000000..91d69ac16 --- /dev/null +++ b/modules/worker/front/phones/index.js @@ -0,0 +1,48 @@ +import ngModule from '../module'; + +class Controller { + constructor($scope) { + this.$scope = $scope; + } + + get worker() { + return this._worker; + } + + set worker(value) { + this._worker = value; + if (value) + this.setLink(value); + } + + setLink(value) { + this.$scope.$applyAsync(()=> { + this.$scope.model.link = {userFk: value.userFk}; + this.$scope.model.refresh(); + }); + } + + onSubmit() { + this.$scope.watcher.check(); + return this.$scope.model.save().then(() => { + this.$scope.watcher.updateOriginalData(); + this.$scope.watcher.notifySaved(); + this.card.reload(); + }); + } + + add() { + this.$scope.model.insert(); + } +} + +Controller.$inject = ['$scope']; + +ngModule.component('vnWorkerPhones', { + template: require('./index.html'), + controller: Controller, + require: {card: '^vnWorkerCard'}, + bindings: { + worker: '<' + } +}); diff --git a/modules/worker/front/phones/index.spec.js b/modules/worker/front/phones/index.spec.js new file mode 100644 index 000000000..e3f6f9bf5 --- /dev/null +++ b/modules/worker/front/phones/index.spec.js @@ -0,0 +1,47 @@ +import './index'; +import watcher from 'core/mocks/watcher'; + +describe('Component vnWorkerPhones', () => { + let controller; + + beforeEach(ngModule('worker')); + + beforeEach(angular.mock.inject(($componentController, $rootScope) => { + let $scope = $rootScope.$new(); + controller = $componentController('vnWorkerPhones', $scope); + controller.$scope.watcher = watcher; + controller.$scope.model = { + link: 1, + save: () => {} + }; + controller.card = {reload: () => {}}; + })); + + describe('setLink()', () => { + it('set the link in the model and refreshes it', () => { + spyOn(controller.$scope, '$applyAsync'); + let value = {userFk: 106}; + controller.setLink(value); + + expect(controller.$scope.$applyAsync).toHaveBeenCalledWith(jasmine.any(Function)); + }); + }); + + describe('onSubmit()', () => { + it('should call watcher functions, reload the card and save the model', done => { + spyOn(controller.$scope.watcher, 'check'); + spyOn(controller.$scope.model, 'save').and.returnValue(Promise.resolve()); + + spyOn(controller.$scope.watcher, 'updateOriginalData'); + spyOn(controller.$scope.watcher, 'notifySaved'); + spyOn(controller.card, 'reload'); + controller.onSubmit(); + controller.onSubmit().then(() => { + expect(controller.$scope.watcher.updateOriginalData).toHaveBeenCalledWith(); + expect(controller.$scope.watcher.notifySaved).toHaveBeenCalledWith(); + expect(controller.card.reload).toHaveBeenCalledWith(); + done(); + }).catch(done.fail); + }); + }); +}); diff --git a/modules/worker/front/phones/locale/es.yml b/modules/worker/front/phones/locale/es.yml new file mode 100644 index 000000000..8628f38ee --- /dev/null +++ b/modules/worker/front/phones/locale/es.yml @@ -0,0 +1,4 @@ +Phones: Teléfonos +Type: Tipo +Remove phone: Eliminar teléfono +Add phone: Añadir teléfono \ No newline at end of file diff --git a/modules/worker/front/routes.json b/modules/worker/front/routes.json new file mode 100644 index 000000000..6414c9ed2 --- /dev/null +++ b/modules/worker/front/routes.json @@ -0,0 +1,130 @@ +{ + "module": "worker", + "name": "Workers", + "icon" : "icon-worker", + "validations" : true, + "menus": { + "main": [ + {"state": "worker.index", "icon": "icon-worker"}, + {"state": "worker.department", "icon": "work"} + ], + "card": [ + {"state": "worker.card.basicData", "icon": "settings"}, + {"state": "worker.card.pbx", "icon": "icon-pbx"}, + {"state": "worker.card.calendar", "icon": "icon-calendar"}, + {"state": "worker.card.timeControl", "icon": "access_time"}, + {"state": "worker.card.phones", "icon": "contact_phone"}, + {"state": "worker.card.dms.index", "icon": "cloud_upload"} + ] + }, + "routes": [ + { + "url": "/worker", + "state": "worker", + "abstract": true, + "component": "vn-worker", + "description": "Workers" + }, { + "url": "/index?q", + "state": "worker.index", + "component": "vn-worker-index", + "description": "Workers" + }, { + "url" : "/summary", + "state": "worker.card.summary", + "component": "vn-worker-summary", + "description": "Summary", + "params": { + "worker": "$ctrl.worker" + } + }, { + "url": "/:id", + "state": "worker.card", + "component": "vn-worker-card", + "abstract": true, + "description": "Detail" + }, { + "url": "/basic-data", + "state": "worker.card.basicData", + "component": "vn-worker-basic-data", + "description": "Basic data", + "params": { + "worker": "$ctrl.worker" + }, + "acl": ["hr"] + }, { + "url": "/pbx", + "state": "worker.card.pbx", + "component": "vn-worker-pbx", + "description": "Private Branch Exchange", + "params": { + "worker": "$ctrl.worker" + }, + "acl": ["hr"] + }, { + "url": "/calendar", + "state": "worker.card.calendar", + "component": "vn-worker-calendar", + "description": "Calendar", + "params": { + "worker": "$ctrl.worker" + } + }, { + "url": "/time-control", + "state": "worker.card.timeControl", + "component": "vn-worker-time-control", + "description": "Time control", + "params": { + "worker": "$ctrl.worker" + } + }, { + "url" : "/department", + "state": "worker.department", + "component": "vn-worker-department", + "description": "Departments", + "acl": ["hr"] + }, { + "url": "/phones", + "state": "worker.card.phones", + "component": "vn-worker-phones", + "description": "Phones", + "params": { + "worker": "$ctrl.worker" + }, + "acl": ["hr"] + }, + { + "url": "/dms", + "state": "worker.card.dms", + "abstract": true, + "component": "ui-view" + }, + { + "url": "/index", + "state": "worker.card.dms.index", + "component": "vn-worker-dms-index", + "description": "File management", + "acl": ["hr"] + }, + { + "url": "/create", + "state": "worker.card.dms.create", + "component": "vn-worker-dms-create", + "description": "Upload file", + "params": { + "worker": "$ctrl.worker" + }, + "acl": ["hr"] + }, + { + "url": "/:dmsId/edit", + "state": "worker.card.dms.edit", + "component": "vn-worker-dms-edit", + "description": "Edit file", + "params": { + "worker": "$ctrl.worker" + }, + "acl": ["hr"] + } + ] +} \ No newline at end of file diff --git a/modules/worker/front/search-panel/index.html b/modules/worker/front/search-panel/index.html new file mode 100644 index 000000000..cdda4a0a0 --- /dev/null +++ b/modules/worker/front/search-panel/index.html @@ -0,0 +1,67 @@ +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    \ No newline at end of file diff --git a/modules/worker/front/search-panel/index.js b/modules/worker/front/search-panel/index.js new file mode 100644 index 000000000..ef85c998b --- /dev/null +++ b/modules/worker/front/search-panel/index.js @@ -0,0 +1,7 @@ +import ngModule from '../module'; +import SearchPanel from 'core/components/searchbar/search-panel'; + +ngModule.component('vnWorkerSearchPanel', { + template: require('./index.html'), + controller: SearchPanel +}); diff --git a/modules/worker/front/summary/index.html b/modules/worker/front/summary/index.html new file mode 100644 index 000000000..de86c1f84 --- /dev/null +++ b/modules/worker/front/summary/index.html @@ -0,0 +1,36 @@ + +
    {{worker.firstName}} {{worker.lastName}}
    + + +

    Basic data

    + + + + + + + + +
    + +

    User data

    + + + + + + + + +
    +
    +
    \ No newline at end of file diff --git a/modules/worker/front/summary/index.js b/modules/worker/front/summary/index.js new file mode 100644 index 000000000..f055a0903 --- /dev/null +++ b/modules/worker/front/summary/index.js @@ -0,0 +1,77 @@ +import ngModule from '../module'; + +class Controller { + constructor($, $http) { + Object.assign(this, { + $, + $http + }); + } + + get worker() { + return this._worker; + } + + set worker(value) { + this._worker = value; + this.$.worker = null; + if (!value) return; + + let query = `Workers/${value.id}`; + let filter = { + include: [ + { + relation: 'user', + scope: { + fields: ['name', 'roleFk'], + include: [{ + relation: 'role', + scope: { + fields: ['name'] + } + }, + { + relation: 'emailUser', + scope: { + fields: ['email'] + } + }] + } + }, { + relation: 'client', + scope: {fields: ['fi']} + }, { + relation: 'sip', + scope: {fields: ['extension']} + }, { + relation: 'department', + scope: { + include: { + relation: 'department' + } + } + }, { + relation: 'phones', + scope: { + fields: ['phone'], + order: 'typeFk ASC' + } + } + ] + }; + + this.$http.get(query, {params: {filter}}).then(res => { + this.$.worker = res.data; + }); + } +} + +Controller.$inject = ['$scope', '$http']; + +ngModule.component('vnWorkerSummary', { + template: require('./index.html'), + controller: Controller, + bindings: { + worker: '<' + } +}); diff --git a/modules/worker/front/time-control/index.html b/modules/worker/front/time-control/index.html new file mode 100644 index 000000000..10691d301 --- /dev/null +++ b/modules/worker/front/time-control/index.html @@ -0,0 +1,119 @@ + + + + + + + +
    {{::$ctrl.weekdayNames[$index].name}}
    +
    + {{::weekday.dated | date: 'dd'}} + + {{::weekday.dated | date: 'MMMM'}} + +
    + + + +
    + {{::weekday.event.name}} +
    +
    +
    +
    +
    + + + +
    + + + + {{::hour.timed | date: 'HH:mm'}} + +
    +
    +
    +
    + + + + {{$ctrl.formatHours(weekday.workedHours)}} h. + + + + + + + + + +
    +
    + +
    +
    +
    Hours
    + + + + +
    + + +
    +
    + + +
    +
    + Add time +
    + + +
    +
    + + + + +
    + + \ No newline at end of file diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js new file mode 100644 index 000000000..c355138c3 --- /dev/null +++ b/modules/worker/front/time-control/index.js @@ -0,0 +1,265 @@ +import Component from 'core/lib/component'; +import ngModule from '../module'; +import './style.scss'; +class Controller extends Component { + constructor($element, $, vnWeekDays) { + super($element, $); + this.weekDays = []; + this.weekdayNames = vnWeekDays.locales; + } + + $postLink() { + this.date = new Date(); + } + + /** + * The current selected date + */ + get date() { + return this._date; + } + + set date(value) { + this._date = value; + value.setHours(0, 0, 0, 0); + + let weekOffset = value.getDay() - 1; + if (weekOffset < 0) weekOffset = 6; + + let started = new Date(value.getTime()); + started.setDate(started.getDate() - weekOffset); + this.started = started; + + let ended = new Date(started.getTime()); + ended.setHours(23, 59, 59, 59); + ended.setDate(ended.getDate() + 6); + this.ended = ended; + + this.weekDays = []; + let dayIndex = new Date(started.getTime()); + + while (dayIndex < ended) { + this.weekDays.push({ + dated: new Date(dayIndex.getTime()) + }); + dayIndex.setDate(dayIndex.getDate() + 1); + } + + this.fetchHours(); + } + + /** + * Worker hours data + */ + get hours() { + return this._hours; + } + + set hours(value) { + this._hours = value; + + for (const weekDay of this.weekDays) { + if (value) { + let day = weekDay.dated.getDay(); + weekDay.hours = value + .filter(hour => new Date(hour.timed).getDay() == day) + .sort((a, b) => new Date(a.timed) - new Date(b.timed)); + } else + weekDay.hours = null; + } + } + + fetchHours() { + const params = {workerFk: this.$params.id}; + const filter = { + where: {and: [ + {timed: {gte: this.started}}, + {timed: {lte: this.ended}} + ]} + }; + this.$.model.applyFilter(filter, params); + + this.getAbsences(); + this.getWorkedHours(this.started, this.ended); + } + + hasEvents(day) { + return day >= this.started && day < this.ended; + } + + getWorkedHours(from, to) { + this.weekTotalHours = null; + let weekTotalHours = 0; + let params = { + id: this.$params.id, + from: from, + to: to + }; + + const query = `Workers/${this.$params.id}/getWorkedHours`; + return this.$http.get(query, {params}).then(res => { + const workDays = res.data; + const map = new Map(); + + for (const workDay of workDays) { + workDay.dated = new Date(workDay.dated); + map.set(workDay.dated, workDay); + weekTotalHours += workDay.workedHours; + } + + for (const weekDay of this.weekDays) { + const workDay = workDays.find(day => { + let from = new Date(day.dated); + from.setHours(0, 0, 0, 0); + + let to = new Date(day.dated); + to.setHours(23, 59, 59, 59); + + return weekDay.dated >= from && weekDay.dated <= to; + }); + + if (workDay) { + weekDay.expectedHours = workDay.expectedHours; + weekDay.workedHours = workDay.workedHours; + } + } + this.weekTotalHours = weekTotalHours; + }); + } + + getFinishTime() { + if (!this.weekDays) return; + + let today = new Date(); + today.setHours(0, 0, 0, 0); + + let todayInWeek = this.weekDays.find(day => day.dated.getTime() === today.getTime()); + + if (todayInWeek && todayInWeek.hours && todayInWeek.hours.length) { + const remainingTime = todayInWeek.workedHours ? ((todayInWeek.expectedHours - todayInWeek.workedHours) * 1000) : null; + const lastKnownEntry = todayInWeek.hours[todayInWeek.hours.length - 1]; + const lastKnownTime = new Date(lastKnownEntry.timed).getTime(); + const finishTimeStamp = lastKnownTime && remainingTime ? lastKnownTime + remainingTime : null; + + if (finishTimeStamp) { + let finishDate = new Date(finishTimeStamp); + let hour = finishDate.getHours(); + let minute = finishDate.getMinutes(); + + if (hour < 10) hour = `0${hour}`; + if (minute < 10) minute = `0${minute}`; + + return `${hour}:${minute} h.`; + } + } + } + + set weekTotalHours(totalHours) { + if (!totalHours) return this._weekTotalHours = this.formatHours(0); + + this._weekTotalHours = this.formatHours(totalHours); + } + + get weekTotalHours() { + return this._weekTotalHours; + } + + formatHours(timestamp) { + timestamp = timestamp || 0; + + let hour = Math.floor(timestamp / 3600); + let min = Math.floor(timestamp / 60 - 60 * hour); + + if (hour < 10) hour = `0${hour}`; + if (min < 10) min = `0${min}`; + + return `${hour}:${min}`; + } + + showAddTimeDialog(weekday) { + const timed = new Date(weekday.dated.getTime()); + timed.setHours(0, 0, 0, 0); + + this.newTime = timed; + this.selectedWeekday = weekday; + this.$.addTimeDialog.show(); + } + + addTime(response) { + if (response !== 'accept') return; + let data = { + workerFk: this.$params.id, + timed: this.newTime + }; + this.$http.post(`WorkerTimeControls/addTimeEntry`, data) + .then(() => this.fetchHours()); + } + + showDeleteDialog(hour) { + this.timeEntryToDelete = hour; + this.$.deleteEntryDialog.show(); + } + + deleteTimeEntry() { + const entryId = this.timeEntryToDelete.id; + + this.$http.post(`WorkerTimeControls/${entryId}/deleteTimeEntry`).then(() => { + this.fetchHours(); + this.vnApp.showSuccess(this.$t('Entry removed')); + }); + } + + getAbsences() { + let params = { + workerFk: this.$params.id, + started: this.started, + ended: this.ended + }; + + return this.$http.get(`WorkerCalendars/absences`, {params}) + .then(res => this.onData(res.data)); + } + + onData(data) { + const events = {}; + + let addEvent = (day, event) => { + events[new Date(day).getTime()] = event; + }; + + if (data.holidays) { + data.holidays.forEach(holiday => { + const holidayDetail = holiday.detail && holiday.detail.description; + const holidayType = holiday.type && holiday.type.name; + const holidayName = holidayDetail || holidayType; + + addEvent(holiday.dated, { + name: holidayName, + color: '#ff0' + }); + }); + } + if (data.absences) { + data.absences.forEach(absence => { + const type = absence.absenceType; + addEvent(absence.dated, { + name: type.name, + color: type.rgb + }); + }); + } + + this.weekDays.forEach(day => { + const timestamp = day.dated.getTime(); + if (events[timestamp]) + day.event = events[timestamp]; + }); + } +} + +Controller.$inject = ['$element', '$scope', 'vnWeekDays']; + +ngModule.component('vnWorkerTimeControl', { + template: require('./index.html'), + controller: Controller +}); diff --git a/modules/worker/front/time-control/index.spec.js b/modules/worker/front/time-control/index.spec.js new file mode 100644 index 000000000..abfe95580 --- /dev/null +++ b/modules/worker/front/time-control/index.spec.js @@ -0,0 +1,118 @@ +import './index.js'; + + +describe('Component vnWorkerTimeControl', () => { + let $httpBackend; + let $scope; + let $element; + let controller; + + beforeEach(ngModule('worker')); + + beforeEach(angular.mock.inject(($componentController, $compile, $rootScope, $stateParams, _$httpBackend_) => { + $stateParams.id = 1; + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + $element = angular.element(''); + controller = $componentController('vnWorkerTimeControl', {$element, $scope}); + })); + + describe('date() setter', () => { + it(`should set the weekDays, the date in the controller and call fetchHours`, () => { + let today = new Date(); + spyOn(controller, 'fetchHours'); + + controller.date = today; + + expect(controller._date).toEqual(today); + expect(controller.started).toBeDefined(); + expect(controller.ended).toBeDefined(); + expect(controller.weekDays.length).toEqual(7); + expect(controller.fetchHours).toHaveBeenCalledWith(); + }); + }); + + describe('hours() setter', () => { + it(`should set hours data at it's corresponding week day`, () => { + let today = new Date(); + spyOn(controller, 'fetchHours'); + + controller.date = today; + + let hours = [ + { + id: 1, + timed: controller.started.toJSON(), + userFk: 1 + }, { + id: 2, + timed: controller.ended.toJSON(), + userFk: 1 + }, { + id: 3, + timed: controller.ended.toJSON(), + userFk: 1 + } + ]; + + controller.hours = hours; + + expect(controller.weekDays.length).toEqual(7); + expect(controller.weekDays[0].hours.length).toEqual(1); + expect(controller.weekDays[6].hours.length).toEqual(2); + }); + }); + + describe('getWorkedHours() ', () => { + it(`should `, () => { + let today = new Date(); + spyOn(controller, 'fetchHours'); + + controller.date = today; + + let sixHoursInSeconds = 6 * 60 * 60; + let tenHoursInSeconds = 10 * 60 * 60; + let response = [ + { + dated: today, + expectedHours: sixHoursInSeconds, + workedHours: tenHoursInSeconds, + + }, + ]; + $httpBackend.whenRoute('GET', 'Workers/:id/getWorkedHours') + .respond(response); + + today.setHours(0, 0, 0, 0); + + let weekOffset = today.getDay() - 1; + if (weekOffset < 0) weekOffset = 6; + + let started = new Date(today.getTime()); + started.setDate(started.getDate() - weekOffset); + controller.started = started; + + let ended = new Date(started.getTime()); + ended.setHours(23, 59, 59, 59); + ended.setDate(ended.getDate() + 6); + controller.ended = ended; + + controller.getWorkedHours(controller.started, controller.ended); + + $httpBackend.flush(); + + expect(controller.weekDays.length).toEqual(7); + expect(controller.weekDays[weekOffset].expectedHours).toEqual(response[0].expectedHours); + expect(controller.weekDays[weekOffset].workedHours).toEqual(response[0].workedHours); + expect(controller.weekTotalHours).toEqual('10:00'); + }); + + describe('formatHours() ', () => { + it(`should format a passed timestamp to hours and minutes`, () => { + const result = controller.formatHours(3600); + + expect(result).toEqual('01:00'); + }); + }); + }); +}); diff --git a/modules/worker/front/time-control/locale/es.yml b/modules/worker/front/time-control/locale/es.yml new file mode 100644 index 000000000..1d28b0e2b --- /dev/null +++ b/modules/worker/front/time-control/locale/es.yml @@ -0,0 +1,11 @@ +In: Entrada +Out: Salida +Hour: Hora +Hours: Horas +Add time: Añadir hora +Week total: Total semana +Current week: Semana actual +This time entry will be deleted: Se eliminará la hora fichada +Are you sure you want to delete this entry?: ¿Seguro que quieres eliminarla? +Finish at: Termina a las +Entry removed: Fichada borrada \ No newline at end of file diff --git a/modules/worker/front/time-control/style.scss b/modules/worker/front/time-control/style.scss new file mode 100644 index 000000000..8555e827b --- /dev/null +++ b/modules/worker/front/time-control/style.scss @@ -0,0 +1,27 @@ +@import "variables"; + +vn-worker-time-control { + vn-thead > vn-tr > vn-td > div.weekday { + margin-bottom: 5px; + color: $color-main + } + vn-td.hours { + min-width: 100px; + vertical-align: top; + + & > section { + display: flex; + align-items: center; + justify-content: center; + padding: .3em 0; + + & > vn-icon { + color: $color-font-secondary; + padding-right: .1em; + } + } + } + .totalBox { + max-width: none + } +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 8d9be895f..c51e1b9f3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,17508 +1,17909 @@ { - "name": "salix-app", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "@types/node": { - "version": "7.0.48", - "resolved": "https://registry.npmjs.org/@types/node/-/node-7.0.48.tgz", - "integrity": "sha1-JL/cCqguj229AXFZxYCUouBtCrs=", - "dev": true - }, - "@uirouter/angularjs": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@uirouter/angularjs/-/angularjs-1.0.3.tgz", - "integrity": "sha1-UYuHVUK02G3RqvX0JizO5BbywWY=", - "requires": { - "@uirouter/core": "5.0.3" - } - }, - "@uirouter/core": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/@uirouter/core/-/core-5.0.3.tgz", - "integrity": "sha1-4rWx5FGQ4gxnuk4VwBPeXU4MyrM=" - }, - "abbrev": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.9.tgz", - "integrity": "sha1-kbR5JYinc4wl813W9jdSovh3YTU=", - "dev": true - }, - "accepts": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.3.tgz", - "integrity": "sha1-w8p0NJOGSMPg2cHjKN1otiLChMo=", - "dev": true, - "requires": { - "mime-types": "2.1.12", - "negotiator": "0.6.1" - } - }, - "acorn": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.4.1.tgz", - "integrity": "sha512-XLmq3H/BVvW6/GbxKryGxWORz1ebilSsUDlyC27bXhWGWAZWkGwS6FLHjOlwFXNFoWFQEO/Df4u0YYd0K3BQgQ==" - }, - "acorn-dynamic-import": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/acorn-dynamic-import/-/acorn-dynamic-import-2.0.2.tgz", - "integrity": "sha1-x1K9IQvvZ5UBtsbLf8hPj0cVjMQ=", - "dev": true, - "requires": { - "acorn": "4.0.13" - }, - "dependencies": { - "acorn": { - "version": "4.0.13", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-4.0.13.tgz", - "integrity": "sha1-EFSVrlNh1pe9GVyCUZLhrX8lN4c=", - "dev": true - } - } - }, - "acorn-jsx": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-3.0.1.tgz", - "integrity": "sha1-r9+UiPsezvyDSPb7IvRk4ypYs2s=", - "requires": { - "acorn": "3.3.0" - }, - "dependencies": { - "acorn": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-3.3.0.tgz", - "integrity": "sha1-ReN/s56No/JbruP/U2niu18iAXo=" - } - } - }, - "after": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/after/-/after-0.8.2.tgz", - "integrity": "sha1-/ts5T58OAqqXaOcCvaI7UF+ufh8=", - "dev": true - }, - "ajv": { - "version": "5.5.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz", - "integrity": "sha1-c7Xuyj+rZT49P5Qis0GtQiBdyWU=", - "requires": { - "co": "4.6.0", - "fast-deep-equal": "1.0.0", - "fast-json-stable-stringify": "2.0.0", - "json-schema-traverse": "0.3.1" - } - }, - "ajv-keywords": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-2.1.1.tgz", - "integrity": "sha1-YXmX/F9gV2iUxDX5QNgZ4TW4B2I=" - }, - "align-text": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/align-text/-/align-text-0.1.4.tgz", - "integrity": "sha1-DNkKVhCT810KmSVsIrcGlDP60Rc=", - "dev": true, - "requires": { - "kind-of": "3.0.4", - "longest": "1.0.1", - "repeat-string": "1.6.1" - } - }, - "amdefine": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz", - "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=", - "dev": true - }, - "angular": { - "version": "1.6.8", - "resolved": "https://registry.npmjs.org/angular/-/angular-1.6.8.tgz", - "integrity": "sha1-W+N4pYvpGlSJ54tZxFGM2f0nP/s=" - }, - "angular-cookies": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/angular-cookies/-/angular-cookies-1.6.4.tgz", - "integrity": "sha1-wo8/aqx6mCbB5F8daAckADblsm0=" - }, - "angular-mocks": { - "version": "1.6.6", - "resolved": "https://registry.npmjs.org/angular-mocks/-/angular-mocks-1.6.6.tgz", - "integrity": "sha1-yTAY54OMbcXOrxprz5vhPIMOpRU=", - "dev": true - }, - "angular-paging": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/angular-paging/-/angular-paging-2.2.2.tgz", - "integrity": "sha1-cC9XTW0UBpADXqxkOV/jEfeYf7s=" - }, - "angular-translate": { - "version": "2.17.0", - "resolved": "https://registry.npmjs.org/angular-translate/-/angular-translate-2.17.0.tgz", - "integrity": "sha512-SudfI0R0Hhtvngc0X3wFChXQGmw90o95i+QPZ11LhJJryneTq8LR3+3E4E7jgHA4fu6TcswgcfZ9+cp5ckbUHw==", - "requires": { - "angular": "1.6.8" - } - }, - "angular-translate-loader-partial": { - "version": "2.17.0", - "resolved": "https://registry.npmjs.org/angular-translate-loader-partial/-/angular-translate-loader-partial-2.17.0.tgz", - "integrity": "sha512-pyRJcRc93iwiUnRnh9ZfehbQE/yxO5T6jmEqIvLEVz8gKLjDqDLKcaQFgPef9wCIN2n3e531YbStkkbSH3LYmQ==", - "requires": { - "angular-translate": "2.17.0" - } - }, - "ansi-align": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-2.0.0.tgz", - "integrity": "sha1-w2rsy6VjuJzrVW82kPCx2eNUf38=", - "dev": true, - "requires": { - "string-width": "2.1.1" - }, - "dependencies": { - "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", - "dev": true - }, - "is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", - "dev": true - }, - "string-width": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", - "integrity": "sha1-q5Pyeo3BPSjKyBXEYhQ6bZASrp4=", - "dev": true, - "requires": { - "is-fullwidth-code-point": "2.0.0", - "strip-ansi": "4.0.0" - } - }, - "strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "dev": true, - "requires": { - "ansi-regex": "3.0.0" - } - } - } - }, - "ansi-colors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-1.0.1.tgz", - "integrity": "sha512-yopkAU0ZD/WQ56Tms3xLn6jRuX3SyUMAVi0FdmDIbmmnHW3jHiI1sQFdUl3gfVddjnrsP3Y6ywFKvCRopvoVIA==", - "dev": true, - "requires": { - "ansi-wrap": "0.1.0" - } - }, - "ansi-cyan": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/ansi-cyan/-/ansi-cyan-0.1.1.tgz", - "integrity": "sha1-U4rlKK+JgvKK4w2G8vF0VtJgmHM=", - "dev": true, - "requires": { - "ansi-wrap": "0.1.0" - } - }, - "ansi-escapes": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.0.0.tgz", - "integrity": "sha512-O/klc27mWNUigtv0F8NJWbLF00OcegQalkqKURWdosW08YZKi4m6CnSUSvIZG1otNJbTWhN01Hhz389DW7mvDQ==" - }, - "ansi-gray": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/ansi-gray/-/ansi-gray-0.1.1.tgz", - "integrity": "sha1-KWLPVOyXksSFEKPetSRDaGHvclE=", - "dev": true, - "requires": { - "ansi-wrap": "0.1.0" - } - }, - "ansi-html": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/ansi-html/-/ansi-html-0.0.7.tgz", - "integrity": "sha1-gTWEAhliqenm/QOflA0S9WynhZ4=", - "dev": true - }, - "ansi-red": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/ansi-red/-/ansi-red-0.1.1.tgz", - "integrity": "sha1-jGOPnRCAgAo1PJwoyKgcpHBdlGw=", - "dev": true, - "requires": { - "ansi-wrap": "0.1.0" - } - }, - "ansi-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz", - "integrity": "sha1-xQYbbg74qBd15Q9dZhUb9r83EQc=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "ansi-wrap": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/ansi-wrap/-/ansi-wrap-0.1.0.tgz", - "integrity": "sha1-qCJQ3bABXponyoLoLqYDu/pF768=", - "dev": true - }, - "ansicolors": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/ansicolors/-/ansicolors-0.2.1.tgz", - "integrity": "sha1-vgiVmQl7dKXJxKhKDNvNtivYeu8=", - "dev": true - }, - "anymatch": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-1.3.0.tgz", - "integrity": "sha1-o+Uvo5FoyCX/V7AkgSbOWo/5VQc=", - "dev": true, - "requires": { - "arrify": "1.0.1", - "micromatch": "2.3.11" - } - }, - "aproba": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz", - "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==", - "dev": true - }, - "archy": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/archy/-/archy-1.0.0.tgz", - "integrity": "sha1-+cjBN1fMHde8N5rHeyxipcKGjEA=", - "dev": true - }, - "are-we-there-yet": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-1.1.4.tgz", - "integrity": "sha1-u13KOCu5TwXhUZQ3PRb9O6HKEQ0=", - "dev": true, - "requires": { - "delegates": "1.0.0", - "readable-stream": "2.1.5" - } - }, - "argparse": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.9.tgz", - "integrity": "sha1-c9g7wmP4bpf4zE9rrhsOkKfSLIY=", - "requires": { - "sprintf-js": "1.0.3" - } - }, - "arr-diff": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", - "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", - "dev": true, - "requires": { - "arr-flatten": "1.0.1" - } - }, - "arr-flatten": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.0.1.tgz", - "integrity": "sha1-5f/lTUXhnzLyFukeuZyM6JK7YEs=", - "dev": true - }, - "arr-union": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", - "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", - "dev": true - }, - "array-differ": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-1.0.0.tgz", - "integrity": "sha1-7/UuN1gknTO+QCuLuOVkuytdQDE=", - "dev": true - }, - "array-each": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/array-each/-/array-each-1.0.1.tgz", - "integrity": "sha1-p5SvDAWrF1KEbudTofIRoFugxE8=", - "dev": true - }, - "array-find-index": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", - "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=", - "dev": true - }, - "array-flatten": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-2.1.1.tgz", - "integrity": "sha1-Qmu52oQJDBg42BLIFQryCoMx4pY=", - "dev": true - }, - "array-includes": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.0.3.tgz", - "integrity": "sha1-GEtI9i2S10UrsxsyMWXH+L0CJm0=", - "dev": true, - "requires": { - "define-properties": "1.1.2", - "es-abstract": "1.10.0" - } - }, - "array-slice": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-0.2.3.tgz", - "integrity": "sha1-3Tz7gO15c6dRF82sabC5nshhhvU=", - "dev": true - }, - "array-union": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", - "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", - "requires": { - "array-uniq": "1.0.3" - } - }, - "array-uniq": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", - "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=" - }, - "array-unique": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", - "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=", - "dev": true - }, - "arraybuffer.slice": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/arraybuffer.slice/-/arraybuffer.slice-0.0.6.tgz", - "integrity": "sha1-8zshWfBTKj8xB6JywMz70a0peco=", - "dev": true - }, - "arrify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", - "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" - }, - "asn1": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.3.tgz", - "integrity": "sha1-2sh4dxPJlmhJ/IGAd36+nB3fO4Y=", - "dev": true - }, - "asn1.js": { - "version": "4.9.2", - "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.9.2.tgz", - "integrity": "sha512-b/OsSjvWEo8Pi8H0zsDd2P6Uqo2TK2pH8gNLSJtNLM2Db0v2QaAZ0pBQJXVjAn4gBuugeVDr7s63ZogpUIwWDg==", - "dev": true, - "requires": { - "bn.js": "4.11.8", - "inherits": "2.0.3", - "minimalistic-assert": "1.0.0" - } - }, - "assert": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/assert/-/assert-1.4.1.tgz", - "integrity": "sha1-mZEtWRg2tab1s0XA8H7vwI/GXZE=", - "dev": true, - "requires": { - "util": "0.10.3" - } - }, - "assert-plus": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-0.2.0.tgz", - "integrity": "sha1-104bh+ev/A24qttwIfP+SBAasjQ=", - "dev": true - }, - "assets-webpack-plugin": { - "version": "3.5.1", - "resolved": "https://registry.npmjs.org/assets-webpack-plugin/-/assets-webpack-plugin-3.5.1.tgz", - "integrity": "sha1-kxzg1m1C6I7V5/GNZVIpQ8V6OH0=", - "dev": true, - "requires": { - "camelcase": "1.2.1", - "escape-string-regexp": "1.0.5", - "lodash.assign": "3.2.0", - "lodash.merge": "3.3.2", - "mkdirp": "0.5.1" - }, - "dependencies": { - "camelcase": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz", - "integrity": "sha1-m7UwTS4LVmmLLHWLCKPqqdqlijk=", - "dev": true - }, - "lodash.assign": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/lodash.assign/-/lodash.assign-3.2.0.tgz", - "integrity": "sha1-POnwI0tLIiPilrj6CsH+6OvKZPo=", - "dev": true, - "requires": { - "lodash._baseassign": "3.2.0", - "lodash._createassigner": "3.1.1", - "lodash.keys": "3.1.2" - } - } - } - }, - "assign-symbols": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", - "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", - "dev": true - }, - "ast-types": { - "version": "0.9.2", - "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.9.2.tgz", - "integrity": "sha1-LMGZedFcZVEIv1ZTI7jn7jh1H2s=", - "dev": true - }, - "async": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/async/-/async-2.1.2.tgz", - "integrity": "sha1-YSpKtF70KnDN6Aa62G7m2wR+g4U=", - "dev": true, - "requires": { - "lodash": "4.16.6" - } - }, - "async-each": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.1.tgz", - "integrity": "sha1-GdOGodntxufByF04iu28xW0zYC0=", - "dev": true - }, - "async-foreach": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/async-foreach/-/async-foreach-0.1.3.tgz", - "integrity": "sha1-NhIfhFwFeBct5Bmpfb6x0W7DRUI=", - "dev": true - }, - "asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", - "dev": true - }, - "atob": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/atob/-/atob-2.0.3.tgz", - "integrity": "sha1-GcenYEc3dEaPILLS0DNyrX1Mv10=", - "dev": true - }, - "aws-sign2": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.6.0.tgz", - "integrity": "sha1-FDQt0428yU0OW4fXY81jYSwOeU8=", - "dev": true - }, - "aws4": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.5.0.tgz", - "integrity": "sha1-Cin/t5wxyecS7rCH6OemS0pW11U=", - "dev": true - }, - "babel": { - "version": "6.23.0", - "resolved": "https://registry.npmjs.org/babel/-/babel-6.23.0.tgz", - "integrity": "sha1-0NHn2APpdHZb7qMjLU4VPA77kPQ=", - "dev": true - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "1.1.3", - "esutils": "2.0.2", - "js-tokens": "3.0.2" - }, - "dependencies": { - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - } - } - }, - "babel-core": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-core/-/babel-core-6.26.0.tgz", - "integrity": "sha1-rzL3izGm/O8RnIew/Y2XU/A6C7g=", - "dev": true, - "requires": { - "babel-code-frame": "6.26.0", - "babel-generator": "6.26.1", - "babel-helpers": "6.24.1", - "babel-messages": "6.23.0", - "babel-register": "6.26.0", - "babel-runtime": "6.26.0", - "babel-template": "6.26.0", - "babel-traverse": "6.26.0", - "babel-types": "6.26.0", - "babylon": "6.18.0", - "convert-source-map": "1.5.1", - "debug": "2.6.9", - "json5": "0.5.1", - "lodash": "4.17.5", - "minimatch": "3.0.4", - "path-is-absolute": "1.0.1", - "private": "0.1.8", - "slash": "1.0.0", - "source-map": "0.5.6" - }, - "dependencies": { - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "dev": true, - "requires": { - "chalk": "1.1.3", - "esutils": "2.0.2", - "js-tokens": "3.0.2" - } - }, - "balanced-match": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", - "dev": true - }, - "brace-expansion": { - "version": "1.1.8", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.8.tgz", - "integrity": "sha1-wHshHHyVLsH479Uad+8NHTmQopI=", - "dev": true, - "requires": { - "balanced-match": "1.0.0", - "concat-map": "0.0.1" - } - }, - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", - "dev": true - }, - "json5": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", - "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=", - "dev": true - }, - "lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", - "dev": true - }, - "minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "dev": true, - "requires": { - "brace-expansion": "1.1.8" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - }, - "private": { - "version": "0.1.8", - "resolved": "https://registry.npmjs.org/private/-/private-0.1.8.tgz", - "integrity": "sha512-VvivMrbvd2nKkiG38qjULzlc+4Vx4wm/whI9pQD35YrARNnhxeiRktSOhSukRLFNlzg6Br/cJPet5J/u19r/mg==", - "dev": true - } - } - }, - "babel-generator": { - "version": "6.26.1", - "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz", - "integrity": "sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA==", - "dev": true, - "requires": { - "babel-messages": "6.23.0", - "babel-runtime": "6.26.0", - "babel-types": "6.26.0", - "detect-indent": "4.0.0", - "jsesc": "1.3.0", - "lodash": "4.17.5", - "source-map": "0.5.7", - "trim-right": "1.0.1" - }, - "dependencies": { - "lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", - "dev": true - }, - "source-map": { - "version": "0.5.7", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", - "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", - "dev": true - } - } - }, - "babel-helper-call-delegate": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-helper-call-delegate/-/babel-helper-call-delegate-6.24.1.tgz", - "integrity": "sha1-7Oaqzdx25Bw0YfiL/Fdb0Nqi340=", - "dev": true, - "requires": { - "babel-helper-hoist-variables": "6.24.1", - "babel-runtime": "6.26.0", - "babel-traverse": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-helper-define-map": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-helper-define-map/-/babel-helper-define-map-6.26.0.tgz", - "integrity": "sha1-pfVtq0GiX5fstJjH66ypgZ+Vvl8=", - "dev": true, - "requires": { - "babel-helper-function-name": "6.24.1", - "babel-runtime": "6.26.0", - "babel-types": "6.26.0", - "lodash": "4.17.5" - }, - "dependencies": { - "lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", - "dev": true - } - } - }, - "babel-helper-function-name": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-helper-function-name/-/babel-helper-function-name-6.24.1.tgz", - "integrity": "sha1-00dbjAPtmCQqJbSDUasYOZ01gKk=", - "dev": true, - "requires": { - "babel-helper-get-function-arity": "6.24.1", - "babel-runtime": "6.26.0", - "babel-template": "6.26.0", - "babel-traverse": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-helper-get-function-arity": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-helper-get-function-arity/-/babel-helper-get-function-arity-6.24.1.tgz", - "integrity": "sha1-j3eCqpNAfEHTqlCQj4mwMbG2hT0=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-helper-hoist-variables": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-helper-hoist-variables/-/babel-helper-hoist-variables-6.24.1.tgz", - "integrity": "sha1-HssnaJydJVE+rbyZFKc/VAi+enY=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-helper-optimise-call-expression": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-helper-optimise-call-expression/-/babel-helper-optimise-call-expression-6.24.1.tgz", - "integrity": "sha1-96E0J7qfc/j0+pk8VKl4gtEkQlc=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-helper-regex": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-helper-regex/-/babel-helper-regex-6.26.0.tgz", - "integrity": "sha1-MlxZ+QL4LyS3T6zu0DY5VPZJXnI=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0", - "babel-types": "6.26.0", - "lodash": "4.17.5" - }, - "dependencies": { - "lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", - "dev": true - } - } - }, - "babel-helper-replace-supers": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-helper-replace-supers/-/babel-helper-replace-supers-6.24.1.tgz", - "integrity": "sha1-v22/5Dk40XNpohPKiov3S2qQqxo=", - "dev": true, - "requires": { - "babel-helper-optimise-call-expression": "6.24.1", - "babel-messages": "6.23.0", - "babel-runtime": "6.26.0", - "babel-template": "6.26.0", - "babel-traverse": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-helpers": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-helpers/-/babel-helpers-6.24.1.tgz", - "integrity": "sha1-NHHenK7DiOXIUOWX5Yom3fN2ArI=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0", - "babel-template": "6.26.0" - } - }, - "babel-loader": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-7.1.2.tgz", - "integrity": "sha512-jRwlFbINAeyDStqK6Dd5YuY0k5YuzQUvlz2ZamuXrXmxav3pNqe9vfJ402+2G+OmlJSXxCOpB6Uz0INM7RQe2A==", - "dev": true, - "requires": { - "find-cache-dir": "1.0.0", - "loader-utils": "1.1.0", - "mkdirp": "0.5.1" - }, - "dependencies": { - "loader-utils": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.1.0.tgz", - "integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=", - "dev": true, - "requires": { - "big.js": "3.1.3", - "emojis-list": "2.1.0", - "json5": "0.5.0" - } - } - } - }, - "babel-messages": { - "version": "6.23.0", - "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", - "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0" - } - }, - "babel-plugin-check-es2015-constants": { - "version": "6.22.0", - "resolved": "https://registry.npmjs.org/babel-plugin-check-es2015-constants/-/babel-plugin-check-es2015-constants-6.22.0.tgz", - "integrity": "sha1-NRV7EBQm/S/9PaP3XH0ekYNbv4o=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0" - } - }, - "babel-plugin-transform-es2015-arrow-functions": { - "version": "6.22.0", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-arrow-functions/-/babel-plugin-transform-es2015-arrow-functions-6.22.0.tgz", - "integrity": "sha1-RSaSy3EdX3ncf4XkQM5BufJE0iE=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0" - } - }, - "babel-plugin-transform-es2015-block-scoped-functions": { - "version": "6.22.0", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-block-scoped-functions/-/babel-plugin-transform-es2015-block-scoped-functions-6.22.0.tgz", - "integrity": "sha1-u8UbSflk1wy42OC5ToICRs46YUE=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0" - } - }, - "babel-plugin-transform-es2015-block-scoping": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-block-scoping/-/babel-plugin-transform-es2015-block-scoping-6.26.0.tgz", - "integrity": "sha1-1w9SmcEwjQXBL0Y4E7CgnnOxiV8=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0", - "babel-template": "6.26.0", - "babel-traverse": "6.26.0", - "babel-types": "6.26.0", - "lodash": "4.17.5" - }, - "dependencies": { - "lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", - "dev": true - } - } - }, - "babel-plugin-transform-es2015-classes": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-classes/-/babel-plugin-transform-es2015-classes-6.24.1.tgz", - "integrity": "sha1-WkxYpQyclGHlZLSyo7+ryXolhNs=", - "dev": true, - "requires": { - "babel-helper-define-map": "6.26.0", - "babel-helper-function-name": "6.24.1", - "babel-helper-optimise-call-expression": "6.24.1", - "babel-helper-replace-supers": "6.24.1", - "babel-messages": "6.23.0", - "babel-runtime": "6.26.0", - "babel-template": "6.26.0", - "babel-traverse": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-plugin-transform-es2015-computed-properties": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-computed-properties/-/babel-plugin-transform-es2015-computed-properties-6.24.1.tgz", - "integrity": "sha1-b+Ko0WiV1WNPTNmZttNICjCBWbM=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0", - "babel-template": "6.26.0" - } - }, - "babel-plugin-transform-es2015-destructuring": { - "version": "6.23.0", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-destructuring/-/babel-plugin-transform-es2015-destructuring-6.23.0.tgz", - "integrity": "sha1-mXux8auWf2gtKwh2/jWNYOdlxW0=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0" - } - }, - "babel-plugin-transform-es2015-duplicate-keys": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-duplicate-keys/-/babel-plugin-transform-es2015-duplicate-keys-6.24.1.tgz", - "integrity": "sha1-c+s9MQypaePvnskcU3QabxV2Qj4=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-plugin-transform-es2015-for-of": { - "version": "6.23.0", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-for-of/-/babel-plugin-transform-es2015-for-of-6.23.0.tgz", - "integrity": "sha1-9HyVsrYT3x0+zC/bdXNiPHUkhpE=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0" - } - }, - "babel-plugin-transform-es2015-function-name": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-function-name/-/babel-plugin-transform-es2015-function-name-6.24.1.tgz", - "integrity": "sha1-g0yJhTvDaxrw86TF26qU/Y6sqos=", - "dev": true, - "requires": { - "babel-helper-function-name": "6.24.1", - "babel-runtime": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-plugin-transform-es2015-literals": { - "version": "6.22.0", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-literals/-/babel-plugin-transform-es2015-literals-6.22.0.tgz", - "integrity": "sha1-T1SgLWzWbPkVKAAZox0xklN3yi4=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0" - } - }, - "babel-plugin-transform-es2015-modules-amd": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-modules-amd/-/babel-plugin-transform-es2015-modules-amd-6.24.1.tgz", - "integrity": "sha1-Oz5UAXI5hC1tGcMBHEvS8AoA0VQ=", - "dev": true, - "requires": { - "babel-plugin-transform-es2015-modules-commonjs": "6.26.0", - "babel-runtime": "6.26.0", - "babel-template": "6.26.0" - } - }, - "babel-plugin-transform-es2015-modules-commonjs": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-modules-commonjs/-/babel-plugin-transform-es2015-modules-commonjs-6.26.0.tgz", - "integrity": "sha1-DYOUApt9xqvhqX7xgeAHWN0uXYo=", - "dev": true, - "requires": { - "babel-plugin-transform-strict-mode": "6.24.1", - "babel-runtime": "6.26.0", - "babel-template": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-plugin-transform-es2015-modules-systemjs": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-modules-systemjs/-/babel-plugin-transform-es2015-modules-systemjs-6.24.1.tgz", - "integrity": "sha1-/4mhQrkRmpBhlfXxBuzzBdlAfSM=", - "dev": true, - "requires": { - "babel-helper-hoist-variables": "6.24.1", - "babel-runtime": "6.26.0", - "babel-template": "6.26.0" - } - }, - "babel-plugin-transform-es2015-modules-umd": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-modules-umd/-/babel-plugin-transform-es2015-modules-umd-6.24.1.tgz", - "integrity": "sha1-rJl+YoXNGO1hdq22B9YCNErThGg=", - "dev": true, - "requires": { - "babel-plugin-transform-es2015-modules-amd": "6.24.1", - "babel-runtime": "6.26.0", - "babel-template": "6.26.0" - } - }, - "babel-plugin-transform-es2015-object-super": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-object-super/-/babel-plugin-transform-es2015-object-super-6.24.1.tgz", - "integrity": "sha1-JM72muIcuDp/hgPa0CH1cusnj40=", - "dev": true, - "requires": { - "babel-helper-replace-supers": "6.24.1", - "babel-runtime": "6.26.0" - } - }, - "babel-plugin-transform-es2015-parameters": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-parameters/-/babel-plugin-transform-es2015-parameters-6.24.1.tgz", - "integrity": "sha1-V6w1GrScrxSpfNE7CfZv3wpiXys=", - "dev": true, - "requires": { - "babel-helper-call-delegate": "6.24.1", - "babel-helper-get-function-arity": "6.24.1", - "babel-runtime": "6.26.0", - "babel-template": "6.26.0", - "babel-traverse": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-plugin-transform-es2015-shorthand-properties": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-shorthand-properties/-/babel-plugin-transform-es2015-shorthand-properties-6.24.1.tgz", - "integrity": "sha1-JPh11nIch2YbvZmkYi5R8U3jiqA=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-plugin-transform-es2015-spread": { - "version": "6.22.0", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-spread/-/babel-plugin-transform-es2015-spread-6.22.0.tgz", - "integrity": "sha1-1taKmfia7cRTbIGlQujdnxdG+NE=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0" - } - }, - "babel-plugin-transform-es2015-sticky-regex": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-sticky-regex/-/babel-plugin-transform-es2015-sticky-regex-6.24.1.tgz", - "integrity": "sha1-AMHNsaynERLN8M9hJsLta0V8zbw=", - "dev": true, - "requires": { - "babel-helper-regex": "6.26.0", - "babel-runtime": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-plugin-transform-es2015-template-literals": { - "version": "6.22.0", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-template-literals/-/babel-plugin-transform-es2015-template-literals-6.22.0.tgz", - "integrity": "sha1-qEs0UPfp+PH2g51taH2oS7EjbY0=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0" - } - }, - "babel-plugin-transform-es2015-typeof-symbol": { - "version": "6.23.0", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-typeof-symbol/-/babel-plugin-transform-es2015-typeof-symbol-6.23.0.tgz", - "integrity": "sha1-3sCfHN3/lLUqxz1QXITfWdzOs3I=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0" - } - }, - "babel-plugin-transform-es2015-unicode-regex": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-unicode-regex/-/babel-plugin-transform-es2015-unicode-regex-6.24.1.tgz", - "integrity": "sha1-04sS9C6nMj9yk4fxinxa4frrNek=", - "dev": true, - "requires": { - "babel-helper-regex": "6.26.0", - "babel-runtime": "6.26.0", - "regexpu-core": "2.0.0" - } - }, - "babel-plugin-transform-regenerator": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-regenerator/-/babel-plugin-transform-regenerator-6.26.0.tgz", - "integrity": "sha1-4HA2lvveJ/Cj78rPi03KL3s6jy8=", - "dev": true, - "requires": { - "regenerator-transform": "0.10.1" - } - }, - "babel-plugin-transform-strict-mode": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-strict-mode/-/babel-plugin-transform-strict-mode-6.24.1.tgz", - "integrity": "sha1-1fr3qleKZbvlkc9e2uBKDGcCB1g=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0", - "babel-types": "6.26.0" - } - }, - "babel-preset-es2015": { - "version": "6.24.1", - "resolved": "https://registry.npmjs.org/babel-preset-es2015/-/babel-preset-es2015-6.24.1.tgz", - "integrity": "sha1-1EBQ1rwsn+6nAqrzjXJ6AhBTiTk=", - "dev": true, - "requires": { - "babel-plugin-check-es2015-constants": "6.22.0", - "babel-plugin-transform-es2015-arrow-functions": "6.22.0", - "babel-plugin-transform-es2015-block-scoped-functions": "6.22.0", - "babel-plugin-transform-es2015-block-scoping": "6.26.0", - "babel-plugin-transform-es2015-classes": "6.24.1", - "babel-plugin-transform-es2015-computed-properties": "6.24.1", - "babel-plugin-transform-es2015-destructuring": "6.23.0", - "babel-plugin-transform-es2015-duplicate-keys": "6.24.1", - "babel-plugin-transform-es2015-for-of": "6.23.0", - "babel-plugin-transform-es2015-function-name": "6.24.1", - "babel-plugin-transform-es2015-literals": "6.22.0", - "babel-plugin-transform-es2015-modules-amd": "6.24.1", - "babel-plugin-transform-es2015-modules-commonjs": "6.26.0", - "babel-plugin-transform-es2015-modules-systemjs": "6.24.1", - "babel-plugin-transform-es2015-modules-umd": "6.24.1", - "babel-plugin-transform-es2015-object-super": "6.24.1", - "babel-plugin-transform-es2015-parameters": "6.24.1", - "babel-plugin-transform-es2015-shorthand-properties": "6.24.1", - "babel-plugin-transform-es2015-spread": "6.22.0", - "babel-plugin-transform-es2015-sticky-regex": "6.24.1", - "babel-plugin-transform-es2015-template-literals": "6.22.0", - "babel-plugin-transform-es2015-typeof-symbol": "6.23.0", - "babel-plugin-transform-es2015-unicode-regex": "6.24.1", - "babel-plugin-transform-regenerator": "6.26.0" - } - }, - "babel-register": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-register/-/babel-register-6.26.0.tgz", - "integrity": "sha1-btAhFz4vy0htestFxgCahW9kcHE=", - "dev": true, - "requires": { - "babel-core": "6.26.0", - "babel-runtime": "6.26.0", - "core-js": "2.5.3", - "home-or-tmp": "2.0.0", - "lodash": "4.17.5", - "mkdirp": "0.5.1", - "source-map-support": "0.4.18" - }, - "dependencies": { - "core-js": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz", - "integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4=", - "dev": true - }, - "lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", - "dev": true - } - } - }, - "babel-runtime": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", - "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", - "dev": true, - "requires": { - "core-js": "2.4.1", - "regenerator-runtime": "0.11.1" - } - }, - "babel-template": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-template/-/babel-template-6.26.0.tgz", - "integrity": "sha1-3gPi0WOWsGn0bdn/+FIfsaDjXgI=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0", - "babel-traverse": "6.26.0", - "babel-types": "6.26.0", - "babylon": "6.18.0", - "lodash": "4.17.5" - }, - "dependencies": { - "lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", - "dev": true - } - } - }, - "babel-traverse": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", - "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", - "dev": true, - "requires": { - "babel-code-frame": "6.26.0", - "babel-messages": "6.23.0", - "babel-runtime": "6.26.0", - "babel-types": "6.26.0", - "babylon": "6.18.0", - "debug": "2.6.9", - "globals": "9.18.0", - "invariant": "2.2.2", - "lodash": "4.17.5" - }, - "dependencies": { - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "dev": true, - "requires": { - "chalk": "1.1.3", - "esutils": "2.0.2", - "js-tokens": "3.0.2" - } - }, - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "globals": { - "version": "9.18.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", - "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==", - "dev": true - }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", - "dev": true - }, - "lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", - "dev": true - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "babel-types": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", - "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", - "dev": true, - "requires": { - "babel-runtime": "6.26.0", - "esutils": "2.0.2", - "lodash": "4.17.5", - "to-fast-properties": "1.0.3" - }, - "dependencies": { - "lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", - "dev": true - } - } - }, - "babylon": { - "version": "6.18.0", - "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", - "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==", - "dev": true - }, - "backo2": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/backo2/-/backo2-1.0.2.tgz", - "integrity": "sha1-MasayLEpNjRj41s+u2n038+6eUc=", - "dev": true - }, - "balanced-match": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-0.4.2.tgz", - "integrity": "sha1-yz8+PHMtwPAe5wtAPzAuYddwmDg=" - }, - "base": { - "version": "0.11.2", - "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", - "integrity": "sha1-e95c7RRbbVUakNuH+DxVi060io8=", - "dev": true, - "requires": { - "cache-base": "1.0.1", - "class-utils": "0.3.6", - "component-emitter": "1.2.1", - "define-property": "1.0.0", - "isobject": "3.0.1", - "mixin-deep": "1.3.0", - "pascalcase": "0.1.1" - }, - "dependencies": { - "component-emitter": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", - "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=", - "dev": true - }, - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - } - } - }, - "base64-arraybuffer": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-0.1.5.tgz", - "integrity": "sha1-c5JncZI7Whl0etZmqlzUv5xunOg=", - "dev": true - }, - "base64-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.2.1.tgz", - "integrity": "sha512-dwVUVIXsBZXwTuwnXI9RK8sBmgq09NDHzyR9SAph9eqk76gKK2JSQmZARC2zRC81JC2QTtxD0ARU5qTS25gIGw==", - "dev": true - }, - "base64id": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/base64id/-/base64id-1.0.0.tgz", - "integrity": "sha1-R2iMuZu2gE8OBtPnY7HDLlfY5rY=", - "dev": true - }, - "batch": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/batch/-/batch-0.6.1.tgz", - "integrity": "sha1-3DQxT05nkxgJP8dgJyUl+UvyXBY=", - "dev": true - }, - "bcrypt-pbkdf": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.0.tgz", - "integrity": "sha1-PKdrhSQccXC/fZcD57mqdGMAQNQ=", - "dev": true, - "optional": true, - "requires": { - "tweetnacl": "0.14.3" - } - }, - "beeper": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/beeper/-/beeper-1.1.1.tgz", - "integrity": "sha1-5tXqjF2tABMEpwsiY4RH9pyy+Ak=", - "dev": true - }, - "better-assert": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/better-assert/-/better-assert-1.0.2.tgz", - "integrity": "sha1-QIZrnhueC1W0gYlDEeaPr/rrxSI=", - "dev": true, - "requires": { - "callsite": "1.0.0" - } - }, - "big.js": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/big.js/-/big.js-3.1.3.tgz", - "integrity": "sha1-TK2iGTZS6zyp7I5VyQFWacmAaXg=", - "dev": true - }, - "binary-extensions": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.8.0.tgz", - "integrity": "sha1-SOyNFt9Dd+rl+liEaCSAr02Vx3Q=", - "dev": true - }, - "blob": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/blob/-/blob-0.0.4.tgz", - "integrity": "sha1-vPEwUspURj8w+fx+lbmkdjCpSSE=", - "dev": true - }, - "block-stream": { - "version": "0.0.9", - "resolved": "https://registry.npmjs.org/block-stream/-/block-stream-0.0.9.tgz", - "integrity": "sha1-E+v+d4oDIFz+A3UUgeu0szAMEmo=", - "dev": true, - "requires": { - "inherits": "2.0.3" - } - }, - "bluebird": { - "version": "3.5.1", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz", - "integrity": "sha1-2VUfnemPH82h5oPRfukaBgLuLrk=", - "dev": true - }, - "bn.js": { - "version": "4.11.8", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.8.tgz", - "integrity": "sha512-ItfYfPLkWHUjckQCk8xC+LwxgK8NYcXywGigJgSwOP8Y2iyWT4f2vsZnoOXTTbo+o5yXmIUJ4gn5538SO5S3gA==", - "dev": true - }, - "body-parser": { - "version": "1.18.2", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.2.tgz", - "integrity": "sha1-h2eKGdhLR9hZuDGZvVm84iKxBFQ=", - "dev": true, - "requires": { - "bytes": "3.0.0", - "content-type": "1.0.4", - "debug": "2.6.9", - "depd": "1.1.2", - "http-errors": "1.6.2", - "iconv-lite": "0.4.19", - "on-finished": "2.3.0", - "qs": "6.5.1", - "raw-body": "2.3.2", - "type-is": "1.6.15" - }, - "dependencies": { - "bytes": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", - "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=", - "dev": true - }, - "content-type": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", - "integrity": "sha1-4TjMdeBAxyexlm/l5fjJruJW/js=", - "dev": true - }, - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha1-XRKFFd8TT/Mn6QpMk/Tgd6U2NB8=", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "depd": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", - "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", - "dev": true - }, - "http-errors": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.2.tgz", - "integrity": "sha1-CgAsyFcHGSp+eUbO7cERVfYOxzY=", - "dev": true, - "requires": { - "depd": "1.1.1", - "inherits": "2.0.3", - "setprototypeof": "1.0.3", - "statuses": "1.3.1" - }, - "dependencies": { - "depd": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.1.tgz", - "integrity": "sha1-V4O04cRZ8G+lyif5kfPQbnoxA1k=", - "dev": true + "name": "salix-back", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@babel/code-frame": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz", + "integrity": "sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==", + "dev": true, + "requires": { + "@babel/highlight": "^7.0.0" } - } }, - "mime-db": { - "version": "1.30.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.30.0.tgz", - "integrity": "sha1-dMZD2i3Z1qRTmZY0ZbJtXKfXHwE=", - "dev": true - }, - "mime-types": { - "version": "2.1.17", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.17.tgz", - "integrity": "sha1-Cdejk/A+mVp5+K+Fe3Cp4KsWVXo=", - "dev": true, - "requires": { - "mime-db": "1.30.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - }, - "qs": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.1.tgz", - "integrity": "sha1-NJzfbu+J7EXBLX1es/wMhwNDptg=", - "dev": true - }, - "setprototypeof": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.0.3.tgz", - "integrity": "sha1-ZlZ+NwQ+608E2RvWWMDL77VbjgQ=", - "dev": true - }, - "type-is": { - "version": "1.6.15", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.15.tgz", - "integrity": "sha1-yrEPtJCeRByChC6v4a1kbIGARBA=", - "dev": true, - "requires": { - "media-typer": "0.3.0", - "mime-types": "2.1.17" - } - } - } - }, - "bonjour": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/bonjour/-/bonjour-3.5.0.tgz", - "integrity": "sha1-jokKGD2O6aI5OzhExpGkK897yfU=", - "dev": true, - "requires": { - "array-flatten": "2.1.1", - "deep-equal": "1.0.1", - "dns-equal": "1.0.0", - "dns-txt": "2.0.2", - "multicast-dns": "6.2.3", - "multicast-dns-service-types": "1.1.0" - } - }, - "boom": { - "version": "2.10.1", - "resolved": "https://registry.npmjs.org/boom/-/boom-2.10.1.tgz", - "integrity": "sha1-OciRjO/1eZ+D+UkqhI9iWt0Mdm8=", - "dev": true, - "requires": { - "hoek": "2.16.3" - } - }, - "boxen": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/boxen/-/boxen-1.2.1.tgz", - "integrity": "sha1-DxHn/jRO25OXl3/BPt5/ZNlWSB0=", - "dev": true, - "requires": { - "ansi-align": "2.0.0", - "camelcase": "4.1.0", - "chalk": "2.1.0", - "cli-boxes": "1.0.0", - "string-width": "2.1.1", - "term-size": "1.2.0", - "widest-line": "1.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", - "dev": true - }, - "ansi-styles": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.0.tgz", - "integrity": "sha1-wVm41b4PnlpvNG2rlPFs4CIWG4g=", - "dev": true, - "requires": { - "color-convert": "1.9.0" - } - }, - "camelcase": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", - "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=", - "dev": true - }, - "chalk": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.1.0.tgz", - "integrity": "sha1-rFvs8U+iG5nGySynp9fP1bF+dD4=", - "dev": true, - "requires": { - "ansi-styles": "3.2.0", - "escape-string-regexp": "1.0.5", - "supports-color": "4.4.0" - } - }, - "has-flag": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz", - "integrity": "sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=", - "dev": true - }, - "is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", - "dev": true - }, - "string-width": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", - "integrity": "sha1-q5Pyeo3BPSjKyBXEYhQ6bZASrp4=", - "dev": true, - "requires": { - "is-fullwidth-code-point": "2.0.0", - "strip-ansi": "4.0.0" - } - }, - "strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "dev": true, - "requires": { - "ansi-regex": "3.0.0" - } - }, - "supports-color": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-4.4.0.tgz", - "integrity": "sha1-iD992rwWUUKyphQn8zUt7RldGj4=", - "dev": true, - "requires": { - "has-flag": "2.0.0" - } - } - } - }, - "brace-expansion": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.6.tgz", - "integrity": "sha1-cZfX6qm4fmSDkOph/GbIRCdCDfk=", - "requires": { - "balanced-match": "0.4.2", - "concat-map": "0.0.1" - } - }, - "braces": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", - "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", - "dev": true, - "requires": { - "expand-range": "1.8.2", - "preserve": "0.2.0", - "repeat-element": "1.1.2" - } - }, - "brorand": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", - "integrity": "sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8=", - "dev": true - }, - "browserify-aes": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.1.1.tgz", - "integrity": "sha512-UGnTYAnB2a3YuYKIRy1/4FB2HdM866E0qC46JXvVTYKlBlZlnvfpSfY6OKfXZAkv70eJ2a1SqzpAo5CRhZGDFg==", - "dev": true, - "requires": { - "buffer-xor": "1.0.3", - "cipher-base": "1.0.4", - "create-hash": "1.1.3", - "evp_bytestokey": "1.0.3", - "inherits": "2.0.3", - "safe-buffer": "5.1.1" - } - }, - "browserify-cipher": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.0.tgz", - "integrity": "sha1-mYgkSHS/XtTijalWZtzWasj8Njo=", - "dev": true, - "requires": { - "browserify-aes": "1.1.1", - "browserify-des": "1.0.0", - "evp_bytestokey": "1.0.3" - } - }, - "browserify-des": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.0.tgz", - "integrity": "sha1-2qJ3cXRwki7S/hhZQRihdUOXId0=", - "dev": true, - "requires": { - "cipher-base": "1.0.4", - "des.js": "1.0.0", - "inherits": "2.0.3" - } - }, - "browserify-rsa": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", - "integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=", - "dev": true, - "requires": { - "bn.js": "4.11.8", - "randombytes": "2.0.6" - } - }, - "browserify-sign": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.0.4.tgz", - "integrity": "sha1-qk62jl17ZYuqa/alfmMMvXqT0pg=", - "dev": true, - "requires": { - "bn.js": "4.11.8", - "browserify-rsa": "4.0.1", - "create-hash": "1.1.3", - "create-hmac": "1.1.6", - "elliptic": "6.4.0", - "inherits": "2.0.3", - "parse-asn1": "5.1.0" - } - }, - "browserify-zlib": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz", - "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", - "dev": true, - "requires": { - "pako": "1.0.6" - } - }, - "buffer": { - "version": "4.9.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz", - "integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=", - "dev": true, - "requires": { - "base64-js": "1.2.1", - "ieee754": "1.1.8", - "isarray": "1.0.0" - } - }, - "buffer-indexof": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/buffer-indexof/-/buffer-indexof-1.1.1.tgz", - "integrity": "sha512-4/rOEg86jivtPTeOUUT61jJO1Ya1TrR/OkqCSZDyq84WJh3LuuiphBYJN+fm5xufIk4XAFcEwte/8WzC8If/1g==", - "dev": true - }, - "buffer-shims": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/buffer-shims/-/buffer-shims-1.0.0.tgz", - "integrity": "sha1-mXjOMXOIxkmth5MCjDR37wRKi1E=" - }, - "buffer-xor": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", - "integrity": "sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk=", - "dev": true - }, - "bufferstreams": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/bufferstreams/-/bufferstreams-1.1.0.tgz", - "integrity": "sha1-BzzRIDCMBnjufXxItp4G60U4reA=", - "dev": true, - "requires": { - "readable-stream": "2.1.5" - } - }, - "builtin-modules": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", - "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", - "dev": true - }, - "builtin-status-codes": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz", - "integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug=", - "dev": true - }, - "bytes": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", - "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=", - "dev": true - }, - "cache-base": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", - "integrity": "sha1-Cn9GQWgxyLZi7jb+TnxZ129marI=", - "dev": true, - "requires": { - "collection-visit": "1.0.0", - "component-emitter": "1.2.1", - "get-value": "2.0.6", - "has-value": "1.0.0", - "isobject": "3.0.1", - "set-value": "2.0.0", - "to-object-path": "0.3.0", - "union-value": "1.0.0", - "unset-value": "1.0.0" - }, - "dependencies": { - "component-emitter": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", - "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=", - "dev": true - }, - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - } - } - }, - "caller-path": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/caller-path/-/caller-path-0.1.0.tgz", - "integrity": "sha1-lAhe9jWB7NPaqSREqP6U6CV3dR8=", - "requires": { - "callsites": "0.2.0" - } - }, - "callsite": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/callsite/-/callsite-1.0.0.tgz", - "integrity": "sha1-KAOY5dZkvXQDi28JBRU+borxvCA=", - "dev": true - }, - "callsites": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-0.2.0.tgz", - "integrity": "sha1-r6uWJikQp/M8GaV3WCXGnzTjUMo=" - }, - "camel-case": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/camel-case/-/camel-case-3.0.0.tgz", - "integrity": "sha1-yjw2iKTpzzpM2nd9xNy8cTJJz3M=", - "dev": true, - "requires": { - "no-case": "2.3.0", - "upper-case": "1.1.3" - } - }, - "camelcase": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", - "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=", - "dev": true - }, - "camelcase-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", - "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", - "dev": true, - "requires": { - "camelcase": "2.1.1", - "map-obj": "1.0.1" - } - }, - "capture-stack-trace": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/capture-stack-trace/-/capture-stack-trace-1.0.0.tgz", - "integrity": "sha1-Sm+gc5nCa7pH8LJJa00PtAjFVQ0=", - "dev": true - }, - "cardinal": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/cardinal/-/cardinal-1.0.0.tgz", - "integrity": "sha1-UOIcGwqjdyn5N33vGWtanOyTLuk=", - "dev": true, - "requires": { - "ansicolors": "0.2.1", - "redeyed": "1.0.1" - } - }, - "caseless": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.11.0.tgz", - "integrity": "sha1-cVuW6phBWTzDMGeSP17GDr2k99c=", - "dev": true - }, - "center-align": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/center-align/-/center-align-0.1.3.tgz", - "integrity": "sha1-qg0yYptu6XIgBBHL1EYckHvCt60=", - "dev": true, - "requires": { - "align-text": "0.1.4", - "lazy-cache": "1.0.4" - } - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "2.2.1", - "escape-string-regexp": "1.0.5", - "has-ansi": "2.0.0", - "strip-ansi": "3.0.1", - "supports-color": "2.0.0" - } - }, - "chardet": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.4.2.tgz", - "integrity": "sha1-tUc7M9yXxCTl2Y3IfVXU2KKci/I=" - }, - "chokidar": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-1.6.1.tgz", - "integrity": "sha1-L0RHq16W5Q+z14n9kNTHLg5McMI=", - "dev": true, - "requires": { - "anymatch": "1.3.0", - "async-each": "1.0.1", - "fsevents": "1.1.3", - "glob-parent": "2.0.0", - "inherits": "2.0.3", - "is-binary-path": "1.0.1", - "is-glob": "2.0.1", - "path-is-absolute": "1.0.1", - "readdirp": "2.1.0" - } - }, - "cipher-base": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz", - "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", - "dev": true, - "requires": { - "inherits": "2.0.3", - "safe-buffer": "5.1.1" - } - }, - "circular-json": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/circular-json/-/circular-json-0.3.3.tgz", - "integrity": "sha512-UZK3NBx2Mca+b5LsG7bY183pHWt5Y1xts4P3Pz7ENTwGVnJOUWbRb3ocjvX7hx9tq/yTAdclXm9sZ38gNuem4A==" - }, - "class-utils": { - "version": "0.3.6", - "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", - "integrity": "sha1-+TNprouafOAv1B+q0MqDAzGQxGM=", - "dev": true, - "requires": { - "arr-union": "3.1.0", - "define-property": "0.2.5", - "isobject": "3.0.1", - "static-extend": "0.1.2" - }, - "dependencies": { - "arr-union": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", - "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", - "dev": true - }, - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "0.1.6" - } - }, - "is-accessor-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", - "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "dev": true - }, - "is-data-descriptor": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", - "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "is-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", - "integrity": "sha1-Nm2CQN3kh8pRgjsaufB6EKeCUco=", - "dev": true, - "requires": { - "is-accessor-descriptor": "0.1.6", - "is-data-descriptor": "0.1.4", - "kind-of": "5.1.0" - } - }, - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - }, - "kind-of": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", - "integrity": "sha1-cpyR4thXt6QZofmqZWhcTDP1hF0=", - "dev": true - } - } - }, - "clean-css": { - "version": "3.4.21", - "resolved": "https://registry.npmjs.org/clean-css/-/clean-css-3.4.21.tgz", - "integrity": "sha1-IQHV29GdY9vBanXr1XDnwzlI9ls=", - "dev": true, - "requires": { - "commander": "2.8.1", - "source-map": "0.4.4" - }, - "dependencies": { - "commander": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.8.1.tgz", - "integrity": "sha1-Br42f+v9oMMwqh4qBy09yXYkJdQ=", - "dev": true, - "requires": { - "graceful-readlink": "1.0.1" - } - }, - "source-map": { - "version": "0.4.4", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz", - "integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=", - "dev": true, - "requires": { - "amdefine": "1.0.1" - } - } - } - }, - "cli-boxes": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", - "integrity": "sha1-T6kXw+WclKAEzWH47lCdplFocUM=", - "dev": true - }, - "cli-cursor": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", - "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", - "requires": { - "restore-cursor": "2.0.0" - } - }, - "cli-width": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.0.tgz", - "integrity": "sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk=" - }, - "cliui": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", - "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=", - "dev": true, - "requires": { - "string-width": "1.0.2", - "strip-ansi": "3.0.1", - "wrap-ansi": "2.0.0" - } - }, - "clone": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.2.tgz", - "integrity": "sha1-Jgt6meux7f4kdTgXX3gyQ8sZ0Uk=", - "dev": true - }, - "clone-deep": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-0.3.0.tgz", - "integrity": "sha1-NIxhrpzb4O3+BT2R/0zFIdeQ7eg=", - "dev": true, - "requires": { - "for-own": "1.0.0", - "is-plain-object": "2.0.4", - "kind-of": "3.2.2", - "shallow-clone": "0.1.2" - }, - "dependencies": { - "for-in": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", - "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", - "dev": true - }, - "for-own": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/for-own/-/for-own-1.0.0.tgz", - "integrity": "sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=", - "dev": true, - "requires": { - "for-in": "1.0.2" - } - }, - "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "dev": true - }, - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "clone-stats": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-0.0.1.tgz", - "integrity": "sha1-uI+UqCzzi4eR1YBG6kAprYjKmdE=", - "dev": true - }, - "co": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=" - }, - "code-point-at": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", - "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", - "dev": true - }, - "collection-visit": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz", - "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", - "dev": true, - "requires": { - "map-visit": "1.0.0", - "object-visit": "1.0.1" - } - }, - "color-convert": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.0.tgz", - "integrity": "sha1-Gsz5fdc5uYO/mU1W/sj5WFNkG3o=", - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" - }, - "color-support": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", - "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", - "dev": true - }, - "colors": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/colors/-/colors-1.1.2.tgz", - "integrity": "sha1-FopHAXVran9RoSzgyXv6KMCE7WM=", - "dev": true - }, - "combine-lists": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/combine-lists/-/combine-lists-1.0.1.tgz", - "integrity": "sha1-RYwH4J4NkA/Ci3Cj/sLazR0st/Y=", - "dev": true, - "requires": { - "lodash": "4.16.6" - } - }, - "combined-stream": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.5.tgz", - "integrity": "sha1-k4NwpXtKUd6ix3wV1cX9+JUWQAk=", - "dev": true, - "requires": { - "delayed-stream": "1.0.0" - } - }, - "commander": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.9.0.tgz", - "integrity": "sha1-nJkJQXbhIkDLItbFFGCYQA/g99Q=", - "dev": true, - "requires": { - "graceful-readlink": "1.0.1" - } - }, - "commondir": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", - "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", - "dev": true - }, - "component-bind": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/component-bind/-/component-bind-1.0.0.tgz", - "integrity": "sha1-AMYIq33Nk4l8AAllGx06jh5zu9E=", - "dev": true - }, - "component-emitter": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.1.2.tgz", - "integrity": "sha1-KWWU8nU9qmOZbSrwjRWpURbJrsM=", - "dev": true - }, - "component-inherit": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/component-inherit/-/component-inherit-0.0.3.tgz", - "integrity": "sha1-ZF/ErfWLcrZJ1crmUTVhnbJv8UM=", - "dev": true - }, - "compressible": { - "version": "2.0.12", - "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.12.tgz", - "integrity": "sha1-xZpcmdt2dn6YdlAOJx72OzSTvWY=", - "dev": true, - "requires": { - "mime-db": "1.32.0" - }, - "dependencies": { - "mime-db": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.32.0.tgz", - "integrity": "sha512-+ZWo/xZN40Tt6S+HyakUxnSOgff+JEdaneLWIm0Z6LmpCn5DMcZntLyUY5c/rTDog28LhXLKOUZKoTxTCAdBVw==", - "dev": true - } - } - }, - "compression": { - "version": "1.7.1", - "resolved": "https://registry.npmjs.org/compression/-/compression-1.7.1.tgz", - "integrity": "sha1-7/JgPvwuIs+G810uuTWJ+YdTc9s=", - "dev": true, - "requires": { - "accepts": "1.3.4", - "bytes": "3.0.0", - "compressible": "2.0.12", - "debug": "2.6.9", - "on-headers": "1.0.1", - "safe-buffer": "5.1.1", - "vary": "1.1.2" - }, - "dependencies": { - "accepts": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.4.tgz", - "integrity": "sha1-hiRnWMfdbSGmR0/whKR0DsBesh8=", - "dev": true, - "requires": { - "mime-types": "2.1.17", - "negotiator": "0.6.1" - } - }, - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "mime-db": { - "version": "1.30.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.30.0.tgz", - "integrity": "sha1-dMZD2i3Z1qRTmZY0ZbJtXKfXHwE=", - "dev": true - }, - "mime-types": { - "version": "2.1.17", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.17.tgz", - "integrity": "sha1-Cdejk/A+mVp5+K+Fe3Cp4KsWVXo=", - "dev": true, - "requires": { - "mime-db": "1.30.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" - }, - "concat-stream": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.0.tgz", - "integrity": "sha1-CqxmL9Ur54lk1VMvaUeE5wEQrPc=", - "requires": { - "inherits": "2.0.3", - "readable-stream": "2.3.3", - "typedarray": "0.0.6" - }, - "dependencies": { - "readable-stream": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.3.tgz", - "integrity": "sha1-No8lEtefnUb9/HE0mueHi7weuVw=", - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "safe-buffer": "5.1.1", - "string_decoder": "1.0.3", - "util-deprecate": "1.0.2" - } - }, - "string_decoder": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", - "integrity": "sha1-D8Z9fBQYJd6UKC3VNr7GubzoYKs=", - "requires": { - "safe-buffer": "5.1.1" - } - } - } - }, - "configstore": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/configstore/-/configstore-3.1.1.tgz", - "integrity": "sha1-CU7mYquD+tmRdnjeEU+q6o/NypA=", - "dev": true, - "requires": { - "dot-prop": "4.2.0", - "graceful-fs": "4.1.10", - "make-dir": "1.0.0", - "unique-string": "1.0.0", - "write-file-atomic": "2.3.0", - "xdg-basedir": "3.0.0" - } - }, - "connect": { - "version": "3.6.5", - "resolved": "https://registry.npmjs.org/connect/-/connect-3.6.5.tgz", - "integrity": "sha1-+43ee6B2OHfQ7J352sC0tA5yx9o=", - "dev": true, - "requires": { - "debug": "2.6.9", - "finalhandler": "1.0.6", - "parseurl": "1.3.2", - "utils-merge": "1.0.1" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha1-XRKFFd8TT/Mn6QpMk/Tgd6U2NB8=", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "finalhandler": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.0.6.tgz", - "integrity": "sha1-AHrqM9Gk0+QgF/YkhIrVjSEvgU8=", - "dev": true, - "requires": { - "debug": "2.6.9", - "encodeurl": "1.0.1", - "escape-html": "1.0.3", - "on-finished": "2.3.0", - "parseurl": "1.3.2", - "statuses": "1.3.1", - "unpipe": "1.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - }, - "parseurl": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz", - "integrity": "sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=", - "dev": true - }, - "utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=", - "dev": true - } - } - }, - "connect-history-api-fallback": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/connect-history-api-fallback/-/connect-history-api-fallback-1.5.0.tgz", - "integrity": "sha1-sGhzk0vF40T+9hGhlqb6rgruAVo=", - "dev": true - }, - "console-browserify": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", - "integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=", - "dev": true, - "requires": { - "date-now": "0.1.4" - } - }, - "console-control-strings": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", - "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", - "dev": true - }, - "constants-browserify": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz", - "integrity": "sha1-wguW2MYXdIqvHBYCF2DNJ/y4y3U=", - "dev": true - }, - "content-disposition": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz", - "integrity": "sha1-DPaLud318r55YcOoUXjLhdunjLQ=", - "dev": true - }, - "content-type": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", - "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", - "dev": true - }, - "convert-source-map": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.5.1.tgz", - "integrity": "sha1-uCeAl7m8IpNl3lxiz1/K7YtVmeU=", - "dev": true - }, - "cookie": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz", - "integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=", - "dev": true - }, - "cookie-signature": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", - "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=", - "dev": true - }, - "copy-descriptor": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", - "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", - "dev": true - }, - "core-js": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.4.1.tgz", - "integrity": "sha1-TekR5mew6ukSTjQlS1OupvxhjT4=", - "dev": true - }, - "core-util-is": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" - }, - "cors": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.1.tgz", - "integrity": "sha1-YYGqVqu0WiglvjMEcDdHrk6dI4M=", - "dev": true, - "requires": { - "vary": "1.1.0" - }, - "dependencies": { - "vary": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.0.tgz", - "integrity": "sha1-4eWv+70WrnaN0mdDlLmtMCJlMUA=", - "dev": true - } - } - }, - "create-ecdh": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.0.tgz", - "integrity": "sha1-iIxyNZbN92EvZJgjPuvXo1MBc30=", - "dev": true, - "requires": { - "bn.js": "4.11.8", - "elliptic": "6.4.0" - } - }, - "create-error-class": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/create-error-class/-/create-error-class-3.0.2.tgz", - "integrity": "sha1-Br56vvlHo/FKMP1hBnHUAbyot7Y=", - "dev": true, - "requires": { - "capture-stack-trace": "1.0.0" - } - }, - "create-hash": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.1.3.tgz", - "integrity": "sha1-YGBCrIuSYnUPSDyt2rD1gZFy2P0=", - "dev": true, - "requires": { - "cipher-base": "1.0.4", - "inherits": "2.0.3", - "ripemd160": "2.0.1", - "sha.js": "2.4.10" - } - }, - "create-hmac": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.6.tgz", - "integrity": "sha1-rLniIaThe9sHbpBlfEK5PjcmzwY=", - "dev": true, - "requires": { - "cipher-base": "1.0.4", - "create-hash": "1.1.3", - "inherits": "2.0.3", - "ripemd160": "2.0.1", - "safe-buffer": "5.1.1", - "sha.js": "2.4.10" - } - }, - "cross-spawn": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-3.0.1.tgz", - "integrity": "sha1-ElYDfsufDF9549bvE14wdwGEuYI=", - "dev": true, - "requires": { - "lru-cache": "4.0.1", - "which": "1.2.11" - } - }, - "cryptiles": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/cryptiles/-/cryptiles-2.0.5.tgz", - "integrity": "sha1-O9/s3GCBR8HGcgL6KR59ylnqo7g=", - "dev": true, - "requires": { - "boom": "2.10.1" - } - }, - "crypto-browserify": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", - "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", - "dev": true, - "requires": { - "browserify-cipher": "1.0.0", - "browserify-sign": "4.0.4", - "create-ecdh": "4.0.0", - "create-hash": "1.1.3", - "create-hmac": "1.1.6", - "diffie-hellman": "5.0.2", - "inherits": "2.0.3", - "pbkdf2": "3.0.14", - "public-encrypt": "4.0.0", - "randombytes": "2.0.6", - "randomfill": "1.0.3" - } - }, - "crypto-random-string": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-1.0.0.tgz", - "integrity": "sha1-ojD2T1aDEOFJgAmUB5DsmVRbyn4=", - "dev": true - }, - "css-loader": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-0.25.0.tgz", - "integrity": "sha1-w/68jOKPTINXa2sTcH9H+Qw5AiM=", - "dev": true, - "requires": { - "babel-code-frame": "6.16.0", - "css-selector-tokenizer": "0.6.0", - "cssnano": "3.7.7", - "loader-utils": "0.2.16", - "lodash.camelcase": "3.0.1", - "object-assign": "4.1.0", - "postcss": "5.2.4", - "postcss-modules-extract-imports": "1.0.1", - "postcss-modules-local-by-default": "1.1.1", - "postcss-modules-scope": "1.0.2", - "postcss-modules-values": "1.2.2", - "source-list-map": "0.1.6" - }, - "dependencies": { - "babel-code-frame": { - "version": "6.16.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.16.0.tgz", - "integrity": "sha1-+Q5g2ghikJ084JhzO105h8l8uN4=", - "dev": true, - "requires": { - "chalk": "1.1.3", - "esutils": "2.0.2", - "js-tokens": "2.0.0" - }, - "dependencies": { - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "dev": true, - "requires": { - "ansi-styles": "2.2.1", - "escape-string-regexp": "1.0.5", - "has-ansi": "2.0.0", - "strip-ansi": "3.0.1", - "supports-color": "2.0.0" - }, - "dependencies": { - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", - "dev": true - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true - }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "dev": true, - "requires": { - "ansi-regex": "2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz", - "integrity": "sha1-xQYbbg74qBd15Q9dZhUb9r83EQc=", - "dev": true + "@babel/core": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.6.0.tgz", + "integrity": "sha512-FuRhDRtsd6IptKpHXAa+4WPZYY2ZzgowkbLBecEDDSje1X/apG7jQM33or3NdOmjXBKWGOg4JmSiRfUfuTtHXw==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.5.5", + "@babel/generator": "^7.6.0", + "@babel/helpers": "^7.6.0", + "@babel/parser": "^7.6.0", + "@babel/template": "^7.6.0", + "@babel/traverse": "^7.6.0", + "@babel/types": "^7.6.0", + "convert-source-map": "^1.1.0", + "debug": "^4.1.0", + "json5": "^2.1.0", + "lodash": "^4.17.13", + "resolve": "^1.3.2", + "semver": "^5.4.1", + "source-map": "^0.5.0" + }, + "dependencies": { + "@babel/code-frame": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.5.5.tgz", + "integrity": "sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw==", + "dev": true, + "requires": { + "@babel/highlight": "^7.0.0" + } + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", + "dev": true + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "@babel/generator": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.6.0.tgz", + "integrity": "sha512-Ms8Mo7YBdMMn1BYuNtKuP/z0TgEIhbcyB8HVR6PPNYp4P61lMsABiS4A3VG1qznjXVCf3r+fVHhm4efTYVsySA==", + "dev": true, + "requires": { + "@babel/types": "^7.6.0", + "jsesc": "^2.5.1", + "lodash": "^4.17.13", + "source-map": "^0.5.0", + "trim-right": "^1.0.1" + }, + "dependencies": { + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", + "dev": true + } + } + }, + "@babel/helper-annotate-as-pure": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.0.0.tgz", + "integrity": "sha512-3UYcJUj9kvSLbLbUIfQTqzcy5VX7GRZ/CCDrnOaZorFFM01aXp1+GJwuFGV4NDDoAS+mOUyHcO6UD/RfqOks3Q==", + "dev": true, + "requires": { + "@babel/types": "^7.0.0" + } + }, + "@babel/helper-builder-binary-assignment-operator-visitor": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.1.0.tgz", + "integrity": "sha512-qNSR4jrmJ8M1VMM9tibvyRAHXQs2PmaksQF7c1CGJNipfe3D8p+wgNwgso/P2A2r2mdgBWAXljNWR0QRZAMW8w==", + "dev": true, + "requires": { + "@babel/helper-explode-assignable-expression": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "@babel/helper-call-delegate": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/helper-call-delegate/-/helper-call-delegate-7.4.4.tgz", + "integrity": "sha512-l79boDFJ8S1c5hvQvG+rc+wHw6IuH7YldmRKsYtpbawsxURu/paVy57FZMomGK22/JckepaikOkY0MoAmdyOlQ==", + "dev": true, + "requires": { + "@babel/helper-hoist-variables": "^7.4.4", + "@babel/traverse": "^7.4.4", + "@babel/types": "^7.4.4" + } + }, + "@babel/helper-define-map": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/helper-define-map/-/helper-define-map-7.5.5.tgz", + "integrity": "sha512-fTfxx7i0B5NJqvUOBBGREnrqbTxRh7zinBANpZXAVDlsZxYdclDp467G1sQ8VZYMnAURY3RpBUAgOYT9GfzHBg==", + "dev": true, + "requires": { + "@babel/helper-function-name": "^7.1.0", + "@babel/types": "^7.5.5", + "lodash": "^4.17.13" + }, + "dependencies": { + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", + "dev": true + } + } + }, + "@babel/helper-explode-assignable-expression": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.1.0.tgz", + "integrity": "sha512-NRQpfHrJ1msCHtKjbzs9YcMmJZOg6mQMmGRB+hbamEdG5PNpaSm95275VD92DvJKuyl0s2sFiDmMZ+EnnvufqA==", + "dev": true, + "requires": { + "@babel/traverse": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "@babel/helper-function-name": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz", + "integrity": "sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==", + "dev": true, + "requires": { + "@babel/helper-get-function-arity": "^7.0.0", + "@babel/template": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "@babel/helper-get-function-arity": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz", + "integrity": "sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==", + "dev": true, + "requires": { + "@babel/types": "^7.0.0" + } + }, + "@babel/helper-hoist-variables": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.4.4.tgz", + "integrity": "sha512-VYk2/H/BnYbZDDg39hr3t2kKyifAm1W6zHRfhx8jGjIHpQEBv9dry7oQ2f3+J703TLu69nYdxsovl0XYfcnK4w==", + "dev": true, + "requires": { + "@babel/types": "^7.4.4" + } + }, + "@babel/helper-member-expression-to-functions": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.5.5.tgz", + "integrity": "sha512-5qZ3D1uMclSNqYcXqiHoA0meVdv+xUEex9em2fqMnrk/scphGlGgg66zjMrPJESPwrFJ6sbfFQYUSa0Mz7FabA==", + "dev": true, + "requires": { + "@babel/types": "^7.5.5" + } + }, + "@babel/helper-module-imports": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.0.0.tgz", + "integrity": "sha512-aP/hlLq01DWNEiDg4Jn23i+CXxW/owM4WpDLFUbpjxe4NS3BhLVZQ5i7E0ZrxuQ/vwekIeciyamgB1UIYxxM6A==", + "dev": true, + "requires": { + "@babel/types": "^7.0.0" + } + }, + "@babel/helper-module-transforms": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.5.5.tgz", + "integrity": "sha512-jBeCvETKuJqeiaCdyaheF40aXnnU1+wkSiUs/IQg3tB85up1LyL8x77ClY8qJpuRJUcXQo+ZtdNESmZl4j56Pw==", + "dev": true, + "requires": { + "@babel/helper-module-imports": "^7.0.0", + "@babel/helper-simple-access": "^7.1.0", + "@babel/helper-split-export-declaration": "^7.4.4", + "@babel/template": "^7.4.4", + "@babel/types": "^7.5.5", + "lodash": "^4.17.13" + }, + "dependencies": { + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", + "dev": true + } + } + }, + "@babel/helper-optimise-call-expression": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.0.0.tgz", + "integrity": "sha512-u8nd9NQePYNQV8iPWu/pLLYBqZBa4ZaY1YWRFMuxrid94wKI1QNt67NEZ7GAe5Kc/0LLScbim05xZFWkAdrj9g==", + "dev": true, + "requires": { + "@babel/types": "^7.0.0" + } + }, + "@babel/helper-plugin-utils": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.0.0.tgz", + "integrity": "sha512-CYAOUCARwExnEixLdB6sDm2dIJ/YgEAKDM1MOeMeZu9Ld/bDgVo8aiWrXwcY7OBh+1Ea2uUcVRcxKk0GJvW7QA==", + "dev": true + }, + "@babel/helper-regex": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/helper-regex/-/helper-regex-7.5.5.tgz", + "integrity": "sha512-CkCYQLkfkiugbRDO8eZn6lRuR8kzZoGXCg3149iTk5se7g6qykSpy3+hELSwquhu+TgHn8nkLiBwHvNX8Hofcw==", + "dev": true, + "requires": { + "lodash": "^4.17.13" + }, + "dependencies": { + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", + "dev": true + } + } + }, + "@babel/helper-remap-async-to-generator": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.1.0.tgz", + "integrity": "sha512-3fOK0L+Fdlg8S5al8u/hWE6vhufGSn0bN09xm2LXMy//REAF8kDCrYoOBKYmA8m5Nom+sV9LyLCwrFynA8/slg==", + "dev": true, + "requires": { + "@babel/helper-annotate-as-pure": "^7.0.0", + "@babel/helper-wrap-function": "^7.1.0", + "@babel/template": "^7.1.0", + "@babel/traverse": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "@babel/helper-replace-supers": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.5.5.tgz", + "integrity": "sha512-XvRFWrNnlsow2u7jXDuH4jDDctkxbS7gXssrP4q2nUD606ukXHRvydj346wmNg+zAgpFx4MWf4+usfC93bElJg==", + "dev": true, + "requires": { + "@babel/helper-member-expression-to-functions": "^7.5.5", + "@babel/helper-optimise-call-expression": "^7.0.0", + "@babel/traverse": "^7.5.5", + "@babel/types": "^7.5.5" + } + }, + "@babel/helper-simple-access": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.1.0.tgz", + "integrity": "sha512-Vk+78hNjRbsiu49zAPALxTb+JUQCz1aolpd8osOF16BGnLtseD21nbHgLPGUwrXEurZgiCOUmvs3ExTu4F5x6w==", + "dev": true, + "requires": { + "@babel/template": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "@babel/helper-split-export-declaration": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.4.4.tgz", + "integrity": "sha512-Ro/XkzLf3JFITkW6b+hNxzZ1n5OQ80NvIUdmHspih1XAhtN3vPTuUFT4eQnela+2MaZ5ulH+iyP513KJrxbN7Q==", + "dev": true, + "requires": { + "@babel/types": "^7.4.4" + } + }, + "@babel/helper-wrap-function": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.2.0.tgz", + "integrity": "sha512-o9fP1BZLLSrYlxYEYyl2aS+Flun5gtjTIG8iln+XuEzQTs0PLagAGSXUcqruJwD5fM48jzIEggCKpIfWTcR7pQ==", + "dev": true, + "requires": { + "@babel/helper-function-name": "^7.1.0", + "@babel/template": "^7.1.0", + "@babel/traverse": "^7.1.0", + "@babel/types": "^7.2.0" + } + }, + "@babel/helpers": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.6.0.tgz", + "integrity": "sha512-W9kao7OBleOjfXtFGgArGRX6eCP0UEcA2ZWEWNkJdRZnHhW4eEbeswbG3EwaRsnQUAEGWYgMq1HsIXuNNNy2eQ==", + "dev": true, + "requires": { + "@babel/template": "^7.6.0", + "@babel/traverse": "^7.6.0", + "@babel/types": "^7.6.0" + } + }, + "@babel/highlight": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz", + "integrity": "sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==", + "dev": true, + "requires": { + "chalk": "^2.0.0", + "esutils": "^2.0.2", + "js-tokens": "^4.0.0" + } + }, + "@babel/parser": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.6.0.tgz", + "integrity": "sha512-+o2q111WEx4srBs7L9eJmcwi655eD8sXniLqMB93TBK9GrNzGrxDWSjiqz2hLU0Ha8MTXFIP0yd9fNdP+m43ZQ==", + "dev": true + }, + "@babel/plugin-proposal-async-generator-functions": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.2.0.tgz", + "integrity": "sha512-+Dfo/SCQqrwx48ptLVGLdE39YtWRuKc/Y9I5Fy0P1DDBB9lsAHpjcEJQt+4IifuSOSTLBKJObJqMvaO1pIE8LQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/helper-remap-async-to-generator": "^7.1.0", + "@babel/plugin-syntax-async-generators": "^7.2.0" + } + }, + "@babel/plugin-proposal-dynamic-import": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-dynamic-import/-/plugin-proposal-dynamic-import-7.5.0.tgz", + "integrity": "sha512-x/iMjggsKTFHYC6g11PL7Qy58IK8H5zqfm9e6hu4z1iH2IRyAp9u9dL80zA6R76yFovETFLKz2VJIC2iIPBuFw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/plugin-syntax-dynamic-import": "^7.2.0" + } + }, + "@babel/plugin-proposal-json-strings": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-json-strings/-/plugin-proposal-json-strings-7.2.0.tgz", + "integrity": "sha512-MAFV1CA/YVmYwZG0fBQyXhmj0BHCB5egZHCKWIFVv/XCxAeVGIHfos3SwDck4LvCllENIAg7xMKOG5kH0dzyUg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/plugin-syntax-json-strings": "^7.2.0" + } + }, + "@babel/plugin-proposal-object-rest-spread": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.5.5.tgz", + "integrity": "sha512-F2DxJJSQ7f64FyTVl5cw/9MWn6naXGdk3Q3UhDbFEEHv+EilCPoeRD3Zh/Utx1CJz4uyKlQ4uH+bJPbEhMV7Zw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/plugin-syntax-object-rest-spread": "^7.2.0" + } + }, + "@babel/plugin-proposal-optional-catch-binding": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-catch-binding/-/plugin-proposal-optional-catch-binding-7.2.0.tgz", + "integrity": "sha512-mgYj3jCcxug6KUcX4OBoOJz3CMrwRfQELPQ5560F70YQUBZB7uac9fqaWamKR1iWUzGiK2t0ygzjTScZnVz75g==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/plugin-syntax-optional-catch-binding": "^7.2.0" + } + }, + "@babel/plugin-proposal-unicode-property-regex": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-unicode-property-regex/-/plugin-proposal-unicode-property-regex-7.4.4.tgz", + "integrity": "sha512-j1NwnOqMG9mFUOH58JTFsA/+ZYzQLUZ/drqWUqxCYLGeu2JFZL8YrNC9hBxKmWtAuOCHPcRpgv7fhap09Fb4kA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/helper-regex": "^7.4.4", + "regexpu-core": "^4.5.4" + } + }, + "@babel/plugin-syntax-async-generators": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.2.0.tgz", + "integrity": "sha512-1ZrIRBv2t0GSlcwVoQ6VgSLpLgiN/FVQUzt9znxo7v2Ov4jJrs8RY8tv0wvDmFN3qIdMKWrmMMW6yZ0G19MfGg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-syntax-dynamic-import": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.2.0.tgz", + "integrity": "sha512-mVxuJ0YroI/h/tbFTPGZR8cv6ai+STMKNBq0f8hFxsxWjl94qqhsb+wXbpNMDPU3cfR1TIsVFzU3nXyZMqyK4w==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-syntax-json-strings": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.2.0.tgz", + "integrity": "sha512-5UGYnMSLRE1dqqZwug+1LISpA403HzlSfsg6P9VXU6TBjcSHeNlw4DxDx7LgpF+iKZoOG/+uzqoRHTdcUpiZNg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-syntax-object-rest-spread": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.2.0.tgz", + "integrity": "sha512-t0JKGgqk2We+9may3t0xDdmneaXmyxq0xieYcKHxIsrJO64n1OiMWNUtc5gQK1PA0NpdCRrtZp4z+IUaKugrSA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-syntax-optional-catch-binding": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.2.0.tgz", + "integrity": "sha512-bDe4xKNhb0LI7IvZHiA13kff0KEfaGX/Hv4lMA9+7TEc63hMNvfKo6ZFpXhKuEp+II/q35Gc4NoMeDZyaUbj9w==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-arrow-functions": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.2.0.tgz", + "integrity": "sha512-ER77Cax1+8/8jCB9fo4Ud161OZzWN5qawi4GusDuRLcDbDG+bIGYY20zb2dfAFdTRGzrfq2xZPvF0R64EHnimg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-async-to-generator": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.5.0.tgz", + "integrity": "sha512-mqvkzwIGkq0bEF1zLRRiTdjfomZJDV33AH3oQzHVGkI2VzEmXLpKKOBvEVaFZBJdN0XTyH38s9j/Kiqr68dggg==", + "dev": true, + "requires": { + "@babel/helper-module-imports": "^7.0.0", + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/helper-remap-async-to-generator": "^7.1.0" + } + }, + "@babel/plugin-transform-block-scoped-functions": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.2.0.tgz", + "integrity": "sha512-ntQPR6q1/NKuphly49+QiQiTN0O63uOwjdD6dhIjSWBI5xlrbUFh720TIpzBhpnrLfv2tNH/BXvLIab1+BAI0w==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-block-scoping": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.6.0.tgz", + "integrity": "sha512-tIt4E23+kw6TgL/edACZwP1OUKrjOTyMrFMLoT5IOFrfMRabCgekjqFd5o6PaAMildBu46oFkekIdMuGkkPEpA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "lodash": "^4.17.13" + }, + "dependencies": { + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", + "dev": true + } + } + }, + "@babel/plugin-transform-classes": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.5.5.tgz", + "integrity": "sha512-U2htCNK/6e9K7jGyJ++1p5XRU+LJjrwtoiVn9SzRlDT2KubcZ11OOwy3s24TjHxPgxNwonCYP7U2K51uVYCMDg==", + "dev": true, + "requires": { + "@babel/helper-annotate-as-pure": "^7.0.0", + "@babel/helper-define-map": "^7.5.5", + "@babel/helper-function-name": "^7.1.0", + "@babel/helper-optimise-call-expression": "^7.0.0", + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/helper-replace-supers": "^7.5.5", + "@babel/helper-split-export-declaration": "^7.4.4", + "globals": "^11.1.0" + } + }, + "@babel/plugin-transform-computed-properties": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.2.0.tgz", + "integrity": "sha512-kP/drqTxY6Xt3NNpKiMomfgkNn4o7+vKxK2DDKcBG9sHj51vHqMBGy8wbDS/J4lMxnqs153/T3+DmCEAkC5cpA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-destructuring": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.6.0.tgz", + "integrity": "sha512-2bGIS5P1v4+sWTCnKNDZDxbGvEqi0ijeqM/YqHtVGrvG2y0ySgnEEhXErvE9dA0bnIzY9bIzdFK0jFA46ASIIQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-dotall-regex": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.4.4.tgz", + "integrity": "sha512-P05YEhRc2h53lZDjRPk/OektxCVevFzZs2Gfjd545Wde3k+yFDbXORgl2e0xpbq8mLcKJ7Idss4fAg0zORN/zg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/helper-regex": "^7.4.4", + "regexpu-core": "^4.5.4" + } + }, + "@babel/plugin-transform-duplicate-keys": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-7.5.0.tgz", + "integrity": "sha512-igcziksHizyQPlX9gfSjHkE2wmoCH3evvD2qR5w29/Dk0SMKE/eOI7f1HhBdNhR/zxJDqrgpoDTq5YSLH/XMsQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-exponentiation-operator": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.2.0.tgz", + "integrity": "sha512-umh4hR6N7mu4Elq9GG8TOu9M0bakvlsREEC+ialrQN6ABS4oDQ69qJv1VtR3uxlKMCQMCvzk7vr17RHKcjx68A==", + "dev": true, + "requires": { + "@babel/helper-builder-binary-assignment-operator-visitor": "^7.1.0", + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-for-of": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.4.4.tgz", + "integrity": "sha512-9T/5Dlr14Z9TIEXLXkt8T1DU7F24cbhwhMNUziN3hB1AXoZcdzPcTiKGRn/6iOymDqtTKWnr/BtRKN9JwbKtdQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-function-name": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.4.4.tgz", + "integrity": "sha512-iU9pv7U+2jC9ANQkKeNF6DrPy4GBa4NWQtl6dHB4Pb3izX2JOEvDTFarlNsBj/63ZEzNNIAMs3Qw4fNCcSOXJA==", + "dev": true, + "requires": { + "@babel/helper-function-name": "^7.1.0", + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-literals": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.2.0.tgz", + "integrity": "sha512-2ThDhm4lI4oV7fVQ6pNNK+sx+c/GM5/SaML0w/r4ZB7sAneD/piDJtwdKlNckXeyGK7wlwg2E2w33C/Hh+VFCg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-member-expression-literals": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.2.0.tgz", + "integrity": "sha512-HiU3zKkSU6scTidmnFJ0bMX8hz5ixC93b4MHMiYebmk2lUVNGOboPsqQvx5LzooihijUoLR/v7Nc1rbBtnc7FA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-modules-amd": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-7.5.0.tgz", + "integrity": "sha512-n20UsQMKnWrltocZZm24cRURxQnWIvsABPJlw/fvoy9c6AgHZzoelAIzajDHAQrDpuKFFPPcFGd7ChsYuIUMpg==", + "dev": true, + "requires": { + "@babel/helper-module-transforms": "^7.1.0", + "@babel/helper-plugin-utils": "^7.0.0", + "babel-plugin-dynamic-import-node": "^2.3.0" + } + }, + "@babel/plugin-transform-modules-commonjs": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.6.0.tgz", + "integrity": "sha512-Ma93Ix95PNSEngqomy5LSBMAQvYKVe3dy+JlVJSHEXZR5ASL9lQBedMiCyVtmTLraIDVRE3ZjTZvmXXD2Ozw3g==", + "dev": true, + "requires": { + "@babel/helper-module-transforms": "^7.4.4", + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/helper-simple-access": "^7.1.0", + "babel-plugin-dynamic-import-node": "^2.3.0" + } + }, + "@babel/plugin-transform-modules-systemjs": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.5.0.tgz", + "integrity": "sha512-Q2m56tyoQWmuNGxEtUyeEkm6qJYFqs4c+XyXH5RAuYxObRNz9Zgj/1g2GMnjYp2EUyEy7YTrxliGCXzecl/vJg==", + "dev": true, + "requires": { + "@babel/helper-hoist-variables": "^7.4.4", + "@babel/helper-plugin-utils": "^7.0.0", + "babel-plugin-dynamic-import-node": "^2.3.0" + } + }, + "@babel/plugin-transform-modules-umd": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-7.2.0.tgz", + "integrity": "sha512-BV3bw6MyUH1iIsGhXlOK6sXhmSarZjtJ/vMiD9dNmpY8QXFFQTj+6v92pcfy1iqa8DeAfJFwoxcrS/TUZda6sw==", + "dev": true, + "requires": { + "@babel/helper-module-transforms": "^7.1.0", + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-named-capturing-groups-regex": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.6.0.tgz", + "integrity": "sha512-jem7uytlmrRl3iCAuQyw8BpB4c4LWvSpvIeXKpMb+7j84lkx4m4mYr5ErAcmN5KM7B6BqrAvRGjBIbbzqCczew==", + "dev": true, + "requires": { + "regexp-tree": "^0.1.13" + } + }, + "@babel/plugin-transform-new-target": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-new-target/-/plugin-transform-new-target-7.4.4.tgz", + "integrity": "sha512-r1z3T2DNGQwwe2vPGZMBNjioT2scgWzK9BCnDEh+46z8EEwXBq24uRzd65I7pjtugzPSj921aM15RpESgzsSuA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-object-super": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.5.5.tgz", + "integrity": "sha512-un1zJQAhSosGFBduPgN/YFNvWVpRuHKU7IHBglLoLZsGmruJPOo6pbInneflUdmq7YvSVqhpPs5zdBvLnteltQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/helper-replace-supers": "^7.5.5" + } + }, + "@babel/plugin-transform-parameters": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.4.4.tgz", + "integrity": "sha512-oMh5DUO1V63nZcu/ZVLQFqiihBGo4OpxJxR1otF50GMeCLiRx5nUdtokd+u9SuVJrvvuIh9OosRFPP4pIPnwmw==", + "dev": true, + "requires": { + "@babel/helper-call-delegate": "^7.4.4", + "@babel/helper-get-function-arity": "^7.0.0", + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-property-literals": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.2.0.tgz", + "integrity": "sha512-9q7Dbk4RhgcLp8ebduOpCbtjh7C0itoLYHXd9ueASKAG/is5PQtMR5VJGka9NKqGhYEGn5ITahd4h9QeBMylWQ==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-regenerator": { + "version": "7.4.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.4.5.tgz", + "integrity": "sha512-gBKRh5qAaCWntnd09S8QC7r3auLCqq5DI6O0DlfoyDjslSBVqBibrMdsqO+Uhmx3+BlOmE/Kw1HFxmGbv0N9dA==", + "dev": true, + "requires": { + "regenerator-transform": "^0.14.0" + } + }, + "@babel/plugin-transform-reserved-words": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-7.2.0.tgz", + "integrity": "sha512-fz43fqW8E1tAB3DKF19/vxbpib1fuyCwSPE418ge5ZxILnBhWyhtPgz8eh1RCGGJlwvksHkyxMxh0eenFi+kFw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-shorthand-properties": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.2.0.tgz", + "integrity": "sha512-QP4eUM83ha9zmYtpbnyjTLAGKQritA5XW/iG9cjtuOI8s1RuL/3V6a3DeSHfKutJQ+ayUfeZJPcnCYEQzaPQqg==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-spread": { + "version": "7.2.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.2.2.tgz", + "integrity": "sha512-KWfky/58vubwtS0hLqEnrWJjsMGaOeSBn90Ezn5Jeg9Z8KKHmELbP1yGylMlm5N6TPKeY9A2+UaSYLdxahg01w==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-sticky-regex": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.2.0.tgz", + "integrity": "sha512-KKYCoGaRAf+ckH8gEL3JHUaFVyNHKe3ASNsZ+AlktgHevvxGigoIttrEJb8iKN03Q7Eazlv1s6cx2B2cQ3Jabw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/helper-regex": "^7.0.0" + } + }, + "@babel/plugin-transform-template-literals": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.4.4.tgz", + "integrity": "sha512-mQrEC4TWkhLN0z8ygIvEL9ZEToPhG5K7KDW3pzGqOfIGZ28Jb0POUkeWcoz8HnHvhFy6dwAT1j8OzqN8s804+g==", + "dev": true, + "requires": { + "@babel/helper-annotate-as-pure": "^7.0.0", + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-typeof-symbol": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.2.0.tgz", + "integrity": "sha512-2LNhETWYxiYysBtrBTqL8+La0jIoQQnIScUJc74OYvUGRmkskNY4EzLCnjHBzdmb38wqtTaixpo1NctEcvMDZw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/plugin-transform-unicode-regex": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.4.4.tgz", + "integrity": "sha512-il+/XdNw01i93+M9J9u4T7/e/Ue/vWfNZE4IRUQjplu2Mqb/AFTDimkw2tdEdSH50wuQXZAbXSql0UphQke+vA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/helper-regex": "^7.4.4", + "regexpu-core": "^4.5.4" + } + }, + "@babel/polyfill": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/polyfill/-/polyfill-7.4.4.tgz", + "integrity": "sha512-WlthFLfhQQhh+A2Gn5NSFl0Huxz36x86Jn+E9OW7ibK8edKPq+KLy4apM1yDpQ8kJOVi1OVjpP4vSDLdrI04dg==", + "dev": true, + "requires": { + "core-js": "^2.6.5", + "regenerator-runtime": "^0.13.2" + }, + "dependencies": { + "regenerator-runtime": { + "version": "0.13.2", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.2.tgz", + "integrity": "sha512-S/TQAZJO+D3m9xeN1WTI8dLKBBiRgXBlTJvbWjCThHWZj9EvHK70Ff50/tYj2J/fvBY6JtFVwRuazHN2E7M9BA==", + "dev": true + } + } + }, + "@babel/preset-env": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.6.0.tgz", + "integrity": "sha512-1efzxFv/TcPsNXlRhMzRnkBFMeIqBBgzwmZwlFDw5Ubj0AGLeufxugirwZmkkX/ayi3owsSqoQ4fw8LkfK9SYg==", + "dev": true, + "requires": { + "@babel/helper-module-imports": "^7.0.0", + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/plugin-proposal-async-generator-functions": "^7.2.0", + "@babel/plugin-proposal-dynamic-import": "^7.5.0", + "@babel/plugin-proposal-json-strings": "^7.2.0", + "@babel/plugin-proposal-object-rest-spread": "^7.5.5", + "@babel/plugin-proposal-optional-catch-binding": "^7.2.0", + "@babel/plugin-proposal-unicode-property-regex": "^7.4.4", + "@babel/plugin-syntax-async-generators": "^7.2.0", + "@babel/plugin-syntax-dynamic-import": "^7.2.0", + "@babel/plugin-syntax-json-strings": "^7.2.0", + "@babel/plugin-syntax-object-rest-spread": "^7.2.0", + "@babel/plugin-syntax-optional-catch-binding": "^7.2.0", + "@babel/plugin-transform-arrow-functions": "^7.2.0", + "@babel/plugin-transform-async-to-generator": "^7.5.0", + "@babel/plugin-transform-block-scoped-functions": "^7.2.0", + "@babel/plugin-transform-block-scoping": "^7.6.0", + "@babel/plugin-transform-classes": "^7.5.5", + "@babel/plugin-transform-computed-properties": "^7.2.0", + "@babel/plugin-transform-destructuring": "^7.6.0", + "@babel/plugin-transform-dotall-regex": "^7.4.4", + "@babel/plugin-transform-duplicate-keys": "^7.5.0", + "@babel/plugin-transform-exponentiation-operator": "^7.2.0", + "@babel/plugin-transform-for-of": "^7.4.4", + "@babel/plugin-transform-function-name": "^7.4.4", + "@babel/plugin-transform-literals": "^7.2.0", + "@babel/plugin-transform-member-expression-literals": "^7.2.0", + "@babel/plugin-transform-modules-amd": "^7.5.0", + "@babel/plugin-transform-modules-commonjs": "^7.6.0", + "@babel/plugin-transform-modules-systemjs": "^7.5.0", + "@babel/plugin-transform-modules-umd": "^7.2.0", + "@babel/plugin-transform-named-capturing-groups-regex": "^7.6.0", + "@babel/plugin-transform-new-target": "^7.4.4", + "@babel/plugin-transform-object-super": "^7.5.5", + "@babel/plugin-transform-parameters": "^7.4.4", + "@babel/plugin-transform-property-literals": "^7.2.0", + "@babel/plugin-transform-regenerator": "^7.4.5", + "@babel/plugin-transform-reserved-words": "^7.2.0", + "@babel/plugin-transform-shorthand-properties": "^7.2.0", + "@babel/plugin-transform-spread": "^7.2.0", + "@babel/plugin-transform-sticky-regex": "^7.2.0", + "@babel/plugin-transform-template-literals": "^7.4.4", + "@babel/plugin-transform-typeof-symbol": "^7.2.0", + "@babel/plugin-transform-unicode-regex": "^7.4.4", + "@babel/types": "^7.6.0", + "browserslist": "^4.6.0", + "core-js-compat": "^3.1.1", + "invariant": "^2.2.2", + "js-levenshtein": "^1.1.3", + "semver": "^5.5.0" + } + }, + "@babel/register": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/register/-/register-7.4.4.tgz", + "integrity": "sha512-sn51H88GRa00+ZoMqCVgOphmswG4b7mhf9VOB0LUBAieykq2GnRFerlN+JQkO/ntT7wz4jaHNSRPg9IdMPEUkA==", + "dev": true, + "requires": { + "core-js": "^3.0.0", + "find-cache-dir": "^2.0.0", + "lodash": "^4.17.11", + "mkdirp": "^0.5.1", + "pirates": "^4.0.0", + "source-map-support": "^0.5.9" + }, + "dependencies": { + "core-js": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.1.4.tgz", + "integrity": "sha512-YNZN8lt82XIMLnLirj9MhKDFZHalwzzrL9YLt6eb0T5D0EDl4IQ90IGkua8mHbnxNrkj1d8hbdizMc0Qmg1WnQ==", + "dev": true + } + } + }, + "@babel/template": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.6.0.tgz", + "integrity": "sha512-5AEH2EXD8euCk446b7edmgFdub/qfH1SN6Nii3+fyXP807QRx9Q73A2N5hNwRRslC2H9sNzaFhsPubkS4L8oNQ==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "@babel/parser": "^7.6.0", + "@babel/types": "^7.6.0" + } + }, + "@babel/traverse": { + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.6.0.tgz", + "integrity": "sha512-93t52SaOBgml/xY74lsmt7xOR4ufYvhb5c5qiM6lu4J/dWGMAfAh6eKw4PjLes6DI6nQgearoxnFJk60YchpvQ==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.5.5", + "@babel/generator": "^7.6.0", + "@babel/helper-function-name": "^7.1.0", + "@babel/helper-split-export-declaration": "^7.4.4", + "@babel/parser": "^7.6.0", + "@babel/types": "^7.6.0", + "debug": "^4.1.0", + "globals": "^11.1.0", + "lodash": "^4.17.13" + }, + "dependencies": { + "@babel/code-frame": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.5.5.tgz", + "integrity": "sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw==", + "dev": true, + "requires": { + "@babel/highlight": "^7.0.0" + } + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", + "dev": true + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "@babel/types": { + "version": "7.6.1", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.6.1.tgz", + "integrity": "sha512-X7gdiuaCmA0uRjCmRtYJNAVCc/q+5xSgsfKJHqMN4iNLILX39677fJE1O40arPMh0TTtS9ItH67yre6c7k6t0g==", + "dev": true, + "requires": { + "esutils": "^2.0.2", + "lodash": "^4.17.13", + "to-fast-properties": "^2.0.0" + }, + "dependencies": { + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", + "dev": true + } + } + }, + "@cnakazawa/watch": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@cnakazawa/watch/-/watch-1.0.3.tgz", + "integrity": "sha512-r5160ogAvGyHsal38Kux7YYtodEKOj89RGb28ht1jh3SJb08VwRwAKKJL0bGb04Zd/3r9FL3BFIc3bBidYffCA==", + "dev": true, + "requires": { + "exec-sh": "^0.3.2", + "minimist": "^1.2.0" + } + }, + "@electron/get": { + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/@electron/get/-/get-1.7.1.tgz", + "integrity": "sha512-+BOIzkmYbe+oOBGqSByq8zXYXCFztccoymR3uNkvX5ckJ/5xU+4peVyEvFyH6+zfv58hCo99RxgIpwuaMfRtRg==", + "requires": { + "debug": "^4.1.1", + "env-paths": "^2.2.0", + "fs-extra": "^8.1.0", + "global-agent": "^2.0.2", + "global-tunnel-ng": "^2.7.1", + "got": "^9.6.0", + "sanitize-filename": "^1.6.2", + "sumchecker": "^3.0.0" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "requires": { + "ms": "^2.1.1" + } + }, + "fs-extra": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", + "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", + "requires": { + "graceful-fs": "^4.2.0", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + } + }, + "got": { + "version": "9.6.0", + "resolved": "https://registry.npmjs.org/got/-/got-9.6.0.tgz", + "integrity": "sha512-R7eWptXuGYxwijs0eV+v3o6+XH1IqVK8dJOEecQfTmkncw9AV4dcw/Dhxi8MdlqPthxxpZyizMzyg8RTmEsG+Q==", + "requires": { + "@sindresorhus/is": "^0.14.0", + "@szmarczak/http-timer": "^1.1.2", + "cacheable-request": "^6.0.0", + "decompress-response": "^3.3.0", + "duplexer3": "^0.1.4", + "get-stream": "^4.1.0", + "lowercase-keys": "^1.0.1", + "mimic-response": "^1.0.1", + "p-cancelable": "^1.0.0", + "to-readable-stream": "^1.0.0", + "url-parse-lax": "^3.0.0" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "prepend-http": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-2.0.0.tgz", + "integrity": "sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc=" + }, + "url-parse-lax": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-3.0.0.tgz", + "integrity": "sha1-FrXK/Afb42dsGxmZF3gj1lA6yww=", + "requires": { + "prepend-http": "^2.0.0" + } + } + } + }, + "@google-cloud/common": { + "version": "0.32.1", + "resolved": "https://registry.npmjs.org/@google-cloud/common/-/common-0.32.1.tgz", + "integrity": "sha512-bLdPzFvvBMtVkwsoBtygE9oUm3yrNmPa71gvOgucYI/GqvNP2tb6RYsDHPq98kvignhcgHGDI5wyNgxaCo8bKQ==", + "requires": { + "@google-cloud/projectify": "^0.3.3", + "@google-cloud/promisify": "^0.4.0", + "@types/request": "^2.48.1", + "arrify": "^2.0.0", + "duplexify": "^3.6.0", + "ent": "^2.2.0", + "extend": "^3.0.2", + "google-auth-library": "^3.1.1", + "pify": "^4.0.1", + "retry-request": "^4.0.0", + "teeny-request": "^3.11.3" + }, + "dependencies": { + "arrify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-2.0.1.tgz", + "integrity": "sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==" + } + } + }, + "@google-cloud/paginator": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@google-cloud/paginator/-/paginator-0.2.0.tgz", + "integrity": "sha512-2ZSARojHDhkLvQ+CS32K+iUhBsWg3AEw+uxtqblA7xoCABDyhpj99FPp35xy6A+XlzMhOSrHHaxFE+t6ZTQq0w==", + "requires": { + "arrify": "^1.0.1", + "extend": "^3.0.1", + "split-array-stream": "^2.0.0", + "stream-events": "^1.0.4" + } + }, + "@google-cloud/projectify": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@google-cloud/projectify/-/projectify-0.3.3.tgz", + "integrity": "sha512-7522YHQ4IhaafgSunsFF15nG0TGVmxgXidy9cITMe+256RgqfcrfWphiMufW+Ou4kqagW/u3yxwbzVEW3dk2Uw==" + }, + "@google-cloud/promisify": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@google-cloud/promisify/-/promisify-0.4.0.tgz", + "integrity": "sha512-4yAHDC52TEMCNcMzVC8WlqnKKKq+Ssi2lXoUg9zWWkZ6U6tq9ZBRYLHHCRdfU+EU9YJsVmivwGcKYCjRGjnf4Q==" + }, + "@google-cloud/storage": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@google-cloud/storage/-/storage-2.5.0.tgz", + "integrity": "sha512-q1mwB6RUebIahbA3eriRs8DbG2Ij81Ynb9k8hMqTPkmbd8/S6Z0d6hVvfPmnyvX9Ej13IcmEYIbymuq/RBLghA==", + "requires": { + "@google-cloud/common": "^0.32.0", + "@google-cloud/paginator": "^0.2.0", + "@google-cloud/promisify": "^0.4.0", + "arrify": "^1.0.0", + "async": "^2.0.1", + "compressible": "^2.0.12", + "concat-stream": "^2.0.0", + "date-and-time": "^0.6.3", + "duplexify": "^3.5.0", + "extend": "^3.0.0", + "gcs-resumable-upload": "^1.0.0", + "hash-stream-validation": "^0.2.1", + "mime": "^2.2.0", + "mime-types": "^2.0.8", + "onetime": "^5.1.0", + "pumpify": "^1.5.1", + "snakeize": "^0.1.0", + "stream-events": "^1.0.1", + "teeny-request": "^3.11.3", + "through2": "^3.0.0", + "xdg-basedir": "^3.0.0" + }, + "dependencies": { + "async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", + "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", + "requires": { + "lodash": "^4.17.11" + } + }, + "mime": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.4.tgz", + "integrity": "sha512-LRxmNwziLPT828z+4YkNzloCFC2YM4wrB99k+AV5ZbEyfGNWfG8SO1FUXLmLDBSo89NrJZ4DIWeLjy1CHGhMGA==" + } + } + }, + "@jest/console": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-24.9.0.tgz", + "integrity": "sha512-Zuj6b8TnKXi3q4ymac8EQfc3ea/uhLeCGThFqXeC8H9/raaH8ARPUTdId+XyGd03Z4In0/VjD2OYFcBF09fNLQ==", + "dev": true, + "requires": { + "@jest/source-map": "^24.9.0", + "chalk": "^2.0.1", + "slash": "^2.0.0" + } + }, + "@jest/core": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-24.9.0.tgz", + "integrity": "sha512-Fogg3s4wlAr1VX7q+rhV9RVnUv5tD7VuWfYy1+whMiWUrvl7U3QJSJyWcDio9Lq2prqYsZaeTv2Rz24pWGkJ2A==", + "dev": true, + "requires": { + "@jest/console": "^24.7.1", + "@jest/reporters": "^24.9.0", + "@jest/test-result": "^24.9.0", + "@jest/transform": "^24.9.0", + "@jest/types": "^24.9.0", + "ansi-escapes": "^3.0.0", + "chalk": "^2.0.1", + "exit": "^0.1.2", + "graceful-fs": "^4.1.15", + "jest-changed-files": "^24.9.0", + "jest-config": "^24.9.0", + "jest-haste-map": "^24.9.0", + "jest-message-util": "^24.9.0", + "jest-regex-util": "^24.3.0", + "jest-resolve": "^24.9.0", + "jest-resolve-dependencies": "^24.9.0", + "jest-runner": "^24.9.0", + "jest-runtime": "^24.9.0", + "jest-snapshot": "^24.9.0", + "jest-util": "^24.9.0", + "jest-validate": "^24.9.0", + "jest-watcher": "^24.9.0", + "micromatch": "^3.1.10", + "p-each-series": "^1.0.0", + "realpath-native": "^1.1.0", + "rimraf": "^2.5.4", + "slash": "^2.0.0", + "strip-ansi": "^5.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true + }, + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "dev": true, + "requires": { + "glob": "^7.1.3" } - } }, "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "dev": true, - "requires": { - "ansi-regex": "2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz", - "integrity": "sha1-xQYbbg74qBd15Q9dZhUb9r83EQc=", - "dev": true + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" } - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", - "dev": true } - } - }, - "esutils": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", - "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", - "dev": true - }, - "js-tokens": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-2.0.0.tgz", - "integrity": "sha1-eZA/VWPud4zBFi5tzxoAJ8l/nLU=", - "dev": true } - } }, - "css-selector-tokenizer": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/css-selector-tokenizer/-/css-selector-tokenizer-0.6.0.tgz", - "integrity": "sha1-ZEX1gseTDSQdzFAHpD1vy48HMVI=", - "dev": true, - "requires": { - "cssesc": "0.1.0", - "fastparse": "1.1.1", - "regexpu-core": "1.0.0" - }, - "dependencies": { - "cssesc": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-0.1.0.tgz", - "integrity": "sha1-yBSQPkViM3GgR3tAEJqq++6t27Q=", - "dev": true + "@jest/environment": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-24.9.0.tgz", + "integrity": "sha512-5A1QluTPhvdIPFYnO3sZC3smkNeXPVELz7ikPbhUj0bQjB07EoE9qtLrem14ZUYWdVayYbsjVwIiL4WBIMV4aQ==", + "dev": true, + "requires": { + "@jest/fake-timers": "^24.9.0", + "@jest/transform": "^24.9.0", + "@jest/types": "^24.9.0", + "jest-mock": "^24.9.0" + } + }, + "@jest/fake-timers": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-24.9.0.tgz", + "integrity": "sha512-eWQcNa2YSwzXWIMC5KufBh3oWRIijrQFROsIqt6v/NS9Io/gknw1jsAC9c+ih/RQX4A3O7SeWAhQeN0goKhT9A==", + "dev": true, + "requires": { + "@jest/types": "^24.9.0", + "jest-message-util": "^24.9.0", + "jest-mock": "^24.9.0" + } + }, + "@jest/reporters": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-24.9.0.tgz", + "integrity": "sha512-mu4X0yjaHrffOsWmVLzitKmmmWSQ3GGuefgNscUSWNiUNcEOSEQk9k3pERKEQVBb0Cnn88+UESIsZEMH3o88Gw==", + "dev": true, + "requires": { + "@jest/environment": "^24.9.0", + "@jest/test-result": "^24.9.0", + "@jest/transform": "^24.9.0", + "@jest/types": "^24.9.0", + "chalk": "^2.0.1", + "exit": "^0.1.2", + "glob": "^7.1.2", + "istanbul-lib-coverage": "^2.0.2", + "istanbul-lib-instrument": "^3.0.1", + "istanbul-lib-report": "^2.0.4", + "istanbul-lib-source-maps": "^3.0.1", + "istanbul-reports": "^2.2.6", + "jest-haste-map": "^24.9.0", + "jest-resolve": "^24.9.0", + "jest-runtime": "^24.9.0", + "jest-util": "^24.9.0", + "jest-worker": "^24.6.0", + "node-notifier": "^5.4.2", + "slash": "^2.0.0", + "source-map": "^0.6.0", + "string-length": "^2.0.0" }, - "fastparse": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/fastparse/-/fastparse-1.1.1.tgz", - "integrity": "sha1-0eJkOzipTXWDtHkGDmxK/8lAcfg=", - "dev": true - }, - "regexpu-core": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-1.0.0.tgz", - "integrity": "sha1-hqdj9Y7k18L2sQLkdkBQ3n7ZDGs=", - "dev": true, - "requires": { - "regenerate": "1.3.1", - "regjsgen": "0.2.0", - "regjsparser": "0.1.5" - }, - "dependencies": { - "regenerate": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.3.1.tgz", - "integrity": "sha1-AwAgOl0v3PiRFtzoQnXQEfWQPzM=", - "dev": true - }, - "regjsgen": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/regjsgen/-/regjsgen-0.2.0.tgz", - "integrity": "sha1-bAFq3qxVT3WCP+N6wFuS1aTtsfc=", - "dev": true - }, - "regjsparser": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.1.5.tgz", - "integrity": "sha1-fuj4Tcb6eS0/0K4ijSS9lJ6tIFw=", - "dev": true, - "requires": { - "jsesc": "0.5.0" - }, - "dependencies": { - "jsesc": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", - "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", - "dev": true + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" } - } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true } - } } - } }, - "cssnano": { - "version": "3.7.7", - "resolved": "https://registry.npmjs.org/cssnano/-/cssnano-3.7.7.tgz", - "integrity": "sha1-J/rGETgMaknW9yLAU35amIp4UBA=", - "dev": true, - "requires": { - "autoprefixer": "6.5.1", - "decamelize": "1.2.0", - "defined": "1.0.0", - "has": "1.0.1", - "object-assign": "4.1.0", - "postcss": "5.2.4", - "postcss-calc": "5.3.1", - "postcss-colormin": "2.2.1", - "postcss-convert-values": "2.4.1", - "postcss-discard-comments": "2.0.4", - "postcss-discard-duplicates": "2.0.1", - "postcss-discard-empty": "2.1.0", - "postcss-discard-overridden": "0.1.1", - "postcss-discard-unused": "2.2.1", - "postcss-filter-plugins": "2.0.2", - "postcss-merge-idents": "2.1.7", - "postcss-merge-longhand": "2.0.1", - "postcss-merge-rules": "2.0.10", - "postcss-minify-font-values": "1.0.5", - "postcss-minify-gradients": "1.0.3", - "postcss-minify-params": "1.0.5", - "postcss-minify-selectors": "2.0.5", - "postcss-normalize-charset": "1.1.0", - "postcss-normalize-url": "3.0.7", - "postcss-ordered-values": "2.2.2", - "postcss-reduce-idents": "2.3.0", - "postcss-reduce-initial": "1.0.0", - "postcss-reduce-transforms": "1.0.3", - "postcss-svgo": "2.1.5", - "postcss-unique-selectors": "2.0.2", - "postcss-value-parser": "3.3.0", - "postcss-zindex": "2.1.1" - }, - "dependencies": { - "autoprefixer": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-6.5.1.tgz", - "integrity": "sha1-rnWaUiHnCfPaF8LWViMOZ8Q8u3U=", - "dev": true, - "requires": { - "browserslist": "1.4.0", - "caniuse-db": "1.0.30000559", - "normalize-range": "0.1.2", - "num2fraction": "1.2.2", - "postcss": "5.2.4", - "postcss-value-parser": "3.3.0" - }, - "dependencies": { - "browserslist": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-1.4.0.tgz", - "integrity": "sha1-nP3PU4TZFY9bcNoqoAsw6P8BkEk=", - "dev": true, - "requires": { - "caniuse-db": "1.0.30000559" - } - }, - "caniuse-db": { - "version": "1.0.30000559", - "resolved": "https://registry.npmjs.org/caniuse-db/-/caniuse-db-1.0.30000559.tgz", - "integrity": "sha1-r71okW3SO/1UnCZSDHhjH7Xi45M=", - "dev": true - }, - "normalize-range": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", - "integrity": "sha1-LRDAa9/TEuqXd2laTShDlFa3WUI=", - "dev": true - }, - "num2fraction": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/num2fraction/-/num2fraction-1.2.2.tgz", - "integrity": "sha1-b2gragJ6Tp3fpFZM0lidHU5mnt4=", - "dev": true + "@jest/source-map": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-24.9.0.tgz", + "integrity": "sha512-/Xw7xGlsZb4MJzNDgB7PW5crou5JqWiBQaz6xyPd3ArOg2nfn/PunV8+olXbbEZzNl591o5rWKE9BRDaFAuIBg==", + "dev": true, + "requires": { + "callsites": "^3.0.0", + "graceful-fs": "^4.1.15", + "source-map": "^0.6.0" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true } - } + } + }, + "@jest/test-result": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-24.9.0.tgz", + "integrity": "sha512-XEFrHbBonBJ8dGp2JmF8kP/nQI/ImPpygKHwQ/SY+es59Z3L5PI4Qb9TQQMAEeYsThG1xF0k6tmG0tIKATNiiA==", + "dev": true, + "requires": { + "@jest/console": "^24.9.0", + "@jest/types": "^24.9.0", + "@types/istanbul-lib-coverage": "^2.0.0" + } + }, + "@jest/test-sequencer": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-24.9.0.tgz", + "integrity": "sha512-6qqsU4o0kW1dvA95qfNog8v8gkRN9ph6Lz7r96IvZpHdNipP2cBcb07J1Z45mz/VIS01OHJ3pY8T5fUY38tg4A==", + "dev": true, + "requires": { + "@jest/test-result": "^24.9.0", + "jest-haste-map": "^24.9.0", + "jest-runner": "^24.9.0", + "jest-runtime": "^24.9.0" + } + }, + "@jest/transform": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-24.9.0.tgz", + "integrity": "sha512-TcQUmyNRxV94S0QpMOnZl0++6RMiqpbH/ZMccFB/amku6Uwvyb1cjYX7xkp5nGNkbX4QPH/FcB6q1HBTHynLmQ==", + "dev": true, + "requires": { + "@babel/core": "^7.1.0", + "@jest/types": "^24.9.0", + "babel-plugin-istanbul": "^5.1.0", + "chalk": "^2.0.1", + "convert-source-map": "^1.4.0", + "fast-json-stable-stringify": "^2.0.0", + "graceful-fs": "^4.1.15", + "jest-haste-map": "^24.9.0", + "jest-regex-util": "^24.9.0", + "jest-util": "^24.9.0", + "micromatch": "^3.1.10", + "pirates": "^4.0.1", + "realpath-native": "^1.1.0", + "slash": "^2.0.0", + "source-map": "^0.6.1", + "write-file-atomic": "2.4.1" }, - "decamelize": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", - "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", - "dev": true - }, - "defined": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/defined/-/defined-1.0.0.tgz", - "integrity": "sha1-yY2bzvdWdBiOEQlpFRGZ45sfppM=", - "dev": true - }, - "has": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.1.tgz", - "integrity": "sha1-hGFzP1OLCDfJNh45qauelwTcLyg=", - "dev": true, - "requires": { - "function-bind": "1.1.0" - }, - "dependencies": { - "function-bind": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.0.tgz", - "integrity": "sha1-FhdnFMgBeY5Ojyz391KUZ7tKV3E=", - "dev": true - } - } - }, - "postcss-calc": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/postcss-calc/-/postcss-calc-5.3.1.tgz", - "integrity": "sha1-d7rnypKK2FcW4v2kLyYb98HWW14=", - "dev": true, - "requires": { - "postcss": "5.2.4", - "postcss-message-helpers": "2.0.0", - "reduce-css-calc": "1.3.0" - }, - "dependencies": { - "postcss-message-helpers": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/postcss-message-helpers/-/postcss-message-helpers-2.0.0.tgz", - "integrity": "sha1-pPL0+rbk/gAvCu0ABHjN9S+bpg4=", - "dev": true + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true }, - "reduce-css-calc": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/reduce-css-calc/-/reduce-css-calc-1.3.0.tgz", - "integrity": "sha1-dHyRTgSWFKTJz7umKYca0dKSdxY=", - "dev": true, - "requires": { - "balanced-match": "0.4.2", - "math-expression-evaluator": "1.2.14", - "reduce-function-call": "1.0.1" - }, - "dependencies": { - "balanced-match": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-0.4.2.tgz", - "integrity": "sha1-yz8+PHMtwPAe5wtAPzAuYddwmDg=", - "dev": true - }, - "math-expression-evaluator": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/math-expression-evaluator/-/math-expression-evaluator-1.2.14.tgz", - "integrity": "sha1-OVEXce2WAkBfupr//xfrTSo4Q6s=", - "dev": true, - "requires": { - "lodash.indexof": "4.0.5" - }, - "dependencies": { - "lodash.indexof": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/lodash.indexof/-/lodash.indexof-4.0.5.tgz", - "integrity": "sha1-U3FK3Czd1u2HY4+JOqm2wk4x7zw=", - "dev": true - } - } - }, - "reduce-function-call": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/reduce-function-call/-/reduce-function-call-1.0.1.tgz", - "integrity": "sha1-+gLhJuaVgkJjyrkdOlsP3B3Sepo=", - "dev": true, - "requires": { - "balanced-match": "0.1.0" - }, - "dependencies": { - "balanced-match": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-0.1.0.tgz", - "integrity": "sha1-tQS9BYabOSWd0MXvw12EMXbczEo=", - "dev": true - } - } + "write-file-atomic": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.1.tgz", + "integrity": "sha512-TGHFeZEZMnv+gBFRfjAcxL5bPHrsGKtnb4qsFAws7/vlh+QfwAaySIw4AXP9ZskTTh5GWu3FLuJhsWVdiJPGvg==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.11", + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.2" } - } } - } - }, - "postcss-colormin": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/postcss-colormin/-/postcss-colormin-2.2.1.tgz", - "integrity": "sha1-3FQhtq5vd572v9RzUrlKvlnQMWs=", - "dev": true, - "requires": { - "colormin": "1.1.2", - "postcss": "5.2.4", - "postcss-value-parser": "3.3.0" - }, - "dependencies": { - "colormin": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/colormin/-/colormin-1.1.2.tgz", - "integrity": "sha1-6i90IKcrlogaOKrlnsEkpvcpgTM=", - "dev": true, - "requires": { - "color": "0.11.3", - "css-color-names": "0.0.4", - "has": "1.0.1" - }, - "dependencies": { - "color": { - "version": "0.11.3", - "resolved": "https://registry.npmjs.org/color/-/color-0.11.3.tgz", - "integrity": "sha1-S60dDVJJndANvW8IaEQkZ+STlOY=", - "dev": true, - "requires": { - "clone": "1.0.2", - "color-convert": "1.5.0", - "color-string": "0.3.0" - }, - "dependencies": { - "clone": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.2.tgz", - "integrity": "sha1-Jgt6meux7f4kdTgXX3gyQ8sZ0Uk=", - "dev": true - }, - "color-convert": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.5.0.tgz", - "integrity": "sha1-eitO+0SI34W8pkQ8sDi3EA++feE=", - "dev": true - }, - "color-string": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/color-string/-/color-string-0.3.0.tgz", - "integrity": "sha1-J9RvtnAlxcL6JZk7+/V55HhBuZE=", - "dev": true, - "requires": { - "color-name": "1.1.1" - }, - "dependencies": { - "color-name": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.1.tgz", - "integrity": "sha1-SxQVMEz1ACjqgWQ2Q72C6gWANok=", - "dev": true - } - } - } - } - }, - "css-color-names": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/css-color-names/-/css-color-names-0.0.4.tgz", - "integrity": "sha1-gIrcLnnPhHOAabZGyyDsJ762KeA=", - "dev": true - } - } - } - } - }, - "postcss-convert-values": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/postcss-convert-values/-/postcss-convert-values-2.4.1.tgz", - "integrity": "sha1-Rdzk1OM7fZZ7l6TZN/Jw6pjS/no=", - "dev": true, - "requires": { - "postcss": "5.2.4", - "postcss-value-parser": "3.3.0" - } - }, - "postcss-discard-comments": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/postcss-discard-comments/-/postcss-discard-comments-2.0.4.tgz", - "integrity": "sha1-vv6J+v1bPazlzM5Rt2uBUUvgDj0=", - "dev": true, - "requires": { - "postcss": "5.2.4" - } - }, - "postcss-discard-duplicates": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/postcss-discard-duplicates/-/postcss-discard-duplicates-2.0.1.tgz", - "integrity": "sha1-X64/GnHfPhnP+zcwnRp9ulbEWJw=", - "dev": true, - "requires": { - "postcss": "5.2.4" - } - }, - "postcss-discard-empty": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/postcss-discard-empty/-/postcss-discard-empty-2.1.0.tgz", - "integrity": "sha1-0rS9nVztXr2Nyt52QMfXzX9PkrU=", - "dev": true, - "requires": { - "postcss": "5.2.4" - } - }, - "postcss-discard-overridden": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/postcss-discard-overridden/-/postcss-discard-overridden-0.1.1.tgz", - "integrity": "sha1-ix6vVU9ob7KIzYdMVWZ7CqNmjVg=", - "dev": true, - "requires": { - "postcss": "5.2.4" - } - }, - "postcss-discard-unused": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/postcss-discard-unused/-/postcss-discard-unused-2.2.1.tgz", - "integrity": "sha1-XQIfAhpu1s7HMQ1GA3lKdd3VMjI=", - "dev": true, - "requires": { - "flatten": "1.0.2", - "postcss": "5.2.4", - "uniqs": "2.0.0" - }, - "dependencies": { - "flatten": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/flatten/-/flatten-1.0.2.tgz", - "integrity": "sha1-2uRqnXj74lKSJYzB54CkHZXAN4I=", - "dev": true - }, - "uniqs": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/uniqs/-/uniqs-2.0.0.tgz", - "integrity": "sha1-/+3ks2slKQaW5uFl1KWe25mOawI=", - "dev": true - } - } - }, - "postcss-filter-plugins": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/postcss-filter-plugins/-/postcss-filter-plugins-2.0.2.tgz", - "integrity": "sha1-bYWGJTTXNaxCDkqFgG4fXUKG2Ew=", - "dev": true, - "requires": { - "postcss": "5.2.4", - "uniqid": "4.1.0" - }, - "dependencies": { - "uniqid": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/uniqid/-/uniqid-4.1.0.tgz", - "integrity": "sha1-M9lnn2UCL0iYigP9JOfcr48Qnso=", - "dev": true, - "requires": { - "macaddress": "0.2.8" - }, - "dependencies": { - "macaddress": { - "version": "0.2.8", - "resolved": "https://registry.npmjs.org/macaddress/-/macaddress-0.2.8.tgz", - "integrity": "sha1-WQTcU3w57G2+/q6QIycTX6hRHxI=", - "dev": true - } - } - } - } - }, - "postcss-merge-idents": { - "version": "2.1.7", - "resolved": "https://registry.npmjs.org/postcss-merge-idents/-/postcss-merge-idents-2.1.7.tgz", - "integrity": "sha1-TFUwMTwI4dWzu/PSu8dH4njuonA=", - "dev": true, - "requires": { - "has": "1.0.1", - "postcss": "5.2.4", - "postcss-value-parser": "3.3.0" - } - }, - "postcss-merge-longhand": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/postcss-merge-longhand/-/postcss-merge-longhand-2.0.1.tgz", - "integrity": "sha1-/1m13sbVhs4s6hgxOPVcWHb6nNw=", - "dev": true, - "requires": { - "postcss": "5.2.4" - } - }, - "postcss-merge-rules": { - "version": "2.0.10", - "resolved": "https://registry.npmjs.org/postcss-merge-rules/-/postcss-merge-rules-2.0.10.tgz", - "integrity": "sha1-VLNgvoBOfmmlxyImNSR7kqNWnps=", - "dev": true, - "requires": { - "postcss": "5.2.4", - "vendors": "1.0.1" - }, - "dependencies": { - "vendors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/vendors/-/vendors-1.0.1.tgz", - "integrity": "sha1-N61zyO5Bf7PVgOeFMSMH0nSEfyI=", - "dev": true - } - } - }, - "postcss-minify-font-values": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/postcss-minify-font-values/-/postcss-minify-font-values-1.0.5.tgz", - "integrity": "sha1-S1jttWZB66fIR0qzUmyv17vey2k=", - "dev": true, - "requires": { - "object-assign": "4.1.0", - "postcss": "5.2.4", - "postcss-value-parser": "3.3.0" - } - }, - "postcss-minify-gradients": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/postcss-minify-gradients/-/postcss-minify-gradients-1.0.3.tgz", - "integrity": "sha1-CdIoFIyUL6gSZnnen/dzi1SRn+M=", - "dev": true, - "requires": { - "postcss": "5.2.4", - "postcss-value-parser": "3.3.0" - } - }, - "postcss-minify-params": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/postcss-minify-params/-/postcss-minify-params-1.0.5.tgz", - "integrity": "sha1-gtYCZDuGFqYfs2NNft4CiYNtZ/k=", - "dev": true, - "requires": { - "alphanum-sort": "1.0.2", - "postcss": "5.2.4", - "postcss-value-parser": "3.3.0", - "uniqs": "2.0.0" - }, - "dependencies": { - "alphanum-sort": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/alphanum-sort/-/alphanum-sort-1.0.2.tgz", - "integrity": "sha1-l6ERlkmyEa0zaR2fn0hqjsn74KM=", - "dev": true - }, - "uniqs": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/uniqs/-/uniqs-2.0.0.tgz", - "integrity": "sha1-/+3ks2slKQaW5uFl1KWe25mOawI=", - "dev": true - } - } - }, - "postcss-minify-selectors": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/postcss-minify-selectors/-/postcss-minify-selectors-2.0.5.tgz", - "integrity": "sha1-Th+Wb7SclSZoBAFrqaPGZFu2AeA=", - "dev": true, - "requires": { - "alphanum-sort": "1.0.2", - "postcss": "5.2.4", - "postcss-selector-parser": "2.2.1" - }, - "dependencies": { - "alphanum-sort": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/alphanum-sort/-/alphanum-sort-1.0.2.tgz", - "integrity": "sha1-l6ERlkmyEa0zaR2fn0hqjsn74KM=", - "dev": true - }, - "postcss-selector-parser": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-2.2.1.tgz", - "integrity": "sha1-/b9pYQOxKwpkBg5WEFB/QQSR98g=", - "dev": true, - "requires": { - "flatten": "1.0.2", - "indexes-of": "1.0.1", - "uniq": "1.0.1" - }, - "dependencies": { - "flatten": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/flatten/-/flatten-1.0.2.tgz", - "integrity": "sha1-2uRqnXj74lKSJYzB54CkHZXAN4I=", - "dev": true - }, - "indexes-of": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/indexes-of/-/indexes-of-1.0.1.tgz", - "integrity": "sha1-8w9xbI4r00bHtn0985FVZqfAVgc=", - "dev": true - }, - "uniq": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/uniq/-/uniq-1.0.1.tgz", - "integrity": "sha1-sxxa6CVIRKOoKBVBzisEuGWnNP8=", - "dev": true - } - } - } - } - }, - "postcss-normalize-charset": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/postcss-normalize-charset/-/postcss-normalize-charset-1.1.0.tgz", - "integrity": "sha1-L70w4SJIxEKYHTHqJITUb9BiiXA=", - "dev": true, - "requires": { - "postcss": "5.2.4" - } - }, - "postcss-normalize-url": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/postcss-normalize-url/-/postcss-normalize-url-3.0.7.tgz", - "integrity": "sha1-a9kNCkvFod8iwm6mXFMlfcOCn04=", - "dev": true, - "requires": { - "is-absolute-url": "2.0.0", - "normalize-url": "1.6.1", - "postcss": "5.2.4", - "postcss-value-parser": "3.3.0" - }, - "dependencies": { - "is-absolute-url": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-absolute-url/-/is-absolute-url-2.0.0.tgz", - "integrity": "sha1-nEsgsOXAy++aR5o2ft5vmRZ581k=", - "dev": true - }, - "normalize-url": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-1.6.1.tgz", - "integrity": "sha1-qfJU+gZbvCk0RhwMCUI4FZdhVaI=", - "dev": true, - "requires": { - "object-assign": "4.1.0", - "prepend-http": "1.0.4", - "query-string": "4.2.3", - "sort-keys": "1.1.2" - }, - "dependencies": { - "prepend-http": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", - "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=", - "dev": true - }, - "query-string": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/query-string/-/query-string-4.2.3.tgz", - "integrity": "sha1-nycnPSB6JajuTHuMdNzUXVVtuCI=", - "dev": true, - "requires": { - "object-assign": "4.1.0", - "strict-uri-encode": "1.1.0" - }, - "dependencies": { - "strict-uri-encode": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/strict-uri-encode/-/strict-uri-encode-1.1.0.tgz", - "integrity": "sha1-J5siXfHVgrH1TmWt3UNS4Y+qBxM=", - "dev": true - } - } - }, - "sort-keys": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/sort-keys/-/sort-keys-1.1.2.tgz", - "integrity": "sha1-RBttTTRnmPG05J6JIK37oOVD+a0=", - "dev": true, - "requires": { - "is-plain-obj": "1.1.0" - }, - "dependencies": { - "is-plain-obj": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-1.1.0.tgz", - "integrity": "sha1-caUMhCnfync8kqOQpKA7OfzVHT4=", - "dev": true - } - } - } - } - } - } - }, - "postcss-ordered-values": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/postcss-ordered-values/-/postcss-ordered-values-2.2.2.tgz", - "integrity": "sha1-votRF0H6strI5hSiMC6dECZ7B3E=", - "dev": true, - "requires": { - "postcss": "5.2.4", - "postcss-value-parser": "3.3.0" - } - }, - "postcss-reduce-idents": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/postcss-reduce-idents/-/postcss-reduce-idents-2.3.0.tgz", - "integrity": "sha1-ppe1KVPtaCX/6kBOJqTxBdi41Wk=", - "dev": true, - "requires": { - "postcss": "5.2.4", - "postcss-value-parser": "3.3.0" - } - }, - "postcss-reduce-initial": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/postcss-reduce-initial/-/postcss-reduce-initial-1.0.0.tgz", - "integrity": "sha1-j3Obk4KJ7y5Ik21xAXg+R0HKm7s=", - "dev": true, - "requires": { - "postcss": "5.2.4" - } - }, - "postcss-reduce-transforms": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/postcss-reduce-transforms/-/postcss-reduce-transforms-1.0.3.tgz", - "integrity": "sha1-/Bk+Q1qXPBD5gBx0cAqDD3lkM0M=", - "dev": true, - "requires": { - "postcss": "5.2.4", - "postcss-value-parser": "3.3.0" - } - }, - "postcss-svgo": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/postcss-svgo/-/postcss-svgo-2.1.5.tgz", - "integrity": "sha1-RvwDY/Abq2o2qauwHCKfzEU2MJQ=", - "dev": true, - "requires": { - "is-svg": "2.0.1", - "postcss": "5.2.4", - "postcss-value-parser": "3.3.0", - "svgo": "0.7.1" - }, - "dependencies": { - "is-svg": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-svg/-/is-svg-2.0.1.tgz", - "integrity": "sha1-+Tqzvx1rvKMOl1PNNIWxMA7rwBM=", - "dev": true, - "requires": { - "html-comment-regex": "1.1.1" - }, - "dependencies": { - "html-comment-regex": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/html-comment-regex/-/html-comment-regex-1.1.1.tgz", - "integrity": "sha1-ZouTd26q5V696POtRkswekljYl4=", - "dev": true - } - } - }, - "svgo": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/svgo/-/svgo-0.7.1.tgz", - "integrity": "sha1-KHMg/tlyywl+csK7FoX5b+CPgDQ=", - "dev": true, - "requires": { - "coa": "1.0.1", - "colors": "1.1.2", - "csso": "2.2.1", - "js-yaml": "3.6.1", - "mkdirp": "0.5.1", - "sax": "1.2.1", - "whet.extend": "0.9.9" - }, - "dependencies": { - "coa": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/coa/-/coa-1.0.1.tgz", - "integrity": "sha1-f5WTRs/IcZ4/cjPNaFKFSnxn2KM=", - "dev": true, - "requires": { - "q": "1.4.1" - }, - "dependencies": { - "q": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/q/-/q-1.4.1.tgz", - "integrity": "sha1-VXBbzZPF82c1MMLCy8DCs63cKG4=", - "dev": true - } - } - }, - "colors": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/colors/-/colors-1.1.2.tgz", - "integrity": "sha1-FopHAXVran9RoSzgyXv6KMCE7WM=", - "dev": true - }, - "csso": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/csso/-/csso-2.2.1.tgz", - "integrity": "sha1-Ufu1NH5Q6B5u1RZopISQrm/ir+I=", - "dev": true, - "requires": { - "clap": "1.1.1", - "source-map": "0.5.6" - }, - "dependencies": { - "clap": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/clap/-/clap-1.1.1.tgz", - "integrity": "sha1-qKk+C/t1gawZnE8AGlUlpyTOaW0=", - "dev": true, - "requires": { - "chalk": "1.1.3" - }, - "dependencies": { - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "dev": true, - "requires": { - "ansi-styles": "2.2.1", - "escape-string-regexp": "1.0.5", - "has-ansi": "2.0.0", - "strip-ansi": "3.0.1", - "supports-color": "2.0.0" - }, - "dependencies": { - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", - "dev": true - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true - }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "dev": true, - "requires": { - "ansi-regex": "2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz", - "integrity": "sha1-xQYbbg74qBd15Q9dZhUb9r83EQc=", - "dev": true - } - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "dev": true, - "requires": { - "ansi-regex": "2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz", - "integrity": "sha1-xQYbbg74qBd15Q9dZhUb9r83EQc=", - "dev": true - } - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", - "dev": true - } - } - } - } - }, - "source-map": { - "version": "0.5.6", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.6.tgz", - "integrity": "sha1-dc449SvwczxafwwRjYEzSiu19BI=", - "dev": true - } - } - }, - "js-yaml": { - "version": "3.6.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.6.1.tgz", - "integrity": "sha1-bl/mfYsgXOTSL60Ft3geja3MSzA=", - "dev": true, - "requires": { - "argparse": "1.0.9", - "esprima": "2.7.3" - }, - "dependencies": { - "argparse": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.9.tgz", - "integrity": "sha1-c9g7wmP4bpf4zE9rrhsOkKfSLIY=", - "dev": true, - "requires": { - "sprintf-js": "1.0.3" - }, - "dependencies": { - "sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", - "dev": true - } - } - }, - "esprima": { - "version": "2.7.3", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-2.7.3.tgz", - "integrity": "sha1-luO3DVd59q1JzQMmc9HDEnZ7pYE=", - "dev": true - } - } - }, - "mkdirp": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", - "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", - "dev": true, - "requires": { - "minimist": "0.0.8" - }, - "dependencies": { - "minimist": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", - "dev": true - } - } - }, - "sax": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.1.tgz", - "integrity": "sha1-e45lYZCyKOgaZq6nSEgNgozS03o=", - "dev": true - }, - "whet.extend": { - "version": "0.9.9", - "resolved": "https://registry.npmjs.org/whet.extend/-/whet.extend-0.9.9.tgz", - "integrity": "sha1-+HfVv2SMl+WqVC+twW1qJZucEaE=", - "dev": true - } - } - } - } - }, - "postcss-unique-selectors": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/postcss-unique-selectors/-/postcss-unique-selectors-2.0.2.tgz", - "integrity": "sha1-mB1X0p3csz57Hf4f1DuGSfkzyh0=", - "dev": true, - "requires": { - "alphanum-sort": "1.0.2", - "postcss": "5.2.4", - "uniqs": "2.0.0" - }, - "dependencies": { - "alphanum-sort": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/alphanum-sort/-/alphanum-sort-1.0.2.tgz", - "integrity": "sha1-l6ERlkmyEa0zaR2fn0hqjsn74KM=", - "dev": true - }, - "uniqs": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/uniqs/-/uniqs-2.0.0.tgz", - "integrity": "sha1-/+3ks2slKQaW5uFl1KWe25mOawI=", - "dev": true - } - } - }, - "postcss-value-parser": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-3.3.0.tgz", - "integrity": "sha1-h/OPnxj3dKSrTIojL1xc6IcqnRU=", - "dev": true - }, - "postcss-zindex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/postcss-zindex/-/postcss-zindex-2.1.1.tgz", - "integrity": "sha1-6j++ZWyXOKqHKeLuluwqRgibcg8=", - "dev": true, - "requires": { - "postcss": "5.2.4", - "uniqs": "2.0.0" - }, - "dependencies": { - "uniqs": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/uniqs/-/uniqs-2.0.0.tgz", - "integrity": "sha1-/+3ks2slKQaW5uFl1KWe25mOawI=", - "dev": true - } - } } - } }, - "loader-utils": { - "version": "0.2.16", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-0.2.16.tgz", - "integrity": "sha1-8IYyBm7YKCg13/iN+1JwR2Wt7m0=", - "dev": true, - "requires": { - "big.js": "3.1.3", - "emojis-list": "2.1.0", - "json5": "0.5.0", - "object-assign": "4.1.0" - }, - "dependencies": { - "big.js": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/big.js/-/big.js-3.1.3.tgz", - "integrity": "sha1-TK2iGTZS6zyp7I5VyQFWacmAaXg=", - "dev": true - }, - "emojis-list": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz", - "integrity": "sha1-TapNnbAPmBmIDHn6RXrlsJof04k=", - "dev": true - }, - "json5": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.0.tgz", - "integrity": "sha1-myBxWwJsvjd4/Xae3M2CLYMypbI=", - "dev": true + "@jest/types": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-24.9.0.tgz", + "integrity": "sha512-XKK7ze1apu5JWQ5eZjHITP66AX+QsLlbaJRBGYr8pNzwcAE2JVkwnf0yqjHTsDRcjR0mujy/NmZMXw5kl+kGBw==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^1.1.1", + "@types/yargs": "^13.0.0" } - } }, - "lodash.camelcase": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-3.0.1.tgz", - "integrity": "sha1-kyyLh/ikN3iXxnGXUzKC+Xrqwpg=", - "dev": true, - "requires": { - "lodash._createcompounder": "3.0.0" - }, - "dependencies": { - "lodash._createcompounder": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._createcompounder/-/lodash._createcompounder-3.0.0.tgz", - "integrity": "sha1-XdLLVTctbnDg4jkvsjBNZjEJEHU=", - "dev": true, - "requires": { - "lodash.deburr": "3.2.0", - "lodash.words": "3.2.0" - }, - "dependencies": { - "lodash.deburr": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/lodash.deburr/-/lodash.deburr-3.2.0.tgz", - "integrity": "sha1-baj1QzSjZqfPTEx2742Aqhs2XtU=", - "dev": true, - "requires": { - "lodash._root": "3.0.1" - }, - "dependencies": { - "lodash._root": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash._root/-/lodash._root-3.0.1.tgz", - "integrity": "sha1-+6HEUkwZ7ppfgTa0YJ8BfPTe1pI=", - "dev": true - } - } - }, - "lodash.words": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/lodash.words/-/lodash.words-3.2.0.tgz", - "integrity": "sha1-TiqGSbwIdFsXxpWxo86P7llmI7M=", - "dev": true, - "requires": { - "lodash._root": "3.0.1" - }, - "dependencies": { - "lodash._root": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash._root/-/lodash._root-3.0.1.tgz", - "integrity": "sha1-+6HEUkwZ7ppfgTa0YJ8BfPTe1pI=", - "dev": true - } - } - } - } + "@kyleshockey/object-assign-deep": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@kyleshockey/object-assign-deep/-/object-assign-deep-0.4.2.tgz", + "integrity": "sha1-hJAPDu/DcnmPR1G1JigwuCCJIuw=" + }, + "@sindresorhus/is": { + "version": "0.14.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", + "integrity": "sha512-9NET910DNaIPngYnLLPeg+Ogzqsi9uM4mSboU5y6p8S5DzMTVEsJZrawi+BoDNUVBa2DhJqQYUFvMDfgU062LQ==" + }, + "@szmarczak/http-timer": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-1.1.2.tgz", + "integrity": "sha512-XIB2XbzHTN6ieIjfIMV9hlVcfPU26s2vafYWQcZHWXHOxiaRZYEDKEwdl129Zyg50+foYV2jCgtrqSA6qNuNSA==", + "requires": { + "defer-to-connect": "^1.0.1" } - } }, - "object-assign": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.0.tgz", - "integrity": "sha1-ejs9DpgGPUP0wD8uiubNUahog6A=", - "dev": true - }, - "postcss": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-5.2.4.tgz", - "integrity": "sha1-jrS+4+XE4JFYWxFt8y2NskpTXyE=", - "dev": true, - "requires": { - "chalk": "1.1.3", - "js-base64": "2.1.9", - "source-map": "0.5.6", - "supports-color": "3.1.2" - }, - "dependencies": { - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "dev": true, - "requires": { - "ansi-styles": "2.2.1", - "escape-string-regexp": "1.0.5", - "has-ansi": "2.0.0", - "strip-ansi": "3.0.1", - "supports-color": "2.0.0" - }, - "dependencies": { - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", - "dev": true - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true - }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "dev": true, - "requires": { - "ansi-regex": "2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz", - "integrity": "sha1-xQYbbg74qBd15Q9dZhUb9r83EQc=", - "dev": true - } - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "dev": true, - "requires": { - "ansi-regex": "2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz", - "integrity": "sha1-xQYbbg74qBd15Q9dZhUb9r83EQc=", - "dev": true - } - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", - "dev": true - } - } - }, - "js-base64": { - "version": "2.1.9", - "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-2.1.9.tgz", - "integrity": "sha1-8OgK4DmkvWVLXygfyT8EqRSn/M4=", - "dev": true - }, - "source-map": { - "version": "0.5.6", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.6.tgz", - "integrity": "sha1-dc449SvwczxafwwRjYEzSiu19BI=", - "dev": true - }, - "supports-color": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.1.2.tgz", - "integrity": "sha1-cqJiiU2dQIuVbKBf83su2KbiotU=", - "dev": true, - "requires": { - "has-flag": "1.0.0" - }, - "dependencies": { - "has-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz", - "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=", - "dev": true - } - } + "@types/babel__core": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.1.3.tgz", + "integrity": "sha512-8fBo0UR2CcwWxeX7WIIgJ7lXjasFxoYgRnFHUj+hRvKkpiBJbxhdAPTCY6/ZKM0uxANFVzt4yObSLuTiTnazDA==", + "dev": true, + "requires": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" } - } }, - "postcss-modules-extract-imports": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-1.0.1.tgz", - "integrity": "sha1-j7P++abdBCDT9tQ1PPH/c/Kyo0E=", - "dev": true, - "requires": { - "postcss": "5.2.4" - } - }, - "postcss-modules-local-by-default": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/postcss-modules-local-by-default/-/postcss-modules-local-by-default-1.1.1.tgz", - "integrity": "sha1-KaEGc/o30ZJRJlyiujFQ2QQOtM4=", - "dev": true, - "requires": { - "css-selector-tokenizer": "0.6.0", - "postcss": "5.2.4" - } - }, - "postcss-modules-scope": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/postcss-modules-scope/-/postcss-modules-scope-1.0.2.tgz", - "integrity": "sha1-/5dzleXgYgLXNiKQuIsejNBJ3ik=", - "dev": true, - "requires": { - "css-selector-tokenizer": "0.6.0", - "postcss": "5.2.4" - } - }, - "postcss-modules-values": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/postcss-modules-values/-/postcss-modules-values-1.2.2.tgz", - "integrity": "sha1-8OfUdv4e2IxeTH+XUzo+dyrZTKE=", - "dev": true, - "requires": { - "icss-replace-symbols": "1.0.2", - "postcss": "5.2.4" - }, - "dependencies": { - "icss-replace-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/icss-replace-symbols/-/icss-replace-symbols-1.0.2.tgz", - "integrity": "sha1-ywtgVOs69u3Jqx1i0Bkz4tTIv6U=", - "dev": true + "@types/babel__generator": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.0.2.tgz", + "integrity": "sha512-NHcOfab3Zw4q5sEE2COkpfXjoE7o+PmqD9DQW4koUT3roNxwziUdXGnRndMat/LJNUtePwn1TlP4do3uoe3KZQ==", + "dev": true, + "requires": { + "@babel/types": "^7.0.0" } - } }, - "source-list-map": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-0.1.6.tgz", - "integrity": "sha1-4eb5TwtAxNKNz49bh2bg5FY2h38=", - "dev": true - } - } - }, - "currently-unhandled": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/currently-unhandled/-/currently-unhandled-0.4.1.tgz", - "integrity": "sha1-mI3zP+qxke95mmE2nddsF635V+o=", - "dev": true, - "requires": { - "array-find-index": "1.0.2" - } - }, - "custom-event": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/custom-event/-/custom-event-1.0.1.tgz", - "integrity": "sha1-XQKkaFCt8bSjF5RqOSj8y1v9BCU=", - "dev": true - }, - "d": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/d/-/d-0.1.1.tgz", - "integrity": "sha1-2hhMU10Y2O57oqoim5FACfrhEwk=", - "dev": true, - "requires": { - "es5-ext": "0.10.12" - } - }, - "dargs": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/dargs/-/dargs-5.1.0.tgz", - "integrity": "sha1-7H6lDHhWTNNsnV7Bj2Yyn63ieCk=", - "dev": true - }, - "dashdash": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.0.tgz", - "integrity": "sha1-KeSGxUGL8PNWA0qZPVFoajPoQUE=", - "dev": true, - "requires": { - "assert-plus": "1.0.0" - }, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", - "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", - "dev": true - } - } - }, - "date-now": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz", - "integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs=", - "dev": true - }, - "dateformat": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-1.0.12.tgz", - "integrity": "sha1-nxJLZ1lMk3/3BpMuSmQsyo27/uk=", - "dev": true, - "requires": { - "get-stdin": "4.0.1", - "meow": "3.7.0" - } - }, - "debug": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", - "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", - "dev": true, - "requires": { - "ms": "0.7.1" - } - }, - "decamelize": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", - "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", - "dev": true - }, - "decode-uri-component": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", - "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", - "dev": true - }, - "deep-defaults": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/deep-defaults/-/deep-defaults-1.0.4.tgz", - "integrity": "sha1-Gpdi4rbI1qTpkxuO5/+M3O4dF1A=", - "dev": true, - "requires": { - "lodash": "3.0.1" - }, - "dependencies": { - "lodash": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.0.1.tgz", - "integrity": "sha1-FNSQKKOLx0AkHRHi7NV+wG1zwZo=", - "dev": true - } - } - }, - "deep-equal": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz", - "integrity": "sha1-9dJgKStmDghO/0zbyfCK0yR0SLU=", - "dev": true - }, - "deep-extend": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.4.2.tgz", - "integrity": "sha1-SLaZwn4zS/ifEIkr5DL25MfTSn8=", - "dev": true - }, - "deep-is": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", - "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=" - }, - "defaults": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.3.tgz", - "integrity": "sha1-xlYFHpgX2f8I7YgUd/P+QBnz730=", - "dev": true, - "requires": { - "clone": "1.0.2" - } - }, - "define-properties": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.2.tgz", - "integrity": "sha1-g6c/L+pWmJj7c3GTyPhzyvbUXJQ=", - "dev": true, - "requires": { - "foreach": "2.0.5", - "object-keys": "1.0.11" - }, - "dependencies": { - "object-keys": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.0.11.tgz", - "integrity": "sha1-xUYBd4rVYPEULODgG8yotW0TQm0=", - "dev": true - } - } - }, - "define-property": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", - "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", - "dev": true, - "requires": { - "is-descriptor": "1.0.2" - } - }, - "del": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/del/-/del-2.2.2.tgz", - "integrity": "sha1-wSyYHQZ4RshLyvhiz/kw2Qf/0ag=", - "requires": { - "globby": "5.0.0", - "is-path-cwd": "1.0.0", - "is-path-in-cwd": "1.0.0", - "object-assign": "4.1.0", - "pify": "2.3.0", - "pinkie-promise": "2.0.1", - "rimraf": "2.5.4" - } - }, - "delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", - "dev": true - }, - "delegates": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", - "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=", - "dev": true - }, - "denque": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/denque/-/denque-1.2.3.tgz", - "integrity": "sha512-BOjyD1zPf7gqgXlXBCnCsz84cbRNfqpQNvWOUiw3Onu9s7a2afW2LyHzctoie/2KELfUoZkNHTnW02C3hCU20w==", - "dev": true - }, - "depd": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", - "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", - "dev": true - }, - "deprecated": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/deprecated/-/deprecated-0.0.1.tgz", - "integrity": "sha1-+cmvVGSvoeepcUWKi97yqpTVuxk=", - "dev": true - }, - "des.js": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.0.tgz", - "integrity": "sha1-wHTS4qpqipoH29YfmhXCzYPsjsw=", - "dev": true, - "requires": { - "inherits": "2.0.3", - "minimalistic-assert": "1.0.0" - } - }, - "destroy": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", - "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=", - "dev": true - }, - "detect-file": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-1.0.0.tgz", - "integrity": "sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc=", - "dev": true - }, - "detect-indent": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz", - "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", - "dev": true, - "requires": { - "repeating": "2.0.1" - } - }, - "detect-node": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.0.3.tgz", - "integrity": "sha1-ogM8CcyOFY03dI+951B4Mr1s4Sc=", - "dev": true - }, - "di": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/di/-/di-0.0.1.tgz", - "integrity": "sha1-gGZJMmzqp8qjMG112YXqJ0i6kTw=", - "dev": true - }, - "diffie-hellman": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.2.tgz", - "integrity": "sha1-tYNXOScM/ias9jIJn97SoH8gnl4=", - "dev": true, - "requires": { - "bn.js": "4.11.8", - "miller-rabin": "4.0.1", - "randombytes": "2.0.6" - } - }, - "dns-equal": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/dns-equal/-/dns-equal-1.0.0.tgz", - "integrity": "sha1-s55/HabrCnW6nBcySzR1PEfgZU0=", - "dev": true - }, - "dns-packet": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-1.3.1.tgz", - "integrity": "sha512-0UxfQkMhYAUaZI+xrNZOz/as5KgDU0M/fQ9b6SpkyLbk3GEswDi6PADJVaYJradtRVsRIlF1zLyOodbcTCDzUg==", - "dev": true, - "requires": { - "ip": "1.1.5", - "safe-buffer": "5.1.1" - } - }, - "dns-txt": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/dns-txt/-/dns-txt-2.0.2.tgz", - "integrity": "sha1-uR2Ab10nGI5Ks+fRB9iBocxGQrY=", - "dev": true, - "requires": { - "buffer-indexof": "1.1.1" - } - }, - "doctrine": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", - "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", - "requires": { - "esutils": "2.0.2" - } - }, - "dom-serialize": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/dom-serialize/-/dom-serialize-2.2.1.tgz", - "integrity": "sha1-ViromZ9Evl6jB29UGdzVnrQ6yVs=", - "dev": true, - "requires": { - "custom-event": "1.0.1", - "ent": "2.2.0", - "extend": "3.0.0", - "void-elements": "2.0.1" - } - }, - "dom-serializer": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.0.tgz", - "integrity": "sha1-BzxpdUbOB4DOI75KKOKT5AvDDII=", - "requires": { - "domelementtype": "1.1.3", - "entities": "1.1.1" - }, - "dependencies": { - "domelementtype": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.1.3.tgz", - "integrity": "sha1-vSh3PiZCiBrsUVRJJCmcXNgiGFs=" - } - } - }, - "domain-browser": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.2.0.tgz", - "integrity": "sha512-jnjyiM6eRyZl2H+W8Q/zLMA481hzi0eszAaBUzIVnmYVDBbnLxVNnfu1HgEBvCbL+71FrxMl3E6lpKH7Ge3OXA==", - "dev": true - }, - "domelementtype": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.0.tgz", - "integrity": "sha1-sXrtguirWeUt2cGbF1bg/BhyBMI=" - }, - "domhandler": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.4.1.tgz", - "integrity": "sha1-iS5HAAqZvlW783dP/qBWHYh5wlk=", - "requires": { - "domelementtype": "1.3.0" - } - }, - "domutils": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.7.0.tgz", - "integrity": "sha512-Lgd2XcJ/NjEw+7tFvfKxOzCYKZsdct5lczQ2ZaQY8Djz7pfAD3Gbp8ySJWtreII/vDlMVmxwa6pHmdxIYgttDg==", - "requires": { - "dom-serializer": "0.1.0", - "domelementtype": "1.3.0" - } - }, - "dot-prop": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-4.2.0.tgz", - "integrity": "sha1-HxngwuGqDjJ5fEl5nyg3rGr2nFc=", - "dev": true, - "requires": { - "is-obj": "1.0.1" - } - }, - "duplexer": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz", - "integrity": "sha1-rOb/gIwc5mtX0ev5eXessCM0z8E=", - "dev": true - }, - "duplexer2": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.0.2.tgz", - "integrity": "sha1-xhTc9n4vsUmVqRcR5aYX6KYKMds=", - "dev": true, - "requires": { - "readable-stream": "1.1.14" - }, - "dependencies": { - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - }, - "readable-stream": { - "version": "1.1.14", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", - "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "0.0.1", - "string_decoder": "0.10.31" - } - } - } - }, - "duplexer3": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/duplexer3/-/duplexer3-0.1.4.tgz", - "integrity": "sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=", - "dev": true - }, - "ecc-jsbn": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz", - "integrity": "sha1-D8c6ntXw1Tw4GTOYUj735UN3dQU=", - "dev": true, - "optional": true, - "requires": { - "jsbn": "0.1.0" - } - }, - "ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", - "dev": true - }, - "electron": { - "version": "1.7.9", - "resolved": "https://registry.npmjs.org/electron/-/electron-1.7.9.tgz", - "integrity": "sha1-rdVOn4+D7QL2UZ7BATX2mLGTNs8=", - "dev": true, - "requires": { - "@types/node": "7.0.48", - "electron-download": "3.3.0", - "extract-zip": "1.6.6" - } - }, - "electron-download": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/electron-download/-/electron-download-3.3.0.tgz", - "integrity": "sha1-LP1U1pZsAZxNSa1l++Zcyc3vaMg=", - "dev": true, - "requires": { - "debug": "2.2.0", - "fs-extra": "0.30.0", - "home-path": "1.0.5", - "minimist": "1.2.0", - "nugget": "2.0.1", - "path-exists": "2.1.0", - "rc": "1.2.1", - "semver": "5.3.0", - "sumchecker": "1.3.1" - }, - "dependencies": { - "fs-extra": { - "version": "0.30.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-0.30.0.tgz", - "integrity": "sha1-8jP/zAjU2n1DLapEl3aYnbHfk/A=", - "dev": true, - "requires": { - "graceful-fs": "4.1.10", - "jsonfile": "2.4.0", - "klaw": "1.3.1", - "path-is-absolute": "1.0.1", - "rimraf": "2.5.4" - } - }, - "jsonfile": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-2.4.0.tgz", - "integrity": "sha1-NzaitCi4e72gzIO1P6PWM6NcKug=", - "dev": true, - "requires": { - "graceful-fs": "4.1.10" - } - } - } - }, - "elliptic": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.0.tgz", - "integrity": "sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=", - "dev": true, - "requires": { - "bn.js": "4.11.8", - "brorand": "1.1.0", - "hash.js": "1.1.3", - "hmac-drbg": "1.0.1", - "inherits": "2.0.3", - "minimalistic-assert": "1.0.0", - "minimalistic-crypto-utils": "1.0.1" - } - }, - "emojis-list": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz", - "integrity": "sha1-TapNnbAPmBmIDHn6RXrlsJof04k=", - "dev": true - }, - "encodeurl": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.1.tgz", - "integrity": "sha1-eePVhlU0aQn+bw9Fpd5oEDspTSA=", - "dev": true - }, - "end-of-stream": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-0.1.5.tgz", - "integrity": "sha1-jhdyBsPICDfYVjLouTWd/osvbq8=", - "dev": true, - "requires": { - "once": "1.3.3" - }, - "dependencies": { - "once": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/once/-/once-1.3.3.tgz", - "integrity": "sha1-suJhVXzkwxTsgwTz+oJmPkKXyiA=", - "dev": true, - "requires": { - "wrappy": "1.0.2" - } - } - } - }, - "engine.io": { - "version": "1.8.3", - "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-1.8.3.tgz", - "integrity": "sha1-jef5eJXSDTm4X4ju7nd7K9QrE9Q=", - "dev": true, - "requires": { - "accepts": "1.3.3", - "base64id": "1.0.0", - "cookie": "0.3.1", - "debug": "2.3.3", - "engine.io-parser": "1.3.2", - "ws": "1.1.2" - }, - "dependencies": { - "debug": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.3.3.tgz", - "integrity": "sha1-QMRT5n5uE8kB3ewxeviYbNqe/4w=", - "dev": true, - "requires": { - "ms": "0.7.2" - } - }, - "ms": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.2.tgz", - "integrity": "sha1-riXPJRKziFodldfwN4aNhDESR2U=", - "dev": true - } - } - }, - "engine.io-client": { - "version": "1.8.3", - "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-1.8.3.tgz", - "integrity": "sha1-F5jtk0USRkU9TG9jXXogH+lA1as=", - "dev": true, - "requires": { - "component-emitter": "1.2.1", - "component-inherit": "0.0.3", - "debug": "2.3.3", - "engine.io-parser": "1.3.2", - "has-cors": "1.1.0", - "indexof": "0.0.1", - "parsejson": "0.0.3", - "parseqs": "0.0.5", - "parseuri": "0.0.5", - "ws": "1.1.2", - "xmlhttprequest-ssl": "1.5.3", - "yeast": "0.1.2" - }, - "dependencies": { - "component-emitter": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", - "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=", - "dev": true - }, - "debug": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.3.3.tgz", - "integrity": "sha1-QMRT5n5uE8kB3ewxeviYbNqe/4w=", - "dev": true, - "requires": { - "ms": "0.7.2" - } - }, - "ms": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.2.tgz", - "integrity": "sha1-riXPJRKziFodldfwN4aNhDESR2U=", - "dev": true - } - } - }, - "engine.io-parser": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-1.3.2.tgz", - "integrity": "sha1-k3sHnwAH0Ik+xW1GyyILjLQ1Igo=", - "dev": true, - "requires": { - "after": "0.8.2", - "arraybuffer.slice": "0.0.6", - "base64-arraybuffer": "0.1.5", - "blob": "0.0.4", - "has-binary": "0.1.7", - "wtf-8": "1.0.0" - } - }, - "enhanced-resolve": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-3.4.1.tgz", - "integrity": "sha1-BCHjOf1xQZs9oT0Smzl5BAIwR24=", - "dev": true, - "requires": { - "graceful-fs": "4.1.10", - "memory-fs": "0.4.1", - "object-assign": "4.1.0", - "tapable": "0.2.8" - } - }, - "enqueue": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/enqueue/-/enqueue-1.0.2.tgz", - "integrity": "sha1-kBTpvOVw7pPKlubI5jrVTBkra8g=", - "dev": true, - "requires": { - "sliced": "0.0.5" - }, - "dependencies": { - "sliced": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz", - "integrity": "sha1-XtwETKTrb3gW1Qui/GPiXY/kcH8=", - "dev": true - } - } - }, - "ent": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/ent/-/ent-2.2.0.tgz", - "integrity": "sha1-6WQhkyWiHQX0RGai9obtbOX13R0=", - "dev": true - }, - "entities": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.1.tgz", - "integrity": "sha1-blwtClYhtdra7O+AuQ7ftc13cvA=" - }, - "errno": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.4.tgz", - "integrity": "sha1-uJbiOp5ei6M4cfyZar02NfyaHH0=", - "dev": true, - "requires": { - "prr": "0.0.0" - } - }, - "error-ex": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.0.tgz", - "integrity": "sha1-5ntD8+gsluo6WE/+4Ln8MyXYAtk=", - "dev": true, - "requires": { - "is-arrayish": "0.2.1" - } - }, - "es-abstract": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.10.0.tgz", - "integrity": "sha512-/uh/DhdqIOSkAWifU+8nG78vlQxdLckUdI/sPgy0VhuXi2qJ7T8czBmqIYtLQVpCIFYafChnsRsB5pyb1JdmCQ==", - "dev": true, - "requires": { - "es-to-primitive": "1.1.1", - "function-bind": "1.1.1", - "has": "1.0.1", - "is-callable": "1.1.3", - "is-regex": "1.0.4" - } - }, - "es-to-primitive": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.1.1.tgz", - "integrity": "sha1-RTVSSKiJeQNLZ5Lhm7gfK3l13Q0=", - "dev": true, - "requires": { - "is-callable": "1.1.3", - "is-date-object": "1.0.1", - "is-symbol": "1.0.1" - } - }, - "es5-ext": { - "version": "0.10.12", - "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.12.tgz", - "integrity": "sha1-qoRkHU23a2Krul5F/YBey6sUAEc=", - "dev": true, - "requires": { - "es6-iterator": "2.0.0", - "es6-symbol": "3.1.0" - } - }, - "es6-iterator": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.0.tgz", - "integrity": "sha1-vZaFZ9YWNeM8C4BydhPJy0sJa6w=", - "dev": true, - "requires": { - "d": "0.1.1", - "es5-ext": "0.10.12", - "es6-symbol": "3.1.0" - } - }, - "es6-map": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/es6-map/-/es6-map-0.1.5.tgz", - "integrity": "sha1-kTbgUD3MBqMBaQ8LsU/042TpSfA=", - "dev": true, - "requires": { - "d": "1.0.0", - "es5-ext": "0.10.30", - "es6-iterator": "2.0.1", - "es6-set": "0.1.5", - "es6-symbol": "3.1.1", - "event-emitter": "0.3.5" - }, - "dependencies": { - "d": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/d/-/d-1.0.0.tgz", - "integrity": "sha1-dUu1v+VUUdpppYuU1F9MWwRi1Y8=", - "dev": true, - "requires": { - "es5-ext": "0.10.30" - } - }, - "es5-ext": { - "version": "0.10.30", - "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.30.tgz", - "integrity": "sha1-cUGhaDZpfbq/qq7uQUlc4p9SyTk=", - "dev": true, - "requires": { - "es6-iterator": "2.0.1", - "es6-symbol": "3.1.1" - } - }, - "es6-iterator": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.1.tgz", - "integrity": "sha1-jjGcnwRTv1ddN0lAplWSDlnKVRI=", - "dev": true, - "requires": { - "d": "1.0.0", - "es5-ext": "0.10.30", - "es6-symbol": "3.1.1" - } - }, - "es6-symbol": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.1.tgz", - "integrity": "sha1-vwDvT9q2uhtG7Le2KbTH7VcVzHc=", - "dev": true, - "requires": { - "d": "1.0.0", - "es5-ext": "0.10.30" - } - } - } - }, - "es6-promise": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.1.1.tgz", - "integrity": "sha1-iBHpCRXZoNujYnTwskLb2nj5ySo=", - "dev": true - }, - "es6-set": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/es6-set/-/es6-set-0.1.5.tgz", - "integrity": "sha1-0rPsXU2ADO2BjbU40ol02wpzzLE=", - "dev": true, - "requires": { - "d": "1.0.0", - "es5-ext": "0.10.30", - "es6-iterator": "2.0.1", - "es6-symbol": "3.1.1", - "event-emitter": "0.3.5" - }, - "dependencies": { - "d": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/d/-/d-1.0.0.tgz", - "integrity": "sha1-dUu1v+VUUdpppYuU1F9MWwRi1Y8=", - "dev": true, - "requires": { - "es5-ext": "0.10.30" - } - }, - "es5-ext": { - "version": "0.10.30", - "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.30.tgz", - "integrity": "sha1-cUGhaDZpfbq/qq7uQUlc4p9SyTk=", - "dev": true, - "requires": { - "es6-iterator": "2.0.1", - "es6-symbol": "3.1.1" - } - }, - "es6-iterator": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.1.tgz", - "integrity": "sha1-jjGcnwRTv1ddN0lAplWSDlnKVRI=", - "dev": true, - "requires": { - "d": "1.0.0", - "es5-ext": "0.10.30", - "es6-symbol": "3.1.1" - } - }, - "es6-symbol": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.1.tgz", - "integrity": "sha1-vwDvT9q2uhtG7Le2KbTH7VcVzHc=", - "dev": true, - "requires": { - "d": "1.0.0", - "es5-ext": "0.10.30" - } - } - } - }, - "es6-symbol": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.0.tgz", - "integrity": "sha1-lEgcZV56fK2C66gy2X1UM0ltf/o=", - "dev": true, - "requires": { - "d": "0.1.1", - "es5-ext": "0.10.12" - } - }, - "es6-templates": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/es6-templates/-/es6-templates-0.2.3.tgz", - "integrity": "sha1-XLmsn7He1usSOTQrgdeSu7QHjuQ=", - "dev": true, - "requires": { - "recast": "0.11.18", - "through": "2.3.8" - } - }, - "es6-weak-map": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/es6-weak-map/-/es6-weak-map-2.0.2.tgz", - "integrity": "sha1-XjqzIlH/0VOKH45f+hNXdy+S2W8=", - "dev": true, - "requires": { - "d": "1.0.0", - "es5-ext": "0.10.30", - "es6-iterator": "2.0.1", - "es6-symbol": "3.1.1" - }, - "dependencies": { - "d": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/d/-/d-1.0.0.tgz", - "integrity": "sha1-dUu1v+VUUdpppYuU1F9MWwRi1Y8=", - "dev": true, - "requires": { - "es5-ext": "0.10.30" - } - }, - "es5-ext": { - "version": "0.10.30", - "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.30.tgz", - "integrity": "sha1-cUGhaDZpfbq/qq7uQUlc4p9SyTk=", - "dev": true, - "requires": { - "es6-iterator": "2.0.1", - "es6-symbol": "3.1.1" - } - }, - "es6-iterator": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.1.tgz", - "integrity": "sha1-jjGcnwRTv1ddN0lAplWSDlnKVRI=", - "dev": true, - "requires": { - "d": "1.0.0", - "es5-ext": "0.10.30", - "es6-symbol": "3.1.1" - } - }, - "es6-symbol": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.1.tgz", - "integrity": "sha1-vwDvT9q2uhtG7Le2KbTH7VcVzHc=", - "dev": true, - "requires": { - "d": "1.0.0", - "es5-ext": "0.10.30" - } - } - } - }, - "escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", - "dev": true - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" - }, - "escope": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/escope/-/escope-3.6.0.tgz", - "integrity": "sha1-4Bl16BJ4GhY6ba392AOY3GTIicM=", - "dev": true, - "requires": { - "es6-map": "0.1.5", - "es6-weak-map": "2.0.2", - "esrecurse": "4.2.0", - "estraverse": "4.2.0" - } - }, - "eslint": { - "version": "4.17.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-4.17.0.tgz", - "integrity": "sha512-AyxBUCANU/o/xC0ijGMKavo5Ls3oK6xykiOITlMdjFjrKOsqLrA7Nf5cnrDgcKrHzBirclAZt63XO7YZlVUPwA==", - "requires": { - "ajv": "5.5.2", - "babel-code-frame": "6.26.0", - "chalk": "2.3.1", - "concat-stream": "1.6.0", - "cross-spawn": "5.1.0", - "debug": "3.1.0", - "doctrine": "2.1.0", - "eslint-scope": "3.7.1", - "eslint-visitor-keys": "1.0.0", - "espree": "3.5.3", - "esquery": "1.0.0", - "esutils": "2.0.2", - "file-entry-cache": "2.0.0", - "functional-red-black-tree": "1.0.1", - "glob": "7.1.2", - "globals": "11.3.0", - "ignore": "3.3.7", - "imurmurhash": "0.1.4", - "inquirer": "3.3.0", - "is-resolvable": "1.1.0", - "js-yaml": "3.10.0", - "json-stable-stringify-without-jsonify": "1.0.1", - "levn": "0.3.0", - "lodash": "4.17.5", - "minimatch": "3.0.3", - "mkdirp": "0.5.1", - "natural-compare": "1.4.0", - "optionator": "0.8.2", - "path-is-inside": "1.0.2", - "pluralize": "7.0.0", - "progress": "2.0.0", - "require-uncached": "1.0.3", - "semver": "5.3.0", - "strip-ansi": "4.0.0", - "strip-json-comments": "2.0.1", - "table": "4.0.2", - "text-table": "0.2.0" - }, - "dependencies": { - "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" - }, - "ansi-styles": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.0.tgz", - "integrity": "sha512-NnSOmMEYtVR2JVMIGTzynRkkaxtiq1xnFBcdQD/DnNCYPoEPsVJhM98BDyaoNOQIi7p4okdi3E27eN7GQbsUug==", - "requires": { - "color-convert": "1.9.0" - } - }, - "balanced-match": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" - }, - "brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "requires": { - "balanced-match": "1.0.0", - "concat-map": "0.0.1" - } - }, - "chalk": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.3.1.tgz", - "integrity": "sha512-QUU4ofkDoMIVO7hcx1iPTISs88wsO8jA92RQIm4JAwZvFGGAV2hSAA1NX7oVj2Ej2Q6NDTcRDjPTFrMCRZoJ6g==", - "requires": { - "ansi-styles": "3.2.0", - "escape-string-regexp": "1.0.5", - "supports-color": "5.2.0" - } - }, - "cross-spawn": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-5.1.0.tgz", - "integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=", - "requires": { - "lru-cache": "4.0.1", - "shebang-command": "1.2.0", - "which": "1.2.11" - } - }, - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", - "requires": { - "ms": "2.0.0" - } - }, - "glob": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", - "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", - "requires": { - "fs.realpath": "1.0.0", - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.4", - "once": "1.4.0", - "path-is-absolute": "1.0.1" - }, - "dependencies": { - "minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "requires": { - "brace-expansion": "1.1.11" - } + "@types/babel__template": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.0.2.tgz", + "integrity": "sha512-/K6zCpeW7Imzgab2bLkLEbz0+1JlFSrUMdw7KoIIu+IUdu51GWaBZpd3y1VXGVXzynvGa4DaIaxNZHiON3GXUg==", + "dev": true, + "requires": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" } - } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" - }, - "lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==" - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" - }, - "pluralize": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-7.0.0.tgz", - "integrity": "sha512-ARhBOdzS3e41FbkW/XWrTEtukqqLoK5+Z/4UeDaLuSW+39JPeFgs4gCGqsrJHVZX0fUrx//4OF0K1CUGwlIFow==" - }, - "strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "requires": { - "ansi-regex": "3.0.0" - } - }, - "supports-color": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.2.0.tgz", - "integrity": "sha512-F39vS48la4YvTZUPVeTqsjsFNrvcMwrV3RLZINsmHo+7djCvuUzSIeXOnZ5hmjef4bajL1dNccN+tg5XAliO5Q==", - "requires": { - "has-flag": "3.0.0" - } - } - } - }, - "eslint-config-angular": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/eslint-config-angular/-/eslint-config-angular-0.5.0.tgz", - "integrity": "sha1-4KrgEy4550Z98/dUf+yBpE02hcQ=", - "dev": true - }, - "eslint-config-google": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/eslint-config-google/-/eslint-config-google-0.6.0.tgz", - "integrity": "sha1-xULsGPsyR5g6wWu6MWYtAWJbdj8=", - "dev": true, - "requires": { - "eslint-config-xo": "0.13.0" - }, - "dependencies": { - "eslint-config-xo": { - "version": "0.13.0", - "resolved": "https://registry.npmjs.org/eslint-config-xo/-/eslint-config-xo-0.13.0.tgz", - "integrity": "sha1-+RZ2VDK6Z9L8enF3uLz+8/brBWQ=", - "dev": true - } - } - }, - "eslint-config-loopback": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/eslint-config-loopback/-/eslint-config-loopback-4.0.0.tgz", - "integrity": "sha1-0iwQUq19TNELij7KJStKkYSey9I=", - "dev": true - }, - "eslint-config-xo": { - "version": "0.17.0", - "resolved": "https://registry.npmjs.org/eslint-config-xo/-/eslint-config-xo-0.17.0.tgz", - "integrity": "sha1-Hn1Khr9JF5gFxGIugyp7G+606IE=", - "dev": true - }, - "eslint-plugin-html": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/eslint-plugin-html/-/eslint-plugin-html-4.0.2.tgz", - "integrity": "sha512-CrQd0F8GWdNWnu4PFrYZl+LjUCXNVy2h0uhDMtnf/7VKc9HRcnkXSrlg0BSGfptZPSzmwnnwCaREAa9+fnQhYw==", - "requires": { - "htmlparser2": "3.9.2" - } - }, - "eslint-plugin-jasmine": { - "version": "2.8.4", - "resolved": "https://registry.npmjs.org/eslint-plugin-jasmine/-/eslint-plugin-jasmine-2.8.4.tgz", - "integrity": "sha1-Z6VVHj0dXguMa1Sq66uVNw9dN94=", - "dev": true - }, - "eslint-scope": { - "version": "3.7.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-3.7.1.tgz", - "integrity": "sha1-PWPD7f2gLgbgGkUq2IyqzHzctug=", - "requires": { - "esrecurse": "4.2.0", - "estraverse": "4.2.0" - } - }, - "eslint-visitor-keys": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", - "integrity": "sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==" - }, - "espree": { - "version": "3.5.3", - "resolved": "https://registry.npmjs.org/espree/-/espree-3.5.3.tgz", - "integrity": "sha512-Zy3tAJDORxQZLl2baguiRU1syPERAIg0L+JB2MWorORgTu/CplzvxS9WWA7Xh4+Q+eOQihNs/1o1Xep8cvCxWQ==", - "requires": { - "acorn": "5.4.1", - "acorn-jsx": "3.0.1" - } - }, - "esprima": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.2.tgz", - "integrity": "sha1-lUtdGTIcpDYJL6kPBtZ5hTH+gYQ=", - "dev": true - }, - "esquery": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.0.0.tgz", - "integrity": "sha1-z7qLV9f7qT8XKYqKAGoEzaE9gPo=", - "requires": { - "estraverse": "4.2.0" - } - }, - "esrecurse": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.0.tgz", - "integrity": "sha1-+pVo2Y04I/mkHZHpAtyrnqblsWM=", - "requires": { - "estraverse": "4.2.0", - "object-assign": "4.1.0" - } - }, - "estraverse": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", - "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=" - }, - "esutils": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", - "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=" - }, - "etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=", - "dev": true - }, - "event-emitter": { - "version": "0.3.5", - "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz", - "integrity": "sha1-34xp7vFkeSPHFXuc6DhAYQsCzDk=", - "dev": true, - "requires": { - "d": "1.0.0", - "es5-ext": "0.10.30" - }, - "dependencies": { - "d": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/d/-/d-1.0.0.tgz", - "integrity": "sha1-dUu1v+VUUdpppYuU1F9MWwRi1Y8=", - "dev": true, - "requires": { - "es5-ext": "0.10.30" - } - }, - "es5-ext": { - "version": "0.10.30", - "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.30.tgz", - "integrity": "sha1-cUGhaDZpfbq/qq7uQUlc4p9SyTk=", - "dev": true, - "requires": { - "es6-iterator": "2.0.0", - "es6-symbol": "3.1.0" - } - } - } - }, - "event-stream": { - "version": "3.3.4", - "resolved": "https://registry.npmjs.org/event-stream/-/event-stream-3.3.4.tgz", - "integrity": "sha1-SrTJoPWlTbkzi0w02Gv86PSzVXE=", - "dev": true, - "requires": { - "duplexer": "0.1.1", - "from": "0.1.3", - "map-stream": "0.1.0", - "pause-stream": "0.0.11", - "split": "0.3.3", - "stream-combiner": "0.0.4", - "through": "2.3.8" - } - }, - "eventemitter3": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-1.2.0.tgz", - "integrity": "sha1-HIaZHYFq0eUEdQ5zh0Ik7PO+xQg=", - "dev": true - }, - "events": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz", - "integrity": "sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ=", - "dev": true - }, - "eventsource": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-0.1.6.tgz", - "integrity": "sha1-Cs7ehJ7X3RzMMsgRuxG5RNTykjI=", - "dev": true, - "requires": { - "original": "1.0.0" - } - }, - "evp_bytestokey": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", - "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", - "dev": true, - "requires": { - "md5.js": "1.3.4", - "safe-buffer": "5.1.1" - } - }, - "execa": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-0.7.0.tgz", - "integrity": "sha1-lEvs00zEHuMqY6n68nrVpl/Fl3c=", - "dev": true, - "requires": { - "cross-spawn": "5.1.0", - "get-stream": "3.0.0", - "is-stream": "1.1.0", - "npm-run-path": "2.0.2", - "p-finally": "1.0.0", - "signal-exit": "3.0.1", - "strip-eof": "1.0.0" - }, - "dependencies": { - "cross-spawn": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-5.1.0.tgz", - "integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=", - "dev": true, - "requires": { - "lru-cache": "4.0.1", - "shebang-command": "1.2.0", - "which": "1.2.11" - } - } - } - }, - "exit": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", - "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", - "dev": true - }, - "expand-braces": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/expand-braces/-/expand-braces-0.1.2.tgz", - "integrity": "sha1-SIsdHSRRyz06axks/AMPRMWFX+o=", - "dev": true, - "requires": { - "array-slice": "0.2.3", - "array-unique": "0.2.1", - "braces": "0.1.5" - }, - "dependencies": { - "braces": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/braces/-/braces-0.1.5.tgz", - "integrity": "sha1-wIVxEIUpHYt1/ddOqw+FlygHEeY=", - "dev": true, - "requires": { - "expand-range": "0.1.1" - } - }, - "expand-range": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/expand-range/-/expand-range-0.1.1.tgz", - "integrity": "sha1-TLjtoJk8pW+k9B/ELzy7TMrf8EQ=", - "dev": true, - "requires": { - "is-number": "0.1.1", - "repeat-string": "0.2.2" - } - }, - "is-number": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-0.1.1.tgz", - "integrity": "sha1-aaevEWlj1HIG7JvZtIoUIW8eOAY=", - "dev": true - }, - "repeat-string": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-0.2.2.tgz", - "integrity": "sha1-x6jTI2BoNiBZp+RlH8aITosftK4=", - "dev": true - } - } - }, - "expand-brackets": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", - "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", - "dev": true, - "requires": { - "is-posix-bracket": "0.1.1" - } - }, - "expand-range": { - "version": "1.8.2", - "resolved": "https://registry.npmjs.org/expand-range/-/expand-range-1.8.2.tgz", - "integrity": "sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc=", - "dev": true, - "requires": { - "fill-range": "2.2.3" - } - }, - "expand-tilde": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", - "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=", - "dev": true, - "requires": { - "homedir-polyfill": "1.0.1" - } - }, - "express": { - "version": "4.16.2", - "resolved": "https://registry.npmjs.org/express/-/express-4.16.2.tgz", - "integrity": "sha1-41xt/i1kt9ygpc1PIXgb4ymeB2w=", - "dev": true, - "requires": { - "accepts": "1.3.4", - "array-flatten": "1.1.1", - "body-parser": "1.18.2", - "content-disposition": "0.5.2", - "content-type": "1.0.4", - "cookie": "0.3.1", - "cookie-signature": "1.0.6", - "debug": "2.6.9", - "depd": "1.1.2", - "encodeurl": "1.0.1", - "escape-html": "1.0.3", - "etag": "1.8.1", - "finalhandler": "1.1.0", - "fresh": "0.5.2", - "merge-descriptors": "1.0.1", - "methods": "1.1.2", - "on-finished": "2.3.0", - "parseurl": "1.3.2", - "path-to-regexp": "0.1.7", - "proxy-addr": "2.0.2", - "qs": "6.5.1", - "range-parser": "1.2.0", - "safe-buffer": "5.1.1", - "send": "0.16.1", - "serve-static": "1.13.1", - "setprototypeof": "1.1.0", - "statuses": "1.3.1", - "type-is": "1.6.15", - "utils-merge": "1.0.1", - "vary": "1.1.2" - }, - "dependencies": { - "accepts": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.4.tgz", - "integrity": "sha1-hiRnWMfdbSGmR0/whKR0DsBesh8=", - "dev": true, - "requires": { - "mime-types": "2.1.17", - "negotiator": "0.6.1" - } - }, - "array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=", - "dev": true - }, - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "mime-db": { - "version": "1.30.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.30.0.tgz", - "integrity": "sha1-dMZD2i3Z1qRTmZY0ZbJtXKfXHwE=", - "dev": true - }, - "mime-types": { - "version": "2.1.17", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.17.tgz", - "integrity": "sha1-Cdejk/A+mVp5+K+Fe3Cp4KsWVXo=", - "dev": true, - "requires": { - "mime-db": "1.30.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - }, - "qs": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.1.tgz", - "integrity": "sha512-eRzhrN1WSINYCDCbrz796z37LOe3m5tmW7RQf6oBntukAG1nmovJvhnwHHRMAfeoItc1m2Hk02WER2aQ/iqs+A==", - "dev": true - } - } - }, - "extend": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.0.tgz", - "integrity": "sha1-WkdDU7nzNT3dgXbf03uRyDpG8dQ=", - "dev": true - }, - "extend-shallow": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", - "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", - "dev": true, - "requires": { - "assign-symbols": "1.0.0", - "is-extendable": "1.0.1" - }, - "dependencies": { - "is-extendable": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", - "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", - "dev": true, - "requires": { - "is-plain-object": "2.0.4" - } - } - } - }, - "external-editor": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-2.1.0.tgz", - "integrity": "sha512-E44iT5QVOUJBKij4IIV3uvxuNlbKS38Tw1HiupxEIHPv9qtC2PrDYohbXV5U+1jnfIXttny8gUhj+oZvflFlzA==", - "requires": { - "chardet": "0.4.2", - "iconv-lite": "0.4.19", - "tmp": "0.0.33" - }, - "dependencies": { - "tmp": { - "version": "0.0.33", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", - "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", - "requires": { - "os-tmpdir": "1.0.2" - } - } - } - }, - "extglob": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", - "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", - "dev": true, - "requires": { - "is-extglob": "1.0.0" - } - }, - "extract-zip": { - "version": "1.6.6", - "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-1.6.6.tgz", - "integrity": "sha1-EpDt6NINCHK0Kf0/NRyhKOxe+Fw=", - "dev": true, - "requires": { - "concat-stream": "1.6.0", - "debug": "2.6.9", - "mkdirp": "0.5.0", - "yauzl": "2.4.1" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha1-XRKFFd8TT/Mn6QpMk/Tgd6U2NB8=", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "minimist": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", - "dev": true - }, - "mkdirp": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.0.tgz", - "integrity": "sha1-HXMHam35hs2TROFecfzAWkyavxI=", - "dev": true, - "requires": { - "minimist": "0.0.8" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "extsprintf": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.0.2.tgz", - "integrity": "sha1-4QgOBljjALBilJkMxw4VAiNf1VA=", - "dev": true - }, - "fancy-log": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/fancy-log/-/fancy-log-1.3.2.tgz", - "integrity": "sha1-9BEl49hPLn2JpD0G2VjI94vha+E=", - "dev": true, - "requires": { - "ansi-gray": "0.1.1", - "color-support": "1.1.3", - "time-stamp": "1.1.0" - } - }, - "fast-deep-equal": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.0.0.tgz", - "integrity": "sha1-liVqO8l1WV6zbYLpkp0GDYk0Of8=" - }, - "fast-json-stable-stringify": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", - "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=" - }, - "fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=" - }, - "fastparse": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/fastparse/-/fastparse-1.1.1.tgz", - "integrity": "sha1-0eJkOzipTXWDtHkGDmxK/8lAcfg=", - "dev": true - }, - "faye-websocket": { - "version": "0.10.0", - "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.10.0.tgz", - "integrity": "sha1-TkkvjQTftviQA1B/btvy1QHnxvQ=", - "dev": true, - "requires": { - "websocket-driver": "0.7.0" - } - }, - "fd-slicer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.0.1.tgz", - "integrity": "sha1-i1vL2ewyfFBBv5qwI/1nUPEXfmU=", - "dev": true, - "requires": { - "pend": "1.2.0" - } - }, - "figures": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", - "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", - "requires": { - "escape-string-regexp": "1.0.5" - } - }, - "file-entry-cache": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-2.0.0.tgz", - "integrity": "sha1-w5KZDD5oR4PYOLjISkXYoEhFg2E=", - "requires": { - "flat-cache": "1.3.0", - "object-assign": "4.1.0" - } - }, - "file-loader": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/file-loader/-/file-loader-1.1.6.tgz", - "integrity": "sha512-873ztuL+/hfvXbLDJ262PGO6XjERnybJu2gW1/5j8HUfxSiFJI9Hj/DhZ50ZGRUxBvuNiazb/cM2rh9pqrxP6Q==", - "dev": true, - "requires": { - "loader-utils": "1.1.0", - "schema-utils": "0.3.0" - }, - "dependencies": { - "loader-utils": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.1.0.tgz", - "integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=", - "dev": true, - "requires": { - "big.js": "3.1.3", - "emojis-list": "2.1.0", - "json5": "0.5.0" - } - } - } - }, - "filename-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/filename-regex/-/filename-regex-2.0.0.tgz", - "integrity": "sha1-mW4+gEebmLmJfxWopYs9CE6SZ3U=", - "dev": true - }, - "fill-range": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-2.2.3.tgz", - "integrity": "sha1-ULd9/X5Gm8dJJHCWNpn+eoSFpyM=", - "dev": true, - "requires": { - "is-number": "2.1.0", - "isobject": "2.1.0", - "randomatic": "1.1.6", - "repeat-element": "1.1.2", - "repeat-string": "1.6.1" - } - }, - "finalhandler": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.0.tgz", - "integrity": "sha1-zgtoVbRYU+eRsvzGgARtiCU91/U=", - "dev": true, - "requires": { - "debug": "2.6.9", - "encodeurl": "1.0.1", - "escape-html": "1.0.3", - "on-finished": "2.3.0", - "parseurl": "1.3.2", - "statuses": "1.3.1", - "unpipe": "1.0.0" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "find-cache-dir": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-1.0.0.tgz", - "integrity": "sha1-kojj6ePMN0hxfTnq3hfPcfww7m8=", - "dev": true, - "requires": { - "commondir": "1.0.1", - "make-dir": "1.0.0", - "pkg-dir": "2.0.0" - } - }, - "find-index": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/find-index/-/find-index-0.1.1.tgz", - "integrity": "sha1-Z101iyyjiS15Whq0cjL4tuLg3eQ=", - "dev": true - }, - "find-up": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", - "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", - "dev": true, - "requires": { - "path-exists": "2.1.0", - "pinkie-promise": "2.0.1" - } - }, - "findup-sync": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-2.0.0.tgz", - "integrity": "sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw=", - "dev": true, - "requires": { - "detect-file": "1.0.0", - "is-glob": "3.1.0", - "micromatch": "3.1.5", - "resolve-dir": "1.0.1" - }, - "dependencies": { - "arr-diff": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", - "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", - "dev": true - }, - "arr-flatten": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", - "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", - "dev": true - }, - "array-unique": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", - "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", - "dev": true - }, - "braces": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.0.tgz", - "integrity": "sha512-P4O8UQRdGiMLWSizsApmXVQDBS6KCt7dSexgLKBmH5Hr1CZq7vsnscFh8oR1sP1ab1Zj0uCHCEzZeV6SfUf3rA==", - "dev": true, - "requires": { - "arr-flatten": "1.1.0", - "array-unique": "0.3.2", - "define-property": "1.0.0", - "extend-shallow": "2.0.1", - "fill-range": "4.0.0", - "isobject": "3.0.1", - "repeat-element": "1.1.2", - "snapdragon": "0.8.1", - "snapdragon-node": "2.1.1", - "split-string": "3.1.0", - "to-regex": "3.0.1" - } - }, - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "expand-brackets": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", - "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", - "dev": true, - "requires": { - "debug": "2.6.9", - "define-property": "0.2.5", - "extend-shallow": "2.0.1", - "posix-character-classes": "0.1.1", - "regex-not": "1.0.0", - "snapdragon": "0.8.1", - "to-regex": "3.0.1" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "0.1.6" - } + "@types/babel__traverse": { + "version": "7.0.7", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.0.7.tgz", + "integrity": "sha512-CeBpmX1J8kWLcDEnI3Cl2Eo6RfbGvzUctA+CjZUhOKDFbLfcr7fc4usEqLNWetrlJd7RhAkyYe2czXop4fICpw==", + "dev": true, + "requires": { + "@babel/types": "^7.3.0" } - } }, - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "0.1.1" - } - }, - "extglob": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", - "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", - "dev": true, - "requires": { - "array-unique": "0.3.2", - "define-property": "1.0.0", - "expand-brackets": "2.1.4", - "extend-shallow": "2.0.1", - "fragment-cache": "0.2.1", - "regex-not": "1.0.0", - "snapdragon": "0.8.1", - "to-regex": "3.0.1" - } - }, - "fill-range": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", - "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", - "dev": true, - "requires": { - "extend-shallow": "2.0.1", - "is-number": "3.0.0", - "repeat-string": "1.6.1", - "to-regex-range": "2.1.1" - } - }, - "is-accessor-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", - "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } + "@types/body-parser": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.17.0.tgz", + "integrity": "sha512-a2+YeUjPkztKJu5aIF2yArYFQQp8d51wZ7DavSHjFuY1mqVgidGyzEQ41JIVNy82fXj8yPgy2vJmfIywgESW6w==", + "requires": { + "@types/connect": "*", + "@types/node": "*" } - } }, - "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "dev": true + "@types/caseless": { + "version": "0.12.2", + "resolved": "https://registry.npmjs.org/@types/caseless/-/caseless-0.12.2.tgz", + "integrity": "sha512-6ckxMjBBD8URvjB6J3NcnuAn5Pkl7t3TizAg+xdlzzQGSPSmBcXf8KoIH0ua/i+tio+ZRUHEXp0HEmvaR4kt0w==" }, - "is-data-descriptor": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", - "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } + "@types/connect": { + "version": "3.4.32", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.32.tgz", + "integrity": "sha512-4r8qa0quOvh7lGD0pre62CAb1oni1OO6ecJLGCezTmhQ8Fz50Arx9RUszryR8KlgK6avuSXvviL6yWyViQABOg==", + "requires": { + "@types/node": "*" } - } }, - "is-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", - "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", - "dev": true, - "requires": { - "is-accessor-descriptor": "0.1.6", - "is-data-descriptor": "0.1.4", - "kind-of": "5.1.0" - }, - "dependencies": { - "kind-of": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", - "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", - "dev": true + "@types/events": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-3.0.0.tgz", + "integrity": "sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g==", + "dev": true + }, + "@types/express": { + "version": "4.17.0", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.0.tgz", + "integrity": "sha512-CjaMu57cjgjuZbh9DpkloeGxV45CnMGlVd+XpG7Gm9QgVrd7KFq+X4HY0vM+2v0bczS48Wg7bvnMY5TN+Xmcfw==", + "requires": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "*", + "@types/serve-static": "*" } - } }, - "is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", - "dev": true - }, - "is-glob": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", - "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", - "dev": true, - "requires": { - "is-extglob": "2.1.1" - } - }, - "is-number": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", - "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } + "@types/express-serve-static-core": { + "version": "4.16.7", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.16.7.tgz", + "integrity": "sha512-847KvL8Q1y3TtFLRTXcVakErLJQgdpFSaq+k043xefz9raEf0C7HalpSY7OW5PyjCnY8P7bPW5t/Co9qqp+USg==", + "requires": { + "@types/node": "*", + "@types/range-parser": "*" } - } }, - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true + "@types/form-data": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@types/form-data/-/form-data-2.2.1.tgz", + "integrity": "sha512-JAMFhOaHIciYVh8fb5/83nmuO/AHwmto+Hq7a9y8FzLDcC1KCU344XDOMEmahnrTFlHjgh4L0WJFczNIX2GxnQ==", + "requires": { + "@types/node": "*" + } }, - "kind-of": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", - "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", - "dev": true + "@types/glob": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-7.1.1.tgz", + "integrity": "sha512-1Bh06cbWJUHMC97acuD6UMG29nMt0Aqz1vF3guLfG+kHHJhy3AyohZFFxYk2f7Q1SQIrNwvncxAE0N/9s70F2w==", + "dev": true, + "requires": { + "@types/events": "*", + "@types/minimatch": "*", + "@types/node": "*" + } }, - "micromatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.5.tgz", - "integrity": "sha512-ykttrLPQrz1PUJcXjwsTUjGoPJ64StIGNE2lGVD1c9CuguJ+L7/navsE8IcDNndOoCMvYV0qc/exfVbMHkUhvA==", - "dev": true, - "requires": { - "arr-diff": "4.0.0", - "array-unique": "0.3.2", - "braces": "2.3.0", - "define-property": "1.0.0", - "extend-shallow": "2.0.1", - "extglob": "2.0.4", - "fragment-cache": "0.2.1", - "kind-of": "6.0.2", - "nanomatch": "1.2.7", - "object.pick": "1.3.0", - "regex-not": "1.0.0", - "snapdragon": "0.8.1", - "to-regex": "3.0.1" - } + "@types/istanbul-lib-coverage": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.1.tgz", + "integrity": "sha512-hRJD2ahnnpLgsj6KWMYSrmXkM3rm2Dl1qkx6IOFD5FnuNPXJIG5L0dhgKXCYTRMGzU4n0wImQ/xfmRc4POUFlg==", + "dev": true + }, + "@types/istanbul-lib-report": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-1.1.1.tgz", + "integrity": "sha512-3BUTyMzbZa2DtDI2BkERNC6jJw2Mr2Y0oGI7mRxYNBPxppbtEK1F66u3bKwU2g+wxwWI7PAoRpJnOY1grJqzHg==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "*" + } + }, + "@types/istanbul-reports": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-1.1.1.tgz", + "integrity": "sha512-UpYjBi8xefVChsCoBpKShdxTllC9pwISirfoZsUa2AAdQg/Jd2KQGtSbw+ya7GPo7x/wAPlH6JBhKhAsXUEZNA==", + "dev": true, + "requires": { + "@types/istanbul-lib-coverage": "*", + "@types/istanbul-lib-report": "*" + } + }, + "@types/mime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-2.0.1.tgz", + "integrity": "sha512-FwI9gX75FgVBJ7ywgnq/P7tw+/o1GUbtP0KzbtusLigAOgIgNISRK0ZPl4qertvXSIE8YbsVJueQ90cDt9YYyw==" + }, + "@types/minimatch": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "dev": true + }, + "@types/node": { + "version": "10.14.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-10.14.10.tgz", + "integrity": "sha512-V8wj+w2YMNvGuhgl/MA5fmTxgjmVHVoasfIaxMMZJV6Y8Kk+Ydpi1z2whoShDCJ2BuNVoqH/h1hrygnBxkrw/Q==" + }, + "@types/range-parser": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.3.tgz", + "integrity": "sha512-ewFXqrQHlFsgc09MK5jP5iR7vumV/BYayNC6PgJO2LPe8vrnNFyjQjSppfEngITi0qvfKtzFvgKymGheFM9UOA==" + }, + "@types/request": { + "version": "2.48.1", + "resolved": "https://registry.npmjs.org/@types/request/-/request-2.48.1.tgz", + "integrity": "sha512-ZgEZ1TiD+KGA9LiAAPPJL68Id2UWfeSO62ijSXZjFJArVV+2pKcsVHmrcu+1oiE3q6eDGiFiSolRc4JHoerBBg==", + "requires": { + "@types/caseless": "*", + "@types/form-data": "*", + "@types/node": "*", + "@types/tough-cookie": "*" + } + }, + "@types/serve-static": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.13.2.tgz", + "integrity": "sha512-/BZ4QRLpH/bNYgZgwhKEh+5AsboDBcUdlBYgzoLX0fpj3Y2gp6EApyOlM3bK53wQS/OE1SrdSYBAbux2D1528Q==", + "requires": { + "@types/express-serve-static-core": "*", + "@types/mime": "*" + } + }, + "@types/stack-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-1.0.1.tgz", + "integrity": "sha512-l42BggppR6zLmpfU6fq9HEa2oGPEI8yrSPL3GITjfRInppYFahObbIQOQK3UGxEnyQpltZLaPe75046NOZQikw==", + "dev": true + }, + "@types/tough-cookie": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-2.3.5.tgz", + "integrity": "sha512-SCcK7mvGi3+ZNz833RRjFIxrn4gI1PPR3NtuIS+6vMkvmsGjosqTJwRt5bAEFLRz+wtJMWv8+uOnZf2hi2QXTg==" + }, + "@types/yargs": { + "version": "13.0.2", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-13.0.2.tgz", + "integrity": "sha512-lwwgizwk/bIIU+3ELORkyuOgDjCh7zuWDFqRtPPhhVgq9N1F7CvLNKg1TX4f2duwtKQ0p044Au9r1PLIXHrIzQ==", + "dev": true, + "requires": { + "@types/yargs-parser": "*" + } + }, + "@types/yargs-parser": { + "version": "13.1.0", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-13.1.0.tgz", + "integrity": "sha512-gCubfBUZ6KxzoibJ+SCUc/57Ms1jz5NjHe4+dI2krNmU5zCPAphyLJYyTOg06ueIyfj+SaCUqmzun7ImlxDcKg==", + "dev": true + }, + "@webassemblyjs/ast": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.8.5.tgz", + "integrity": "sha512-aJMfngIZ65+t71C3y2nBBg5FFG0Okt9m0XEgWZ7Ywgn1oMAT8cNwx00Uv1cQyHtidq0Xn94R4TAywO+LCQ+ZAQ==", + "dev": true, + "requires": { + "@webassemblyjs/helper-module-context": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/wast-parser": "1.8.5" + } + }, + "@webassemblyjs/floating-point-hex-parser": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.8.5.tgz", + "integrity": "sha512-9p+79WHru1oqBh9ewP9zW95E3XAo+90oth7S5Re3eQnECGq59ly1Ri5tsIipKGpiStHsUYmY3zMLqtk3gTcOtQ==", + "dev": true + }, + "@webassemblyjs/helper-api-error": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.8.5.tgz", + "integrity": "sha512-Za/tnzsvnqdaSPOUXHyKJ2XI7PDX64kWtURyGiJJZKVEdFOsdKUCPTNEVFZq3zJ2R0G5wc2PZ5gvdTRFgm81zA==", + "dev": true + }, + "@webassemblyjs/helper-buffer": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.8.5.tgz", + "integrity": "sha512-Ri2R8nOS0U6G49Q86goFIPNgjyl6+oE1abW1pS84BuhP1Qcr5JqMwRFT3Ah3ADDDYGEgGs1iyb1DGX+kAi/c/Q==", + "dev": true + }, + "@webassemblyjs/helper-code-frame": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-code-frame/-/helper-code-frame-1.8.5.tgz", + "integrity": "sha512-VQAadSubZIhNpH46IR3yWO4kZZjMxN1opDrzePLdVKAZ+DFjkGD/rf4v1jap744uPVU6yjL/smZbRIIJTOUnKQ==", + "dev": true, + "requires": { + "@webassemblyjs/wast-printer": "1.8.5" + } + }, + "@webassemblyjs/helper-fsm": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-fsm/-/helper-fsm-1.8.5.tgz", + "integrity": "sha512-kRuX/saORcg8se/ft6Q2UbRpZwP4y7YrWsLXPbbmtepKr22i8Z4O3V5QE9DbZK908dh5Xya4Un57SDIKwB9eow==", + "dev": true + }, + "@webassemblyjs/helper-module-context": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-module-context/-/helper-module-context-1.8.5.tgz", + "integrity": "sha512-/O1B236mN7UNEU4t9X7Pj38i4VoU8CcMHyy3l2cV/kIF4U5KoHXDVqcDuOs1ltkac90IM4vZdHc52t1x8Yfs3g==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "mamacro": "^0.0.3" + } + }, + "@webassemblyjs/helper-wasm-bytecode": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.8.5.tgz", + "integrity": "sha512-Cu4YMYG3Ddl72CbmpjU/wbP6SACcOPVbHN1dI4VJNJVgFwaKf1ppeFJrwydOG3NDHxVGuCfPlLZNyEdIYlQ6QQ==", + "dev": true + }, + "@webassemblyjs/helper-wasm-section": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.8.5.tgz", + "integrity": "sha512-VV083zwR+VTrIWWtgIUpqfvVdK4ff38loRmrdDBgBT8ADXYsEZ5mPQ4Nde90N3UYatHdYoDIFb7oHzMncI02tA==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-buffer": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/wasm-gen": "1.8.5" + } + }, + "@webassemblyjs/ieee754": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.8.5.tgz", + "integrity": "sha512-aaCvQYrvKbY/n6wKHb/ylAJr27GglahUO89CcGXMItrOBqRarUMxWLJgxm9PJNuKULwN5n1csT9bYoMeZOGF3g==", + "dev": true, + "requires": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "@webassemblyjs/leb128": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.8.5.tgz", + "integrity": "sha512-plYUuUwleLIziknvlP8VpTgO4kqNaH57Y3JnNa6DLpu/sGcP6hbVdfdX5aHAV716pQBKrfuU26BJK29qY37J7A==", + "dev": true, + "requires": { + "@xtuc/long": "4.2.2" + } + }, + "@webassemblyjs/utf8": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.8.5.tgz", + "integrity": "sha512-U7zgftmQriw37tfD934UNInokz6yTmn29inT2cAetAsaU9YeVCveWEwhKL1Mg4yS7q//NGdzy79nlXh3bT8Kjw==", + "dev": true + }, + "@webassemblyjs/wasm-edit": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.8.5.tgz", + "integrity": "sha512-A41EMy8MWw5yvqj7MQzkDjU29K7UJq1VrX2vWLzfpRHt3ISftOXqrtojn7nlPsZ9Ijhp5NwuODuycSvfAO/26Q==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-buffer": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/helper-wasm-section": "1.8.5", + "@webassemblyjs/wasm-gen": "1.8.5", + "@webassemblyjs/wasm-opt": "1.8.5", + "@webassemblyjs/wasm-parser": "1.8.5", + "@webassemblyjs/wast-printer": "1.8.5" + } + }, + "@webassemblyjs/wasm-gen": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.8.5.tgz", + "integrity": "sha512-BCZBT0LURC0CXDzj5FXSc2FPTsxwp3nWcqXQdOZE4U7h7i8FqtFK5Egia6f9raQLpEKT1VL7zr4r3+QX6zArWg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/ieee754": "1.8.5", + "@webassemblyjs/leb128": "1.8.5", + "@webassemblyjs/utf8": "1.8.5" + } + }, + "@webassemblyjs/wasm-opt": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.8.5.tgz", + "integrity": "sha512-HKo2mO/Uh9A6ojzu7cjslGaHaUU14LdLbGEKqTR7PBKwT6LdPtLLh9fPY33rmr5wcOMrsWDbbdCHq4hQUdd37Q==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-buffer": "1.8.5", + "@webassemblyjs/wasm-gen": "1.8.5", + "@webassemblyjs/wasm-parser": "1.8.5" + } + }, + "@webassemblyjs/wasm-parser": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.8.5.tgz", + "integrity": "sha512-pi0SYE9T6tfcMkthwcgCpL0cM9nRYr6/6fjgDtL6q/ZqKHdMWvxitRi5JcZ7RI4SNJJYnYNaWy5UUrHQy998lw==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-api-error": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/ieee754": "1.8.5", + "@webassemblyjs/leb128": "1.8.5", + "@webassemblyjs/utf8": "1.8.5" + } + }, + "@webassemblyjs/wast-parser": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-parser/-/wast-parser-1.8.5.tgz", + "integrity": "sha512-daXC1FyKWHF1i11obK086QRlsMsY4+tIOKgBqI1lxAnkp9xe9YMcgOxm9kLe+ttjs5aWV2KKE1TWJCN57/Btsg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/floating-point-hex-parser": "1.8.5", + "@webassemblyjs/helper-api-error": "1.8.5", + "@webassemblyjs/helper-code-frame": "1.8.5", + "@webassemblyjs/helper-fsm": "1.8.5", + "@xtuc/long": "4.2.2" + } + }, + "@webassemblyjs/wast-printer": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.8.5.tgz", + "integrity": "sha512-w0U0pD4EhlnvRyeJzBqaVSJAo9w/ce7/WPogeXLzGkO6hzhr4GnQIZ4W4uUt5b9ooAaXPtnXlj0gzsXEOUNYMg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/wast-parser": "1.8.5", + "@xtuc/long": "4.2.2" + } + }, + "@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "dev": true + }, + "@xtuc/long": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true + }, + "JSONStream": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-1.3.5.tgz", + "integrity": "sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ==", + "requires": { + "jsonparse": "^1.2.0", + "through": ">=2.2.7 <3" + } + }, + "abab": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.1.tgz", + "integrity": "sha512-1zSbbCuoIjafKZ3mblY5ikvAb0ODUbqBnFuUb7f6uLeQhhGJ0vEV4ntmtxKLT2WgXCO94E07BjunsIw1jOMPZw==", + "dev": true }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "fined": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/fined/-/fined-1.1.0.tgz", - "integrity": "sha1-s33IRLdqL15wgeiE98CuNE8VNHY=", - "dev": true, - "requires": { - "expand-tilde": "2.0.2", - "is-plain-object": "2.0.4", - "object.defaults": "1.1.0", - "object.pick": "1.3.0", - "parse-filepath": "1.0.2" - } - }, - "first-chunk-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/first-chunk-stream/-/first-chunk-stream-1.0.0.tgz", - "integrity": "sha1-Wb+1DNkF9g18OUzT2ayqtOatk04=", - "dev": true - }, - "flagged-respawn": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/flagged-respawn/-/flagged-respawn-1.0.0.tgz", - "integrity": "sha1-Tnmumy6zi/hrO7Vr8+ClaqX8q9c=", - "dev": true - }, - "flat-cache": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-1.3.0.tgz", - "integrity": "sha1-0wMLMrOBVPTjt+nHCfSQ9++XxIE=", - "requires": { - "circular-json": "0.3.3", - "del": "2.2.2", - "graceful-fs": "4.1.10", - "write": "0.2.1" - } - }, - "flatpickr": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/flatpickr/-/flatpickr-2.6.3.tgz", - "integrity": "sha1-RXNXUy3rE189pktCW/RDVzeWFWQ=" - }, - "for-in": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/for-in/-/for-in-0.1.6.tgz", - "integrity": "sha1-yfluib+tGKVFr17D7TUqHZ5bTcg=", - "dev": true - }, - "for-own": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/for-own/-/for-own-0.1.4.tgz", - "integrity": "sha1-AUm0GjkIjHUV9R6+HBOG1F+TUHI=", - "dev": true, - "requires": { - "for-in": "0.1.6" - } - }, - "foreach": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz", - "integrity": "sha1-C+4AUBiusmDQo6865ljdATbsG5k=", - "dev": true - }, - "forever-agent": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", - "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", - "dev": true - }, - "form-data": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.1.1.tgz", - "integrity": "sha1-St8DQuGnmvoehMjDIKn/yCOSofM=", - "dev": true, - "requires": { - "asynckit": "0.4.0", - "combined-stream": "1.0.5", - "mime-types": "2.1.12" - } - }, - "forwarded": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", - "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=", - "dev": true - }, - "fragment-cache": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", - "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", - "dev": true, - "requires": { - "map-cache": "0.2.2" - } - }, - "fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", - "dev": true - }, - "from": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/from/-/from-0.1.3.tgz", - "integrity": "sha1-72OsIGKsMqz3hi4NQLRLiW8i87w=", - "dev": true - }, - "fs-access": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/fs-access/-/fs-access-1.0.1.tgz", - "integrity": "sha1-1qh/JiJxzv6+wwxVNAf7mV2od3o=", - "dev": true, - "requires": { - "null-check": "1.0.0" - } - }, - "fs-extra": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz", - "integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==", - "requires": { - "graceful-fs": "4.1.10", - "jsonfile": "4.0.0", - "universalify": "0.1.1" - } - }, - "fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" - }, - "fsevents": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.1.3.tgz", - "integrity": "sha512-WIr7iDkdmdbxu/Gh6eKEZJL6KPE74/5MEsf2whTOFNxbIoIixogroLdKYqB6FDav4Wavh/lZdzzd3b2KxIXC5Q==", - "dev": true, - "optional": true, - "requires": { - "nan": "2.8.0", - "node-pre-gyp": "0.6.39" - }, - "dependencies": { "abbrev": { - "version": "1.1.0", - "bundled": true, - "dev": true, - "optional": true + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" + }, + "abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "requires": { + "event-target-shim": "^5.0.0" + } + }, + "accept-language": { + "version": "3.0.18", + "resolved": "https://registry.npmjs.org/accept-language/-/accept-language-3.0.18.tgz", + "integrity": "sha1-9QJfF79lpGaoRYOMz5jNuHfYM4Q=", + "requires": { + "bcp47": "^1.1.2", + "stable": "^0.1.6" + } + }, + "accepts": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", + "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", + "requires": { + "mime-types": "~2.1.24", + "negotiator": "0.6.2" + } + }, + "acorn": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.1.1.tgz", + "integrity": "sha512-jPTiwtOxaHNaAPg/dmrJ/beuzLRnXtB0kQPQ8JpotKJgTB6rX6c8mlf315941pyjBSaPg8NHXS9fhP4u17DpGA==", + "dev": true + }, + "acorn-dynamic-import": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/acorn-dynamic-import/-/acorn-dynamic-import-4.0.0.tgz", + "integrity": "sha512-d3OEjQV4ROpoflsnUA8HozoIR504TFxNivYEUi6uwz0IYhBkTDXGuWlNdMtybRt3nqVx/L6XqMt0FxkXuWKZhw==", + "dev": true + }, + "acorn-globals": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-4.3.4.tgz", + "integrity": "sha512-clfQEh21R+D0leSbUdWf3OcfqyaCSAQ8Ryq00bofSekfr9W8u1jyYZo6ir0xu9Gtcf7BjcHJpnbZH7JOCpP60A==", + "dev": true, + "requires": { + "acorn": "^6.0.1", + "acorn-walk": "^6.0.1" + } + }, + "acorn-jsx": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.0.1.tgz", + "integrity": "sha512-HJ7CfNHrfJLlNTzIEUTj43LNWGkqpRLxm3YjAlcD0ACydk9XynzYsCBHxut+iqt+1aBXkx9UP/w/ZqMr13XIzg==", + "dev": true + }, + "acorn-walk": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-6.2.0.tgz", + "integrity": "sha512-7evsyfH1cLOCdAzZAd43Cic04yKydNx0cF+7tiA19p1XnLLPU4dpCQOqpjqwokFe//vS0QqfqqjCS2JkiIs0cA==", + "dev": true + }, + "agent-base": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-4.3.0.tgz", + "integrity": "sha512-salcGninV0nPrwpGNn4VTXBb1SOuXQBiqbrNXoeizJsHrsL6ERFM2Ne3JUSBWRE6aeNJI2ROP/WEEIDUiDe3cg==", + "requires": { + "es6-promisify": "^5.0.0" + } }, "ajv": { - "version": "4.11.8", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "co": "4.6.0", - "json-stable-stringify": "1.0.1" - } + "version": "6.10.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.0.tgz", + "integrity": "sha512-nffhOpkymDECQyR0mnsUtoCE8RlX38G0rYP+wgLWFyZuUyuuojSSvi/+euOiQBIn63whYwYVIIH1TvE3tu4OEg==", + "requires": { + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "ajv-errors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ajv-errors/-/ajv-errors-1.0.1.tgz", + "integrity": "sha512-DCRfO/4nQ+89p/RK43i8Ezd41EqdGIU4ld7nGF8OQ14oc/we5rEntLCUa7+jrn3nn83BosfwZA0wb4pon2o8iQ==", + "dev": true + }, + "ajv-keywords": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.4.0.tgz", + "integrity": "sha512-aUjdRFISbuFOl0EIZc+9e4FfZp0bDZgAdOOf30bJmw8VM9v84SHyVyxDfbWxpGYbdZD/9XoKxfHVNmxPkhwyGw==", + "dev": true + }, + "ambi": { + "version": "2.5.0", + "resolved": "http://registry.npmjs.org/ambi/-/ambi-2.5.0.tgz", + "integrity": "sha1-fI43K+SIkRV+fOoBy2+RQ9H3QiA=", + "requires": { + "editions": "^1.1.1", + "typechecker": "^4.3.0" + }, + "dependencies": { + "typechecker": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/typechecker/-/typechecker-4.7.0.tgz", + "integrity": "sha512-4LHc1KMNJ6NDGO+dSM/yNfZQRtp8NN7psYrPHUblD62Dvkwsp3VShsbM78kOgpcmMkRTgvwdKOTjctS+uMllgQ==", + "requires": { + "editions": "^2.1.0" + }, + "dependencies": { + "editions": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/editions/-/editions-2.1.3.tgz", + "integrity": "sha512-xDZyVm0A4nLgMNWVVLJvcwMjI80ShiH/27RyLiCnW1L273TcJIA25C4pwJ33AWV01OX6UriP35Xu+lH4S7HWQw==", + "requires": { + "errlop": "^1.1.1", + "semver": "^5.6.0" + } + } + } + } + } + }, + "amdefine": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz", + "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=", + "dev": true + }, + "angular-mocks": { + "version": "1.7.8", + "resolved": "https://registry.npmjs.org/angular-mocks/-/angular-mocks-1.7.8.tgz", + "integrity": "sha512-LB13ESBT0eJrhQhfPXyLR9qm4LI9g44hyBFwUqZKEHEA4DpfxVTu0ONipiNoN0zWtmEAezA8u2gjcoaO2TStig==", + "dev": true + }, + "ansi-align": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-2.0.0.tgz", + "integrity": "sha1-w2rsy6VjuJzrVW82kPCx2eNUf38=", + "dev": true, + "requires": { + "string-width": "^2.0.0" + } + }, + "ansi-colors": { + "version": "1.1.0", + "resolved": "http://registry.npmjs.org/ansi-colors/-/ansi-colors-1.1.0.tgz", + "integrity": "sha512-SFKX67auSNoVR38N3L+nvsPjOE0bybKTYbkf5tRvushrAPQ9V75huw0ZxBkKVeRU9kqH3d6HA4xTckbwZ4ixmA==", + "dev": true, + "requires": { + "ansi-wrap": "^0.1.0" + } + }, + "ansi-cyan": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/ansi-cyan/-/ansi-cyan-0.1.1.tgz", + "integrity": "sha1-U4rlKK+JgvKK4w2G8vF0VtJgmHM=", + "dev": true, + "requires": { + "ansi-wrap": "0.1.0" + } + }, + "ansi-escapes": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==", + "dev": true + }, + "ansi-gray": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/ansi-gray/-/ansi-gray-0.1.1.tgz", + "integrity": "sha1-KWLPVOyXksSFEKPetSRDaGHvclE=", + "dev": true, + "requires": { + "ansi-wrap": "0.1.0" + } + }, + "ansi-html": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/ansi-html/-/ansi-html-0.0.7.tgz", + "integrity": "sha1-gTWEAhliqenm/QOflA0S9WynhZ4=", + "dev": true + }, + "ansi-red": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/ansi-red/-/ansi-red-0.1.1.tgz", + "integrity": "sha1-jGOPnRCAgAo1PJwoyKgcpHBdlGw=", + "dev": true, + "requires": { + "ansi-wrap": "0.1.0" + } }, "ansi-regex": { - "version": "2.1.1", - "bundled": true, - "dev": true + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "dev": true + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "ansi-wrap": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/ansi-wrap/-/ansi-wrap-0.1.0.tgz", + "integrity": "sha1-qCJQ3bABXponyoLoLqYDu/pF768=", + "dev": true + }, + "anymatch": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz", + "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==", + "dev": true, + "requires": { + "micromatch": "^3.1.4", + "normalize-path": "^2.1.1" + }, + "dependencies": { + "normalize-path": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", + "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", + "dev": true, + "requires": { + "remove-trailing-separator": "^1.0.1" + } + } + } + }, + "append-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/append-buffer/-/append-buffer-1.0.2.tgz", + "integrity": "sha1-2CIM9GYIFSXv6lBhTz3mUU36WPE=", + "dev": true, + "requires": { + "buffer-equal": "^1.0.0" + } }, "aproba": { - "version": "1.1.1", - "bundled": true, - "dev": true, - "optional": true + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz", + "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==", + "dev": true + }, + "archy": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/archy/-/archy-1.0.0.tgz", + "integrity": "sha1-+cjBN1fMHde8N5rHeyxipcKGjEA=", + "dev": true }, "are-we-there-yet": { - "version": "1.1.4", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "delegates": "1.0.0", - "readable-stream": "2.2.9" - } - }, - "asn1": { - "version": "0.2.3", - "bundled": true, - "dev": true, - "optional": true - }, - "assert-plus": { - "version": "0.2.0", - "bundled": true, - "dev": true, - "optional": true - }, - "asynckit": { - "version": "0.4.0", - "bundled": true, - "dev": true, - "optional": true - }, - "aws-sign2": { - "version": "0.6.0", - "bundled": true, - "dev": true, - "optional": true - }, - "aws4": { - "version": "1.6.0", - "bundled": true, - "dev": true, - "optional": true - }, - "balanced-match": { - "version": "0.4.2", - "bundled": true, - "dev": true - }, - "bcrypt-pbkdf": { - "version": "1.0.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "tweetnacl": "0.14.5" - } - }, - "block-stream": { - "version": "0.0.9", - "bundled": true, - "dev": true, - "requires": { - "inherits": "2.0.3" - } - }, - "boom": { - "version": "2.10.1", - "bundled": true, - "dev": true, - "requires": { - "hoek": "2.16.3" - } - }, - "brace-expansion": { - "version": "1.1.7", - "bundled": true, - "dev": true, - "requires": { - "balanced-match": "0.4.2", - "concat-map": "0.0.1" - } - }, - "buffer-shims": { - "version": "1.0.0", - "bundled": true, - "dev": true - }, - "caseless": { - "version": "0.12.0", - "bundled": true, - "dev": true, - "optional": true - }, - "co": { - "version": "4.6.0", - "bundled": true, - "dev": true, - "optional": true - }, - "code-point-at": { - "version": "1.1.0", - "bundled": true, - "dev": true - }, - "combined-stream": { - "version": "1.0.5", - "bundled": true, - "dev": true, - "requires": { - "delayed-stream": "1.0.0" - } - }, - "concat-map": { - "version": "0.0.1", - "bundled": true, - "dev": true - }, - "console-control-strings": { - "version": "1.1.0", - "bundled": true, - "dev": true - }, - "core-util-is": { - "version": "1.0.2", - "bundled": true, - "dev": true - }, - "cryptiles": { - "version": "2.0.5", - "bundled": true, - "dev": true, - "requires": { - "boom": "2.10.1" - } - }, - "dashdash": { - "version": "1.14.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "assert-plus": "1.0.0" - }, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-1.1.5.tgz", + "integrity": "sha512-5hYdAkZlcG8tOLujVDTgCT+uPX0VnpAH28gWsLfzpXYm7wP6mp5Q/gYyR7YQ0cKVJcXJnl3j2kpBan13PtQf6w==", + "dev": true, + "requires": { + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" } - } }, - "debug": { - "version": "2.6.8", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "ms": "2.0.0" - } - }, - "deep-extend": { - "version": "0.4.2", - "bundled": true, - "dev": true, - "optional": true - }, - "delayed-stream": { - "version": "1.0.0", - "bundled": true, - "dev": true - }, - "delegates": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "detect-libc": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "ecc-jsbn": { - "version": "0.1.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "jsbn": "0.1.1" - } - }, - "extend": { - "version": "3.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "extsprintf": { - "version": "1.0.2", - "bundled": true, - "dev": true - }, - "forever-agent": { - "version": "0.6.1", - "bundled": true, - "dev": true, - "optional": true - }, - "form-data": { - "version": "2.1.4", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "asynckit": "0.4.0", - "combined-stream": "1.0.5", - "mime-types": "2.1.15" - } - }, - "fs.realpath": { - "version": "1.0.0", - "bundled": true, - "dev": true - }, - "fstream": { - "version": "1.0.11", - "bundled": true, - "dev": true, - "requires": { - "graceful-fs": "4.1.11", - "inherits": "2.0.3", - "mkdirp": "0.5.1", - "rimraf": "2.6.1" - } - }, - "fstream-ignore": { - "version": "1.0.5", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "fstream": "1.0.11", - "inherits": "2.0.3", - "minimatch": "3.0.4" - } - }, - "gauge": { - "version": "2.7.4", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "aproba": "1.1.1", - "console-control-strings": "1.1.0", - "has-unicode": "2.0.1", - "object-assign": "4.1.1", - "signal-exit": "3.0.2", - "string-width": "1.0.2", - "strip-ansi": "3.0.1", - "wide-align": "1.1.2" - } - }, - "getpass": { - "version": "0.1.7", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "assert-plus": "1.0.0" - }, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - } - } - }, - "glob": { - "version": "7.1.2", - "bundled": true, - "dev": true, - "requires": { - "fs.realpath": "1.0.0", - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.4", - "once": "1.4.0", - "path-is-absolute": "1.0.1" - } - }, - "graceful-fs": { - "version": "4.1.11", - "bundled": true, - "dev": true - }, - "har-schema": { - "version": "1.0.5", - "bundled": true, - "dev": true, - "optional": true - }, - "har-validator": { - "version": "4.2.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "ajv": "4.11.8", - "har-schema": "1.0.5" - } - }, - "has-unicode": { - "version": "2.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "hawk": { - "version": "3.1.3", - "bundled": true, - "dev": true, - "requires": { - "boom": "2.10.1", - "cryptiles": "2.0.5", - "hoek": "2.16.3", - "sntp": "1.0.9" - } - }, - "hoek": { - "version": "2.16.3", - "bundled": true, - "dev": true - }, - "http-signature": { - "version": "1.1.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "assert-plus": "0.2.0", - "jsprim": "1.4.0", - "sshpk": "1.13.0" - } - }, - "inflight": { - "version": "1.0.6", - "bundled": true, - "dev": true, - "requires": { - "once": "1.4.0", - "wrappy": "1.0.2" - } - }, - "inherits": { - "version": "2.0.3", - "bundled": true, - "dev": true - }, - "ini": { - "version": "1.3.4", - "bundled": true, - "dev": true, - "optional": true - }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "requires": { - "number-is-nan": "1.0.1" - } - }, - "is-typedarray": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "isarray": { - "version": "1.0.0", - "bundled": true, - "dev": true - }, - "isstream": { - "version": "0.1.2", - "bundled": true, - "dev": true, - "optional": true - }, - "jodid25519": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "jsbn": "0.1.1" - } - }, - "jsbn": { - "version": "0.1.1", - "bundled": true, - "dev": true, - "optional": true - }, - "json-schema": { - "version": "0.2.3", - "bundled": true, - "dev": true, - "optional": true - }, - "json-stable-stringify": { - "version": "1.0.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "jsonify": "0.0.0" - } - }, - "json-stringify-safe": { - "version": "5.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "jsonify": { - "version": "0.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "jsprim": { - "version": "1.4.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "assert-plus": "1.0.0", - "extsprintf": "1.0.2", - "json-schema": "0.2.3", - "verror": "1.3.6" - }, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - } - } - }, - "mime-db": { - "version": "1.27.0", - "bundled": true, - "dev": true - }, - "mime-types": { - "version": "2.1.15", - "bundled": true, - "dev": true, - "requires": { - "mime-db": "1.27.0" - } - }, - "minimatch": { - "version": "3.0.4", - "bundled": true, - "dev": true, - "requires": { - "brace-expansion": "1.1.7" - } - }, - "minimist": { - "version": "0.0.8", - "bundled": true, - "dev": true - }, - "mkdirp": { - "version": "0.5.1", - "bundled": true, - "dev": true, - "requires": { - "minimist": "0.0.8" - } - }, - "ms": { - "version": "2.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "node-pre-gyp": { - "version": "0.6.39", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "detect-libc": "1.0.2", - "hawk": "3.1.3", - "mkdirp": "0.5.1", - "nopt": "4.0.1", - "npmlog": "4.1.0", - "rc": "1.2.1", - "request": "2.81.0", - "rimraf": "2.6.1", - "semver": "5.3.0", - "tar": "2.2.1", - "tar-pack": "3.4.0" - } - }, - "nopt": { - "version": "4.0.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "abbrev": "1.1.0", - "osenv": "0.1.4" - } - }, - "npmlog": { - "version": "4.1.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "are-we-there-yet": "1.1.4", - "console-control-strings": "1.1.0", - "gauge": "2.7.4", - "set-blocking": "2.0.0" - } - }, - "number-is-nan": { - "version": "1.0.1", - "bundled": true, - "dev": true - }, - "oauth-sign": { - "version": "0.8.2", - "bundled": true, - "dev": true, - "optional": true - }, - "object-assign": { - "version": "4.1.1", - "bundled": true, - "dev": true, - "optional": true - }, - "once": { - "version": "1.4.0", - "bundled": true, - "dev": true, - "requires": { - "wrappy": "1.0.2" - } - }, - "os-homedir": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "os-tmpdir": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "osenv": { - "version": "0.1.4", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "os-homedir": "1.0.2", - "os-tmpdir": "1.0.2" - } - }, - "path-is-absolute": { - "version": "1.0.1", - "bundled": true, - "dev": true - }, - "performance-now": { - "version": "0.2.0", - "bundled": true, - "dev": true, - "optional": true - }, - "process-nextick-args": { - "version": "1.0.7", - "bundled": true, - "dev": true - }, - "punycode": { - "version": "1.4.1", - "bundled": true, - "dev": true, - "optional": true - }, - "qs": { - "version": "6.4.0", - "bundled": true, - "dev": true, - "optional": true - }, - "rc": { - "version": "1.2.1", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "deep-extend": "0.4.2", - "ini": "1.3.4", - "minimist": "1.2.0", - "strip-json-comments": "2.0.1" - }, - "dependencies": { - "minimist": { - "version": "1.2.0", - "bundled": true, - "dev": true, - "optional": true - } - } - }, - "readable-stream": { - "version": "2.2.9", - "bundled": true, - "dev": true, - "requires": { - "buffer-shims": "1.0.0", - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "string_decoder": "1.0.1", - "util-deprecate": "1.0.2" - } - }, - "request": { - "version": "2.81.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "aws-sign2": "0.6.0", - "aws4": "1.6.0", - "caseless": "0.12.0", - "combined-stream": "1.0.5", - "extend": "3.0.1", - "forever-agent": "0.6.1", - "form-data": "2.1.4", - "har-validator": "4.2.1", - "hawk": "3.1.3", - "http-signature": "1.1.1", - "is-typedarray": "1.0.0", - "isstream": "0.1.2", - "json-stringify-safe": "5.0.1", - "mime-types": "2.1.15", - "oauth-sign": "0.8.2", - "performance-now": "0.2.0", - "qs": "6.4.0", - "safe-buffer": "5.0.1", - "stringstream": "0.0.5", - "tough-cookie": "2.3.2", - "tunnel-agent": "0.6.0", - "uuid": "3.0.1" - } - }, - "rimraf": { - "version": "2.6.1", - "bundled": true, - "dev": true, - "requires": { - "glob": "7.1.2" - } - }, - "safe-buffer": { - "version": "5.0.1", - "bundled": true, - "dev": true - }, - "semver": { - "version": "5.3.0", - "bundled": true, - "dev": true, - "optional": true - }, - "set-blocking": { - "version": "2.0.0", - "bundled": true, - "dev": true, - "optional": true - }, - "signal-exit": { - "version": "3.0.2", - "bundled": true, - "dev": true, - "optional": true - }, - "sntp": { - "version": "1.0.9", - "bundled": true, - "dev": true, - "requires": { - "hoek": "2.16.3" - } - }, - "sshpk": { - "version": "1.13.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "asn1": "0.2.3", - "assert-plus": "1.0.0", - "bcrypt-pbkdf": "1.0.1", - "dashdash": "1.14.1", - "ecc-jsbn": "0.1.1", - "getpass": "0.1.7", - "jodid25519": "1.0.2", - "jsbn": "0.1.1", - "tweetnacl": "0.14.5" - }, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "bundled": true, - "dev": true, - "optional": true - } - } - }, - "string-width": { - "version": "1.0.2", - "bundled": true, - "dev": true, - "requires": { - "code-point-at": "1.1.0", - "is-fullwidth-code-point": "1.0.0", - "strip-ansi": "3.0.1" - } - }, - "string_decoder": { - "version": "1.0.1", - "bundled": true, - "dev": true, - "requires": { - "safe-buffer": "5.0.1" - } - }, - "stringstream": { - "version": "0.0.5", - "bundled": true, - "dev": true, - "optional": true - }, - "strip-ansi": { - "version": "3.0.1", - "bundled": true, - "dev": true, - "requires": { - "ansi-regex": "2.1.1" - } - }, - "strip-json-comments": { - "version": "2.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "tar": { - "version": "2.2.1", - "bundled": true, - "dev": true, - "requires": { - "block-stream": "0.0.9", - "fstream": "1.0.11", - "inherits": "2.0.3" - } - }, - "tar-pack": { - "version": "3.4.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "debug": "2.6.8", - "fstream": "1.0.11", - "fstream-ignore": "1.0.5", - "once": "1.4.0", - "readable-stream": "2.2.9", - "rimraf": "2.6.1", - "tar": "2.2.1", - "uid-number": "0.0.6" - } - }, - "tough-cookie": { - "version": "2.3.2", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "punycode": "1.4.1" - } - }, - "tunnel-agent": { - "version": "0.6.0", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "safe-buffer": "5.0.1" - } - }, - "tweetnacl": { - "version": "0.14.5", - "bundled": true, - "dev": true, - "optional": true - }, - "uid-number": { - "version": "0.0.6", - "bundled": true, - "dev": true, - "optional": true - }, - "util-deprecate": { - "version": "1.0.2", - "bundled": true, - "dev": true - }, - "uuid": { - "version": "3.0.1", - "bundled": true, - "dev": true, - "optional": true - }, - "verror": { - "version": "1.3.6", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "extsprintf": "1.0.2" - } - }, - "wide-align": { - "version": "1.1.2", - "bundled": true, - "dev": true, - "optional": true, - "requires": { - "string-width": "1.0.2" - } - }, - "wrappy": { - "version": "1.0.2", - "bundled": true, - "dev": true - } - } - }, - "fstream": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.11.tgz", - "integrity": "sha1-XB+x8RdHcRTwYyoOtLcbPLD9MXE=", - "dev": true, - "requires": { - "graceful-fs": "4.1.10", - "inherits": "2.0.3", - "mkdirp": "0.5.1", - "rimraf": "2.5.4" - } - }, - "function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "dev": true - }, - "function-source": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/function-source/-/function-source-0.1.0.tgz", - "integrity": "sha1-2RBL8+RniLVUaMAr8bL6vPj8Ga8=", - "dev": true - }, - "functional-red-black-tree": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", - "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=" - }, - "gauge": { - "version": "2.7.4", - "resolved": "https://registry.npmjs.org/gauge/-/gauge-2.7.4.tgz", - "integrity": "sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=", - "dev": true, - "requires": { - "aproba": "1.2.0", - "console-control-strings": "1.1.0", - "has-unicode": "2.0.1", - "object-assign": "4.1.0", - "signal-exit": "3.0.1", - "string-width": "1.0.2", - "strip-ansi": "3.0.1", - "wide-align": "1.1.2" - } - }, - "gaze": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/gaze/-/gaze-1.1.2.tgz", - "integrity": "sha1-hHIkZ3rbiHDWeSV+0ziP22HkAQU=", - "dev": true, - "requires": { - "globule": "1.2.0" - } - }, - "generate-function": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.0.0.tgz", - "integrity": "sha1-aFj+fAlpt9TpCTM3ZHrHn2DfvnQ=", - "dev": true - }, - "generate-object-property": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/generate-object-property/-/generate-object-property-1.2.0.tgz", - "integrity": "sha1-nA4cQDCM6AT0eDYYuTf6iPmdUNA=", - "dev": true, - "requires": { - "is-property": "1.0.2" - } - }, - "get-caller-file": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.2.tgz", - "integrity": "sha1-9wLmMSfn4jHBYKgMFVSstw1QR+U=", - "dev": true - }, - "get-stdin": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz", - "integrity": "sha1-uWjGsKBDhDJJAui/Gl3zJXmkUP4=", - "dev": true - }, - "get-stream": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz", - "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=", - "dev": true - }, - "get-value": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", - "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", - "dev": true - }, - "getpass": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.6.tgz", - "integrity": "sha1-KD/9n8ElaECHUxHBtg6MQBhxEOY=", - "dev": true, - "requires": { - "assert-plus": "1.0.0" - }, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", - "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", - "dev": true - } - } - }, - "glob": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.1.tgz", - "integrity": "sha1-gFIR3wT6rxxjo2ADBs31reULLsg=", - "requires": { - "fs.realpath": "1.0.0", - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.3", - "once": "1.4.0", - "path-is-absolute": "1.0.1" - } - }, - "glob-base": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/glob-base/-/glob-base-0.3.0.tgz", - "integrity": "sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q=", - "dev": true, - "requires": { - "glob-parent": "2.0.0", - "is-glob": "2.0.1" - } - }, - "glob-parent": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-2.0.0.tgz", - "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", - "dev": true, - "requires": { - "is-glob": "2.0.1" - } - }, - "glob-stream": { - "version": "3.1.18", - "resolved": "https://registry.npmjs.org/glob-stream/-/glob-stream-3.1.18.tgz", - "integrity": "sha1-kXCl8St5Awb9/lmPMT+PeVT9FDs=", - "dev": true, - "requires": { - "glob": "4.5.3", - "glob2base": "0.0.12", - "minimatch": "2.0.10", - "ordered-read-streams": "0.1.0", - "through2": "0.6.5", - "unique-stream": "1.0.0" - }, - "dependencies": { - "glob": { - "version": "4.5.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-4.5.3.tgz", - "integrity": "sha1-xstz0yJsHv7wTePFbQEvAzd+4V8=", - "dev": true, - "requires": { - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "2.0.10", - "once": "1.4.0" - } - }, - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - }, - "minimatch": { - "version": "2.0.10", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.10.tgz", - "integrity": "sha1-jQh8OcazjAAbl/ynzm0OHoCvusc=", - "dev": true, - "requires": { - "brace-expansion": "1.1.6" - } - }, - "readable-stream": { - "version": "1.0.34", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", - "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "0.0.1", - "string_decoder": "0.10.31" - } - }, - "through2": { - "version": "0.6.5", - "resolved": "https://registry.npmjs.org/through2/-/through2-0.6.5.tgz", - "integrity": "sha1-QaucZ7KdVyCQcUEOHXp6lozTrUg=", - "dev": true, - "requires": { - "readable-stream": "1.0.34", - "xtend": "4.0.1" - } - } - } - }, - "glob-watcher": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/glob-watcher/-/glob-watcher-0.0.6.tgz", - "integrity": "sha1-uVtKjfdLOcgymLDAXJeLTZo7cQs=", - "dev": true, - "requires": { - "gaze": "0.5.2" - }, - "dependencies": { - "gaze": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/gaze/-/gaze-0.5.2.tgz", - "integrity": "sha1-QLcJU30k0dRXZ9takIaJ3+aaxE8=", - "dev": true, - "requires": { - "globule": "0.1.0" - } - }, - "glob": { - "version": "3.1.21", - "resolved": "https://registry.npmjs.org/glob/-/glob-3.1.21.tgz", - "integrity": "sha1-0p4KBV3qUTj00H7UDomC6DwgZs0=", - "dev": true, - "requires": { - "graceful-fs": "1.2.3", - "inherits": "1.0.2", - "minimatch": "0.2.14" - } - }, - "globule": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/globule/-/globule-0.1.0.tgz", - "integrity": "sha1-2cjt3h2nnRJaFRt5UzuXhnY0auU=", - "dev": true, - "requires": { - "glob": "3.1.21", - "lodash": "1.0.2", - "minimatch": "0.2.14" - } - }, - "graceful-fs": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-1.2.3.tgz", - "integrity": "sha1-FaSAaldUfLLS2/J/QuiajDRRs2Q=", - "dev": true - }, - "inherits": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-1.0.2.tgz", - "integrity": "sha1-ykMJ2t7mtUzAuNJH6NfHoJdb3Js=", - "dev": true - }, - "lodash": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-1.0.2.tgz", - "integrity": "sha1-j1dWDIO1n8JwvT1WG2kAQ0MOJVE=", - "dev": true - }, - "lru-cache": { - "version": "2.7.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.7.3.tgz", - "integrity": "sha1-bUUk6LlV+V1PW1iFHOId1y+06VI=", - "dev": true - }, - "minimatch": { - "version": "0.2.14", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-0.2.14.tgz", - "integrity": "sha1-x054BXT2PG+aCQ6Q775u9TpqdWo=", - "dev": true, - "requires": { - "lru-cache": "2.7.3", - "sigmund": "1.0.1" - } - } - } - }, - "glob2base": { - "version": "0.0.12", - "resolved": "https://registry.npmjs.org/glob2base/-/glob2base-0.0.12.tgz", - "integrity": "sha1-nUGbPijxLoOjYhZKJ3BVkiycDVY=", - "dev": true, - "requires": { - "find-index": "0.1.1" - } - }, - "global-modules": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", - "integrity": "sha1-bXcPDrUjrHgWTXK15xqIdyZcw+o=", - "dev": true, - "requires": { - "global-prefix": "1.0.2", - "is-windows": "1.0.1", - "resolve-dir": "1.0.1" - } - }, - "global-prefix": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-1.0.2.tgz", - "integrity": "sha1-2/dDxsFJklk8ZVVoy2btMsASLr4=", - "dev": true, - "requires": { - "expand-tilde": "2.0.2", - "homedir-polyfill": "1.0.1", - "ini": "1.3.4", - "is-windows": "1.0.1", - "which": "1.3.0" - }, - "dependencies": { - "isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", - "dev": true - }, - "which": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/which/-/which-1.3.0.tgz", - "integrity": "sha512-xcJpopdamTuY5duC/KnTTNBraPK54YwpenP4lzxU8H91GudWpFv38u0CKjclE1Wi2EH2EDz5LRcHcKbCIzqGyg==", - "dev": true, - "requires": { - "isexe": "2.0.0" - } - } - } - }, - "globals": { - "version": "11.3.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.3.0.tgz", - "integrity": "sha512-kkpcKNlmQan9Z5ZmgqKH/SMbSmjxQ7QjyNqfXVc8VJcoBV2UEg+sxQD15GQofGRh2hfpwUb70VC31DR7Rq5Hdw==" - }, - "globby": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-5.0.0.tgz", - "integrity": "sha1-69hGZ8oNuzMLmbz8aOrCvFQ3Dg0=", - "requires": { - "array-union": "1.0.2", - "arrify": "1.0.1", - "glob": "7.1.1", - "object-assign": "4.1.0", - "pify": "2.3.0", - "pinkie-promise": "2.0.1" - } - }, - "globule": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/globule/-/globule-1.2.0.tgz", - "integrity": "sha1-HcScaCLdnoovoAuiopUAboZkvQk=", - "dev": true, - "requires": { - "glob": "7.1.1", - "lodash": "4.17.4", - "minimatch": "3.0.3" - }, - "dependencies": { - "lodash": { - "version": "4.17.4", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.4.tgz", - "integrity": "sha1-eCA6TRwyiuHYbcpkYONptX9AVa4=", - "dev": true - } - } - }, - "glogg": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/glogg/-/glogg-1.0.0.tgz", - "integrity": "sha1-f+DxmfV6yQbPUS/urY+Q7kooT8U=", - "dev": true, - "requires": { - "sparkles": "1.0.0" - } - }, - "got": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/got/-/got-6.7.1.tgz", - "integrity": "sha1-JAzQV4WpoY5WHcG0S0HHY+8ejbA=", - "dev": true, - "requires": { - "create-error-class": "3.0.2", - "duplexer3": "0.1.4", - "get-stream": "3.0.0", - "is-redirect": "1.0.0", - "is-retry-allowed": "1.1.0", - "is-stream": "1.1.0", - "lowercase-keys": "1.0.0", - "safe-buffer": "5.1.1", - "timed-out": "4.0.1", - "unzip-response": "2.0.1", - "url-parse-lax": "1.0.0" - } - }, - "graceful-fs": { - "version": "4.1.10", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.10.tgz", - "integrity": "sha1-8tcgwiCS90Mih3XHXjYSYyUB8TE=" - }, - "graceful-readlink": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/graceful-readlink/-/graceful-readlink-1.0.1.tgz", - "integrity": "sha1-TK+tdrxi8C+gObL5Tpo906ORpyU=", - "dev": true - }, - "gulp": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/gulp/-/gulp-3.9.1.tgz", - "integrity": "sha1-VxzkWSjdQK9lFPxAEYZgFsE4RbQ=", - "dev": true, - "requires": { - "archy": "1.0.0", - "chalk": "1.1.3", - "deprecated": "0.0.1", - "gulp-util": "3.0.7", - "interpret": "1.0.1", - "liftoff": "2.5.0", - "minimist": "1.2.0", - "orchestrator": "0.3.8", - "pretty-hrtime": "1.0.3", - "semver": "4.3.6", - "tildify": "1.2.0", - "v8flags": "2.1.1", - "vinyl-fs": "0.3.14" - }, - "dependencies": { - "semver": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/semver/-/semver-4.3.6.tgz", - "integrity": "sha1-MAvG4OhjdPe6YQaLWx7NV/xlMto=", - "dev": true - } - } - }, - "gulp-concat": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/gulp-concat/-/gulp-concat-2.6.0.tgz", - "integrity": "sha1-WFz7EVQR80h3MTEUBWa2qBxpy5E=", - "dev": true, - "requires": { - "concat-with-sourcemaps": "1.0.4", - "gulp-util": "3.0.7", - "through2": "0.6.5" - }, - "dependencies": { - "concat-with-sourcemaps": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/concat-with-sourcemaps/-/concat-with-sourcemaps-1.0.4.tgz", - "integrity": "sha1-9Vs74q60dgGxCi1SWcz7cP0vHdY=", - "dev": true, - "requires": { - "source-map": "0.5.6" - }, - "dependencies": { - "source-map": { - "version": "0.5.6", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.6.tgz", - "integrity": "sha1-dc449SvwczxafwwRjYEzSiu19BI=", - "dev": true - } - } - }, - "gulp-util": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/gulp-util/-/gulp-util-3.0.7.tgz", - "integrity": "sha1-eJJcS4+LSQBawBoBHFV+YhiUHLs=", - "dev": true, - "requires": { - "array-differ": "1.0.0", - "array-uniq": "1.0.3", - "beeper": "1.1.0", - "chalk": "1.1.3", - "dateformat": "1.0.12", - "fancy-log": "1.2.0", - "gulplog": "1.0.0", - "has-gulplog": "0.1.0", - "lodash._reescape": "3.0.0", - "lodash._reevaluate": "3.0.0", - "lodash._reinterpolate": "3.0.0", - "lodash.template": "3.6.2", - "minimist": "1.2.0", - "multipipe": "0.1.2", - "object-assign": "3.0.0", - "replace-ext": "0.0.1", - "through2": "2.0.1", - "vinyl": "0.5.3" - }, - "dependencies": { - "array-differ": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-1.0.0.tgz", - "integrity": "sha1-7/UuN1gknTO+QCuLuOVkuytdQDE=", - "dev": true + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "requires": { + "sprintf-js": "~1.0.2" }, - "array-uniq": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", - "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=", - "dev": true - }, - "beeper": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/beeper/-/beeper-1.1.0.tgz", - "integrity": "sha1-nub8HOf1T+qs585zWIsFYDeGaiw=", - "dev": true - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "dev": true, - "requires": { - "ansi-styles": "2.2.1", - "escape-string-regexp": "1.0.5", - "has-ansi": "2.0.0", - "strip-ansi": "3.0.1", - "supports-color": "2.0.0" - }, - "dependencies": { - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", - "dev": true - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true - }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "dev": true, - "requires": { - "ansi-regex": "2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz", - "integrity": "sha1-xQYbbg74qBd15Q9dZhUb9r83EQc=", - "dev": true - } - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "dev": true, - "requires": { - "ansi-regex": "2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz", - "integrity": "sha1-xQYbbg74qBd15Q9dZhUb9r83EQc=", - "dev": true - } - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", - "dev": true - } - } - }, - "dateformat": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-1.0.12.tgz", - "integrity": "sha1-nxJLZ1lMk3/3BpMuSmQsyo27/uk=", - "dev": true, - "requires": { - "get-stdin": "4.0.1", - "meow": "3.7.0" - }, - "dependencies": { - "get-stdin": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz", - "integrity": "sha1-uWjGsKBDhDJJAui/Gl3zJXmkUP4=", - "dev": true - }, - "meow": { - "version": "3.7.0", - "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz", - "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", - "dev": true, - "requires": { - "camelcase-keys": "2.1.0", - "decamelize": "1.2.0", - "loud-rejection": "1.6.0", - "map-obj": "1.0.1", - "minimist": "1.2.0", - "normalize-package-data": "2.3.5", - "object-assign": "4.1.0", - "read-pkg-up": "1.0.1", - "redent": "1.0.0", - "trim-newlines": "1.0.0" - }, - "dependencies": { - "camelcase-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", - "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", - "dev": true, - "requires": { - "camelcase": "2.1.1", - "map-obj": "1.0.1" - }, - "dependencies": { - "camelcase": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", - "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=", - "dev": true - } - } - }, - "decamelize": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", - "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", - "dev": true - }, - "loud-rejection": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/loud-rejection/-/loud-rejection-1.6.0.tgz", - "integrity": "sha1-W0b4AUft7leIcPCG0Eghz5mOVR8=", - "dev": true, - "requires": { - "currently-unhandled": "0.4.1", - "signal-exit": "3.0.1" - }, - "dependencies": { - "currently-unhandled": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/currently-unhandled/-/currently-unhandled-0.4.1.tgz", - "integrity": "sha1-mI3zP+qxke95mmE2nddsF635V+o=", - "dev": true, - "requires": { - "array-find-index": "1.0.2" - }, - "dependencies": { - "array-find-index": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", - "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=", - "dev": true - } - } - }, - "signal-exit": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.1.tgz", - "integrity": "sha1-WkyISZK2OnrNm623iUw+6c/MrYE=", - "dev": true - } - } - }, - "map-obj": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", - "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=", - "dev": true - }, - "normalize-package-data": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.3.5.tgz", - "integrity": "sha1-jZJPFClg4Xd+f/4XBUNjHMfLAt8=", - "dev": true, - "requires": { - "hosted-git-info": "2.1.5", - "is-builtin-module": "1.0.0", - "semver": "5.3.0", - "validate-npm-package-license": "3.0.1" - }, - "dependencies": { - "hosted-git-info": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.1.5.tgz", - "integrity": "sha1-C6gdkNouJas0ozLm7HeTbhWYEYs=", - "dev": true - }, - "is-builtin-module": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-builtin-module/-/is-builtin-module-1.0.0.tgz", - "integrity": "sha1-VAVy0096wxGfj3bDDLwbHgN6/74=", - "dev": true, - "requires": { - "builtin-modules": "1.1.1" - }, - "dependencies": { - "builtin-modules": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", - "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", - "dev": true - } - } - }, - "semver": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz", - "integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8=", - "dev": true - }, - "validate-npm-package-license": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.1.tgz", - "integrity": "sha1-KAS6vnEq0zeUWaz74kdGqywwP7w=", - "dev": true, - "requires": { - "spdx-correct": "1.0.2", - "spdx-expression-parse": "1.0.4" - }, - "dependencies": { - "spdx-correct": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-1.0.2.tgz", - "integrity": "sha1-SzBz2TP/UfORLwOsVRlJikFQ20A=", - "dev": true, - "requires": { - "spdx-license-ids": "1.2.2" - }, - "dependencies": { - "spdx-license-ids": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-1.2.2.tgz", - "integrity": "sha1-yd96NCRZSt5r0RkA1ZZpbcBrrFc=", - "dev": true - } - } - }, - "spdx-expression-parse": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-1.0.4.tgz", - "integrity": "sha1-m98vIOH0DtRH++JzJmGR/O1RYmw=", - "dev": true - } - } - } - } - }, - "object-assign": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.0.tgz", - "integrity": "sha1-ejs9DpgGPUP0wD8uiubNUahog6A=", - "dev": true - }, - "read-pkg-up": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-1.0.1.tgz", - "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", - "dev": true, - "requires": { - "find-up": "1.1.2", - "read-pkg": "1.1.0" - }, - "dependencies": { - "find-up": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", - "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", - "dev": true, - "requires": { - "path-exists": "2.1.0", - "pinkie-promise": "2.0.1" - }, - "dependencies": { - "path-exists": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", - "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", - "dev": true, - "requires": { - "pinkie-promise": "2.0.1" - } - }, - "pinkie-promise": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", - "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", - "dev": true, - "requires": { - "pinkie": "2.0.4" - }, - "dependencies": { - "pinkie": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", - "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", - "dev": true - } - } - } - } - }, - "read-pkg": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz", - "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", - "dev": true, - "requires": { - "load-json-file": "1.1.0", - "normalize-package-data": "2.3.5", - "path-type": "1.1.0" - }, - "dependencies": { - "load-json-file": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", - "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", - "dev": true, - "requires": { - "graceful-fs": "4.1.9", - "parse-json": "2.2.0", - "pify": "2.3.0", - "pinkie-promise": "2.0.1", - "strip-bom": "2.0.0" - }, - "dependencies": { - "graceful-fs": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.9.tgz", - "integrity": "sha1-uqy6N9GdEfnRRtNXi8mZWMN4fik=", - "dev": true - }, - "parse-json": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", - "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", - "dev": true, - "requires": { - "error-ex": "1.3.0" - }, - "dependencies": { - "error-ex": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.0.tgz", - "integrity": "sha1-5ntD8+gsluo6WE/+4Ln8MyXYAtk=", - "dev": true, - "requires": { - "is-arrayish": "0.2.1" - }, - "dependencies": { - "is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", - "dev": true - } - } - } - } - }, - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", - "dev": true - }, - "pinkie-promise": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", - "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", - "dev": true, - "requires": { - "pinkie": "2.0.4" - }, - "dependencies": { - "pinkie": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", - "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", - "dev": true - } - } - }, - "strip-bom": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", - "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", - "dev": true, - "requires": { - "is-utf8": "0.2.1" - }, - "dependencies": { - "is-utf8": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", - "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=", - "dev": true - } - } - } - } - }, - "path-type": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz", - "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", - "dev": true, - "requires": { - "graceful-fs": "4.1.9", - "pify": "2.3.0", - "pinkie-promise": "2.0.1" - }, - "dependencies": { - "graceful-fs": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.9.tgz", - "integrity": "sha1-uqy6N9GdEfnRRtNXi8mZWMN4fik=", - "dev": true - }, - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", - "dev": true - }, - "pinkie-promise": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", - "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", - "dev": true, - "requires": { - "pinkie": "2.0.4" - }, - "dependencies": { - "pinkie": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", - "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", - "dev": true - } - } - } - } - } - } - } - } - }, - "redent": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/redent/-/redent-1.0.0.tgz", - "integrity": "sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94=", - "dev": true, - "requires": { - "indent-string": "2.1.0", - "strip-indent": "1.0.1" - }, - "dependencies": { - "indent-string": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-2.1.0.tgz", - "integrity": "sha1-ji1INIdCEhtKghi3oTfppSBJ3IA=", - "dev": true, - "requires": { - "repeating": "2.0.1" - }, - "dependencies": { - "repeating": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", - "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", - "dev": true, - "requires": { - "is-finite": "1.0.2" - }, - "dependencies": { - "is-finite": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", - "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", - "dev": true, - "requires": { - "number-is-nan": "1.0.1" - }, - "dependencies": { - "number-is-nan": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", - "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", - "dev": true - } - } - } - } - } - } - }, - "strip-indent": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-1.0.1.tgz", - "integrity": "sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI=", - "dev": true, - "requires": { - "get-stdin": "4.0.1" - } - } - } - }, - "trim-newlines": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-1.0.0.tgz", - "integrity": "sha1-WIeWa7WCpFA6QetST301ARgVphM=", - "dev": true - } - } - } - } - }, - "fancy-log": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/fancy-log/-/fancy-log-1.2.0.tgz", - "integrity": "sha1-1aUbU+mrIsoH1VjytnrlX9tfy9g=", - "dev": true, - "requires": { - "chalk": "1.1.3", - "time-stamp": "1.0.1" - }, - "dependencies": { - "time-stamp": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/time-stamp/-/time-stamp-1.0.1.tgz", - "integrity": "sha1-n0vSNVnJNllm8zAtu6KwfGuZsVE=", - "dev": true - } - } - }, - "gulplog": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/gulplog/-/gulplog-1.0.0.tgz", - "integrity": "sha1-4oxNRdBey77YGDY86PnFkmIp/+U=", - "dev": true, - "requires": { - "glogg": "1.0.0" - }, - "dependencies": { - "glogg": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/glogg/-/glogg-1.0.0.tgz", - "integrity": "sha1-f+DxmfV6yQbPUS/urY+Q7kooT8U=", - "dev": true, - "requires": { - "sparkles": "1.0.0" - }, - "dependencies": { - "sparkles": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/sparkles/-/sparkles-1.0.0.tgz", - "integrity": "sha1-Gsu/tZJDbRC76PeFt8xvgoFQEsM=", - "dev": true - } - } - } - } - }, - "has-gulplog": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/has-gulplog/-/has-gulplog-0.1.0.tgz", - "integrity": "sha1-ZBTIKRNpfaUVkDl9r7EvIpZ4Ec4=", - "dev": true, - "requires": { - "sparkles": "1.0.0" - }, - "dependencies": { - "sparkles": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/sparkles/-/sparkles-1.0.0.tgz", - "integrity": "sha1-Gsu/tZJDbRC76PeFt8xvgoFQEsM=", - "dev": true - } - } - }, - "lodash._reescape": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._reescape/-/lodash._reescape-3.0.0.tgz", - "integrity": "sha1-Kx1vXf4HyKNVdT5fJ/rH8c3hYWo=", - "dev": true - }, - "lodash._reevaluate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._reevaluate/-/lodash._reevaluate-3.0.0.tgz", - "integrity": "sha1-WLx0xAZklTrgsSTYBpltrKQx4u0=", - "dev": true - }, - "lodash._reinterpolate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz", - "integrity": "sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=", - "dev": true - }, - "lodash.template": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-3.6.2.tgz", - "integrity": "sha1-+M3sxhaaJVvpCYrosMU9N4kx0U8=", - "dev": true, - "requires": { - "lodash._basecopy": "3.0.1", - "lodash._basetostring": "3.0.1", - "lodash._basevalues": "3.0.0", - "lodash._isiterateecall": "3.0.9", - "lodash._reinterpolate": "3.0.0", - "lodash.escape": "3.2.0", - "lodash.keys": "3.1.2", - "lodash.restparam": "3.6.1", - "lodash.templatesettings": "3.1.1" - }, - "dependencies": { - "lodash._basecopy": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz", - "integrity": "sha1-jaDmqHbPNEwK2KVIghEd08XHyjY=", - "dev": true - }, - "lodash._basetostring": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash._basetostring/-/lodash._basetostring-3.0.1.tgz", - "integrity": "sha1-0YYdh3+CSlL2aYMtyvPuFVZqB9U=", - "dev": true - }, - "lodash._basevalues": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._basevalues/-/lodash._basevalues-3.0.0.tgz", - "integrity": "sha1-W3dXYoAr3j0yl1A+JjAIIP32Ybc=", - "dev": true - }, - "lodash._isiterateecall": { - "version": "3.0.9", - "resolved": "https://registry.npmjs.org/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz", - "integrity": "sha1-UgOte6Ql+uhCRg5pbbnPPmqsBXw=", - "dev": true - }, - "lodash.escape": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/lodash.escape/-/lodash.escape-3.2.0.tgz", - "integrity": "sha1-mV7g3BjBtIzJLv+ucaEKq1tIdpg=", - "dev": true, - "requires": { - "lodash._root": "3.0.1" - }, - "dependencies": { - "lodash._root": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash._root/-/lodash._root-3.0.1.tgz", - "integrity": "sha1-+6HEUkwZ7ppfgTa0YJ8BfPTe1pI=", - "dev": true - } - } - }, - "lodash.keys": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-3.1.2.tgz", - "integrity": "sha1-TbwEcrFWvlCgsoaFXRvQsMZWCYo=", - "dev": true, - "requires": { - "lodash._getnative": "3.9.1", - "lodash.isarguments": "3.1.0", - "lodash.isarray": "3.0.4" - }, - "dependencies": { - "lodash._getnative": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/lodash._getnative/-/lodash._getnative-3.9.1.tgz", - "integrity": "sha1-VwvH3t5G1hzc3mh9ZdPuy6o6r/U=", - "dev": true - }, - "lodash.isarguments": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", - "integrity": "sha1-L1c9hcaiQon/AGY7SRwdM4/zRYo=", - "dev": true - }, - "lodash.isarray": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/lodash.isarray/-/lodash.isarray-3.0.4.tgz", - "integrity": "sha1-eeTriMNqgSKvhvhEqpvNhRtfu1U=", - "dev": true - } - } - }, - "lodash.restparam": { - "version": "3.6.1", - "resolved": "https://registry.npmjs.org/lodash.restparam/-/lodash.restparam-3.6.1.tgz", - "integrity": "sha1-k2pOMJ7zMKdkXtQUWYbIWuWyCAU=", - "dev": true - }, - "lodash.templatesettings": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/lodash.templatesettings/-/lodash.templatesettings-3.1.1.tgz", - "integrity": "sha1-+zB4RHU7Zrnxr6VOJix0UwfbqOU=", - "dev": true, - "requires": { - "lodash._reinterpolate": "3.0.0", - "lodash.escape": "3.2.0" - } - } - } - }, - "minimist": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", - "dev": true - }, - "multipipe": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/multipipe/-/multipipe-0.1.2.tgz", - "integrity": "sha1-Ko8t33Du1WTf8tV/HhoTfZ8FB4s=", - "dev": true, - "requires": { - "duplexer2": "0.0.2" - }, - "dependencies": { - "duplexer2": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.0.2.tgz", - "integrity": "sha1-xhTc9n4vsUmVqRcR5aYX6KYKMds=", - "dev": true, - "requires": { - "readable-stream": "1.1.14" - }, - "dependencies": { - "readable-stream": { - "version": "1.1.14", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", - "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "0.0.1", - "string_decoder": "0.10.31" - }, - "dependencies": { - "core-util-is": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", - "dev": true - }, - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", - "dev": true - }, - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - }, - "string_decoder": { - "version": "0.10.31", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", - "dev": true - } - } - } - } - } - } - }, - "object-assign": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz", - "integrity": "sha1-m+3VygiXlJvKR+f/QIBi1Un1h/I=", - "dev": true - }, - "replace-ext": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-0.0.1.tgz", - "integrity": "sha1-KbvZIHinOfC8zitO5B6DeVNSKSQ=", - "dev": true - }, - "through2": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.1.tgz", - "integrity": "sha1-OE51MU1J8y3hLuu4E2uOtrXVnak=", - "dev": true, - "requires": { - "readable-stream": "2.0.6", - "xtend": "4.0.1" - }, - "dependencies": { - "readable-stream": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.0.6.tgz", - "integrity": "sha1-j5A0HmilPMySh4jaz80Rs265t44=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "string_decoder": "0.10.31", - "util-deprecate": "1.0.2" - }, - "dependencies": { - "core-util-is": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", - "dev": true - }, - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", - "dev": true - }, - "isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", - "dev": true - }, - "process-nextick-args": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz", - "integrity": "sha1-FQ4gt1ZZCtP5EJPyWk8q2L/zC6M=", - "dev": true - }, - "string_decoder": { - "version": "0.10.31", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", - "dev": true - }, - "util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", - "dev": true - } - } - }, - "xtend": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", - "dev": true - } - } - }, - "vinyl": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-0.5.3.tgz", - "integrity": "sha1-sEVbOPxeDPMNQyUTLkYZcMIJHN4=", - "dev": true, - "requires": { - "clone": "1.0.2", - "clone-stats": "0.0.1", - "replace-ext": "0.0.1" - }, - "dependencies": { - "clone": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.2.tgz", - "integrity": "sha1-Jgt6meux7f4kdTgXX3gyQ8sZ0Uk=", - "dev": true - }, - "clone-stats": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-0.0.1.tgz", - "integrity": "sha1-uI+UqCzzi4eR1YBG6kAprYjKmdE=", - "dev": true - } - } - } - } - }, - "through2": { - "version": "0.6.5", - "resolved": "https://registry.npmjs.org/through2/-/through2-0.6.5.tgz", - "integrity": "sha1-QaucZ7KdVyCQcUEOHXp6lozTrUg=", - "dev": true, - "requires": { - "readable-stream": "1.0.34", - "xtend": "4.0.1" - }, - "dependencies": { - "readable-stream": { - "version": "1.0.34", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", - "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "0.0.1", - "string_decoder": "0.10.31" - }, - "dependencies": { - "core-util-is": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", - "dev": true - }, - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", - "dev": true - }, - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - }, - "string_decoder": { - "version": "0.10.31", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", - "dev": true - } - } - }, - "xtend": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", - "dev": true - } - } - } - } - }, - "gulp-extend": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/gulp-extend/-/gulp-extend-0.2.0.tgz", - "integrity": "sha1-BRHbpAj5JAP5xSDAEw3oGWYLDZA=", - "dev": true, - "requires": { - "event-stream": "3.3.4", - "gulp-util": "2.2.20", - "node.extend": "1.0.10", - "through": "2.3.8" - }, - "dependencies": { - "ansi-regex": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-0.2.1.tgz", - "integrity": "sha1-DY6UaWej2BQ/k+JOKYUl/BsiNfk=", - "dev": true - }, - "ansi-styles": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-1.1.0.tgz", - "integrity": "sha1-6uy/Zs1waIJ2Cy9GkVgrj1XXp94=", - "dev": true - }, - "chalk": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-0.5.1.tgz", - "integrity": "sha1-Zjs6ZItotV0EaQ1JFnqoN4WPIXQ=", - "dev": true, - "requires": { - "ansi-styles": "1.1.0", - "escape-string-regexp": "1.0.5", - "has-ansi": "0.1.0", - "strip-ansi": "0.3.0", - "supports-color": "0.2.0" - } - }, - "gulp-util": { - "version": "2.2.20", - "resolved": "https://registry.npmjs.org/gulp-util/-/gulp-util-2.2.20.tgz", - "integrity": "sha1-1xRuVyiRC9jwR6awseVJvCLb1kw=", - "dev": true, - "requires": { - "chalk": "0.5.1", - "dateformat": "1.0.12", - "lodash._reinterpolate": "2.4.1", - "lodash.template": "2.4.1", - "minimist": "0.2.0", - "multipipe": "0.1.2", - "through2": "0.5.1", - "vinyl": "0.2.3" - } - }, - "has-ansi": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-0.1.0.tgz", - "integrity": "sha1-hPJlqujA5qiKEtcCKJS3VoiUxi4=", - "dev": true, - "requires": { - "ansi-regex": "0.2.1" - } - }, - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - }, - "lodash._reinterpolate": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-2.4.1.tgz", - "integrity": "sha1-TxInqlqHEfxjL1sHofRgequLMiI=", - "dev": true - }, - "lodash.escape": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.escape/-/lodash.escape-2.4.1.tgz", - "integrity": "sha1-LOEsXghNsKV92l5dHu659dF1o7Q=", - "dev": true, - "requires": { - "lodash._escapehtmlchar": "2.4.1", - "lodash._reunescapedhtml": "2.4.1", - "lodash.keys": "2.4.1" - } - }, - "lodash.keys": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-2.4.1.tgz", - "integrity": "sha1-SN6kbfj/djKxDXBrissmWR4rNyc=", - "dev": true, - "requires": { - "lodash._isnative": "2.4.1", - "lodash._shimkeys": "2.4.1", - "lodash.isobject": "2.4.1" - } - }, - "lodash.template": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-2.4.1.tgz", - "integrity": "sha1-nmEQB+32KRKal0qzxIuBez4c8g0=", - "dev": true, - "requires": { - "lodash._escapestringchar": "2.4.1", - "lodash._reinterpolate": "2.4.1", - "lodash.defaults": "2.4.1", - "lodash.escape": "2.4.1", - "lodash.keys": "2.4.1", - "lodash.templatesettings": "2.4.1", - "lodash.values": "2.4.1" - } - }, - "lodash.templatesettings": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.templatesettings/-/lodash.templatesettings-2.4.1.tgz", - "integrity": "sha1-6nbHXRHrhtTb6JqDiTu4YZKaxpk=", - "dev": true, - "requires": { - "lodash._reinterpolate": "2.4.1", - "lodash.escape": "2.4.1" - } - }, - "minimist": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.2.0.tgz", - "integrity": "sha1-Tf/lJdriuGTGbC4jxicdev3s784=", - "dev": true - }, - "readable-stream": { - "version": "1.0.34", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", - "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "0.0.1", - "string_decoder": "0.10.31" - } - }, - "strip-ansi": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-0.3.0.tgz", - "integrity": "sha1-JfSOoiynkYfzF0pNuHWTR7sSYiA=", - "dev": true, - "requires": { - "ansi-regex": "0.2.1" - } - }, - "supports-color": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-0.2.0.tgz", - "integrity": "sha1-2S3iaU6z9nMjlz1649i1W0wiGQo=", - "dev": true - }, - "through2": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/through2/-/through2-0.5.1.tgz", - "integrity": "sha1-390BLrnHAOIyP9M084rGIqs3Lac=", - "dev": true, - "requires": { - "readable-stream": "1.0.34", - "xtend": "3.0.0" - } - }, - "vinyl": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-0.2.3.tgz", - "integrity": "sha1-vKk4IJWC7FpJrVOKAPofEl5RMlI=", - "dev": true, - "requires": { - "clone-stats": "0.0.1" - } - }, - "xtend": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-3.0.0.tgz", - "integrity": "sha1-XM50B7r2Qsunvs2laBEcST9ZZlo=", - "dev": true - } - } - }, - "gulp-install": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/gulp-install/-/gulp-install-1.1.0.tgz", - "integrity": "sha1-k4a0bLRmm0cle2rfTj6i6DySiho=", - "dev": true, - "requires": { - "dargs": "5.1.0", - "gulp-util": "3.0.7", - "lodash.groupby": "4.6.0", - "p-queue": "1.2.0", - "through2": "2.0.3", - "which": "1.3.0" - }, - "dependencies": { - "isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", - "dev": true - }, - "through2": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.3.tgz", - "integrity": "sha1-AARWmzfHx0ujnEPzzteNGtlBQL4=", - "dev": true, - "requires": { - "readable-stream": "2.1.5", - "xtend": "4.0.1" - } - }, - "which": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/which/-/which-1.3.0.tgz", - "integrity": "sha1-/wS9/AEO5UfXgL7DjhrBwnd9JTo=", - "dev": true, - "requires": { - "isexe": "2.0.0" - } - } - } - }, - "gulp-jasmine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/gulp-jasmine/-/gulp-jasmine-3.0.0.tgz", - "integrity": "sha1-ATFIbwzVmv/toY4AxkOZKpGWljs=", - "dev": true, - "requires": { - "arrify": "1.0.1", - "jasmine": "2.9.0", - "jasmine-terminal-reporter": "1.0.3", - "plugin-error": "0.1.2", - "through2": "2.0.1" - }, - "dependencies": { - "arr-diff": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-1.1.0.tgz", - "integrity": "sha1-aHwydYFjWI/vfeezb6vklesaOZo=", - "dev": true, - "requires": { - "arr-flatten": "1.0.1", - "array-slice": "0.2.3" - } - }, - "arr-union": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-2.1.0.tgz", - "integrity": "sha1-IPnqtexw9cfSFbEHexw5Fh0pLH0=", - "dev": true - }, - "extend-shallow": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-1.1.4.tgz", - "integrity": "sha1-Gda/lN/AnXa6cR85uHLSH/TdkHE=", - "dev": true, - "requires": { - "kind-of": "1.1.0" - } - }, - "kind-of": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-1.1.0.tgz", - "integrity": "sha1-FAo9LUGjbS78+pN3tiwk+ElaXEQ=", - "dev": true - }, - "plugin-error": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/plugin-error/-/plugin-error-0.1.2.tgz", - "integrity": "sha1-O5uzM1zPAPQl4HQ34ZJ2ln2kes4=", - "dev": true, - "requires": { - "ansi-cyan": "0.1.1", - "ansi-red": "0.1.1", - "arr-diff": "1.1.0", - "arr-union": "2.1.0", - "extend-shallow": "1.1.4" - } - } - } - }, - "gulp-print": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/gulp-print/-/gulp-print-2.0.1.tgz", - "integrity": "sha1-Gs7ljqyK8tPErTMp2+RldYOTxBQ=", - "dev": true, - "requires": { - "gulp-util": "3.0.7", - "map-stream": "0.0.7" - }, - "dependencies": { - "map-stream": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/map-stream/-/map-stream-0.0.7.tgz", - "integrity": "sha1-ih8HiW2CsQkmvTdEokIACfiJdKg=", - "dev": true - } - } - }, - "gulp-util": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/gulp-util/-/gulp-util-3.0.7.tgz", - "integrity": "sha1-eJJcS4+LSQBawBoBHFV+YhiUHLs=", - "dev": true, - "requires": { - "array-differ": "1.0.0", - "array-uniq": "1.0.3", - "beeper": "1.1.1", - "chalk": "1.1.3", - "dateformat": "1.0.12", - "fancy-log": "1.3.2", - "gulplog": "1.0.0", - "has-gulplog": "0.1.0", - "lodash._reescape": "3.0.0", - "lodash._reevaluate": "3.0.0", - "lodash._reinterpolate": "3.0.0", - "lodash.template": "3.6.2", - "minimist": "1.2.0", - "multipipe": "0.1.2", - "object-assign": "3.0.0", - "replace-ext": "0.0.1", - "through2": "2.0.1", - "vinyl": "0.5.3" - }, - "dependencies": { - "object-assign": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz", - "integrity": "sha1-m+3VygiXlJvKR+f/QIBi1Un1h/I=", - "dev": true - } - } - }, - "gulp-wrap": { - "version": "0.13.0", - "resolved": "https://registry.npmjs.org/gulp-wrap/-/gulp-wrap-0.13.0.tgz", - "integrity": "sha1-kPsLSieiZkM4Mv98YSLbXB7olMY=", - "dev": true, - "requires": { - "consolidate": "0.14.1", - "es6-promise": "3.3.1", - "fs-readfile-promise": "2.0.1", - "gulp-util": "3.0.7", - "js-yaml": "3.6.1", - "lodash": "4.16.4", - "node.extend": "1.1.6", - "through2": "2.0.1", - "tryit": "1.0.2", - "vinyl-bufferstream": "1.0.1" - }, - "dependencies": { - "consolidate": { - "version": "0.14.1", - "resolved": "https://registry.npmjs.org/consolidate/-/consolidate-0.14.1.tgz", - "integrity": "sha1-UG1SnvfiEWJNLkpfM334vhNu9yc=", - "dev": true, - "requires": { - "bluebird": "3.4.6" - }, - "dependencies": { - "bluebird": { - "version": "3.4.6", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.6.tgz", - "integrity": "sha1-AdqNgh2HgT0ViWfnQ9X+bGLPjA8=", - "dev": true - } - } - }, - "es6-promise": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz", - "integrity": "sha1-oIzd6EzNvzTQJ6FFG8kdS80ophM=", - "dev": true - }, - "fs-readfile-promise": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/fs-readfile-promise/-/fs-readfile-promise-2.0.1.tgz", - "integrity": "sha1-gAI4I5gfn//+AWCei+Zo9prknnA=", - "dev": true, - "requires": { - "graceful-fs": "4.1.9" - }, - "dependencies": { - "graceful-fs": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.9.tgz", - "integrity": "sha1-uqy6N9GdEfnRRtNXi8mZWMN4fik=", - "dev": true - } - } - }, - "gulp-util": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/gulp-util/-/gulp-util-3.0.7.tgz", - "integrity": "sha1-eJJcS4+LSQBawBoBHFV+YhiUHLs=", - "dev": true, - "requires": { - "array-differ": "1.0.0", - "array-uniq": "1.0.3", - "beeper": "1.1.0", - "chalk": "1.1.3", - "dateformat": "1.0.12", - "fancy-log": "1.2.0", - "gulplog": "1.0.0", - "has-gulplog": "0.1.0", - "lodash._reescape": "3.0.0", - "lodash._reevaluate": "3.0.0", - "lodash._reinterpolate": "3.0.0", - "lodash.template": "3.6.2", - "minimist": "1.2.0", - "multipipe": "0.1.2", - "object-assign": "3.0.0", - "replace-ext": "0.0.1", - "through2": "2.0.1", - "vinyl": "0.5.3" - }, - "dependencies": { - "array-differ": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-1.0.0.tgz", - "integrity": "sha1-7/UuN1gknTO+QCuLuOVkuytdQDE=", - "dev": true - }, - "array-uniq": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", - "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=", - "dev": true - }, - "beeper": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/beeper/-/beeper-1.1.0.tgz", - "integrity": "sha1-nub8HOf1T+qs585zWIsFYDeGaiw=", - "dev": true - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "dev": true, - "requires": { - "ansi-styles": "2.2.1", - "escape-string-regexp": "1.0.5", - "has-ansi": "2.0.0", - "strip-ansi": "3.0.1", - "supports-color": "2.0.0" - }, - "dependencies": { - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", - "dev": true - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true - }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "dev": true, - "requires": { - "ansi-regex": "2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz", - "integrity": "sha1-xQYbbg74qBd15Q9dZhUb9r83EQc=", - "dev": true - } - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "dev": true, - "requires": { - "ansi-regex": "2.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz", - "integrity": "sha1-xQYbbg74qBd15Q9dZhUb9r83EQc=", - "dev": true - } - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", - "dev": true - } - } - }, - "dateformat": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-1.0.12.tgz", - "integrity": "sha1-nxJLZ1lMk3/3BpMuSmQsyo27/uk=", - "dev": true, - "requires": { - "get-stdin": "4.0.1", - "meow": "3.7.0" - }, - "dependencies": { - "get-stdin": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz", - "integrity": "sha1-uWjGsKBDhDJJAui/Gl3zJXmkUP4=", - "dev": true - }, - "meow": { - "version": "3.7.0", - "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz", - "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", - "dev": true, - "requires": { - "camelcase-keys": "2.1.0", - "decamelize": "1.2.0", - "loud-rejection": "1.6.0", - "map-obj": "1.0.1", - "minimist": "1.2.0", - "normalize-package-data": "2.3.5", - "object-assign": "4.1.0", - "read-pkg-up": "1.0.1", - "redent": "1.0.0", - "trim-newlines": "1.0.0" - }, - "dependencies": { - "camelcase-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", - "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", - "dev": true, - "requires": { - "camelcase": "2.1.1", - "map-obj": "1.0.1" - }, - "dependencies": { - "camelcase": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", - "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=", - "dev": true - } - } - }, - "decamelize": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", - "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", - "dev": true - }, - "loud-rejection": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/loud-rejection/-/loud-rejection-1.6.0.tgz", - "integrity": "sha1-W0b4AUft7leIcPCG0Eghz5mOVR8=", - "dev": true, - "requires": { - "currently-unhandled": "0.4.1", - "signal-exit": "3.0.1" - }, - "dependencies": { - "currently-unhandled": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/currently-unhandled/-/currently-unhandled-0.4.1.tgz", - "integrity": "sha1-mI3zP+qxke95mmE2nddsF635V+o=", - "dev": true, - "requires": { - "array-find-index": "1.0.2" - }, - "dependencies": { - "array-find-index": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", - "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=", - "dev": true - } - } - }, - "signal-exit": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.1.tgz", - "integrity": "sha1-WkyISZK2OnrNm623iUw+6c/MrYE=", - "dev": true - } - } - }, - "map-obj": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", - "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=", - "dev": true - }, - "normalize-package-data": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.3.5.tgz", - "integrity": "sha1-jZJPFClg4Xd+f/4XBUNjHMfLAt8=", - "dev": true, - "requires": { - "hosted-git-info": "2.1.5", - "is-builtin-module": "1.0.0", - "semver": "5.3.0", - "validate-npm-package-license": "3.0.1" - }, - "dependencies": { - "hosted-git-info": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.1.5.tgz", - "integrity": "sha1-C6gdkNouJas0ozLm7HeTbhWYEYs=", - "dev": true - }, - "is-builtin-module": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-builtin-module/-/is-builtin-module-1.0.0.tgz", - "integrity": "sha1-VAVy0096wxGfj3bDDLwbHgN6/74=", - "dev": true, - "requires": { - "builtin-modules": "1.1.1" - }, - "dependencies": { - "builtin-modules": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", - "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", - "dev": true - } - } - }, - "semver": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz", - "integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8=", - "dev": true - }, - "validate-npm-package-license": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.1.tgz", - "integrity": "sha1-KAS6vnEq0zeUWaz74kdGqywwP7w=", - "dev": true, - "requires": { - "spdx-correct": "1.0.2", - "spdx-expression-parse": "1.0.4" - }, - "dependencies": { - "spdx-correct": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-1.0.2.tgz", - "integrity": "sha1-SzBz2TP/UfORLwOsVRlJikFQ20A=", - "dev": true, - "requires": { - "spdx-license-ids": "1.2.2" - }, - "dependencies": { - "spdx-license-ids": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-1.2.2.tgz", - "integrity": "sha1-yd96NCRZSt5r0RkA1ZZpbcBrrFc=", - "dev": true - } - } - }, - "spdx-expression-parse": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-1.0.4.tgz", - "integrity": "sha1-m98vIOH0DtRH++JzJmGR/O1RYmw=", - "dev": true - } - } - } - } - }, - "object-assign": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.0.tgz", - "integrity": "sha1-ejs9DpgGPUP0wD8uiubNUahog6A=", - "dev": true - }, - "read-pkg-up": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-1.0.1.tgz", - "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", - "dev": true, - "requires": { - "find-up": "1.1.2", - "read-pkg": "1.1.0" - }, - "dependencies": { - "find-up": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", - "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", - "dev": true, - "requires": { - "path-exists": "2.1.0", - "pinkie-promise": "2.0.1" - }, - "dependencies": { - "path-exists": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", - "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", - "dev": true, - "requires": { - "pinkie-promise": "2.0.1" - } - }, - "pinkie-promise": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", - "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", - "dev": true, - "requires": { - "pinkie": "2.0.4" - }, - "dependencies": { - "pinkie": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", - "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", - "dev": true - } - } - } - } - }, - "read-pkg": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz", - "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", - "dev": true, - "requires": { - "load-json-file": "1.1.0", - "normalize-package-data": "2.3.5", - "path-type": "1.1.0" - }, - "dependencies": { - "load-json-file": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", - "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", - "dev": true, - "requires": { - "graceful-fs": "4.1.9", - "parse-json": "2.2.0", - "pify": "2.3.0", - "pinkie-promise": "2.0.1", - "strip-bom": "2.0.0" - }, - "dependencies": { - "graceful-fs": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.9.tgz", - "integrity": "sha1-uqy6N9GdEfnRRtNXi8mZWMN4fik=", - "dev": true - }, - "parse-json": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", - "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", - "dev": true, - "requires": { - "error-ex": "1.3.0" - }, - "dependencies": { - "error-ex": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.0.tgz", - "integrity": "sha1-5ntD8+gsluo6WE/+4Ln8MyXYAtk=", - "dev": true, - "requires": { - "is-arrayish": "0.2.1" - }, - "dependencies": { - "is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", - "dev": true - } - } - } - } - }, - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", - "dev": true - }, - "pinkie-promise": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", - "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", - "dev": true, - "requires": { - "pinkie": "2.0.4" - }, - "dependencies": { - "pinkie": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", - "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", - "dev": true - } - } - }, - "strip-bom": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", - "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", - "dev": true, - "requires": { - "is-utf8": "0.2.1" - }, - "dependencies": { - "is-utf8": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", - "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=", - "dev": true - } - } - } - } - }, - "path-type": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz", - "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", - "dev": true, - "requires": { - "graceful-fs": "4.1.9", - "pify": "2.3.0", - "pinkie-promise": "2.0.1" - }, - "dependencies": { - "graceful-fs": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.9.tgz", - "integrity": "sha1-uqy6N9GdEfnRRtNXi8mZWMN4fik=", - "dev": true - }, - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", - "dev": true - }, - "pinkie-promise": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", - "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", - "dev": true, - "requires": { - "pinkie": "2.0.4" - }, - "dependencies": { - "pinkie": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", - "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", - "dev": true - } - } - } - } - } - } - } - } - }, - "redent": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/redent/-/redent-1.0.0.tgz", - "integrity": "sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94=", - "dev": true, - "requires": { - "indent-string": "2.1.0", - "strip-indent": "1.0.1" - }, - "dependencies": { - "indent-string": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-2.1.0.tgz", - "integrity": "sha1-ji1INIdCEhtKghi3oTfppSBJ3IA=", - "dev": true, - "requires": { - "repeating": "2.0.1" - }, - "dependencies": { - "repeating": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", - "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", - "dev": true, - "requires": { - "is-finite": "1.0.2" - }, - "dependencies": { - "is-finite": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", - "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", - "dev": true, - "requires": { - "number-is-nan": "1.0.1" - }, - "dependencies": { - "number-is-nan": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", - "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", - "dev": true - } - } - } - } - } - } - }, - "strip-indent": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-1.0.1.tgz", - "integrity": "sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI=", - "dev": true, - "requires": { - "get-stdin": "4.0.1" - } - } - } - }, - "trim-newlines": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-1.0.0.tgz", - "integrity": "sha1-WIeWa7WCpFA6QetST301ARgVphM=", - "dev": true - } - } - } - } - }, - "fancy-log": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/fancy-log/-/fancy-log-1.2.0.tgz", - "integrity": "sha1-1aUbU+mrIsoH1VjytnrlX9tfy9g=", - "dev": true, - "requires": { - "chalk": "1.1.3", - "time-stamp": "1.0.1" - }, - "dependencies": { - "time-stamp": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/time-stamp/-/time-stamp-1.0.1.tgz", - "integrity": "sha1-n0vSNVnJNllm8zAtu6KwfGuZsVE=", - "dev": true - } - } - }, - "gulplog": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/gulplog/-/gulplog-1.0.0.tgz", - "integrity": "sha1-4oxNRdBey77YGDY86PnFkmIp/+U=", - "dev": true, - "requires": { - "glogg": "1.0.0" - }, - "dependencies": { - "glogg": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/glogg/-/glogg-1.0.0.tgz", - "integrity": "sha1-f+DxmfV6yQbPUS/urY+Q7kooT8U=", - "dev": true, - "requires": { - "sparkles": "1.0.0" - }, - "dependencies": { - "sparkles": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/sparkles/-/sparkles-1.0.0.tgz", - "integrity": "sha1-Gsu/tZJDbRC76PeFt8xvgoFQEsM=", - "dev": true - } - } - } - } - }, - "has-gulplog": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/has-gulplog/-/has-gulplog-0.1.0.tgz", - "integrity": "sha1-ZBTIKRNpfaUVkDl9r7EvIpZ4Ec4=", - "dev": true, - "requires": { - "sparkles": "1.0.0" - }, - "dependencies": { - "sparkles": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/sparkles/-/sparkles-1.0.0.tgz", - "integrity": "sha1-Gsu/tZJDbRC76PeFt8xvgoFQEsM=", - "dev": true - } - } - }, - "lodash._reescape": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._reescape/-/lodash._reescape-3.0.0.tgz", - "integrity": "sha1-Kx1vXf4HyKNVdT5fJ/rH8c3hYWo=", - "dev": true - }, - "lodash._reevaluate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._reevaluate/-/lodash._reevaluate-3.0.0.tgz", - "integrity": "sha1-WLx0xAZklTrgsSTYBpltrKQx4u0=", - "dev": true - }, - "lodash._reinterpolate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz", - "integrity": "sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=", - "dev": true - }, - "lodash.template": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-3.6.2.tgz", - "integrity": "sha1-+M3sxhaaJVvpCYrosMU9N4kx0U8=", - "dev": true, - "requires": { - "lodash._basecopy": "3.0.1", - "lodash._basetostring": "3.0.1", - "lodash._basevalues": "3.0.0", - "lodash._isiterateecall": "3.0.9", - "lodash._reinterpolate": "3.0.0", - "lodash.escape": "3.2.0", - "lodash.keys": "3.1.2", - "lodash.restparam": "3.6.1", - "lodash.templatesettings": "3.1.1" - }, - "dependencies": { - "lodash._basecopy": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz", - "integrity": "sha1-jaDmqHbPNEwK2KVIghEd08XHyjY=", - "dev": true - }, - "lodash._basetostring": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash._basetostring/-/lodash._basetostring-3.0.1.tgz", - "integrity": "sha1-0YYdh3+CSlL2aYMtyvPuFVZqB9U=", - "dev": true - }, - "lodash._basevalues": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._basevalues/-/lodash._basevalues-3.0.0.tgz", - "integrity": "sha1-W3dXYoAr3j0yl1A+JjAIIP32Ybc=", - "dev": true - }, - "lodash._isiterateecall": { - "version": "3.0.9", - "resolved": "https://registry.npmjs.org/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz", - "integrity": "sha1-UgOte6Ql+uhCRg5pbbnPPmqsBXw=", - "dev": true - }, - "lodash.escape": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/lodash.escape/-/lodash.escape-3.2.0.tgz", - "integrity": "sha1-mV7g3BjBtIzJLv+ucaEKq1tIdpg=", - "dev": true, - "requires": { - "lodash._root": "3.0.1" - }, - "dependencies": { - "lodash._root": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash._root/-/lodash._root-3.0.1.tgz", - "integrity": "sha1-+6HEUkwZ7ppfgTa0YJ8BfPTe1pI=", - "dev": true - } - } - }, - "lodash.keys": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-3.1.2.tgz", - "integrity": "sha1-TbwEcrFWvlCgsoaFXRvQsMZWCYo=", - "dev": true, - "requires": { - "lodash._getnative": "3.9.1", - "lodash.isarguments": "3.1.0", - "lodash.isarray": "3.0.4" - }, - "dependencies": { - "lodash._getnative": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/lodash._getnative/-/lodash._getnative-3.9.1.tgz", - "integrity": "sha1-VwvH3t5G1hzc3mh9ZdPuy6o6r/U=", - "dev": true - }, - "lodash.isarguments": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", - "integrity": "sha1-L1c9hcaiQon/AGY7SRwdM4/zRYo=", - "dev": true - }, - "lodash.isarray": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/lodash.isarray/-/lodash.isarray-3.0.4.tgz", - "integrity": "sha1-eeTriMNqgSKvhvhEqpvNhRtfu1U=", - "dev": true - } - } - }, - "lodash.restparam": { - "version": "3.6.1", - "resolved": "https://registry.npmjs.org/lodash.restparam/-/lodash.restparam-3.6.1.tgz", - "integrity": "sha1-k2pOMJ7zMKdkXtQUWYbIWuWyCAU=", - "dev": true - }, - "lodash.templatesettings": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/lodash.templatesettings/-/lodash.templatesettings-3.1.1.tgz", - "integrity": "sha1-+zB4RHU7Zrnxr6VOJix0UwfbqOU=", - "dev": true, - "requires": { - "lodash._reinterpolate": "3.0.0", - "lodash.escape": "3.2.0" - } - } - } - }, - "minimist": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", - "dev": true - }, - "multipipe": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/multipipe/-/multipipe-0.1.2.tgz", - "integrity": "sha1-Ko8t33Du1WTf8tV/HhoTfZ8FB4s=", - "dev": true, - "requires": { - "duplexer2": "0.0.2" - }, - "dependencies": { - "duplexer2": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.0.2.tgz", - "integrity": "sha1-xhTc9n4vsUmVqRcR5aYX6KYKMds=", - "dev": true, - "requires": { - "readable-stream": "1.1.14" - }, - "dependencies": { - "readable-stream": { - "version": "1.1.14", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", - "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "0.0.1", - "string_decoder": "0.10.31" - }, - "dependencies": { - "core-util-is": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", - "dev": true - }, - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", - "dev": true - }, - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - }, - "string_decoder": { - "version": "0.10.31", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", - "dev": true - } - } - } - } - } - } - }, - "object-assign": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz", - "integrity": "sha1-m+3VygiXlJvKR+f/QIBi1Un1h/I=", - "dev": true - }, - "replace-ext": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-0.0.1.tgz", - "integrity": "sha1-KbvZIHinOfC8zitO5B6DeVNSKSQ=", - "dev": true - }, - "vinyl": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-0.5.3.tgz", - "integrity": "sha1-sEVbOPxeDPMNQyUTLkYZcMIJHN4=", - "dev": true, - "requires": { - "clone": "1.0.2", - "clone-stats": "0.0.1", - "replace-ext": "0.0.1" - }, - "dependencies": { - "clone": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.2.tgz", - "integrity": "sha1-Jgt6meux7f4kdTgXX3gyQ8sZ0Uk=", - "dev": true - }, - "clone-stats": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-0.0.1.tgz", - "integrity": "sha1-uI+UqCzzi4eR1YBG6kAprYjKmdE=", - "dev": true - } - } - } - } - }, - "js-yaml": { - "version": "3.6.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.6.1.tgz", - "integrity": "sha1-bl/mfYsgXOTSL60Ft3geja3MSzA=", - "dev": true, - "requires": { - "argparse": "1.0.9", - "esprima": "2.7.3" - }, - "dependencies": { - "argparse": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.9.tgz", - "integrity": "sha1-c9g7wmP4bpf4zE9rrhsOkKfSLIY=", - "dev": true, - "requires": { - "sprintf-js": "1.0.3" - }, - "dependencies": { + "dependencies": { "sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", - "dev": true + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" } - } - }, - "esprima": { - "version": "2.7.3", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-2.7.3.tgz", - "integrity": "sha1-luO3DVd59q1JzQMmc9HDEnZ7pYE=", - "dev": true } - } - }, - "lodash": { - "version": "4.16.4", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.16.4.tgz", - "integrity": "sha1-Ac4wa5utExnypVKGdPiCl663ASc=", - "dev": true - }, - "node.extend": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/node.extend/-/node.extend-1.1.6.tgz", - "integrity": "sha1-p7iCyC1sk6SGOlUEvV3o7IYli5Y=", - "dev": true, - "requires": { - "is": "3.1.0" - }, - "dependencies": { - "is": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/is/-/is-3.1.0.tgz", - "integrity": "sha1-KUXSBdaRy/5IM+P4oRyK6UZz8qc=", - "dev": true - } - } - }, - "through2": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.1.tgz", - "integrity": "sha1-OE51MU1J8y3hLuu4E2uOtrXVnak=", - "dev": true, - "requires": { - "readable-stream": "2.0.6", - "xtend": "4.0.1" - }, - "dependencies": { - "readable-stream": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.0.6.tgz", - "integrity": "sha1-j5A0HmilPMySh4jaz80Rs265t44=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "string_decoder": "0.10.31", - "util-deprecate": "1.0.2" - }, - "dependencies": { - "core-util-is": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", - "dev": true - }, - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", - "dev": true - }, - "isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", - "dev": true - }, - "process-nextick-args": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz", - "integrity": "sha1-FQ4gt1ZZCtP5EJPyWk8q2L/zC6M=", - "dev": true - }, - "string_decoder": { - "version": "0.10.31", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", - "dev": true - }, - "util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", - "dev": true - } - } - }, - "xtend": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", - "dev": true - } - } - }, - "tryit": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/tryit/-/tryit-1.0.2.tgz", - "integrity": "sha1-wZawBz5rHFldk8nIMIVbeswypFM=", - "dev": true - }, - "vinyl-bufferstream": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/vinyl-bufferstream/-/vinyl-bufferstream-1.0.1.tgz", - "integrity": "sha1-BTeGn1gO/6TKRay0dXnkuf5jCBo=", - "dev": true, - "requires": { - "bufferstreams": "1.0.1" - }, - "dependencies": { - "bufferstreams": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/bufferstreams/-/bufferstreams-1.0.1.tgz", - "integrity": "sha1-z7GtlWjTujz+k1upq92VLeiKqyo=", - "dev": true, - "requires": { - "readable-stream": "1.1.14" - }, - "dependencies": { - "readable-stream": { - "version": "1.1.14", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", - "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "0.0.1", - "string_decoder": "0.10.31" - }, - "dependencies": { - "core-util-is": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", - "dev": true - }, - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", - "dev": true - }, - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - }, - "string_decoder": { - "version": "0.10.31", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", - "dev": true - } - } - } - } - } - } - } - } - }, - "gulp-yaml": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/gulp-yaml/-/gulp-yaml-1.0.1.tgz", - "integrity": "sha1-AIHJMhOCe66xJzD5P97on9a+Ey0=", - "dev": true, - "requires": { - "bufferstreams": "1.1.0", - "gulp-util": "3.0.7", - "js-yaml": "3.10.0", - "through2": "2.0.1", - "xtend": "4.0.1" - } - }, - "gulplog": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/gulplog/-/gulplog-1.0.0.tgz", - "integrity": "sha1-4oxNRdBey77YGDY86PnFkmIp/+U=", - "dev": true, - "requires": { - "glogg": "1.0.0" - } - }, - "handle-thing": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/handle-thing/-/handle-thing-1.2.5.tgz", - "integrity": "sha1-/Xqtcmvxpf0W38KbL3pmAdJxOcQ=", - "dev": true - }, - "har-validator": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-2.0.6.tgz", - "integrity": "sha1-zcvAgYgmWtEZtqWnyKtw7s+10n0=", - "dev": true, - "requires": { - "chalk": "1.1.3", - "commander": "2.9.0", - "is-my-json-valid": "2.15.0", - "pinkie-promise": "2.0.1" - } - }, - "has": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.1.tgz", - "integrity": "sha1-hGFzP1OLCDfJNh45qauelwTcLyg=", - "dev": true, - "requires": { - "function-bind": "1.1.1" - } - }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "2.0.0" - } - }, - "has-binary": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/has-binary/-/has-binary-0.1.7.tgz", - "integrity": "sha1-aOYesWIQyVRaClzOBqhzkS/h5ow=", - "dev": true, - "requires": { - "isarray": "0.0.1" - }, - "dependencies": { - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - } - } - }, - "has-cors": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-cors/-/has-cors-1.1.0.tgz", - "integrity": "sha1-XkdHk/fqmEPRu5nCPu9J/xJv/zk=", - "dev": true - }, - "has-flag": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz", - "integrity": "sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=", - "dev": true - }, - "has-gulplog": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/has-gulplog/-/has-gulplog-0.1.0.tgz", - "integrity": "sha1-ZBTIKRNpfaUVkDl9r7EvIpZ4Ec4=", - "dev": true, - "requires": { - "sparkles": "1.0.0" - } - }, - "has-unicode": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", - "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=", - "dev": true - }, - "has-value": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", - "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", - "dev": true, - "requires": { - "get-value": "2.0.6", - "has-values": "1.0.0", - "isobject": "3.0.1" - }, - "dependencies": { - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - } - } - }, - "has-values": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz", - "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", - "dev": true, - "requires": { - "is-number": "3.0.0", - "kind-of": "4.0.0" - }, - "dependencies": { - "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "dev": true - }, - "is-number": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", - "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "kind-of": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", - "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "hash-base": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-2.0.2.tgz", - "integrity": "sha1-ZuodhW206KVHDK32/OI65SRO8uE=", - "dev": true, - "requires": { - "inherits": "2.0.3" - } - }, - "hash.js": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.3.tgz", - "integrity": "sha512-/UETyP0W22QILqS+6HowevwhEFJ3MBJnwTf75Qob9Wz9t0DPuisL8kW8YZMK62dHAKE1c1p+gY1TtOLY+USEHA==", - "dev": true, - "requires": { - "inherits": "2.0.3", - "minimalistic-assert": "1.0.0" - } - }, - "hawk": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/hawk/-/hawk-3.1.3.tgz", - "integrity": "sha1-B4REvXwWQLD+VA0sm3PVlnjo4cQ=", - "dev": true, - "requires": { - "boom": "2.10.1", - "cryptiles": "2.0.5", - "hoek": "2.16.3", - "sntp": "1.0.9" - } - }, - "he": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/he/-/he-1.1.0.tgz", - "integrity": "sha1-KTGdSb7sE6mx88T5sqbd5IWbsqc=", - "dev": true - }, - "hmac-drbg": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", - "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", - "dev": true, - "requires": { - "hash.js": "1.1.3", - "minimalistic-assert": "1.0.0", - "minimalistic-crypto-utils": "1.0.1" - } - }, - "hoek": { - "version": "2.16.3", - "resolved": "https://registry.npmjs.org/hoek/-/hoek-2.16.3.tgz", - "integrity": "sha1-ILt0A9POo5jpHcRxCo/xuCdKJe0=", - "dev": true - }, - "home-or-tmp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/home-or-tmp/-/home-or-tmp-2.0.0.tgz", - "integrity": "sha1-42w/LSyufXRqhX440Y1fMqeILbg=", - "dev": true, - "requires": { - "os-homedir": "1.0.2", - "os-tmpdir": "1.0.2" - } - }, - "home-path": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/home-path/-/home-path-1.0.5.tgz", - "integrity": "sha1-eIspgVsS1Tus9XVkhHbm+QQdEz8=", - "dev": true - }, - "homedir-polyfill": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.1.tgz", - "integrity": "sha1-TCu8inWJmP7r9e1oWA921GdotLw=", - "dev": true, - "requires": { - "parse-passwd": "1.0.0" - } - }, - "hosted-git-info": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.1.5.tgz", - "integrity": "sha1-C6gdkNouJas0ozLm7HeTbhWYEYs=", - "dev": true - }, - "hpack.js": { - "version": "2.1.6", - "resolved": "https://registry.npmjs.org/hpack.js/-/hpack.js-2.1.6.tgz", - "integrity": "sha1-h3dMCUnlE/QuhFdbPEVoH63ioLI=", - "dev": true, - "requires": { - "inherits": "2.0.3", - "obuf": "1.1.1", - "readable-stream": "2.1.5", - "wbuf": "1.7.2" - } - }, - "html-entities": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-1.2.1.tgz", - "integrity": "sha1-DfKTUfByEWNRXfueVUPl9u7VFi8=", - "dev": true - }, - "html-loader": { - "version": "0.4.4", - "resolved": "https://registry.npmjs.org/html-loader/-/html-loader-0.4.4.tgz", - "integrity": "sha1-8rW5rNXgNf86tf02nBPJenuwFNo=", - "dev": true, - "requires": { - "es6-templates": "0.2.3", - "fastparse": "1.1.1", - "html-minifier": "3.2.3", - "loader-utils": "0.2.16", - "object-assign": "4.1.0" - } - }, - "html-minifier": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/html-minifier/-/html-minifier-3.2.3.tgz", - "integrity": "sha1-0v9TbiTZVybDMkk9j3fYTb7YU3I=", - "dev": true, - "requires": { - "camel-case": "3.0.0", - "clean-css": "3.4.21", - "commander": "2.9.0", - "he": "1.1.0", - "ncname": "1.0.0", - "param-case": "2.1.0", - "relateurl": "0.2.7", - "uglify-js": "2.7.4" - } - }, - "htmlparser2": { - "version": "3.9.2", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.9.2.tgz", - "integrity": "sha1-G9+HrMoPP55T+k/M6w9LTLsAszg=", - "requires": { - "domelementtype": "1.3.0", - "domhandler": "2.4.1", - "domutils": "1.7.0", - "entities": "1.1.1", - "inherits": "2.0.3", - "readable-stream": "2.1.5" - } - }, - "http-deceiver": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/http-deceiver/-/http-deceiver-1.2.7.tgz", - "integrity": "sha1-+nFolEq5pRnTN8sL7HKE3D5yPYc=", - "dev": true - }, - "http-errors": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.2.tgz", - "integrity": "sha1-CgAsyFcHGSp+eUbO7cERVfYOxzY=", - "dev": true, - "requires": { - "depd": "1.1.1", - "inherits": "2.0.3", - "setprototypeof": "1.0.3", - "statuses": "1.3.1" - }, - "dependencies": { - "depd": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.1.tgz", - "integrity": "sha1-V4O04cRZ8G+lyif5kfPQbnoxA1k=", - "dev": true - }, - "setprototypeof": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.0.3.tgz", - "integrity": "sha1-ZlZ+NwQ+608E2RvWWMDL77VbjgQ=", - "dev": true - } - } - }, - "http-parser-js": { - "version": "0.4.10", - "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.4.10.tgz", - "integrity": "sha1-ksnBN0w1CF912zWexWzCV8u5P6Q=", - "dev": true - }, - "http-proxy": { - "version": "1.16.2", - "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.16.2.tgz", - "integrity": "sha1-Bt/ykpUr9k2+hHH6nfcwZtTzd0I=", - "dev": true, - "requires": { - "eventemitter3": "1.2.0", - "requires-port": "1.0.0" - } - }, - "http-proxy-middleware": { - "version": "0.17.4", - "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-0.17.4.tgz", - "integrity": "sha1-ZC6ISIUdZvCdTxJJEoRtuutBuDM=", - "dev": true, - "requires": { - "http-proxy": "1.16.2", - "is-glob": "3.1.0", - "lodash": "4.17.5", - "micromatch": "2.3.11" - }, - "dependencies": { - "is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", - "dev": true - }, - "is-glob": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", - "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", - "dev": true, - "requires": { - "is-extglob": "2.1.1" - } - }, - "lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", - "dev": true - } - } - }, - "http-signature": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.1.1.tgz", - "integrity": "sha1-33LiZwZs0Kxn+3at+OE0qPvPkb8=", - "dev": true, - "requires": { - "assert-plus": "0.2.0", - "jsprim": "1.3.1", - "sshpk": "1.10.1" - } - }, - "https-browserify": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-1.0.0.tgz", - "integrity": "sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM=", - "dev": true - }, - "iconv-lite": { - "version": "0.4.19", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.19.tgz", - "integrity": "sha1-90aPYBNfXl2tM5nAqBvpoWA6CCs=" - }, - "ieee754": { - "version": "1.1.8", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.8.tgz", - "integrity": "sha1-vjPUCsEO8ZJnAfbwii2G+/0a0+Q=", - "dev": true - }, - "ignore": { - "version": "3.3.7", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.7.tgz", - "integrity": "sha512-YGG3ejvBNHRqu0559EOxxNFihD0AjpvHlC/pdGKd3X3ofe+CoJkYazwNJYTNebqpPKN+VVQbh4ZFn1DivMNuHA==" - }, - "ignore-by-default": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", - "integrity": "sha1-SMptcvbGo68Aqa1K5odr44ieKwk=", - "dev": true - }, - "import-lazy": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-2.1.0.tgz", - "integrity": "sha1-BWmOPUXIjo1+nZLLBYTnfwlvPkM=", - "dev": true - }, - "import-local": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-1.0.0.tgz", - "integrity": "sha512-vAaZHieK9qjGo58agRBg+bhHX3hoTZU/Oa3GESWLz7t1U62fk63aHuDJJEteXoDeTCcPmUT+z38gkHPZkkmpmQ==", - "dev": true, - "requires": { - "pkg-dir": "2.0.0", - "resolve-cwd": "2.0.0" - }, - "dependencies": { - "find-up": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", - "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", - "dev": true, - "requires": { - "locate-path": "2.0.0" - } - }, - "pkg-dir": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", - "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", - "dev": true, - "requires": { - "find-up": "2.1.0" - } - } - } - }, - "imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=" - }, - "in-publish": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/in-publish/-/in-publish-2.0.0.tgz", - "integrity": "sha1-4g/146KvwmkDILbcVSaCqcf631E=", - "dev": true - }, - "indent-string": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-2.1.0.tgz", - "integrity": "sha1-ji1INIdCEhtKghi3oTfppSBJ3IA=", - "dev": true, - "requires": { - "repeating": "2.0.1" - } - }, - "indexof": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz", - "integrity": "sha1-gtwzbSMrkGIXnQWrMpOmYFn9Q10=", - "dev": true - }, - "inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "requires": { - "once": "1.4.0", - "wrappy": "1.0.2" - } - }, - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" - }, - "ini": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.4.tgz", - "integrity": "sha1-BTfLedr1m1mhpRff9wbIbsA5Fi4=", - "dev": true - }, - "inquirer": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-3.3.0.tgz", - "integrity": "sha512-h+xtnyk4EwKvFWHrUYsWErEVR+igKtLdchu+o0Z1RL7VU/jVMFbYir2bp6bAj8efFNxWqHX0dIss6fJQ+/+qeQ==", - "requires": { - "ansi-escapes": "3.0.0", - "chalk": "2.3.1", - "cli-cursor": "2.1.0", - "cli-width": "2.2.0", - "external-editor": "2.1.0", - "figures": "2.0.0", - "lodash": "4.16.6", - "mute-stream": "0.0.7", - "run-async": "2.3.0", - "rx-lite": "4.0.8", - "rx-lite-aggregates": "4.0.8", - "string-width": "2.1.1", - "strip-ansi": "4.0.0", - "through": "2.3.8" - }, - "dependencies": { - "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" - }, - "ansi-styles": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.0.tgz", - "integrity": "sha512-NnSOmMEYtVR2JVMIGTzynRkkaxtiq1xnFBcdQD/DnNCYPoEPsVJhM98BDyaoNOQIi7p4okdi3E27eN7GQbsUug==", - "requires": { - "color-convert": "1.9.0" - } - }, - "chalk": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.3.1.tgz", - "integrity": "sha512-QUU4ofkDoMIVO7hcx1iPTISs88wsO8jA92RQIm4JAwZvFGGAV2hSAA1NX7oVj2Ej2Q6NDTcRDjPTFrMCRZoJ6g==", - "requires": { - "ansi-styles": "3.2.0", - "escape-string-regexp": "1.0.5", - "supports-color": "5.2.0" - } - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" - }, - "is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=" - }, - "string-width": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", - "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", - "requires": { - "is-fullwidth-code-point": "2.0.0", - "strip-ansi": "4.0.0" - } - }, - "strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "requires": { - "ansi-regex": "3.0.0" - } - }, - "supports-color": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.2.0.tgz", - "integrity": "sha512-F39vS48la4YvTZUPVeTqsjsFNrvcMwrV3RLZINsmHo+7djCvuUzSIeXOnZ5hmjef4bajL1dNccN+tg5XAliO5Q==", - "requires": { - "has-flag": "3.0.0" - } - } - } - }, - "internal-ip": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/internal-ip/-/internal-ip-1.2.0.tgz", - "integrity": "sha1-rp+/k7mEh4eF1QqN4bNWlWBYz1w=", - "dev": true, - "requires": { - "meow": "3.7.0" - } - }, - "interpret": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.0.1.tgz", - "integrity": "sha1-1Xn7f2k7hYAElHrzn6DbSfeVYCw=", - "dev": true - }, - "invariant": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.2.tgz", - "integrity": "sha1-nh9WrArNtr8wMwbzOL47IErmA2A=", - "dev": true, - "requires": { - "loose-envify": "1.3.1" - } - }, - "invert-kv": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz", - "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=", - "dev": true - }, - "ip": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/ip/-/ip-1.1.5.tgz", - "integrity": "sha1-vd7XARQpCCjAoDnnLvJfWq7ENUo=", - "dev": true - }, - "ipaddr.js": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.5.2.tgz", - "integrity": "sha1-1LUFvemUaYfM8PxY2QEP+WB+P6A=", - "dev": true - }, - "is": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/is/-/is-0.3.0.tgz", - "integrity": "sha1-qPcd/IpuKDcWJ/JskpCYxvTV1dc=", - "dev": true - }, - "is-absolute": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-absolute/-/is-absolute-1.0.0.tgz", - "integrity": "sha1-OV4a6EsR8mrReV5zwXN45IowFXY=", - "dev": true, - "requires": { - "is-relative": "1.0.0", - "is-windows": "1.0.1" - } - }, - "is-accessor-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", - "integrity": "sha1-FpwvbT3x+ZJhgHI2XJsOofaHhlY=", - "dev": true, - "requires": { - "kind-of": "6.0.2" - }, - "dependencies": { - "kind-of": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", - "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", - "dev": true - } - } - }, - "is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", - "dev": true - }, - "is-binary-path": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz", - "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=", - "dev": true, - "requires": { - "binary-extensions": "1.8.0" - } - }, - "is-buffer": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.4.tgz", - "integrity": "sha1-z8hszV3FpS+oBIkRHGkgxFfi2Ys=", - "dev": true - }, - "is-builtin-module": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-builtin-module/-/is-builtin-module-1.0.0.tgz", - "integrity": "sha1-VAVy0096wxGfj3bDDLwbHgN6/74=", - "dev": true, - "requires": { - "builtin-modules": "1.1.1" - } - }, - "is-callable": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.3.tgz", - "integrity": "sha1-hut1OSgF3cM69xySoO7fdO52BLI=", - "dev": true - }, - "is-data-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", - "integrity": "sha1-2Eh2Mh0Oet0DmQQGq7u9NrqSaMc=", - "dev": true, - "requires": { - "kind-of": "6.0.2" - }, - "dependencies": { - "kind-of": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", - "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", - "dev": true - } - } - }, - "is-date-object": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz", - "integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=", - "dev": true - }, - "is-descriptor": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", - "integrity": "sha1-OxWXRqZmBLBPjIFSS6NlxfFNhuw=", - "dev": true, - "requires": { - "is-accessor-descriptor": "1.0.0", - "is-data-descriptor": "1.0.0", - "kind-of": "6.0.2" - }, - "dependencies": { - "kind-of": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", - "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", - "dev": true - } - } - }, - "is-dotfile": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-dotfile/-/is-dotfile-1.0.2.tgz", - "integrity": "sha1-LBMjg/ORmfjtwmjKAbmwB9IFzE0=", - "dev": true - }, - "is-equal-shallow": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz", - "integrity": "sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ=", - "dev": true, - "requires": { - "is-primitive": "2.0.0" - } - }, - "is-extendable": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", - "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", - "dev": true - }, - "is-extglob": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", - "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", - "dev": true - }, - "is-finite": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", - "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", - "dev": true, - "requires": { - "number-is-nan": "1.0.1" - } - }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", - "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", - "dev": true, - "requires": { - "number-is-nan": "1.0.1" - } - }, - "is-glob": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", - "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", - "dev": true, - "requires": { - "is-extglob": "1.0.0" - } - }, - "is-my-json-valid": { - "version": "2.15.0", - "resolved": "https://registry.npmjs.org/is-my-json-valid/-/is-my-json-valid-2.15.0.tgz", - "integrity": "sha1-k27do8o8IR/ZjzstPgjaQ/eykVs=", - "dev": true, - "requires": { - "generate-function": "2.0.0", - "generate-object-property": "1.2.0", - "jsonpointer": "4.0.0", - "xtend": "4.0.1" - } - }, - "is-npm": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-npm/-/is-npm-1.0.0.tgz", - "integrity": "sha1-8vtjpl5JBbQGyGBydloaTceTufQ=", - "dev": true - }, - "is-number": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-2.1.0.tgz", - "integrity": "sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=", - "dev": true, - "requires": { - "kind-of": "3.0.4" - } - }, - "is-obj": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", - "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=", - "dev": true - }, - "is-odd": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-odd/-/is-odd-1.0.0.tgz", - "integrity": "sha1-O4qTLrAos3dcObsJ6RdnrM22kIg=", - "dev": true, - "requires": { - "is-number": "3.0.0" - }, - "dependencies": { - "is-number": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", - "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", - "dev": true, - "requires": { - "kind-of": "3.0.4" - } - } - } - }, - "is-path-cwd": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-1.0.0.tgz", - "integrity": "sha1-0iXsIxMuie3Tj9p2dHLmLmXxEG0=" - }, - "is-path-in-cwd": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-path-in-cwd/-/is-path-in-cwd-1.0.0.tgz", - "integrity": "sha1-ZHdYK4IU1gI0YJRWcAO+ip6sBNw=", - "requires": { - "is-path-inside": "1.0.0" - } - }, - "is-path-inside": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-1.0.0.tgz", - "integrity": "sha1-/AbloWg/vaE95mev9xe7wQpI838=", - "requires": { - "path-is-inside": "1.0.2" - } - }, - "is-plain-object": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", - "integrity": "sha1-LBY7P6+xtgbZ0Xko8FwqHDjgdnc=", - "dev": true, - "requires": { - "isobject": "3.0.1" - }, - "dependencies": { - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - } - } - }, - "is-posix-bracket": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz", - "integrity": "sha1-MzTceXdDaOkvAW5vvAqI9c1ua8Q=", - "dev": true - }, - "is-primitive": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-primitive/-/is-primitive-2.0.0.tgz", - "integrity": "sha1-IHurkWOEmcB7Kt8kCkGochADRXU=", - "dev": true - }, - "is-promise": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", - "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=" - }, - "is-property": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", - "integrity": "sha1-V/4cTkhHTt1lsJkR8msc1Ald2oQ=", - "dev": true - }, - "is-redirect": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-redirect/-/is-redirect-1.0.0.tgz", - "integrity": "sha1-HQPd7VO9jbDzDCbk+V02/HyH3CQ=", - "dev": true - }, - "is-regex": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz", - "integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", - "dev": true, - "requires": { - "has": "1.0.1" - } - }, - "is-relative": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-relative/-/is-relative-1.0.0.tgz", - "integrity": "sha1-obtpNc6MXboei5dUubLcwCDiJg0=", - "dev": true, - "requires": { - "is-unc-path": "1.0.0" - } - }, - "is-resolvable": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-resolvable/-/is-resolvable-1.1.0.tgz", - "integrity": "sha512-qgDYXFSR5WvEfuS5dMj6oTMEbrrSaM0CrFk2Yiq/gXnBvD9pMa2jGXxyhGLfvhZpuMZe18CJpFxAt3CRs42NMg==" - }, - "is-retry-allowed": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-1.1.0.tgz", - "integrity": "sha1-EaBgVotnM5REAz0BJaYaINVk+zQ=", - "dev": true - }, - "is-stream": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", - "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", - "dev": true - }, - "is-symbol": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.1.tgz", - "integrity": "sha1-PMWfAAJRlLarLjjbrmaJJWtmBXI=", - "dev": true - }, - "is-typedarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", - "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", - "dev": true - }, - "is-unc-path": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-unc-path/-/is-unc-path-1.0.0.tgz", - "integrity": "sha1-1zHoiY7QkKEsNSrS6u1Qla0yLJ0=", - "dev": true, - "requires": { - "unc-path-regex": "0.1.2" - } - }, - "is-utf8": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", - "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=", - "dev": true - }, - "is-windows": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.1.tgz", - "integrity": "sha1-MQ23D3QtJZoWo2kgK1GvhCMzENk=", - "dev": true - }, - "is-wsl": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-1.1.0.tgz", - "integrity": "sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0=", - "dev": true - }, - "isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" - }, - "isbinaryfile": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-3.0.2.tgz", - "integrity": "sha1-Sj6XTsDLqQBNP8bN5yCeppNopiE=", - "dev": true - }, - "isexe": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-1.1.2.tgz", - "integrity": "sha1-NvPiLmB1CSD15yQaR2qMakInWtA=" - }, - "isobject": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", - "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", - "dev": true, - "requires": { - "isarray": "1.0.0" - } - }, - "isstream": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", - "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", - "dev": true - }, - "jasmine": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/jasmine/-/jasmine-2.9.0.tgz", - "integrity": "sha1-dlcfklyHg0CefGFTVy5aY0HPk+s=", - "dev": true, - "requires": { - "exit": "0.1.2", - "glob": "7.1.1", - "jasmine-core": "2.9.1" - } - }, - "jasmine-core": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-2.9.1.tgz", - "integrity": "sha1-trvB2OZSUNVvWIhGFwXr7uuI8i8=", - "dev": true - }, - "jasmine-spec-reporter": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/jasmine-spec-reporter/-/jasmine-spec-reporter-4.2.1.tgz", - "integrity": "sha1-HWMq7ANBZwrTJPkrqEtLMrNeniI=", - "dev": true, - "requires": { - "colors": "1.1.2" - } - }, - "jasmine-terminal-reporter": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/jasmine-terminal-reporter/-/jasmine-terminal-reporter-1.0.3.tgz", - "integrity": "sha1-iW8eyP30v2rs3UHFA+2nNH9hUms=", - "dev": true, - "requires": { - "indent-string": "2.1.0", - "pluralize": "1.2.1" - } - }, - "jodid25519": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/jodid25519/-/jodid25519-1.0.2.tgz", - "integrity": "sha1-BtSRIlUJNBlHfUJWM2BuDpB4KWc=", - "dev": true, - "optional": true, - "requires": { - "jsbn": "0.1.0" - } - }, - "js-base64": { - "version": "2.4.3", - "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-2.4.3.tgz", - "integrity": "sha512-H7ErYLM34CvDMto3GbD6xD0JLUGYXR3QTcH6B/tr4Hi/QpSThnCsIp+Sy5FRTw3B0d6py4HcNkW7nO/wdtGWEw==", - "dev": true - }, - "js-tokens": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.1.tgz", - "integrity": "sha1-COnxMkhKLEWjCQfp3E1VZ7fxFNc=", - "dev": true - }, - "js-yaml": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.10.0.tgz", - "integrity": "sha512-O2v52ffjLa9VeM43J4XocZE//WT9N0IiwDa3KSHH7Tu8CtH+1qM8SIZvnsTh6v+4yFy5KUY3BHUVwjpfAWsjIA==", - "requires": { - "argparse": "1.0.9", - "esprima": "4.0.0" - }, - "dependencies": { - "esprima": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.0.tgz", - "integrity": "sha512-oftTcaMu/EGrEIu904mWteKIv8vMuOgGYo7EhVJJN00R/EED9DCua/xxHRdYnKtcECzVg7xOWhflvJMnqcFZjw==" - } - } - }, - "jsbn": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.0.tgz", - "integrity": "sha1-ZQmH2g3XT06/WhE3eiqi0nPpff0=", - "dev": true, - "optional": true - }, - "jsesc": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz", - "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", - "dev": true - }, - "json-loader": { - "version": "0.5.7", - "resolved": "https://registry.npmjs.org/json-loader/-/json-loader-0.5.7.tgz", - "integrity": "sha512-QLPs8Dj7lnf3e3QYS1zkCo+4ZwqOiF9d/nZnYozTISxXWCfNs9yuky5rJw4/W34s7POaNlbZmQGaB5NiXCbP4w==", - "dev": true - }, - "json-schema": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", - "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=", - "dev": true - }, - "json-schema-traverse": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz", - "integrity": "sha1-NJptRMU6Ud6JtAgFxdXlm0F9M0A=" - }, - "json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=" - }, - "json-stringify-safe": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", - "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", - "dev": true - }, - "json3": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/json3/-/json3-3.3.2.tgz", - "integrity": "sha1-PAQ0dD35Pi9cQq7nsZvLSDV19OE=", - "dev": true - }, - "json5": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.0.tgz", - "integrity": "sha1-myBxWwJsvjd4/Xae3M2CLYMypbI=", - "dev": true - }, - "jsonfile": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", - "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", - "requires": { - "graceful-fs": "4.1.10" - } - }, - "jsonpointer": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonpointer/-/jsonpointer-4.0.0.tgz", - "integrity": "sha1-ZmHhYdL8RF8Z+YQwIxNDci4fy9U=", - "dev": true - }, - "jsprim": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.3.1.tgz", - "integrity": "sha1-KnJW9wQSop7jZwqspiWZTE3P8lI=", - "dev": true, - "requires": { - "extsprintf": "1.0.2", - "json-schema": "0.2.3", - "verror": "1.3.6" - } - }, - "karma": { - "version": "1.7.1", - "resolved": "https://registry.npmjs.org/karma/-/karma-1.7.1.tgz", - "integrity": "sha1-hcwI6eCiLXzpzKN8ShvoJPaisa4=", - "dev": true, - "requires": { - "bluebird": "3.5.1", - "body-parser": "1.18.2", - "chokidar": "1.6.1", - "colors": "1.1.2", - "combine-lists": "1.0.1", - "connect": "3.6.5", - "core-js": "2.4.1", - "di": "0.0.1", - "dom-serialize": "2.2.1", - "expand-braces": "0.1.2", - "glob": "7.1.1", - "graceful-fs": "4.1.10", - "http-proxy": "1.16.2", - "isbinaryfile": "3.0.2", - "lodash": "3.10.1", - "log4js": "0.6.38", - "mime": "1.3.4", - "minimatch": "3.0.3", - "optimist": "0.6.1", - "qjobs": "1.1.5", - "range-parser": "1.2.0", - "rimraf": "2.6.2", - "safe-buffer": "5.1.1", - "socket.io": "1.7.3", - "source-map": "0.5.6", - "tmp": "0.0.31", - "useragent": "2.3.0" - }, - "dependencies": { - "lodash": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.10.1.tgz", - "integrity": "sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y=", - "dev": true - }, - "rimraf": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.2.tgz", - "integrity": "sha1-LtgVDSShbqhlHm1u8PR8QVjOejY=", - "dev": true, - "requires": { - "glob": "7.1.1" - } - } - } - }, - "karma-chrome-launcher": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/karma-chrome-launcher/-/karma-chrome-launcher-2.2.0.tgz", - "integrity": "sha1-zxudBxNswY/iOTJ9JGVMPbw2is8=", - "dev": true, - "requires": { - "fs-access": "1.0.1", - "which": "1.2.11" - } - }, - "karma-firefox-launcher": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/karma-firefox-launcher/-/karma-firefox-launcher-1.1.0.tgz", - "integrity": "sha1-LEcDBFLwRTHrfRPU/HZpYwu5Mzk=", - "dev": true - }, - "karma-jasmine": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/karma-jasmine/-/karma-jasmine-1.1.1.tgz", - "integrity": "sha1-b+hA51oRYAydkehLM8RY4cRqNSk=", - "dev": true - }, - "karma-sourcemap-loader": { - "version": "0.3.7", - "resolved": "https://registry.npmjs.org/karma-sourcemap-loader/-/karma-sourcemap-loader-0.3.7.tgz", - "integrity": "sha1-kTIsd/jxPUb+0GKwQuEAnUxFBdg=", - "dev": true, - "requires": { - "graceful-fs": "4.1.10" - } - }, - "karma-webpack": { - "version": "2.0.9", - "resolved": "https://registry.npmjs.org/karma-webpack/-/karma-webpack-2.0.9.tgz", - "integrity": "sha1-YciAkffdkQY1E0wDKyZqRlr/tX8=", - "dev": true, - "requires": { - "async": "0.9.2", - "loader-utils": "0.2.16", - "lodash": "3.10.1", - "source-map": "0.5.6", - "webpack-dev-middleware": "1.12.2" - }, - "dependencies": { - "async": { - "version": "0.9.2", - "resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz", - "integrity": "sha1-rqdNXmHB+JlhO/ZL2mbUx48v0X0=", - "dev": true - }, - "lodash": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.10.1.tgz", - "integrity": "sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y=", - "dev": true - }, - "mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", - "dev": true - }, - "time-stamp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/time-stamp/-/time-stamp-2.0.0.tgz", - "integrity": "sha1-lcakRTDhW6jW9KPsuMOj+sRto1c=", - "dev": true - }, - "webpack-dev-middleware": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-1.12.2.tgz", - "integrity": "sha512-FCrqPy1yy/sN6U/SaEZcHKRXGlqU0DUaEBL45jkUYoB8foVb6wCnbIJ1HKIx+qUFTW+3JpVcCJCxZ8VATL4e+A==", - "dev": true, - "requires": { - "memory-fs": "0.4.1", - "mime": "1.6.0", - "path-is-absolute": "1.0.1", - "range-parser": "1.2.0", - "time-stamp": "2.0.0" - } - } - } - }, - "keypress": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/keypress/-/keypress-0.1.0.tgz", - "integrity": "sha1-SjGI1CkbZrT2XtuZ+AaqmuKTWSo=", - "dev": true - }, - "killable": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/killable/-/killable-1.0.0.tgz", - "integrity": "sha1-2ouEvUfeU5WHj5XWTQLyRJ/gXms=", - "dev": true - }, - "kind-of": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.0.4.tgz", - "integrity": "sha1-e47PGKThf4Jp1ztQHJ8jLJaIenQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.4" - } - }, - "klaw": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/klaw/-/klaw-1.3.1.tgz", - "integrity": "sha1-QIhDO0azsbolnXh4XY6W9zugJDk=", - "dev": true, - "requires": { - "graceful-fs": "4.1.10" - } - }, - "latest-version": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/latest-version/-/latest-version-3.1.0.tgz", - "integrity": "sha1-ogU4P+oyKzO1rjsYq+4NwvNW7hU=", - "dev": true, - "requires": { - "package-json": "4.0.1" - } - }, - "lazy-cache": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-1.0.4.tgz", - "integrity": "sha1-odePw6UEdMuAhF07O24dpJpEbo4=", - "dev": true - }, - "lcid": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz", - "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", - "dev": true, - "requires": { - "invert-kv": "1.0.0" - } - }, - "levn": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", - "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", - "requires": { - "prelude-ls": "1.1.2", - "type-check": "0.3.2" - } - }, - "liftoff": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/liftoff/-/liftoff-2.5.0.tgz", - "integrity": "sha1-IAkpG7Mc6oYbvxCnwVooyvdcMew=", - "dev": true, - "requires": { - "extend": "3.0.0", - "findup-sync": "2.0.0", - "fined": "1.1.0", - "flagged-respawn": "1.0.0", - "is-plain-object": "2.0.4", - "object.map": "1.0.1", - "rechoir": "0.6.2", - "resolve": "1.4.0" - } - }, - "load-json-file": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", - "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", - "dev": true, - "requires": { - "graceful-fs": "4.1.10", - "parse-json": "2.2.0", - "pify": "2.3.0", - "pinkie-promise": "2.0.1", - "strip-bom": "2.0.0" - } - }, - "loader-runner": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-2.3.0.tgz", - "integrity": "sha1-9IKuqC1UPgeSFwDVpG7yb9rGuKI=", - "dev": true - }, - "loader-utils": { - "version": "0.2.16", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-0.2.16.tgz", - "integrity": "sha1-8IYyBm7YKCg13/iN+1JwR2Wt7m0=", - "dev": true, - "requires": { - "big.js": "3.1.3", - "emojis-list": "2.1.0", - "json5": "0.5.0", - "object-assign": "4.1.0" - } - }, - "locate-path": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", - "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", - "dev": true, - "requires": { - "p-locate": "2.0.0", - "path-exists": "3.0.0" - }, - "dependencies": { - "path-exists": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", - "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", - "dev": true - } - } - }, - "lodash": { - "version": "4.16.6", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.16.6.tgz", - "integrity": "sha1-0iyaxmAojzhD4Wun0rXQbMon13c=" - }, - "lodash._arraycopy": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._arraycopy/-/lodash._arraycopy-3.0.0.tgz", - "integrity": "sha1-due3wfH7klRzdIeKVi7Qaj5Q9uE=", - "dev": true - }, - "lodash._arrayeach": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._arrayeach/-/lodash._arrayeach-3.0.0.tgz", - "integrity": "sha1-urFWsqkNPxu9XGU0AzSeXlkz754=", - "dev": true - }, - "lodash._baseassign": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/lodash._baseassign/-/lodash._baseassign-3.2.0.tgz", - "integrity": "sha1-jDigmVAPIVrQnlnxci/QxSv+Ck4=", - "dev": true, - "requires": { - "lodash._basecopy": "3.0.1", - "lodash.keys": "3.1.2" - } - }, - "lodash._basecopy": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz", - "integrity": "sha1-jaDmqHbPNEwK2KVIghEd08XHyjY=", - "dev": true - }, - "lodash._basefor": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/lodash._basefor/-/lodash._basefor-3.0.3.tgz", - "integrity": "sha1-dVC06SGO8J+tJDQ7YSAhx5tMIMI=", - "dev": true - }, - "lodash._basetostring": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash._basetostring/-/lodash._basetostring-3.0.1.tgz", - "integrity": "sha1-0YYdh3+CSlL2aYMtyvPuFVZqB9U=", - "dev": true - }, - "lodash._basevalues": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._basevalues/-/lodash._basevalues-3.0.0.tgz", - "integrity": "sha1-W3dXYoAr3j0yl1A+JjAIIP32Ybc=", - "dev": true - }, - "lodash._bindcallback": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash._bindcallback/-/lodash._bindcallback-3.0.1.tgz", - "integrity": "sha1-5THCdkTPi1epnhftlbNcdIeJOS4=", - "dev": true - }, - "lodash._createassigner": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/lodash._createassigner/-/lodash._createassigner-3.1.1.tgz", - "integrity": "sha1-g4pbri/aymOsIt7o4Z+k5taXCxE=", - "dev": true, - "requires": { - "lodash._bindcallback": "3.0.1", - "lodash._isiterateecall": "3.0.9", - "lodash.restparam": "3.6.1" - } - }, - "lodash._escapehtmlchar": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._escapehtmlchar/-/lodash._escapehtmlchar-2.4.1.tgz", - "integrity": "sha1-32fDu2t+jh6DGrSL+geVuSr+iZ0=", - "dev": true, - "requires": { - "lodash._htmlescapes": "2.4.1" - } - }, - "lodash._escapestringchar": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._escapestringchar/-/lodash._escapestringchar-2.4.1.tgz", - "integrity": "sha1-7P4iYYoq3lC/7qQ5N+Ud9m8O23I=", - "dev": true - }, - "lodash._getnative": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/lodash._getnative/-/lodash._getnative-3.9.1.tgz", - "integrity": "sha1-VwvH3t5G1hzc3mh9ZdPuy6o6r/U=", - "dev": true - }, - "lodash._htmlescapes": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._htmlescapes/-/lodash._htmlescapes-2.4.1.tgz", - "integrity": "sha1-MtFL8IRLbeb4tioFG09nwii2JMs=", - "dev": true - }, - "lodash._isiterateecall": { - "version": "3.0.9", - "resolved": "https://registry.npmjs.org/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz", - "integrity": "sha1-UgOte6Ql+uhCRg5pbbnPPmqsBXw=", - "dev": true - }, - "lodash._isnative": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._isnative/-/lodash._isnative-2.4.1.tgz", - "integrity": "sha1-PqZAS3hKe+g2x7V1gOHN95sUgyw=", - "dev": true - }, - "lodash._objecttypes": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._objecttypes/-/lodash._objecttypes-2.4.1.tgz", - "integrity": "sha1-fAt/admKH3ZSn4kLDNsbTf7BHBE=", - "dev": true - }, - "lodash._reescape": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._reescape/-/lodash._reescape-3.0.0.tgz", - "integrity": "sha1-Kx1vXf4HyKNVdT5fJ/rH8c3hYWo=", - "dev": true - }, - "lodash._reevaluate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._reevaluate/-/lodash._reevaluate-3.0.0.tgz", - "integrity": "sha1-WLx0xAZklTrgsSTYBpltrKQx4u0=", - "dev": true - }, - "lodash._reinterpolate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz", - "integrity": "sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=", - "dev": true - }, - "lodash._reunescapedhtml": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._reunescapedhtml/-/lodash._reunescapedhtml-2.4.1.tgz", - "integrity": "sha1-dHxPxAED6zu4oJduVx96JlnpO6c=", - "dev": true, - "requires": { - "lodash._htmlescapes": "2.4.1", - "lodash.keys": "2.4.1" - }, - "dependencies": { - "lodash.keys": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-2.4.1.tgz", - "integrity": "sha1-SN6kbfj/djKxDXBrissmWR4rNyc=", - "dev": true, - "requires": { - "lodash._isnative": "2.4.1", - "lodash._shimkeys": "2.4.1", - "lodash.isobject": "2.4.1" - } - } - } - }, - "lodash._root": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash._root/-/lodash._root-3.0.1.tgz", - "integrity": "sha1-+6HEUkwZ7ppfgTa0YJ8BfPTe1pI=", - "dev": true - }, - "lodash._shimkeys": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash._shimkeys/-/lodash._shimkeys-2.4.1.tgz", - "integrity": "sha1-bpzJZm/wgfC1psl4uD4kLmlJ0gM=", - "dev": true, - "requires": { - "lodash._objecttypes": "2.4.1" - } - }, - "lodash.assign": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/lodash.assign/-/lodash.assign-4.2.0.tgz", - "integrity": "sha1-DZnzzNem0mHRm9rrkkUAXShYCOc=", - "dev": true - }, - "lodash.clonedeep": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", - "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=", - "dev": true - }, - "lodash.defaults": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-2.4.1.tgz", - "integrity": "sha1-p+iIXwXmiFEUS24SqPNngCa8TFQ=", - "dev": true, - "requires": { - "lodash._objecttypes": "2.4.1", - "lodash.keys": "2.4.1" - }, - "dependencies": { - "lodash.keys": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-2.4.1.tgz", - "integrity": "sha1-SN6kbfj/djKxDXBrissmWR4rNyc=", - "dev": true, - "requires": { - "lodash._isnative": "2.4.1", - "lodash._shimkeys": "2.4.1", - "lodash.isobject": "2.4.1" - } - } - } - }, - "lodash.escape": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/lodash.escape/-/lodash.escape-3.2.0.tgz", - "integrity": "sha1-mV7g3BjBtIzJLv+ucaEKq1tIdpg=", - "dev": true, - "requires": { - "lodash._root": "3.0.1" - } - }, - "lodash.groupby": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/lodash.groupby/-/lodash.groupby-4.6.0.tgz", - "integrity": "sha1-Cwih3PaDl8OXhVwyOXg4Mt90A9E=", - "dev": true - }, - "lodash.isarguments": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", - "integrity": "sha1-L1c9hcaiQon/AGY7SRwdM4/zRYo=", - "dev": true - }, - "lodash.isarray": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/lodash.isarray/-/lodash.isarray-3.0.4.tgz", - "integrity": "sha1-eeTriMNqgSKvhvhEqpvNhRtfu1U=", - "dev": true - }, - "lodash.isobject": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.isobject/-/lodash.isobject-2.4.1.tgz", - "integrity": "sha1-Wi5H/mmVPx7mMafrof5k0tBlWPU=", - "dev": true, - "requires": { - "lodash._objecttypes": "2.4.1" - } - }, - "lodash.isplainobject": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-3.2.0.tgz", - "integrity": "sha1-moI4rhayAEMpYM1zRlEtASP79MU=", - "dev": true, - "requires": { - "lodash._basefor": "3.0.3", - "lodash.isarguments": "3.1.0", - "lodash.keysin": "3.0.8" - } - }, - "lodash.istypedarray": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/lodash.istypedarray/-/lodash.istypedarray-3.0.6.tgz", - "integrity": "sha1-yaR3SYYHUB2OhJTSg7h8OSgc72I=", - "dev": true - }, - "lodash.keys": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-3.1.2.tgz", - "integrity": "sha1-TbwEcrFWvlCgsoaFXRvQsMZWCYo=", - "dev": true, - "requires": { - "lodash._getnative": "3.9.1", - "lodash.isarguments": "3.1.0", - "lodash.isarray": "3.0.4" - } - }, - "lodash.keysin": { - "version": "3.0.8", - "resolved": "https://registry.npmjs.org/lodash.keysin/-/lodash.keysin-3.0.8.tgz", - "integrity": "sha1-IsRJPrvtsUJ5YqVLRFssinZ/tH8=", - "dev": true, - "requires": { - "lodash.isarguments": "3.1.0", - "lodash.isarray": "3.0.4" - } - }, - "lodash.merge": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-3.3.2.tgz", - "integrity": "sha1-DZDZPtY3sYeEN7s+IWASYNev6ZQ=", - "dev": true, - "requires": { - "lodash._arraycopy": "3.0.0", - "lodash._arrayeach": "3.0.0", - "lodash._createassigner": "3.1.1", - "lodash._getnative": "3.9.1", - "lodash.isarguments": "3.1.0", - "lodash.isarray": "3.0.4", - "lodash.isplainobject": "3.2.0", - "lodash.istypedarray": "3.0.6", - "lodash.keys": "3.1.2", - "lodash.keysin": "3.0.8", - "lodash.toplainobject": "3.0.0" - } - }, - "lodash.mergewith": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/lodash.mergewith/-/lodash.mergewith-4.6.0.tgz", - "integrity": "sha1-FQzwoWeR9ZA7iJHqsVRgknS96lU=", - "dev": true - }, - "lodash.restparam": { - "version": "3.6.1", - "resolved": "https://registry.npmjs.org/lodash.restparam/-/lodash.restparam-3.6.1.tgz", - "integrity": "sha1-k2pOMJ7zMKdkXtQUWYbIWuWyCAU=", - "dev": true - }, - "lodash.tail": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/lodash.tail/-/lodash.tail-4.1.1.tgz", - "integrity": "sha1-0jM6NtnncXyK0vfKyv7HwytERmQ=", - "dev": true - }, - "lodash.template": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-3.6.2.tgz", - "integrity": "sha1-+M3sxhaaJVvpCYrosMU9N4kx0U8=", - "dev": true, - "requires": { - "lodash._basecopy": "3.0.1", - "lodash._basetostring": "3.0.1", - "lodash._basevalues": "3.0.0", - "lodash._isiterateecall": "3.0.9", - "lodash._reinterpolate": "3.0.0", - "lodash.escape": "3.2.0", - "lodash.keys": "3.1.2", - "lodash.restparam": "3.6.1", - "lodash.templatesettings": "3.1.1" - } - }, - "lodash.templatesettings": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/lodash.templatesettings/-/lodash.templatesettings-3.1.1.tgz", - "integrity": "sha1-+zB4RHU7Zrnxr6VOJix0UwfbqOU=", - "dev": true, - "requires": { - "lodash._reinterpolate": "3.0.0", - "lodash.escape": "3.2.0" - } - }, - "lodash.toplainobject": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lodash.toplainobject/-/lodash.toplainobject-3.0.0.tgz", - "integrity": "sha1-KHkK2ULSk9eKpmOgfs9/UsoEGY0=", - "dev": true, - "requires": { - "lodash._basecopy": "3.0.1", - "lodash.keysin": "3.0.8" - } - }, - "lodash.values": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.values/-/lodash.values-2.4.1.tgz", - "integrity": "sha1-q/UUQ2s8twUAFieXjLzzCxKA7qQ=", - "dev": true, - "requires": { - "lodash.keys": "2.4.1" - }, - "dependencies": { - "lodash.keys": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-2.4.1.tgz", - "integrity": "sha1-SN6kbfj/djKxDXBrissmWR4rNyc=", - "dev": true, - "requires": { - "lodash._isnative": "2.4.1", - "lodash._shimkeys": "2.4.1", - "lodash.isobject": "2.4.1" - } - } - } - }, - "log4js": { - "version": "0.6.38", - "resolved": "https://registry.npmjs.org/log4js/-/log4js-0.6.38.tgz", - "integrity": "sha1-LElBFmldb7JUgJQ9P8hy5mKlIv0=", - "dev": true, - "requires": { - "readable-stream": "1.0.34", - "semver": "4.3.6" - }, - "dependencies": { - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - }, - "readable-stream": { - "version": "1.0.34", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", - "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "0.0.1", - "string_decoder": "0.10.31" - } - }, - "semver": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/semver/-/semver-4.3.6.tgz", - "integrity": "sha1-MAvG4OhjdPe6YQaLWx7NV/xlMto=", - "dev": true - } - } - }, - "loglevel": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.6.1.tgz", - "integrity": "sha1-4PyVEztu8nbNyIh82vJKpvFW+Po=", - "dev": true - }, - "long": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", - "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==", - "dev": true - }, - "longest": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz", - "integrity": "sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc=", - "dev": true - }, - "loose-envify": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz", - "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", - "dev": true, - "requires": { - "js-tokens": "3.0.1" - } - }, - "loud-rejection": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/loud-rejection/-/loud-rejection-1.6.0.tgz", - "integrity": "sha1-W0b4AUft7leIcPCG0Eghz5mOVR8=", - "dev": true, - "requires": { - "currently-unhandled": "0.4.1", - "signal-exit": "3.0.1" - } - }, - "lower-case": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-1.1.3.tgz", - "integrity": "sha1-ySOT2XZ5Pu5bpO21g8+OrjW9m/s=", - "dev": true - }, - "lowercase-keys": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.0.tgz", - "integrity": "sha1-TjNms55/VFfjXxMkvfb4jQv8cwY=", - "dev": true - }, - "lru-cache": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.0.1.tgz", - "integrity": "sha1-E0OVXtry432bnn7nJB4nxLn7cr4=", - "requires": { - "pseudomap": "1.0.2", - "yallist": "2.0.0" - } - }, - "make-dir": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.0.0.tgz", - "integrity": "sha1-l6ARdR6R3YfPre9Ygy67BJNt6Xg=", - "dev": true, - "requires": { - "pify": "2.3.0" - } - }, - "make-iterator": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/make-iterator/-/make-iterator-1.0.0.tgz", - "integrity": "sha1-V7713IXSOSO6I3ZzJNjo+PPZaUs=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "dev": true - }, - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "map-cache": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", - "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", - "dev": true - }, - "map-obj": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", - "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=", - "dev": true - }, - "map-stream": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/map-stream/-/map-stream-0.1.0.tgz", - "integrity": "sha1-5WqpTEyAVaFkBKBnS3jyFffI4ZQ=", - "dev": true - }, - "map-visit": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", - "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", - "dev": true, - "requires": { - "object-visit": "1.0.1" - } - }, - "material-design-lite": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/material-design-lite/-/material-design-lite-1.3.0.tgz", - "integrity": "sha1-0ATOP+6Zoe63Sni4oyUTSl8RcdM=" - }, - "md5.js": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.4.tgz", - "integrity": "sha1-6b296UogpawYsENA/Fdk1bCdkB0=", - "dev": true, - "requires": { - "hash-base": "3.0.4", - "inherits": "2.0.3" - }, - "dependencies": { - "hash-base": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.0.4.tgz", - "integrity": "sha1-X8hoaEfs1zSZQDMZprCj8/auSRg=", - "dev": true, - "requires": { - "inherits": "2.0.3", - "safe-buffer": "5.1.1" - } - } - } - }, - "media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", - "dev": true - }, - "mem": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/mem/-/mem-1.1.0.tgz", - "integrity": "sha1-Xt1StIXKHZAP5kiVUFOZoN+kX3Y=", - "dev": true, - "requires": { - "mimic-fn": "1.2.0" - } - }, - "memory-fs": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/memory-fs/-/memory-fs-0.4.1.tgz", - "integrity": "sha1-OpoguEYlI+RHz7x+i7gO1me/xVI=", - "dev": true, - "requires": { - "errno": "0.1.4", - "readable-stream": "2.1.5" - } - }, - "meow": { - "version": "3.7.0", - "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz", - "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", - "dev": true, - "requires": { - "camelcase-keys": "2.1.0", - "decamelize": "1.2.0", - "loud-rejection": "1.6.0", - "map-obj": "1.0.1", - "minimist": "1.2.0", - "normalize-package-data": "2.3.5", - "object-assign": "4.1.0", - "read-pkg-up": "1.0.1", - "redent": "1.0.0", - "trim-newlines": "1.0.0" - } - }, - "merge-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", - "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=", - "dev": true - }, - "merge-stream": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-1.0.1.tgz", - "integrity": "sha1-QEEgLVCKNCugAXQAjfDCUbjBNeE=", - "dev": true, - "requires": { - "readable-stream": "2.1.5" - } - }, - "methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=", - "dev": true - }, - "mg-crud": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/mg-crud/-/mg-crud-1.1.2.tgz", - "integrity": "sha1-p6AWGzWSPK7/8ZpIBpS2V1vDggw=", - "requires": { - "angular": "1.6.8" - } - }, - "micromatch": { - "version": "2.3.11", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", - "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", - "dev": true, - "requires": { - "arr-diff": "2.0.0", - "array-unique": "0.2.1", - "braces": "1.8.5", - "expand-brackets": "0.1.5", - "extglob": "0.3.2", - "filename-regex": "2.0.0", - "is-extglob": "1.0.0", - "is-glob": "2.0.1", - "kind-of": "3.0.4", - "normalize-path": "2.0.1", - "object.omit": "2.0.1", - "parse-glob": "3.0.4", - "regex-cache": "0.4.3" - } - }, - "miller-rabin": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", - "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", - "dev": true, - "requires": { - "bn.js": "4.11.8", - "brorand": "1.1.0" - } - }, - "mime": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.3.4.tgz", - "integrity": "sha1-EV+eO2s9rylZmDyzjxSaLUDrXVM=", - "dev": true - }, - "mime-db": { - "version": "1.24.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.24.0.tgz", - "integrity": "sha1-4tE/k58AFsbk6a0lqGUvEmxGfww=", - "dev": true - }, - "mime-types": { - "version": "2.1.12", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.12.tgz", - "integrity": "sha1-FSuiVndwIN1GY/VMLnvCY4HnFyk=", - "dev": true, - "requires": { - "mime-db": "1.24.0" - } - }, - "mimic-fn": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", - "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==" - }, - "minimalistic-assert": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.0.tgz", - "integrity": "sha1-cCvi3aazf0g2vLP121ZkG2Sh09M=", - "dev": true - }, - "minimalistic-crypto-utils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", - "integrity": "sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=", - "dev": true - }, - "minimatch": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.3.tgz", - "integrity": "sha1-Kk5AkLlrLbBqnX3wEFWmKnfJt3Q=", - "requires": { - "brace-expansion": "1.1.6" - } - }, - "minimist": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", - "dev": true - }, - "minstache": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minstache/-/minstache-1.2.0.tgz", - "integrity": "sha1-/xzEA6woRPaNvxjGYhKb5+sO/EE=", - "dev": true, - "requires": { - "commander": "1.0.4" - }, - "dependencies": { - "commander": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/commander/-/commander-1.0.4.tgz", - "integrity": "sha1-Xt6xruI8T7VBprcNaSq+8ZZpotM=", - "dev": true, - "requires": { - "keypress": "0.1.0" - } - } - } - }, - "mixin-deep": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.0.tgz", - "integrity": "sha1-R6hzK6l3mUV8jB7KKPlRMtfoFQo=", - "dev": true, - "requires": { - "for-in": "1.0.2", - "is-extendable": "1.0.1" - }, - "dependencies": { - "for-in": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", - "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", - "dev": true - }, - "is-extendable": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", - "integrity": "sha1-p0cPnkJnM9gb2B4RVSZOOjUHyrQ=", - "dev": true, - "requires": { - "is-plain-object": "2.0.4" - } - } - } - }, - "mixin-object": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/mixin-object/-/mixin-object-2.0.1.tgz", - "integrity": "sha1-T7lJRB2rGCVA8f4DW6YOGUel5X4=", - "dev": true, - "requires": { - "for-in": "0.1.6", - "is-extendable": "0.1.1" - } - }, - "mkdirp": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", - "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", - "requires": { - "minimist": "0.0.8" - }, - "dependencies": { - "minimist": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=" - } - } - }, - "ms": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", - "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", - "dev": true - }, - "multicast-dns": { - "version": "6.2.3", - "resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-6.2.3.tgz", - "integrity": "sha512-ji6J5enbMyGRHIAkAOu3WdV8nggqviKCEKtXcOqfphZZtQrmHKycfynJ2V7eVPUA4NhJ6V7Wf4TmGbTwKE9B6g==", - "dev": true, - "requires": { - "dns-packet": "1.3.1", - "thunky": "1.0.2" - } - }, - "multicast-dns-service-types": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/multicast-dns-service-types/-/multicast-dns-service-types-1.1.0.tgz", - "integrity": "sha1-iZ8R2WhuXgXLkbNdXw5jt3PPyQE=", - "dev": true - }, - "multipipe": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/multipipe/-/multipipe-0.1.2.tgz", - "integrity": "sha1-Ko8t33Du1WTf8tV/HhoTfZ8FB4s=", - "dev": true, - "requires": { - "duplexer2": "0.0.2" - } - }, - "mustache": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/mustache/-/mustache-2.3.0.tgz", - "integrity": "sha1-QCj3d4sXcIpImTCm5SrDvKDaQdA=", - "dev": true - }, - "mute-stream": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz", - "integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=" - }, - "mysql2": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-1.5.2.tgz", - "integrity": "sha512-976p3FxXdNMRRiF6Qe/FCOwaUYw3KXVJiIYu5iE5shM7ggIASgF6G/9gd9rhpBqP8V6MVa3KQJ6Ao1xBeGBljw==", - "dev": true, - "requires": { - "cardinal": "1.0.0", - "denque": "1.2.3", - "generate-function": "2.0.0", - "iconv-lite": "0.4.19", - "long": "4.0.0", - "lru-cache": "4.1.1", - "named-placeholders": "1.1.1", - "object-assign": "4.1.1", - "readable-stream": "2.3.2", - "safe-buffer": "5.1.1", - "seq-queue": "0.0.5", - "sqlstring": "2.3.0" - }, - "dependencies": { - "lru-cache": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.1.tgz", - "integrity": "sha512-q4spe4KTfsAS1SUHLO0wz8Qiyf1+vMIAgpRYioFYDMNqKfHQbg+AVDH3i4fvpl71/P1L0dBl+fQi+P37UYf0ew==", - "dev": true, - "requires": { - "pseudomap": "1.0.2", - "yallist": "2.1.2" - } - }, - "object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", - "dev": true - }, - "readable-stream": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.2.tgz", - "integrity": "sha1-WgTfBeT1f+Pw3Gj90R3FyXx+b00=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "safe-buffer": "5.1.1", - "string_decoder": "1.0.3", - "util-deprecate": "1.0.2" - } - }, - "string_decoder": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", - "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", - "dev": true, - "requires": { - "safe-buffer": "5.1.1" - } - }, - "yallist": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", - "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", - "dev": true - } - } - }, - "named-placeholders": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.1.tgz", - "integrity": "sha1-O3oNJiA910s6nfTJz7gnsvuQfmQ=", - "dev": true, - "requires": { - "lru-cache": "2.5.0" - }, - "dependencies": { - "lru-cache": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.5.0.tgz", - "integrity": "sha1-2COIrpyWC+y+oMc7uet5tsbOmus=", - "dev": true - } - } - }, - "nan": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.8.0.tgz", - "integrity": "sha1-7XFfP+neArV6XmJS2QqWZ14fCFo=", - "dev": true - }, - "nanomatch": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.7.tgz", - "integrity": "sha1-U81KoQn/aLf4aVkf3J0Q2u7qPnk=", - "dev": true, - "requires": { - "arr-diff": "4.0.0", - "array-unique": "0.3.2", - "define-property": "1.0.0", - "extend-shallow": "2.0.1", - "fragment-cache": "0.2.1", - "is-odd": "1.0.0", - "kind-of": "5.1.0", - "object.pick": "1.3.0", - "regex-not": "1.0.0", - "snapdragon": "0.8.1", - "to-regex": "3.0.1" - }, - "dependencies": { - "arr-diff": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", - "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", - "dev": true - }, - "array-unique": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", - "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", - "dev": true - }, - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "0.1.1" - } - }, - "kind-of": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", - "integrity": "sha1-cpyR4thXt6QZofmqZWhcTDP1hF0=", - "dev": true - } - } - }, - "natives": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/natives/-/natives-1.1.1.tgz", - "integrity": "sha1-ARrM4ffL2H97prMJPWzZOSvhxXQ=", - "dev": true - }, - "natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=" - }, - "ncname": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/ncname/-/ncname-1.0.0.tgz", - "integrity": "sha1-W1etGLHKCShk72Kwse2BlPODtxw=", - "dev": true, - "requires": { - "xml-char-classes": "1.0.0" - } - }, - "negotiator": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz", - "integrity": "sha1-KzJxhOiZIQEXeyhWP7XnECrNDKk=", - "dev": true - }, - "nightmare": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/nightmare/-/nightmare-2.10.0.tgz", - "integrity": "sha1-6cXVkLspb1loX9SCGML7rER2eyE=", - "dev": true, - "requires": { - "debug": "2.2.0", - "deep-defaults": "1.0.4", - "defaults": "1.0.3", - "electron": "1.7.9", - "enqueue": "1.0.2", - "function-source": "0.1.0", - "jsesc": "0.5.0", - "minstache": "1.2.0", - "mkdirp": "0.5.1", - "once": "1.4.0", - "rimraf": "2.5.4", - "sliced": "1.0.1", - "split2": "2.2.0" - }, - "dependencies": { - "jsesc": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", - "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", - "dev": true - } - } - }, - "no-case": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/no-case/-/no-case-2.3.0.tgz", - "integrity": "sha1-yiglzLdrGOb3nVc9z78erOM90WQ=", - "dev": true, - "requires": { - "lower-case": "1.1.3" - } - }, - "node-forge": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-0.7.1.tgz", - "integrity": "sha1-naYR6giYL0uUIGs760zJZl8gwwA=", - "dev": true - }, - "node-gyp": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-3.6.2.tgz", - "integrity": "sha1-m/vlRWIoYoSDjnUOrAUpWFP6HGA=", - "dev": true, - "requires": { - "fstream": "1.0.11", - "glob": "7.1.1", - "graceful-fs": "4.1.10", - "minimatch": "3.0.3", - "mkdirp": "0.5.1", - "nopt": "3.0.6", - "npmlog": "4.1.2", - "osenv": "0.1.4", - "request": "2.77.0", - "rimraf": "2.5.4", - "semver": "5.3.0", - "tar": "2.2.1", - "which": "1.2.11" - } - }, - "node-libs-browser": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/node-libs-browser/-/node-libs-browser-2.1.0.tgz", - "integrity": "sha512-5AzFzdoIMb89hBGMZglEegffzgRg+ZFoUmisQ8HI4j1KDdpx13J0taNp2y9xPbur6W61gepGDDotGBVQ7mfUCg==", - "dev": true, - "requires": { - "assert": "1.4.1", - "browserify-zlib": "0.2.0", - "buffer": "4.9.1", - "console-browserify": "1.1.0", - "constants-browserify": "1.0.0", - "crypto-browserify": "3.12.0", - "domain-browser": "1.2.0", - "events": "1.1.1", - "https-browserify": "1.0.0", - "os-browserify": "0.3.0", - "path-browserify": "0.0.0", - "process": "0.11.10", - "punycode": "1.4.1", - "querystring-es3": "0.2.1", - "readable-stream": "2.3.3", - "stream-browserify": "2.0.1", - "stream-http": "2.8.0", - "string_decoder": "1.0.3", - "timers-browserify": "2.0.6", - "tty-browserify": "0.0.0", - "url": "0.11.0", - "util": "0.10.3", - "vm-browserify": "0.0.4" - }, - "dependencies": { - "readable-stream": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.3.tgz", - "integrity": "sha512-m+qzzcn7KUxEmd1gMbchF+Y2eIUbieUaxkWtptyHywrX0rE8QEYqPC07Vuy4Wm32/xE16NcdBctb8S0Xe/5IeQ==", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "safe-buffer": "5.1.1", - "string_decoder": "1.0.3", - "util-deprecate": "1.0.2" - } - }, - "string_decoder": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", - "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", - "dev": true, - "requires": { - "safe-buffer": "5.1.1" - } - } - } - }, - "node-sass": { - "version": "4.7.2", - "resolved": "https://registry.npmjs.org/node-sass/-/node-sass-4.7.2.tgz", - "integrity": "sha512-CaV+wLqZ7//Jdom5aUFCpGNoECd7BbNhjuwdsX/LkXBrHl8eb1Wjw4HvWqcFvhr5KuNgAk8i/myf/MQ1YYeroA==", - "dev": true, - "requires": { - "async-foreach": "0.1.3", - "chalk": "1.1.3", - "cross-spawn": "3.0.1", - "gaze": "1.1.2", - "get-stdin": "4.0.1", - "glob": "7.1.1", - "in-publish": "2.0.0", - "lodash.assign": "4.2.0", - "lodash.clonedeep": "4.5.0", - "lodash.mergewith": "4.6.0", - "meow": "3.7.0", - "mkdirp": "0.5.1", - "nan": "2.8.0", - "node-gyp": "3.6.2", - "npmlog": "4.1.2", - "request": "2.79.0", - "sass-graph": "2.2.4", - "stdout-stream": "1.4.0", - "true-case-path": "1.0.2" - }, - "dependencies": { - "request": { - "version": "2.79.0", - "resolved": "https://registry.npmjs.org/request/-/request-2.79.0.tgz", - "integrity": "sha1-Tf5b9r6LjNw3/Pk+BLZVd3InEN4=", - "dev": true, - "requires": { - "aws-sign2": "0.6.0", - "aws4": "1.5.0", - "caseless": "0.11.0", - "combined-stream": "1.0.5", - "extend": "3.0.0", - "forever-agent": "0.6.1", - "form-data": "2.1.1", - "har-validator": "2.0.6", - "hawk": "3.1.3", - "http-signature": "1.1.1", - "is-typedarray": "1.0.0", - "isstream": "0.1.2", - "json-stringify-safe": "5.0.1", - "mime-types": "2.1.12", - "oauth-sign": "0.8.2", - "qs": "6.3.0", - "stringstream": "0.0.5", - "tough-cookie": "2.3.2", - "tunnel-agent": "0.4.3", - "uuid": "3.2.1" - } - }, - "uuid": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.2.1.tgz", - "integrity": "sha512-jZnMwlb9Iku/O3smGWvZhauCf6cvvpKi4BKRiliS3cxnI+Gz9j5MEpTz2UFuXiKPJocb7gnsLHwiS05ige5BEA==", - "dev": true - } - } - }, - "node-uuid": { - "version": "1.4.7", - "resolved": "https://registry.npmjs.org/node-uuid/-/node-uuid-1.4.7.tgz", - "integrity": "sha1-baWhdmjEs91ZYjvaEc9/pMH2Cm8=", - "dev": true - }, - "node.extend": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/node.extend/-/node.extend-1.0.10.tgz", - "integrity": "sha1-Mmm934HFRTX0CKvHhMMrDSvVX28=", - "dev": true, - "requires": { - "is": "0.3.0" - } - }, - "nodemon": { - "version": "1.12.1", - "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-1.12.1.tgz", - "integrity": "sha1-mWpW3EnZ8Wu/G3ik3gjxNjSzh40=", - "dev": true, - "requires": { - "chokidar": "1.7.0", - "debug": "2.6.9", - "es6-promise": "3.3.1", - "ignore-by-default": "1.0.1", - "lodash.defaults": "3.1.2", - "minimatch": "3.0.4", - "ps-tree": "1.1.0", - "touch": "3.1.0", - "undefsafe": "0.0.3", - "update-notifier": "2.2.0" - }, - "dependencies": { - "balanced-match": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", - "dev": true - }, - "brace-expansion": { - "version": "1.1.8", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.8.tgz", - "integrity": "sha1-wHshHHyVLsH479Uad+8NHTmQopI=", - "dev": true, - "requires": { - "balanced-match": "1.0.0", - "concat-map": "0.0.1" - } - }, - "chokidar": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-1.7.0.tgz", - "integrity": "sha1-eY5ol3gVHIB2tLNg5e3SjNortGg=", - "dev": true, - "requires": { - "anymatch": "1.3.0", - "async-each": "1.0.1", - "fsevents": "1.1.3", - "glob-parent": "2.0.0", - "inherits": "2.0.3", - "is-binary-path": "1.0.1", - "is-glob": "2.0.1", - "path-is-absolute": "1.0.1", - "readdirp": "2.1.0" - } - }, - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha1-XRKFFd8TT/Mn6QpMk/Tgd6U2NB8=", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "es6-promise": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz", - "integrity": "sha1-oIzd6EzNvzTQJ6FFG8kdS80ophM=", - "dev": true - }, - "lodash.assign": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/lodash.assign/-/lodash.assign-3.2.0.tgz", - "integrity": "sha1-POnwI0tLIiPilrj6CsH+6OvKZPo=", - "dev": true, - "requires": { - "lodash._baseassign": "3.2.0", - "lodash._createassigner": "3.1.1", - "lodash.keys": "3.1.2" - } - }, - "lodash.defaults": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-3.1.2.tgz", - "integrity": "sha1-xzCLGNv4vJNy1wGnNJPGEZK9Liw=", - "dev": true, - "requires": { - "lodash.assign": "3.2.0", - "lodash.restparam": "3.6.1" - } - }, - "minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha1-UWbihkV/AzBgZL5Ul+jbsMPTIIM=", - "dev": true, - "requires": { - "brace-expansion": "1.1.8" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "nopt": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.6.tgz", - "integrity": "sha1-xkZdvwirzU2zWTF/eaxopkayj/k=", - "dev": true, - "requires": { - "abbrev": "1.0.9" - } - }, - "normalize-package-data": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.3.5.tgz", - "integrity": "sha1-jZJPFClg4Xd+f/4XBUNjHMfLAt8=", - "dev": true, - "requires": { - "hosted-git-info": "2.1.5", - "is-builtin-module": "1.0.0", - "semver": "5.3.0", - "validate-npm-package-license": "3.0.1" - } - }, - "normalize-path": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.0.1.tgz", - "integrity": "sha1-R4hqwWYnYNQmG32XnSQXCdPOP3o=", - "dev": true - }, - "npm-run-path": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", - "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", - "dev": true, - "requires": { - "path-key": "2.0.1" - } - }, - "npmlog": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-4.1.2.tgz", - "integrity": "sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==", - "dev": true, - "requires": { - "are-we-there-yet": "1.1.4", - "console-control-strings": "1.1.0", - "gauge": "2.7.4", - "set-blocking": "2.0.0" - } - }, - "nugget": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/nugget/-/nugget-2.0.1.tgz", - "integrity": "sha1-IBCVpIfhrTYIGzQy+jytpPjQcbA=", - "dev": true, - "requires": { - "debug": "2.2.0", - "minimist": "1.2.0", - "pretty-bytes": "1.0.4", - "progress-stream": "1.2.0", - "request": "2.77.0", - "single-line-log": "1.1.2", - "throttleit": "0.0.2" - } - }, - "null-check": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/null-check/-/null-check-1.0.0.tgz", - "integrity": "sha1-l33/1xdgErnsMNKjnbXPcqBDnt0=", - "dev": true - }, - "number-is-nan": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", - "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", - "dev": true - }, - "oauth-sign": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.8.2.tgz", - "integrity": "sha1-Rqarfwrq2N6unsBWV4C31O/rnUM=", - "dev": true - }, - "object-assign": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.0.tgz", - "integrity": "sha1-ejs9DpgGPUP0wD8uiubNUahog6A=" - }, - "object-component": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/object-component/-/object-component-0.0.3.tgz", - "integrity": "sha1-8MaapQ78lbhmwYb0AKM3acsvEpE=", - "dev": true - }, - "object-copy": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", - "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", - "dev": true, - "requires": { - "copy-descriptor": "0.1.1", - "define-property": "0.2.5", - "kind-of": "3.0.4" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "0.1.6" - } - }, - "is-accessor-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", - "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", - "dev": true, - "requires": { - "kind-of": "3.0.4" - } - }, - "is-data-descriptor": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", - "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", - "dev": true, - "requires": { - "kind-of": "3.0.4" - } - }, - "is-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", - "integrity": "sha1-Nm2CQN3kh8pRgjsaufB6EKeCUco=", - "dev": true, - "requires": { - "is-accessor-descriptor": "0.1.6", - "is-data-descriptor": "0.1.4", - "kind-of": "5.1.0" - }, - "dependencies": { - "kind-of": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", - "integrity": "sha1-cpyR4thXt6QZofmqZWhcTDP1hF0=", - "dev": true - } - } - } - } - }, - "object-keys": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-0.4.0.tgz", - "integrity": "sha1-KKaq50KN0sOpLz2V8hM13SBOAzY=", - "dev": true - }, - "object-visit": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", - "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", - "dev": true, - "requires": { - "isobject": "3.0.1" - }, - "dependencies": { - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - } - } - }, - "object.defaults": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/object.defaults/-/object.defaults-1.1.0.tgz", - "integrity": "sha1-On+GgzS0B96gbaFtiNXNKeQ1/s8=", - "dev": true, - "requires": { - "array-each": "1.0.1", - "array-slice": "1.1.0", - "for-own": "1.0.0", - "isobject": "3.0.1" - }, - "dependencies": { - "array-slice": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-1.1.0.tgz", - "integrity": "sha512-B1qMD3RBP7O8o0H2KbrXDyB0IccejMF15+87Lvlor12ONPRHP6gTjXMNkt/d3ZuOGbAe66hFmaCfECI24Ufp6w==", - "dev": true - }, - "for-in": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", - "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", - "dev": true - }, - "for-own": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/for-own/-/for-own-1.0.0.tgz", - "integrity": "sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=", - "dev": true, - "requires": { - "for-in": "1.0.2" - } - }, - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - } - } - }, - "object.map": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/object.map/-/object.map-1.0.1.tgz", - "integrity": "sha1-z4Plncj8wK1fQlDh94s7gb2AHTc=", - "dev": true, - "requires": { - "for-own": "1.0.0", - "make-iterator": "1.0.0" - }, - "dependencies": { - "for-in": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", - "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", - "dev": true - }, - "for-own": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/for-own/-/for-own-1.0.0.tgz", - "integrity": "sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=", - "dev": true, - "requires": { - "for-in": "1.0.2" - } - } - } - }, - "object.omit": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/object.omit/-/object.omit-2.0.1.tgz", - "integrity": "sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo=", - "dev": true, - "requires": { - "for-own": "0.1.4", - "is-extendable": "0.1.1" - } - }, - "object.pick": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", - "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", - "dev": true, - "requires": { - "isobject": "3.0.1" - }, - "dependencies": { - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - } - } - }, - "obuf": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/obuf/-/obuf-1.1.1.tgz", - "integrity": "sha1-EEEktsYCxnlogaBCVB0220OlJk4=", - "dev": true - }, - "oclazyload": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/oclazyload/-/oclazyload-0.6.3.tgz", - "integrity": "sha1-Kjirv/QJDAihEBZxkZRbWfLoJ5w=" - }, - "on-finished": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", - "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", - "dev": true, - "requires": { - "ee-first": "1.1.1" - } - }, - "on-headers": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.1.tgz", - "integrity": "sha1-ko9dD0cNSTQmUepnlLCFfBAGk/c=", - "dev": true - }, - "once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", - "requires": { - "wrappy": "1.0.2" - } - }, - "onetime": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", - "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", - "requires": { - "mimic-fn": "1.2.0" - } - }, - "opn": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/opn/-/opn-5.2.0.tgz", - "integrity": "sha512-Jd/GpzPyHF4P2/aNOVmS3lfMSWV9J7cOhCG1s08XCEAsPkB7lp6ddiU0J7XzyQRDUh8BqJ7PchfINjR8jyofRQ==", - "dev": true, - "requires": { - "is-wsl": "1.1.0" - } - }, - "optimist": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz", - "integrity": "sha1-2j6nRob6IaGaERwybpDrFaAZZoY=", - "dev": true, - "requires": { - "minimist": "0.0.10", - "wordwrap": "0.0.2" - }, - "dependencies": { - "minimist": { - "version": "0.0.10", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz", - "integrity": "sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8=", - "dev": true - } - } - }, - "optionator": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", - "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", - "requires": { - "deep-is": "0.1.3", - "fast-levenshtein": "2.0.6", - "levn": "0.3.0", - "prelude-ls": "1.1.2", - "type-check": "0.3.2", - "wordwrap": "1.0.0" - }, - "dependencies": { - "wordwrap": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", - "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=" - } - } - }, - "options": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/options/-/options-0.0.6.tgz", - "integrity": "sha1-7CLTEoBrtT5zF3Pnza788cZDEo8=", - "dev": true - }, - "orchestrator": { - "version": "0.3.8", - "resolved": "https://registry.npmjs.org/orchestrator/-/orchestrator-0.3.8.tgz", - "integrity": "sha1-FOfp4nZPcxX7rBhOUGx6pt+UrX4=", - "dev": true, - "requires": { - "end-of-stream": "0.1.5", - "sequencify": "0.0.7", - "stream-consume": "0.1.0" - } - }, - "ordered-read-streams": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/ordered-read-streams/-/ordered-read-streams-0.1.0.tgz", - "integrity": "sha1-/VZamvjrRHO6abbtijQ1LLVS8SY=", - "dev": true - }, - "original": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/original/-/original-1.0.0.tgz", - "integrity": "sha1-kUf5P6FpbQS+YeAb1QuurKZWvTs=", - "dev": true, - "requires": { - "url-parse": "1.0.5" - }, - "dependencies": { - "url-parse": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.0.5.tgz", - "integrity": "sha1-CFSGBCKv3P7+tsllxmLUgAFpkns=", - "dev": true, - "requires": { - "querystringify": "0.0.4", - "requires-port": "1.0.0" - } - } - } - }, - "os-browserify": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", - "integrity": "sha1-hUNzx/XCMVkU/Jv8a9gjj92h7Cc=", - "dev": true - }, - "os-homedir": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", - "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=", - "dev": true - }, - "os-locale": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz", - "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=", - "dev": true, - "requires": { - "lcid": "1.0.0" - } - }, - "os-tmpdir": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", - "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" - }, - "osenv": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/osenv/-/osenv-0.1.4.tgz", - "integrity": "sha1-Qv5tWVPfBsgGS+bxdsPQWqqjRkQ=", - "dev": true, - "requires": { - "os-homedir": "1.0.2", - "os-tmpdir": "1.0.2" - } - }, - "p-finally": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", - "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", - "dev": true - }, - "p-limit": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.2.0.tgz", - "integrity": "sha512-Y/OtIaXtUPr4/YpMv1pCL5L5ed0rumAaAeBSj12F+bSlMdys7i8oQF/GUJmfpTS/QoaRrS/k6pma29haJpsMng==", - "dev": true, - "requires": { - "p-try": "1.0.0" - } - }, - "p-locate": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", - "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", - "dev": true, - "requires": { - "p-limit": "1.2.0" - } - }, - "p-map": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-1.2.0.tgz", - "integrity": "sha512-r6zKACMNhjPJMTl8KcFH4li//gkrXWfbD6feV8l6doRHlzljFWGJ2AP6iKaCJXyZmAUMOPtvbW7EXkbWO/pLEA==", - "dev": true - }, - "p-queue": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-1.2.0.tgz", - "integrity": "sha1-Y5y4sHJwwVtx16ZEao4wQU88ltE=", - "dev": true - }, - "p-try": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", - "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", - "dev": true - }, - "package-json": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/package-json/-/package-json-4.0.1.tgz", - "integrity": "sha1-iGmgQBJTZhxMTKPabCEh7VVfXu0=", - "dev": true, - "requires": { - "got": "6.7.1", - "registry-auth-token": "3.3.1", - "registry-url": "3.1.0", - "semver": "5.3.0" - } - }, - "pako": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.6.tgz", - "integrity": "sha512-lQe48YPsMJAig+yngZ87Lus+NF+3mtu7DVOBu6b/gHO1YpKwIj5AWjZ/TOS7i46HD/UixzWb1zeWDZfGZ3iYcg==", - "dev": true - }, - "param-case": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/param-case/-/param-case-2.1.0.tgz", - "integrity": "sha1-Jhn5D9bIKe0LlY8chO0Dp0Wm1wo=", - "dev": true, - "requires": { - "no-case": "2.3.0" - } - }, - "parse-asn1": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.0.tgz", - "integrity": "sha1-N8T5t+06tlx0gXtfJICTf7+XxxI=", - "dev": true, - "requires": { - "asn1.js": "4.9.2", - "browserify-aes": "1.1.1", - "create-hash": "1.1.3", - "evp_bytestokey": "1.0.3", - "pbkdf2": "3.0.14" - } - }, - "parse-filepath": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/parse-filepath/-/parse-filepath-1.0.2.tgz", - "integrity": "sha1-pjISf1Oq89FYdvWHLz/6x2PWyJE=", - "dev": true, - "requires": { - "is-absolute": "1.0.0", - "map-cache": "0.2.2", - "path-root": "0.1.1" - } - }, - "parse-glob": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/parse-glob/-/parse-glob-3.0.4.tgz", - "integrity": "sha1-ssN2z7EfNVE7rdFz7wu246OIORw=", - "dev": true, - "requires": { - "glob-base": "0.3.0", - "is-dotfile": "1.0.2", - "is-extglob": "1.0.0", - "is-glob": "2.0.1" - } - }, - "parse-json": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", - "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", - "dev": true, - "requires": { - "error-ex": "1.3.0" - } - }, - "parse-passwd": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", - "integrity": "sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY=", - "dev": true - }, - "parsejson": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/parsejson/-/parsejson-0.0.3.tgz", - "integrity": "sha1-q343WfIJ7OmUN5c/fQ8fZK4OZKs=", - "dev": true, - "requires": { - "better-assert": "1.0.2" - } - }, - "parseqs": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/parseqs/-/parseqs-0.0.5.tgz", - "integrity": "sha1-1SCKNzjkZ2bikbouoXNoSSGouJ0=", - "dev": true, - "requires": { - "better-assert": "1.0.2" - } - }, - "parseuri": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/parseuri/-/parseuri-0.0.5.tgz", - "integrity": "sha1-gCBKUNTbt3m/3G6+J3jZDkvOMgo=", - "dev": true, - "requires": { - "better-assert": "1.0.2" - } - }, - "parseurl": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz", - "integrity": "sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=", - "dev": true - }, - "pascalcase": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", - "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", - "dev": true - }, - "path-browserify": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.0.tgz", - "integrity": "sha1-oLhwcpquIUAFt9UDLsLLuw+0RRo=", - "dev": true - }, - "path-dirname": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/path-dirname/-/path-dirname-1.0.2.tgz", - "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=", - "dev": true - }, - "path-exists": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", - "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", - "dev": true, - "requires": { - "pinkie-promise": "2.0.1" - } - }, - "path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" - }, - "path-is-inside": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", - "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=" - }, - "path-key": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", - "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", - "dev": true - }, - "path-parse": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.5.tgz", - "integrity": "sha1-PBrfhx6pzWyUMbbqK9dKD/BVxME=", - "dev": true - }, - "path-root": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/path-root/-/path-root-0.1.1.tgz", - "integrity": "sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc=", - "dev": true, - "requires": { - "path-root-regex": "0.1.2" - } - }, - "path-root-regex": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/path-root-regex/-/path-root-regex-0.1.2.tgz", - "integrity": "sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0=", - "dev": true - }, - "path-to-regexp": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", - "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=", - "dev": true - }, - "path-type": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz", - "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", - "dev": true, - "requires": { - "graceful-fs": "4.1.10", - "pify": "2.3.0", - "pinkie-promise": "2.0.1" - } - }, - "pause-stream": { - "version": "0.0.11", - "resolved": "https://registry.npmjs.org/pause-stream/-/pause-stream-0.0.11.tgz", - "integrity": "sha1-/lo0sMvOErWqaitAPuLnO2AvFEU=", - "dev": true, - "requires": { - "through": "2.3.8" - } - }, - "pbkdf2": { - "version": "3.0.14", - "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.0.14.tgz", - "integrity": "sha512-gjsZW9O34fm0R7PaLHRJmLLVfSoesxztjPjE9o6R+qtVJij90ltg1joIovN9GKrRW3t1PzhDDG3UMEMFfZ+1wA==", - "dev": true, - "requires": { - "create-hash": "1.1.3", - "create-hmac": "1.1.6", - "ripemd160": "2.0.1", - "safe-buffer": "5.1.1", - "sha.js": "2.4.10" - } - }, - "pend": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", - "integrity": "sha1-elfrVQpng/kRUzH89GY9XI4AelA=", - "dev": true - }, - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=" - }, - "pinkie": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", - "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=" - }, - "pinkie-promise": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", - "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", - "requires": { - "pinkie": "2.0.4" - } - }, - "pkg-dir": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", - "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", - "dev": true, - "requires": { - "find-up": "2.1.0" - }, - "dependencies": { - "find-up": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", - "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", - "dev": true, - "requires": { - "locate-path": "2.0.0" - } - } - } - }, - "plugin-error": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/plugin-error/-/plugin-error-1.0.1.tgz", - "integrity": "sha512-L1zP0dk7vGweZME2i+EeakvUNqSrdiI3F91TwEoYiGrAfUXmVv6fJIq4g82PAXxNsWOp0J7ZqQy/3Szz0ajTxA==", - "dev": true, - "requires": { - "ansi-colors": "1.0.1", - "arr-diff": "4.0.0", - "arr-union": "3.1.0", - "extend-shallow": "3.0.2" - }, - "dependencies": { - "arr-diff": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", - "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", - "dev": true - } - } - }, - "pluralize": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-1.2.1.tgz", - "integrity": "sha1-0aIUg/0iu0HlihL6NCGCMUCJfEU=", - "dev": true - }, - "portfinder": { - "version": "1.0.13", - "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.13.tgz", - "integrity": "sha1-uzLs2HwnEErm7kS1o8y/Drsa7ek=", - "dev": true, - "requires": { - "async": "1.5.2", - "debug": "2.2.0", - "mkdirp": "0.5.1" - }, - "dependencies": { - "async": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=", - "dev": true - } - } - }, - "posix-character-classes": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", - "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", - "dev": true - }, - "prelude-ls": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", - "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=" - }, - "prepend-http": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", - "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=", - "dev": true - }, - "preserve": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/preserve/-/preserve-0.2.0.tgz", - "integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=", - "dev": true - }, - "pretty-bytes": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-1.0.4.tgz", - "integrity": "sha1-CiLoIQYJrTVUL4yNXSFZr/B1HIQ=", - "dev": true, - "requires": { - "get-stdin": "4.0.1", - "meow": "3.7.0" - } - }, - "pretty-hrtime": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/pretty-hrtime/-/pretty-hrtime-1.0.3.tgz", - "integrity": "sha1-t+PqQkNaTJsnWdmeDyAesZWALuE=", - "dev": true - }, - "private": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/private/-/private-0.1.6.tgz", - "integrity": "sha1-VcapdtD5uvuZJIUTUP5HubX7t8E=", - "dev": true - }, - "process": { - "version": "0.11.10", - "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", - "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=", - "dev": true - }, - "process-nextick-args": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz", - "integrity": "sha1-FQ4gt1ZZCtP5EJPyWk8q2L/zC6M=" - }, - "progress": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.0.tgz", - "integrity": "sha1-ihvjZr+Pwj2yvSPxDG/pILQ4nR8=" - }, - "progress-stream": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/progress-stream/-/progress-stream-1.2.0.tgz", - "integrity": "sha1-LNPP6jO6OonJwSHsM0er6asSX3c=", - "dev": true, - "requires": { - "speedometer": "0.1.4", - "through2": "0.2.3" - }, - "dependencies": { - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - }, - "readable-stream": { - "version": "1.1.14", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", - "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "0.0.1", - "string_decoder": "0.10.31" - } - }, - "through2": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/through2/-/through2-0.2.3.tgz", - "integrity": "sha1-6zKE2k6jEbbMis42U3SKUqvyWj8=", - "dev": true, - "requires": { - "readable-stream": "1.1.14", - "xtend": "2.1.2" - } - }, - "xtend": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-2.1.2.tgz", - "integrity": "sha1-bv7MKk2tjmlixJAbM3znuoe10os=", - "dev": true, - "requires": { - "object-keys": "0.4.0" - } - } - } - }, - "proxy-addr": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.2.tgz", - "integrity": "sha1-ZXFQT0e7mI7IGAJT+F3X4UlSvew=", - "dev": true, - "requires": { - "forwarded": "0.1.2", - "ipaddr.js": "1.5.2" - } - }, - "prr": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/prr/-/prr-0.0.0.tgz", - "integrity": "sha1-GoS4WQgyVQFBGFPQCB7j+obikmo=", - "dev": true - }, - "ps-tree": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/ps-tree/-/ps-tree-1.1.0.tgz", - "integrity": "sha1-tCGyQUDWID8e08dplrRCewjowBQ=", - "dev": true, - "requires": { - "event-stream": "3.3.4" - } - }, - "pseudomap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", - "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=" - }, - "public-encrypt": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.0.tgz", - "integrity": "sha1-OfaZ86RlYN1eusvKaTyvfGXBjMY=", - "dev": true, - "requires": { - "bn.js": "4.11.8", - "browserify-rsa": "4.0.1", - "create-hash": "1.1.3", - "parse-asn1": "5.1.0", - "randombytes": "2.0.6" - } - }, - "punycode": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", - "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=", - "dev": true - }, - "qjobs": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/qjobs/-/qjobs-1.1.5.tgz", - "integrity": "sha1-ZZ3p8s+NzCehSBJ28gU3cnI4LnM=", - "dev": true - }, - "qs": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.3.0.tgz", - "integrity": "sha1-9AOyZPI7wBIox0ExtAfxjV6l1EI=", - "dev": true - }, - "querystring": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", - "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=", - "dev": true - }, - "querystring-es3": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz", - "integrity": "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM=", - "dev": true - }, - "querystringify": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-0.0.4.tgz", - "integrity": "sha1-DPf4T5Rj/wrlHExLFC2VvjdyTZw=", - "dev": true - }, - "randomatic": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/randomatic/-/randomatic-1.1.6.tgz", - "integrity": "sha1-EQ3Kv/OX6dz/fAeJzMCkmt8exbs=", - "dev": true, - "requires": { - "is-number": "2.1.0", - "kind-of": "3.0.4" - } - }, - "randombytes": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.0.6.tgz", - "integrity": "sha512-CIQ5OFxf4Jou6uOKe9t1AOgqpeU5fd70A8NPdHSGeYXqXsPe6peOwI0cUl88RWZ6sP1vPMV3avd/R6cZ5/sP1A==", - "dev": true, - "requires": { - "safe-buffer": "5.1.1" - } - }, - "randomfill": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.3.tgz", - "integrity": "sha512-YL6GrhrWoic0Eq8rXVbMptH7dAxCs0J+mh5Y0euNekPPYaxEmdVGim6GdoxoRzKW2yJoU8tueifS7mYxvcFDEQ==", - "dev": true, - "requires": { - "randombytes": "2.0.6", - "safe-buffer": "5.1.1" - } - }, - "range-parser": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.0.tgz", - "integrity": "sha1-9JvmtIeJTdxA3MlKMi9hEJLgDV4=", - "dev": true - }, - "raw-body": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.3.2.tgz", - "integrity": "sha1-vNYMd9Prk83gBQKVw/N5OJvIj4k=", - "dev": true, - "requires": { - "bytes": "3.0.0", - "http-errors": "1.6.2", - "iconv-lite": "0.4.19", - "unpipe": "1.0.0" - }, - "dependencies": { - "bytes": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", - "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=", - "dev": true - }, - "depd": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.1.tgz", - "integrity": "sha1-V4O04cRZ8G+lyif5kfPQbnoxA1k=", - "dev": true - }, - "http-errors": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.2.tgz", - "integrity": "sha1-CgAsyFcHGSp+eUbO7cERVfYOxzY=", - "dev": true, - "requires": { - "depd": "1.1.1", - "inherits": "2.0.3", - "setprototypeof": "1.0.3", - "statuses": "1.3.1" - } - }, - "setprototypeof": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.0.3.tgz", - "integrity": "sha1-ZlZ+NwQ+608E2RvWWMDL77VbjgQ=", - "dev": true - } - } - }, - "raw-loader": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/raw-loader/-/raw-loader-0.5.1.tgz", - "integrity": "sha1-DD0L6u2KAclm2Xh793goElKpeao=", - "dev": true - }, - "rc": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.1.tgz", - "integrity": "sha1-LgPo5C7kULjLPc5lvhv4l04d/ZU=", - "dev": true, - "requires": { - "deep-extend": "0.4.2", - "ini": "1.3.4", - "minimist": "1.2.0", - "strip-json-comments": "2.0.1" - } - }, - "read-pkg": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz", - "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", - "dev": true, - "requires": { - "load-json-file": "1.1.0", - "normalize-package-data": "2.3.5", - "path-type": "1.1.0" - } - }, - "read-pkg-up": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-1.0.1.tgz", - "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", - "dev": true, - "requires": { - "find-up": "1.1.2", - "read-pkg": "1.1.0" - } - }, - "readable-stream": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.1.5.tgz", - "integrity": "sha1-ZvqLcg4UOLNkaB8q0aY8YYRIydA=", - "requires": { - "buffer-shims": "1.0.0", - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "string_decoder": "0.10.31", - "util-deprecate": "1.0.2" - } - }, - "readdirp": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.1.0.tgz", - "integrity": "sha1-TtCtBg3zBzMAxIRANz9y0cxkLXg=", - "dev": true, - "requires": { - "graceful-fs": "4.1.10", - "minimatch": "3.0.3", - "readable-stream": "2.1.5", - "set-immediate-shim": "1.0.1" - } - }, - "recast": { - "version": "0.11.18", - "resolved": "https://registry.npmjs.org/recast/-/recast-0.11.18.tgz", - "integrity": "sha1-B69iV8p2mGiBUglAHU1g7vG1uUc=", - "dev": true, - "requires": { - "ast-types": "0.9.2", - "esprima": "3.1.2", - "private": "0.1.6", - "source-map": "0.5.6" - } - }, - "rechoir": { - "version": "0.6.2", - "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz", - "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=", - "dev": true, - "requires": { - "resolve": "1.4.0" - } - }, - "redent": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/redent/-/redent-1.0.0.tgz", - "integrity": "sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94=", - "dev": true, - "requires": { - "indent-string": "2.1.0", - "strip-indent": "1.0.1" - } - }, - "redeyed": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/redeyed/-/redeyed-1.0.1.tgz", - "integrity": "sha1-6WwZO0DAgWsArshCaY5hGF5VSYo=", - "dev": true, - "requires": { - "esprima": "3.0.0" - }, - "dependencies": { - "esprima": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.0.0.tgz", - "integrity": "sha1-U88kes2ncxPlUcOqLnM0LT+099k=", - "dev": true - } - } - }, - "regenerate": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.3.3.tgz", - "integrity": "sha512-jVpo1GadrDAK59t/0jRx5VxYWQEDkkEKi6+HjE3joFVLfDOh9Xrdh0dF1eSq+BI/SwvTQ44gSscJ8N5zYL61sg==", - "dev": true - }, - "regenerator-runtime": { - "version": "0.11.1", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", - "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==", - "dev": true - }, - "regenerator-transform": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.10.1.tgz", - "integrity": "sha512-PJepbvDbuK1xgIgnau7Y90cwaAmO/LCLMI2mPvaXq2heGMR3aWW5/BQvYrhJ8jgmQjXewXvBjzfqKcVOmhjZ6Q==", - "dev": true, - "requires": { - "babel-runtime": "6.26.0", - "babel-types": "6.26.0", - "private": "0.1.6" - } - }, - "regex-cache": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/regex-cache/-/regex-cache-0.4.3.tgz", - "integrity": "sha1-mxpsNdTQ3871cRrmUejp09cRQUU=", - "dev": true, - "requires": { - "is-equal-shallow": "0.1.3", - "is-primitive": "2.0.0" - } - }, - "regex-not": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.0.tgz", - "integrity": "sha1-Qvg+OXcWIt+CawKvF2Ul1qXxV/k=", - "dev": true, - "requires": { - "extend-shallow": "2.0.1" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "0.1.1" - } - } - } - }, - "regexpu-core": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-2.0.0.tgz", - "integrity": "sha1-SdA4g3uNz4v6W5pCE5k45uoq4kA=", - "dev": true, - "requires": { - "regenerate": "1.3.3", - "regjsgen": "0.2.0", - "regjsparser": "0.1.5" - } - }, - "registry-auth-token": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.3.1.tgz", - "integrity": "sha1-+w0yie4Nmtosu1KvXf5mywcNMAY=", - "dev": true, - "requires": { - "rc": "1.2.1", - "safe-buffer": "5.1.1" - } - }, - "registry-url": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/registry-url/-/registry-url-3.1.0.tgz", - "integrity": "sha1-PU74cPc93h138M+aOBQyRE4XSUI=", - "dev": true, - "requires": { - "rc": "1.2.1" - } - }, - "regjsgen": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/regjsgen/-/regjsgen-0.2.0.tgz", - "integrity": "sha1-bAFq3qxVT3WCP+N6wFuS1aTtsfc=", - "dev": true - }, - "regjsparser": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.1.5.tgz", - "integrity": "sha1-fuj4Tcb6eS0/0K4ijSS9lJ6tIFw=", - "dev": true, - "requires": { - "jsesc": "0.5.0" - }, - "dependencies": { - "jsesc": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", - "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", - "dev": true - } - } - }, - "relateurl": { - "version": "0.2.7", - "resolved": "https://registry.npmjs.org/relateurl/-/relateurl-0.2.7.tgz", - "integrity": "sha1-VNvzd+UUQKypCkzSdGANP/LYiKk=", - "dev": true - }, - "remove-trailing-separator": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", - "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", - "dev": true - }, - "repeat-element": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.2.tgz", - "integrity": "sha1-7wiaF40Ug7quTZPrmLT55OEdmQo=", - "dev": true - }, - "repeat-string": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", - "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", - "dev": true - }, - "repeating": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", - "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", - "dev": true, - "requires": { - "is-finite": "1.0.2" - } - }, - "replace-ext": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-0.0.1.tgz", - "integrity": "sha1-KbvZIHinOfC8zitO5B6DeVNSKSQ=", - "dev": true - }, - "request": { - "version": "2.77.0", - "resolved": "https://registry.npmjs.org/request/-/request-2.77.0.tgz", - "integrity": "sha1-KwDYIDDt7cyXCJ/6XYgQqcKqMUs=", - "dev": true, - "requires": { - "aws-sign2": "0.6.0", - "aws4": "1.5.0", - "caseless": "0.11.0", - "combined-stream": "1.0.5", - "extend": "3.0.0", - "forever-agent": "0.6.1", - "form-data": "2.1.1", - "har-validator": "2.0.6", - "hawk": "3.1.3", - "http-signature": "1.1.1", - "is-typedarray": "1.0.0", - "isstream": "0.1.2", - "json-stringify-safe": "5.0.1", - "mime-types": "2.1.12", - "node-uuid": "1.4.7", - "oauth-sign": "0.8.2", - "qs": "6.3.0", - "stringstream": "0.0.5", - "tough-cookie": "2.3.2", - "tunnel-agent": "0.4.3" - } - }, - "require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", - "dev": true - }, - "require-main-filename": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz", - "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=", - "dev": true - }, - "require-uncached": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/require-uncached/-/require-uncached-1.0.3.tgz", - "integrity": "sha1-Tg1W1slmL9MeQwEcS5WqSZVUIdM=", - "requires": { - "caller-path": "0.1.0", - "resolve-from": "1.0.1" - } - }, - "require-yaml": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/require-yaml/-/require-yaml-0.0.1.tgz", - "integrity": "sha1-LhsY2RPDuqcqWk03O28Tjd0sMr0=", - "requires": { - "js-yaml": "3.10.0" - }, - "dependencies": { - "esprima": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.0.tgz", - "integrity": "sha512-oftTcaMu/EGrEIu904mWteKIv8vMuOgGYo7EhVJJN00R/EED9DCua/xxHRdYnKtcECzVg7xOWhflvJMnqcFZjw==" - }, - "js-yaml": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.10.0.tgz", - "integrity": "sha512-O2v52ffjLa9VeM43J4XocZE//WT9N0IiwDa3KSHH7Tu8CtH+1qM8SIZvnsTh6v+4yFy5KUY3BHUVwjpfAWsjIA==", - "requires": { - "argparse": "1.0.9", - "esprima": "4.0.0" - } - } - } - }, - "requires-port": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", - "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=", - "dev": true - }, - "resolve": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.4.0.tgz", - "integrity": "sha1-p1vgHFPaJdk0qY69DkxKcxL5KoY=", - "dev": true, - "requires": { - "path-parse": "1.0.5" - } - }, - "resolve-cwd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-2.0.0.tgz", - "integrity": "sha1-AKn3OHVW4nA46uIyyqNypqWbZlo=", - "dev": true, - "requires": { - "resolve-from": "3.0.0" - }, - "dependencies": { - "resolve-from": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-3.0.0.tgz", - "integrity": "sha1-six699nWiBvItuZTM17rywoYh0g=", - "dev": true - } - } - }, - "resolve-dir": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", - "integrity": "sha1-eaQGRMNivoLybv/nOcm7U4IEb0M=", - "dev": true, - "requires": { - "expand-tilde": "2.0.2", - "global-modules": "1.0.0" - } - }, - "resolve-from": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-1.0.1.tgz", - "integrity": "sha1-Jsv+k10a7uq7Kbw/5a6wHpPUQiY=" - }, - "resolve-url": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", - "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", - "dev": true - }, - "restore-cursor": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", - "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", - "requires": { - "onetime": "2.0.1", - "signal-exit": "3.0.2" - }, - "dependencies": { - "signal-exit": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", - "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=" - } - } - }, - "right-align": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/right-align/-/right-align-0.1.3.tgz", - "integrity": "sha1-YTObci/mo1FWiSENJOFMlhSGE+8=", - "dev": true, - "requires": { - "align-text": "0.1.4" - } - }, - "rimraf": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.5.4.tgz", - "integrity": "sha1-loAAk8vxoMhr2VtGJUZ1NcKd+gQ=", - "requires": { - "glob": "7.1.1" - } - }, - "ripemd160": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.1.tgz", - "integrity": "sha1-D0WEKVxTo2KK9+bXmsohzlfRxuc=", - "dev": true, - "requires": { - "hash-base": "2.0.2", - "inherits": "2.0.3" - } - }, - "run-async": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.3.0.tgz", - "integrity": "sha1-A3GrSuC91yDUFm19/aZP96RFpsA=", - "requires": { - "is-promise": "2.1.0" - } - }, - "run-sequence": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/run-sequence/-/run-sequence-2.2.0.tgz", - "integrity": "sha1-s/jUKDbbidCLL+cE6vDJPf2DNeI=", - "dev": true, - "requires": { - "chalk": "1.1.3", - "gulp-util": "3.0.8" - }, - "dependencies": { - "dateformat": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-2.2.0.tgz", - "integrity": "sha1-QGXiATz5+5Ft39gu+1Bq1MZ2kGI=", - "dev": true - }, - "gulp-util": { - "version": "3.0.8", - "resolved": "https://registry.npmjs.org/gulp-util/-/gulp-util-3.0.8.tgz", - "integrity": "sha1-AFTh50RQLifATBh8PsxQXdVLu08=", - "dev": true, - "requires": { - "array-differ": "1.0.0", - "array-uniq": "1.0.3", - "beeper": "1.1.1", - "chalk": "1.1.3", - "dateformat": "2.2.0", - "fancy-log": "1.3.2", - "gulplog": "1.0.0", - "has-gulplog": "0.1.0", - "lodash._reescape": "3.0.0", - "lodash._reevaluate": "3.0.0", - "lodash._reinterpolate": "3.0.0", - "lodash.template": "3.6.2", - "minimist": "1.2.0", - "multipipe": "0.1.2", - "object-assign": "3.0.0", - "replace-ext": "0.0.1", - "through2": "2.0.1", - "vinyl": "0.5.3" - } - }, - "object-assign": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz", - "integrity": "sha1-m+3VygiXlJvKR+f/QIBi1Un1h/I=", - "dev": true - } - } - }, - "rx-lite": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/rx-lite/-/rx-lite-4.0.8.tgz", - "integrity": "sha1-Cx4Rr4vESDbwSmQH6S2kJGe3lEQ=" - }, - "rx-lite-aggregates": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/rx-lite-aggregates/-/rx-lite-aggregates-4.0.8.tgz", - "integrity": "sha1-dTuHqJoRyVRnxKwWJsTvxOBcZ74=", - "requires": { - "rx-lite": "4.0.8" - } - }, - "safe-buffer": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", - "integrity": "sha1-iTMSr2myEj3vcfV4iQAWce6yyFM=" - }, - "sass-graph": { - "version": "2.2.4", - "resolved": "https://registry.npmjs.org/sass-graph/-/sass-graph-2.2.4.tgz", - "integrity": "sha1-E/vWPNHK8JCLn9k0dq1DpR0eC0k=", - "dev": true, - "requires": { - "glob": "7.1.1", - "lodash": "4.16.6", - "scss-tokenizer": "0.2.3", - "yargs": "7.1.0" - } - }, - "sass-loader": { - "version": "6.0.6", - "resolved": "https://registry.npmjs.org/sass-loader/-/sass-loader-6.0.6.tgz", - "integrity": "sha512-c3/Zc+iW+qqDip6kXPYLEgsAu2lf4xz0EZDplB7EmSUMda12U1sGJPetH55B/j9eu0bTtKzKlNPWWyYC7wFNyQ==", - "dev": true, - "requires": { - "async": "2.6.0", - "clone-deep": "0.3.0", - "loader-utils": "1.1.0", - "lodash.tail": "4.1.1", - "pify": "3.0.0" - }, - "dependencies": { - "async": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/async/-/async-2.6.0.tgz", - "integrity": "sha512-xAfGg1/NTLBBKlHFmnd7PlmUW9KhVQIUuSrYem9xzFUZy13ScvtyGGejaae9iAVRiRq9+Cx7DPFaAAhCpyxyPw==", - "dev": true, - "requires": { - "lodash": "4.16.6" - } - }, - "loader-utils": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.1.0.tgz", - "integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=", - "dev": true, - "requires": { - "big.js": "3.1.3", - "emojis-list": "2.1.0", - "json5": "0.5.0" - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - } - } - }, - "schema-utils": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.3.0.tgz", - "integrity": "sha1-9YdyIs4+kx7a4DnxfrNxbnE3+M8=", - "dev": true, - "requires": { - "ajv": "5.5.2" - }, - "dependencies": { - "ajv": { - "version": "5.5.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz", - "integrity": "sha1-c7Xuyj+rZT49P5Qis0GtQiBdyWU=", - "dev": true, - "requires": { - "co": "4.6.0", - "fast-deep-equal": "1.0.0", - "fast-json-stable-stringify": "2.0.0", - "json-schema-traverse": "0.3.1" - } - } - } - }, - "scss-tokenizer": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/scss-tokenizer/-/scss-tokenizer-0.2.3.tgz", - "integrity": "sha1-jrBtualyMzOCTT9VMGQRSYR85dE=", - "dev": true, - "requires": { - "js-base64": "2.4.3", - "source-map": "0.4.4" - }, - "dependencies": { - "source-map": { - "version": "0.4.4", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz", - "integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=", - "dev": true, - "requires": { - "amdefine": "1.0.1" - } - } - } - }, - "select-hose": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/select-hose/-/select-hose-2.0.0.tgz", - "integrity": "sha1-Yl2GWPhlr0Psliv8N2o3NZpJlMo=", - "dev": true - }, - "selfsigned": { - "version": "1.10.2", - "resolved": "https://registry.npmjs.org/selfsigned/-/selfsigned-1.10.2.tgz", - "integrity": "sha1-tESVgNmZKbZbEKSDiTAaZZIIh1g=", - "dev": true, - "requires": { - "node-forge": "0.7.1" - } - }, - "semver": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz", - "integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8=" - }, - "semver-diff": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/semver-diff/-/semver-diff-2.1.0.tgz", - "integrity": "sha1-S7uEN8jTfksM8aaP1ybsbWRdbTY=", - "dev": true, - "requires": { - "semver": "5.3.0" - } - }, - "send": { - "version": "0.16.1", - "resolved": "https://registry.npmjs.org/send/-/send-0.16.1.tgz", - "integrity": "sha512-ElCLJdJIKPk6ux/Hocwhk7NFHpI3pVm/IZOYWqUmoxcgeyM+MpxHHKhb8QmlJDX1pU6WrgaHBkVNm73Sv7uc2A==", - "dev": true, - "requires": { - "debug": "2.6.9", - "depd": "1.1.2", - "destroy": "1.0.4", - "encodeurl": "1.0.1", - "escape-html": "1.0.3", - "etag": "1.8.1", - "fresh": "0.5.2", - "http-errors": "1.6.2", - "mime": "1.4.1", - "ms": "2.0.0", - "on-finished": "2.3.0", - "range-parser": "1.2.0", - "statuses": "1.3.1" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "mime": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.4.1.tgz", - "integrity": "sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ==", - "dev": true - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "seq-queue": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz", - "integrity": "sha1-1WgS4cAXpuTnw+Ojeh2m143TyT4=", - "dev": true - }, - "sequencify": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/sequencify/-/sequencify-0.0.7.tgz", - "integrity": "sha1-kM/xnQLgcCf9dn9erT57ldHnOAw=", - "dev": true - }, - "serve-index": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/serve-index/-/serve-index-1.9.1.tgz", - "integrity": "sha1-03aNabHn2C5c4FD/9bRTvqEqkjk=", - "dev": true, - "requires": { - "accepts": "1.3.4", - "batch": "0.6.1", - "debug": "2.6.9", - "escape-html": "1.0.3", - "http-errors": "1.6.2", - "mime-types": "2.1.17", - "parseurl": "1.3.2" - }, - "dependencies": { - "accepts": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.4.tgz", - "integrity": "sha1-hiRnWMfdbSGmR0/whKR0DsBesh8=", - "dev": true, - "requires": { - "mime-types": "2.1.17", - "negotiator": "0.6.1" - } - }, - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "mime-db": { - "version": "1.30.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.30.0.tgz", - "integrity": "sha1-dMZD2i3Z1qRTmZY0ZbJtXKfXHwE=", - "dev": true - }, - "mime-types": { - "version": "2.1.17", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.17.tgz", - "integrity": "sha1-Cdejk/A+mVp5+K+Fe3Cp4KsWVXo=", - "dev": true, - "requires": { - "mime-db": "1.30.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "serve-static": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.13.1.tgz", - "integrity": "sha512-hSMUZrsPa/I09VYFJwa627JJkNs0NrfL1Uzuup+GqHfToR2KcsXFymXSV90hoyw3M+msjFuQly+YzIH/q0MGlQ==", - "dev": true, - "requires": { - "encodeurl": "1.0.1", - "escape-html": "1.0.3", - "parseurl": "1.3.2", - "send": "0.16.1" - } - }, - "set-blocking": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", - "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", - "dev": true - }, - "set-getter": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/set-getter/-/set-getter-0.1.0.tgz", - "integrity": "sha1-12nBgsnVpR9AkUXy+6guXoboA3Y=", - "dev": true, - "requires": { - "to-object-path": "0.3.0" - } - }, - "set-immediate-shim": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/set-immediate-shim/-/set-immediate-shim-1.0.1.tgz", - "integrity": "sha1-SysbJ+uAip+NzEgaWOXlb1mfP2E=", - "dev": true - }, - "set-value": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.0.tgz", - "integrity": "sha1-ca5KiPD+77v1LR6mBPP7MV67YnQ=", - "dev": true, - "requires": { - "extend-shallow": "2.0.1", - "is-extendable": "0.1.1", - "is-plain-object": "2.0.4", - "split-string": "3.1.0" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "0.1.1" - } - } - } - }, - "setimmediate": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", - "integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=", - "dev": true - }, - "setprototypeof": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", - "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==", - "dev": true - }, - "sha.js": { - "version": "2.4.10", - "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.10.tgz", - "integrity": "sha512-vnwmrFDlOExK4Nm16J2KMWHLrp14lBrjxMxBJpu++EnsuBmpiYaM/MEs46Vxxm/4FvdP5yTwuCTO9it5FSjrqA==", - "dev": true, - "requires": { - "inherits": "2.0.3", - "safe-buffer": "5.1.1" - } - }, - "shallow-clone": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-0.1.2.tgz", - "integrity": "sha1-WQnodLp3EG1zrEFM/sH/yofZcGA=", - "dev": true, - "requires": { - "is-extendable": "0.1.1", - "kind-of": "2.0.1", - "lazy-cache": "0.2.7", - "mixin-object": "2.0.1" - }, - "dependencies": { - "kind-of": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-2.0.1.tgz", - "integrity": "sha1-AY7HpM5+OobLkUG+UZ0kyPqpgbU=", - "dev": true, - "requires": { - "is-buffer": "1.1.4" - } - }, - "lazy-cache": { - "version": "0.2.7", - "resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-0.2.7.tgz", - "integrity": "sha1-f+3fLctu23fRHvHRF6tf/fCrG2U=", - "dev": true - } - } - }, - "shebang-command": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", - "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", - "requires": { - "shebang-regex": "1.0.0" - } - }, - "shebang-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", - "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=" - }, - "sigmund": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/sigmund/-/sigmund-1.0.1.tgz", - "integrity": "sha1-P/IfGYytIXX587eBhT/ZTQ0ZtZA=", - "dev": true - }, - "signal-exit": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.1.tgz", - "integrity": "sha1-WkyISZK2OnrNm623iUw+6c/MrYE=", - "dev": true - }, - "single-line-log": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/single-line-log/-/single-line-log-1.1.2.tgz", - "integrity": "sha1-wvg/Jzo+GhbtsJlWYdoO1e8DM2Q=", - "dev": true, - "requires": { - "string-width": "1.0.2" - } - }, - "slash": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-1.0.0.tgz", - "integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU=", - "dev": true - }, - "slice-ansi": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-1.0.0.tgz", - "integrity": "sha512-POqxBK6Lb3q6s047D/XsDVNPnF9Dl8JSaqe9h9lURl0OdNqy/ujDrOiIHtsqXMGbWWTIomRzAMaTyawAU//Reg==", - "requires": { - "is-fullwidth-code-point": "2.0.0" - }, - "dependencies": { - "is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=" - } - } - }, - "sliced": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", - "integrity": "sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E=", - "dev": true - }, - "snapdragon": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.1.tgz", - "integrity": "sha1-4StUh/re0+PeoKyR6UAL91tAE3A=", - "dev": true, - "requires": { - "base": "0.11.2", - "debug": "2.2.0", - "define-property": "0.2.5", - "extend-shallow": "2.0.1", - "map-cache": "0.2.2", - "source-map": "0.5.6", - "source-map-resolve": "0.5.1", - "use": "2.0.2" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "0.1.6" - } - }, - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "0.1.1" - } - }, - "is-accessor-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", - "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "dev": true - }, - "is-data-descriptor": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", - "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "is-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", - "integrity": "sha1-Nm2CQN3kh8pRgjsaufB6EKeCUco=", - "dev": true, - "requires": { - "is-accessor-descriptor": "0.1.6", - "is-data-descriptor": "0.1.4", - "kind-of": "5.1.0" - } - }, - "kind-of": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", - "integrity": "sha1-cpyR4thXt6QZofmqZWhcTDP1hF0=", - "dev": true - } - } - }, - "snapdragon-node": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", - "integrity": "sha1-bBdfhv8UvbByRWPo88GwIaKGhTs=", - "dev": true, - "requires": { - "define-property": "1.0.0", - "isobject": "3.0.1", - "snapdragon-util": "3.0.1" - }, - "dependencies": { - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - } - } - }, - "snapdragon-util": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", - "integrity": "sha1-+VZHlIbyrNeXAGk/b3uAXkWrVuI=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "dev": true - }, - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "sntp": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/sntp/-/sntp-1.0.9.tgz", - "integrity": "sha1-ZUEYTMkK7qbG57NeJlkIJEPGYZg=", - "dev": true, - "requires": { - "hoek": "2.16.3" - } - }, - "socket.io": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-1.7.3.tgz", - "integrity": "sha1-uK+cq6AJSeVo42nxMn6pvp6iRhs=", - "dev": true, - "requires": { - "debug": "2.3.3", - "engine.io": "1.8.3", - "has-binary": "0.1.7", - "object-assign": "4.1.0", - "socket.io-adapter": "0.5.0", - "socket.io-client": "1.7.3", - "socket.io-parser": "2.3.1" - }, - "dependencies": { - "debug": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.3.3.tgz", - "integrity": "sha1-QMRT5n5uE8kB3ewxeviYbNqe/4w=", - "dev": true, - "requires": { - "ms": "0.7.2" - } - }, - "ms": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.2.tgz", - "integrity": "sha1-riXPJRKziFodldfwN4aNhDESR2U=", - "dev": true - } - } - }, - "socket.io-adapter": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-0.5.0.tgz", - "integrity": "sha1-y21LuL7IHhB4uZZ3+c7QBGBmu4s=", - "dev": true, - "requires": { - "debug": "2.3.3", - "socket.io-parser": "2.3.1" - }, - "dependencies": { - "debug": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.3.3.tgz", - "integrity": "sha1-QMRT5n5uE8kB3ewxeviYbNqe/4w=", - "dev": true, - "requires": { - "ms": "0.7.2" - } - }, - "ms": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.2.tgz", - "integrity": "sha1-riXPJRKziFodldfwN4aNhDESR2U=", - "dev": true - } - } - }, - "socket.io-client": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-1.7.3.tgz", - "integrity": "sha1-sw6GqhDV7zVGYBwJzeR2Xjgdo3c=", - "dev": true, - "requires": { - "backo2": "1.0.2", - "component-bind": "1.0.0", - "component-emitter": "1.2.1", - "debug": "2.3.3", - "engine.io-client": "1.8.3", - "has-binary": "0.1.7", - "indexof": "0.0.1", - "object-component": "0.0.3", - "parseuri": "0.0.5", - "socket.io-parser": "2.3.1", - "to-array": "0.1.4" - }, - "dependencies": { - "component-emitter": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", - "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=", - "dev": true - }, - "debug": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.3.3.tgz", - "integrity": "sha1-QMRT5n5uE8kB3ewxeviYbNqe/4w=", - "dev": true, - "requires": { - "ms": "0.7.2" - } - }, - "ms": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.2.tgz", - "integrity": "sha1-riXPJRKziFodldfwN4aNhDESR2U=", - "dev": true - } - } - }, - "socket.io-parser": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-2.3.1.tgz", - "integrity": "sha1-3VMgJRA85Clpcya+/WQAX8/ltKA=", - "dev": true, - "requires": { - "component-emitter": "1.1.2", - "debug": "2.2.0", - "isarray": "0.0.1", - "json3": "3.3.2" - }, - "dependencies": { - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - } - } - }, - "sockjs": { - "version": "0.3.19", - "resolved": "https://registry.npmjs.org/sockjs/-/sockjs-0.3.19.tgz", - "integrity": "sha512-V48klKZl8T6MzatbLlzzRNhMepEys9Y4oGFpypBFFn1gLI/QQ9HtLLyWJNbPlwGLelOVOEijUbTTJeLLI59jLw==", - "dev": true, - "requires": { - "faye-websocket": "0.10.0", - "uuid": "3.2.1" - }, - "dependencies": { - "uuid": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.2.1.tgz", - "integrity": "sha512-jZnMwlb9Iku/O3smGWvZhauCf6cvvpKi4BKRiliS3cxnI+Gz9j5MEpTz2UFuXiKPJocb7gnsLHwiS05ige5BEA==", - "dev": true - } - } - }, - "sockjs-client": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/sockjs-client/-/sockjs-client-1.1.4.tgz", - "integrity": "sha1-W6vjhrd15M8U51IJEUUmVAFsixI=", - "dev": true, - "requires": { - "debug": "2.6.9", - "eventsource": "0.1.6", - "faye-websocket": "0.11.1", - "inherits": "2.0.3", - "json3": "3.3.2", - "url-parse": "1.2.0" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "faye-websocket": { - "version": "0.11.1", - "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.1.tgz", - "integrity": "sha1-8O/hjE9W5PQK/H4Gxxn9XuYYjzg=", - "dev": true, - "requires": { - "websocket-driver": "0.7.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "source-list-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.0.tgz", - "integrity": "sha512-I2UmuJSRr/T8jisiROLU3A3ltr+swpniSmNPI4Ml3ZCX6tVnDsuZzK7F2hl5jTqbZBWCEKlj5HRQiPExXLgE8A==", - "dev": true - }, - "source-map": { - "version": "0.5.6", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.6.tgz", - "integrity": "sha1-dc449SvwczxafwwRjYEzSiu19BI=", - "dev": true - }, - "source-map-resolve": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.1.tgz", - "integrity": "sha1-etD1k/IoFZjoVN+A8ZquS5LXoRo=", - "dev": true, - "requires": { - "atob": "2.0.3", - "decode-uri-component": "0.2.0", - "resolve-url": "0.2.1", - "source-map-url": "0.4.0", - "urix": "0.1.0" - } - }, - "source-map-support": { - "version": "0.4.18", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.4.18.tgz", - "integrity": "sha512-try0/JqxPLF9nOjvSta7tVondkP5dwgyLDjVoyMDlmjugT2lRZ1OfsrYTkCd2hkDnJTKRbO/Rl3orm8vlsUzbA==", - "dev": true, - "requires": { - "source-map": "0.5.6" - } - }, - "source-map-url": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", - "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=", - "dev": true - }, - "sparkles": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/sparkles/-/sparkles-1.0.0.tgz", - "integrity": "sha1-Gsu/tZJDbRC76PeFt8xvgoFQEsM=", - "dev": true - }, - "spdx-correct": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-1.0.2.tgz", - "integrity": "sha1-SzBz2TP/UfORLwOsVRlJikFQ20A=", - "dev": true, - "requires": { - "spdx-license-ids": "1.2.2" - } - }, - "spdx-expression-parse": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-1.0.4.tgz", - "integrity": "sha1-m98vIOH0DtRH++JzJmGR/O1RYmw=", - "dev": true - }, - "spdx-license-ids": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-1.2.2.tgz", - "integrity": "sha1-yd96NCRZSt5r0RkA1ZZpbcBrrFc=", - "dev": true - }, - "spdy": { - "version": "3.4.7", - "resolved": "https://registry.npmjs.org/spdy/-/spdy-3.4.7.tgz", - "integrity": "sha1-Qv9B7OXMD5mjpsKKq7c/XDsDrLw=", - "dev": true, - "requires": { - "debug": "2.6.9", - "handle-thing": "1.2.5", - "http-deceiver": "1.2.7", - "safe-buffer": "5.1.1", - "select-hose": "2.0.0", - "spdy-transport": "2.0.20" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - } - } - }, - "spdy-transport": { - "version": "2.0.20", - "resolved": "https://registry.npmjs.org/spdy-transport/-/spdy-transport-2.0.20.tgz", - "integrity": "sha1-c15yBUxIayNU/onnAiVgBKOazk0=", - "dev": true, - "requires": { - "debug": "2.6.9", - "detect-node": "2.0.3", - "hpack.js": "2.1.6", - "obuf": "1.1.1", - "readable-stream": "2.3.3", - "safe-buffer": "5.1.1", - "wbuf": "1.7.2" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - }, - "readable-stream": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.3.tgz", - "integrity": "sha512-m+qzzcn7KUxEmd1gMbchF+Y2eIUbieUaxkWtptyHywrX0rE8QEYqPC07Vuy4Wm32/xE16NcdBctb8S0Xe/5IeQ==", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "safe-buffer": "5.1.1", - "string_decoder": "1.0.3", - "util-deprecate": "1.0.2" - } - }, - "string_decoder": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", - "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", - "dev": true, - "requires": { - "safe-buffer": "5.1.1" - } - } - } - }, - "speedometer": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/speedometer/-/speedometer-0.1.4.tgz", - "integrity": "sha1-mHbb0qFp0xFUAtSObqYynIgWpQ0=", - "dev": true - }, - "split": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/split/-/split-0.3.3.tgz", - "integrity": "sha1-zQ7qXmOiEd//frDwkcQTPi0N0o8=", - "dev": true, - "requires": { - "through": "2.3.8" - } - }, - "split-string": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", - "integrity": "sha1-fLCd2jqGWFcFxks5pkZgOGguj+I=", - "dev": true, - "requires": { - "extend-shallow": "3.0.2" - }, - "dependencies": { - "extend-shallow": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", - "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", - "dev": true, - "requires": { - "assign-symbols": "1.0.0", - "is-extendable": "1.0.1" - } - }, - "is-extendable": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", - "integrity": "sha1-p0cPnkJnM9gb2B4RVSZOOjUHyrQ=", - "dev": true, - "requires": { - "is-plain-object": "2.0.4" - } - } - } - }, - "split2": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/split2/-/split2-2.2.0.tgz", - "integrity": "sha1-GGsldbz4PoW30YRldWI47k7kJJM=", - "dev": true, - "requires": { - "through2": "2.0.3" - }, - "dependencies": { - "through2": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.3.tgz", - "integrity": "sha1-AARWmzfHx0ujnEPzzteNGtlBQL4=", - "dev": true, - "requires": { - "readable-stream": "2.1.5", - "xtend": "4.0.1" - } - } - } - }, - "sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" - }, - "sqlstring": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.0.tgz", - "integrity": "sha1-UluKT9Jtb3GqYegipsr5dtMa0qg=", - "dev": true - }, - "sshpk": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.10.1.tgz", - "integrity": "sha1-MOGl0ykkSXShr2FREznVla9mOLA=", - "dev": true, - "requires": { - "asn1": "0.2.3", - "assert-plus": "1.0.0", - "bcrypt-pbkdf": "1.0.0", - "dashdash": "1.14.0", - "ecc-jsbn": "0.1.1", - "getpass": "0.1.6", - "jodid25519": "1.0.2", - "jsbn": "0.1.0", - "tweetnacl": "0.14.3" - }, - "dependencies": { - "assert-plus": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", - "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", - "dev": true - } - } - }, - "static-extend": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", - "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", - "dev": true, - "requires": { - "define-property": "0.2.5", - "object-copy": "0.1.0" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "0.1.6" - } - }, - "is-accessor-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", - "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "dev": true - }, - "is-data-descriptor": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", - "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "is-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", - "integrity": "sha1-Nm2CQN3kh8pRgjsaufB6EKeCUco=", - "dev": true, - "requires": { - "is-accessor-descriptor": "0.1.6", - "is-data-descriptor": "0.1.4", - "kind-of": "5.1.0" - } - }, - "kind-of": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", - "integrity": "sha1-cpyR4thXt6QZofmqZWhcTDP1hF0=", - "dev": true - } - } - }, - "statuses": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.3.1.tgz", - "integrity": "sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4=", - "dev": true - }, - "stdout-stream": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/stdout-stream/-/stdout-stream-1.4.0.tgz", - "integrity": "sha1-osfIWH5U2UJ+qe2zrD8s1SLfN4s=", - "dev": true, - "requires": { - "readable-stream": "2.1.5" - } - }, - "stream-browserify": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.1.tgz", - "integrity": "sha1-ZiZu5fm9uZQKTkUUyvtDu3Hlyds=", - "dev": true, - "requires": { - "inherits": "2.0.3", - "readable-stream": "2.1.5" - } - }, - "stream-combiner": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/stream-combiner/-/stream-combiner-0.0.4.tgz", - "integrity": "sha1-TV5DPBhSYd3mI8o/RMWGvPXErRQ=", - "dev": true, - "requires": { - "duplexer": "0.1.1" - } - }, - "stream-consume": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/stream-consume/-/stream-consume-0.1.0.tgz", - "integrity": "sha1-pB6tGm1ggc63n2WwYZAbbY89HQ8=", - "dev": true - }, - "stream-http": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/stream-http/-/stream-http-2.8.0.tgz", - "integrity": "sha512-sZOFxI/5xw058XIRHl4dU3dZ+TTOIGJR78Dvo0oEAejIt4ou27k+3ne1zYmCV+v7UucbxIFQuOgnkTVHh8YPnw==", - "dev": true, - "requires": { - "builtin-status-codes": "3.0.0", - "inherits": "2.0.3", - "readable-stream": "2.3.3", - "to-arraybuffer": "1.0.1", - "xtend": "4.0.1" - }, - "dependencies": { - "readable-stream": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.3.tgz", - "integrity": "sha512-m+qzzcn7KUxEmd1gMbchF+Y2eIUbieUaxkWtptyHywrX0rE8QEYqPC07Vuy4Wm32/xE16NcdBctb8S0Xe/5IeQ==", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "safe-buffer": "5.1.1", - "string_decoder": "1.0.3", - "util-deprecate": "1.0.2" - } - }, - "string_decoder": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", - "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", - "dev": true, - "requires": { - "safe-buffer": "5.1.1" - } - } - } - }, - "string-width": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", - "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", - "dev": true, - "requires": { - "code-point-at": "1.1.0", - "is-fullwidth-code-point": "1.0.0", - "strip-ansi": "3.0.1" - } - }, - "string_decoder": { - "version": "0.10.31", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=" - }, - "stringstream": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/stringstream/-/stringstream-0.0.5.tgz", - "integrity": "sha1-TkhM1N5aC7vuGORjB3EKioFiGHg=", - "dev": true - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "2.0.0" - } - }, - "strip-bom": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", - "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", - "dev": true, - "requires": { - "is-utf8": "0.2.1" - } - }, - "strip-eof": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", - "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", - "dev": true - }, - "strip-indent": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-1.0.1.tgz", - "integrity": "sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI=", - "dev": true, - "requires": { - "get-stdin": "4.0.1" - } - }, - "strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=" - }, - "style-loader": { - "version": "0.20.1", - "resolved": "https://registry.npmjs.org/style-loader/-/style-loader-0.20.1.tgz", - "integrity": "sha512-NtlwQOHQvUgEKuPs4JoUMQUkML8UNMxLbXM2JAZerIQVVVMgO5VVRjYQA8zzkpBu/X2OnTt+5ZKe8IbGk5TjRA==", - "dev": true, - "requires": { - "loader-utils": "1.1.0", - "schema-utils": "0.4.3" - }, - "dependencies": { - "ajv": { - "version": "5.5.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz", - "integrity": "sha1-c7Xuyj+rZT49P5Qis0GtQiBdyWU=", - "dev": true, - "requires": { - "co": "4.6.0", - "fast-deep-equal": "1.0.0", - "fast-json-stable-stringify": "2.0.0", - "json-schema-traverse": "0.3.1" - } - }, - "ajv-keywords": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-2.1.1.tgz", - "integrity": "sha1-YXmX/F9gV2iUxDX5QNgZ4TW4B2I=", - "dev": true - }, - "loader-utils": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.1.0.tgz", - "integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=", - "dev": true, - "requires": { - "big.js": "3.1.3", - "emojis-list": "2.1.0", - "json5": "0.5.0" - } - }, - "schema-utils": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.4.3.tgz", - "integrity": "sha512-sgv/iF/T4/SewJkaVpldKC4WjSkz0JsOh2eKtxCPpCO1oR05+7MOF+H476HVRbLArkgA7j5TRJJ4p2jdFkUGQQ==", - "dev": true, - "requires": { - "ajv": "5.5.2", - "ajv-keywords": "2.1.1" - } - } - } - }, - "sumchecker": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-1.3.1.tgz", - "integrity": "sha1-ebs7RFbdBPGOvbwNcDodHa7FEF0=", - "dev": true, - "requires": { - "debug": "2.2.0", - "es6-promise": "4.1.1" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - }, - "table": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/table/-/table-4.0.2.tgz", - "integrity": "sha512-UUkEAPdSGxtRpiV9ozJ5cMTtYiqz7Ni1OGqLXRCynrvzdtR1p+cfOWe2RJLwvUG8hNanaSRjecIqwOjqeatDsA==", - "requires": { - "ajv": "5.5.2", - "ajv-keywords": "2.1.1", - "chalk": "2.3.1", - "lodash": "4.17.5", - "slice-ansi": "1.0.0", - "string-width": "2.1.1" - }, - "dependencies": { - "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" - }, - "ansi-styles": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.0.tgz", - "integrity": "sha512-NnSOmMEYtVR2JVMIGTzynRkkaxtiq1xnFBcdQD/DnNCYPoEPsVJhM98BDyaoNOQIi7p4okdi3E27eN7GQbsUug==", - "requires": { - "color-convert": "1.9.0" - } - }, - "chalk": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.3.1.tgz", - "integrity": "sha512-QUU4ofkDoMIVO7hcx1iPTISs88wsO8jA92RQIm4JAwZvFGGAV2hSAA1NX7oVj2Ej2Q6NDTcRDjPTFrMCRZoJ6g==", - "requires": { - "ansi-styles": "3.2.0", - "escape-string-regexp": "1.0.5", - "supports-color": "5.2.0" - } - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" - }, - "is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=" - }, - "lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==" - }, - "string-width": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", - "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", - "requires": { - "is-fullwidth-code-point": "2.0.0", - "strip-ansi": "4.0.0" - } - }, - "strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "requires": { - "ansi-regex": "3.0.0" - } - }, - "supports-color": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.2.0.tgz", - "integrity": "sha512-F39vS48la4YvTZUPVeTqsjsFNrvcMwrV3RLZINsmHo+7djCvuUzSIeXOnZ5hmjef4bajL1dNccN+tg5XAliO5Q==", - "requires": { - "has-flag": "3.0.0" - } - } - } - }, - "tapable": { - "version": "0.2.8", - "resolved": "https://registry.npmjs.org/tapable/-/tapable-0.2.8.tgz", - "integrity": "sha1-mTcqXJmb8t8WCvwNdL7U9HlIzSI=", - "dev": true - }, - "tar": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/tar/-/tar-2.2.1.tgz", - "integrity": "sha1-jk0qJWwOIYXGsYrWlK7JaLg8sdE=", - "dev": true, - "requires": { - "block-stream": "0.0.9", - "fstream": "1.0.11", - "inherits": "2.0.3" - } - }, - "term-size": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/term-size/-/term-size-1.2.0.tgz", - "integrity": "sha1-RYuDiH8oj8Vtb/+/rSYuJmOO+mk=", - "dev": true, - "requires": { - "execa": "0.7.0" - } - }, - "text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=" - }, - "throttleit": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/throttleit/-/throttleit-0.0.2.tgz", - "integrity": "sha1-z+34jmDADdlpe2H90qg0OptoDq8=", - "dev": true - }, - "through": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", - "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=" - }, - "through2": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.1.tgz", - "integrity": "sha1-OE51MU1J8y3hLuu4E2uOtrXVnak=", - "dev": true, - "requires": { - "readable-stream": "2.0.6", - "xtend": "4.0.1" - }, - "dependencies": { - "readable-stream": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.0.6.tgz", - "integrity": "sha1-j5A0HmilPMySh4jaz80Rs265t44=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "string_decoder": "0.10.31", - "util-deprecate": "1.0.2" - } - } - } - }, - "thunky": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.0.2.tgz", - "integrity": "sha1-qGLgGOP7HqLsP85dVWBc9X8kc3E=", - "dev": true - }, - "tildify": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/tildify/-/tildify-1.2.0.tgz", - "integrity": "sha1-3OwD9V3Km3qj5bBPIYF+tW5jWIo=", - "dev": true, - "requires": { - "os-homedir": "1.0.2" - } - }, - "time-stamp": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/time-stamp/-/time-stamp-1.1.0.tgz", - "integrity": "sha1-dkpaEa9QVhkhsTPztE5hhofg9cM=", - "dev": true - }, - "timed-out": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/timed-out/-/timed-out-4.0.1.tgz", - "integrity": "sha1-8y6srFoXW+ol1/q1Zas+2HQe9W8=", - "dev": true - }, - "timers-browserify": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-2.0.6.tgz", - "integrity": "sha512-HQ3nbYRAowdVd0ckGFvmJPPCOH/CHleFN/Y0YQCX1DVaB7t+KFvisuyN09fuP8Jtp1CpfSh8O8bMkHbdbPe6Pw==", - "dev": true, - "requires": { - "setimmediate": "1.0.5" - } - }, - "tmp": { - "version": "0.0.31", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.31.tgz", - "integrity": "sha1-jzirlDjhcxXl29izZX6L+yd65Kc=", - "dev": true, - "requires": { - "os-tmpdir": "1.0.2" - } - }, - "to-array": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/to-array/-/to-array-0.1.4.tgz", - "integrity": "sha1-F+bBH3PdTz10zaek/zI46a2b+JA=", - "dev": true - }, - "to-arraybuffer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz", - "integrity": "sha1-fSKbH8xjfkZsoIEYCDanqr/4P0M=", - "dev": true - }, - "to-fast-properties": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", - "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=", - "dev": true - }, - "to-object-path": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", - "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", - "dev": true, - "requires": { - "kind-of": "3.0.4" - } - }, - "to-regex": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.1.tgz", - "integrity": "sha1-FTWL7kosg712N3uh3ASdDxiDeq4=", - "dev": true, - "requires": { - "define-property": "0.2.5", - "extend-shallow": "2.0.1", - "regex-not": "1.0.0" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "0.1.6" - } - }, - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "0.1.1" - } - }, - "is-accessor-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", - "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "dev": true - }, - "is-data-descriptor": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", - "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "is-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", - "integrity": "sha1-Nm2CQN3kh8pRgjsaufB6EKeCUco=", - "dev": true, - "requires": { - "is-accessor-descriptor": "0.1.6", - "is-data-descriptor": "0.1.4", - "kind-of": "5.1.0" - } - }, - "kind-of": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", - "integrity": "sha1-cpyR4thXt6QZofmqZWhcTDP1hF0=", - "dev": true - } - } - }, - "to-regex-range": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz", - "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", - "dev": true, - "requires": { - "is-number": "3.0.0", - "repeat-string": "1.6.1" - }, - "dependencies": { - "is-number": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", - "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", - "dev": true, - "requires": { - "kind-of": "3.0.4" - } - } - } - }, - "touch": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.0.tgz", - "integrity": "sha1-/jZfX3XsntTlaCXgu3bSSrdK+Ds=", - "dev": true, - "requires": { - "nopt": "1.0.10" - }, - "dependencies": { - "nopt": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz", - "integrity": "sha1-bd0hvSoxQXuScn3Vhfim83YI6+4=", - "dev": true, - "requires": { - "abbrev": "1.0.9" - } - } - } - }, - "tough-cookie": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.3.2.tgz", - "integrity": "sha1-8IH3bkyFcg5sN6X6ztc3FQ2EByo=", - "dev": true, - "requires": { - "punycode": "1.4.1" - } - }, - "trim-newlines": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-1.0.0.tgz", - "integrity": "sha1-WIeWa7WCpFA6QetST301ARgVphM=", - "dev": true - }, - "trim-right": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", - "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", - "dev": true - }, - "true-case-path": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/true-case-path/-/true-case-path-1.0.2.tgz", - "integrity": "sha1-fskRMJJHZsf1c74wIMNPj9/QDWI=", - "dev": true, - "requires": { - "glob": "6.0.4" - }, - "dependencies": { - "glob": { - "version": "6.0.4", - "resolved": "https://registry.npmjs.org/glob/-/glob-6.0.4.tgz", - "integrity": "sha1-DwiGD2oVUSey+t1PnOJLGqtuTSI=", - "dev": true, - "requires": { - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.3", - "once": "1.4.0", - "path-is-absolute": "1.0.1" - } - } - } - }, - "tty-browserify": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", - "integrity": "sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=", - "dev": true - }, - "tunnel-agent": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.4.3.tgz", - "integrity": "sha1-Y3PbdpCf5XDgjXNYM2Xtgop07us=", - "dev": true - }, - "tweetnacl": { - "version": "0.14.3", - "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.3.tgz", - "integrity": "sha1-PaOC9nDyXe1417PReSEZvKC3Ey0=", - "dev": true, - "optional": true - }, - "type-check": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", - "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", - "requires": { - "prelude-ls": "1.1.2" - } - }, - "type-is": { - "version": "1.6.15", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.15.tgz", - "integrity": "sha1-yrEPtJCeRByChC6v4a1kbIGARBA=", - "dev": true, - "requires": { - "media-typer": "0.3.0", - "mime-types": "2.1.17" - }, - "dependencies": { - "mime-db": { - "version": "1.30.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.30.0.tgz", - "integrity": "sha1-dMZD2i3Z1qRTmZY0ZbJtXKfXHwE=", - "dev": true - }, - "mime-types": { - "version": "2.1.17", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.17.tgz", - "integrity": "sha1-Cdejk/A+mVp5+K+Fe3Cp4KsWVXo=", - "dev": true, - "requires": { - "mime-db": "1.30.0" - } - } - } - }, - "typedarray": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", - "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=" - }, - "uglify-js": { - "version": "2.7.4", - "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.7.4.tgz", - "integrity": "sha1-opWg3hK2plDAMcQN6w3ECxRWi9I=", - "dev": true, - "requires": { - "async": "0.2.10", - "source-map": "0.5.6", - "uglify-to-browserify": "1.0.2", - "yargs": "3.10.0" - }, - "dependencies": { - "async": { - "version": "0.2.10", - "resolved": "https://registry.npmjs.org/async/-/async-0.2.10.tgz", - "integrity": "sha1-trvgsGdLnXGXCMo43owjfLUmw9E=", - "dev": true - }, - "camelcase": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz", - "integrity": "sha1-m7UwTS4LVmmLLHWLCKPqqdqlijk=", - "dev": true - }, - "cliui": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-2.1.0.tgz", - "integrity": "sha1-S0dXYP+AJkx2LDoXGQMukcf+oNE=", - "dev": true, - "requires": { - "center-align": "0.1.3", - "right-align": "0.1.3", - "wordwrap": "0.0.2" - } - }, - "window-size": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.1.0.tgz", - "integrity": "sha1-VDjNLqk7IC76Ohn+iIeu58lPnJ0=", - "dev": true - }, - "yargs": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz", - "integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=", - "dev": true, - "requires": { - "camelcase": "1.2.1", - "cliui": "2.1.0", - "decamelize": "1.2.0", - "window-size": "0.1.0" - } - } - } - }, - "uglify-to-browserify": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz", - "integrity": "sha1-bgkk1r2mta/jSeOabWMoUKD4grc=", - "dev": true - }, - "uglifyjs-webpack-plugin": { - "version": "0.4.6", - "resolved": "https://registry.npmjs.org/uglifyjs-webpack-plugin/-/uglifyjs-webpack-plugin-0.4.6.tgz", - "integrity": "sha1-uVH0q7a9YX5m9j64kUmOORdj4wk=", - "dev": true, - "requires": { - "source-map": "0.5.6", - "uglify-js": "2.8.29", - "webpack-sources": "1.1.0" - }, - "dependencies": { - "camelcase": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz", - "integrity": "sha1-m7UwTS4LVmmLLHWLCKPqqdqlijk=", - "dev": true - }, - "cliui": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-2.1.0.tgz", - "integrity": "sha1-S0dXYP+AJkx2LDoXGQMukcf+oNE=", - "dev": true, - "requires": { - "center-align": "0.1.3", - "right-align": "0.1.3", - "wordwrap": "0.0.2" - } - }, - "uglify-js": { - "version": "2.8.29", - "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.8.29.tgz", - "integrity": "sha1-KcVzMUgFe7Th913zW3qcty5qWd0=", - "dev": true, - "requires": { - "source-map": "0.5.6", - "uglify-to-browserify": "1.0.2", - "yargs": "3.10.0" - } - }, - "yargs": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz", - "integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=", - "dev": true, - "requires": { - "camelcase": "1.2.1", - "cliui": "2.1.0", - "decamelize": "1.2.0", - "window-size": "0.1.0" - } - } - } - }, - "ultron": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/ultron/-/ultron-1.0.2.tgz", - "integrity": "sha1-rOEWq1V80Zc4ak6I9GhTeMiy5Po=", - "dev": true - }, - "unc-path-regex": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/unc-path-regex/-/unc-path-regex-0.1.2.tgz", - "integrity": "sha1-5z3T17DXxe2G+6xrCufYxqadUPo=", - "dev": true - }, - "undefsafe": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-0.0.3.tgz", - "integrity": "sha1-7Mo6A+VrmvFzhbqsgSrIO5lKli8=", - "dev": true - }, - "union-value": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.0.tgz", - "integrity": "sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=", - "dev": true, - "requires": { - "arr-union": "3.1.0", - "get-value": "2.0.6", - "is-extendable": "0.1.1", - "set-value": "0.4.3" - }, - "dependencies": { - "arr-union": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", - "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", - "dev": true - }, - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "0.1.1" - } - }, - "set-value": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/set-value/-/set-value-0.4.3.tgz", - "integrity": "sha1-fbCPnT0i3H945Trzw79GZuzfzPE=", - "dev": true, - "requires": { - "extend-shallow": "2.0.1", - "is-extendable": "0.1.1", - "is-plain-object": "2.0.4", - "to-object-path": "0.3.0" - } - } - } - }, - "unique-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unique-stream/-/unique-stream-1.0.0.tgz", - "integrity": "sha1-1ZpKdUJ0R9mqbJHnAmP40mpLEEs=", - "dev": true - }, - "unique-string": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-1.0.0.tgz", - "integrity": "sha1-nhBXzKhRq7kzmPizOuGHuZyuwRo=", - "dev": true, - "requires": { - "crypto-random-string": "1.0.0" - } - }, - "universalify": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.1.tgz", - "integrity": "sha1-+nG63UQ3r0wUiEHjs7Fl+enlkLc=" - }, - "unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=", - "dev": true - }, - "unset-value": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", - "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", - "dev": true, - "requires": { - "has-value": "0.3.1", - "isobject": "3.0.1" - }, - "dependencies": { - "has-value": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz", - "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", - "dev": true, - "requires": { - "get-value": "2.0.6", - "has-values": "0.1.4", - "isobject": "2.1.0" - }, - "dependencies": { - "isobject": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", - "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", - "dev": true, - "requires": { - "isarray": "1.0.0" - } - } - } - }, - "has-values": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", - "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", - "dev": true - }, - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - } - } - }, - "unzip-response": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/unzip-response/-/unzip-response-2.0.1.tgz", - "integrity": "sha1-0vD3N9FrBhXnKmk17QQhRXLVb5c=", - "dev": true - }, - "update-notifier": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/update-notifier/-/update-notifier-2.2.0.tgz", - "integrity": "sha1-G1g3z5DAc22IYncytmHBOPht5y8=", - "dev": true, - "requires": { - "boxen": "1.2.1", - "chalk": "1.1.3", - "configstore": "3.1.1", - "import-lazy": "2.1.0", - "is-npm": "1.0.0", - "latest-version": "3.1.0", - "semver-diff": "2.1.0", - "xdg-basedir": "3.0.0" - } - }, - "upper-case": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/upper-case/-/upper-case-1.1.3.tgz", - "integrity": "sha1-9rRQHC7EzdJrp4vnIilh3ndiFZg=", - "dev": true - }, - "urix": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", - "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", - "dev": true - }, - "url": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", - "integrity": "sha1-ODjpfPxgUh63PFJajlW/3Z4uKPE=", - "dev": true, - "requires": { - "punycode": "1.3.2", - "querystring": "0.2.0" - }, - "dependencies": { - "punycode": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", - "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=", - "dev": true - } - } - }, - "url-parse": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.2.0.tgz", - "integrity": "sha512-DT1XbYAfmQP65M/mE6OALxmXzZ/z1+e5zk2TcSKe/KiYbNGZxgtttzC0mR/sjopbpOXcbniq7eIKmocJnUWlEw==", - "dev": true, - "requires": { - "querystringify": "1.0.0", - "requires-port": "1.0.0" - }, - "dependencies": { - "querystringify": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-1.0.0.tgz", - "integrity": "sha1-YoYkIRLFtxL6ZU5SZlK/ahP/Bcs=", - "dev": true - } - } - }, - "url-parse-lax": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-1.0.0.tgz", - "integrity": "sha1-evjzA2Rem9eaJy56FKxovAYJ2nM=", - "dev": true, - "requires": { - "prepend-http": "1.0.4" - } - }, - "use": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/use/-/use-2.0.2.tgz", - "integrity": "sha1-riig1y+TvyJCKhii43mZMRLeyOg=", - "dev": true, - "requires": { - "define-property": "0.2.5", - "isobject": "3.0.1", - "lazy-cache": "2.0.2" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "0.1.6" - } - }, - "is-accessor-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", - "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "dev": true - }, - "is-data-descriptor": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", - "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "is-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", - "integrity": "sha1-Nm2CQN3kh8pRgjsaufB6EKeCUco=", - "dev": true, - "requires": { - "is-accessor-descriptor": "0.1.6", - "is-data-descriptor": "0.1.4", - "kind-of": "5.1.0" - } - }, - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true - }, - "kind-of": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", - "integrity": "sha1-cpyR4thXt6QZofmqZWhcTDP1hF0=", - "dev": true - }, - "lazy-cache": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-2.0.2.tgz", - "integrity": "sha1-uRkKT5EzVGlIQIWfio9whNiCImQ=", - "dev": true, - "requires": { - "set-getter": "0.1.0" - } - } - } - }, - "useragent": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/useragent/-/useragent-2.3.0.tgz", - "integrity": "sha1-IX+UOtVAyyEoZYqyP8lg9qiMmXI=", - "dev": true, - "requires": { - "lru-cache": "4.1.1", - "tmp": "0.0.31" - }, - "dependencies": { - "lru-cache": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.1.tgz", - "integrity": "sha512-q4spe4KTfsAS1SUHLO0wz8Qiyf1+vMIAgpRYioFYDMNqKfHQbg+AVDH3i4fvpl71/P1L0dBl+fQi+P37UYf0ew==", - "dev": true, - "requires": { - "pseudomap": "1.0.2", - "yallist": "2.1.2" - } - }, - "yallist": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", - "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", - "dev": true - } - } - }, - "util": { - "version": "0.10.3", - "resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz", - "integrity": "sha1-evsa/lCAUkZInj23/g7TeTNqwPk=", - "dev": true, - "requires": { - "inherits": "2.0.1" - }, - "dependencies": { - "inherits": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", - "integrity": "sha1-sX0I0ya0Qj5Wjv9xn5GwscvfafE=", - "dev": true - } - } - }, - "util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" - }, - "utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=", - "dev": true - }, - "v8flags": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/v8flags/-/v8flags-2.1.1.tgz", - "integrity": "sha1-qrGh+jDUX4jdMhFIh1rALAtV5bQ=", - "dev": true, - "requires": { - "user-home": "1.1.1" - }, - "dependencies": { - "user-home": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/user-home/-/user-home-1.1.1.tgz", - "integrity": "sha1-K1viOjK2Onyd640PKNSFcko98ZA=", - "dev": true - } - } - }, - "validate-npm-package-license": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.1.tgz", - "integrity": "sha1-KAS6vnEq0zeUWaz74kdGqywwP7w=", - "dev": true, - "requires": { - "spdx-correct": "1.0.2", - "spdx-expression-parse": "1.0.4" - } - }, - "validator": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/validator/-/validator-6.2.1.tgz", - "integrity": "sha1-vFdbeNFb6y4zimZbqVMMf0Ce9mc=" - }, - "vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=", - "dev": true - }, - "verror": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/verror/-/verror-1.3.6.tgz", - "integrity": "sha1-z/XfEpRtKX0rqu+qJoniW+AcAFw=", - "dev": true, - "requires": { - "extsprintf": "1.0.2" - } - }, - "vinyl": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-0.5.3.tgz", - "integrity": "sha1-sEVbOPxeDPMNQyUTLkYZcMIJHN4=", - "dev": true, - "requires": { - "clone": "1.0.2", - "clone-stats": "0.0.1", - "replace-ext": "0.0.1" - } - }, - "vinyl-fs": { - "version": "0.3.14", - "resolved": "https://registry.npmjs.org/vinyl-fs/-/vinyl-fs-0.3.14.tgz", - "integrity": "sha1-mmhRzhysHBzqX+hsCTHWIMLPqeY=", - "dev": true, - "requires": { - "defaults": "1.0.3", - "glob-stream": "3.1.18", - "glob-watcher": "0.0.6", - "graceful-fs": "3.0.11", - "mkdirp": "0.5.1", - "strip-bom": "1.0.0", - "through2": "0.6.5", - "vinyl": "0.4.6" - }, - "dependencies": { - "clone": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/clone/-/clone-0.2.0.tgz", - "integrity": "sha1-xhJqkK1Pctv1rNskPMN3JP6T/B8=", - "dev": true - }, - "graceful-fs": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-3.0.11.tgz", - "integrity": "sha1-dhPHeKGv6mLyXGMKCG1/Osu92Bg=", - "dev": true, - "requires": { - "natives": "1.1.1" - } - }, - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "dev": true - }, - "readable-stream": { - "version": "1.0.34", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", - "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", - "dev": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "0.0.1", - "string_decoder": "0.10.31" - } - }, - "strip-bom": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-1.0.0.tgz", - "integrity": "sha1-hbiGLzhEtabV7IRnqTWYFzo295Q=", - "dev": true, - "requires": { - "first-chunk-stream": "1.0.0", - "is-utf8": "0.2.1" - } - }, - "through2": { - "version": "0.6.5", - "resolved": "https://registry.npmjs.org/through2/-/through2-0.6.5.tgz", - "integrity": "sha1-QaucZ7KdVyCQcUEOHXp6lozTrUg=", - "dev": true, - "requires": { - "readable-stream": "1.0.34", - "xtend": "4.0.1" - } - }, - "vinyl": { - "version": "0.4.6", - "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-0.4.6.tgz", - "integrity": "sha1-LzVsh6VQolVGHza76ypbqL94SEc=", - "dev": true, - "requires": { - "clone": "0.2.0", - "clone-stats": "0.0.1" - } - } - } - }, - "vm-browserify": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-0.0.4.tgz", - "integrity": "sha1-XX6kW7755Kb/ZflUOOCofDV9WnM=", - "dev": true, - "requires": { - "indexof": "0.0.1" - } - }, - "void-elements": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-2.0.1.tgz", - "integrity": "sha1-wGavtYK7HLQSjWDqkjkulNXp2+w=", - "dev": true - }, - "watchpack": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-1.4.0.tgz", - "integrity": "sha1-ShRyvLuVK9Cpu0A2gB+VTfs5+qw=", - "dev": true, - "requires": { - "async": "2.1.2", - "chokidar": "1.7.0", - "graceful-fs": "4.1.10" - }, - "dependencies": { - "chokidar": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-1.7.0.tgz", - "integrity": "sha1-eY5ol3gVHIB2tLNg5e3SjNortGg=", - "dev": true, - "requires": { - "anymatch": "1.3.0", - "async-each": "1.0.1", - "fsevents": "1.1.3", - "glob-parent": "2.0.0", - "inherits": "2.0.3", - "is-binary-path": "1.0.1", - "is-glob": "2.0.1", - "path-is-absolute": "1.0.1", - "readdirp": "2.1.0" - } - } - } - }, - "wbuf": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/wbuf/-/wbuf-1.7.2.tgz", - "integrity": "sha1-1pe5nx9ZUS3ydRvkJ2nBWAtYAf4=", - "dev": true, - "requires": { - "minimalistic-assert": "1.0.0" - } - }, - "webpack": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-3.10.0.tgz", - "integrity": "sha512-fxxKXoicjdXNUMY7LIdY89tkJJJ0m1Oo8PQutZ5rLgWbV5QVKI15Cn7+/IHnRTd3vfKfiwBx6SBqlorAuNA8LA==", - "dev": true, - "requires": { - "acorn": "5.4.1", - "acorn-dynamic-import": "2.0.2", - "ajv": "5.5.2", - "ajv-keywords": "2.1.1", - "async": "2.1.2", - "enhanced-resolve": "3.4.1", - "escope": "3.6.0", - "interpret": "1.0.1", - "json-loader": "0.5.7", - "json5": "0.5.1", - "loader-runner": "2.3.0", - "loader-utils": "1.1.0", - "memory-fs": "0.4.1", - "mkdirp": "0.5.1", - "node-libs-browser": "2.1.0", - "source-map": "0.5.6", - "supports-color": "4.5.0", - "tapable": "0.2.8", - "uglifyjs-webpack-plugin": "0.4.6", - "watchpack": "1.4.0", - "webpack-sources": "1.1.0", - "yargs": "8.0.2" - }, - "dependencies": { - "ajv": { - "version": "5.5.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz", - "integrity": "sha1-c7Xuyj+rZT49P5Qis0GtQiBdyWU=", - "dev": true, - "requires": { - "co": "4.6.0", - "fast-deep-equal": "1.0.0", - "fast-json-stable-stringify": "2.0.0", - "json-schema-traverse": "0.3.1" - } - }, - "ajv-keywords": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-2.1.1.tgz", - "integrity": "sha1-YXmX/F9gV2iUxDX5QNgZ4TW4B2I=", - "dev": true - }, - "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", - "dev": true - }, - "camelcase": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", - "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=", - "dev": true - }, - "find-up": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", - "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", - "dev": true, - "requires": { - "locate-path": "2.0.0" - } - }, - "is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", - "dev": true - }, - "json5": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", - "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=", - "dev": true - }, - "load-json-file": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz", - "integrity": "sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg=", - "dev": true, - "requires": { - "graceful-fs": "4.1.10", - "parse-json": "2.2.0", - "pify": "2.3.0", - "strip-bom": "3.0.0" - } - }, - "loader-utils": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.1.0.tgz", - "integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=", - "dev": true, - "requires": { - "big.js": "3.1.3", - "emojis-list": "2.1.0", - "json5": "0.5.1" - } - }, - "os-locale": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-2.1.0.tgz", - "integrity": "sha512-3sslG3zJbEYcaC4YVAvDorjGxc7tv6KVATnLPZONiljsUncvihe9BQoVCEs0RZ1kmf4Hk9OBqlZfJZWI4GanKA==", - "dev": true, - "requires": { - "execa": "0.7.0", - "lcid": "1.0.0", - "mem": "1.1.0" - } - }, - "path-type": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-2.0.0.tgz", - "integrity": "sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM=", - "dev": true, - "requires": { - "pify": "2.3.0" - } - }, - "read-pkg": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz", - "integrity": "sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg=", - "dev": true, - "requires": { - "load-json-file": "2.0.0", - "normalize-package-data": "2.3.5", - "path-type": "2.0.0" - } - }, - "read-pkg-up": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-2.0.0.tgz", - "integrity": "sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4=", - "dev": true, - "requires": { - "find-up": "2.1.0", - "read-pkg": "2.0.0" - } - }, - "string-width": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", - "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", - "dev": true, - "requires": { - "is-fullwidth-code-point": "2.0.0", - "strip-ansi": "4.0.0" - } - }, - "strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "dev": true, - "requires": { - "ansi-regex": "3.0.0" - } - }, - "strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", - "dev": true - }, - "supports-color": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-4.5.0.tgz", - "integrity": "sha1-vnoN5ITexcXN34s9WRJQRJEvY1s=", - "dev": true, - "requires": { - "has-flag": "2.0.0" - } - }, - "which-module": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", - "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", - "dev": true - }, - "yargs": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-8.0.2.tgz", - "integrity": "sha1-YpmpBVsc78lp/355wdkY3Osiw2A=", - "dev": true, - "requires": { - "camelcase": "4.1.0", - "cliui": "3.2.0", - "decamelize": "1.2.0", - "get-caller-file": "1.0.2", - "os-locale": "2.1.0", - "read-pkg-up": "2.0.0", - "require-directory": "2.1.1", - "require-main-filename": "1.0.1", - "set-blocking": "2.0.0", - "string-width": "2.1.1", - "which-module": "2.0.0", - "y18n": "3.2.1", - "yargs-parser": "7.0.0" - } - }, - "yargs-parser": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-7.0.0.tgz", - "integrity": "sha1-jQrELxbqVd69MyyvTEA4s+P139k=", - "dev": true, - "requires": { - "camelcase": "4.1.0" - } - } - } - }, - "webpack-dev-middleware": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-1.12.2.tgz", - "integrity": "sha512-FCrqPy1yy/sN6U/SaEZcHKRXGlqU0DUaEBL45jkUYoB8foVb6wCnbIJ1HKIx+qUFTW+3JpVcCJCxZ8VATL4e+A==", - "dev": true, - "requires": { - "memory-fs": "0.4.1", - "mime": "1.6.0", - "path-is-absolute": "1.0.1", - "range-parser": "1.2.0", - "time-stamp": "2.0.0" - }, - "dependencies": { - "mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", - "dev": true - }, - "time-stamp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/time-stamp/-/time-stamp-2.0.0.tgz", - "integrity": "sha1-lcakRTDhW6jW9KPsuMOj+sRto1c=", - "dev": true - } - } - }, - "webpack-dev-server": { - "version": "2.11.1", - "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-2.11.1.tgz", - "integrity": "sha512-ombhu5KsO/85sVshIDTyQ5HF3xjZR3N0sf5Ao6h3vFwpNyzInEzA1GV3QPVjTMLTNckp8PjfG1PFGznzBwS5lg==", - "dev": true, - "requires": { - "ansi-html": "0.0.7", - "array-includes": "3.0.3", - "bonjour": "3.5.0", - "chokidar": "2.0.0", - "compression": "1.7.1", - "connect-history-api-fallback": "1.5.0", - "debug": "3.1.0", - "del": "3.0.0", - "express": "4.16.2", - "html-entities": "1.2.1", - "http-proxy-middleware": "0.17.4", - "import-local": "1.0.0", - "internal-ip": "1.2.0", - "ip": "1.1.5", - "killable": "1.0.0", - "loglevel": "1.6.1", - "opn": "5.2.0", - "portfinder": "1.0.13", - "selfsigned": "1.10.2", - "serve-index": "1.9.1", - "sockjs": "0.3.19", - "sockjs-client": "1.1.4", - "spdy": "3.4.7", - "strip-ansi": "3.0.1", - "supports-color": "5.1.0", - "webpack-dev-middleware": "1.12.2", - "yargs": "6.6.0" - }, - "dependencies": { - "anymatch": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz", - "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==", - "dev": true, - "requires": { - "micromatch": "3.1.5", - "normalize-path": "2.1.1" - } }, "arr-diff": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", - "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", - "dev": true + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", + "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", + "dev": true + }, + "arr-filter": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/arr-filter/-/arr-filter-1.1.2.tgz", + "integrity": "sha1-Q/3d0JHo7xGqTEXZzcGOLf8XEe4=", + "dev": true, + "requires": { + "make-iterator": "^1.0.0" + } }, "arr-flatten": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", - "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", - "dev": true + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", + "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", + "dev": true + }, + "arr-map": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/arr-map/-/arr-map-2.0.2.tgz", + "integrity": "sha1-Onc0X/wc814qkYJWAfnljy4kysQ=", + "dev": true, + "requires": { + "make-iterator": "^1.0.0" + } + }, + "arr-union": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", + "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", + "dev": true + }, + "array-differ": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-1.0.0.tgz", + "integrity": "sha1-7/UuN1gknTO+QCuLuOVkuytdQDE=", + "dev": true + }, + "array-each": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/array-each/-/array-each-1.0.1.tgz", + "integrity": "sha1-p5SvDAWrF1KEbudTofIRoFugxE8=", + "dev": true + }, + "array-equal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/array-equal/-/array-equal-1.0.0.tgz", + "integrity": "sha1-jCpe8kcv2ep0KwTHenUJO6J1fJM=", + "dev": true + }, + "array-find-index": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", + "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=", + "dev": true + }, + "array-flatten": { + "version": "1.1.1", + "resolved": "http://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" + }, + "array-initial": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/array-initial/-/array-initial-1.1.0.tgz", + "integrity": "sha1-L6dLJnOTccOUe9enrcc74zSz15U=", + "dev": true, + "requires": { + "array-slice": "^1.0.0", + "is-number": "^4.0.0" + }, + "dependencies": { + "is-number": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-4.0.0.tgz", + "integrity": "sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ==", + "dev": true + } + } + }, + "array-last": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/array-last/-/array-last-1.3.0.tgz", + "integrity": "sha512-eOCut5rXlI6aCOS7Z7kCplKRKyiFQ6dHFBem4PwlwKeNFk2/XxTrhRh5T9PyaEWGy/NHTZWbY+nsZlNFJu9rYg==", + "dev": true, + "requires": { + "is-number": "^4.0.0" + }, + "dependencies": { + "is-number": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-4.0.0.tgz", + "integrity": "sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ==", + "dev": true + } + } + }, + "array-slice": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-1.1.0.tgz", + "integrity": "sha512-B1qMD3RBP7O8o0H2KbrXDyB0IccejMF15+87Lvlor12ONPRHP6gTjXMNkt/d3ZuOGbAe66hFmaCfECI24Ufp6w==", + "dev": true + }, + "array-sort": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/array-sort/-/array-sort-1.0.0.tgz", + "integrity": "sha512-ihLeJkonmdiAsD7vpgN3CRcx2J2S0TiYW+IS/5zHBI7mKUq3ySvBdzzBfD236ubDBQFiiyG3SWCPc+msQ9KoYg==", + "dev": true, + "requires": { + "default-compare": "^1.0.0", + "get-value": "^2.0.6", + "kind-of": "^5.0.2" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "array-union": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", + "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", + "dev": true, + "requires": { + "array-uniq": "^1.0.1" + } + }, + "array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=", + "dev": true }, "array-unique": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", - "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", - "dev": true + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", + "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", + "dev": true + }, + "arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" + }, + "asn1": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", + "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", + "requires": { + "safer-buffer": "~2.1.0" + } + }, + "asn1.js": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.10.1.tgz", + "integrity": "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw==", + "dev": true, + "requires": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "assert": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/assert/-/assert-1.5.0.tgz", + "integrity": "sha512-EDsgawzwoun2CZkCgtxJbv392v4nbk9XDD06zI+kQYoBM/3RBWLlEyJARDOmhAAosBjWACEkKL6S+lIZtcAubA==", + "dev": true, + "requires": { + "object-assign": "^4.1.1", + "util": "0.10.3" + }, + "dependencies": { + "inherits": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "integrity": "sha1-sX0I0ya0Qj5Wjv9xn5GwscvfafE=", + "dev": true + }, + "util": { + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz", + "integrity": "sha1-evsa/lCAUkZInj23/g7TeTNqwPk=", + "dev": true, + "requires": { + "inherits": "2.0.1" + } + } + } + }, + "assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=" + }, + "assign-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", + "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", + "dev": true + }, + "ast-types": { + "version": "0.9.6", + "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.9.6.tgz", + "integrity": "sha1-ECyenpAF0+fjgpvwxPok7oYu6bk=", + "dev": true + }, + "astral-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz", + "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==", + "dev": true + }, + "async": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", + "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" + }, + "async-done": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/async-done/-/async-done-1.3.2.tgz", + "integrity": "sha512-uYkTP8dw2og1tu1nmza1n1CMW0qb8gWWlwqMmLb7MhBVs4BXrFziT6HXUd+/RlRA/i4H9AkofYloUbs1fwMqlw==", + "dev": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.2", + "process-nextick-args": "^2.0.0", + "stream-exhaust": "^1.0.1" + } + }, + "async-each": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.3.tgz", + "integrity": "sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ==", + "dev": true + }, + "async-foreach": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/async-foreach/-/async-foreach-0.1.3.tgz", + "integrity": "sha1-NhIfhFwFeBct5Bmpfb6x0W7DRUI=", + "dev": true + }, + "async-hook-jl": { + "version": "1.7.6", + "resolved": "https://registry.npmjs.org/async-hook-jl/-/async-hook-jl-1.7.6.tgz", + "integrity": "sha512-gFaHkFfSxTjvoxDMYqDuGHlcRyUuamF8s+ZTtJdDzqjws4mCt7v0vuV79/E2Wr2/riMQgtG4/yUtXWs1gZ7JMg==", + "requires": { + "stack-chain": "^1.3.7" + } + }, + "async-limiter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", + "integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==", + "dev": true + }, + "async-settle": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-settle/-/async-settle-1.0.0.tgz", + "integrity": "sha1-HQqRS7Aldb7IqPOnTlCA9yssDGs=", + "dev": true, + "requires": { + "async-done": "^1.2.2" + } + }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" + }, + "atob": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", + "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", + "dev": true + }, + "aws-sdk": { + "version": "2.487.0", + "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.487.0.tgz", + "integrity": "sha512-bdImYaIzvRL4nn8DEvI39VCrQYPDeC/PTYg++EBobhaFh8ksbsTzBnIFAn5IxtlRsXWUzaZVyOgRTGqiiS6YHA==", + "requires": { + "buffer": "4.9.1", + "events": "1.1.1", + "ieee754": "1.1.8", + "jmespath": "0.15.0", + "querystring": "0.2.0", + "sax": "1.2.1", + "url": "0.10.3", + "uuid": "3.3.2", + "xml2js": "0.4.19" + }, + "dependencies": { + "sax": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.1.tgz", + "integrity": "sha1-e45lYZCyKOgaZq6nSEgNgozS03o=" + } + } + }, + "aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=" + }, + "aws4": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.8.0.tgz", + "integrity": "sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ==" + }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "dev": true, + "requires": { + "chalk": "^1.1.3", + "esutils": "^2.0.2", + "js-tokens": "^3.0.2" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + } + } + }, + "babel-helper-call-delegate": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-call-delegate/-/babel-helper-call-delegate-6.24.1.tgz", + "integrity": "sha1-7Oaqzdx25Bw0YfiL/Fdb0Nqi340=", + "dev": true, + "requires": { + "babel-helper-hoist-variables": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" + } + }, + "babel-helper-define-map": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-helper-define-map/-/babel-helper-define-map-6.26.0.tgz", + "integrity": "sha1-pfVtq0GiX5fstJjH66ypgZ+Vvl8=", + "dev": true, + "requires": { + "babel-helper-function-name": "^6.24.1", + "babel-runtime": "^6.26.0", + "babel-types": "^6.26.0", + "lodash": "^4.17.4" + } + }, + "babel-helper-function-name": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-function-name/-/babel-helper-function-name-6.24.1.tgz", + "integrity": "sha1-00dbjAPtmCQqJbSDUasYOZ01gKk=", + "dev": true, + "requires": { + "babel-helper-get-function-arity": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" + } + }, + "babel-helper-get-function-arity": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-get-function-arity/-/babel-helper-get-function-arity-6.24.1.tgz", + "integrity": "sha1-j3eCqpNAfEHTqlCQj4mwMbG2hT0=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-helper-hoist-variables": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-hoist-variables/-/babel-helper-hoist-variables-6.24.1.tgz", + "integrity": "sha1-HssnaJydJVE+rbyZFKc/VAi+enY=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-helper-optimise-call-expression": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-optimise-call-expression/-/babel-helper-optimise-call-expression-6.24.1.tgz", + "integrity": "sha1-96E0J7qfc/j0+pk8VKl4gtEkQlc=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-helper-regex": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-helper-regex/-/babel-helper-regex-6.26.0.tgz", + "integrity": "sha1-MlxZ+QL4LyS3T6zu0DY5VPZJXnI=", + "dev": true, + "requires": { + "babel-runtime": "^6.26.0", + "babel-types": "^6.26.0", + "lodash": "^4.17.4" + } + }, + "babel-helper-replace-supers": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-helper-replace-supers/-/babel-helper-replace-supers-6.24.1.tgz", + "integrity": "sha1-v22/5Dk40XNpohPKiov3S2qQqxo=", + "dev": true, + "requires": { + "babel-helper-optimise-call-expression": "^6.24.1", + "babel-messages": "^6.23.0", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" + } + }, + "babel-jest": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-24.9.0.tgz", + "integrity": "sha512-ntuddfyiN+EhMw58PTNL1ph4C9rECiQXjI4nMMBKBaNjXvqLdkXpPRcMSr4iyBrJg/+wz9brFUD6RhOAT6r4Iw==", + "dev": true, + "requires": { + "@jest/transform": "^24.9.0", + "@jest/types": "^24.9.0", + "@types/babel__core": "^7.1.0", + "babel-plugin-istanbul": "^5.1.0", + "babel-preset-jest": "^24.9.0", + "chalk": "^2.4.2", + "slash": "^2.0.0" + } + }, + "babel-loader": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.0.6.tgz", + "integrity": "sha512-4BmWKtBOBm13uoUwd08UwjZlaw3O9GWf456R9j+5YykFZ6LUIjIKLc0zEZf+hauxPOJs96C8k6FvYD09vWzhYw==", + "dev": true, + "requires": { + "find-cache-dir": "^2.0.0", + "loader-utils": "^1.0.2", + "mkdirp": "^0.5.1", + "pify": "^4.0.1" + } + }, + "babel-messages": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz", + "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-check-es2015-constants": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-check-es2015-constants/-/babel-plugin-check-es2015-constants-6.22.0.tgz", + "integrity": "sha1-NRV7EBQm/S/9PaP3XH0ekYNbv4o=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-dynamic-import-node": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/babel-plugin-dynamic-import-node/-/babel-plugin-dynamic-import-node-2.3.0.tgz", + "integrity": "sha512-o6qFkpeQEBxcqt0XYlWzAVxNCSCZdUgcR8IRlhD/8DylxjjO4foPcvTW0GGKa/cVt3rvxZ7o5ippJ+/0nvLhlQ==", + "dev": true, + "requires": { + "object.assign": "^4.1.0" + } + }, + "babel-plugin-istanbul": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-5.2.0.tgz", + "integrity": "sha512-5LphC0USA8t4i1zCtjbbNb6jJj/9+X6P37Qfirc/70EQ34xKlMW+a1RHGwxGI+SwWpNwZ27HqvzAobeqaXwiZw==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0", + "find-up": "^3.0.0", + "istanbul-lib-instrument": "^3.3.0", + "test-exclude": "^5.2.3" + } + }, + "babel-plugin-jest-hoist": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-24.9.0.tgz", + "integrity": "sha512-2EMA2P8Vp7lG0RAzr4HXqtYwacfMErOuv1U3wrvxHX6rD1sV6xS3WXG3r8TRQ2r6w8OhvSdWt+z41hQNwNm3Xw==", + "dev": true, + "requires": { + "@types/babel__traverse": "^7.0.6" + } + }, + "babel-plugin-transform-es2015-arrow-functions": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-arrow-functions/-/babel-plugin-transform-es2015-arrow-functions-6.22.0.tgz", + "integrity": "sha1-RSaSy3EdX3ncf4XkQM5BufJE0iE=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-block-scoped-functions": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-block-scoped-functions/-/babel-plugin-transform-es2015-block-scoped-functions-6.22.0.tgz", + "integrity": "sha1-u8UbSflk1wy42OC5ToICRs46YUE=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-block-scoping": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-block-scoping/-/babel-plugin-transform-es2015-block-scoping-6.26.0.tgz", + "integrity": "sha1-1w9SmcEwjQXBL0Y4E7CgnnOxiV8=", + "dev": true, + "requires": { + "babel-runtime": "^6.26.0", + "babel-template": "^6.26.0", + "babel-traverse": "^6.26.0", + "babel-types": "^6.26.0", + "lodash": "^4.17.4" + } + }, + "babel-plugin-transform-es2015-classes": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-classes/-/babel-plugin-transform-es2015-classes-6.24.1.tgz", + "integrity": "sha1-WkxYpQyclGHlZLSyo7+ryXolhNs=", + "dev": true, + "requires": { + "babel-helper-define-map": "^6.24.1", + "babel-helper-function-name": "^6.24.1", + "babel-helper-optimise-call-expression": "^6.24.1", + "babel-helper-replace-supers": "^6.24.1", + "babel-messages": "^6.23.0", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-computed-properties": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-computed-properties/-/babel-plugin-transform-es2015-computed-properties-6.24.1.tgz", + "integrity": "sha1-b+Ko0WiV1WNPTNmZttNICjCBWbM=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-destructuring": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-destructuring/-/babel-plugin-transform-es2015-destructuring-6.23.0.tgz", + "integrity": "sha1-mXux8auWf2gtKwh2/jWNYOdlxW0=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-duplicate-keys": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-duplicate-keys/-/babel-plugin-transform-es2015-duplicate-keys-6.24.1.tgz", + "integrity": "sha1-c+s9MQypaePvnskcU3QabxV2Qj4=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-for-of": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-for-of/-/babel-plugin-transform-es2015-for-of-6.23.0.tgz", + "integrity": "sha1-9HyVsrYT3x0+zC/bdXNiPHUkhpE=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-function-name": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-function-name/-/babel-plugin-transform-es2015-function-name-6.24.1.tgz", + "integrity": "sha1-g0yJhTvDaxrw86TF26qU/Y6sqos=", + "dev": true, + "requires": { + "babel-helper-function-name": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-literals": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-literals/-/babel-plugin-transform-es2015-literals-6.22.0.tgz", + "integrity": "sha1-T1SgLWzWbPkVKAAZox0xklN3yi4=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-modules-amd": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-modules-amd/-/babel-plugin-transform-es2015-modules-amd-6.24.1.tgz", + "integrity": "sha1-Oz5UAXI5hC1tGcMBHEvS8AoA0VQ=", + "dev": true, + "requires": { + "babel-plugin-transform-es2015-modules-commonjs": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-modules-commonjs": { + "version": "6.26.2", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-modules-commonjs/-/babel-plugin-transform-es2015-modules-commonjs-6.26.2.tgz", + "integrity": "sha512-CV9ROOHEdrjcwhIaJNBGMBCodN+1cfkwtM1SbUHmvyy35KGT7fohbpOxkE2uLz1o6odKK2Ck/tz47z+VqQfi9Q==", + "dev": true, + "requires": { + "babel-plugin-transform-strict-mode": "^6.24.1", + "babel-runtime": "^6.26.0", + "babel-template": "^6.26.0", + "babel-types": "^6.26.0" + } + }, + "babel-plugin-transform-es2015-modules-systemjs": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-modules-systemjs/-/babel-plugin-transform-es2015-modules-systemjs-6.24.1.tgz", + "integrity": "sha1-/4mhQrkRmpBhlfXxBuzzBdlAfSM=", + "dev": true, + "requires": { + "babel-helper-hoist-variables": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-modules-umd": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-modules-umd/-/babel-plugin-transform-es2015-modules-umd-6.24.1.tgz", + "integrity": "sha1-rJl+YoXNGO1hdq22B9YCNErThGg=", + "dev": true, + "requires": { + "babel-plugin-transform-es2015-modules-amd": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-object-super": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-object-super/-/babel-plugin-transform-es2015-object-super-6.24.1.tgz", + "integrity": "sha1-JM72muIcuDp/hgPa0CH1cusnj40=", + "dev": true, + "requires": { + "babel-helper-replace-supers": "^6.24.1", + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-parameters": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-parameters/-/babel-plugin-transform-es2015-parameters-6.24.1.tgz", + "integrity": "sha1-V6w1GrScrxSpfNE7CfZv3wpiXys=", + "dev": true, + "requires": { + "babel-helper-call-delegate": "^6.24.1", + "babel-helper-get-function-arity": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1", + "babel-traverse": "^6.24.1", + "babel-types": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-shorthand-properties": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-shorthand-properties/-/babel-plugin-transform-es2015-shorthand-properties-6.24.1.tgz", + "integrity": "sha1-JPh11nIch2YbvZmkYi5R8U3jiqA=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-spread": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-spread/-/babel-plugin-transform-es2015-spread-6.22.0.tgz", + "integrity": "sha1-1taKmfia7cRTbIGlQujdnxdG+NE=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-sticky-regex": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-sticky-regex/-/babel-plugin-transform-es2015-sticky-regex-6.24.1.tgz", + "integrity": "sha1-AMHNsaynERLN8M9hJsLta0V8zbw=", + "dev": true, + "requires": { + "babel-helper-regex": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-plugin-transform-es2015-template-literals": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-template-literals/-/babel-plugin-transform-es2015-template-literals-6.22.0.tgz", + "integrity": "sha1-qEs0UPfp+PH2g51taH2oS7EjbY0=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-typeof-symbol": { + "version": "6.23.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-typeof-symbol/-/babel-plugin-transform-es2015-typeof-symbol-6.23.0.tgz", + "integrity": "sha1-3sCfHN3/lLUqxz1QXITfWdzOs3I=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0" + } + }, + "babel-plugin-transform-es2015-unicode-regex": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-unicode-regex/-/babel-plugin-transform-es2015-unicode-regex-6.24.1.tgz", + "integrity": "sha1-04sS9C6nMj9yk4fxinxa4frrNek=", + "dev": true, + "requires": { + "babel-helper-regex": "^6.24.1", + "babel-runtime": "^6.22.0", + "regexpu-core": "^2.0.0" + }, + "dependencies": { + "jsesc": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", + "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", + "dev": true + }, + "regexpu-core": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-2.0.0.tgz", + "integrity": "sha1-SdA4g3uNz4v6W5pCE5k45uoq4kA=", + "dev": true, + "requires": { + "regenerate": "^1.2.1", + "regjsgen": "^0.2.0", + "regjsparser": "^0.1.4" + } + }, + "regjsgen": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/regjsgen/-/regjsgen-0.2.0.tgz", + "integrity": "sha1-bAFq3qxVT3WCP+N6wFuS1aTtsfc=", + "dev": true + }, + "regjsparser": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.1.5.tgz", + "integrity": "sha1-fuj4Tcb6eS0/0K4ijSS9lJ6tIFw=", + "dev": true, + "requires": { + "jsesc": "~0.5.0" + } + } + } + }, + "babel-plugin-transform-regenerator": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-regenerator/-/babel-plugin-transform-regenerator-6.26.0.tgz", + "integrity": "sha1-4HA2lvveJ/Cj78rPi03KL3s6jy8=", + "dev": true, + "requires": { + "regenerator-transform": "^0.10.0" + }, + "dependencies": { + "regenerator-transform": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.10.1.tgz", + "integrity": "sha512-PJepbvDbuK1xgIgnau7Y90cwaAmO/LCLMI2mPvaXq2heGMR3aWW5/BQvYrhJ8jgmQjXewXvBjzfqKcVOmhjZ6Q==", + "dev": true, + "requires": { + "babel-runtime": "^6.18.0", + "babel-types": "^6.19.0", + "private": "^0.1.6" + } + } + } + }, + "babel-plugin-transform-strict-mode": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-strict-mode/-/babel-plugin-transform-strict-mode-6.24.1.tgz", + "integrity": "sha1-1fr3qleKZbvlkc9e2uBKDGcCB1g=", + "dev": true, + "requires": { + "babel-runtime": "^6.22.0", + "babel-types": "^6.24.1" + } + }, + "babel-preset-es2015": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-preset-es2015/-/babel-preset-es2015-6.24.1.tgz", + "integrity": "sha1-1EBQ1rwsn+6nAqrzjXJ6AhBTiTk=", + "dev": true, + "requires": { + "babel-plugin-check-es2015-constants": "^6.22.0", + "babel-plugin-transform-es2015-arrow-functions": "^6.22.0", + "babel-plugin-transform-es2015-block-scoped-functions": "^6.22.0", + "babel-plugin-transform-es2015-block-scoping": "^6.24.1", + "babel-plugin-transform-es2015-classes": "^6.24.1", + "babel-plugin-transform-es2015-computed-properties": "^6.24.1", + "babel-plugin-transform-es2015-destructuring": "^6.22.0", + "babel-plugin-transform-es2015-duplicate-keys": "^6.24.1", + "babel-plugin-transform-es2015-for-of": "^6.22.0", + "babel-plugin-transform-es2015-function-name": "^6.24.1", + "babel-plugin-transform-es2015-literals": "^6.22.0", + "babel-plugin-transform-es2015-modules-amd": "^6.24.1", + "babel-plugin-transform-es2015-modules-commonjs": "^6.24.1", + "babel-plugin-transform-es2015-modules-systemjs": "^6.24.1", + "babel-plugin-transform-es2015-modules-umd": "^6.24.1", + "babel-plugin-transform-es2015-object-super": "^6.24.1", + "babel-plugin-transform-es2015-parameters": "^6.24.1", + "babel-plugin-transform-es2015-shorthand-properties": "^6.24.1", + "babel-plugin-transform-es2015-spread": "^6.22.0", + "babel-plugin-transform-es2015-sticky-regex": "^6.24.1", + "babel-plugin-transform-es2015-template-literals": "^6.22.0", + "babel-plugin-transform-es2015-typeof-symbol": "^6.22.0", + "babel-plugin-transform-es2015-unicode-regex": "^6.24.1", + "babel-plugin-transform-regenerator": "^6.24.1" + } + }, + "babel-preset-jest": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-24.9.0.tgz", + "integrity": "sha512-izTUuhE4TMfTRPF92fFwD2QfdXaZW08qvWTFCI51V8rW5x00UuPgc3ajRoWofXOuxjfcOM5zzSYsQS3H8KGCAg==", + "dev": true, + "requires": { + "@babel/plugin-syntax-object-rest-spread": "^7.0.0", + "babel-plugin-jest-hoist": "^24.9.0" + } + }, + "babel-runtime": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", + "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", + "requires": { + "core-js": "^2.4.0", + "regenerator-runtime": "^0.11.0" + } + }, + "babel-template": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-template/-/babel-template-6.26.0.tgz", + "integrity": "sha1-3gPi0WOWsGn0bdn/+FIfsaDjXgI=", + "dev": true, + "requires": { + "babel-runtime": "^6.26.0", + "babel-traverse": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "lodash": "^4.17.4" + } + }, + "babel-traverse": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz", + "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", + "dev": true, + "requires": { + "babel-code-frame": "^6.26.0", + "babel-messages": "^6.23.0", + "babel-runtime": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "debug": "^2.6.8", + "globals": "^9.18.0", + "invariant": "^2.2.2", + "lodash": "^4.17.4" + }, + "dependencies": { + "globals": { + "version": "9.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz", + "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==", + "dev": true + } + } + }, + "babel-types": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", + "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", + "dev": true, + "requires": { + "babel-runtime": "^6.26.0", + "esutils": "^2.0.2", + "lodash": "^4.17.4", + "to-fast-properties": "^1.0.3" + }, + "dependencies": { + "to-fast-properties": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz", + "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=", + "dev": true + } + } + }, + "babylon": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz", + "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==", + "dev": true + }, + "bach": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/bach/-/bach-1.2.0.tgz", + "integrity": "sha1-Szzpa/JxNPeaG0FKUcFONMO9mIA=", + "dev": true, + "requires": { + "arr-filter": "^1.1.1", + "arr-flatten": "^1.0.1", + "arr-map": "^2.0.0", + "array-each": "^1.0.0", + "array-initial": "^1.0.0", + "array-last": "^1.1.1", + "async-done": "^1.2.2", + "async-settle": "^1.0.0", + "now-and-later": "^2.0.0" + } + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" + }, + "base": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", + "integrity": "sha1-e95c7RRbbVUakNuH+DxVi060io8=", + "dev": true, + "requires": { + "cache-base": "^1.0.1", + "class-utils": "^0.3.5", + "component-emitter": "^1.2.1", + "define-property": "^1.0.0", + "isobject": "^3.0.1", + "mixin-deep": "^1.2.0", + "pascalcase": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "base64-js": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.0.2.tgz", + "integrity": "sha1-R0IRyV5s8qVH20YeT2d4tR0I+mU=" + }, + "batch": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/batch/-/batch-0.6.1.tgz", + "integrity": "sha1-3DQxT05nkxgJP8dgJyUl+UvyXBY=", + "dev": true + }, + "bcp47": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/bcp47/-/bcp47-1.1.2.tgz", + "integrity": "sha1-NUvjMH/9CEM6ePXh4glYRfifx/4=" + }, + "bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "requires": { + "tweetnacl": "^0.14.3" + } + }, + "bcryptjs": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", + "integrity": "sha1-mrVie5PmBiH/fNrF2pczAn3x0Ms=" + }, + "beeper": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/beeper/-/beeper-1.1.1.tgz", + "integrity": "sha1-5tXqjF2tABMEpwsiY4RH9pyy+Ak=", + "dev": true + }, + "big.js": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz", + "integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==", + "dev": true + }, + "bignumber.js": { + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-7.2.1.tgz", + "integrity": "sha512-S4XzBk5sMB+Rcb/LNcpzXr57VRTxgAvaAEDAl1AwRx27j00hT84O6OkteE7u8UB3NuaaygCRrEpqox4uDOrbdQ==" + }, + "binary-extensions": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.13.1.tgz", + "integrity": "sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw==", + "dev": true + }, + "bl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-2.2.0.tgz", + "integrity": "sha512-wbgvOpqopSr7uq6fJrLH8EsvYMJf9gzfo2jCsL2eTy75qXPukA4pCgHamOQkZtY5vmfVtjB+P3LNlMHW5CEZXA==", + "requires": { + "readable-stream": "^2.3.5", + "safe-buffer": "^5.1.1" + } + }, + "block-stream": { + "version": "0.0.9", + "resolved": "https://registry.npmjs.org/block-stream/-/block-stream-0.0.9.tgz", + "integrity": "sha1-E+v+d4oDIFz+A3UUgeu0szAMEmo=", + "dev": true, + "requires": { + "inherits": "~2.0.0" + } + }, + "bluebird": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.5.tgz", + "integrity": "sha512-5am6HnnfN+urzt4yfg7IgTbotDjIT/u8AJpEt0sIU9FtXfVeezXAPKswrG+xKUCOYAINpSdgZVDU6QFh+cuH3w==" + }, + "bn.js": { + "version": "4.11.8", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.8.tgz", + "integrity": "sha512-ItfYfPLkWHUjckQCk8xC+LwxgK8NYcXywGigJgSwOP8Y2iyWT4f2vsZnoOXTTbo+o5yXmIUJ4gn5538SO5S3gA==", + "dev": true + }, + "body-parser": { + "version": "1.19.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz", + "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==", + "requires": { + "bytes": "3.1.0", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "~1.1.2", + "http-errors": "1.7.2", + "iconv-lite": "0.4.24", + "on-finished": "~2.3.0", + "qs": "6.7.0", + "raw-body": "2.4.0", + "type-is": "~1.6.17" + }, + "dependencies": { + "bytes": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", + "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==" + }, + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" + } + } + }, + "bonjour": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/bonjour/-/bonjour-3.5.0.tgz", + "integrity": "sha1-jokKGD2O6aI5OzhExpGkK897yfU=", + "dev": true, + "requires": { + "array-flatten": "^2.1.0", + "deep-equal": "^1.0.1", + "dns-equal": "^1.0.0", + "dns-txt": "^2.0.2", + "multicast-dns": "^6.0.1", + "multicast-dns-service-types": "^1.1.0" + }, + "dependencies": { + "array-flatten": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-2.1.2.tgz", + "integrity": "sha512-hNfzcOV8W4NdualtqBFPyVO+54DSJuZGY9qT4pRroB6S9e3iiido2ISIC5h9R2sPJ8H3FHCIiEnsv1lPXO3KtQ==", + "dev": true + } + } + }, + "boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha1-aN/1++YMUes3cl6p4+0xDcwed24=", + "dev": true + }, + "boolean": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.0.0.tgz", + "integrity": "sha512-OElxJ1lUSinuoUnkpOgLmxp0DC4ytEhODEL6QJU0NpxE/mI4rUSh8h1P1Wkvfi3xQEBcxXR2gBIPNYNuaFcAbQ==", + "optional": true + }, + "bops": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/bops/-/bops-1.0.0.tgz", + "integrity": "sha1-YxqJKPEXhBfrb3Bs9prNteWk6q0=", + "requires": { + "base64-js": "1.0.2", + "to-utf8": "0.0.1" + } + }, + "bowser": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.6.1.tgz", + "integrity": "sha512-hySGUuLhi0KetfxPZpuJOsjM0kRvCiCgPBygBkzGzJNsq/nbJmaO8QJc6xlWfeFFnMvtd/LeKkhDJGVrmVobUA==" + }, + "boxen": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/boxen/-/boxen-1.3.0.tgz", + "integrity": "sha512-TNPjfTr432qx7yOjQyaXm3dSR0MH9vXp7eT1BFSl/C51g+EFnOR9hTg1IreahGBmDNCehscshe45f+C1TBZbLw==", + "dev": true, + "requires": { + "ansi-align": "^2.0.0", + "camelcase": "^4.0.0", + "chalk": "^2.0.1", + "cli-boxes": "^1.0.0", + "string-width": "^2.0.0", + "term-size": "^1.2.0", + "widest-line": "^2.0.0" + }, + "dependencies": { + "camelcase": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", + "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=", + "dev": true + } + } + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } }, "braces": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.0.tgz", - "integrity": "sha512-P4O8UQRdGiMLWSizsApmXVQDBS6KCt7dSexgLKBmH5Hr1CZq7vsnscFh8oR1sP1ab1Zj0uCHCEzZeV6SfUf3rA==", - "dev": true, - "requires": { - "arr-flatten": "1.1.0", - "array-unique": "0.3.2", - "define-property": "1.0.0", - "extend-shallow": "2.0.1", - "fill-range": "4.0.0", - "isobject": "3.0.1", - "repeat-element": "1.1.2", - "snapdragon": "0.8.1", - "snapdragon-node": "2.1.1", - "split-string": "3.1.0", - "to-regex": "3.0.1" - } + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz", + "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", + "dev": true, + "requires": { + "arr-flatten": "^1.1.0", + "array-unique": "^0.3.2", + "extend-shallow": "^2.0.1", + "fill-range": "^4.0.0", + "isobject": "^3.0.1", + "repeat-element": "^1.1.2", + "snapdragon": "^0.8.1", + "snapdragon-node": "^2.0.1", + "split-string": "^3.0.2", + "to-regex": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "brorand": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", + "integrity": "sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8=", + "dev": true + }, + "browser-process-hrtime": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/browser-process-hrtime/-/browser-process-hrtime-0.1.3.tgz", + "integrity": "sha512-bRFnI4NnjO6cnyLmOV/7PVoDEMJChlcfN0z4s1YMBY989/SvlfMI1lgCnkFUs53e9gQF+w7qu7XdllSTiSl8Aw==", + "dev": true + }, + "browser-resolve": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/browser-resolve/-/browser-resolve-1.11.3.tgz", + "integrity": "sha512-exDi1BYWB/6raKHmDTCicQfTkqwN5fioMFV4j8BsfMU4R2DK/QfZfK7kOVkmWCNANf0snkBzqGqAJBao9gZMdQ==", + "dev": true, + "requires": { + "resolve": "1.1.7" + }, + "dependencies": { + "resolve": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.1.7.tgz", + "integrity": "sha1-IDEU2CrSxe2ejgQRs5ModeiJ6Xs=", + "dev": true + } + } + }, + "browserify-aes": { + "version": "1.2.0", + "resolved": "http://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", + "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", + "dev": true, + "requires": { + "buffer-xor": "^1.0.3", + "cipher-base": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.3", + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "browserify-cipher": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.1.tgz", + "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==", + "dev": true, + "requires": { + "browserify-aes": "^1.0.4", + "browserify-des": "^1.0.0", + "evp_bytestokey": "^1.0.0" + } + }, + "browserify-des": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.2.tgz", + "integrity": "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A==", + "dev": true, + "requires": { + "cipher-base": "^1.0.1", + "des.js": "^1.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "browserify-rsa": { + "version": "4.0.1", + "resolved": "http://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", + "integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "randombytes": "^2.0.1" + } + }, + "browserify-sign": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.0.4.tgz", + "integrity": "sha1-qk62jl17ZYuqa/alfmMMvXqT0pg=", + "dev": true, + "requires": { + "bn.js": "^4.1.1", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.2", + "elliptic": "^6.0.0", + "inherits": "^2.0.1", + "parse-asn1": "^5.0.0" + } + }, + "browserify-zlib": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz", + "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", + "dev": true, + "requires": { + "pako": "~1.0.5" + } + }, + "browserslist": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.7.0.tgz", + "integrity": "sha512-9rGNDtnj+HaahxiVV38Gn8n8Lr8REKsel68v1sPFfIGEK6uSXTY3h9acgiT1dZVtOOUtifo/Dn8daDQ5dUgVsA==", + "dev": true, + "requires": { + "caniuse-lite": "^1.0.30000989", + "electron-to-chromium": "^1.3.247", + "node-releases": "^1.1.29" + } + }, + "bser": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.0.tgz", + "integrity": "sha512-8zsjWrQkkBoLK6uxASk1nJ2SKv97ltiGDo6A3wA0/yRPz+CwmEyDo0hUrhIuukG2JHpAl3bvFIixw2/3Hi0DOg==", + "dev": true, + "requires": { + "node-int64": "^0.4.0" + } + }, + "btoa": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/btoa/-/btoa-1.1.2.tgz", + "integrity": "sha1-PkC4FmP4HS3WWWpMtxSo3BbPq+A=" + }, + "buffer": { + "version": "4.9.1", + "resolved": "http://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz", + "integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=", + "requires": { + "base64-js": "^1.0.2", + "ieee754": "^1.1.4", + "isarray": "^1.0.0" + } + }, + "buffer-equal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-equal/-/buffer-equal-1.0.0.tgz", + "integrity": "sha1-WWFrSYME1Var1GaWayLu2j7KX74=", + "dev": true + }, + "buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" + }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==" + }, + "buffer-indexof": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-indexof/-/buffer-indexof-1.1.1.tgz", + "integrity": "sha512-4/rOEg86jivtPTeOUUT61jJO1Ya1TrR/OkqCSZDyq84WJh3LuuiphBYJN+fm5xufIk4XAFcEwte/8WzC8If/1g==", + "dev": true + }, + "buffer-xor": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", + "integrity": "sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk=", + "dev": true + }, + "bufferstreams": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/bufferstreams/-/bufferstreams-1.0.1.tgz", + "integrity": "sha1-z7GtlWjTujz+k1upq92VLeiKqyo=", + "dev": true, + "requires": { + "readable-stream": "^1.0.33" + }, + "dependencies": { + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "readable-stream": { + "version": "1.1.14", + "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", + "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "http://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + } + } + }, + "builtin-status-codes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz", + "integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug=", + "dev": true + }, + "bytes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", + "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=" + }, + "cacache": { + "version": "11.3.3", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-11.3.3.tgz", + "integrity": "sha512-p8WcneCytvzPxhDvYp31PD039vi77I12W+/KfR9S8AZbaiARFBCpsPJS+9uhWfeBfeAtW7o/4vt3MUqLkbY6nA==", + "dev": true, + "requires": { + "bluebird": "^3.5.5", + "chownr": "^1.1.1", + "figgy-pudding": "^3.5.1", + "glob": "^7.1.4", + "graceful-fs": "^4.1.15", + "lru-cache": "^5.1.1", + "mississippi": "^3.0.0", + "mkdirp": "^0.5.1", + "move-concurrently": "^1.0.1", + "promise-inflight": "^1.0.1", + "rimraf": "^2.6.3", + "ssri": "^6.0.1", + "unique-filename": "^1.1.1", + "y18n": "^4.0.0" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "y18n": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", + "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==", + "dev": true + } + } + }, + "cache-base": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", + "integrity": "sha1-Cn9GQWgxyLZi7jb+TnxZ129marI=", + "dev": true, + "requires": { + "collection-visit": "^1.0.0", + "component-emitter": "^1.2.1", + "get-value": "^2.0.6", + "has-value": "^1.0.0", + "isobject": "^3.0.1", + "set-value": "^2.0.0", + "to-object-path": "^0.3.0", + "union-value": "^1.0.0", + "unset-value": "^1.0.0" + } + }, + "cacheable-request": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-6.1.0.tgz", + "integrity": "sha512-Oj3cAGPCqOZX7Rz64Uny2GYAZNliQSqfbePrgAQ1wKAihYmCUnraBtJtKcGR4xz7wF+LoJC+ssFZvv5BgF9Igg==", + "requires": { + "clone-response": "^1.0.2", + "get-stream": "^5.1.0", + "http-cache-semantics": "^4.0.0", + "keyv": "^3.0.0", + "lowercase-keys": "^2.0.0", + "normalize-url": "^4.1.0", + "responselike": "^1.0.2" + }, + "dependencies": { + "get-stream": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.1.0.tgz", + "integrity": "sha512-EXr1FOzrzTfGeL0gQdeFEvOMm2mzMOglyiOXSTpPC+iAjAKftbr3jpCMWynogwYnM+eSj9sHGc6wjIcDvYiygw==", + "requires": { + "pump": "^3.0.0" + } + }, + "lowercase-keys": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", + "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==" + } + } + }, + "callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true + }, + "camel-case": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/camel-case/-/camel-case-3.0.0.tgz", + "integrity": "sha1-yjw2iKTpzzpM2nd9xNy8cTJJz3M=", + "dev": true, + "requires": { + "no-case": "^2.2.0", + "upper-case": "^1.1.1" + } }, "camelcase": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", - "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=", - "dev": true + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true + }, + "camelcase-keys": { + "version": "2.1.0", + "resolved": "http://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", + "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", + "dev": true, + "requires": { + "camelcase": "^2.0.0", + "map-obj": "^1.0.0" + }, + "dependencies": { + "camelcase": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", + "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=", + "dev": true + } + } + }, + "camelize": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/camelize/-/camelize-1.0.0.tgz", + "integrity": "sha1-FkpUg+Yw+kMh5a8HAg5TGDGyYJs=" + }, + "caniuse-lite": { + "version": "1.0.30000989", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30000989.tgz", + "integrity": "sha512-vrMcvSuMz16YY6GSVZ0dWDTJP8jqk3iFQ/Aq5iqblPwxSVVZI+zxDyTX0VPqtQsDnfdrBDcsmhgTEOh5R8Lbpw==", + "dev": true + }, + "canonical-json": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/canonical-json/-/canonical-json-0.0.4.tgz", + "integrity": "sha1-ZXnAcsPbXEd+xB3JePvyuPQQdKM=" + }, + "capture-exit": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/capture-exit/-/capture-exit-2.0.0.tgz", + "integrity": "sha512-PiT/hQmTonHhl/HFGN+Lx3JJUznrVYJ3+AQsnthneZbvW7x+f08Tk7yLJTLEOUvBTbduLeeBkxEaYXUOUrRq6g==", + "dev": true, + "requires": { + "rsvp": "^4.8.4" + } + }, + "capture-stack-trace": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/capture-stack-trace/-/capture-stack-trace-1.0.1.tgz", + "integrity": "sha512-mYQLZnx5Qt1JgB1WEiMCf2647plpGeQ2NMR/5L0HNZzGQo4fuSPnK+wjfPnKZV0aiJDgzmWqqkV/g7JD+DW0qw==", + "dev": true + }, + "caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "dependencies": { + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true + }, + "charenc": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz", + "integrity": "sha1-wKHS86cJLgN3S/qD8UwPxXkKhmc=" }, "chokidar": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.0.0.tgz", - "integrity": "sha512-OgXCNv2U6TnG04D3tth0gsvdbV4zdbxFG3sYUqcoQMoEFVd1j1pZR6TZ8iknC45o9IJ6PeQI/J6wT/+cHcniAw==", - "dev": true, - "requires": { - "anymatch": "2.0.0", - "async-each": "1.0.1", - "braces": "2.3.0", - "fsevents": "1.1.3", - "glob-parent": "3.1.0", - "inherits": "2.0.3", - "is-binary-path": "1.0.1", - "is-glob": "4.0.0", - "normalize-path": "2.1.1", - "path-is-absolute": "1.0.1", - "readdirp": "2.1.0" - } + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.1.6.tgz", + "integrity": "sha512-V2jUo67OKkc6ySiRpJrjlpJKl9kDuG+Xb8VgsGzb+aEouhgS1D0weyPU4lEzdAcsCAvrih2J2BqyXqHWvVLw5g==", + "dev": true, + "requires": { + "anymatch": "^2.0.0", + "async-each": "^1.0.1", + "braces": "^2.3.2", + "fsevents": "^1.2.7", + "glob-parent": "^3.1.0", + "inherits": "^2.0.3", + "is-binary-path": "^1.0.0", + "is-glob": "^4.0.0", + "normalize-path": "^3.0.0", + "path-is-absolute": "^1.0.0", + "readdirp": "^2.2.1", + "upath": "^1.1.1" + } + }, + "chownr": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.1.tgz", + "integrity": "sha512-j38EvO5+LHX84jlo6h4UzmOwi0UgW61WRyPtJz4qaadK5eY3BTS5TY/S1Stc3Uk2lIM6TPevAlULiEJwie860g==", + "dev": true + }, + "chrome-trace-event": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.2.tgz", + "integrity": "sha512-9e/zx1jw7B4CO+c/RXoCsfg/x1AfUBioy4owYH0bJprEYAx5hRFLRhWBqHAG57D0ZM4H7vxbP7bPe0VwhQRYDQ==", + "dev": true, + "requires": { + "tslib": "^1.9.0" + } + }, + "ci-info": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz", + "integrity": "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==", + "dev": true + }, + "cipher-base": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz", + "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "class-utils": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", + "integrity": "sha1-+TNprouafOAv1B+q0MqDAzGQxGM=", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "define-property": "^0.2.5", + "isobject": "^3.0.0", + "static-extend": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "cldrjs": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/cldrjs/-/cldrjs-0.5.1.tgz", + "integrity": "sha512-xyiP8uAm8K1IhmpDndZLraloW1yqu0L+HYdQ7O1aGPxx9Cr+BMnPANlNhSt++UKfxytL2hd2NPXgTjiy7k43Ew==" + }, + "clean-css": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/clean-css/-/clean-css-4.2.1.tgz", + "integrity": "sha512-4ZxI6dy4lrY6FHzfiy1aEOXgu4LIsW2MhwG0VBKdcoGoH/XLFgaHSdLTGr4O8Be6A8r3MOphEiI8Gc1n0ecf3g==", + "dev": true, + "requires": { + "source-map": "~0.6.0" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "cli-boxes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz", + "integrity": "sha1-T6kXw+WclKAEzWH47lCdplFocUM=", + "dev": true + }, + "cli-cursor": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", + "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", + "dev": true, + "requires": { + "restore-cursor": "^2.0.0" + } + }, + "cli-width": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.0.tgz", + "integrity": "sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk=", + "dev": true + }, + "cliui": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", + "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=", + "dev": true, + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wrap-ansi": "^2.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "dev": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "http://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "dev": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, + "clone": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "integrity": "sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18=", + "dev": true + }, + "clone-buffer": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/clone-buffer/-/clone-buffer-1.0.0.tgz", + "integrity": "sha1-4+JbIHrE5wGvch4staFnksrD3Fg=", + "dev": true + }, + "clone-deep": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-2.0.2.tgz", + "integrity": "sha512-SZegPTKjCgpQH63E+eN6mVEEPdQBOUzjyJm5Pora4lrwWRFS8I0QAxV/KD6vV/i0WuijHZWQC1fMsPEdxfdVCQ==", + "dev": true, + "requires": { + "for-own": "^1.0.0", + "is-plain-object": "^2.0.4", + "kind-of": "^6.0.0", + "shallow-clone": "^1.0.0" + } + }, + "clone-response": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.2.tgz", + "integrity": "sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws=", + "requires": { + "mimic-response": "^1.0.0" + } + }, + "clone-stats": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-1.0.0.tgz", + "integrity": "sha1-s3gt/4u1R04Yuba/D9/ngvh3doA=", + "dev": true + }, + "cloneable-readable": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/cloneable-readable/-/cloneable-readable-1.1.3.tgz", + "integrity": "sha512-2EF8zTQOxYq70Y4XKtorQupqF0m49MBz2/yf5Bj+MHjvpG3Hy7sImifnqD6UA+TKYxeSV+u6qqQPawN5UvnpKQ==", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "process-nextick-args": "^2.0.0", + "readable-stream": "^2.3.5" + } + }, + "cls-hooked": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/cls-hooked/-/cls-hooked-4.2.2.tgz", + "integrity": "sha512-J4Xj5f5wq/4jAvcdgoGsL3G103BtWpZrMo8NEinRltN+xpTZdI+M38pyQqhuFU/P792xkMFvnKSf+Lm81U1bxw==", + "requires": { + "async-hook-jl": "^1.7.6", + "emitter-listener": "^1.0.1", + "semver": "^5.4.1" + } + }, + "co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=", + "dev": true + }, + "code-point-at": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", + "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", + "dev": true + }, + "collection-map": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/collection-map/-/collection-map-1.0.0.tgz", + "integrity": "sha1-rqDwb40mx4DCt1SUOFVEsiVa8Yw=", + "dev": true, + "requires": { + "arr-map": "^2.0.2", + "for-own": "^1.0.0", + "make-iterator": "^1.0.0" + } + }, + "collection-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz", + "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", + "dev": true, + "requires": { + "map-visit": "^1.0.0", + "object-visit": "^1.0.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "dev": true + }, + "colors": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.3.3.tgz", + "integrity": "sha512-mmGt/1pZqYRjMxB1axhTo16/snVZ5krrKkcmMeVKxzECMMXoCgnvTPp10QgHfcbQZw8Dq2jMNG6je4JlWU0gWg==", + "dev": true + }, + "combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "commander": { + "version": "2.20.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==" + }, + "commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=" + }, + "component-emitter": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", + "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==", + "dev": true + }, + "compressible": { + "version": "2.0.17", + "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.17.tgz", + "integrity": "sha512-BGHeLCK1GV7j1bSmQQAi26X+GgWcTjLr/0tzSvMCl3LH1w1IJ4PFSPoV5316b30cneTziC+B1a+3OjoSUcQYmw==", + "requires": { + "mime-db": ">= 1.40.0 < 2" + } + }, + "compression": { + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.7.4.tgz", + "integrity": "sha512-jaSIDzP9pZVS4ZfQ+TzvtiWhdpFhE2RDHz8QJkpX9SIpLq88VueF5jJw6t+6CUQcAoA6t+x89MLrWAqpfDE8iQ==", + "requires": { + "accepts": "~1.3.5", + "bytes": "3.0.0", + "compressible": "~2.0.16", + "debug": "2.6.9", + "on-headers": "~1.0.2", + "safe-buffer": "5.1.2", + "vary": "~1.1.2" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + }, + "dependencies": { + "readable-stream": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.4.0.tgz", + "integrity": "sha512-jItXPLmrSR8jmTRmRWJXCnGJsfy85mB3Wd/uINMXA65yrnFo0cPClFIUWzo2najVNSl+mx7/4W8ttlLWJe99pQ==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + } + } + }, + "concat-with-sourcemaps": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/concat-with-sourcemaps/-/concat-with-sourcemaps-1.1.0.tgz", + "integrity": "sha512-4gEjHJFT9e+2W/77h/DS5SGUgwDaOwprX8L/gl5+3ixnzkVJJsZWDSelmN3Oilw3LNDZjZV0yqH1hLG3k6nghg==", + "dev": true, + "requires": { + "source-map": "^0.6.1" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "config-chain": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/config-chain/-/config-chain-1.1.12.tgz", + "integrity": "sha512-a1eOIcu8+7lUInge4Rpf/n4Krkf3Dd9lqhljRzII1/Zno/kRtUWnznPO3jOKBmTEktkt3fkxisUcivoj0ebzoA==", + "optional": true, + "requires": { + "ini": "^1.3.4", + "proto-list": "~1.2.1" + } + }, + "configstore": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/configstore/-/configstore-4.0.0.tgz", + "integrity": "sha512-CmquAXFBocrzaSM8mtGPMM/HiWmyIpr4CcJl/rgY2uCObZ/S7cKU0silxslqJejl+t/T9HS8E0PUNQD81JGUEQ==", + "requires": { + "dot-prop": "^4.1.0", + "graceful-fs": "^4.1.2", + "make-dir": "^1.0.0", + "unique-string": "^1.0.0", + "write-file-atomic": "^2.0.0", + "xdg-basedir": "^3.0.0" + } + }, + "connect-history-api-fallback": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/connect-history-api-fallback/-/connect-history-api-fallback-1.6.0.tgz", + "integrity": "sha512-e54B99q/OUoH64zYYRf3HBP5z24G38h5D3qXu23JGRoigpX5Ss4r9ZnDk3g0Z8uQC2x2lPaJ+UlWBc1ZWBWdLg==", + "dev": true + }, + "console-browserify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", + "integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=", + "dev": true, + "requires": { + "date-now": "^0.1.4" + } + }, + "console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", + "dev": true + }, + "consolidate": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/consolidate/-/consolidate-0.14.5.tgz", + "integrity": "sha1-WiUEe8dvcwcmZ8jLUsmJiI9JTGM=", + "dev": true, + "requires": { + "bluebird": "^3.1.1" + } + }, + "constants-browserify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz", + "integrity": "sha1-wguW2MYXdIqvHBYCF2DNJ/y4y3U=", + "dev": true + }, + "content-disposition": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", + "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", + "requires": { + "safe-buffer": "5.1.2" + } + }, + "content-security-policy-builder": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-security-policy-builder/-/content-security-policy-builder-2.1.0.tgz", + "integrity": "sha512-/MtLWhJVvJNkA9dVLAp6fg9LxD2gfI6R2Fi1hPmfjYXSahJJzcfvoeDOxSyp4NvxMuwWv3WMssE9o31DoULHrQ==" + }, + "content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==" + }, + "convert-source-map": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.6.0.tgz", + "integrity": "sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.1" + } + }, + "cookie": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", + "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==" + }, + "cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" + }, + "copy-concurrently": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/copy-concurrently/-/copy-concurrently-1.0.5.tgz", + "integrity": "sha512-f2domd9fsVDFtaFcbaRZuYXwtdmnzqbADSwhSWYxYB/Q8zsdUUFMXVRwXGDMWmbEzAn1kdRrtI1T/KTFOL4X2A==", + "dev": true, + "requires": { + "aproba": "^1.1.1", + "fs-write-stream-atomic": "^1.0.8", + "iferr": "^0.1.5", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.0" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + } + } + }, + "copy-descriptor": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", + "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", + "dev": true + }, + "copy-props": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/copy-props/-/copy-props-2.0.4.tgz", + "integrity": "sha512-7cjuUME+p+S3HZlbllgsn2CDwS+5eCCX16qBgNC4jgSTf49qR1VKy/Zhl400m0IQXl/bPGEVqncgUUMjrr4s8A==", + "dev": true, + "requires": { + "each-props": "^1.3.0", + "is-plain-object": "^2.0.1" + } + }, + "core-js": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.9.tgz", + "integrity": "sha512-HOpZf6eXmnl7la+cUdMnLvUxKNqLUzJvgIziQ0DiF3JwSImNphIqdGqzj6hIKyX04MmV0poclQ7+wjWvxQyR2A==" + }, + "core-js-compat": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.2.1.tgz", + "integrity": "sha512-MwPZle5CF9dEaMYdDeWm73ao/IflDH+FjeJCWEADcEgFSE9TLimFKwJsfmkwzI8eC0Aj0mgvMDjeQjrElkz4/A==", + "dev": true, + "requires": { + "browserslist": "^4.6.6", + "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + }, + "create-ecdh": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.3.tgz", + "integrity": "sha512-GbEHQPMOswGpKXM9kCWVrremUcBmjteUaQ01T9rkKCPDXfUHX0IoP9LpHYo2NPFampa4e+/pFDc3jQdxrxQLaw==", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "elliptic": "^6.0.0" + } + }, + "create-error-class": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/create-error-class/-/create-error-class-3.0.2.tgz", + "integrity": "sha1-Br56vvlHo/FKMP1hBnHUAbyot7Y=", + "dev": true, + "requires": { + "capture-stack-trace": "^1.0.0" + } + }, + "create-hash": { + "version": "1.2.0", + "resolved": "http://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", + "dev": true, + "requires": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" + } + }, + "create-hmac": { + "version": "1.1.7", + "resolved": "http://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", + "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", + "dev": true, + "requires": { + "cipher-base": "^1.0.3", + "create-hash": "^1.1.0", + "inherits": "^2.0.1", + "ripemd160": "^2.0.0", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, + "cross-fetch": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-0.0.8.tgz", + "integrity": "sha1-Ae2U3EB98sAPGAf95wCnz6SKIFw=", + "requires": { + "node-fetch": "1.7.3", + "whatwg-fetch": "2.0.3" + }, + "dependencies": { + "node-fetch": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-1.7.3.tgz", + "integrity": "sha512-NhZ4CsKx7cYm2vSrBAr2PvFOe6sWDf0UYLRqA6svUYg7+/TSfVAu49jYC4BvQ4Sms9SZgdqGBgroqfDhJdTyKQ==", + "requires": { + "encoding": "^0.1.11", + "is-stream": "^1.0.1" + } + } + } + }, + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "crypt": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz", + "integrity": "sha1-iNf/fsDfuG9xPch7u0LQRNPmxBs=" + }, + "crypto-browserify": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", + "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", + "dev": true, + "requires": { + "browserify-cipher": "^1.0.0", + "browserify-sign": "^4.0.0", + "create-ecdh": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.0", + "diffie-hellman": "^5.0.0", + "inherits": "^2.0.1", + "pbkdf2": "^3.0.3", + "public-encrypt": "^4.0.0", + "randombytes": "^2.0.0", + "randomfill": "^1.0.3" + } + }, + "crypto-random-string": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-1.0.0.tgz", + "integrity": "sha1-ojD2T1aDEOFJgAmUB5DsmVRbyn4=" + }, + "csextends": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/csextends/-/csextends-1.2.0.tgz", + "integrity": "sha512-S/8k1bDTJIwuGgQYmsRoE+8P+ohV32WhQ0l4zqrc0XDdxOhjQQD7/wTZwCzoZX53jSX3V/qwjT+OkPTxWQcmjg==" + }, + "css-loader": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-2.1.1.tgz", + "integrity": "sha512-OcKJU/lt232vl1P9EEDamhoO9iKY3tIjY5GU+XDLblAykTdgs6Ux9P1hTHve8nFKy5KPpOXOsVI/hIwi3841+w==", + "dev": true, + "requires": { + "camelcase": "^5.2.0", + "icss-utils": "^4.1.0", + "loader-utils": "^1.2.3", + "normalize-path": "^3.0.0", + "postcss": "^7.0.14", + "postcss-modules-extract-imports": "^2.0.0", + "postcss-modules-local-by-default": "^2.0.6", + "postcss-modules-scope": "^2.1.0", + "postcss-modules-values": "^2.0.0", + "postcss-value-parser": "^3.3.0", + "schema-utils": "^1.0.0" + } + }, + "css-select": { + "version": "1.2.0", + "resolved": "http://registry.npmjs.org/css-select/-/css-select-1.2.0.tgz", + "integrity": "sha1-KzoRBTnFNV8c2NMUYj6HCxIeyFg=", + "dev": true, + "requires": { + "boolbase": "~1.0.0", + "css-what": "2.1", + "domutils": "1.5.1", + "nth-check": "~1.0.1" + }, + "dependencies": { + "domutils": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz", + "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=", + "dev": true, + "requires": { + "dom-serializer": "0", + "domelementtype": "1" + } + } + } + }, + "css-what": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-2.1.3.tgz", + "integrity": "sha512-a+EPoD+uZiNfh+5fxw2nO9QwFa6nJe2Or35fGY6Ipw1R3R4AGz1d1TEZrCegvw2YTmZ0jXirGYlzxxpYSHwpEg==", + "dev": true + }, + "cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true + }, + "cssom": { + "version": "0.3.8", + "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz", + "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", + "dev": true + }, + "cssstyle": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-1.4.0.tgz", + "integrity": "sha512-GBrLZYZ4X4x6/QEoBnIrqb8B/f5l4+8me2dkom/j1Gtbxy0kBv6OGzKuAsGM75bkGwGAFkt56Iwg28S3XTZgSA==", + "dev": true, + "requires": { + "cssom": "0.3.x" + } + }, + "currently-unhandled": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/currently-unhandled/-/currently-unhandled-0.4.1.tgz", + "integrity": "sha1-mI3zP+qxke95mmE2nddsF635V+o=", + "dev": true, + "requires": { + "array-find-index": "^1.0.1" + } + }, + "cyclist": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/cyclist/-/cyclist-0.2.2.tgz", + "integrity": "sha1-GzN5LhHpFKL9bW7WRHRkRE5fpkA=", + "dev": true + }, + "d": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/d/-/d-1.0.1.tgz", + "integrity": "sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA==", + "dev": true, + "requires": { + "es5-ext": "^0.10.50", + "type": "^1.0.1" + } + }, + "dargs": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/dargs/-/dargs-5.1.0.tgz", + "integrity": "sha1-7H6lDHhWTNNsnV7Bj2Yyn63ieCk=", + "dev": true + }, + "dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "requires": { + "assert-plus": "^1.0.0" + } + }, + "dasherize": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/dasherize/-/dasherize-2.0.0.tgz", + "integrity": "sha1-bYCcnNDPe7iVLYD8hPoT1H3bEwg=" + }, + "data-urls": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-1.1.0.tgz", + "integrity": "sha512-YTWYI9se1P55u58gL5GkQHW4P6VJBJ5iBT+B5a7i2Tjadhv52paJG0qHX4A0OR6/t52odI64KP2YvFpkDOi3eQ==", + "dev": true, + "requires": { + "abab": "^2.0.0", + "whatwg-mimetype": "^2.2.0", + "whatwg-url": "^7.0.0" + }, + "dependencies": { + "whatwg-url": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-7.0.0.tgz", + "integrity": "sha512-37GeVSIJ3kn1JgKyjiYNmSLP1yzbpb29jdmwBSgkD9h40/hyrR/OifpVUndji3tmwGgD8qpw7iQu3RSbCrBpsQ==", + "dev": true, + "requires": { + "lodash.sortby": "^4.7.0", + "tr46": "^1.0.1", + "webidl-conversions": "^4.0.2" + } + } + } + }, + "date-and-time": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/date-and-time/-/date-and-time-0.6.3.tgz", + "integrity": "sha512-lcWy3AXDRJOD7MplwZMmNSRM//kZtJaLz4n6D1P5z9wEmZGBKhJRBIr1Xs9KNQJmdXPblvgffynYji4iylUTcA==" + }, + "date-now": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz", + "integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs=", + "dev": true + }, + "dateformat": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-2.2.0.tgz", + "integrity": "sha1-QGXiATz5+5Ft39gu+1Bq1MZ2kGI=", + "dev": true }, "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", - "dev": true, - "requires": { - "ms": "2.0.0" - } + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", + "dev": true + }, + "decode-uri-component": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", + "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", + "dev": true + }, + "decompress-response": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-3.3.0.tgz", + "integrity": "sha1-gKTdMjdIOEv6JICDYirt7Jgq3/M=", + "requires": { + "mimic-response": "^1.0.0" + } + }, + "deep-defaults": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/deep-defaults/-/deep-defaults-1.0.5.tgz", + "integrity": "sha512-5ev/sNkiHTmeTqbDJEDgdQa/Ub0eOMQNix9l+dLLGbwOos7/in5HdvHXI014wqxsET4YeJG9Eq4qj0PJRL8rSw==", + "dev": true, + "requires": { + "lodash": "^4.17.5" + } + }, + "deep-equal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz", + "integrity": "sha1-9dJgKStmDghO/0zbyfCK0yR0SLU=" + }, + "deep-extend": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.5.1.tgz", + "integrity": "sha512-N8vBdOa+DF7zkRrDCsaOXoCs/E2fJfx9B9MrKnnSiHNh4ws7eSys6YQE4KvT1cecKmOASYQBhbKjeuDD9lT81w==" + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "default-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/default-compare/-/default-compare-1.0.0.tgz", + "integrity": "sha512-QWfXlM0EkAbqOCbD/6HjdwT19j7WCkMyiRhWilc4H9/5h/RzTF9gv5LYh1+CmDV5d1rki6KAWLtQale0xt20eQ==", + "dev": true, + "requires": { + "kind-of": "^5.0.2" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "default-gateway": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/default-gateway/-/default-gateway-4.2.0.tgz", + "integrity": "sha512-h6sMrVB1VMWVrW13mSc6ia/DwYYw5MN6+exNu1OaJeFac5aSAvwM7lZ0NVfTABuSkQelr4h5oebg3KB1XPdjgA==", + "dev": true, + "requires": { + "execa": "^1.0.0", + "ip-regex": "^2.1.0" + } + }, + "default-resolution": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/default-resolution/-/default-resolution-2.0.0.tgz", + "integrity": "sha1-vLgrqnKtebQmp2cy8aga1t8m1oQ=", + "dev": true + }, + "defaults": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.3.tgz", + "integrity": "sha1-xlYFHpgX2f8I7YgUd/P+QBnz730=", + "dev": true, + "requires": { + "clone": "^1.0.2" + }, + "dependencies": { + "clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=", + "dev": true + } + } + }, + "defer-to-connect": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-1.1.0.tgz", + "integrity": "sha512-WE2sZoctWm/v4smfCAdjYbrfS55JiMRdlY9ZubFhsYbteCK9+BvAx4YV7nPjYM6ZnX5BcoVKwfmyx9sIFTgQMQ==" + }, + "define-properties": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", + "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "requires": { + "object-keys": "^1.0.12" + } + }, + "define-property": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", + "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==", + "dev": true, + "requires": { + "is-descriptor": "^1.0.2", + "isobject": "^3.0.1" + }, + "dependencies": { + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } }, "del": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/del/-/del-3.0.0.tgz", - "integrity": "sha1-U+z2mf/LyzljdpGrE7rxYIGXZuU=", - "dev": true, - "requires": { - "globby": "6.1.0", - "is-path-cwd": "1.0.0", - "is-path-in-cwd": "1.0.0", - "p-map": "1.2.0", - "pify": "3.0.0", - "rimraf": "2.5.4" - } + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/del/-/del-2.2.2.tgz", + "integrity": "sha1-wSyYHQZ4RshLyvhiz/kw2Qf/0ag=", + "dev": true, + "requires": { + "globby": "^5.0.0", + "is-path-cwd": "^1.0.0", + "is-path-in-cwd": "^1.0.0", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "rimraf": "^2.2.8" + }, + "dependencies": { + "pify": { + "version": "2.3.0", + "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + } + } + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" + }, + "delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=", + "dev": true + }, + "denque": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/denque/-/denque-1.4.1.tgz", + "integrity": "sha512-OfzPuSZKGcgr96rf1oODnfjqBFmr1DVoc/TrItj3Ohe0Ah1C5WX5Baquw/9U9KovnQ88EqmJbD66rKYUQYN1tQ==", + "dev": true + }, + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==" + }, + "deprecate": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/deprecate/-/deprecate-1.1.0.tgz", + "integrity": "sha512-b5dDNQYdy2vW9WXUD8+RQlfoxvqztLLhDE+T7Gd37I5E8My7nJkKu6FmhdDeRWJ8B+yjZKuwjCta8pgi8kgSqA==", + "dev": true + }, + "des.js": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.0.tgz", + "integrity": "sha1-wHTS4qpqipoH29YfmhXCzYPsjsw=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "destroy": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" + }, + "detect-file": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-1.0.0.tgz", + "integrity": "sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc=", + "dev": true + }, + "detect-newline": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-2.1.0.tgz", + "integrity": "sha1-9B8cEL5LAOh7XxPaaAdZ8sW/0+I=", + "dev": true + }, + "detect-node": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.0.4.tgz", + "integrity": "sha512-ZIzRpLJrOj7jjP2miAtgqIfmzbxa4ZOr5jJc601zklsfEx9oTzmmj2nVpIPRpNlRTIh8lc1kyViIY7BWSGNmKw==" + }, + "diff": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-1.4.0.tgz", + "integrity": "sha1-fyjS657nsVqX79ic5j3P2qPMur8=" + }, + "diff-sequences": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-24.9.0.tgz", + "integrity": "sha512-Dj6Wk3tWyTE+Fo1rW8v0Xhwk80um6yFYKbuAxc9c3EZxIHFDYwbi34Uk42u1CdnIiVorvt4RmlSDjIPyzGC2ew==", + "dev": true + }, + "diffie-hellman": { + "version": "5.0.3", + "resolved": "http://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", + "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "miller-rabin": "^4.0.0", + "randombytes": "^2.0.0" + } + }, + "dns-equal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/dns-equal/-/dns-equal-1.0.0.tgz", + "integrity": "sha1-s55/HabrCnW6nBcySzR1PEfgZU0=", + "dev": true + }, + "dns-packet": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-1.3.1.tgz", + "integrity": "sha512-0UxfQkMhYAUaZI+xrNZOz/as5KgDU0M/fQ9b6SpkyLbk3GEswDi6PADJVaYJradtRVsRIlF1zLyOodbcTCDzUg==", + "dev": true, + "requires": { + "ip": "^1.1.0", + "safe-buffer": "^5.0.1" + } + }, + "dns-prefetch-control": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/dns-prefetch-control/-/dns-prefetch-control-0.2.0.tgz", + "integrity": "sha512-hvSnros73+qyZXhHFjx2CMLwoj3Fe7eR9EJsFsqmcI1bB2OBWL/+0YzaEaKssCHnj/6crawNnUyw74Gm2EKe+Q==" + }, + "dns-txt": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/dns-txt/-/dns-txt-2.0.2.tgz", + "integrity": "sha1-uR2Ab10nGI5Ks+fRB9iBocxGQrY=", + "dev": true, + "requires": { + "buffer-indexof": "^1.0.0" + } + }, + "doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dev": true, + "requires": { + "esutils": "^2.0.2" + } + }, + "dom-converter": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/dom-converter/-/dom-converter-0.2.0.tgz", + "integrity": "sha512-gd3ypIPfOMr9h5jIKq8E3sHOTCjeirnl0WK5ZdS1AW0Odt0b1PaWaHdJ4Qk4klv+YB9aJBS7mESXjFoDQPu6DA==", + "dev": true, + "requires": { + "utila": "~0.4" + } + }, + "dom-serializer": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.1.tgz", + "integrity": "sha512-l0IU0pPzLWSHBcieZbpOKgkIn3ts3vAh7ZuFyXNwJxJXk/c4Gwj9xaTJwIDVQCXawWD0qb3IzMGH5rglQaO0XA==", + "requires": { + "domelementtype": "^1.3.0", + "entities": "^1.1.1" + } + }, + "domain-browser": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.2.0.tgz", + "integrity": "sha512-jnjyiM6eRyZl2H+W8Q/zLMA481hzi0eszAaBUzIVnmYVDBbnLxVNnfu1HgEBvCbL+71FrxMl3E6lpKH7Ge3OXA==", + "dev": true + }, + "domelementtype": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz", + "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==" + }, + "domexception": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/domexception/-/domexception-1.0.1.tgz", + "integrity": "sha512-raigMkn7CJNNo6Ihro1fzG7wr3fHuYVytzquZKX5n0yizGsTcYgzdIUwj1X9pK0VvjeihV+XiclP+DjwbsSKug==", + "dev": true, + "requires": { + "webidl-conversions": "^4.0.2" + } + }, + "domhandler": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.4.2.tgz", + "integrity": "sha512-JiK04h0Ht5u/80fdLMCEmV4zkNh2BcoMFBmZ/91WtYZ8qVXSKjiw7fXMgFPnHcSZgOo3XdinHvmnDUeMf5R4wA==", + "requires": { + "domelementtype": "1" + } + }, + "domutils": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.7.0.tgz", + "integrity": "sha512-Lgd2XcJ/NjEw+7tFvfKxOzCYKZsdct5lczQ2ZaQY8Djz7pfAD3Gbp8ySJWtreII/vDlMVmxwa6pHmdxIYgttDg==", + "requires": { + "dom-serializer": "0", + "domelementtype": "1" + } + }, + "dont-sniff-mimetype": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/dont-sniff-mimetype/-/dont-sniff-mimetype-1.1.0.tgz", + "integrity": "sha512-ZjI4zqTaxveH2/tTlzS1wFp+7ncxNZaIEWYg3lzZRHkKf5zPT/MnEG6WL0BhHMJUabkh8GeU5NL5j+rEUCb7Ug==" + }, + "dot-prop": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-4.2.0.tgz", + "integrity": "sha1-HxngwuGqDjJ5fEl5nyg3rGr2nFc=", + "requires": { + "is-obj": "^1.0.0" + } + }, + "duplex": { + "version": "1.0.0", + "resolved": "http://registry.npmjs.org/duplex/-/duplex-1.0.0.tgz", + "integrity": "sha1-arxcFuwX5MV4V4cnEmcAWQ06Ldo=" + }, + "duplexer": { + "version": "0.0.4", + "resolved": "http://registry.npmjs.org/duplexer/-/duplexer-0.0.4.tgz", + "integrity": "sha1-r8t/H4uNdPggcmFx1dZKyeSo/yA=" + }, + "duplexer2": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.0.2.tgz", + "integrity": "sha1-xhTc9n4vsUmVqRcR5aYX6KYKMds=", + "dev": true, + "requires": { + "readable-stream": "~1.1.9" + }, + "dependencies": { + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "readable-stream": { + "version": "1.1.14", + "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", + "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "http://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + } + } + }, + "duplexer3": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer3/-/duplexer3-0.1.4.tgz", + "integrity": "sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=" + }, + "duplexify": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-3.7.1.tgz", + "integrity": "sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g==", + "requires": { + "end-of-stream": "^1.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.0.0", + "stream-shift": "^1.0.0" + } + }, + "each-props": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/each-props/-/each-props-1.3.2.tgz", + "integrity": "sha512-vV0Hem3zAGkJAyU7JSjixeU66rwdynTAa1vofCrSA5fEln+m67Az9CcnkVD776/fsN/UjIWmBDoNRS6t6G9RfA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.1", + "object.defaults": "^1.1.0" + } + }, + "eachr": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/eachr/-/eachr-2.0.4.tgz", + "integrity": "sha1-Rm98qhBwj2EFCeMsgHqv5X/BIr8=", + "requires": { + "typechecker": "^2.0.8" + } + }, + "ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", + "requires": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "editions": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/editions/-/editions-1.3.4.tgz", + "integrity": "sha512-gzao+mxnYDzIysXKMQi/+M1mjy/rjestjg6OPoYTtI+3Izp23oiGZitsl9lPDPiTGXbcSIk1iJWhliSaglxnUg==" + }, + "ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" + }, + "ejs": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-2.6.2.tgz", + "integrity": "sha512-PcW2a0tyTuPHz3tWyYqtK6r1fZ3gp+3Sop8Ph+ZYN81Ob5rwmbHEzaqs10N3BEsaGTkh/ooniXK+WwszGlc2+Q==" + }, + "electron": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/electron/-/electron-7.1.2.tgz", + "integrity": "sha512-7hjONYt2GlQfKuKgQrhhUL1P9lbGWLBfMUq+2QFU3yeLtCvM0ROfPJCRP4OF5pVp3KDyfFp4DtmhuVzAnxV3jA==", + "requires": { + "@electron/get": "^1.0.1", + "@types/node": "^12.0.12", + "extract-zip": "^1.0.3" + }, + "dependencies": { + "@types/node": { + "version": "12.12.12", + "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.12.tgz", + "integrity": "sha512-MGuvYJrPU0HUwqF7LqvIj50RZUX23Z+m583KBygKYUZLlZ88n6w28XRNJRJgsHukLEnLz6w6SvxZoLgbr5wLqQ==" + } + } + }, + "electron-download": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/electron-download/-/electron-download-3.3.0.tgz", + "integrity": "sha1-LP1U1pZsAZxNSa1l++Zcyc3vaMg=", + "dev": true, + "requires": { + "debug": "^2.2.0", + "fs-extra": "^0.30.0", + "home-path": "^1.0.1", + "minimist": "^1.2.0", + "nugget": "^2.0.0", + "path-exists": "^2.1.0", + "rc": "^1.1.2", + "semver": "^5.3.0", + "sumchecker": "^1.2.0" + }, + "dependencies": { + "fs-extra": { + "version": "0.30.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-0.30.0.tgz", + "integrity": "sha1-8jP/zAjU2n1DLapEl3aYnbHfk/A=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "jsonfile": "^2.1.0", + "klaw": "^1.0.0", + "path-is-absolute": "^1.0.0", + "rimraf": "^2.2.8" + } + }, + "jsonfile": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-2.4.0.tgz", + "integrity": "sha1-NzaitCi4e72gzIO1P6PWM6NcKug=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.6" + } + }, + "path-exists": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", + "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", + "dev": true, + "requires": { + "pinkie-promise": "^2.0.0" + } + }, + "sumchecker": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-1.3.1.tgz", + "integrity": "sha1-ebs7RFbdBPGOvbwNcDodHa7FEF0=", + "dev": true, + "requires": { + "debug": "^2.2.0", + "es6-promise": "^4.0.5" + } + } + } + }, + "electron-to-chromium": { + "version": "1.3.264", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.264.tgz", + "integrity": "sha512-z8E7WkrrquCuGYv+kKyybuZIbdms+4PeHp7Zm2uIgEhAigP0bOwqXILItwj0YO73o+QyHY/7XtEfP5DsHOWQgQ==", + "dev": true + }, + "elliptic": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.0.tgz", + "integrity": "sha512-eFOJTMyCYb7xtE/caJ6JJu+bhi67WCYNbkGSknu20pmM8Ke/bqOfdnZWxyoGN26JgfxTbXrsCkEw4KheCT/KGg==", + "dev": true, + "requires": { + "bn.js": "^4.4.0", + "brorand": "^1.0.1", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.0" + } + }, + "emitter-listener": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/emitter-listener/-/emitter-listener-1.1.2.tgz", + "integrity": "sha512-Bt1sBAGFHY9DKY+4/2cV6izcKJUf5T7/gkdmkxzX/qv9CcGH8xSwVRW5mtX03SWJtRTWSOpzCuWN9rBFYZepZQ==", + "requires": { + "shimmer": "^1.2.0" + } + }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, + "emojis-list": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz", + "integrity": "sha1-TapNnbAPmBmIDHn6RXrlsJof04k=", + "dev": true + }, + "encode-3986": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/encode-3986/-/encode-3986-1.0.0.tgz", + "integrity": "sha1-lA1RSY+HQa3hhLda0UObMXwMemA=" + }, + "encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=" + }, + "encoding": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.12.tgz", + "integrity": "sha1-U4tm8+5izRq1HsMjgp0flIDHS+s=", + "requires": { + "iconv-lite": "~0.4.13" + } + }, + "end-of-stream": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.1.tgz", + "integrity": "sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==", + "requires": { + "once": "^1.4.0" + } + }, + "enhanced-resolve": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-4.1.0.tgz", + "integrity": "sha512-F/7vkyTtyc/llOIn8oWclcB25KdRaiPBpZYDgJHgh/UHtpgT2p2eldQgtQnLtUvfMKPKxbRaQM/hHkvLHt1Vng==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "memory-fs": "^0.4.0", + "tapable": "^1.0.0" + } + }, + "enqueue": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/enqueue/-/enqueue-1.0.2.tgz", + "integrity": "sha1-kBTpvOVw7pPKlubI5jrVTBkra8g=", + "dev": true, + "requires": { + "sliced": "0.0.5" + }, + "dependencies": { + "sliced": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz", + "integrity": "sha1-XtwETKTrb3gW1Qui/GPiXY/kcH8=", + "dev": true + } + } + }, + "ent": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/ent/-/ent-2.2.0.tgz", + "integrity": "sha1-6WQhkyWiHQX0RGai9obtbOX13R0=" + }, + "entities": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.2.tgz", + "integrity": "sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w==" + }, + "env-paths": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.0.tgz", + "integrity": "sha512-6u0VYSCo/OW6IoD5WCLLy9JUGARbamfSavcNXry/eu8aHVFei6CD3Sw+VGX5alea1i9pgPHW0mbu6Xj0uBh7gA==" + }, + "errlop": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/errlop/-/errlop-1.1.1.tgz", + "integrity": "sha512-WX7QjiPHhsny7/PQvrhS5VMizXXKoKCS3udaBp8gjlARdbn+XmK300eKBAAN0hGyRaTCtRpOaxK+xFVPUJ3zkw==", + "requires": { + "editions": "^2.1.2" + }, + "dependencies": { + "editions": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/editions/-/editions-2.1.3.tgz", + "integrity": "sha512-xDZyVm0A4nLgMNWVVLJvcwMjI80ShiH/27RyLiCnW1L273TcJIA25C4pwJ33AWV01OX6UriP35Xu+lH4S7HWQw==", + "requires": { + "errlop": "^1.1.1", + "semver": "^5.6.0" + } + } + } + }, + "errno": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.7.tgz", + "integrity": "sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg==", + "dev": true, + "requires": { + "prr": "~1.0.1" + } + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "errs": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/errs/-/errs-0.3.2.tgz", + "integrity": "sha1-eYCZstvTfKK8dJ5TinwTB9C1BJk=" + }, + "es-abstract": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.13.0.tgz", + "integrity": "sha512-vDZfg/ykNxQVwup/8E1BZhVzFfBxs9NqMzGcvIJrqg5k2/5Za2bWo40dK2J1pgLngZ7c+Shh8lwYtLGyrwPutg==", + "dev": true, + "requires": { + "es-to-primitive": "^1.2.0", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "is-callable": "^1.1.4", + "is-regex": "^1.0.4", + "object-keys": "^1.0.12" + } + }, + "es-to-primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.0.tgz", + "integrity": "sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg==", + "dev": true, + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } + }, + "es5-ext": { + "version": "0.10.50", + "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.50.tgz", + "integrity": "sha512-KMzZTPBkeQV/JcSQhI5/z6d9VWJ3EnQ194USTUwIYZ2ZbpN8+SGXQKt1h68EX44+qt+Fzr8DO17vnxrw7c3agw==", + "dev": true, + "requires": { + "es6-iterator": "~2.0.3", + "es6-symbol": "~3.1.1", + "next-tick": "^1.0.0" + } + }, + "es6-error": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz", + "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==", + "optional": true + }, + "es6-iterator": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", + "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=", + "dev": true, + "requires": { + "d": "1", + "es5-ext": "^0.10.35", + "es6-symbol": "^3.1.1" + } + }, + "es6-promise": { + "version": "4.2.8", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.8.tgz", + "integrity": "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w==" + }, + "es6-promisify": { + "version": "5.0.0", + "resolved": "http://registry.npmjs.org/es6-promisify/-/es6-promisify-5.0.0.tgz", + "integrity": "sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM=", + "requires": { + "es6-promise": "^4.0.3" + } + }, + "es6-symbol": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.1.tgz", + "integrity": "sha1-vwDvT9q2uhtG7Le2KbTH7VcVzHc=", + "dev": true, + "requires": { + "d": "1", + "es5-ext": "~0.10.14" + } + }, + "es6-templates": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/es6-templates/-/es6-templates-0.2.3.tgz", + "integrity": "sha1-XLmsn7He1usSOTQrgdeSu7QHjuQ=", + "dev": true, + "requires": { + "recast": "~0.11.12", + "through": "~2.3.6" + } + }, + "es6-weak-map": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/es6-weak-map/-/es6-weak-map-2.0.3.tgz", + "integrity": "sha512-p5um32HOTO1kP+w7PRnB+5lQ43Z6muuMuIMffvDN8ZB4GcnjLBV6zGStpbASIMk4DCAvEaamhe2zhyCb/QXXsA==", + "dev": true, + "requires": { + "d": "1", + "es5-ext": "^0.10.46", + "es6-iterator": "^2.0.3", + "es6-symbol": "^3.1.1" + } + }, + "escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, + "escodegen": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.12.0.tgz", + "integrity": "sha512-TuA+EhsanGcme5T3R0L80u4t8CpbXQjegRmf7+FPTJrtCTErXFeelblRgHQa1FofEzqYYJmJ/OqjTwREp9qgmg==", + "dev": true, + "requires": { + "esprima": "^3.1.3", + "estraverse": "^4.2.0", + "esutils": "^2.0.2", + "optionator": "^0.8.1", + "source-map": "~0.6.1" + }, + "dependencies": { + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "optional": true + } + } + }, + "eslint": { + "version": "5.16.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-5.16.0.tgz", + "integrity": "sha512-S3Rz11i7c8AA5JPv7xAH+dOyq/Cu/VXHiHXBPOU1k/JAM5dXqQPt3qcrhpHSorXmrpu2g0gkIBVXAqCpzfoZIg==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "ajv": "^6.9.1", + "chalk": "^2.1.0", + "cross-spawn": "^6.0.5", + "debug": "^4.0.1", + "doctrine": "^3.0.0", + "eslint-scope": "^4.0.3", + "eslint-utils": "^1.3.1", + "eslint-visitor-keys": "^1.0.0", + "espree": "^5.0.1", + "esquery": "^1.0.1", + "esutils": "^2.0.2", + "file-entry-cache": "^5.0.1", + "functional-red-black-tree": "^1.0.1", + "glob": "^7.1.2", + "globals": "^11.7.0", + "ignore": "^4.0.6", + "import-fresh": "^3.0.0", + "imurmurhash": "^0.1.4", + "inquirer": "^6.2.2", + "js-yaml": "^3.13.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.3.0", + "lodash": "^4.17.11", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", + "natural-compare": "^1.4.0", + "optionator": "^0.8.2", + "path-is-inside": "^1.0.2", + "progress": "^2.0.0", + "regexpp": "^2.0.1", + "semver": "^5.5.1", + "strip-ansi": "^4.0.0", + "strip-json-comments": "^2.0.1", + "table": "^5.2.3", + "text-table": "^0.2.0" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "eslint-config-google": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/eslint-config-google/-/eslint-config-google-0.11.0.tgz", + "integrity": "sha512-z541Fs5TFaY7/35v/z100InQ2f3V2J7e3u/0yKrnImgsHjh6JWgSRngfC/mZepn/+XN16jUydt64k//kxXc1fw==", + "dev": true + }, + "eslint-plugin-jasmine": { + "version": "2.10.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-jasmine/-/eslint-plugin-jasmine-2.10.1.tgz", + "integrity": "sha1-VzO3CedR9LxA4x4cFpib0s377Jc=", + "dev": true + }, + "eslint-scope": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.3.tgz", + "integrity": "sha512-p7VutNr1O/QrxysMo3E45FjYDTeXBy0iTltPFNSqKAIfjDSXC+4dj+qfyuD8bfAXrW/y6lW3O76VaYNPKfpKrg==", + "dev": true, + "requires": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + } + }, + "eslint-utils": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.4.2.tgz", + "integrity": "sha512-eAZS2sEUMlIeCjBeubdj45dmBHQwPHWyBcT1VSYB7o9x9WRRqKxyUoiXlRjyAwzN7YEzHJlYg0NmzDRWx6GP4Q==", + "dev": true, + "requires": { + "eslint-visitor-keys": "^1.0.0" + } + }, + "eslint-visitor-keys": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", + "integrity": "sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==", + "dev": true + }, + "espree": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-5.0.1.tgz", + "integrity": "sha512-qWAZcWh4XE/RwzLJejfcofscgMc9CamR6Tn1+XRXNzrvUSSbiAjGOI/fggztjIi7y9VLPqnICMIPiGyr8JaZ0A==", + "dev": true, + "requires": { + "acorn": "^6.0.7", + "acorn-jsx": "^5.0.0", + "eslint-visitor-keys": "^1.0.0" + } + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" + }, + "esquery": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.0.1.tgz", + "integrity": "sha512-SmiyZ5zIWH9VM+SRUReLS5Q8a7GxtRdxEBVZpm98rJM7Sb+A9DVCndXfkeFUd3byderg+EbDkfnevfCwynWaNA==", + "dev": true, + "requires": { + "estraverse": "^4.0.0" + } + }, + "esrecurse": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", + "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", + "dev": true, + "requires": { + "estraverse": "^4.1.0" + } + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=" + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=" + }, + "event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==" + }, + "eventemitter2": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-5.0.1.tgz", + "integrity": "sha1-YZegldX7a1folC9v1+qtY6CclFI=" + }, + "eventemitter3": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.2.tgz", + "integrity": "sha512-tvtQIeLVHjDkJYnzf2dgVMxfuSGJeM/7UCG17TT4EumTfNtF+0nebF/4zWOIkCreAbtNqhGEboB6BWrwqNaw4Q==", + "dev": true + }, + "events": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz", + "integrity": "sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ=" + }, + "eventsource": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-1.0.7.tgz", + "integrity": "sha512-4Ln17+vVT0k8aWq+t/bF5arcS3EpT9gYtW66EPacdj/mAFevznsnyoHLPy2BA8gbIQeIHoPsvwmfBftfcG//BQ==", + "dev": true, + "requires": { + "original": "^1.0.0" + } + }, + "evp_bytestokey": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", + "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", + "dev": true, + "requires": { + "md5.js": "^1.3.4", + "safe-buffer": "^5.1.1" + } + }, + "exec-sh": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/exec-sh/-/exec-sh-0.3.2.tgz", + "integrity": "sha512-9sLAvzhI5nc8TpuQUh4ahMdCrWT00wPWz7j47/emR5+2qEfoZP5zzUXvx+vdx+H6ohhnsYC31iX04QLYJK8zTg==", + "dev": true + }, + "execa": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", + "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", + "requires": { + "cross-spawn": "^6.0.0", + "get-stream": "^4.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + } + }, + "exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", + "dev": true }, "expand-brackets": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", - "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", - "dev": true, - "requires": { - "debug": "2.6.9", - "define-property": "0.2.5", - "extend-shallow": "2.0.1", - "posix-character-classes": "0.1.1", - "regex-not": "1.0.0", - "snapdragon": "0.8.1", - "to-regex": "3.0.1" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", + "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", + "dev": true, + "requires": { + "debug": "^2.3.3", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "posix-character-classes": "^0.1.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" }, - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "0.1.6" - } + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } } - } + }, + "expand-tilde": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", + "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=", + "dev": true, + "requires": { + "homedir-polyfill": "^1.0.1" + } + }, + "expect": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/expect/-/expect-24.9.0.tgz", + "integrity": "sha512-wvVAx8XIol3Z5m9zvZXiyZOQ+sRJqNTIm6sGjdWlaZIeupQGO3WbYI+15D/AmEwZywL6wtJkbAbJtzkOfBuR0Q==", + "dev": true, + "requires": { + "@jest/types": "^24.9.0", + "ansi-styles": "^3.2.0", + "jest-get-type": "^24.9.0", + "jest-matcher-utils": "^24.9.0", + "jest-message-util": "^24.9.0", + "jest-regex-util": "^24.9.0" + } + }, + "expect-ct": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/expect-ct/-/expect-ct-0.2.0.tgz", + "integrity": "sha512-6SK3MG/Bbhm8MsgyJAylg+ucIOU71/FzyFalcfu5nY19dH8y/z0tBJU0wrNBXD4B27EoQtqPF/9wqH0iYAd04g==" + }, + "express": { + "version": "4.17.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz", + "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==", + "requires": { + "accepts": "~1.3.7", + "array-flatten": "1.1.1", + "body-parser": "1.19.0", + "content-disposition": "0.5.3", + "content-type": "~1.0.4", + "cookie": "0.4.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~1.1.2", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.1.2", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.5", + "qs": "6.7.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.1.2", + "send": "0.17.1", + "serve-static": "1.14.1", + "setprototypeof": "1.1.1", + "statuses": "~1.5.0", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "dependencies": { + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" + } + } + }, + "extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" }, "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "0.1.1" - } + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", + "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", + "dev": true, + "requires": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, + "extendr": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/extendr/-/extendr-2.1.0.tgz", + "integrity": "sha1-MBqgu+pWX00tyPVw8qImEahSe1Y=", + "requires": { + "typechecker": "~2.0.1" + }, + "dependencies": { + "typechecker": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/typechecker/-/typechecker-2.0.8.tgz", + "integrity": "sha1-6D2oS7ZMWEzLNFg4V2xAsDN9uC4=" + } + } + }, + "external-editor": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.0.3.tgz", + "integrity": "sha512-bn71H9+qWoOQKyZDo25mOMVpSmXROAsTJVVVYzrrtol3d4y+AsKjf4Iwl2Q+IuT0kFSQ1qo166UuIwqYq7mGnA==", + "dev": true, + "requires": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + } }, "extglob": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", - "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", - "dev": true, - "requires": { - "array-unique": "0.3.2", - "define-property": "1.0.0", - "expand-brackets": "2.1.4", - "extend-shallow": "2.0.1", - "fragment-cache": "0.2.1", - "regex-not": "1.0.0", - "snapdragon": "0.8.1", - "to-regex": "3.0.1" - } + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", + "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", + "dev": true, + "requires": { + "array-unique": "^0.3.2", + "define-property": "^1.0.0", + "expand-brackets": "^2.1.4", + "extend-shallow": "^2.0.1", + "fragment-cache": "^0.2.1", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "extract-opts": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/extract-opts/-/extract-opts-2.2.0.tgz", + "integrity": "sha1-H6KOunNSxttID4hc63GkaBC+bX0=", + "requires": { + "typechecker": "~2.0.1" + }, + "dependencies": { + "typechecker": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/typechecker/-/typechecker-2.0.8.tgz", + "integrity": "sha1-6D2oS7ZMWEzLNFg4V2xAsDN9uC4=" + } + } + }, + "extract-zip": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-1.6.7.tgz", + "integrity": "sha1-qEC0uK9kAyZMjbV/Txp0Mz74H+k=", + "requires": { + "concat-stream": "1.6.2", + "debug": "2.6.9", + "mkdirp": "0.5.1", + "yauzl": "2.4.1" + }, + "dependencies": { + "concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + } + } + }, + "extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=" + }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=" + }, + "fancy-log": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/fancy-log/-/fancy-log-1.3.3.tgz", + "integrity": "sha512-k9oEhlyc0FrVh25qYuSELjr8oxsCoc4/LEZfg2iJJrfEk/tZL9bCoJE47gqAvI2m/AUjluCS4+3I0eTx8n3AEw==", + "dev": true, + "requires": { + "ansi-gray": "^0.1.1", + "color-support": "^1.1.3", + "parse-node-version": "^1.0.0", + "time-stamp": "^1.0.0" + } + }, + "fast-deep-equal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", + "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=" + }, + "fast-json-patch": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-patch/-/fast-json-patch-2.1.0.tgz", + "integrity": "sha512-PipOsAKamRw7+CXtKiieehyjUeDVPJ5J7b2kdJYerEf6TSUQoD2ijpVyZ88KQm5YXziff4h762bz3+vzf56khg==", + "requires": { + "deep-equal": "^1.0.1" + } + }, + "fast-json-stable-stringify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", + "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=" + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "fast-text-encoding": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fast-text-encoding/-/fast-text-encoding-1.0.0.tgz", + "integrity": "sha512-R9bHCvweUxxwkDwhjav5vxpFvdPGlVngtqmx4pIZfSUhM/Q4NiIUHB456BAf+Q1Nwu3HEZYONtu+Rya+af4jiQ==" + }, + "fastparse": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/fastparse/-/fastparse-1.1.2.tgz", + "integrity": "sha512-483XLLxTVIwWK3QTrMGRqUfUpoOs/0hbQrl2oz4J0pAcm3A3bu84wxTFqGqkJzewCLdME38xJLJAxBABfQT8sQ==", + "dev": true + }, + "faye-websocket": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.10.0.tgz", + "integrity": "sha1-TkkvjQTftviQA1B/btvy1QHnxvQ=", + "dev": true, + "requires": { + "websocket-driver": ">=0.5.1" + } + }, + "fb-watchman": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.0.tgz", + "integrity": "sha1-VOmr99+i8mzZsWNsWIwa/AXeXVg=", + "dev": true, + "requires": { + "bser": "^2.0.0" + } + }, + "fd-slicer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.0.1.tgz", + "integrity": "sha1-i1vL2ewyfFBBv5qwI/1nUPEXfmU=", + "requires": { + "pend": "~1.2.0" + } + }, + "feature-policy": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/feature-policy/-/feature-policy-0.3.0.tgz", + "integrity": "sha512-ZtijOTFN7TzCujt1fnNhfWPFPSHeZkesff9AXZj+UEjYBynWNUIYpC87Ve4wHzyexQsImicLu7WsC2LHq7/xrQ==" + }, + "figgy-pudding": { + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/figgy-pudding/-/figgy-pudding-3.5.1.tgz", + "integrity": "sha512-vNKxJHTEKNThjfrdJwHc7brvM6eVevuO5nTj6ez8ZQ1qbXTvGthucRF7S4vf2cr71QVnT70V34v0S1DyQsti0w==", + "dev": true + }, + "figures": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", + "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", + "dev": true, + "requires": { + "escape-string-regexp": "^1.0.5" + } + }, + "file-entry-cache": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-5.0.1.tgz", + "integrity": "sha512-bCg29ictuBaKUwwArK4ouCaqDgLZcysCFLmM/Yn/FDoqndh/9vNuQfXRDvTuXKLxfD/JtZQGKFT8MGcJBK644g==", + "dev": true, + "requires": { + "flat-cache": "^2.0.1" + } + }, + "file-loader": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/file-loader/-/file-loader-1.1.11.tgz", + "integrity": "sha512-TGR4HU7HUsGg6GCOPJnFk06RhWgEWFLAGWiT6rcD+GRC2keU3s9RGJ+b3Z6/U73jwwNb2gKLJ7YCrp+jvU4ALg==", + "dev": true, + "requires": { + "loader-utils": "^1.0.2", + "schema-utils": "^0.4.5" + }, + "dependencies": { + "schema-utils": { + "version": "0.4.7", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.4.7.tgz", + "integrity": "sha512-v/iwU6wvwGK8HbU9yi3/nhGzP0yGSuhQMzL6ySiec1FSrZZDkhm4noOSWzrNFo/jEc+SJY6jRTwuwbSXJPDUnQ==", + "dev": true, + "requires": { + "ajv": "^6.1.0", + "ajv-keywords": "^3.1.0" + } + } + } + }, + "filed-mimefix": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/filed-mimefix/-/filed-mimefix-0.1.3.tgz", + "integrity": "sha1-Cwtn0HWmP8dPJv3znH+dQxSWe7U=", + "requires": { + "mime": "^1.4.0" + } }, "fill-range": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", - "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", - "dev": true, - "requires": { - "extend-shallow": "2.0.1", - "is-number": "3.0.0", - "repeat-string": "1.6.1", - "to-regex-range": "2.1.1" - } + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", + "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-number": "^3.0.0", + "repeat-string": "^1.6.1", + "to-regex-range": "^2.1.0" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "finalhandler": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", + "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", + "requires": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.3", + "statuses": "~1.5.0", + "unpipe": "~1.0.0" + } + }, + "find-cache-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-2.1.0.tgz", + "integrity": "sha512-Tq6PixE0w/VMFfCgbONnkiQIVol/JJL7nRMi20fqzA4NRs9AfeqMGeRdPi3wIhYkxjeBaWh2rxwapn5Tu3IqOQ==", + "dev": true, + "requires": { + "commondir": "^1.0.1", + "make-dir": "^2.0.0", + "pkg-dir": "^3.0.0" + }, + "dependencies": { + "make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dev": true, + "requires": { + "pify": "^4.0.1", + "semver": "^5.6.0" + } + } + } + }, + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "dev": true, + "requires": { + "locate-path": "^3.0.0" + } + }, + "findup-sync": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-3.0.0.tgz", + "integrity": "sha512-YbffarhcicEhOrm4CtrwdKBdCuz576RLdhJDsIfvNtxUuhdRet1qZcsMjqbePtAseKdAnDyM/IyXbu7PRPRLYg==", + "dev": true, + "requires": { + "detect-file": "^1.0.0", + "is-glob": "^4.0.0", + "micromatch": "^3.0.4", + "resolve-dir": "^1.0.1" + } + }, + "fined": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/fined/-/fined-1.2.0.tgz", + "integrity": "sha512-ZYDqPLGxDkDhDZBjZBb+oD1+j0rA4E0pXY50eplAAOPg2N/gUBSSk5IM1/QhPfyVo19lJ+CvXpqfvk+b2p/8Ng==", + "dev": true, + "requires": { + "expand-tilde": "^2.0.2", + "is-plain-object": "^2.0.3", + "object.defaults": "^1.1.0", + "object.pick": "^1.2.0", + "parse-filepath": "^1.0.1" + } + }, + "first-chunk-stream": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/first-chunk-stream/-/first-chunk-stream-0.1.0.tgz", + "integrity": "sha1-dV0+wU1JqG49L8wIvurVwMornAo=" + }, + "flagged-respawn": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/flagged-respawn/-/flagged-respawn-1.0.1.tgz", + "integrity": "sha512-lNaHNVymajmk0OJMBn8fVUAU1BtDeKIqKoVhk4xAALB57aALg6b4W0MfJ/cUE0g9YBXy5XhSlPIpYIJ7HaY/3Q==", + "dev": true + }, + "flat-cache": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-2.0.1.tgz", + "integrity": "sha512-LoQe6yDuUMDzQAEH8sgmh4Md6oZnc/7PjtwjNFSzveXqSHt6ka9fPBuso7IGf9Rz4uqnSnWiFH2B/zj24a5ReA==", + "dev": true, + "requires": { + "flatted": "^2.0.0", + "rimraf": "2.6.3", + "write": "1.0.3" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + } + } + }, + "flatted": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.1.tgz", + "integrity": "sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg==", + "dev": true + }, + "flush-write-stream": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/flush-write-stream/-/flush-write-stream-1.1.1.tgz", + "integrity": "sha512-3Z4XhFZ3992uIq0XOqb9AreonueSYphE6oYbpt5+3u06JWklbsPkNv3ZKkP9Bz/r+1MWCaMoSQ28P85+1Yc77w==", + "dev": true, + "requires": { + "inherits": "^2.0.3", + "readable-stream": "^2.3.6" + } + }, + "follow-redirects": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.7.0.tgz", + "integrity": "sha512-m/pZQy4Gj287eNy94nivy5wchN3Kp+Q5WgUPNy5lJSZ3sgkVKSYV/ZChMAQVIgx1SqfZ2zBZtPA2YlXIWxxJOQ==", + "dev": true, + "requires": { + "debug": "^3.2.6" + }, + "dependencies": { + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "for-in": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", + "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", + "dev": true + }, + "for-own": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/for-own/-/for-own-1.0.0.tgz", + "integrity": "sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=", + "dev": true, + "requires": { + "for-in": "^1.0.1" + } + }, + "forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=" + }, + "form-data": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", + "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + } + }, + "formidable": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/formidable/-/formidable-1.2.1.tgz", + "integrity": "sha512-Fs9VRguL0gqGHkXS5GQiMCr1VhZBxz0JnJs4JmMp/2jL18Fmbzvv7vOFRU+U8TBkHEE/CX1qDXzJplVULgsLeg==" + }, + "forwarded": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", + "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=" + }, + "fragment-cache": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", + "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", + "dev": true, + "requires": { + "map-cache": "^0.2.2" + } + }, + "frameguard": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/frameguard/-/frameguard-3.1.0.tgz", + "integrity": "sha512-TxgSKM+7LTA6sidjOiSZK9wxY0ffMPY3Wta//MqwmX0nZuEHc8QrkV8Fh3ZhMJeiH+Uyh/tcaarImRy8u77O7g==" + }, + "fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=" + }, + "from2": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/from2/-/from2-2.3.0.tgz", + "integrity": "sha1-i/tVAr3kpNNs/e6gB/zKIdfjgq8=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.0" + } + }, + "fs-extra": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz", + "integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==", + "requires": { + "graceful-fs": "^4.1.2", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + } + }, + "fs-mkdirp-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-mkdirp-stream/-/fs-mkdirp-stream-1.0.0.tgz", + "integrity": "sha1-C3gV/DIBxqaeFNuYzgmMFpNSWes=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.11", + "through2": "^2.0.3" + }, + "dependencies": { + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "fs-readfile-promise": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fs-readfile-promise/-/fs-readfile-promise-2.0.1.tgz", + "integrity": "sha1-gAI4I5gfn//+AWCei+Zo9prknnA=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2" + } + }, + "fs-write-stream-atomic": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/fs-write-stream-atomic/-/fs-write-stream-atomic-1.0.10.tgz", + "integrity": "sha1-tH31NJPvkR33VzHnCp3tAYnbQMk=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "iferr": "^0.1.5", + "imurmurhash": "^0.1.4", + "readable-stream": "1 || 2" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "fsevents": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.9.tgz", + "integrity": "sha512-oeyj2H3EjjonWcFjD5NvZNE9Rqe4UW+nQBU2HNeKw0koVLEFIhtyETyAakeAM3de7Z/SW5kcA+fZUait9EApnw==", + "dev": true, + "optional": true, + "requires": { + "nan": "^2.12.1", + "node-pre-gyp": "^0.12.0" + }, + "dependencies": { + "abbrev": { + "version": "1.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "ansi-regex": { + "version": "2.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "aproba": { + "version": "1.2.0", + "bundled": true, + "dev": true, + "optional": true + }, + "are-we-there-yet": { + "version": "1.1.5", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" + } + }, + "balanced-match": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "brace-expansion": { + "version": "1.1.11", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "chownr": { + "version": "1.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "code-point-at": { + "version": "1.1.0", + "bundled": true, + "dev": true, + "optional": true + }, + "concat-map": { + "version": "0.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "console-control-strings": { + "version": "1.1.0", + "bundled": true, + "dev": true, + "optional": true + }, + "core-util-is": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "debug": { + "version": "4.1.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "ms": "^2.1.1" + } + }, + "deep-extend": { + "version": "0.6.0", + "bundled": true, + "dev": true, + "optional": true + }, + "delegates": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "detect-libc": { + "version": "1.0.3", + "bundled": true, + "dev": true, + "optional": true + }, + "fs-minipass": { + "version": "1.2.5", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minipass": "^2.2.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "gauge": { + "version": "2.7.4", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" + } + }, + "glob": { + "version": "7.1.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "has-unicode": { + "version": "2.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "iconv-lite": { + "version": "0.4.24", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "ignore-walk": { + "version": "3.0.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minimatch": "^3.0.4" + } + }, + "inflight": { + "version": "1.0.6", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "bundled": true, + "dev": true, + "optional": true + }, + "ini": { + "version": "1.3.5", + "bundled": true, + "dev": true, + "optional": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "isarray": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "minimatch": { + "version": "3.0.4", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "bundled": true, + "dev": true, + "optional": true + }, + "minipass": { + "version": "2.3.5", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "safe-buffer": "^5.1.2", + "yallist": "^3.0.0" + } + }, + "minizlib": { + "version": "1.2.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minipass": "^2.2.1" + } + }, + "mkdirp": { + "version": "0.5.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minimist": "0.0.8" + } + }, + "ms": { + "version": "2.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "needle": { + "version": "2.3.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "debug": "^4.1.0", + "iconv-lite": "^0.4.4", + "sax": "^1.2.4" + } + }, + "node-pre-gyp": { + "version": "0.12.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "detect-libc": "^1.0.2", + "mkdirp": "^0.5.1", + "needle": "^2.2.1", + "nopt": "^4.0.1", + "npm-packlist": "^1.1.6", + "npmlog": "^4.0.2", + "rc": "^1.2.7", + "rimraf": "^2.6.1", + "semver": "^5.3.0", + "tar": "^4" + } + }, + "nopt": { + "version": "4.0.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "abbrev": "1", + "osenv": "^0.1.4" + } + }, + "npm-bundled": { + "version": "1.0.6", + "bundled": true, + "dev": true, + "optional": true + }, + "npm-packlist": { + "version": "1.4.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "ignore-walk": "^3.0.1", + "npm-bundled": "^1.0.1" + } + }, + "npmlog": { + "version": "4.1.2", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" + } + }, + "number-is-nan": { + "version": "1.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "object-assign": { + "version": "4.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "once": { + "version": "1.4.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "wrappy": "1" + } + }, + "os-homedir": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "os-tmpdir": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "osenv": { + "version": "0.1.5", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "process-nextick-args": { + "version": "2.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "rc": { + "version": "1.2.8", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "bundled": true, + "dev": true, + "optional": true + } + } + }, + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "rimraf": { + "version": "2.6.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "glob": "^7.1.3" + } + }, + "safe-buffer": { + "version": "5.1.2", + "bundled": true, + "dev": true, + "optional": true + }, + "safer-buffer": { + "version": "2.1.2", + "bundled": true, + "dev": true, + "optional": true + }, + "sax": { + "version": "1.2.4", + "bundled": true, + "dev": true, + "optional": true + }, + "semver": { + "version": "5.7.0", + "bundled": true, + "dev": true, + "optional": true + }, + "set-blocking": { + "version": "2.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "signal-exit": { + "version": "3.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "string-width": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "strip-json-comments": { + "version": "2.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "tar": { + "version": "4.4.8", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "chownr": "^1.1.1", + "fs-minipass": "^1.2.5", + "minipass": "^2.3.4", + "minizlib": "^1.1.1", + "mkdirp": "^0.5.0", + "safe-buffer": "^5.1.2", + "yallist": "^3.0.2" + } + }, + "util-deprecate": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "wide-align": { + "version": "1.1.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "string-width": "^1.0.2 || 2" + } + }, + "wrappy": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "yallist": { + "version": "3.0.3", + "bundled": true, + "dev": true, + "optional": true + } + } + }, + "fstream": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.12.tgz", + "integrity": "sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "inherits": "~2.0.0", + "mkdirp": ">=0.5 0", + "rimraf": "2" + } + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "function-source": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/function-source/-/function-source-0.1.0.tgz", + "integrity": "sha1-2RBL8+RniLVUaMAr8bL6vPj8Ga8=", + "dev": true + }, + "functional-red-black-tree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", + "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", + "dev": true + }, + "g11n-pipeline": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/g11n-pipeline/-/g11n-pipeline-2.0.6.tgz", + "integrity": "sha512-ykVjThha+dGKAR/F31kCUxMn7vu1JrmUkDxMs+h7TvjGbQoNx29hsw618GQKm9eT4Qo6E+8zJAnt0BT3gMtggQ==", + "requires": { + "swagger-client": "^3.8.3" + } + }, + "gauge": { + "version": "2.7.4", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-2.7.4.tgz", + "integrity": "sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=", + "dev": true, + "requires": { + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "dev": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "http://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "dev": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, + "gaxios": { + "version": "1.8.4", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-1.8.4.tgz", + "integrity": "sha512-BoENMnu1Gav18HcpV9IleMPZ9exM+AvUjrAOV4Mzs/vfz2Lu/ABv451iEXByKiMPn2M140uul1txXCg83sAENw==", + "requires": { + "abort-controller": "^3.0.0", + "extend": "^3.0.2", + "https-proxy-agent": "^2.2.1", + "node-fetch": "^2.3.0" + } + }, + "gaze": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/gaze/-/gaze-1.1.3.tgz", + "integrity": "sha512-BRdNm8hbWzFzWHERTrejLqwHDfS4GibPoq5wjTPIoJHoBtKGPg3xAFfxmM+9ztbXelxcf2hwQcaz1PtmFeue8g==", + "dev": true, + "requires": { + "globule": "^1.0.0" + } + }, + "gcp-metadata": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-1.0.0.tgz", + "integrity": "sha512-Q6HrgfrCQeEircnNP3rCcEgiDv7eF9+1B+1MMgpE190+/+0mjQR8PxeOaRgxZWmdDAF9EIryHB9g1moPiw1SbQ==", + "requires": { + "gaxios": "^1.0.2", + "json-bigint": "^0.3.0" + } + }, + "gcs-resumable-upload": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/gcs-resumable-upload/-/gcs-resumable-upload-1.1.0.tgz", + "integrity": "sha512-uBz7uHqp44xjSDzG3kLbOYZDjxxR/UAGbB47A0cC907W6yd2LkcyFDTHg+bjivkHMwiJlKv4guVWcjPCk2zScg==", + "requires": { + "abort-controller": "^2.0.2", + "configstore": "^4.0.0", + "gaxios": "^1.5.0", + "google-auth-library": "^3.0.0", + "pumpify": "^1.5.1", + "stream-events": "^1.0.4" + }, + "dependencies": { + "abort-controller": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-2.0.3.tgz", + "integrity": "sha512-EPSq5wr2aFyAZ1PejJB32IX9Qd4Nwus+adnp7STYFM5/23nLPBazqZ1oor6ZqbH+4otaaGXTlC8RN5hq3C8w9Q==", + "requires": { + "event-target-shim": "^5.0.0" + } + } + } + }, + "generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "dev": true, + "requires": { + "is-property": "^1.0.2" + } + }, + "get-caller-file": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz", + "integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==", + "dev": true + }, + "get-stdin": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz", + "integrity": "sha1-uWjGsKBDhDJJAui/Gl3zJXmkUP4=", + "dev": true + }, + "get-stream": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", + "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", + "requires": { + "pump": "^3.0.0" + } + }, + "get-value": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", + "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", + "dev": true + }, + "getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "requires": { + "assert-plus": "^1.0.0" + } + }, + "glob": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-6.0.4.tgz", + "integrity": "sha1-DwiGD2oVUSey+t1PnOJLGqtuTSI=", + "requires": { + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "2 || 3", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } }, "glob-parent": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", - "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", - "dev": true, - "requires": { - "is-glob": "3.1.0", - "path-dirname": "1.0.2" - }, - "dependencies": { - "is-glob": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", - "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", - "dev": true, - "requires": { - "is-extglob": "2.1.1" - } + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", + "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", + "dev": true, + "requires": { + "is-glob": "^3.1.0", + "path-dirname": "^1.0.0" + }, + "dependencies": { + "is-glob": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", + "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", + "dev": true, + "requires": { + "is-extglob": "^2.1.0" + } + } + } + }, + "glob-stream": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/glob-stream/-/glob-stream-6.1.0.tgz", + "integrity": "sha1-cEXJlBOz65SIjYOrRtC0BMx73eQ=", + "dev": true, + "requires": { + "extend": "^3.0.0", + "glob": "^7.1.1", + "glob-parent": "^3.1.0", + "is-negated-glob": "^1.0.0", + "ordered-read-streams": "^1.0.0", + "pumpify": "^1.3.5", + "readable-stream": "^2.1.5", + "remove-trailing-separator": "^1.0.1", + "to-absolute-glob": "^2.0.0", + "unique-stream": "^2.0.2" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + } + } + }, + "glob-watcher": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/glob-watcher/-/glob-watcher-5.0.3.tgz", + "integrity": "sha512-8tWsULNEPHKQ2MR4zXuzSmqbdyV5PtwwCaWSGQ1WwHsJ07ilNeN1JB8ntxhckbnpSHaf9dXFUHzIWvm1I13dsg==", + "dev": true, + "requires": { + "anymatch": "^2.0.0", + "async-done": "^1.2.0", + "chokidar": "^2.0.0", + "is-negated-glob": "^1.0.0", + "just-debounce": "^1.0.0", + "object.defaults": "^1.1.0" + } + }, + "global-agent": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-2.1.7.tgz", + "integrity": "sha512-ooK7eqGYZku+LgnbfH/Iv0RJ74XfhrBZDlke1QSzcBt0bw1PmJcnRADPAQuFE+R45pKKDTynAr25SBasY2kvow==", + "optional": true, + "requires": { + "boolean": "^3.0.0", + "core-js": "^3.4.1", + "es6-error": "^4.1.1", + "matcher": "^2.0.0", + "roarr": "^2.14.5", + "semver": "^6.3.0", + "serialize-error": "^5.0.0" + }, + "dependencies": { + "core-js": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.4.2.tgz", + "integrity": "sha512-bUTfqFWtNKWp73oNIfRkqwYZJeNT3lstzZcAkhhiuvDraRSgOH1/+F9ZklbpR4zpdKuo4cpXN8tKP7s61yjX+g==", + "optional": true + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "optional": true + } + } + }, + "global-dirs": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/global-dirs/-/global-dirs-0.1.1.tgz", + "integrity": "sha1-sxnA3UYH81PzvpzKTHL8FIxJ9EU=", + "dev": true, + "requires": { + "ini": "^1.3.4" + } + }, + "global-modules": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", + "integrity": "sha1-bXcPDrUjrHgWTXK15xqIdyZcw+o=", + "dev": true, + "requires": { + "global-prefix": "^1.0.1", + "is-windows": "^1.0.1", + "resolve-dir": "^1.0.0" + } + }, + "global-prefix": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-1.0.2.tgz", + "integrity": "sha1-2/dDxsFJklk8ZVVoy2btMsASLr4=", + "dev": true, + "requires": { + "expand-tilde": "^2.0.2", + "homedir-polyfill": "^1.0.1", + "ini": "^1.3.4", + "is-windows": "^1.0.1", + "which": "^1.2.14" + } + }, + "global-tunnel-ng": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/global-tunnel-ng/-/global-tunnel-ng-2.7.1.tgz", + "integrity": "sha512-4s+DyciWBV0eK148wqXxcmVAbFVPqtc3sEtUE/GTQfuU80rySLcMhUmHKSHI7/LDj8q0gDYI1lIhRRB7ieRAqg==", + "optional": true, + "requires": { + "encodeurl": "^1.0.2", + "lodash": "^4.17.10", + "npm-conf": "^1.1.3", + "tunnel": "^0.0.6" + } + }, + "globalize": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/globalize/-/globalize-1.4.2.tgz", + "integrity": "sha512-IfKeYI5mAITBmT5EnH8kSQB5uGson4Fkj2XtTpyEbIS7IHNfLHoeTyLJ6tfjiKC6cJXng3IhVurDk5C7ORqFhQ==", + "requires": { + "cldrjs": "^0.5.0" + } + }, + "globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true + }, + "globalthis": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.0.tgz", + "integrity": "sha512-vcCAZTJ3r5Qcu5l8/2oyVdoFwxKgfYnMTR2vwWeux/NAVZK3PwcMaWkdUIn4GJbmKuRK7xcvDsLuK+CKcXyodg==", + "optional": true, + "requires": { + "define-properties": "^1.1.2", + "function-bind": "^1.1.1", + "object-keys": "^1.0.12" } - } }, "globby": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-6.1.0.tgz", - "integrity": "sha1-9abXDoOV4hyFj7BInWTfAkJNUGw=", - "dev": true, - "requires": { - "array-union": "1.0.2", - "glob": "7.1.1", - "object-assign": "4.1.0", - "pify": "2.3.0", - "pinkie-promise": "2.0.1" - }, - "dependencies": { - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", - "dev": true + "version": "5.0.0", + "resolved": "http://registry.npmjs.org/globby/-/globby-5.0.0.tgz", + "integrity": "sha1-69hGZ8oNuzMLmbz8aOrCvFQ3Dg0=", + "dev": true, + "requires": { + "array-union": "^1.0.1", + "arrify": "^1.0.0", + "glob": "^7.0.3", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "pify": { + "version": "2.3.0", + "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + } + } + }, + "globule": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/globule/-/globule-1.2.1.tgz", + "integrity": "sha512-g7QtgWF4uYSL5/dn71WxubOrS7JVGCnFPEnoeChJmBnyR9Mw8nGoEwOgJL/RC2Te0WhbsEUCejfH8SZNJ+adYQ==", + "dev": true, + "requires": { + "glob": "~7.1.1", + "lodash": "~4.17.10", + "minimatch": "~3.0.2" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + } + } + }, + "glogg": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/glogg/-/glogg-1.0.2.tgz", + "integrity": "sha512-5mwUoSuBk44Y4EshyiqcH95ZntbDdTQqA3QYSrxmzj28Ai0vXBGMH1ApSANH14j2sIRtqCEyg6PfsuP7ElOEDA==", + "dev": true, + "requires": { + "sparkles": "^1.0.0" + } + }, + "google-auth-library": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-3.1.2.tgz", + "integrity": "sha512-cDQMzTotwyWMrg5jRO7q0A4TL/3GWBgO7I7q5xGKNiiFf9SmGY/OJ1YsLMgI2MVHHsEGyrqYnbnmV1AE+Z6DnQ==", + "requires": { + "base64-js": "^1.3.0", + "fast-text-encoding": "^1.0.0", + "gaxios": "^1.2.1", + "gcp-metadata": "^1.0.0", + "gtoken": "^2.3.2", + "https-proxy-agent": "^2.2.1", + "jws": "^3.1.5", + "lru-cache": "^5.0.0", + "semver": "^5.5.0" + }, + "dependencies": { + "base64-js": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.0.tgz", + "integrity": "sha512-ccav/yGvoa80BQDljCxsmmQ3Xvx60/UpBIij5QN21W3wBi/hhIC9OoO+KLpu9IJTS9j4DRVJ3aDDF9cMSoa2lw==" + } + } + }, + "google-p12-pem": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/google-p12-pem/-/google-p12-pem-1.0.4.tgz", + "integrity": "sha512-SwLAUJqUfTB2iS+wFfSS/G9p7bt4eWcc2LyfvmUXe7cWp6p3mpxDo6LLI29MXdU6wvPcQ/up298X7GMC5ylAlA==", + "requires": { + "node-forge": "^0.8.0", + "pify": "^4.0.0" + } + }, + "got": { + "version": "6.7.1", + "resolved": "http://registry.npmjs.org/got/-/got-6.7.1.tgz", + "integrity": "sha1-JAzQV4WpoY5WHcG0S0HHY+8ejbA=", + "dev": true, + "requires": { + "create-error-class": "^3.0.0", + "duplexer3": "^0.1.4", + "get-stream": "^3.0.0", + "is-redirect": "^1.0.0", + "is-retry-allowed": "^1.0.0", + "is-stream": "^1.0.0", + "lowercase-keys": "^1.0.0", + "safe-buffer": "^5.0.1", + "timed-out": "^4.0.0", + "unzip-response": "^2.0.1", + "url-parse-lax": "^1.0.0" + }, + "dependencies": { + "get-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz", + "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=", + "dev": true + } + } + }, + "graceful-fs": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.0.tgz", + "integrity": "sha512-jpSvDPV4Cq/bgtpndIWbI5hmYxhQGHPC4d4cqBPb4DLniCfhJokdXhwhaDuLBGLQdvvRum/UiX6ECVIPvDXqdg==" + }, + "growl": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/growl/-/growl-1.9.2.tgz", + "integrity": "sha1-Dqd0NxXbjY3ixe3hd14bRayFwC8=" + }, + "growly": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/growly/-/growly-1.3.0.tgz", + "integrity": "sha1-8QdIy+dq+WS3yWyTxrzCivEgwIE=", + "dev": true + }, + "gtoken": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-2.3.3.tgz", + "integrity": "sha512-EaB49bu/TCoNeQjhCYKI/CurooBKkGxIqFHsWABW0b25fobBYVTMe84A8EBVVZhl8emiUdNypil9huMOTmyAnw==", + "requires": { + "gaxios": "^1.0.4", + "google-p12-pem": "^1.0.0", + "jws": "^3.1.5", + "mime": "^2.2.0", + "pify": "^4.0.0" + }, + "dependencies": { + "mime": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.4.tgz", + "integrity": "sha512-LRxmNwziLPT828z+4YkNzloCFC2YM4wrB99k+AV5ZbEyfGNWfG8SO1FUXLmLDBSo89NrJZ4DIWeLjy1CHGhMGA==" + } + } + }, + "gulp": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/gulp/-/gulp-4.0.2.tgz", + "integrity": "sha512-dvEs27SCZt2ibF29xYgmnwwCYZxdxhQ/+LFWlbAW8y7jt68L/65402Lz3+CKy0Ov4rOs+NERmDq7YlZaDqUIfA==", + "dev": true, + "requires": { + "glob-watcher": "^5.0.3", + "gulp-cli": "^2.2.0", + "undertaker": "^1.2.1", + "vinyl-fs": "^3.0.0" + }, + "dependencies": { + "concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "gulp-cli": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/gulp-cli/-/gulp-cli-2.2.0.tgz", + "integrity": "sha512-rGs3bVYHdyJpLqR0TUBnlcZ1O5O++Zs4bA0ajm+zr3WFCfiSLjGwoCBqFs18wzN+ZxahT9DkOK5nDf26iDsWjA==", + "dev": true, + "requires": { + "ansi-colors": "^1.0.1", + "archy": "^1.0.0", + "array-sort": "^1.0.0", + "color-support": "^1.1.3", + "concat-stream": "^1.6.0", + "copy-props": "^2.0.1", + "fancy-log": "^1.3.2", + "gulplog": "^1.0.0", + "interpret": "^1.1.0", + "isobject": "^3.0.1", + "liftoff": "^3.1.0", + "matchdep": "^2.0.0", + "mute-stdout": "^1.0.0", + "pretty-hrtime": "^1.0.0", + "replace-homedir": "^1.0.0", + "semver-greatest-satisfied-range": "^1.1.0", + "v8flags": "^3.0.1", + "yargs": "^7.1.0" + } + } + } + }, + "gulp-concat": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/gulp-concat/-/gulp-concat-2.6.1.tgz", + "integrity": "sha1-Yz0WyV2IUEYorQJmVmPO5aR5M1M=", + "dev": true, + "requires": { + "concat-with-sourcemaps": "^1.0.0", + "through2": "^2.0.0", + "vinyl": "^2.0.0" + }, + "dependencies": { + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "gulp-env": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/gulp-env/-/gulp-env-0.4.0.tgz", + "integrity": "sha1-g3BkaUmjJJPcBtrZSgZDKW+q2+g=", + "dev": true, + "requires": { + "ini": "^1.3.4", + "through2": "^2.0.0" + }, + "dependencies": { + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "gulp-file": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/gulp-file/-/gulp-file-0.4.0.tgz", + "integrity": "sha1-RRNWoqxQicbbkaBEQlKgVDZXAGs=", + "dev": true, + "requires": { + "through2": "^0.4.1", + "vinyl": "^2.1.0" + }, + "dependencies": { + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "object-keys": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-0.4.0.tgz", + "integrity": "sha1-KKaq50KN0sOpLz2V8hM13SBOAzY=", + "dev": true + }, + "readable-stream": { + "version": "1.0.34", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", + "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + }, + "through2": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/through2/-/through2-0.4.2.tgz", + "integrity": "sha1-2/WGYDEVHsg1K7bE22SiKSqEC5s=", + "dev": true, + "requires": { + "readable-stream": "~1.0.17", + "xtend": "~2.1.1" + } + }, + "xtend": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-2.1.2.tgz", + "integrity": "sha1-bv7MKk2tjmlixJAbM3znuoe10os=", + "dev": true, + "requires": { + "object-keys": "~0.4.0" + } + } + } + }, + "gulp-install": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/gulp-install/-/gulp-install-1.1.0.tgz", + "integrity": "sha1-k4a0bLRmm0cle2rfTj6i6DySiho=", + "dev": true, + "requires": { + "dargs": "^5.1.0", + "gulp-util": "^3.0.7", + "lodash.groupby": "^4.6.0", + "p-queue": "^1.0.0", + "through2": "^2.0.3", + "which": "^1.2.14" + }, + "dependencies": { + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "gulp-jasmine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/gulp-jasmine/-/gulp-jasmine-3.0.0.tgz", + "integrity": "sha1-ATFIbwzVmv/toY4AxkOZKpGWljs=", + "dev": true, + "requires": { + "arrify": "^1.0.0", + "jasmine": "^2.8.0", + "jasmine-terminal-reporter": "^1.0.3", + "plugin-error": "^0.1.2", + "through2": "^2.0.0" + }, + "dependencies": { + "arr-diff": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-1.1.0.tgz", + "integrity": "sha1-aHwydYFjWI/vfeezb6vklesaOZo=", + "dev": true, + "requires": { + "arr-flatten": "^1.0.1", + "array-slice": "^0.2.3" + } + }, + "arr-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-2.1.0.tgz", + "integrity": "sha1-IPnqtexw9cfSFbEHexw5Fh0pLH0=", + "dev": true + }, + "array-slice": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-0.2.3.tgz", + "integrity": "sha1-3Tz7gO15c6dRF82sabC5nshhhvU=", + "dev": true + }, + "extend-shallow": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-1.1.4.tgz", + "integrity": "sha1-Gda/lN/AnXa6cR85uHLSH/TdkHE=", + "dev": true, + "requires": { + "kind-of": "^1.1.0" + } + }, + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "jasmine": { + "version": "2.99.0", + "resolved": "https://registry.npmjs.org/jasmine/-/jasmine-2.99.0.tgz", + "integrity": "sha1-jKctEC5jm4Z8ZImFbg4YqceqQrc=", + "dev": true, + "requires": { + "exit": "^0.1.2", + "glob": "^7.0.6", + "jasmine-core": "~2.99.0" + } + }, + "kind-of": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-1.1.0.tgz", + "integrity": "sha1-FAo9LUGjbS78+pN3tiwk+ElaXEQ=", + "dev": true + }, + "plugin-error": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/plugin-error/-/plugin-error-0.1.2.tgz", + "integrity": "sha1-O5uzM1zPAPQl4HQ34ZJ2ln2kes4=", + "dev": true, + "requires": { + "ansi-cyan": "^0.1.1", + "ansi-red": "^0.1.1", + "arr-diff": "^1.0.1", + "arr-union": "^2.0.1", + "extend-shallow": "^1.1.2" + } + }, + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "gulp-merge-json": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/gulp-merge-json/-/gulp-merge-json-1.3.1.tgz", + "integrity": "sha512-J1N//k3Kfa0RgtzuJdn1pz+ROQF2AH2gOHGhebSc7NvATIKgeRTThPlBaOK+jvYfhNVpviWILAFo8QvUgNV4ig==", + "dev": true, + "requires": { + "deprecate": "^1.0.0", + "json5": "^1.0.1", + "lodash.mergewith": "^4.6.1", + "plugin-error": "^1.0.1", + "through": "^2.3.8", + "vinyl": "^2.1.0" + }, + "dependencies": { + "json5": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", + "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "dev": true, + "requires": { + "minimist": "^1.2.0" + } + } + } + }, + "gulp-nodemon": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/gulp-nodemon/-/gulp-nodemon-2.4.2.tgz", + "integrity": "sha512-r8ShC9yzL3lK5qUsTStMeZRwqLG6t2m4lEBVcfUYzVkiYSeYXu9xYXG5rfvzBOPZOZ2dWugTKr+zeWbnMnzWDA==", + "dev": true, + "requires": { + "colors": "^1.2.1", + "gulp": "^4.0.0", + "nodemon": "^1.18.7" + } + }, + "gulp-print": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/gulp-print/-/gulp-print-2.0.1.tgz", + "integrity": "sha1-Gs7ljqyK8tPErTMp2+RldYOTxBQ=", + "dev": true, + "requires": { + "gulp-util": "^3.0.6", + "map-stream": "~0.0.6" + } + }, + "gulp-util": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/gulp-util/-/gulp-util-3.0.8.tgz", + "integrity": "sha1-AFTh50RQLifATBh8PsxQXdVLu08=", + "dev": true, + "requires": { + "array-differ": "^1.0.0", + "array-uniq": "^1.0.2", + "beeper": "^1.0.0", + "chalk": "^1.0.0", + "dateformat": "^2.0.0", + "fancy-log": "^1.1.0", + "gulplog": "^1.0.0", + "has-gulplog": "^0.1.0", + "lodash._reescape": "^3.0.0", + "lodash._reevaluate": "^3.0.0", + "lodash._reinterpolate": "^3.0.0", + "lodash.template": "^3.0.0", + "minimist": "^1.1.0", + "multipipe": "^0.1.2", + "object-assign": "^3.0.0", + "replace-ext": "0.0.1", + "through2": "^2.0.0", + "vinyl": "^0.5.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "http://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=", + "dev": true + }, + "clone-stats": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-0.0.1.tgz", + "integrity": "sha1-uI+UqCzzi4eR1YBG6kAprYjKmdE=", + "dev": true + }, + "object-assign": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz", + "integrity": "sha1-m+3VygiXlJvKR+f/QIBi1Un1h/I=", + "dev": true + }, + "replace-ext": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-0.0.1.tgz", + "integrity": "sha1-KbvZIHinOfC8zitO5B6DeVNSKSQ=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "vinyl": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-0.5.3.tgz", + "integrity": "sha1-sEVbOPxeDPMNQyUTLkYZcMIJHN4=", + "dev": true, + "requires": { + "clone": "^1.0.0", + "clone-stats": "^0.0.1", + "replace-ext": "0.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "gulp-wrap": { + "version": "0.13.0", + "resolved": "https://registry.npmjs.org/gulp-wrap/-/gulp-wrap-0.13.0.tgz", + "integrity": "sha1-kPsLSieiZkM4Mv98YSLbXB7olMY=", + "dev": true, + "requires": { + "consolidate": "^0.14.1", + "es6-promise": "^3.1.2", + "fs-readfile-promise": "^2.0.1", + "gulp-util": "^3.0.3", + "js-yaml": "^3.2.6", + "lodash": "^4.11.1", + "node.extend": "^1.1.2", + "through2": "^2.0.1", + "tryit": "^1.0.1", + "vinyl-bufferstream": "^1.0.1" + }, + "dependencies": { + "es6-promise": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz", + "integrity": "sha1-oIzd6EzNvzTQJ6FFG8kdS80ophM=", + "dev": true + }, + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "gulp-yaml": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gulp-yaml/-/gulp-yaml-1.0.1.tgz", + "integrity": "sha1-AIHJMhOCe66xJzD5P97on9a+Ey0=", + "dev": true, + "requires": { + "bufferstreams": "1.1.0", + "gulp-util": "^3.0.6", + "js-yaml": "^3.4.3", + "through2": "^2.0.0", + "xtend": "^4.0.0" + }, + "dependencies": { + "bufferstreams": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/bufferstreams/-/bufferstreams-1.1.0.tgz", + "integrity": "sha1-BzzRIDCMBnjufXxItp4G60U4reA=", + "dev": true, + "requires": { + "readable-stream": "^2.0.2" + } + }, + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "gulplog": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gulplog/-/gulplog-1.0.0.tgz", + "integrity": "sha1-4oxNRdBey77YGDY86PnFkmIp/+U=", + "dev": true, + "requires": { + "glogg": "^1.0.0" + } + }, + "handle-thing": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/handle-thing/-/handle-thing-2.0.0.tgz", + "integrity": "sha512-d4sze1JNC454Wdo2fkuyzCr6aHcbL6PGGuFAz0Li/NcOm1tCHGnWDRmJP85dh9IhQErTc2svWFEX5xHIOo//kQ==", + "dev": true + }, + "handlebars": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.4.0.tgz", + "integrity": "sha512-xkRtOt3/3DzTKMOt3xahj2M/EqNhY988T+imYSlMgs5fVhLN2fmKVVj0LtEGmb+3UUYV5Qmm1052Mm3dIQxOvw==", + "dev": true, + "requires": { + "neo-async": "^2.6.0", + "optimist": "^0.6.1", + "source-map": "^0.6.1", + "uglify-js": "^3.1.4" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=" + }, + "har-validator": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.3.tgz", + "integrity": "sha512-sNvOCzEQNr/qrvJgc3UG/kD4QtlHycrzwS+6mfTrrSq97BvaYcPZZI1ZSqGSPR73Cxn4LKTD4PttRwfU7jWq5g==", + "requires": { + "ajv": "^6.5.5", + "har-schema": "^2.0.0" + } + }, + "harmony-reflect": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/harmony-reflect/-/harmony-reflect-1.6.1.tgz", + "integrity": "sha512-WJTeyp0JzGtHcuMsi7rw2VwtkvLa+JyfEKJCFyfcS0+CDkjQ5lHPu7zEhFZP+PDSRrEgXa5Ah0l1MbgbE41XjA==", + "dev": true + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + } + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "has-gulplog": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/has-gulplog/-/has-gulplog-0.1.0.tgz", + "integrity": "sha1-ZBTIKRNpfaUVkDl9r7EvIpZ4Ec4=", + "dev": true, + "requires": { + "sparkles": "^1.0.0" + } + }, + "has-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.0.tgz", + "integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=", + "dev": true + }, + "has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=", + "dev": true + }, + "has-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", + "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", + "dev": true, + "requires": { + "get-value": "^2.0.6", + "has-values": "^1.0.0", + "isobject": "^3.0.0" + } + }, + "has-values": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz", + "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "kind-of": "^4.0.0" + }, + "dependencies": { + "kind-of": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", + "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "hash-base": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.0.4.tgz", + "integrity": "sha1-X8hoaEfs1zSZQDMZprCj8/auSRg=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "hash-stream-validation": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/hash-stream-validation/-/hash-stream-validation-0.2.1.tgz", + "integrity": "sha1-7Mm5l7IYvluzEphii7gHhptz3NE=", + "requires": { + "through2": "^2.0.0" + }, + "dependencies": { + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=" + } + } + }, + "hash.js": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", + "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==", + "dev": true, + "requires": { + "inherits": "^2.0.3", + "minimalistic-assert": "^1.0.1" + } + }, + "he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "dev": true + }, + "helmet": { + "version": "3.21.1", + "resolved": "https://registry.npmjs.org/helmet/-/helmet-3.21.1.tgz", + "integrity": "sha512-IC/54Lxvvad2YiUdgLmPlNFKLhNuG++waTF5KPYq/Feo3NNhqMFbcLAlbVkai+9q0+4uxjxGPJ9bNykG+3zZNg==", + "requires": { + "depd": "2.0.0", + "dns-prefetch-control": "0.2.0", + "dont-sniff-mimetype": "1.1.0", + "expect-ct": "0.2.0", + "feature-policy": "0.3.0", + "frameguard": "3.1.0", + "helmet-crossdomain": "0.4.0", + "helmet-csp": "2.9.2", + "hide-powered-by": "1.1.0", + "hpkp": "2.0.0", + "hsts": "2.2.0", + "ienoopen": "1.1.0", + "nocache": "2.1.0", + "referrer-policy": "1.2.0", + "x-xss-protection": "1.3.0" + } + }, + "helmet-crossdomain": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/helmet-crossdomain/-/helmet-crossdomain-0.4.0.tgz", + "integrity": "sha512-AB4DTykRw3HCOxovD1nPR16hllrVImeFp5VBV9/twj66lJ2nU75DP8FPL0/Jp4jj79JhTfG+pFI2MD02kWJ+fA==" + }, + "helmet-csp": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/helmet-csp/-/helmet-csp-2.9.2.tgz", + "integrity": "sha512-Lt5WqNfbNjEJ6ysD4UNpVktSyjEKfU9LVJ1LaFmPfYseg/xPealPfgHhtqdAdjPDopp5zbg/VWCyp4cluMIckw==", + "requires": { + "bowser": "^2.6.1", + "camelize": "1.0.0", + "content-security-policy-builder": "2.1.0", + "dasherize": "2.0.0" + } + }, + "hide-powered-by": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/hide-powered-by/-/hide-powered-by-1.1.0.tgz", + "integrity": "sha512-Io1zA2yOA1YJslkr+AJlWSf2yWFkKjvkcL9Ni1XSUqnGLr/qRQe2UI3Cn/J9MsJht7yEVCe0SscY1HgVMujbgg==" + }, + "hmac-drbg": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", + "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", + "dev": true, + "requires": { + "hash.js": "^1.0.3", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.1" + } + }, + "home-path": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/home-path/-/home-path-1.0.7.tgz", + "integrity": "sha512-tM1pVa+u3ZqQwIkXcWfhUlY3HWS3TsnKsfi2OHHvnhkX52s9etyktPyy1rQotkr0euWimChDq+QkQuDe8ngUlQ==", + "dev": true + }, + "homedir-polyfill": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz", + "integrity": "sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==", + "dev": true, + "requires": { + "parse-passwd": "^1.0.0" + } + }, + "hosted-git-info": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.7.1.tgz", + "integrity": "sha512-7T/BxH19zbcCTa8XkMlbK5lTo1WtgkFi3GvdWEyNuc4Vex7/9Dqbnpsf4JMydcfj9HCg4zUWFTL3Za6lapg5/w==", + "dev": true + }, + "hpack.js": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/hpack.js/-/hpack.js-2.1.6.tgz", + "integrity": "sha1-h3dMCUnlE/QuhFdbPEVoH63ioLI=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "obuf": "^1.0.0", + "readable-stream": "^2.0.1", + "wbuf": "^1.1.0" + } + }, + "hpkp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/hpkp/-/hpkp-2.0.0.tgz", + "integrity": "sha1-EOFCJk52IVpdMMROxD3mTe5tFnI=" + }, + "hsts": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/hsts/-/hsts-2.2.0.tgz", + "integrity": "sha512-ToaTnQ2TbJkochoVcdXYm4HOCliNozlviNsg+X2XQLQvZNI/kCHR9rZxVYpJB3UPcHz80PgxRyWQ7PdU1r+VBQ==", + "requires": { + "depd": "2.0.0" + } + }, + "html-encoding-sniffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-1.0.2.tgz", + "integrity": "sha512-71lZziiDnsuabfdYiUeWdCVyKuqwWi23L8YeIgV9jSSZHCtb6wB1BKWooH7L3tn4/FuZJMVWyNaIDr4RGmaSYw==", + "dev": true, + "requires": { + "whatwg-encoding": "^1.0.1" + } + }, + "html-entities": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-1.2.1.tgz", + "integrity": "sha1-DfKTUfByEWNRXfueVUPl9u7VFi8=", + "dev": true + }, + "html-loader": { + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/html-loader/-/html-loader-0.4.5.tgz", + "integrity": "sha1-X7zYfNY6XEmn/OL+VvQl4Fcpxow=", + "dev": true, + "requires": { + "es6-templates": "^0.2.2", + "fastparse": "^1.1.1", + "html-minifier": "^3.0.1", + "loader-utils": "^1.0.2", + "object-assign": "^4.1.0" + } + }, + "html-loader-jest": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/html-loader-jest/-/html-loader-jest-0.2.1.tgz", + "integrity": "sha512-Sq9eDpsr/8kI+kyiQAL8jawa+aGRphANCeIeoLyU05DEfHd9vCi4Zz8AXUQTbqnF0TRGfVn9qN69/ox378kyGg==", + "dev": true, + "requires": { + "html-loader": "^0.5.1" + }, + "dependencies": { + "html-loader": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/html-loader/-/html-loader-0.5.5.tgz", + "integrity": "sha512-7hIW7YinOYUpo//kSYcPB6dCKoceKLmOwjEMmhIobHuWGDVl0Nwe4l68mdG/Ru0wcUxQjVMEoZpkalZ/SE7zog==", + "dev": true, + "requires": { + "es6-templates": "^0.2.3", + "fastparse": "^1.1.1", + "html-minifier": "^3.5.8", + "loader-utils": "^1.1.0", + "object-assign": "^4.1.1" + } + } + } + }, + "html-minifier": { + "version": "3.5.21", + "resolved": "https://registry.npmjs.org/html-minifier/-/html-minifier-3.5.21.tgz", + "integrity": "sha512-LKUKwuJDhxNa3uf/LPR/KVjm/l3rBqtYeCOAekvG8F1vItxMUpueGd94i/asDDr8/1u7InxzFA5EeGjhhG5mMA==", + "dev": true, + "requires": { + "camel-case": "3.0.x", + "clean-css": "4.2.x", + "commander": "2.17.x", + "he": "1.2.x", + "param-case": "2.1.x", + "relateurl": "0.2.x", + "uglify-js": "3.4.x" + }, + "dependencies": { + "commander": { + "version": "2.17.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.17.1.tgz", + "integrity": "sha512-wPMUt6FnH2yzG95SA6mzjQOEKUU3aLaDEmzs1ti+1E9h+CsrZghRlqEM/EJ4KscsQVG8uNN4uVreUeT8+drlgg==", + "dev": true + } + } + }, + "html-webpack-plugin": { + "version": "4.0.0-beta.5", + "resolved": "https://registry.npmjs.org/html-webpack-plugin/-/html-webpack-plugin-4.0.0-beta.5.tgz", + "integrity": "sha512-y5l4lGxOW3pz3xBTFdfB9rnnrWRPVxlAhX6nrBYIcW+2k2zC3mSp/3DxlWVCMBfnO6UAnoF8OcFn0IMy6kaKAQ==", + "dev": true, + "requires": { + "html-minifier": "^3.5.20", + "loader-utils": "^1.1.0", + "lodash": "^4.17.11", + "pretty-error": "^2.1.1", + "tapable": "^1.1.0", + "util.promisify": "1.0.0" + } + }, + "htmlparser2": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.10.1.tgz", + "integrity": "sha512-IgieNijUMbkDovyoKObU1DUhm1iwNYE/fuifEoEHfd1oZKZDaONBSkal7Y01shxsM49R4XaMdGez3WnF9UfiCQ==", + "requires": { + "domelementtype": "^1.3.1", + "domhandler": "^2.3.0", + "domutils": "^1.5.1", + "entities": "^1.1.1", + "inherits": "^2.0.1", + "readable-stream": "^3.1.1" + }, + "dependencies": { + "readable-stream": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.4.0.tgz", + "integrity": "sha512-jItXPLmrSR8jmTRmRWJXCnGJsfy85mB3Wd/uINMXA65yrnFo0cPClFIUWzo2najVNSl+mx7/4W8ttlLWJe99pQ==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + } + } + }, + "http-cache-semantics": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.0.3.tgz", + "integrity": "sha512-TcIMG3qeVLgDr1TEd2XvHaTnMPwYQUQMIBLy+5pLSDKYFc7UIqj39w8EGzZkaxoLv/l2K8HaI0t5AVA+YYgUew==" + }, + "http-deceiver": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/http-deceiver/-/http-deceiver-1.2.7.tgz", + "integrity": "sha1-+nFolEq5pRnTN8sL7HKE3D5yPYc=", + "dev": true + }, + "http-errors": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", + "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", + "requires": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.1", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.0" + }, + "dependencies": { + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + } + } + }, + "http-parser-js": { + "version": "0.4.10", + "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.4.10.tgz", + "integrity": "sha1-ksnBN0w1CF912zWexWzCV8u5P6Q=", + "dev": true + }, + "http-proxy": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.17.0.tgz", + "integrity": "sha512-Taqn+3nNvYRfJ3bGvKfBSRwy1v6eePlm3oc/aWVxZp57DQr5Eq3xhKJi7Z4hZpS8PC3H4qI+Yly5EmFacGuA/g==", + "dev": true, + "requires": { + "eventemitter3": "^3.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + } + }, + "http-proxy-middleware": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-0.19.1.tgz", + "integrity": "sha512-yHYTgWMQO8VvwNS22eLLloAkvungsKdKTLO8AJlftYIKNfJr3GK3zK0ZCfzDDGUBttdGc8xFy1mCitvNKQtC3Q==", + "dev": true, + "requires": { + "http-proxy": "^1.17.0", + "is-glob": "^4.0.0", + "lodash": "^4.17.11", + "micromatch": "^3.1.10" + } + }, + "http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "requires": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + } + }, + "http-status": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/http-status/-/http-status-1.3.2.tgz", + "integrity": "sha512-vR1YTaDyi2BukI0UiH01xy92oiZi4in7r0dmSPnrZg72Vu1SzyOLalwWP5NUk1rNiB2L+XVK2lcSVOqaertX8A==" + }, + "httpntlm": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/httpntlm/-/httpntlm-1.6.1.tgz", + "integrity": "sha1-rQFScUOi6Hc8+uapb1hla7UqNLI=", + "requires": { + "httpreq": ">=0.4.22", + "underscore": "~1.7.0" + } + }, + "httpreq": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/httpreq/-/httpreq-0.4.24.tgz", + "integrity": "sha1-QzX/2CzZaWaKOUZckprGHWOTYn8=" + }, + "https-browserify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-1.0.0.tgz", + "integrity": "sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM=", + "dev": true + }, + "https-proxy-agent": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-2.2.4.tgz", + "integrity": "sha512-OmvfoQ53WLjtA9HeYP9RNrWMJzzAz1JGaSFr1nijg0PVR1JaD/xbJq1mdEIIlxGpXp9eSe/O2LgU9DJmTPd0Eg==", + "requires": { + "agent-base": "^4.3.0", + "debug": "^3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "i18n": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/i18n/-/i18n-0.8.3.tgz", + "integrity": "sha1-LYzxwkciYCwgQdAbpq5eqlE4jw4=", + "requires": { + "debug": "*", + "make-plural": "^3.0.3", + "math-interval-parser": "^1.1.0", + "messageformat": "^0.3.1", + "mustache": "*", + "sprintf-js": ">=1.0.3" + } + }, + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "icss-replace-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/icss-replace-symbols/-/icss-replace-symbols-1.1.0.tgz", + "integrity": "sha1-Bupvg2ead0njhs/h/oEq5dsiPe0=", + "dev": true + }, + "icss-utils": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/icss-utils/-/icss-utils-4.1.1.tgz", + "integrity": "sha512-4aFq7wvWyMHKgxsH8QQtGpvbASCf+eM3wPRLI6R+MgAnTCZ6STYsRvttLvRWK0Nfif5piF394St3HeJDaljGPA==", + "dev": true, + "requires": { + "postcss": "^7.0.14" + } + }, + "identity-obj-proxy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/identity-obj-proxy/-/identity-obj-proxy-3.0.0.tgz", + "integrity": "sha1-lNK9qWCERT7zb7xarsN+D3nx/BQ=", + "dev": true, + "requires": { + "harmony-reflect": "^1.4.6" + } + }, + "ieee754": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.8.tgz", + "integrity": "sha1-vjPUCsEO8ZJnAfbwii2G+/0a0+Q=" + }, + "ienoopen": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/ienoopen/-/ienoopen-1.1.0.tgz", + "integrity": "sha512-MFs36e/ca6ohEKtinTJ5VvAJ6oDRAYFdYXweUnGY9L9vcoqFOU4n2ZhmJ0C4z/cwGZ3YIQRSB3XZ1+ghZkY5NQ==" + }, + "iferr": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/iferr/-/iferr-0.1.5.tgz", + "integrity": "sha1-xg7taebY/bazEEofy8ocGS3FtQE=", + "dev": true + }, + "ignore": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "dev": true + }, + "ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha1-SMptcvbGo68Aqa1K5odr44ieKwk=", + "dev": true + }, + "ignorefs": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/ignorefs/-/ignorefs-1.2.0.tgz", + "integrity": "sha1-2ln7hYl25KXkNwLM0fKC/byeV1Y=", + "requires": { + "editions": "^1.3.3", + "ignorepatterns": "^1.1.0" + } + }, + "ignorepatterns": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/ignorepatterns/-/ignorepatterns-1.1.0.tgz", + "integrity": "sha1-rI9DbyI5td+2bV8NOpBKh6xnzF4=" + }, + "import-fresh": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.1.0.tgz", + "integrity": "sha512-PpuksHKGt8rXfWEr9m9EHIpgyyaltBy8+eF6GJM0QCAxMgxCfucMF3mjecK2QsJr0amJW7gTqh5/wht0z2UhEQ==", + "dev": true, + "requires": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + } + }, + "import-lazy": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-2.1.0.tgz", + "integrity": "sha1-BWmOPUXIjo1+nZLLBYTnfwlvPkM=", + "dev": true + }, + "import-local": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-2.0.0.tgz", + "integrity": "sha512-b6s04m3O+s3CGSbqDIyP4R6aAwAeYlVq9+WUWep6iHa8ETRf9yei1U48C5MmfJmV9AiLYYBKPMq/W+/WRpQmCQ==", + "dev": true, + "requires": { + "pkg-dir": "^3.0.0", + "resolve-cwd": "^2.0.0" + } + }, + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=" + }, + "in-publish": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/in-publish/-/in-publish-2.0.0.tgz", + "integrity": "sha1-4g/146KvwmkDILbcVSaCqcf631E=", + "dev": true + }, + "indent-string": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-2.1.0.tgz", + "integrity": "sha1-ji1INIdCEhtKghi3oTfppSBJ3IA=", + "dev": true, + "requires": { + "repeating": "^2.0.0" + } + }, + "indexes-of": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/indexes-of/-/indexes-of-1.0.1.tgz", + "integrity": "sha1-8w9xbI4r00bHtn0985FVZqfAVgc=", + "dev": true + }, + "inflection": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/inflection/-/inflection-1.12.0.tgz", + "integrity": "sha1-ogCTVlbW9fa8TcdQLhrstwMihBY=" + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "ini": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", + "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==" + }, + "inquirer": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.4.1.tgz", + "integrity": "sha512-/Jw+qPZx4EDYsaT6uz7F4GJRNFMRdKNeUZw3ZnKV8lyuUgz/YWRCSUAJMZSVhSq4Ec0R2oYnyi6b3d4JXcL5Nw==", + "dev": true, + "requires": { + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", + "cli-cursor": "^2.1.0", + "cli-width": "^2.0.0", + "external-editor": "^3.0.3", + "figures": "^2.0.0", + "lodash": "^4.17.11", + "mute-stream": "0.0.7", + "run-async": "^2.2.0", + "rxjs": "^6.4.0", + "string-width": "^2.1.0", + "strip-ansi": "^5.1.0", + "through": "^2.3.6" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" + } + } + } + }, + "internal-ip": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/internal-ip/-/internal-ip-4.3.0.tgz", + "integrity": "sha512-S1zBo1D6zcsyuC6PMmY5+55YMILQ9av8lotMx447Bq6SAgo/sDK6y6uUKmuYhW7eacnIhFfsPmCNYdDzsnnDCg==", + "dev": true, + "requires": { + "default-gateway": "^4.2.0", + "ipaddr.js": "^1.9.0" + } + }, + "interpret": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.2.0.tgz", + "integrity": "sha512-mT34yGKMNceBQUoVn7iCDKDntA7SC6gycMAWzGx1z/CMCTV7b2AAtXlo3nRyHZ1FelRkQbQjprHSYGwzLtkVbw==", + "dev": true + }, + "invariant": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz", + "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==", + "dev": true, + "requires": { + "loose-envify": "^1.0.0" + } + }, + "invert-kv": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz", + "integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==" + }, + "ip": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/ip/-/ip-1.1.5.tgz", + "integrity": "sha1-vd7XARQpCCjAoDnnLvJfWq7ENUo=" + }, + "ip-regex": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-2.1.0.tgz", + "integrity": "sha1-+ni/XS5pE8kRzp+BnuUUa7bYROk=", + "dev": true + }, + "ipaddr.js": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.0.tgz", + "integrity": "sha512-M4Sjn6N/+O6/IXSJseKqHoFc+5FdGJ22sXqnjTpdZweHK64MzEPAyQZyEU3R/KRv2GLoa7nNtg/C2Ev6m7z+eA==" + }, + "is": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/is/-/is-3.3.0.tgz", + "integrity": "sha512-nW24QBoPcFGGHJGUwnfpI7Yc5CdqWNdsyHQszVE/z2pKHXzh7FZ5GWhJqSyaQ9wMkQnsTx+kAI8bHlCX4tKdbg==", + "dev": true + }, + "is-absolute": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-absolute/-/is-absolute-1.0.0.tgz", + "integrity": "sha512-dOWoqflvcydARa360Gvv18DZ/gRuHKi2NU/wU5X1ZFzdYfH29nkiNZsF3mp4OJ3H4yo9Mx8A/uAGNzpzPN3yBA==", + "dev": true, + "requires": { + "is-relative": "^1.0.0", + "is-windows": "^1.0.1" } - } }, "is-accessor-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", - "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } + "version": "0.1.6", + "resolved": "http://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "dev": true + }, + "is-binary-path": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz", + "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=", + "dev": true, + "requires": { + "binary-extensions": "^1.0.0" } - } }, "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "dev": true + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==" + }, + "is-callable": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.4.tgz", + "integrity": "sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA==", + "dev": true + }, + "is-ci": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-1.2.1.tgz", + "integrity": "sha512-s6tfsaQaQi3JNciBH6shVqEDvhGut0SUXr31ag8Pd8BBbVVlcGfWhpPmEOoM6RJ5TFhbypvf5yyRw/VXW1IiWg==", + "dev": true, + "requires": { + "ci-info": "^1.5.0" + } }, "is-data-descriptor": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", - "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } + "version": "0.1.4", + "resolved": "http://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } } - } + }, + "is-date-object": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz", + "integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=", + "dev": true }, "is-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", - "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", - "dev": true, - "requires": { - "is-accessor-descriptor": "0.1.6", - "is-data-descriptor": "0.1.4", - "kind-of": "5.1.0" - }, - "dependencies": { - "kind-of": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", - "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", - "dev": true + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^0.1.6", + "is-data-descriptor": "^0.1.4", + "kind-of": "^5.0.0" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } } - } + }, + "is-extendable": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", + "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", + "dev": true }, "is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", - "dev": true + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "dev": true + }, + "is-finite": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.0.2.tgz", + "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", + "dev": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true + }, + "is-generator-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", + "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", + "dev": true }, "is-glob": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.0.tgz", - "integrity": "sha1-lSHHaEXMJhCoUgPd8ICpWML/q8A=", - "dev": true, - "requires": { - "is-extglob": "2.1.1" - } + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", + "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", + "dev": true, + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-installed-globally": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-installed-globally/-/is-installed-globally-0.1.0.tgz", + "integrity": "sha1-Df2Y9akRFxbdU13aZJL2e/PSWoA=", + "dev": true, + "requires": { + "global-dirs": "^0.1.0", + "is-path-inside": "^1.0.0" + } + }, + "is-negated-glob": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-negated-glob/-/is-negated-glob-1.0.0.tgz", + "integrity": "sha1-aRC8pdqMleeEtXUbl2z1oQ/uNtI=", + "dev": true + }, + "is-npm": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-npm/-/is-npm-1.0.0.tgz", + "integrity": "sha1-8vtjpl5JBbQGyGBydloaTceTufQ=", + "dev": true }, "is-number": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", - "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", - "dev": true, - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } } - } + }, + "is-obj": { + "version": "1.0.1", + "resolved": "http://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", + "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=" + }, + "is-path-cwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-1.0.0.tgz", + "integrity": "sha1-0iXsIxMuie3Tj9p2dHLmLmXxEG0=", + "dev": true + }, + "is-path-in-cwd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-path-in-cwd/-/is-path-in-cwd-1.0.1.tgz", + "integrity": "sha512-FjV1RTW48E7CWM7eE/J2NJvAEEVektecDBVBE5Hh3nM1Jd0kvhHtX68Pr3xsDf857xt3Y4AkwVULK1Vku62aaQ==", + "dev": true, + "requires": { + "is-path-inside": "^1.0.0" + } + }, + "is-path-inside": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-1.0.1.tgz", + "integrity": "sha1-jvW33lBDej/cprToZe96pVy0gDY=", + "dev": true, + "requires": { + "path-is-inside": "^1.0.1" + } + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha1-LBY7P6+xtgbZ0Xko8FwqHDjgdnc=", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + }, + "is-promise": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", + "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=", + "dev": true + }, + "is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha1-V/4cTkhHTt1lsJkR8msc1Ald2oQ=", + "dev": true + }, + "is-redirect": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-redirect/-/is-redirect-1.0.0.tgz", + "integrity": "sha1-HQPd7VO9jbDzDCbk+V02/HyH3CQ=", + "dev": true + }, + "is-regex": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz", + "integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", + "dev": true, + "requires": { + "has": "^1.0.1" + } + }, + "is-relative": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-relative/-/is-relative-1.0.0.tgz", + "integrity": "sha512-Kw/ReK0iqwKeu0MITLFuj0jbPAmEiOsIwyIXvvbfa6QfmN9pkD1M+8pdk7Rl/dTKbH34/XBFMbgD4iMJhLQbGA==", + "dev": true, + "requires": { + "is-unc-path": "^1.0.0" + } + }, + "is-retry-allowed": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-1.1.0.tgz", + "integrity": "sha1-EaBgVotnM5REAz0BJaYaINVk+zQ=", + "dev": true + }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=" + }, + "is-stream-ended": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-stream-ended/-/is-stream-ended-0.1.4.tgz", + "integrity": "sha512-xj0XPvmr7bQFTvirqnFr50o0hQIh6ZItDqloxt5aJrR4NQsYeSsyFQERYGCAzfindAcnKjINnwEEgLx4IqVzQw==" + }, + "is-symbol": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.2.tgz", + "integrity": "sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw==", + "dev": true, + "requires": { + "has-symbols": "^1.0.0" + } + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" + }, + "is-unc-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-unc-path/-/is-unc-path-1.0.0.tgz", + "integrity": "sha512-mrGpVd0fs7WWLfVsStvgF6iEJnbjDFZh9/emhRDcGWTduTfNHd9CHeUwH3gYIjdbwo4On6hunkztwOaAw0yllQ==", + "dev": true, + "requires": { + "unc-path-regex": "^0.1.2" + } + }, + "is-utf8": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", + "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=" + }, + "is-valid-glob": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-valid-glob/-/is-valid-glob-1.0.0.tgz", + "integrity": "sha1-Kb8+/3Ab4tTTFdusw5vDn+j2Aao=", + "dev": true + }, + "is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true + }, + "is-wsl": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-1.1.0.tgz", + "integrity": "sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0=", + "dev": true + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" + }, + "isemail": { + "version": "2.2.1", + "resolved": "http://registry.npmjs.org/isemail/-/isemail-2.2.1.tgz", + "integrity": "sha1-A1PT2aYpUQgMJiwqoKQrjqjp4qY=" + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" }, "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=" + }, + "isomorphic-form-data": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isomorphic-form-data/-/isomorphic-form-data-0.0.1.tgz", + "integrity": "sha1-Am9ifgMrDNhBPsyHVZKLlKRosGI=", + "requires": { + "form-data": "^1.0.0-rc3" + }, + "dependencies": { + "async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", + "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", + "requires": { + "lodash": "^4.17.11" + } + }, + "form-data": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-1.0.1.tgz", + "integrity": "sha1-rjFduaSQf6BlUCMEpm13M0de43w=", + "requires": { + "async": "^2.0.1", + "combined-stream": "^1.0.5", + "mime-types": "^2.1.11" + } + } + } + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" + }, + "istanbul-lib-coverage": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.5.tgz", + "integrity": "sha512-8aXznuEPCJvGnMSRft4udDRDtb1V3pkQkMMI5LI+6HuQz5oQ4J2UFn1H82raA3qJtyOLkkwVqICBQkjnGtn5mA==", + "dev": true + }, + "istanbul-lib-instrument": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-3.3.0.tgz", + "integrity": "sha512-5nnIN4vo5xQZHdXno/YDXJ0G+I3dAm4XgzfSVTPLQpj/zAV2dV6Juy0yaf10/zrJOJeHoN3fraFe+XRq2bFVZA==", + "dev": true, + "requires": { + "@babel/generator": "^7.4.0", + "@babel/parser": "^7.4.3", + "@babel/template": "^7.4.0", + "@babel/traverse": "^7.4.3", + "@babel/types": "^7.4.0", + "istanbul-lib-coverage": "^2.0.5", + "semver": "^6.0.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "istanbul-lib-report": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-2.0.8.tgz", + "integrity": "sha512-fHBeG573EIihhAblwgxrSenp0Dby6tJMFR/HvlerBsrCTD5bkUuoNtn3gVh29ZCS824cGGBPn7Sg7cNk+2xUsQ==", + "dev": true, + "requires": { + "istanbul-lib-coverage": "^2.0.5", + "make-dir": "^2.1.0", + "supports-color": "^6.1.0" + }, + "dependencies": { + "make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dev": true, + "requires": { + "pify": "^4.0.1", + "semver": "^5.6.0" + } + }, + "supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "istanbul-lib-source-maps": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-3.0.6.tgz", + "integrity": "sha512-R47KzMtDJH6X4/YW9XTx+jrLnZnscW4VpNN+1PViSYTejLVPWv7oov+Duf8YQSPyVRUvueQqz1TcsC6mooZTXw==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^2.0.5", + "make-dir": "^2.1.0", + "rimraf": "^2.6.3", + "source-map": "^0.6.1" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dev": true, + "requires": { + "pify": "^4.0.1", + "semver": "^5.6.0" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "istanbul-reports": { + "version": "2.2.6", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-2.2.6.tgz", + "integrity": "sha512-SKi4rnMyLBKe0Jy2uUdx28h8oG7ph2PPuQPvIAh31d+Ci+lSiEu4C+h3oBPuJ9+mPKhOyW0M8gY4U5NM1WLeXA==", + "dev": true, + "requires": { + "handlebars": "^4.1.2" + } + }, + "jade": { + "version": "0.26.3", + "resolved": "https://registry.npmjs.org/jade/-/jade-0.26.3.tgz", + "integrity": "sha1-jxDXl32NefL2/4YqgbBRPMslaGw=", + "requires": { + "commander": "0.6.1", + "mkdirp": "0.3.0" + }, + "dependencies": { + "commander": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-0.6.1.tgz", + "integrity": "sha1-+mihT2qUXVTbvlDYzbMyDp47GgY=" + }, + "mkdirp": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.3.0.tgz", + "integrity": "sha1-G79asbqCevI1dRQ0kEJkVfSB/h4=" + } + } + }, + "jasmine": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/jasmine/-/jasmine-3.4.0.tgz", + "integrity": "sha512-sR9b4n+fnBFDEd7VS2el2DeHgKcPiMVn44rtKFumq9q7P/t8WrxsVIZPob4UDdgcDNCwyDqwxCt4k9TDRmjPoQ==", + "dev": true, + "requires": { + "glob": "^7.1.3", + "jasmine-core": "~3.4.0" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "jasmine-core": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-3.4.0.tgz", + "integrity": "sha512-HU/YxV4i6GcmiH4duATwAbJQMlE0MsDIR5XmSVxURxKHn3aGAdbY1/ZJFmVRbKtnLwIxxMJD7gYaPsypcbYimg==", + "dev": true + } + } + }, + "jasmine-core": { + "version": "2.99.1", + "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-2.99.1.tgz", + "integrity": "sha1-5kAN8ea1bhMLYcS80JPap/boyhU=", + "dev": true + }, + "jasmine-reporters": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/jasmine-reporters/-/jasmine-reporters-2.3.2.tgz", + "integrity": "sha512-u/7AT9SkuZsUfFBLLzbErohTGNsEUCKaQbsVYnLFW1gEuL2DzmBL4n8v90uZsqIqlWvWUgian8J6yOt5Fyk/+A==", + "dev": true, + "requires": { + "mkdirp": "^0.5.1", + "xmldom": "^0.1.22" + }, + "dependencies": { + "xmldom": { + "version": "0.1.27", + "resolved": "https://registry.npmjs.org/xmldom/-/xmldom-0.1.27.tgz", + "integrity": "sha1-1QH5ezvbQDr4757MIFcxh6rawOk=", + "dev": true + } + } + }, + "jasmine-spec-reporter": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/jasmine-spec-reporter/-/jasmine-spec-reporter-4.2.1.tgz", + "integrity": "sha1-HWMq7ANBZwrTJPkrqEtLMrNeniI=", + "dev": true, + "requires": { + "colors": "1.1.2" + }, + "dependencies": { + "colors": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.1.2.tgz", + "integrity": "sha1-FopHAXVran9RoSzgyXv6KMCE7WM=", + "dev": true + } + } + }, + "jasmine-terminal-reporter": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/jasmine-terminal-reporter/-/jasmine-terminal-reporter-1.0.3.tgz", + "integrity": "sha1-iW8eyP30v2rs3UHFA+2nNH9hUms=", + "dev": true, + "requires": { + "indent-string": "^2.1.0", + "pluralize": "^1.2.1" + } + }, + "jayson": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/jayson/-/jayson-2.1.2.tgz", + "integrity": "sha512-2GejcQnEV35KYTXoBvzALIDdO/1oyEIoJHBnaJFhJhcurv0x2JqUXQW6xlDUhcNOpN9t+d2w+JGA6vOphb+5mg==", + "requires": { + "@types/node": "^10.3.5", + "JSONStream": "^1.3.1", + "commander": "^2.12.2", + "es6-promisify": "^5.0.0", + "eyes": "^0.1.8", + "json-stringify-safe": "^5.0.1", + "lodash": "^4.17.11", + "uuid": "^3.2.1" + } + }, + "jest": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest/-/jest-24.9.0.tgz", + "integrity": "sha512-YvkBL1Zm7d2B1+h5fHEOdyjCG+sGMz4f8D86/0HiqJ6MB4MnDc8FgP5vdWsGnemOQro7lnYo8UakZ3+5A0jxGw==", + "dev": true, + "requires": { + "import-local": "^2.0.0", + "jest-cli": "^24.9.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true + }, + "ci-info": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", + "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==", + "dev": true + }, + "cliui": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", + "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", + "dev": true, + "requires": { + "string-width": "^3.1.0", + "strip-ansi": "^5.2.0", + "wrap-ansi": "^5.1.0" + } + }, + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true + }, + "is-ci": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", + "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", + "dev": true, + "requires": { + "ci-info": "^2.0.0" + } + }, + "jest-cli": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-24.9.0.tgz", + "integrity": "sha512-+VLRKyitT3BWoMeSUIHRxV/2g8y9gw91Jh5z2UmXZzkZKpbC08CSehVxgHUwTpy+HwGcns/tqafQDJW7imYvGg==", + "dev": true, + "requires": { + "@jest/core": "^24.9.0", + "@jest/test-result": "^24.9.0", + "@jest/types": "^24.9.0", + "chalk": "^2.0.1", + "exit": "^0.1.2", + "import-local": "^2.0.0", + "is-ci": "^2.0.0", + "jest-config": "^24.9.0", + "jest-util": "^24.9.0", + "jest-validate": "^24.9.0", + "prompts": "^2.0.1", + "realpath-native": "^1.1.0", + "yargs": "^13.3.0" + } + }, + "require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "dev": true + }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + } + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" + } + }, + "which-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", + "dev": true + }, + "wrap-ansi": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.0", + "string-width": "^3.0.0", + "strip-ansi": "^5.0.0" + } + }, + "y18n": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", + "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==", + "dev": true + }, + "yargs": { + "version": "13.3.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.0.tgz", + "integrity": "sha512-2eehun/8ALW8TLoIl7MVaRUrg+yCnenu8B4kBlRxj3GJGDKU1Og7sMXPNm1BYyM1DOJmTZ4YeN/Nwxv+8XJsUA==", + "dev": true, + "requires": { + "cliui": "^5.0.0", + "find-up": "^3.0.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^3.0.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^13.1.1" + } + }, + "yargs-parser": { + "version": "13.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.1.tgz", + "integrity": "sha512-oVAVsHz6uFrg3XQheFII8ESO2ssAf9luWuAd6Wexsu4F3OtIW0o8IribPXYrD4WC24LWtPrJlGy87y5udK+dxQ==", + "dev": true, + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + } + } + }, + "jest-changed-files": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-24.9.0.tgz", + "integrity": "sha512-6aTWpe2mHF0DhL28WjdkO8LyGjs3zItPET4bMSeXU6T3ub4FPMw+mcOcbdGXQOAfmLcxofD23/5Bl9Z4AkFwqg==", + "dev": true, + "requires": { + "@jest/types": "^24.9.0", + "execa": "^1.0.0", + "throat": "^4.0.0" + } + }, + "jest-config": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-24.9.0.tgz", + "integrity": "sha512-RATtQJtVYQrp7fvWg6f5y3pEFj9I+H8sWw4aKxnDZ96mob5i5SD6ZEGWgMLXQ4LE8UurrjbdlLWdUeo+28QpfQ==", + "dev": true, + "requires": { + "@babel/core": "^7.1.0", + "@jest/test-sequencer": "^24.9.0", + "@jest/types": "^24.9.0", + "babel-jest": "^24.9.0", + "chalk": "^2.0.1", + "glob": "^7.1.1", + "jest-environment-jsdom": "^24.9.0", + "jest-environment-node": "^24.9.0", + "jest-get-type": "^24.9.0", + "jest-jasmine2": "^24.9.0", + "jest-regex-util": "^24.3.0", + "jest-resolve": "^24.9.0", + "jest-util": "^24.9.0", + "jest-validate": "^24.9.0", + "micromatch": "^3.1.10", + "pretty-format": "^24.9.0", + "realpath-native": "^1.1.0" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + } + } + }, + "jest-diff": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-24.9.0.tgz", + "integrity": "sha512-qMfrTs8AdJE2iqrTp0hzh7kTd2PQWrsFyj9tORoKmu32xjPjeE4NyjVRDz8ybYwqS2ik8N4hsIpiVTyFeo2lBQ==", + "dev": true, + "requires": { + "chalk": "^2.0.1", + "diff-sequences": "^24.9.0", + "jest-get-type": "^24.9.0", + "pretty-format": "^24.9.0" + } + }, + "jest-docblock": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-24.9.0.tgz", + "integrity": "sha512-F1DjdpDMJMA1cN6He0FNYNZlo3yYmOtRUnktrT9Q37njYzC5WEaDdmbynIgy0L/IvXvvgsG8OsqhLPXTpfmZAA==", + "dev": true, + "requires": { + "detect-newline": "^2.1.0" + } + }, + "jest-each": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-24.9.0.tgz", + "integrity": "sha512-ONi0R4BvW45cw8s2Lrx8YgbeXL1oCQ/wIDwmsM3CqM/nlblNCPmnC3IPQlMbRFZu3wKdQ2U8BqM6lh3LJ5Bsog==", + "dev": true, + "requires": { + "@jest/types": "^24.9.0", + "chalk": "^2.0.1", + "jest-get-type": "^24.9.0", + "jest-util": "^24.9.0", + "pretty-format": "^24.9.0" + } + }, + "jest-environment-jsdom": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-24.9.0.tgz", + "integrity": "sha512-Zv9FV9NBRzLuALXjvRijO2351DRQeLYXtpD4xNvfoVFw21IOKNhZAEUKcbiEtjTkm2GsJ3boMVgkaR7rN8qetA==", + "dev": true, + "requires": { + "@jest/environment": "^24.9.0", + "@jest/fake-timers": "^24.9.0", + "@jest/types": "^24.9.0", + "jest-mock": "^24.9.0", + "jest-util": "^24.9.0", + "jsdom": "^11.5.1" + } + }, + "jest-environment-node": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-24.9.0.tgz", + "integrity": "sha512-6d4V2f4nxzIzwendo27Tr0aFm+IXWa0XEUnaH6nU0FMaozxovt+sfRvh4J47wL1OvF83I3SSTu0XK+i4Bqe7uA==", + "dev": true, + "requires": { + "@jest/environment": "^24.9.0", + "@jest/fake-timers": "^24.9.0", + "@jest/types": "^24.9.0", + "jest-mock": "^24.9.0", + "jest-util": "^24.9.0" + } + }, + "jest-get-type": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-24.9.0.tgz", + "integrity": "sha512-lUseMzAley4LhIcpSP9Jf+fTrQ4a1yHQwLNeeVa2cEmbCGeoZAtYPOIv8JaxLD/sUpKxetKGP+gsHl8f8TSj8Q==", + "dev": true + }, + "jest-haste-map": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-24.9.0.tgz", + "integrity": "sha512-kfVFmsuWui2Sj1Rp1AJ4D9HqJwE4uwTlS/vO+eRUaMmd54BFpli2XhMQnPC2k4cHFVbB2Q2C+jtI1AGLgEnCjQ==", + "dev": true, + "requires": { + "@jest/types": "^24.9.0", + "anymatch": "^2.0.0", + "fb-watchman": "^2.0.0", + "fsevents": "^1.2.7", + "graceful-fs": "^4.1.15", + "invariant": "^2.2.4", + "jest-serializer": "^24.9.0", + "jest-util": "^24.9.0", + "jest-worker": "^24.9.0", + "micromatch": "^3.1.10", + "sane": "^4.0.3", + "walker": "^1.0.7" + } + }, + "jest-jasmine2": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-jasmine2/-/jest-jasmine2-24.9.0.tgz", + "integrity": "sha512-Cq7vkAgaYKp+PsX+2/JbTarrk0DmNhsEtqBXNwUHkdlbrTBLtMJINADf2mf5FkowNsq8evbPc07/qFO0AdKTzw==", + "dev": true, + "requires": { + "@babel/traverse": "^7.1.0", + "@jest/environment": "^24.9.0", + "@jest/test-result": "^24.9.0", + "@jest/types": "^24.9.0", + "chalk": "^2.0.1", + "co": "^4.6.0", + "expect": "^24.9.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^24.9.0", + "jest-matcher-utils": "^24.9.0", + "jest-message-util": "^24.9.0", + "jest-runtime": "^24.9.0", + "jest-snapshot": "^24.9.0", + "jest-util": "^24.9.0", + "pretty-format": "^24.9.0", + "throat": "^4.0.0" + } + }, + "jest-junit": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/jest-junit/-/jest-junit-8.0.0.tgz", + "integrity": "sha512-cuD2XM2youMjrOxOu/7H2pLfsO8LfAG4D3WsBxd9fFyI9U0uPpmr/CORH64kbIyZ47X5x1Rbzb9ovUkAEvhEEA==", + "dev": true, + "requires": { + "jest-validate": "^24.0.0", + "mkdirp": "^0.5.1", + "strip-ansi": "^4.0.0", + "xml": "^1.0.1" + } + }, + "jest-leak-detector": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-24.9.0.tgz", + "integrity": "sha512-tYkFIDsiKTGwb2FG1w8hX9V0aUb2ot8zY/2nFg087dUageonw1zrLMP4W6zsRO59dPkTSKie+D4rhMuP9nRmrA==", + "dev": true, + "requires": { + "jest-get-type": "^24.9.0", + "pretty-format": "^24.9.0" + } + }, + "jest-matcher-utils": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-24.9.0.tgz", + "integrity": "sha512-OZz2IXsu6eaiMAwe67c1T+5tUAtQyQx27/EMEkbFAGiw52tB9em+uGbzpcgYVpA8wl0hlxKPZxrly4CXU/GjHA==", + "dev": true, + "requires": { + "chalk": "^2.0.1", + "jest-diff": "^24.9.0", + "jest-get-type": "^24.9.0", + "pretty-format": "^24.9.0" + } + }, + "jest-message-util": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-24.9.0.tgz", + "integrity": "sha512-oCj8FiZ3U0hTP4aSui87P4L4jC37BtQwUMqk+zk/b11FR19BJDeZsZAvIHutWnmtw7r85UmR3CEWZ0HWU2mAlw==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "@jest/test-result": "^24.9.0", + "@jest/types": "^24.9.0", + "@types/stack-utils": "^1.0.1", + "chalk": "^2.0.1", + "micromatch": "^3.1.10", + "slash": "^2.0.0", + "stack-utils": "^1.0.1" + } + }, + "jest-mock": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-24.9.0.tgz", + "integrity": "sha512-3BEYN5WbSq9wd+SyLDES7AHnjH9A/ROBwmz7l2y+ol+NtSFO8DYiEBzoO1CeFc9a8DYy10EO4dDFVv/wN3zl1w==", + "dev": true, + "requires": { + "@jest/types": "^24.9.0" + } + }, + "jest-pnp-resolver": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.1.tgz", + "integrity": "sha512-pgFw2tm54fzgYvc/OHrnysABEObZCUNFnhjoRjaVOCN8NYc032/gVjPaHD4Aq6ApkSieWtfKAFQtmDKAmhupnQ==", + "dev": true + }, + "jest-regex-util": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-24.9.0.tgz", + "integrity": "sha512-05Cmb6CuxaA+Ys6fjr3PhvV3bGQmO+2p2La4hFbU+W5uOc479f7FdLXUWXw4pYMAhhSZIuKHwSXSu6CsSBAXQA==", + "dev": true + }, + "jest-resolve": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-24.9.0.tgz", + "integrity": "sha512-TaLeLVL1l08YFZAt3zaPtjiVvyy4oSA6CRe+0AFPPVX3Q/VI0giIWWoAvoS5L96vj9Dqxj4fB5p2qrHCmTU/MQ==", + "dev": true, + "requires": { + "@jest/types": "^24.9.0", + "browser-resolve": "^1.11.3", + "chalk": "^2.0.1", + "jest-pnp-resolver": "^1.2.1", + "realpath-native": "^1.1.0" + } + }, + "jest-resolve-dependencies": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-24.9.0.tgz", + "integrity": "sha512-Fm7b6AlWnYhT0BXy4hXpactHIqER7erNgIsIozDXWl5dVm+k8XdGVe1oTg1JyaFnOxarMEbax3wyRJqGP2Pq+g==", + "dev": true, + "requires": { + "@jest/types": "^24.9.0", + "jest-regex-util": "^24.3.0", + "jest-snapshot": "^24.9.0" + } + }, + "jest-runner": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-24.9.0.tgz", + "integrity": "sha512-KksJQyI3/0mhcfspnxxEOBueGrd5E4vV7ADQLT9ESaCzz02WnbdbKWIf5Mkaucoaj7obQckYPVX6JJhgUcoWWg==", + "dev": true, + "requires": { + "@jest/console": "^24.7.1", + "@jest/environment": "^24.9.0", + "@jest/test-result": "^24.9.0", + "@jest/types": "^24.9.0", + "chalk": "^2.4.2", + "exit": "^0.1.2", + "graceful-fs": "^4.1.15", + "jest-config": "^24.9.0", + "jest-docblock": "^24.3.0", + "jest-haste-map": "^24.9.0", + "jest-jasmine2": "^24.9.0", + "jest-leak-detector": "^24.9.0", + "jest-message-util": "^24.9.0", + "jest-resolve": "^24.9.0", + "jest-runtime": "^24.9.0", + "jest-util": "^24.9.0", + "jest-worker": "^24.6.0", + "source-map-support": "^0.5.6", + "throat": "^4.0.0" + } + }, + "jest-runtime": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-24.9.0.tgz", + "integrity": "sha512-8oNqgnmF3v2J6PVRM2Jfuj8oX3syKmaynlDMMKQ4iyzbQzIG6th5ub/lM2bCMTmoTKM3ykcUYI2Pw9xwNtjMnw==", + "dev": true, + "requires": { + "@jest/console": "^24.7.1", + "@jest/environment": "^24.9.0", + "@jest/source-map": "^24.3.0", + "@jest/transform": "^24.9.0", + "@jest/types": "^24.9.0", + "@types/yargs": "^13.0.0", + "chalk": "^2.0.1", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.1.15", + "jest-config": "^24.9.0", + "jest-haste-map": "^24.9.0", + "jest-message-util": "^24.9.0", + "jest-mock": "^24.9.0", + "jest-regex-util": "^24.3.0", + "jest-resolve": "^24.9.0", + "jest-snapshot": "^24.9.0", + "jest-util": "^24.9.0", + "jest-validate": "^24.9.0", + "realpath-native": "^1.1.0", + "slash": "^2.0.0", + "strip-bom": "^3.0.0", + "yargs": "^13.3.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true + }, + "cliui": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", + "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", + "dev": true, + "requires": { + "string-width": "^3.1.0", + "strip-ansi": "^5.2.0", + "wrap-ansi": "^5.1.0" + } + }, + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true + }, + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "dev": true + }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + } + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" + } + }, + "strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "dev": true + }, + "which-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", + "dev": true + }, + "wrap-ansi": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.0", + "string-width": "^3.0.0", + "strip-ansi": "^5.0.0" + } + }, + "y18n": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", + "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==", + "dev": true + }, + "yargs": { + "version": "13.3.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.0.tgz", + "integrity": "sha512-2eehun/8ALW8TLoIl7MVaRUrg+yCnenu8B4kBlRxj3GJGDKU1Og7sMXPNm1BYyM1DOJmTZ4YeN/Nwxv+8XJsUA==", + "dev": true, + "requires": { + "cliui": "^5.0.0", + "find-up": "^3.0.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^3.0.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^13.1.1" + } + }, + "yargs-parser": { + "version": "13.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.1.tgz", + "integrity": "sha512-oVAVsHz6uFrg3XQheFII8ESO2ssAf9luWuAd6Wexsu4F3OtIW0o8IribPXYrD4WC24LWtPrJlGy87y5udK+dxQ==", + "dev": true, + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + } + } + }, + "jest-serializer": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-serializer/-/jest-serializer-24.9.0.tgz", + "integrity": "sha512-DxYipDr8OvfrKH3Kel6NdED3OXxjvxXZ1uIY2I9OFbGg+vUkkg7AGvi65qbhbWNPvDckXmzMPbK3u3HaDO49bQ==", + "dev": true + }, + "jest-snapshot": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-24.9.0.tgz", + "integrity": "sha512-uI/rszGSs73xCM0l+up7O7a40o90cnrk429LOiK3aeTvfC0HHmldbd81/B7Ix81KSFe1lwkbl7GnBGG4UfuDew==", + "dev": true, + "requires": { + "@babel/types": "^7.0.0", + "@jest/types": "^24.9.0", + "chalk": "^2.0.1", + "expect": "^24.9.0", + "jest-diff": "^24.9.0", + "jest-get-type": "^24.9.0", + "jest-matcher-utils": "^24.9.0", + "jest-message-util": "^24.9.0", + "jest-resolve": "^24.9.0", + "mkdirp": "^0.5.1", + "natural-compare": "^1.4.0", + "pretty-format": "^24.9.0", + "semver": "^6.2.0" + }, + "dependencies": { + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + } + } + }, + "jest-util": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-24.9.0.tgz", + "integrity": "sha512-x+cZU8VRmOJxbA1K5oDBdxQmdq0OIdADarLxk0Mq+3XS4jgvhG/oKGWcIDCtPG0HgjxOYvF+ilPJQsAyXfbNOg==", + "dev": true, + "requires": { + "@jest/console": "^24.9.0", + "@jest/fake-timers": "^24.9.0", + "@jest/source-map": "^24.9.0", + "@jest/test-result": "^24.9.0", + "@jest/types": "^24.9.0", + "callsites": "^3.0.0", + "chalk": "^2.0.1", + "graceful-fs": "^4.1.15", + "is-ci": "^2.0.0", + "mkdirp": "^0.5.1", + "slash": "^2.0.0", + "source-map": "^0.6.0" + }, + "dependencies": { + "ci-info": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", + "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==", + "dev": true + }, + "is-ci": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", + "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", + "dev": true, + "requires": { + "ci-info": "^2.0.0" + } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "jest-validate": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-24.9.0.tgz", + "integrity": "sha512-HPIt6C5ACwiqSiwi+OfSSHbK8sG7akG8eATl+IPKaeIjtPOeBUd/g3J7DghugzxrGjI93qS/+RPKe1H6PqvhRQ==", + "dev": true, + "requires": { + "@jest/types": "^24.9.0", + "camelcase": "^5.3.1", + "chalk": "^2.0.1", + "jest-get-type": "^24.9.0", + "leven": "^3.1.0", + "pretty-format": "^24.9.0" + } + }, + "jest-watcher": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-24.9.0.tgz", + "integrity": "sha512-+/fLOfKPXXYJDYlks62/4R4GoT+GU1tYZed99JSCOsmzkkF7727RqKrjNAxtfO4YpGv11wybgRvCjR73lK2GZw==", + "dev": true, + "requires": { + "@jest/test-result": "^24.9.0", + "@jest/types": "^24.9.0", + "@types/yargs": "^13.0.0", + "ansi-escapes": "^3.0.0", + "chalk": "^2.0.1", + "jest-util": "^24.9.0", + "string-length": "^2.0.0" + } + }, + "jest-worker": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-24.9.0.tgz", + "integrity": "sha512-51PE4haMSXcHohnSMdM42anbvZANYTqMrr52tVKPqqsPJMzoP6FYYDVqahX/HrAoKEKz3uUPzSvKs9A3qR4iVw==", + "dev": true, + "requires": { + "merge-stream": "^2.0.0", + "supports-color": "^6.1.0" + }, + "dependencies": { + "merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, + "supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "jmespath": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/jmespath/-/jmespath-0.15.0.tgz", + "integrity": "sha1-o/Iiqarp+Wb10nx5ZRDigJF2Qhc=" + }, + "js-base64": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-2.5.1.tgz", + "integrity": "sha512-M7kLczedRMYX4L8Mdh4MzyAMM9O5osx+4FcOQuTvr3A9F2D9S5JXheN0ewNbrvK2UatkTRhL5ejGmGSjNMiZuw==", + "dev": true + }, + "js-levenshtein": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/js-levenshtein/-/js-levenshtein-1.1.6.tgz", + "integrity": "sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g==", + "dev": true + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "js-yaml": { + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "js2xmlparser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-3.0.0.tgz", + "integrity": "sha1-P7YOqgicVED5MZ9RdgzNB+JJlzM=", + "requires": { + "xmlcreate": "^1.0.1" + } + }, + "jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=" + }, + "jsdom": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-11.12.0.tgz", + "integrity": "sha512-y8Px43oyiBM13Zc1z780FrfNLJCXTL40EWlty/LXUtcjykRBNgLlCjWXpfSPBl2iv+N7koQN+dvqszHZgT/Fjw==", + "dev": true, + "requires": { + "abab": "^2.0.0", + "acorn": "^5.5.3", + "acorn-globals": "^4.1.0", + "array-equal": "^1.0.0", + "cssom": ">= 0.3.2 < 0.4.0", + "cssstyle": "^1.0.0", + "data-urls": "^1.0.0", + "domexception": "^1.0.1", + "escodegen": "^1.9.1", + "html-encoding-sniffer": "^1.0.2", + "left-pad": "^1.3.0", + "nwsapi": "^2.0.7", + "parse5": "4.0.0", + "pn": "^1.1.0", + "request": "^2.87.0", + "request-promise-native": "^1.0.5", + "sax": "^1.2.4", + "symbol-tree": "^3.2.2", + "tough-cookie": "^2.3.4", + "w3c-hr-time": "^1.0.1", + "webidl-conversions": "^4.0.2", + "whatwg-encoding": "^1.0.3", + "whatwg-mimetype": "^2.1.0", + "whatwg-url": "^6.4.1", + "ws": "^5.2.0", + "xml-name-validator": "^3.0.0" + }, + "dependencies": { + "acorn": { + "version": "5.7.3", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.3.tgz", + "integrity": "sha512-T/zvzYRfbVojPWahDsE5evJdHb3oJoQfFbsrKM7w5Zcs++Tr257tia3BmMP8XYVjp1S9RZXQMh7gao96BlqZOw==", + "dev": true + }, + "ws": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-5.2.2.tgz", + "integrity": "sha512-jaHFD6PFv6UgoIVda6qZllptQsMlDEJkTQcybzzXDYM1XO9Y8em691FGMPmM46WGyLU4z9KMgQN+qrux/nhlHA==", + "dev": true, + "requires": { + "async-limiter": "~1.0.0" + } + } + } + }, + "jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true + }, + "json-bigint": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-0.3.0.tgz", + "integrity": "sha1-DM2RLEuCcNBfBW+9E4FLU9OCWx4=", + "requires": { + "bignumber.js": "^7.0.0" + } + }, + "json-buffer": { + "version": "2.0.11", + "resolved": "http://registry.npmjs.org/json-buffer/-/json-buffer-2.0.11.tgz", + "integrity": "sha1-PkQf2jCYvo0eMXGtWRvGKjPi1V8=" + }, + "json-loader": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/json-loader/-/json-loader-0.5.7.tgz", + "integrity": "sha512-QLPs8Dj7lnf3e3QYS1zkCo+4ZwqOiF9d/nZnYozTISxXWCfNs9yuky5rJw4/W34s7POaNlbZmQGaB5NiXCbP4w==", + "dev": true + }, + "json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "dev": true + }, + "json-schema": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", + "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=" + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" + }, + "json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", + "dev": true + }, + "json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" + }, + "json3": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/json3/-/json3-3.3.3.tgz", + "integrity": "sha512-c7/8mbUsKigAbLkD5B010BK4D9LZm7A1pNItkEwiUZRpIN66exu/e7YQWysGun+TRKaJp8MhemM+VkfWv42aCA==", + "dev": true + }, + "json5": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.0.tgz", + "integrity": "sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==", + "dev": true, + "requires": { + "minimist": "^1.2.0" + } + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "requires": { + "graceful-fs": "^4.1.6" + } + }, + "jsonparse": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", + "integrity": "sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA=" + }, + "jsprim": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", + "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.2.3", + "verror": "1.10.0" + } + }, + "just-debounce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/just-debounce/-/just-debounce-1.0.0.tgz", + "integrity": "sha1-h/zPrv/AtozRnVX2cilD+SnqNeo=", + "dev": true + }, + "jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "requires": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "requires": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "keypress": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/keypress/-/keypress-0.1.0.tgz", + "integrity": "sha1-SjGI1CkbZrT2XtuZ+AaqmuKTWSo=", + "dev": true + }, + "keyv": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-3.1.0.tgz", + "integrity": "sha512-9ykJ/46SN/9KPM/sichzQ7OvXyGDYKGTaDlKMGCAlg2UK8KRy4jb0d8sFc+0Tt0YYnThq8X2RZgCg74RPxgcVA==", + "requires": { + "json-buffer": "3.0.0" + }, + "dependencies": { + "json-buffer": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.0.tgz", + "integrity": "sha1-Wx85evx11ne96Lz8Dkfh+aPZqJg=" + } + } + }, + "killable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/killable/-/killable-1.0.1.tgz", + "integrity": "sha512-LzqtLKlUwirEUyl/nicirVmNiPvYs7l5n8wOPP7fyJVpUPkvCnW/vuiXGpylGUlnPDnB7311rARzAt3Mhswpjg==", + "dev": true }, "kind-of": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", - "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", - "dev": true + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true + }, + "klaw": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/klaw/-/klaw-1.3.1.tgz", + "integrity": "sha1-QIhDO0azsbolnXh4XY6W9zugJDk=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.9" + } + }, + "kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true + }, + "last-run": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/last-run/-/last-run-1.1.1.tgz", + "integrity": "sha1-RblpQsF7HHnHchmCWbqUO+v4yls=", + "dev": true, + "requires": { + "default-resolution": "^2.0.0", + "es6-weak-map": "^2.0.1" + } + }, + "latest-version": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/latest-version/-/latest-version-3.1.0.tgz", + "integrity": "sha1-ogU4P+oyKzO1rjsYq+4NwvNW7hU=", + "dev": true, + "requires": { + "package-json": "^4.0.0" + } + }, + "lazystream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.0.tgz", + "integrity": "sha1-9plf4PggOS9hOWvolGJAe7dxaOQ=", + "dev": true, + "requires": { + "readable-stream": "^2.0.5" + } + }, + "lcid": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz", + "integrity": "sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==", + "requires": { + "invert-kv": "^2.0.0" + } + }, + "lead": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/lead/-/lead-1.0.0.tgz", + "integrity": "sha1-bxT5mje+Op3XhPVJVpDlkDRm7kI=", + "dev": true, + "requires": { + "flush-write-stream": "^1.0.2" + } + }, + "left-pad": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/left-pad/-/left-pad-1.3.0.tgz", + "integrity": "sha512-XI5MPzVNApjAyhQzphX8BkmKsKUxD4LdyK24iZeQGinBN9yTQT3bFlCBy/aVx2HrNcqQGsdot8ghrjyrvMCoEA==", + "dev": true + }, + "leven": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", + "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", + "dev": true + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + } + }, + "liboneandone": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/liboneandone/-/liboneandone-1.2.0.tgz", + "integrity": "sha512-EB6Ak9qw+U4HAOnKqPtatxQ9pLclvtsBsggrvOuD4zclJ5xOeEASojsLKEC3O8KJ1Q4obE2JHhOeDuqWXvkoUQ==", + "requires": { + "mocha": "^2.5.3", + "request": "^2.74.0" + } + }, + "liftoff": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/liftoff/-/liftoff-3.1.0.tgz", + "integrity": "sha512-DlIPlJUkCV0Ips2zf2pJP0unEoT1kwYhiiPUGF3s/jtxTCjziNLoiVVh+jqWOWeFi6mmwQ5fNxvAUyPad4Dfog==", + "dev": true, + "requires": { + "extend": "^3.0.0", + "findup-sync": "^3.0.0", + "fined": "^1.0.1", + "flagged-respawn": "^1.0.0", + "is-plain-object": "^2.0.4", + "object.map": "^1.0.0", + "rechoir": "^0.6.2", + "resolve": "^1.1.7" + } + }, + "load-json-file": { + "version": "1.1.0", + "resolved": "http://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", + "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "strip-bom": "^2.0.0" + }, + "dependencies": { + "pify": { + "version": "2.3.0", + "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + }, + "strip-bom": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", + "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", + "dev": true, + "requires": { + "is-utf8": "^0.2.0" + } + } + } + }, + "loader-runner": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-2.4.0.tgz", + "integrity": "sha512-Jsmr89RcXGIwivFY21FcRrisYZfvLMTWx5kOLc+JTxtpBOG6xML0vzbc6SEQG2FO9/4Fc3wW4LVcB5DmGflaRw==", + "dev": true + }, + "loader-utils": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.2.3.tgz", + "integrity": "sha512-fkpz8ejdnEMG3s37wGL07iSBDg99O9D5yflE9RGNH3hRdx9SOwYfnGYdZOUIZitN8E+E2vkq3MUMYMvPYl5ZZA==", + "dev": true, + "requires": { + "big.js": "^5.2.2", + "emojis-list": "^2.0.0", + "json5": "^1.0.1" + }, + "dependencies": { + "json5": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", + "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "dev": true, + "requires": { + "minimist": "^1.2.0" + } + } + } + }, + "locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "dev": true, + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==" + }, + "lodash._basecopy": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz", + "integrity": "sha1-jaDmqHbPNEwK2KVIghEd08XHyjY=", + "dev": true + }, + "lodash._basetostring": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/lodash._basetostring/-/lodash._basetostring-3.0.1.tgz", + "integrity": "sha1-0YYdh3+CSlL2aYMtyvPuFVZqB9U=", + "dev": true + }, + "lodash._basevalues": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lodash._basevalues/-/lodash._basevalues-3.0.0.tgz", + "integrity": "sha1-W3dXYoAr3j0yl1A+JjAIIP32Ybc=", + "dev": true + }, + "lodash._getnative": { + "version": "3.9.1", + "resolved": "https://registry.npmjs.org/lodash._getnative/-/lodash._getnative-3.9.1.tgz", + "integrity": "sha1-VwvH3t5G1hzc3mh9ZdPuy6o6r/U=", + "dev": true + }, + "lodash._isiterateecall": { + "version": "3.0.9", + "resolved": "https://registry.npmjs.org/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz", + "integrity": "sha1-UgOte6Ql+uhCRg5pbbnPPmqsBXw=", + "dev": true + }, + "lodash._reescape": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lodash._reescape/-/lodash._reescape-3.0.0.tgz", + "integrity": "sha1-Kx1vXf4HyKNVdT5fJ/rH8c3hYWo=", + "dev": true + }, + "lodash._reevaluate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lodash._reevaluate/-/lodash._reevaluate-3.0.0.tgz", + "integrity": "sha1-WLx0xAZklTrgsSTYBpltrKQx4u0=", + "dev": true + }, + "lodash._reinterpolate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz", + "integrity": "sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=", + "dev": true + }, + "lodash._root": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/lodash._root/-/lodash._root-3.0.1.tgz", + "integrity": "sha1-+6HEUkwZ7ppfgTa0YJ8BfPTe1pI=", + "dev": true + }, + "lodash.escape": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/lodash.escape/-/lodash.escape-3.2.0.tgz", + "integrity": "sha1-mV7g3BjBtIzJLv+ucaEKq1tIdpg=", + "dev": true, + "requires": { + "lodash._root": "^3.0.0" + } + }, + "lodash.groupby": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.groupby/-/lodash.groupby-4.6.0.tgz", + "integrity": "sha1-Cwih3PaDl8OXhVwyOXg4Mt90A9E=", + "dev": true + }, + "lodash.isarguments": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", + "integrity": "sha1-L1c9hcaiQon/AGY7SRwdM4/zRYo=", + "dev": true + }, + "lodash.isarray": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/lodash.isarray/-/lodash.isarray-3.0.4.tgz", + "integrity": "sha1-eeTriMNqgSKvhvhEqpvNhRtfu1U=", + "dev": true + }, + "lodash.keys": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-3.1.2.tgz", + "integrity": "sha1-TbwEcrFWvlCgsoaFXRvQsMZWCYo=", + "dev": true, + "requires": { + "lodash._getnative": "^3.0.0", + "lodash.isarguments": "^3.0.0", + "lodash.isarray": "^3.0.0" + } + }, + "lodash.mergewith": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.mergewith/-/lodash.mergewith-4.6.2.tgz", + "integrity": "sha512-GK3g5RPZWTRSeLSpgP8Xhra+pnjBC56q9FZYe1d5RN3TJ35dbkGy3YqBSMbyCrlbi+CM9Z3Jk5yTL7RCsqboyQ==", + "dev": true + }, + "lodash.restparam": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/lodash.restparam/-/lodash.restparam-3.6.1.tgz", + "integrity": "sha1-k2pOMJ7zMKdkXtQUWYbIWuWyCAU=", + "dev": true + }, + "lodash.sortby": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz", + "integrity": "sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=", + "dev": true + }, + "lodash.tail": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.tail/-/lodash.tail-4.1.1.tgz", + "integrity": "sha1-0jM6NtnncXyK0vfKyv7HwytERmQ=", + "dev": true + }, + "lodash.template": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-3.6.2.tgz", + "integrity": "sha1-+M3sxhaaJVvpCYrosMU9N4kx0U8=", + "dev": true, + "requires": { + "lodash._basecopy": "^3.0.0", + "lodash._basetostring": "^3.0.0", + "lodash._basevalues": "^3.0.0", + "lodash._isiterateecall": "^3.0.0", + "lodash._reinterpolate": "^3.0.0", + "lodash.escape": "^3.0.0", + "lodash.keys": "^3.0.0", + "lodash.restparam": "^3.0.0", + "lodash.templatesettings": "^3.0.0" + } + }, + "lodash.templatesettings": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/lodash.templatesettings/-/lodash.templatesettings-3.1.1.tgz", + "integrity": "sha1-+zB4RHU7Zrnxr6VOJix0UwfbqOU=", + "dev": true, + "requires": { + "lodash._reinterpolate": "^3.0.0", + "lodash.escape": "^3.0.0" + } + }, + "loglevel": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.6.3.tgz", + "integrity": "sha512-LoEDv5pgpvWgPF4kNYuIp0qqSJVWak/dML0RY74xlzMZiT9w77teNAwKYKWBTYjlokMirg+o3jBwp+vlLrcfAA==", + "dev": true + }, + "long": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", + "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==", + "dev": true + }, + "loopback": { + "version": "3.26.0", + "resolved": "https://registry.npmjs.org/loopback/-/loopback-3.26.0.tgz", + "integrity": "sha512-QDREGpTTjLwMgteSIajFXMklW4slbVO5PvY2bPXBn3EUfPzmWXfaDiSlzwbbRbw+cyMUAr2EorL1r0+IsIslWg==", + "requires": { + "async": "^2.0.1", + "bcryptjs": "^2.1.0", + "bluebird": "^3.1.1", + "body-parser": "^1.12.0", + "canonical-json": "0.0.4", + "debug": "^2.1.2", + "depd": "^1.0.0", + "ejs": "^2.3.1", + "express": "^4.14.0", + "inflection": "^1.6.0", + "isemail": "^2.2.1", + "loopback-connector-remote": "^3.0.0", + "loopback-datasource-juggler": "^3.28.0", + "loopback-filters": "^1.0.0", + "loopback-phase": "^3.0.0", + "nodemailer": "^4.0.1", + "nodemailer-direct-transport": "^3.3.2", + "nodemailer-stub-transport": "^1.1.0", + "serve-favicon": "^2.2.0", + "stable": "^0.1.5", + "strong-globalize": "^4.1.1", + "strong-remoting": "^3.11.0", + "uid2": "0.0.3", + "underscore.string": "^3.3.5" + }, + "dependencies": { + "async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", + "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", + "requires": { + "lodash": "^4.17.11" + } + }, + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" + } + } + }, + "loopback-boot": { + "version": "2.28.0", + "resolved": "https://registry.npmjs.org/loopback-boot/-/loopback-boot-2.28.0.tgz", + "integrity": "sha512-DTZnoWEMukgG2PrtguJ0Xk9HmIlHgcynGoxkDPa9oFiJ7l+8v92Ym8q7RQxOf8Nqws1kykPQ7PNuia+9AoeC7w==", + "requires": { + "async": "^0.9.2", + "commondir": "^1.0.1", + "debug": "^3.2.6", + "lodash": "^4.17.11", + "semver": "^5.6.0", + "strong-globalize": "^4.1.3", + "toposort": "^2.0.2" + }, + "dependencies": { + "async": { + "version": "0.9.2", + "resolved": "http://registry.npmjs.org/async/-/async-0.9.2.tgz", + "integrity": "sha1-rqdNXmHB+JlhO/ZL2mbUx48v0X0=" + }, + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "loopback-component-explorer": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/loopback-component-explorer/-/loopback-component-explorer-6.4.0.tgz", + "integrity": "sha512-vDRR4gqkvGOEXh5yL383xGuGxUW9xtF+NCY6/lJu1VAgupKltZxEx3Vw+L3nsGvQrlkJTSmiK3jk72qxkoBtbw==", + "requires": { + "debug": "^3.1.0", + "lodash": "^4.17.11", + "loopback-swagger": "^5.0.0", + "strong-globalize": "^4.1.1", + "swagger-ui": "^2.2.5" + }, + "dependencies": { + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "loopback-component-storage": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/loopback-component-storage/-/loopback-component-storage-3.6.1.tgz", + "integrity": "sha512-KM+Q8XhaLtpUfCabeBxYDxs9ZuKyvWiP+iCLmnjem2UZvPp04B5MCLz4A3Rc1jqKQugAe3Ijk15hZQE+Zob8PQ==", + "requires": { + "async": "^2.6.1", + "debug": "^3.1.0", + "formidable": "^1.2.1", + "pkgcloud": "^2.0.0", + "strong-globalize": "^4.1.1", + "uuid": "^3.2.1" + }, + "dependencies": { + "async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", + "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", + "requires": { + "lodash": "^4.17.11" + } + }, + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "loopback-connector": { + "version": "4.8.0", + "resolved": "https://registry.npmjs.org/loopback-connector/-/loopback-connector-4.8.0.tgz", + "integrity": "sha512-X5A4YaS6iifomym97ll/J/V+iPZ3Av69J6gmG3QXkq2JtzDtAOh6g2ITgo9aYJ/rzRf9HESH3Ys7aqeppDkpZQ==", + "requires": { + "async": "^2.1.5", + "bluebird": "^3.4.6", + "debug": "^3.1.0", + "msgpack5": "^4.2.0", + "strong-globalize": "^4.1.1", + "uuid": "^3.0.1" + }, + "dependencies": { + "async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", + "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", + "requires": { + "lodash": "^4.17.11" + } + }, + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "loopback-connector-mysql": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/loopback-connector-mysql/-/loopback-connector-mysql-5.4.1.tgz", + "integrity": "sha512-+nXuodxmAVotvXGYrJRyzF21AT+3250Rodhsbh7lUrwRHOsYuja6ulT15P1P9NAoHeoZkzbw6XV9DQSJe6JyXw==", + "requires": { + "async": "^2.6.1", + "debug": "^3.1.0", + "lodash": "^4.17.11", + "loopback-connector": "^4.0.0", + "mysql": "^2.11.1", + "strong-globalize": "^4.1.1" + }, + "dependencies": { + "async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", + "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", + "requires": { + "lodash": "^4.17.11" + } + }, + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "loopback-connector-remote": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/loopback-connector-remote/-/loopback-connector-remote-3.4.1.tgz", + "integrity": "sha512-O22X2Gcq8YzZF9DvRjOCyktQlASw1/22i/zzqxJHNKSQA5aQYeTB0w5FttOiKxcw6Q/jzL476hUvUE/NaZVZ1Q==", + "requires": { + "loopback-datasource-juggler": "^3.0.0", + "strong-remoting": "^3.0.0" + } + }, + "loopback-context": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/loopback-context/-/loopback-context-3.4.0.tgz", + "integrity": "sha512-Vd9bjgQlqQoG9dkb73waNvWqJFv8HVyrTSYh2JgnclTGEihijIJ4g/tGeOJ9Xwpe/0ZuGdHZN+iGFJRo1U7gdQ==", + "requires": { + "cls-hooked": "^4.2.0" + } + }, + "loopback-datasource-juggler": { + "version": "3.31.1", + "resolved": "https://registry.npmjs.org/loopback-datasource-juggler/-/loopback-datasource-juggler-3.31.1.tgz", + "integrity": "sha512-B33enq3yKcSsMha/xysomLG7y8rHuTOkKPtsZjg5P63PmtAPVZ8DaA5KJPQ8J5rNINdjVactVAvx7hd4h0cEQA==", + "requires": { + "async": "^2.6.0", + "bluebird": "^3.1.1", + "debug": "^3.1.0", + "depd": "^1.0.0", + "inflection": "^1.6.0", + "lodash": "^4.17.4", + "loopback-connector": "^4.4.0", + "minimatch": "^3.0.3", + "qs": "^6.5.0", + "shortid": "^2.2.6", + "strong-globalize": "^4.1.1", + "traverse": "^0.6.6", + "uuid": "^3.0.1" + }, + "dependencies": { + "async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", + "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", + "requires": { + "lodash": "^4.17.11" + } + }, + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "loopback-datatype-geopoint": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/loopback-datatype-geopoint/-/loopback-datatype-geopoint-1.0.0.tgz", + "integrity": "sha1-/apcerjXMKmrflRVS+Fl8xzfYQA=" + }, + "loopback-filters": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/loopback-filters/-/loopback-filters-1.0.0.tgz", + "integrity": "sha512-uFQQLfj4T27CM6dzlWMH6aF1lf/Qj97VmXMlVnNWcG+Pd8R8ZbU4i/shArYXArXfis+ICD80YadrPbf9DYRbOA==", + "requires": { + "debug": "^3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "loopback-phase": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/loopback-phase/-/loopback-phase-3.3.0.tgz", + "integrity": "sha512-0NAMtZ2P7VHtW2vgADmDFzFCeniCJwL4I3AdAxX5Ds8IFDQNbnRFnBQSvg+F50HcB7ZkKmR5gtOxtr7bXbqaAQ==", + "requires": { + "async": "^2.6.1", + "debug": "^3.1.0", + "strong-globalize": "^4.1.1" + }, + "dependencies": { + "async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", + "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", + "requires": { + "lodash": "^4.17.11" + } + }, + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "loopback-swagger": { + "version": "5.7.3", + "resolved": "https://registry.npmjs.org/loopback-swagger/-/loopback-swagger-5.7.3.tgz", + "integrity": "sha512-RKmmaaiYS6gkAybiY17Poh1NBPrOI5rYlEJY+cf5VlL5p0e1MK9ivfOVDFpfPaxXEnYt7NL/Cz/iZ9QuKyfA5g==", + "requires": { + "async": "^2.1.4", + "debug": "^3.1.0", + "ejs": "^2.5.5", + "lodash": "^4.17.11", + "strong-globalize": "^4.1.1" + }, + "dependencies": { + "async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", + "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", + "requires": { + "lodash": "^4.17.11" + } + }, + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dev": true, + "requires": { + "js-tokens": "^3.0.0 || ^4.0.0" + } + }, + "loud-rejection": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/loud-rejection/-/loud-rejection-1.6.0.tgz", + "integrity": "sha1-W0b4AUft7leIcPCG0Eghz5mOVR8=", + "dev": true, + "requires": { + "currently-unhandled": "^0.4.1", + "signal-exit": "^3.0.0" + } + }, + "lower-case": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-1.1.4.tgz", + "integrity": "sha1-miyr0bno4K6ZOkv31YdcOcQujqw=", + "dev": true + }, + "lowercase-keys": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz", + "integrity": "sha512-G2Lj61tXDnVFFOi8VZds+SoQjtQC3dgokKdDG2mTm1tx4m50NUHBOZSBwQQHyy0V12A0JTG4icfZQH+xPyh8VA==" + }, + "lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "requires": { + "yallist": "^3.0.2" + } + }, + "make-dir": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.3.0.tgz", + "integrity": "sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ==", + "requires": { + "pify": "^3.0.0" + }, + "dependencies": { + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=" + } + } + }, + "make-iterator": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/make-iterator/-/make-iterator-1.0.1.tgz", + "integrity": "sha512-pxiuXh0iVEq7VM7KMIhs5gxsfxCux2URptUQaXo4iZZJxBAzTPOLE2BumO5dbfVYq/hBJFBR/a1mFDmOx5AGmw==", + "dev": true, + "requires": { + "kind-of": "^6.0.2" + } + }, + "make-plural": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/make-plural/-/make-plural-3.0.6.tgz", + "integrity": "sha1-IDOgO6wpC487uRJY9lud9+iwHKc=", + "requires": { + "minimist": "^1.2.0" + } + }, + "makeerror": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.11.tgz", + "integrity": "sha1-4BpckQnyr3lmDk6LlYd5AYT1qWw=", + "dev": true, + "requires": { + "tmpl": "1.0.x" + } + }, + "mamacro": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/mamacro/-/mamacro-0.0.3.tgz", + "integrity": "sha512-qMEwh+UujcQ+kbz3T6V+wAmO2U8veoq2w+3wY8MquqwVA3jChfwY+Tk52GZKDfACEPjuZ7r2oJLejwpt8jtwTA==", + "dev": true + }, + "map-age-cleaner": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz", + "integrity": "sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w==", + "requires": { + "p-defer": "^1.0.0" + } + }, + "map-cache": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", + "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", + "dev": true + }, + "map-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz", + "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=", + "dev": true + }, + "map-stream": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/map-stream/-/map-stream-0.0.7.tgz", + "integrity": "sha1-ih8HiW2CsQkmvTdEokIACfiJdKg=", + "dev": true + }, + "map-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", + "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", + "dev": true, + "requires": { + "object-visit": "^1.0.0" + } + }, + "matchdep": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/matchdep/-/matchdep-2.0.0.tgz", + "integrity": "sha1-xvNINKDY28OzfCfui7yyfHd1WC4=", + "dev": true, + "requires": { + "findup-sync": "^2.0.0", + "micromatch": "^3.0.4", + "resolve": "^1.4.0", + "stack-trace": "0.0.10" + }, + "dependencies": { + "findup-sync": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-2.0.0.tgz", + "integrity": "sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw=", + "dev": true, + "requires": { + "detect-file": "^1.0.0", + "is-glob": "^3.1.0", + "micromatch": "^3.0.4", + "resolve-dir": "^1.0.1" + } + }, + "is-glob": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", + "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", + "dev": true, + "requires": { + "is-extglob": "^2.1.0" + } + } + } + }, + "matcher": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/matcher/-/matcher-2.1.0.tgz", + "integrity": "sha512-o+nZr+vtJtgPNklyeUKkkH42OsK8WAfdgaJE2FNxcjLPg+5QbeEoT6vRj8Xq/iv18JlQ9cmKsEu0b94ixWf1YQ==", + "optional": true, + "requires": { + "escape-string-regexp": "^2.0.0" + }, + "dependencies": { + "escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "optional": true + } + } + }, + "math-interval-parser": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-interval-parser/-/math-interval-parser-1.1.0.tgz", + "integrity": "sha1-2+2lsGsySZc8bfYXD94jhvCv2JM=", + "requires": { + "xregexp": "^2.0.0" + } + }, + "md5": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/md5/-/md5-2.2.1.tgz", + "integrity": "sha1-U6s41f48iJG6RlMp6iP6wFQBJvk=", + "requires": { + "charenc": "~0.0.1", + "crypt": "~0.0.1", + "is-buffer": "~1.1.1" + } + }, + "md5.js": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", + "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", + "dev": true, + "requires": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "media-typer": { + "version": "0.3.0", + "resolved": "http://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" + }, + "mem": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/mem/-/mem-4.3.0.tgz", + "integrity": "sha512-qX2bG48pTqYRVmDB37rn/6PT7LcR8T7oAX3bf99u1Tt1nzxYfxkgqDwUwolPlXweM0XzBOBFzSx4kfp7KP1s/w==", + "requires": { + "map-age-cleaner": "^0.1.1", + "mimic-fn": "^2.0.0", + "p-is-promise": "^2.0.0" + } + }, + "memory-fs": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/memory-fs/-/memory-fs-0.4.1.tgz", + "integrity": "sha1-OpoguEYlI+RHz7x+i7gO1me/xVI=", + "dev": true, + "requires": { + "errno": "^0.1.3", + "readable-stream": "^2.0.1" + } + }, + "meow": { + "version": "3.7.0", + "resolved": "http://registry.npmjs.org/meow/-/meow-3.7.0.tgz", + "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", + "dev": true, + "requires": { + "camelcase-keys": "^2.0.0", + "decamelize": "^1.1.2", + "loud-rejection": "^1.0.0", + "map-obj": "^1.0.1", + "minimist": "^1.1.3", + "normalize-package-data": "^2.3.4", + "object-assign": "^4.0.1", + "read-pkg-up": "^1.0.1", + "redent": "^1.0.0", + "trim-newlines": "^1.0.0" + } + }, + "merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" + }, + "merge-stream": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-1.0.1.tgz", + "integrity": "sha1-QEEgLVCKNCugAXQAjfDCUbjBNeE=", + "dev": true, + "requires": { + "readable-stream": "^2.0.1" + } + }, + "messageformat": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/messageformat/-/messageformat-0.3.1.tgz", + "integrity": "sha1-5Y//gkXps5cXmeW0PbWLPpQX9aI=", + "requires": { + "async": "~1.5.2", + "glob": "~6.0.4", + "make-plural": "~3.0.3", + "nopt": "~3.0.6", + "watchr": "~2.4.13" + } + }, + "methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=" }, "micromatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.5.tgz", - "integrity": "sha512-ykttrLPQrz1PUJcXjwsTUjGoPJ64StIGNE2lGVD1c9CuguJ+L7/navsE8IcDNndOoCMvYV0qc/exfVbMHkUhvA==", - "dev": true, - "requires": { - "arr-diff": "4.0.0", - "array-unique": "0.3.2", - "braces": "2.3.0", - "define-property": "1.0.0", - "extend-shallow": "2.0.1", - "extglob": "2.0.4", - "fragment-cache": "0.2.1", - "kind-of": "6.0.2", - "nanomatch": "1.2.7", - "object.pick": "1.3.0", - "regex-not": "1.0.0", - "snapdragon": "0.8.1", - "to-regex": "3.0.1" - } + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", + "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", + "dev": true, + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "braces": "^2.3.1", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "extglob": "^2.0.4", + "fragment-cache": "^0.2.1", + "kind-of": "^6.0.2", + "nanomatch": "^1.2.9", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.2" + } + }, + "miller-rabin": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", + "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", + "dev": true, + "requires": { + "bn.js": "^4.0.0", + "brorand": "^1.0.1" + } + }, + "mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" + }, + "mime-db": { + "version": "1.40.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.40.0.tgz", + "integrity": "sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA==" + }, + "mime-types": { + "version": "2.1.24", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.24.tgz", + "integrity": "sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ==", + "requires": { + "mime-db": "1.40.0" + } + }, + "mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==" + }, + "mimic-response": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", + "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==" + }, + "minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "dev": true + }, + "minimalistic-crypto-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", + "integrity": "sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=", + "dev": true + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" + }, + "minstache": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minstache/-/minstache-1.2.0.tgz", + "integrity": "sha1-/xzEA6woRPaNvxjGYhKb5+sO/EE=", + "dev": true, + "requires": { + "commander": "1.0.4" + }, + "dependencies": { + "commander": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/commander/-/commander-1.0.4.tgz", + "integrity": "sha1-Xt6xruI8T7VBprcNaSq+8ZZpotM=", + "dev": true, + "requires": { + "keypress": "0.1.x" + } + } + } + }, + "mississippi": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mississippi/-/mississippi-3.0.0.tgz", + "integrity": "sha512-x471SsVjUtBRtcvd4BzKE9kFC+/2TeWgKCgw0bZcw1b9l2X3QX5vCWgF+KaZaYm87Ss//rHnWryupDrgLvmSkA==", + "dev": true, + "requires": { + "concat-stream": "^1.5.0", + "duplexify": "^3.4.2", + "end-of-stream": "^1.1.0", + "flush-write-stream": "^1.0.0", + "from2": "^2.1.0", + "parallel-transform": "^1.1.0", + "pump": "^3.0.0", + "pumpify": "^1.3.3", + "stream-each": "^1.1.0", + "through2": "^2.0.0" + }, + "dependencies": { + "concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "mixin-deep": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.2.tgz", + "integrity": "sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==", + "dev": true, + "requires": { + "for-in": "^1.0.2", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, + "mixin-object": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mixin-object/-/mixin-object-2.0.1.tgz", + "integrity": "sha1-T7lJRB2rGCVA8f4DW6YOGUel5X4=", + "dev": true, + "requires": { + "for-in": "^0.1.3", + "is-extendable": "^0.1.1" + }, + "dependencies": { + "for-in": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/for-in/-/for-in-0.1.8.tgz", + "integrity": "sha1-2Hc5COMSVhCZUrH9ubP6hn0ndeE=", + "dev": true + } + } + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "requires": { + "minimist": "0.0.8" + }, + "dependencies": { + "minimist": { + "version": "0.0.8", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=" + } + } + }, + "mktmpdir": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/mktmpdir/-/mktmpdir-0.1.1.tgz", + "integrity": "sha1-OKyCCVDXjvoLnN38A/99XFp4bbk=", + "requires": { + "rimraf": "~2.2.8" + } + }, + "mocha": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-2.5.3.tgz", + "integrity": "sha1-FhvlvetJZ3HrmzV0UFC2IrWu/Fg=", + "requires": { + "commander": "2.3.0", + "debug": "2.2.0", + "diff": "1.4.0", + "escape-string-regexp": "1.0.2", + "glob": "3.2.11", + "growl": "1.9.2", + "jade": "0.26.3", + "mkdirp": "0.5.1", + "supports-color": "1.2.0", + "to-iso-string": "0.0.2" + }, + "dependencies": { + "commander": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.3.0.tgz", + "integrity": "sha1-/UMOiJgy7DU7ms0d4hfBHLPu+HM=" + }, + "debug": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", + "requires": { + "ms": "0.7.1" + } + }, + "escape-string-regexp": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.2.tgz", + "integrity": "sha1-Tbwv5nTnGUnK8/smlc5/LcHZqNE=" + }, + "glob": { + "version": "3.2.11", + "resolved": "https://registry.npmjs.org/glob/-/glob-3.2.11.tgz", + "integrity": "sha1-Spc/Y1uRkPcV0QmH1cAP0oFevj0=", + "requires": { + "inherits": "2", + "minimatch": "0.3" + } + }, + "lru-cache": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.7.3.tgz", + "integrity": "sha1-bUUk6LlV+V1PW1iFHOId1y+06VI=" + }, + "minimatch": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-0.3.0.tgz", + "integrity": "sha1-J12O2qxPG7MyZHIInnlJyDlGmd0=", + "requires": { + "lru-cache": "2", + "sigmund": "~1.0.0" + } + }, + "ms": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=" + } + } + }, + "move-concurrently": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/move-concurrently/-/move-concurrently-1.0.1.tgz", + "integrity": "sha1-viwAX9oy4LKa8fBdfEszIUxwH5I=", + "dev": true, + "requires": { + "aproba": "^1.1.1", + "copy-concurrently": "^1.0.0", + "fs-write-stream-atomic": "^1.0.8", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.3" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + } + } }, "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "msgpack-js": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/msgpack-js/-/msgpack-js-0.3.0.tgz", + "integrity": "sha1-Aw7AjFlW+cp9F9QKVy1Tlv7BCSM=", + "requires": { + "bops": "~0.0.6" + }, + "dependencies": { + "base64-js": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.2.tgz", + "integrity": "sha1-Ak8Pcq+iW3X5wO5zzU9V7Bvtl4Q=" + }, + "bops": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/bops/-/bops-0.0.7.tgz", + "integrity": "sha1-tKClqDmkBkVK8P4FqLkaenZqVOI=", + "requires": { + "base64-js": "0.0.2", + "to-utf8": "0.0.1" + } + } + } + }, + "msgpack-stream": { + "version": "0.0.13", + "resolved": "https://registry.npmjs.org/msgpack-stream/-/msgpack-stream-0.0.13.tgz", + "integrity": "sha1-UKZzrE6uyl43cBkk0JPUM1DB5Sw=", + "requires": { + "bops": "1.0.0", + "msgpack-js": "0.3.0", + "through": "2.3.4" + }, + "dependencies": { + "through": { + "version": "2.3.4", + "resolved": "http://registry.npmjs.org/through/-/through-2.3.4.tgz", + "integrity": "sha1-SV5A6Nio6uvHwnXqiMK4/BTFZFU=" + } + } + }, + "msgpack5": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/msgpack5/-/msgpack5-4.2.1.tgz", + "integrity": "sha512-Xo7nE9ZfBVonQi1rSopNAqPdts/QHyuSEUwIEzAkB+V2FtmkkLUbP6MyVqVVQxsZYI65FpvW3Bb8Z9ZWEjbgHQ==", + "requires": { + "bl": "^2.0.1", + "inherits": "^2.0.3", + "readable-stream": "^2.3.6", + "safe-buffer": "^5.1.2" + } + }, + "multicast-dns": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-6.2.3.tgz", + "integrity": "sha512-ji6J5enbMyGRHIAkAOu3WdV8nggqviKCEKtXcOqfphZZtQrmHKycfynJ2V7eVPUA4NhJ6V7Wf4TmGbTwKE9B6g==", + "dev": true, + "requires": { + "dns-packet": "^1.3.1", + "thunky": "^1.0.2" + } + }, + "multicast-dns-service-types": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/multicast-dns-service-types/-/multicast-dns-service-types-1.1.0.tgz", + "integrity": "sha1-iZ8R2WhuXgXLkbNdXw5jt3PPyQE=", + "dev": true + }, + "multiline": { + "version": "1.0.2", + "resolved": "http://registry.npmjs.org/multiline/-/multiline-1.0.2.tgz", + "integrity": "sha1-abHyX/B00oKJBPJE3dBrfZbvbJM=", + "dev": true, + "requires": { + "strip-indent": "^1.0.0" + } + }, + "multipipe": { + "version": "0.1.2", + "resolved": "http://registry.npmjs.org/multipipe/-/multipipe-0.1.2.tgz", + "integrity": "sha1-Ko8t33Du1WTf8tV/HhoTfZ8FB4s=", + "dev": true, + "requires": { + "duplexer2": "0.0.2" + } + }, + "mustache": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mustache/-/mustache-3.0.1.tgz", + "integrity": "sha512-jFI/4UVRsRYdUbuDTKT7KzfOp7FiD5WzYmmwNwXyUVypC0xjoTL78Fqc0jHUPIvvGD+6DQSPHIt1NE7D1ArsqA==" + }, + "mute-stdout": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mute-stdout/-/mute-stdout-1.0.1.tgz", + "integrity": "sha512-kDcwXR4PS7caBpuRYYBUz9iVixUk3anO3f5OYFiIPwK/20vCzKCHyKoulbiDY1S53zD2bxUpxN/IJ+TnXjfvxg==", + "dev": true + }, + "mute-stream": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz", + "integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=", + "dev": true + }, + "mux-demux": { + "version": "3.7.9", + "resolved": "http://registry.npmjs.org/mux-demux/-/mux-demux-3.7.9.tgz", + "integrity": "sha1-NTZ3GP02AcgLzi63YlMVdtekrO8=", + "requires": { + "duplex": "~1.0.0", + "json-buffer": "~2.0.4", + "msgpack-stream": "~0.0.10", + "stream-combiner": "0.0.2", + "stream-serializer": "~1.1.1", + "through": "~2.3.1", + "xtend": "~1.0.3" + } + }, + "mysql": { + "version": "2.17.1", + "resolved": "https://registry.npmjs.org/mysql/-/mysql-2.17.1.tgz", + "integrity": "sha512-7vMqHQ673SAk5C8fOzTG2LpPcf3bNt0oL3sFpxPEEFp1mdlDcrLK0On7z8ZYKaaHrHwNcQ/MTUz7/oobZ2OyyA==", + "requires": { + "bignumber.js": "7.2.1", + "readable-stream": "2.3.6", + "safe-buffer": "5.1.2", + "sqlstring": "2.3.1" + } + }, + "mysql2": { + "version": "1.6.5", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-1.6.5.tgz", + "integrity": "sha512-zedaOOyb3msuuZcJJnxIX/EGOpmljDG7B+UevRH5lqcv+yhy9eCwkArBz8/AO+/rlY3/oCsOdG8R5oD6k0hNfg==", + "dev": true, + "requires": { + "denque": "^1.4.0", + "generate-function": "^2.3.1", + "iconv-lite": "^0.4.24", + "long": "^4.0.0", + "lru-cache": "^4.1.3", + "named-placeholders": "^1.1.2", + "seq-queue": "^0.0.5", + "sqlstring": "^2.3.1" + }, + "dependencies": { + "lru-cache": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", + "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", + "dev": true, + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", + "dev": true + } + } + }, + "named-placeholders": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.2.tgz", + "integrity": "sha512-wiFWqxoLL3PGVReSZpjLVxyJ1bRqe+KKJVbr4hGs1KWfTZTQyezHFBbuKj9hsizHyGV2ne7EMjHdxEGAybD5SA==", + "dev": true, + "requires": { + "lru-cache": "^4.1.3" + }, + "dependencies": { + "lru-cache": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", + "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", + "dev": true, + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", + "dev": true + } + } + }, + "nan": { + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.0.tgz", + "integrity": "sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg==", + "dev": true + }, + "nanoid": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-2.0.3.tgz", + "integrity": "sha512-NbaoqdhIYmY6FXDRB4eYtDVC9Z9eCbn8TyaiC16LNKtpPv/aqa0tOPD8y6gNE4yUNnaZ7LLhYtXOev/6+cBtfw==" + }, + "nanomatch": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", + "integrity": "sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==", + "dev": true, + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "fragment-cache": "^0.2.1", + "is-windows": "^1.0.2", + "kind-of": "^6.0.2", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + } + }, + "natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", + "dev": true + }, + "negotiator": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", + "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==" + }, + "neo-async": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.1.tgz", + "integrity": "sha512-iyam8fBuCUpWeKPGpaNMetEocMt364qkCsfL9JuhjXX6dRnguRVOfk2GZaDpPjcOKiiXCPINZC1GczQ7iTq3Zw==", + "dev": true + }, + "next-tick": { + "version": "1.0.0", + "resolved": "http://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz", + "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=", + "dev": true + }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==" + }, + "nightmare": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/nightmare/-/nightmare-3.0.2.tgz", + "integrity": "sha512-z6Sr7k71pFcNHFH0orejum9xMzrsdU1lcxlbvNGRsKgDltmu4r52sK5opDnoqfyWS+w9SNthj/4Bbt5zNofzhw==", + "dev": true, + "requires": { + "debug": "^2.2.0", + "deep-defaults": "^1.0.3", + "defaults": "^1.0.2", + "electron": "^2.0.18", + "enqueue": "^1.0.2", + "function-source": "^0.1.0", + "jsesc": "^0.5.0", + "minstache": "^1.2.0", + "mkdirp": "^0.5.1", + "multiline": "^1.0.2", + "once": "^1.3.3", + "rimraf": "^2.4.3", + "sliced": "1.0.1", + "split2": "^2.0.1" + }, + "dependencies": { + "@types/node": { + "version": "8.10.59", + "resolved": "https://registry.npmjs.org/@types/node/-/node-8.10.59.tgz", + "integrity": "sha512-8RkBivJrDCyPpBXhVZcjh7cQxVBSmRk9QM7hOketZzp6Tg79c0N8kkpAIito9bnJ3HCVCHVYz+KHTEbfQNfeVQ==", + "dev": true + }, + "electron": { + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/electron/-/electron-2.0.18.tgz", + "integrity": "sha512-PQRHtFvLxHdJzMMIwTddUtkS+Te/fZIs+PHO+zPmTUTBE76V3Od3WRGzMQwiJHxN679licmCKhJpMyxZfDEVWQ==", + "dev": true, + "requires": { + "@types/node": "^8.0.24", + "electron-download": "^3.0.1", + "extract-zip": "^1.0.3" + } + }, + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "jsesc": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", + "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", + "dev": true + }, + "rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + } + } + }, + "no-case": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/no-case/-/no-case-2.3.2.tgz", + "integrity": "sha512-rmTZ9kz+f3rCvK2TD1Ue/oZlns7OGoIWP4fc3llxxRXlOkHKoWPPWJOfFYpITabSow43QJbRIoHQXtt10VldyQ==", + "dev": true, + "requires": { + "lower-case": "^1.1.1" + } + }, + "nocache": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/nocache/-/nocache-2.1.0.tgz", + "integrity": "sha512-0L9FvHG3nfnnmaEQPjT9xhfN4ISk0A8/2j4M37Np4mcDesJjHgEUfgPhdCyZuFI954tjokaIj/A3NdpFNdEh4Q==" + }, + "node-fetch": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.0.tgz", + "integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA==" + }, + "node-forge": { + "version": "0.8.5", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-0.8.5.tgz", + "integrity": "sha512-vFMQIWt+J/7FLNyKouZ9TazT74PRV3wgv9UT4cRjC8BffxFbKXkgIWR42URCPSnHm/QDz6BOlb2Q0U4+VQT67Q==" + }, + "node-gyp": { + "version": "3.8.0", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-3.8.0.tgz", + "integrity": "sha512-3g8lYefrRRzvGeSowdJKAKyks8oUpLEd/DyPV4eMhVlhJ0aNaZqIrNUIPuEWWTAoPqyFkfGrM67MC69baqn6vA==", + "dev": true, + "requires": { + "fstream": "^1.0.0", + "glob": "^7.0.3", + "graceful-fs": "^4.1.2", + "mkdirp": "^0.5.0", + "nopt": "2 || 3", + "npmlog": "0 || 1 || 2 || 3 || 4", + "osenv": "0", + "request": "^2.87.0", + "rimraf": "2", + "semver": "~5.3.0", + "tar": "^2.0.0", + "which": "1" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "semver": { + "version": "5.3.0", + "resolved": "http://registry.npmjs.org/semver/-/semver-5.3.0.tgz", + "integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8=", + "dev": true + } + } + }, + "node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha1-h6kGXNs1XTGC2PlM4RGIuCXGijs=", + "dev": true + }, + "node-libs-browser": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/node-libs-browser/-/node-libs-browser-2.2.1.tgz", + "integrity": "sha512-h/zcD8H9kaDZ9ALUWwlBUDo6TKF8a7qBSCSEGfjTVIYeqsioSKaAX+BN7NgiMGp6iSIXZ3PxgCu8KS3b71YK5Q==", + "dev": true, + "requires": { + "assert": "^1.1.1", + "browserify-zlib": "^0.2.0", + "buffer": "^4.3.0", + "console-browserify": "^1.1.0", + "constants-browserify": "^1.0.0", + "crypto-browserify": "^3.11.0", + "domain-browser": "^1.1.1", + "events": "^3.0.0", + "https-browserify": "^1.0.0", + "os-browserify": "^0.3.0", + "path-browserify": "0.0.1", + "process": "^0.11.10", + "punycode": "^1.2.4", + "querystring-es3": "^0.2.0", + "readable-stream": "^2.3.3", + "stream-browserify": "^2.0.1", + "stream-http": "^2.7.2", + "string_decoder": "^1.0.0", + "timers-browserify": "^2.0.4", + "tty-browserify": "0.0.0", + "url": "^0.11.0", + "util": "^0.11.0", + "vm-browserify": "^1.0.1" + }, + "dependencies": { + "events": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.0.0.tgz", + "integrity": "sha512-Dc381HFWJzEOhQ+d8pkNon++bk9h6cdAoAj4iE6Q4y6xgTzySWXlKn05/TVNpjnfRqi/X0EpJEJohPjNI3zpVA==", + "dev": true + }, + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=", + "dev": true + }, + "url": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", + "integrity": "sha1-ODjpfPxgUh63PFJajlW/3Z4uKPE=", + "dev": true, + "requires": { + "punycode": "1.3.2", + "querystring": "0.2.0" + }, + "dependencies": { + "punycode": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", + "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=", + "dev": true + } + } + } + } + }, + "node-modules-regexp": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-modules-regexp/-/node-modules-regexp-1.0.0.tgz", + "integrity": "sha1-jZ2+KJZKSsVxLpExZCEHxx6Q7EA=", + "dev": true + }, + "node-notifier": { + "version": "5.4.3", + "resolved": "https://registry.npmjs.org/node-notifier/-/node-notifier-5.4.3.tgz", + "integrity": "sha512-M4UBGcs4jeOK9CjTsYwkvH6/MzuUmGCyTW+kCY7uO+1ZVr0+FHGdPdIf5CCLqAaxnRrWidyoQlNkMIIVwbKB8Q==", + "dev": true, + "requires": { + "growly": "^1.3.0", + "is-wsl": "^1.1.0", + "semver": "^5.5.0", + "shellwords": "^0.1.1", + "which": "^1.3.0" + } + }, + "node-releases": { + "version": "1.1.32", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.32.tgz", + "integrity": "sha512-VhVknkitq8dqtWoluagsGPn3dxTvN9fwgR59fV3D7sLBHe0JfDramsMI8n8mY//ccq/Kkrf8ZRHRpsyVZ3qw1A==", + "dev": true, + "requires": { + "semver": "^5.3.0" + } + }, + "node-sass": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/node-sass/-/node-sass-4.12.0.tgz", + "integrity": "sha512-A1Iv4oN+Iel6EPv77/HddXErL2a+gZ4uBeZUy+a8O35CFYTXhgA8MgLCWBtwpGZdCvTvQ9d+bQxX/QC36GDPpQ==", + "dev": true, + "requires": { + "async-foreach": "^0.1.3", + "chalk": "^1.1.1", + "cross-spawn": "^3.0.0", + "gaze": "^1.0.0", + "get-stdin": "^4.0.1", + "glob": "^7.0.3", + "in-publish": "^2.0.0", + "lodash": "^4.17.11", + "meow": "^3.7.0", + "mkdirp": "^0.5.1", + "nan": "^2.13.2", + "node-gyp": "^3.8.0", + "npmlog": "^4.0.0", + "request": "^2.88.0", + "sass-graph": "^2.2.4", + "stdout-stream": "^1.4.0", + "true-case-path": "^1.0.2" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "http://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "cross-spawn": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-3.0.1.tgz", + "integrity": "sha1-ElYDfsufDF9549bvE14wdwGEuYI=", + "dev": true, + "requires": { + "lru-cache": "^4.0.1", + "which": "^1.2.9" + } + }, + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "lru-cache": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", + "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", + "dev": true, + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", + "dev": true + } + } + }, + "node.extend": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/node.extend/-/node.extend-1.1.8.tgz", + "integrity": "sha512-L/dvEBwyg3UowwqOUTyDsGBU6kjBQOpOhshio9V3i3BMPv5YUb9+mWNN8MK0IbWqT0AqaTSONZf0aTuMMahWgA==", + "dev": true, + "requires": { + "has": "^1.0.3", + "is": "^3.2.1" + } + }, + "nodemailer": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-4.7.0.tgz", + "integrity": "sha512-IludxDypFpYw4xpzKdMAozBSkzKHmNBvGanUREjJItgJ2NYcK/s8+PggVhj7c2yGFQykKsnnmv1+Aqo0ZfjHmw==" + }, + "nodemailer-direct-transport": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/nodemailer-direct-transport/-/nodemailer-direct-transport-3.3.2.tgz", + "integrity": "sha1-6W+vuQNYVglH5WkBfZfmBzilCoY=", + "requires": { + "nodemailer-shared": "1.1.0", + "smtp-connection": "2.12.0" + } + }, + "nodemailer-fetch": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/nodemailer-fetch/-/nodemailer-fetch-1.6.0.tgz", + "integrity": "sha1-ecSQihwPXzdbc/6IjamCj23JY6Q=" + }, + "nodemailer-shared": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/nodemailer-shared/-/nodemailer-shared-1.1.0.tgz", + "integrity": "sha1-z1mU4v0mjQD1zw+nZ6CBae2wfsA=", + "requires": { + "nodemailer-fetch": "1.6.0" + } + }, + "nodemailer-stub-transport": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/nodemailer-stub-transport/-/nodemailer-stub-transport-1.1.0.tgz", + "integrity": "sha1-EUIdLWa07m9AU1T5FMH0ZB6ySw0=" + }, + "nodemon": { + "version": "1.19.1", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-1.19.1.tgz", + "integrity": "sha512-/DXLzd/GhiaDXXbGId5BzxP1GlsqtMGM9zTmkWrgXtSqjKmGSbLicM/oAy4FR0YWm14jCHRwnR31AHS2dYFHrg==", + "dev": true, + "requires": { + "chokidar": "^2.1.5", + "debug": "^3.1.0", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.0.4", + "pstree.remy": "^1.1.6", + "semver": "^5.5.0", + "supports-color": "^5.2.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.2", + "update-notifier": "^2.5.0" + }, + "dependencies": { + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "nopt": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.6.tgz", + "integrity": "sha1-xkZdvwirzU2zWTF/eaxopkayj/k=", + "requires": { + "abbrev": "1" + } + }, + "normalize-package-data": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "dev": true, + "requires": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } }, "normalize-path": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", - "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", - "dev": true, - "requires": { - "remove-trailing-separator": "1.1.0" - } + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true + }, + "normalize-url": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-4.5.0.tgz", + "integrity": "sha512-2s47yzUxdexf1OhyRi4Em83iQk0aPvwTddtFz4hnSSw9dCEsLEGf6SwIO8ss/19S9iBb5sJaOuTvTGDeZI00BQ==" + }, + "now-and-later": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/now-and-later/-/now-and-later-2.0.1.tgz", + "integrity": "sha512-KGvQ0cB70AQfg107Xvs/Fbu+dGmZoTRJp2TaPwcwQm3/7PteUyN2BCgk8KBMPGBUXZdVwyWS8fDCGFygBm19UQ==", + "dev": true, + "requires": { + "once": "^1.3.2" + } + }, + "npm-conf": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/npm-conf/-/npm-conf-1.1.3.tgz", + "integrity": "sha512-Yic4bZHJOt9RCFbRP3GgpqhScOY4HH3V2P8yBj6CeYq118Qr+BLXqT2JvpJ00mryLESpgOxf5XlFv4ZjXxLScw==", + "optional": true, + "requires": { + "config-chain": "^1.1.11", + "pify": "^3.0.0" + }, + "dependencies": { + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "optional": true + } + } + }, + "npm-run-path": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", + "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", + "requires": { + "path-key": "^2.0.0" + } + }, + "npmlog": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-4.1.2.tgz", + "integrity": "sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==", + "dev": true, + "requires": { + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" + } + }, + "nth-check": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-1.0.2.tgz", + "integrity": "sha512-WeBOdju8SnzPN5vTUJYxYUxLeXpCaVP5i5e0LF8fg7WORF2Wd7wFX/pk0tYZk7s8T+J7VLy0Da6J1+wCT0AtHg==", + "dev": true, + "requires": { + "boolbase": "~1.0.0" + } + }, + "nugget": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/nugget/-/nugget-2.0.1.tgz", + "integrity": "sha1-IBCVpIfhrTYIGzQy+jytpPjQcbA=", + "dev": true, + "requires": { + "debug": "^2.1.3", + "minimist": "^1.1.0", + "pretty-bytes": "^1.0.2", + "progress-stream": "^1.1.0", + "request": "^2.45.0", + "single-line-log": "^1.1.2", + "throttleit": "0.0.2" + } + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "nwsapi": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.1.4.tgz", + "integrity": "sha512-iGfd9Y6SFdTNldEy2L0GUhcarIutFmk+MPWIn9dmj8NMIup03G08uUF2KGbbmv/Ux4RT0VZJoP/sVbWA6d/VIw==", + "dev": true + }, + "oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==" + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "dev": true + }, + "object-copy": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", + "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", + "dev": true, + "requires": { + "copy-descriptor": "^0.1.0", + "define-property": "^0.2.5", + "kind-of": "^3.0.3" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "object-diff": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/object-diff/-/object-diff-0.0.4.tgz", + "integrity": "sha1-2IOwRE/o/W4E5ZXXu2ZWgskWBH8=" + }, + "object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==" + }, + "object-visit": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", + "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", + "dev": true, + "requires": { + "isobject": "^3.0.0" + } + }, + "object.assign": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz", + "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", + "dev": true, + "requires": { + "define-properties": "^1.1.2", + "function-bind": "^1.1.1", + "has-symbols": "^1.0.0", + "object-keys": "^1.0.11" + } + }, + "object.defaults": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/object.defaults/-/object.defaults-1.1.0.tgz", + "integrity": "sha1-On+GgzS0B96gbaFtiNXNKeQ1/s8=", + "dev": true, + "requires": { + "array-each": "^1.0.1", + "array-slice": "^1.0.0", + "for-own": "^1.0.0", + "isobject": "^3.0.0" + } + }, + "object.getownpropertydescriptors": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.0.3.tgz", + "integrity": "sha1-h1jIRvW0B62rDyNuCYbxSwUcqhY=", + "dev": true, + "requires": { + "define-properties": "^1.1.2", + "es-abstract": "^1.5.1" + } + }, + "object.map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object.map/-/object.map-1.0.1.tgz", + "integrity": "sha1-z4Plncj8wK1fQlDh94s7gb2AHTc=", + "dev": true, + "requires": { + "for-own": "^1.0.0", + "make-iterator": "^1.0.0" + } + }, + "object.pick": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", + "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", + "requires": { + "isobject": "^3.0.1" + } + }, + "object.reduce": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object.reduce/-/object.reduce-1.0.1.tgz", + "integrity": "sha1-b+NI8qx/oPlcpiEiZZkJaCW7A60=", + "dev": true, + "requires": { + "for-own": "^1.0.0", + "make-iterator": "^1.0.0" + } + }, + "obuf": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/obuf/-/obuf-1.1.2.tgz", + "integrity": "sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg==", + "dev": true + }, + "on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "requires": { + "ee-first": "1.1.1" + } + }, + "on-headers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", + "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==" + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.0.tgz", + "integrity": "sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q==", + "requires": { + "mimic-fn": "^2.1.0" + } + }, + "opn": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/opn/-/opn-5.5.0.tgz", + "integrity": "sha512-PqHpggC9bLV0VeWcdKhkpxY+3JTzetLSqTCWL/z/tFIbI6G8JCjondXklT1JinczLz2Xib62sSp0T/gKT4KksA==", + "dev": true, + "requires": { + "is-wsl": "^1.1.0" + } + }, + "optimist": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz", + "integrity": "sha1-2j6nRob6IaGaERwybpDrFaAZZoY=", + "dev": true, + "requires": { + "minimist": "~0.0.1", + "wordwrap": "~0.0.2" + }, + "dependencies": { + "minimist": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz", + "integrity": "sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8=", + "dev": true + }, + "wordwrap": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz", + "integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=", + "dev": true + } + } + }, + "optional": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/optional/-/optional-0.1.4.tgz", + "integrity": "sha512-gtvrrCfkE08wKcgXaVwQVgwEQ8vel2dc5DDBn9RLQZ3YtmtkBss6A2HY6BnJH4N/4Ku97Ri/SF8sNWE2225WJw==" + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.4", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "wordwrap": "~1.0.0" + } + }, + "options": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/options/-/options-0.0.6.tgz", + "integrity": "sha1-7CLTEoBrtT5zF3Pnza788cZDEo8=" + }, + "ordered-read-streams": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ordered-read-streams/-/ordered-read-streams-1.0.1.tgz", + "integrity": "sha1-d8DLN8QVJdZBZtmQ/61+xqDhNj4=", + "dev": true, + "requires": { + "readable-stream": "^2.0.1" + } + }, + "original": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/original/-/original-1.0.2.tgz", + "integrity": "sha512-hyBVl6iqqUOJ8FqRe+l/gS8H+kKYjrEndd5Pm1MfBtsEKA038HkkdbAl/72EAXGyonD/PFsvmVG+EvcIpliMBg==", + "dev": true, + "requires": { + "url-parse": "^1.4.3" + } + }, + "os-browserify": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", + "integrity": "sha1-hUNzx/XCMVkU/Jv8a9gjj92h7Cc=", + "dev": true + }, + "os-homedir": { + "version": "1.0.2", + "resolved": "http://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=", + "dev": true + }, + "os-locale": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.1.0.tgz", + "integrity": "sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==", + "requires": { + "execa": "^1.0.0", + "lcid": "^2.0.0", + "mem": "^4.0.0" + } + }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "http://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", + "dev": true + }, + "osenv": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/osenv/-/osenv-0.1.5.tgz", + "integrity": "sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==", + "dev": true, + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } + }, + "p-cancelable": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz", + "integrity": "sha512-s73XxOZ4zpt1edZYZzvhqFa6uvQc1vwUa0K0BdtIZgQMAJj9IbebH+JkgKZc9h+B05PKHLOTl4ajG1BmNrVZlw==" + }, + "p-defer": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz", + "integrity": "sha1-n26xgvbJqozXQwBKfU+WsZaw+ww=" + }, + "p-each-series": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-each-series/-/p-each-series-1.0.0.tgz", + "integrity": "sha1-kw89Et0fUOdDRFeiLNbwSsatf3E=", + "dev": true, + "requires": { + "p-reduce": "^1.0.0" + } + }, + "p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=" + }, + "p-is-promise": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-2.1.0.tgz", + "integrity": "sha512-Y3W0wlRPK8ZMRbNq97l4M5otioeA5lm1z7bkNkxCka8HSPjR0xRWmpCmc9utiaLP9Jb1eD8BgeIxTW4AIF45Pg==" + }, + "p-limit": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", + "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "dev": true, + "requires": { + "p-limit": "^2.0.0" + } + }, + "p-map": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-2.1.0.tgz", + "integrity": "sha512-y3b8Kpd8OAN444hxfBbFfj1FY/RjtTd8tzYwhUqNYXx0fXx2iX4maP4Qr6qhIKbQXI02wTLAda4fYUbDagTUFw==", + "dev": true + }, + "p-queue": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-1.2.0.tgz", + "integrity": "sha1-Y5y4sHJwwVtx16ZEao4wQU88ltE=", + "dev": true + }, + "p-reduce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-reduce/-/p-reduce-1.0.0.tgz", + "integrity": "sha1-GMKw3ZNqRpClKfgjH1ig/bakffo=", + "dev": true + }, + "p-retry": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-3.0.1.tgz", + "integrity": "sha512-XE6G4+YTTkT2a0UWb2kjZe8xNwf8bIbnqpc/IS/idOBVhyves0mK5OJgeocjx7q5pvX/6m23xuzVPYT1uGM73w==", + "dev": true, + "requires": { + "retry": "^0.12.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true + }, + "package-json": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/package-json/-/package-json-4.0.1.tgz", + "integrity": "sha1-iGmgQBJTZhxMTKPabCEh7VVfXu0=", + "dev": true, + "requires": { + "got": "^6.7.1", + "registry-auth-token": "^3.0.1", + "registry-url": "^3.0.3", + "semver": "^5.1.0" + } + }, + "pako": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.10.tgz", + "integrity": "sha512-0DTvPVU3ed8+HNXOu5Bs+o//Mbdj9VNQMUOe9oKCwh8l0GNwpTDMKCWbRjgtD291AWnkAgkqA/LOnQS8AmS1tw==", + "dev": true + }, + "parallel-transform": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/parallel-transform/-/parallel-transform-1.1.0.tgz", + "integrity": "sha1-1BDwZbBdojCB/NEPKIVMKb2jOwY=", + "dev": true, + "requires": { + "cyclist": "~0.2.2", + "inherits": "^2.0.3", + "readable-stream": "^2.1.5" + } + }, + "param-case": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/param-case/-/param-case-2.1.1.tgz", + "integrity": "sha1-35T9jPZTHs915r75oIWPvHK+Ikc=", + "dev": true, + "requires": { + "no-case": "^2.2.0" + } + }, + "parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "requires": { + "callsites": "^3.0.0" + } + }, + "parse-asn1": { + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.4.tgz", + "integrity": "sha512-Qs5duJcuvNExRfFZ99HDD3z4mAi3r9Wl/FOjEOijlxwCZs7E7mW2vjTpgQ4J8LpTF8x5v+1Vn5UQFejmWT11aw==", + "dev": true, + "requires": { + "asn1.js": "^4.0.0", + "browserify-aes": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.0", + "pbkdf2": "^3.0.3", + "safe-buffer": "^5.1.1" + } + }, + "parse-filepath": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/parse-filepath/-/parse-filepath-1.0.2.tgz", + "integrity": "sha1-pjISf1Oq89FYdvWHLz/6x2PWyJE=", + "dev": true, + "requires": { + "is-absolute": "^1.0.0", + "map-cache": "^0.2.0", + "path-root": "^0.1.1" + } + }, + "parse-json": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz", + "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", + "dev": true, + "requires": { + "error-ex": "^1.2.0" + } + }, + "parse-node-version": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parse-node-version/-/parse-node-version-1.0.1.tgz", + "integrity": "sha512-3YHlOa/JgH6Mnpr05jP9eDG254US9ek25LyIxZlDItp2iJtwyaXQb57lBYLdT3MowkUFYEV2XXNAYIPlESvJlA==", + "dev": true + }, + "parse-passwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", + "integrity": "sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY=", + "dev": true + }, + "parse5": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", + "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", + "dev": true + }, + "parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==" + }, + "pascalcase": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", + "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", + "dev": true + }, + "path-browserify": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.1.tgz", + "integrity": "sha512-BapA40NHICOS+USX9SN4tyhq+A2RrN/Ws5F0Z5aMHDp98Fl86lX8Oti8B7uN93L4Ifv4fHOEA+pQw87gmMO/lQ==", + "dev": true + }, + "path-dirname": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-dirname/-/path-dirname-1.0.2.tgz", + "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=", + "dev": true + }, + "path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" + }, + "path-is-inside": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", + "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=", + "dev": true + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=" + }, + "path-parse": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", + "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", + "dev": true + }, + "path-root": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/path-root/-/path-root-0.1.1.tgz", + "integrity": "sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc=", + "dev": true, + "requires": { + "path-root-regex": "^0.1.0" + } + }, + "path-root-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/path-root-regex/-/path-root-regex-0.1.2.tgz", + "integrity": "sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0=", + "dev": true + }, + "path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" + }, + "path-type": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz", + "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + }, + "dependencies": { + "pify": { + "version": "2.3.0", + "resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + } + } + }, + "pbkdf2": { + "version": "3.0.17", + "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.0.17.tgz", + "integrity": "sha512-U/il5MsrZp7mGg3mSQfn742na2T+1/vHDCG5/iTI3X9MKUuYUZVLQhyRsg06mCgDBTd57TxzgZt7P+fYfjRLtA==", + "dev": true, + "requires": { + "create-hash": "^1.1.2", + "create-hmac": "^1.1.4", + "ripemd160": "^2.0.1", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, + "pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha1-elfrVQpng/kRUzH89GY9XI4AelA=" + }, + "performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=" }, "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==" }, - "supports-color": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.1.0.tgz", - "integrity": "sha512-Ry0AwkoKjDpVKK4sV4h6o3UJmNRbjYm2uXhwfj3J56lMVdvnUNqzQVRztOOMGQ++w1K/TjNDFvpJk0F/LoeBCQ==", - "dev": true, - "requires": { - "has-flag": "2.0.0" - } + "pinkie": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", + "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", + "dev": true }, - "yargs": { - "version": "6.6.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-6.6.0.tgz", - "integrity": "sha1-eC7CHvQDNF+DCoCMo9UTr1YGUgg=", - "dev": true, - "requires": { - "camelcase": "3.0.0", - "cliui": "3.2.0", - "decamelize": "1.2.0", - "get-caller-file": "1.0.2", - "os-locale": "1.4.0", - "read-pkg-up": "1.0.1", - "require-directory": "2.1.1", - "require-main-filename": "1.0.1", - "set-blocking": "2.0.0", - "string-width": "1.0.2", - "which-module": "1.0.0", - "y18n": "3.2.1", - "yargs-parser": "4.2.1" - } + "pinkie-promise": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", + "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", + "dev": true, + "requires": { + "pinkie": "^2.0.0" + } }, - "yargs-parser": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-4.2.1.tgz", - "integrity": "sha1-KczqwNxPA8bIe0qfIX3RjJ90hxw=", - "dev": true, - "requires": { - "camelcase": "3.0.0" - } - } - } - }, - "webpack-merge": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-4.1.1.tgz", - "integrity": "sha512-geQsZ86YkXOVOjvPC5yv3JSNnL6/X3Kzh935AQ/gJNEYXEfJDQFu/sdFuktS9OW2JcH/SJec8TGfRdrpHshH7A==", - "dev": true, - "requires": { - "lodash": "4.17.5" - }, - "dependencies": { - "lodash": { - "version": "4.17.5", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.5.tgz", - "integrity": "sha512-svL3uiZf1RwhH+cWrfZn3A4+U58wbP0tGVTLQPbjplZxZ8ROD9VLuNgsRniTlLe7OlSqR79RUehXgpBW/s0IQw==", - "dev": true - } - } - }, - "webpack-sources": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.1.0.tgz", - "integrity": "sha512-aqYp18kPphgoO5c/+NaUvEeACtZjMESmDChuD3NBciVpah3XpMEU9VAAtIaB1BsfJWWTSdv8Vv1m3T0aRk2dUw==", - "dev": true, - "requires": { - "source-list-map": "2.0.0", - "source-map": "0.6.1" - }, - "dependencies": { - "source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true - } - } - }, - "websocket-driver": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.0.tgz", - "integrity": "sha1-DK+dLXVdk67gSdS90NP+LMoqJOs=", - "dev": true, - "requires": { - "http-parser-js": "0.4.10", - "websocket-extensions": "0.1.3" - } - }, - "websocket-extensions": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.3.tgz", - "integrity": "sha512-nqHUnMXmBzT0w570r2JpJxfiSD1IzoI+HGVdd3aZ0yNi3ngvQ4jv1dtHt5VGxfI2yj5yqImPhOK4vmIh2xMbGg==", - "dev": true - }, - "which": { - "version": "1.2.11", - "resolved": "https://registry.npmjs.org/which/-/which-1.2.11.tgz", - "integrity": "sha1-yLLu6muMFln6fB3U/aq+lTPcXos=", - "requires": { - "isexe": "1.1.2" - } - }, - "which-module": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/which-module/-/which-module-1.0.0.tgz", - "integrity": "sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8=", - "dev": true - }, - "wide-align": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.2.tgz", - "integrity": "sha512-ijDLlyQ7s6x1JgCLur53osjm/UXUYD9+0PbYKrBsYisYXzCxN+HC3mYDNy/dWdmf3AwqwU3CXwDCvsNgGK1S0w==", - "dev": true, - "requires": { - "string-width": "1.0.2" - } - }, - "widest-line": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-1.0.0.tgz", - "integrity": "sha1-DAnIXCqUaD0Nfq+O4JfVZL8OEFw=", - "dev": true, - "requires": { - "string-width": "1.0.2" - } - }, - "window-size": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.1.0.tgz", - "integrity": "sha1-VDjNLqk7IC76Ohn+iIeu58lPnJ0=", - "dev": true - }, - "wordwrap": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz", - "integrity": "sha1-t5Zpu0LstAn4PVg8rVLKF+qhZD8=", - "dev": true - }, - "wrap-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.0.0.tgz", - "integrity": "sha1-fTD4+HP5pbvDpk2ryNF34HGuQm8=", - "dev": true, - "requires": { - "string-width": "1.0.2" - } - }, - "wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" - }, - "write": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/write/-/write-0.2.1.tgz", - "integrity": "sha1-X8A4KOJkzqP+kUVUdvejxWbLB1c=", - "requires": { - "mkdirp": "0.5.1" - } - }, - "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha1-H/YVdcLipOjlENb6TiQ8zhg5mas=", - "dev": true, - "requires": { - "graceful-fs": "4.1.11", - "imurmurhash": "0.1.4", - "signal-exit": "3.0.2" - }, - "dependencies": { - "graceful-fs": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", - "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", - "dev": true + "pirates": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.1.tgz", + "integrity": "sha512-WuNqLTbMI3tmfef2TKxlQmAiLHKtFhlsCZnPIpuv2Ow0RDVO8lfy1Opf4NUzlMXLjPl+Men7AuVdX6TA+s+uGA==", + "dev": true, + "requires": { + "node-modules-regexp": "^1.0.0" + } + }, + "pkg-dir": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", + "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", + "dev": true, + "requires": { + "find-up": "^3.0.0" + } + }, + "pkgcloud": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/pkgcloud/-/pkgcloud-2.1.0.tgz", + "integrity": "sha512-0029nB7g1Y9ESCPLESORiZaG19Yh9aHXZqe/odvJS9O5SJao2RUA1h8Oksz+qw4yS8ZaexcCEGqRPmQ+il7+yA==", + "requires": { + "@google-cloud/storage": "^2.4.3", + "async": "^2.6.1", + "aws-sdk": "^2.382.0", + "errs": "^0.3.2", + "eventemitter2": "^5.0.1", + "fast-json-patch": "^2.1.0", + "filed-mimefix": "^0.1.3", + "ip": "^1.1.5", + "liboneandone": "^1.2.0", + "lodash": "^4.17.10", + "mime": "^2.4.1", + "qs": "^6.5.2", + "request": "^2.88.0", + "through2": "^3.0.1", + "url-join": "^4.0.0", + "xml2js": "^0.4.19" + }, + "dependencies": { + "async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", + "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", + "requires": { + "lodash": "^4.17.11" + } + }, + "mime": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.4.tgz", + "integrity": "sha512-LRxmNwziLPT828z+4YkNzloCFC2YM4wrB99k+AV5ZbEyfGNWfG8SO1FUXLmLDBSo89NrJZ4DIWeLjy1CHGhMGA==" + } + } + }, + "plugin-error": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/plugin-error/-/plugin-error-1.0.1.tgz", + "integrity": "sha512-L1zP0dk7vGweZME2i+EeakvUNqSrdiI3F91TwEoYiGrAfUXmVv6fJIq4g82PAXxNsWOp0J7ZqQy/3Szz0ajTxA==", + "dev": true, + "requires": { + "ansi-colors": "^1.0.1", + "arr-diff": "^4.0.0", + "arr-union": "^3.1.0", + "extend-shallow": "^3.0.2" + } + }, + "pluralize": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-1.2.1.tgz", + "integrity": "sha1-0aIUg/0iu0HlihL6NCGCMUCJfEU=", + "dev": true + }, + "pn": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/pn/-/pn-1.1.0.tgz", + "integrity": "sha512-2qHaIQr2VLRFoxe2nASzsV6ef4yOOH+Fi9FBOVH6cqeSgUnoyySPZkxzLuzd+RYOQTRpROA0ztTMqxROKSb/nA==", + "dev": true + }, + "portfinder": { + "version": "1.0.20", + "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.20.tgz", + "integrity": "sha512-Yxe4mTyDzTd59PZJY4ojZR8F+E5e97iq2ZOHPz3HDgSvYC5siNad2tLooQ5y5QHyQhc3xVqvyk/eNA3wuoa7Sw==", + "dev": true, + "requires": { + "async": "^1.5.2", + "debug": "^2.2.0", + "mkdirp": "0.5.x" + } + }, + "posix-character-classes": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", + "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", + "dev": true + }, + "posix-getopt": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/posix-getopt/-/posix-getopt-1.2.0.tgz", + "integrity": "sha1-Su7rfa3mb8qKk2XdqfawBXQctiE=" + }, + "postcss": { + "version": "7.0.17", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-7.0.17.tgz", + "integrity": "sha512-546ZowA+KZ3OasvQZHsbuEpysvwTZNGJv9EfyCQdsIDltPSWHAeTQ5fQy/Npi2ZDtLI3zs7Ps/p6wThErhm9fQ==", + "dev": true, + "requires": { + "chalk": "^2.4.2", + "source-map": "^0.6.1", + "supports-color": "^6.1.0" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + }, + "supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "postcss-modules-extract-imports": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-2.0.0.tgz", + "integrity": "sha512-LaYLDNS4SG8Q5WAWqIJgdHPJrDDr/Lv775rMBFUbgjTz6j34lUznACHcdRWroPvXANP2Vj7yNK57vp9eFqzLWQ==", + "dev": true, + "requires": { + "postcss": "^7.0.5" + } + }, + "postcss-modules-local-by-default": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/postcss-modules-local-by-default/-/postcss-modules-local-by-default-2.0.6.tgz", + "integrity": "sha512-oLUV5YNkeIBa0yQl7EYnxMgy4N6noxmiwZStaEJUSe2xPMcdNc8WmBQuQCx18H5psYbVxz8zoHk0RAAYZXP9gA==", + "dev": true, + "requires": { + "postcss": "^7.0.6", + "postcss-selector-parser": "^6.0.0", + "postcss-value-parser": "^3.3.1" + } + }, + "postcss-modules-scope": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/postcss-modules-scope/-/postcss-modules-scope-2.1.0.tgz", + "integrity": "sha512-91Rjps0JnmtUB0cujlc8KIKCsJXWjzuxGeT/+Q2i2HXKZ7nBUeF9YQTZZTNvHVoNYj1AthsjnGLtqDUE0Op79A==", + "dev": true, + "requires": { + "postcss": "^7.0.6", + "postcss-selector-parser": "^6.0.0" + } + }, + "postcss-modules-values": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-values/-/postcss-modules-values-2.0.0.tgz", + "integrity": "sha512-Ki7JZa7ff1N3EIMlPnGTZfUMe69FFwiQPnVSXC9mnn3jozCRBYIxiZd44yJOV2AmabOo4qFf8s0dC/+lweG7+w==", + "dev": true, + "requires": { + "icss-replace-symbols": "^1.1.0", + "postcss": "^7.0.6" + } + }, + "postcss-selector-parser": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.2.tgz", + "integrity": "sha512-36P2QR59jDTOAiIkqEprfJDsoNrvwFei3eCqKd1Y0tUsBimsq39BLp7RD+JWny3WgB1zGhJX8XVePwm9k4wdBg==", + "dev": true, + "requires": { + "cssesc": "^3.0.0", + "indexes-of": "^1.0.1", + "uniq": "^1.0.1" + } + }, + "postcss-value-parser": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-3.3.1.tgz", + "integrity": "sha512-pISE66AbVkp4fDQ7VHBwRNXzAAKJjw4Vw7nWI/+Q3vuly7SNfgYXvm6i5IgFylHGK5sP/xHAbB7N49OS4gWNyQ==", + "dev": true + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "prepend-http": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-1.0.4.tgz", + "integrity": "sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw=", + "dev": true + }, + "pretty-bytes": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-1.0.4.tgz", + "integrity": "sha1-CiLoIQYJrTVUL4yNXSFZr/B1HIQ=", + "dev": true, + "requires": { + "get-stdin": "^4.0.1", + "meow": "^3.1.0" + } + }, + "pretty-error": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-2.1.1.tgz", + "integrity": "sha1-X0+HyPkeWuPzuoerTPXgOxoX8aM=", + "dev": true, + "requires": { + "renderkid": "^2.0.1", + "utila": "~0.4" + } + }, + "pretty-format": { + "version": "24.9.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-24.9.0.tgz", + "integrity": "sha512-00ZMZUiHaJrNfk33guavqgvfJS30sLYf0f8+Srklv0AMPodGGHcoHgksZ3OThYnIvOd+8yMCn0YiEOogjlgsnA==", + "dev": true, + "requires": { + "@jest/types": "^24.9.0", + "ansi-regex": "^4.0.0", + "ansi-styles": "^3.2.0", + "react-is": "^16.8.4" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true + } + } + }, + "pretty-hrtime": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/pretty-hrtime/-/pretty-hrtime-1.0.3.tgz", + "integrity": "sha1-t+PqQkNaTJsnWdmeDyAesZWALuE=", + "dev": true + }, + "private": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/private/-/private-0.1.8.tgz", + "integrity": "sha512-VvivMrbvd2nKkiG38qjULzlc+4Vx4wm/whI9pQD35YrARNnhxeiRktSOhSukRLFNlzg6Br/cJPet5J/u19r/mg==", + "dev": true + }, + "process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=", + "dev": true + }, + "process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, + "progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true + }, + "progress-stream": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/progress-stream/-/progress-stream-1.2.0.tgz", + "integrity": "sha1-LNPP6jO6OonJwSHsM0er6asSX3c=", + "dev": true, + "requires": { + "speedometer": "~0.1.2", + "through2": "~0.2.3" + }, + "dependencies": { + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "object-keys": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-0.4.0.tgz", + "integrity": "sha1-KKaq50KN0sOpLz2V8hM13SBOAzY=", + "dev": true + }, + "readable-stream": { + "version": "1.1.14", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", + "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + }, + "through2": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/through2/-/through2-0.2.3.tgz", + "integrity": "sha1-6zKE2k6jEbbMis42U3SKUqvyWj8=", + "dev": true, + "requires": { + "readable-stream": "~1.1.9", + "xtend": "~2.1.1" + } + }, + "xtend": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-2.1.2.tgz", + "integrity": "sha1-bv7MKk2tjmlixJAbM3znuoe10os=", + "dev": true, + "requires": { + "object-keys": "~0.4.0" + } + } + } + }, + "promise-inflight": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", + "integrity": "sha1-mEcocL8igTL8vdhoEputEsPAKeM=", + "dev": true + }, + "prompts": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.2.1.tgz", + "integrity": "sha512-VObPvJiWPhpZI6C5m60XOzTfnYg/xc/an+r9VYymj9WJW3B/DIH+REzjpAACPf8brwPeP+7vz3bIim3S+AaMjw==", + "dev": true, + "requires": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.3" + } + }, + "proto-list": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/proto-list/-/proto-list-1.2.4.tgz", + "integrity": "sha1-IS1b/hMYMGpCD2QCuOJv85ZHqEk=", + "optional": true + }, + "proxy-addr": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.5.tgz", + "integrity": "sha512-t/7RxHXPH6cJtP0pRG6smSr9QJidhB+3kXu0KgXnbGYMgzEnUxRQ4/LDdfOwZEMyIh3/xHb8PX3t+lfL9z+YVQ==", + "requires": { + "forwarded": "~0.1.2", + "ipaddr.js": "1.9.0" + } + }, + "prr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", + "integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=", + "dev": true + }, + "pseudomap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", + "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=" + }, + "psl": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.2.0.tgz", + "integrity": "sha512-GEn74ZffufCmkDDLNcl3uuyF/aSD6exEyh1v/ZSdAomB82t6G9hzJVRx0jBmLDW+VfZqks3aScmMw9DszwUalA==" + }, + "pstree.remy": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.7.tgz", + "integrity": "sha512-xsMgrUwRpuGskEzBFkH8NmTimbZ5PcPup0LA8JJkHIm2IMUbQcpo3yeLNWVrufEYjh8YwtSVh0xz6UeWc5Oh5A==", + "dev": true + }, + "public-encrypt": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.3.tgz", + "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "parse-asn1": "^5.0.0", + "randombytes": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "pumpify": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/pumpify/-/pumpify-1.5.1.tgz", + "integrity": "sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ==", + "requires": { + "duplexify": "^3.6.0", + "inherits": "^2.0.3", + "pump": "^2.0.0" + }, + "dependencies": { + "pump": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pump/-/pump-2.0.1.tgz", + "integrity": "sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA==", + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + } + } + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" + }, + "qs": { + "version": "6.7.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", + "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==" + }, + "querystring": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", + "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=" + }, + "querystring-browser": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/querystring-browser/-/querystring-browser-1.0.4.tgz", + "integrity": "sha1-8uNYgYQKgZvHsb9Zf68JeeZiLcY=" + }, + "querystring-es3": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz", + "integrity": "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM=", + "dev": true + }, + "querystringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.1.1.tgz", + "integrity": "sha512-w7fLxIRCRT7U8Qu53jQnJyPkYZIaR4n5151KMfcJlO/A9397Wxb1amJvROTK6TOnp7PfoAmg/qXiNHI+08jRfA==", + "dev": true + }, + "randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "requires": { + "safe-buffer": "^5.1.0" + } + }, + "randomfill": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.4.tgz", + "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", + "dev": true, + "requires": { + "randombytes": "^2.0.5", + "safe-buffer": "^5.1.0" + } + }, + "range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==" + }, + "raw-body": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz", + "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==", + "requires": { + "bytes": "3.1.0", + "http-errors": "1.7.2", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "dependencies": { + "bytes": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", + "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==" + } + } + }, + "raw-loader": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/raw-loader/-/raw-loader-1.0.0.tgz", + "integrity": "sha512-Uqy5AqELpytJTRxYT4fhltcKPj0TyaEpzJDcGz7DFJi+pQOOi3GjR/DOdxTkTsF+NzhnldIoG6TORaBlInUuqA==", + "dev": true, + "requires": { + "loader-utils": "^1.1.0", + "schema-utils": "^1.0.0" + } + }, + "rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "dev": true, + "requires": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "dependencies": { + "deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "dev": true + } + } + }, + "react-is": { + "version": "16.9.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.9.0.tgz", + "integrity": "sha512-tJBzzzIgnnRfEm046qRcURvwQnZVXmuCbscxUO5RWrGTXpon2d4c8mI0D8WE6ydVIm29JiLB6+RslkIvym9Rjw==", + "dev": true + }, + "read-pkg": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz", + "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", + "dev": true, + "requires": { + "load-json-file": "^1.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^1.0.0" + } + }, + "read-pkg-up": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-1.0.1.tgz", + "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", + "dev": true, + "requires": { + "find-up": "^1.0.0", + "read-pkg": "^1.0.0" + }, + "dependencies": { + "find-up": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", + "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", + "dev": true, + "requires": { + "path-exists": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "path-exists": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", + "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", + "dev": true, + "requires": { + "pinkie-promise": "^2.0.0" + } + } + } + }, + "readable-stream": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "readdirp": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.2.1.tgz", + "integrity": "sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.11", + "micromatch": "^3.1.10", + "readable-stream": "^2.0.2" + } + }, + "realpath-native": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/realpath-native/-/realpath-native-1.1.0.tgz", + "integrity": "sha512-wlgPA6cCIIg9gKz0fgAPjnzh4yR/LnXovwuo9hvyGvx3h8nX4+/iLZplfUWasXpqD8BdnGnP5njOFjkUwPzvjA==", + "dev": true, + "requires": { + "util.promisify": "^1.0.0" + } + }, + "recast": { + "version": "0.11.23", + "resolved": "https://registry.npmjs.org/recast/-/recast-0.11.23.tgz", + "integrity": "sha1-RR/TAEqx5N+bTktmN2sqIZEkYtM=", + "dev": true, + "requires": { + "ast-types": "0.9.6", + "esprima": "~3.1.0", + "private": "~0.1.5", + "source-map": "~0.5.0" + }, + "dependencies": { + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", + "dev": true + } + } + }, + "rechoir": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz", + "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=", + "dev": true, + "requires": { + "resolve": "^1.1.6" + } + }, + "redent": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-1.0.0.tgz", + "integrity": "sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94=", + "dev": true, + "requires": { + "indent-string": "^2.1.0", + "strip-indent": "^1.0.1" + } + }, + "referrer-policy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/referrer-policy/-/referrer-policy-1.2.0.tgz", + "integrity": "sha512-LgQJIuS6nAy1Jd88DCQRemyE3mS+ispwlqMk3b0yjZ257fI1v9c+/p6SD5gP5FGyXUIgrNOAfmyioHwZtYv2VA==" + }, + "regenerate": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.0.tgz", + "integrity": "sha512-1G6jJVDWrt0rK99kBjvEtziZNCICAuvIPkSiUFIQxVP06RCVpq3dmDo2oi6ABpYaDYaTRr67BEhL8r1wgEZZKg==", + "dev": true + }, + "regenerate-unicode-properties": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-8.1.0.tgz", + "integrity": "sha512-LGZzkgtLY79GeXLm8Dp0BVLdQlWICzBnJz/ipWUgo59qBaZ+BHtq51P2q1uVZlppMuUAT37SDk39qUbjTWB7bA==", + "dev": true, + "requires": { + "regenerate": "^1.4.0" + } + }, + "regenerator-runtime": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", + "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==" + }, + "regenerator-transform": { + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.14.1.tgz", + "integrity": "sha512-flVuee02C3FKRISbxhXl9mGzdbWUVHubl1SMaknjxkFB1/iqpJhArQUvRxOOPEc/9tAiX0BaQ28FJH10E4isSQ==", + "dev": true, + "requires": { + "private": "^0.1.6" + } + }, + "regex-not": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", + "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==", + "dev": true, + "requires": { + "extend-shallow": "^3.0.2", + "safe-regex": "^1.1.0" + } + }, + "regexp-tree": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/regexp-tree/-/regexp-tree-0.1.13.tgz", + "integrity": "sha512-hwdV/GQY5F8ReLZWO+W1SRoN5YfpOKY6852+tBFcma72DKBIcHjPRIlIvQN35bCOljuAfP2G2iB0FC/w236mUw==", + "dev": true + }, + "regexpp": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-2.0.1.tgz", + "integrity": "sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw==", + "dev": true + }, + "regexpu-core": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-4.6.0.tgz", + "integrity": "sha512-YlVaefl8P5BnFYOITTNzDvan1ulLOiXJzCNZxduTIosN17b87h3bvG9yHMoHaRuo88H4mQ06Aodj5VtYGGGiTg==", + "dev": true, + "requires": { + "regenerate": "^1.4.0", + "regenerate-unicode-properties": "^8.1.0", + "regjsgen": "^0.5.0", + "regjsparser": "^0.6.0", + "unicode-match-property-ecmascript": "^1.0.4", + "unicode-match-property-value-ecmascript": "^1.1.0" + } + }, + "registry-auth-token": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-3.4.0.tgz", + "integrity": "sha512-4LM6Fw8eBQdwMYcES4yTnn2TqIasbXuwDx3um+QRs7S55aMKCBKBxvPXl2RiUjHwuJLTyYfxSpmfSAjQpcuP+A==", + "dev": true, + "requires": { + "rc": "^1.1.6", + "safe-buffer": "^5.0.1" + } + }, + "registry-url": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/registry-url/-/registry-url-3.1.0.tgz", + "integrity": "sha1-PU74cPc93h138M+aOBQyRE4XSUI=", + "dev": true, + "requires": { + "rc": "^1.0.1" + } + }, + "regjsgen": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/regjsgen/-/regjsgen-0.5.0.tgz", + "integrity": "sha512-RnIrLhrXCX5ow/E5/Mh2O4e/oa1/jW0eaBKTSy3LaCj+M3Bqvm97GWDp2yUtzIs4LEn65zR2yiYGFqb2ApnzDA==", + "dev": true + }, + "regjsparser": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.6.0.tgz", + "integrity": "sha512-RQ7YyokLiQBomUJuUG8iGVvkgOLxwyZM8k6d3q5SAXpg4r5TZJZigKFvC6PpD+qQ98bCDC5YelPeA3EucDoNeQ==", + "dev": true, + "requires": { + "jsesc": "~0.5.0" + }, + "dependencies": { + "jsesc": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", + "integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=", + "dev": true + } + } + }, + "relateurl": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/relateurl/-/relateurl-0.2.7.tgz", + "integrity": "sha1-VNvzd+UUQKypCkzSdGANP/LYiKk=", + "dev": true + }, + "remove-bom-buffer": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/remove-bom-buffer/-/remove-bom-buffer-3.0.0.tgz", + "integrity": "sha512-8v2rWhaakv18qcvNeli2mZ/TMTL2nEyAKRvzo1WtnZBl15SHyEhrCu2/xKlJyUFKHiHgfXIyuY6g2dObJJycXQ==", + "dev": true, + "requires": { + "is-buffer": "^1.1.5", + "is-utf8": "^0.2.1" + } + }, + "remove-bom-stream": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/remove-bom-stream/-/remove-bom-stream-1.2.0.tgz", + "integrity": "sha1-BfGlk/FuQuH7kOv1nejlaVJflSM=", + "dev": true, + "requires": { + "remove-bom-buffer": "^3.0.0", + "safe-buffer": "^5.1.0", + "through2": "^2.0.3" + }, + "dependencies": { + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "remove-trailing-separator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", + "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", + "dev": true + }, + "renderkid": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/renderkid/-/renderkid-2.0.3.tgz", + "integrity": "sha512-z8CLQp7EZBPCwCnncgf9C4XAi3WR0dv+uWu/PjIyhhAb5d6IJ/QZqlHFprHeKT+59//V6BNUsLbvN8+2LarxGA==", + "dev": true, + "requires": { + "css-select": "^1.1.0", + "dom-converter": "^0.2", + "htmlparser2": "^3.3.0", + "strip-ansi": "^3.0.0", + "utila": "^0.4.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, + "repeat-element": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.3.tgz", + "integrity": "sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g==", + "dev": true + }, + "repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", + "dev": true + }, + "repeating": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", + "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", + "dev": true, + "requires": { + "is-finite": "^1.0.0" + } + }, + "replace-ext": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-1.0.0.tgz", + "integrity": "sha1-3mMSg3P8v3w8z6TeWkgMRaZ5WOs=", + "dev": true + }, + "replace-homedir": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/replace-homedir/-/replace-homedir-1.0.0.tgz", + "integrity": "sha1-6H9tUTuSjd6AgmDBK+f+xv9ueYw=", + "dev": true, + "requires": { + "homedir-polyfill": "^1.0.1", + "is-absolute": "^1.0.0", + "remove-trailing-separator": "^1.1.0" + } + }, + "request": { + "version": "2.88.0", + "resolved": "https://registry.npmjs.org/request/-/request-2.88.0.tgz", + "integrity": "sha512-NAqBSrijGLZdM0WZNsInLJpkJokL72XYjUpnB0iwsRgxh7dB6COrHnTBNwN0E+lHDAJzu7kLAkDeY08z2/A0hg==", + "requires": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.0", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.4.3", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + }, + "dependencies": { + "qs": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", + "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==" + } + } + }, + "request-promise-core": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/request-promise-core/-/request-promise-core-1.1.2.tgz", + "integrity": "sha512-UHYyq1MO8GsefGEt7EprS8UrXsm1TxEvFUX1IMTuSLU2Rh7fTIdFtl8xD7JiEYiWU2dl+NYAjCTksTehQUxPag==", + "requires": { + "lodash": "^4.17.11" + } + }, + "request-promise-native": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/request-promise-native/-/request-promise-native-1.0.7.tgz", + "integrity": "sha512-rIMnbBdgNViL37nZ1b3L/VfPOpSi0TqVDQPAvO6U14lMzOLrt5nilxCQqtDKhZeDiW0/hkCXGoQjhgJd/tCh6w==", + "requires": { + "request-promise-core": "1.1.2", + "stealthy-require": "^1.1.1", + "tough-cookie": "^2.3.3" + } + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", + "dev": true + }, + "require-main-filename": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz", + "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=", + "dev": true + }, + "require-yaml": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/require-yaml/-/require-yaml-0.0.1.tgz", + "integrity": "sha1-LhsY2RPDuqcqWk03O28Tjd0sMr0=", + "requires": { + "js-yaml": "^3.13.1" + } + }, + "requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=", + "dev": true + }, + "resolve": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.1.tgz", + "integrity": "sha512-vIpgF6wfuJOZI7KKKSP+HmiKggadPQAdsp5HiC1mvqnfp0gF1vdwgBWZIdrVft9pgqoMFQN+R7BSWZiBxx+BBw==", + "dev": true, + "requires": { + "path-parse": "^1.0.6" + } + }, + "resolve-cwd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-2.0.0.tgz", + "integrity": "sha1-AKn3OHVW4nA46uIyyqNypqWbZlo=", + "dev": true, + "requires": { + "resolve-from": "^3.0.0" + }, + "dependencies": { + "resolve-from": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-3.0.0.tgz", + "integrity": "sha1-six699nWiBvItuZTM17rywoYh0g=", + "dev": true + } + } + }, + "resolve-dir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", + "integrity": "sha1-eaQGRMNivoLybv/nOcm7U4IEb0M=", + "dev": true, + "requires": { + "expand-tilde": "^2.0.0", + "global-modules": "^1.0.0" + } + }, + "resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true + }, + "resolve-options": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/resolve-options/-/resolve-options-1.1.0.tgz", + "integrity": "sha1-MrueOcBtZzONyTeMDW1gdFZq0TE=", + "dev": true, + "requires": { + "value-or-function": "^3.0.0" + } + }, + "resolve-url": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", + "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", + "dev": true + }, + "responselike": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/responselike/-/responselike-1.0.2.tgz", + "integrity": "sha1-kYcg7ztjHFZCvgaPFa3lpG9Loec=", + "requires": { + "lowercase-keys": "^1.0.0" + } + }, + "restore-cursor": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", + "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", + "dev": true, + "requires": { + "onetime": "^2.0.0", + "signal-exit": "^3.0.2" + }, + "dependencies": { + "mimic-fn": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", + "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==", + "dev": true + }, + "onetime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", + "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", + "dev": true, + "requires": { + "mimic-fn": "^1.0.0" + } + } + } + }, + "ret": { + "version": "0.1.15", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", + "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", + "dev": true + }, + "retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", + "integrity": "sha1-G0KmJmoh8HQh0bC1S33BZ7AcATs=", + "dev": true + }, + "retry-request": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/retry-request/-/retry-request-4.1.1.tgz", + "integrity": "sha512-BINDzVtLI2BDukjWmjAIRZ0oglnCAkpP2vQjM3jdLhmT62h0xnQgciPwBRDAvHqpkPT2Wo1XuUyLyn6nbGrZQQ==", + "requires": { + "debug": "^4.1.1", + "through2": "^3.0.1" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "rimraf": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.2.8.tgz", + "integrity": "sha1-5Dm+Kq7jJzIZUnMPmaiSnk/FBYI=" + }, + "ripemd160": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", + "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", + "dev": true, + "requires": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1" + } + }, + "roarr": { + "version": "2.14.6", + "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.14.6.tgz", + "integrity": "sha512-qjbw0BEesKA+3XFBPt+KVe1PC/Z6ShfJ4wPlx2XifqH5h2Lj8/KQT5XJTsy3n1Es5kai+BwKALaECW3F70B1cg==", + "optional": true, + "requires": { + "boolean": "^3.0.0", + "detect-node": "^2.0.4", + "globalthis": "^1.0.0", + "json-stringify-safe": "^5.0.1", + "semver-compare": "^1.0.0", + "sprintf-js": "^1.1.2" + } + }, + "rsvp": { + "version": "4.8.5", + "resolved": "https://registry.npmjs.org/rsvp/-/rsvp-4.8.5.tgz", + "integrity": "sha512-nfMOlASu9OnRJo1mbEk2cz0D56a1MBNrJ7orjRZQG10XDyuvwksKbuXNp6qa+kbn839HwjwhBzhFmdsaEAfauA==", + "dev": true + }, + "run-async": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.3.0.tgz", + "integrity": "sha1-A3GrSuC91yDUFm19/aZP96RFpsA=", + "dev": true, + "requires": { + "is-promise": "^2.1.0" + } + }, + "run-queue": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/run-queue/-/run-queue-1.0.3.tgz", + "integrity": "sha1-6Eg5bwV9Ij8kOGkkYY4laUFh7Ec=", + "dev": true, + "requires": { + "aproba": "^1.1.1" + } + }, + "rxjs": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", + "dev": true, + "requires": { + "tslib": "^1.9.0" + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "safe-regex": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", + "dev": true, + "requires": { + "ret": "~0.1.10" + } + }, + "safefs": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/safefs/-/safefs-3.2.2.tgz", + "integrity": "sha1-gXDBRE1wOOCMrqBaN0+uL6NJ4Vw=", + "requires": { + "graceful-fs": "*" + } + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "sane": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/sane/-/sane-4.1.0.tgz", + "integrity": "sha512-hhbzAgTIX8O7SHfp2c8/kREfEn4qO/9q8C9beyY6+tvZ87EpoZ3i1RIEvp27YBswnNbY9mWd6paKVmKbAgLfZA==", + "dev": true, + "requires": { + "@cnakazawa/watch": "^1.0.3", + "anymatch": "^2.0.0", + "capture-exit": "^2.0.0", + "exec-sh": "^0.3.2", + "execa": "^1.0.0", + "fb-watchman": "^2.0.0", + "micromatch": "^3.1.4", + "minimist": "^1.1.1", + "walker": "~1.0.5" + } + }, + "sanitize-filename": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/sanitize-filename/-/sanitize-filename-1.6.3.tgz", + "integrity": "sha512-y/52Mcy7aw3gRm7IrcGDFx/bCk4AhRh2eI9luHOQM86nZsqwiRkkq2GekHXBBD+SmPidc8i2PqtYZl+pWJ8Oeg==", + "requires": { + "truncate-utf8-bytes": "^1.0.0" + } + }, + "sass-graph": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/sass-graph/-/sass-graph-2.2.4.tgz", + "integrity": "sha1-E/vWPNHK8JCLn9k0dq1DpR0eC0k=", + "dev": true, + "requires": { + "glob": "^7.0.0", + "lodash": "^4.0.0", + "scss-tokenizer": "^0.2.3", + "yargs": "^7.0.0" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + } + } + }, + "sass-loader": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/sass-loader/-/sass-loader-7.1.0.tgz", + "integrity": "sha512-+G+BKGglmZM2GUSfT9TLuEp6tzehHPjAMoRRItOojWIqIGPloVCMhNIQuG639eJ+y033PaGTSjLaTHts8Kw79w==", + "dev": true, + "requires": { + "clone-deep": "^2.0.1", + "loader-utils": "^1.0.1", + "lodash.tail": "^4.1.1", + "neo-async": "^2.5.0", + "pify": "^3.0.0", + "semver": "^5.5.0" + }, + "dependencies": { + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true + } + } + }, + "sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" + }, + "scandirectory": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/scandirectory/-/scandirectory-2.5.0.tgz", + "integrity": "sha1-bOA/VKCQtmjjy+2/IO354xBZPnI=", + "requires": { + "ignorefs": "^1.0.0", + "safefs": "^3.1.2", + "taskgroup": "^4.0.5" + } + }, + "schema-utils": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz", + "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==", + "dev": true, + "requires": { + "ajv": "^6.1.0", + "ajv-errors": "^1.0.0", + "ajv-keywords": "^3.1.0" + } + }, + "scss-tokenizer": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/scss-tokenizer/-/scss-tokenizer-0.2.3.tgz", + "integrity": "sha1-jrBtualyMzOCTT9VMGQRSYR85dE=", + "dev": true, + "requires": { + "js-base64": "^2.1.8", + "source-map": "^0.4.2" + }, + "dependencies": { + "source-map": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz", + "integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=", + "dev": true, + "requires": { + "amdefine": ">=0.0.4" + } + } + } + }, + "select-hose": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/select-hose/-/select-hose-2.0.0.tgz", + "integrity": "sha1-Yl2GWPhlr0Psliv8N2o3NZpJlMo=", + "dev": true + }, + "selfsigned": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/selfsigned/-/selfsigned-1.10.4.tgz", + "integrity": "sha512-9AukTiDmHXGXWtWjembZ5NDmVvP2695EtpgbCsxCa68w3c88B+alqbmZ4O3hZ4VWGXeGWzEVdvqgAJD8DQPCDw==", + "dev": true, + "requires": { + "node-forge": "0.7.5" + }, + "dependencies": { + "node-forge": { + "version": "0.7.5", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-0.7.5.tgz", + "integrity": "sha512-MmbQJ2MTESTjt3Gi/3yG1wGpIMhUfcIypUCGtTizFR9IiccFwxSpfp0vtIZlkFclEqERemxfnSdZEMR9VqqEFQ==", + "dev": true + } + } + }, + "semver": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", + "integrity": "sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==" + }, + "semver-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", + "integrity": "sha1-De4hahyUGrN+nvsXiPavxf9VN/w=", + "optional": true + }, + "semver-diff": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/semver-diff/-/semver-diff-2.1.0.tgz", + "integrity": "sha1-S7uEN8jTfksM8aaP1ybsbWRdbTY=", + "dev": true, + "requires": { + "semver": "^5.0.3" + } + }, + "semver-greatest-satisfied-range": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/semver-greatest-satisfied-range/-/semver-greatest-satisfied-range-1.1.0.tgz", + "integrity": "sha1-E+jCZYq5aRywzXEJMkAoDTb3els=", + "dev": true, + "requires": { + "sver-compat": "^1.5.0" + } + }, + "send": { + "version": "0.17.1", + "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", + "integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==", + "requires": { + "debug": "2.6.9", + "depd": "~1.1.2", + "destroy": "~1.0.4", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "~1.7.2", + "mime": "1.6.0", + "ms": "2.1.1", + "on-finished": "~2.3.0", + "range-parser": "~1.2.1", + "statuses": "~1.5.0" + }, + "dependencies": { + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" + }, + "ms": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" + } + } + }, + "seq-queue": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz", + "integrity": "sha1-1WgS4cAXpuTnw+Ojeh2m143TyT4=", + "dev": true + }, + "serialize-error": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-5.0.0.tgz", + "integrity": "sha512-/VtpuyzYf82mHYTtI4QKtwHa79vAdU5OQpNPAmE/0UDdlGT0ZxHwC+J6gXkw29wwoVI8fMPsfcVHOwXtUQYYQA==", + "optional": true, + "requires": { + "type-fest": "^0.8.0" + } + }, + "serialize-javascript": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-1.7.0.tgz", + "integrity": "sha512-ke8UG8ulpFOxO8f8gRYabHQe/ZntKlcig2Mp+8+URDP1D8vJZ0KUt7LYo07q25Z/+JVSgpr/cui9PIp5H6/+nA==", + "dev": true + }, + "serve-favicon": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/serve-favicon/-/serve-favicon-2.5.0.tgz", + "integrity": "sha1-k10kDN/g9YBTB/3+ln2IlCosvPA=", + "requires": { + "etag": "~1.8.1", + "fresh": "0.5.2", + "ms": "2.1.1", + "parseurl": "~1.3.2", + "safe-buffer": "5.1.1" + }, + "dependencies": { + "ms": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" + }, + "safe-buffer": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", + "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" + } + } + }, + "serve-index": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/serve-index/-/serve-index-1.9.1.tgz", + "integrity": "sha1-03aNabHn2C5c4FD/9bRTvqEqkjk=", + "dev": true, + "requires": { + "accepts": "~1.3.4", + "batch": "0.6.1", + "debug": "2.6.9", + "escape-html": "~1.0.3", + "http-errors": "~1.6.2", + "mime-types": "~2.1.17", + "parseurl": "~1.3.2" + }, + "dependencies": { + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "dev": true + }, + "http-errors": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz", + "integrity": "sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0=", + "dev": true, + "requires": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.0", + "statuses": ">= 1.4.0 < 2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "setprototypeof": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", + "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==", + "dev": true + } + } + }, + "serve-static": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz", + "integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==", + "requires": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.17.1" + } + }, + "set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", + "dev": true + }, + "set-value": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz", + "integrity": "sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.3", + "split-string": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=", + "dev": true + }, + "setprototypeof": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz", + "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==" + }, + "sha.js": { + "version": "2.4.11", + "resolved": "http://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "shallow-clone": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-1.0.0.tgz", + "integrity": "sha512-oeXreoKR/SyNJtRJMAKPDSvd28OqEwG4eR/xc856cRGBII7gX9lvAqDxusPm0846z/w/hWYjI1NpKwJ00NHzRA==", + "dev": true, + "requires": { + "is-extendable": "^0.1.1", + "kind-of": "^5.0.0", + "mixin-object": "^2.0.1" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=" + }, + "shellwords": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/shellwords/-/shellwords-0.1.1.tgz", + "integrity": "sha512-vFwSUfQvqybiICwZY5+DAWIPLKsWO31Q91JSKl3UYv+K5c2QRPzn0qzec6QPu1Qc9eHYItiP3NdJqNVqetYAww==", + "dev": true + }, + "shimmer": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/shimmer/-/shimmer-1.2.1.tgz", + "integrity": "sha512-sQTKC1Re/rM6XyFM6fIAGHRPVGvyXfgzIDvzoq608vM+jeyVD0Tu1E6Np0Kc2zAIFWIj963V2800iF/9LPieQw==" + }, + "shortid": { + "version": "2.2.14", + "resolved": "https://registry.npmjs.org/shortid/-/shortid-2.2.14.tgz", + "integrity": "sha512-4UnZgr9gDdA1kaKj/38IiudfC3KHKhDc1zi/HSxd9FQDR0VLwH3/y79tZJLsVYPsJgIjeHjqIWaWVRJUj9qZOQ==", + "requires": { + "nanoid": "^2.0.0" + } + }, + "sigmund": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/sigmund/-/sigmund-1.0.1.tgz", + "integrity": "sha1-P/IfGYytIXX587eBhT/ZTQ0ZtZA=" }, "signal-exit": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", - "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", - "dev": true + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", + "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=" + }, + "single-line-log": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/single-line-log/-/single-line-log-1.1.2.tgz", + "integrity": "sha1-wvg/Jzo+GhbtsJlWYdoO1e8DM2Q=", + "dev": true, + "requires": { + "string-width": "^1.0.1" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "dev": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "dev": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, + "sisteransi": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.3.tgz", + "integrity": "sha512-SbEG75TzH8G7eVXFSN5f9EExILKfly7SUvVY5DhhYLvfhKqhDFY0OzevWa/zwak0RLRfWS5AvfMWpd9gJvr5Yg==", + "dev": true + }, + "slash": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", + "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", + "dev": true + }, + "slice-ansi": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-2.1.0.tgz", + "integrity": "sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.0", + "astral-regex": "^1.0.0", + "is-fullwidth-code-point": "^2.0.0" + } + }, + "sliced": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", + "integrity": "sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E=", + "dev": true + }, + "smtp-connection": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/smtp-connection/-/smtp-connection-2.12.0.tgz", + "integrity": "sha1-1275EnyyPCJZ7bHoNJwujV4tdME=", + "requires": { + "httpntlm": "1.6.1", + "nodemailer-shared": "1.1.0" + } + }, + "snakeize": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/snakeize/-/snakeize-0.1.0.tgz", + "integrity": "sha1-EMCI2LWOsHazIpu1oE4jLOEmQi0=" + }, + "snapdragon": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", + "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==", + "dev": true, + "requires": { + "base": "^0.11.1", + "debug": "^2.2.0", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "map-cache": "^0.2.2", + "source-map": "^0.5.6", + "source-map-resolve": "^0.5.0", + "use": "^3.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "snapdragon-node": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", + "integrity": "sha1-bBdfhv8UvbByRWPo88GwIaKGhTs=", + "dev": true, + "requires": { + "define-property": "^1.0.0", + "isobject": "^3.0.0", + "snapdragon-util": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "snapdragon-util": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", + "integrity": "sha1-+VZHlIbyrNeXAGk/b3uAXkWrVuI=", + "dev": true, + "requires": { + "kind-of": "^3.2.0" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "soap": { + "version": "0.26.0", + "resolved": "https://registry.npmjs.org/soap/-/soap-0.26.0.tgz", + "integrity": "sha512-tTS3lnGl6lfjQQuJgNnWOgC0Xa6qYQSwl2G7DX3kCdGmek/FTNmHDM/7icKP1KBMFfCrKpAWEbZiGefa92SCYw==", + "requires": { + "bluebird": "^3.5.0", + "concat-stream": "^1.5.1", + "debug": "^2.6.9", + "ejs": "~2.5.5", + "finalhandler": "^1.0.3", + "httpntlm": "^1.5.2", + "lodash": "^4.17.5", + "request": ">=2.9.0", + "sax": ">=0.6", + "serve-static": "^1.11.1", + "strip-bom": "~0.3.1", + "uuid": "^3.1.0", + "xml-crypto": "~0.8.0" + }, + "dependencies": { + "concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "ejs": { + "version": "2.5.9", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-2.5.9.tgz", + "integrity": "sha512-GJCAeDBKfREgkBtgrYSf9hQy9kTb3helv0zGdzqhM7iAkW8FA/ZF97VQDbwFiwIT8MQLLOe5VlPZOEvZAqtUAQ==" + } + } + }, + "sockjs": { + "version": "0.3.19", + "resolved": "https://registry.npmjs.org/sockjs/-/sockjs-0.3.19.tgz", + "integrity": "sha512-V48klKZl8T6MzatbLlzzRNhMepEys9Y4oGFpypBFFn1gLI/QQ9HtLLyWJNbPlwGLelOVOEijUbTTJeLLI59jLw==", + "dev": true, + "requires": { + "faye-websocket": "^0.10.0", + "uuid": "^3.0.1" + } + }, + "sockjs-client": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/sockjs-client/-/sockjs-client-1.3.0.tgz", + "integrity": "sha512-R9jxEzhnnrdxLCNln0xg5uGHqMnkhPSTzUZH2eXcR03S/On9Yvoq2wyUZILRUhZCNVu2PmwWVoyuiPz8th8zbg==", + "dev": true, + "requires": { + "debug": "^3.2.5", + "eventsource": "^1.0.7", + "faye-websocket": "~0.11.1", + "inherits": "^2.0.3", + "json3": "^3.3.2", + "url-parse": "^1.4.3" + }, + "dependencies": { + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "faye-websocket": { + "version": "0.11.3", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.3.tgz", + "integrity": "sha512-D2y4bovYpzziGgbHYtGCMjlJM36vAl/y+xUyn1C+FVx8szd1E+86KwVw6XvYSzOP8iMpm1X0I4xJD+QtUb36OA==", + "dev": true, + "requires": { + "websocket-driver": ">=0.5.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "source-list-map": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.1.tgz", + "integrity": "sha512-qnQ7gVMxGNxsiL4lEuJwe/To8UnK7fAnmbGEEH8RpLouuKbeEm0lhbQVFIrNSuB+G7tVrAlVsZgETT5nljf+Iw==", + "dev": true + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "source-map-resolve": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.2.tgz", + "integrity": "sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA==", + "dev": true, + "requires": { + "atob": "^2.1.1", + "decode-uri-component": "^0.2.0", + "resolve-url": "^0.2.1", + "source-map-url": "^0.4.0", + "urix": "^0.1.0" + } + }, + "source-map-support": { + "version": "0.5.12", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.12.tgz", + "integrity": "sha512-4h2Pbvyy15EE02G+JOZpUCmqWJuqrs+sEkzewTm++BPi7Hvn/HwcqLAcNxYAyI0x13CpPPn+kMjl+hplXMHITQ==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "source-map-url": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", + "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=", + "dev": true + }, + "sparkles": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/sparkles/-/sparkles-1.0.1.tgz", + "integrity": "sha512-dSO0DDYUahUt/0/pD/Is3VIm5TGJjludZ0HVymmhYF6eNA53PVLhnUk0znSYbH8IYBuJdCE+1luR22jNLMaQdw==", + "dev": true + }, + "spdx-correct": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.0.tgz", + "integrity": "sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q==", + "dev": true, + "requires": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-exceptions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz", + "integrity": "sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA==", + "dev": true + }, + "spdx-expression-parse": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz", + "integrity": "sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg==", + "dev": true, + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-license-ids": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.4.tgz", + "integrity": "sha512-7j8LYJLeY/Yb6ACbQ7F76qy5jHkp0U6jgBfJsk97bwWlVUnUWsAgpyaCvo17h0/RQGnQ036tVDomiwoI4pDkQA==", + "dev": true + }, + "spdy": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/spdy/-/spdy-4.0.0.tgz", + "integrity": "sha512-ot0oEGT/PGUpzf/6uk4AWLqkq+irlqHXkrdbk51oWONh3bxQmBuljxPNl66zlRRcIJStWq0QkLUCPOPjgjvU0Q==", + "dev": true, + "requires": { + "debug": "^4.1.0", + "handle-thing": "^2.0.0", + "http-deceiver": "^1.2.7", + "select-hose": "^2.0.0", + "spdy-transport": "^3.0.0" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "spdy-transport": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdy-transport/-/spdy-transport-3.0.0.tgz", + "integrity": "sha512-hsLVFE5SjA6TCisWeJXFKniGGOpBgMLmerfO2aCyCU5s7nJ/rpAepqmFifv/GCbSbueEeAJJnmSQ2rKC/g8Fcw==", + "dev": true, + "requires": { + "debug": "^4.1.0", + "detect-node": "^2.0.4", + "hpack.js": "^2.1.6", + "obuf": "^1.1.2", + "readable-stream": "^3.0.6", + "wbuf": "^1.7.3" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "readable-stream": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.4.0.tgz", + "integrity": "sha512-jItXPLmrSR8jmTRmRWJXCnGJsfy85mB3Wd/uINMXA65yrnFo0cPClFIUWzo2najVNSl+mx7/4W8ttlLWJe99pQ==", + "dev": true, + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + } + } + }, + "speedometer": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/speedometer/-/speedometer-0.1.4.tgz", + "integrity": "sha1-mHbb0qFp0xFUAtSObqYynIgWpQ0=", + "dev": true + }, + "split-array-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/split-array-stream/-/split-array-stream-2.0.0.tgz", + "integrity": "sha512-hmMswlVY91WvGMxs0k8MRgq8zb2mSen4FmDNc5AFiTWtrBpdZN6nwD6kROVe4vNL+ywrvbCKsWVCnEd4riELIg==", + "requires": { + "is-stream-ended": "^0.1.4" + } + }, + "split-string": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", + "integrity": "sha1-fLCd2jqGWFcFxks5pkZgOGguj+I=", + "dev": true, + "requires": { + "extend-shallow": "^3.0.0" + } + }, + "split2": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-2.2.0.tgz", + "integrity": "sha512-RAb22TG39LhI31MbreBgIuKiIKhVsawfTgEGqKHTK87aG+ul/PB8Sqoi3I7kVdRWiCfrKxK3uo4/YUkpNvhPbw==", + "dev": true, + "requires": { + "through2": "^2.0.2" + }, + "dependencies": { + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "sprintf-js": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.2.tgz", + "integrity": "sha512-VE0SOVEHCk7Qc8ulkWw3ntAzXuqf7S2lvwQaDLRnUeIEaKNQJzV6BwmLKhOqT61aGhfUMrXeaBk+oDGCzvhcug==" + }, + "sqlstring": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz", + "integrity": "sha1-R1OT/56RR5rqYtyvDKPRSYOn+0A=" + }, + "sse": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/sse/-/sse-0.0.8.tgz", + "integrity": "sha512-cviG7JH31TUhZeaEVhac3zTzA+2FwA7qvHziAHpb7mC7RNVJ/RbHN+6LIGsS2ugP4o2H15DWmrSMK+91CboIcg==", + "requires": { + "options": "0.0.6" + } + }, + "sshpk": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", + "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", + "requires": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + } + }, + "ssri": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-6.0.1.tgz", + "integrity": "sha512-3Wge10hNcT1Kur4PDFwEieXSCMCJs/7WvSACcrMYrNp+b8kDL1/0wJch5Ni2WrtwEa2IO8OsVfeKIciKCDx/QA==", + "dev": true, + "requires": { + "figgy-pudding": "^3.5.1" + } + }, + "stable": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.8.tgz", + "integrity": "sha512-ji9qxRnOVfcuLDySj9qzhGSEFVobyt1kIOSkj1qZzYLzq7Tos/oUUWvotUPQLlrsidqsK6tBH89Bc9kL5zHA6w==" + }, + "stack-chain": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/stack-chain/-/stack-chain-1.3.7.tgz", + "integrity": "sha1-0ZLJ/06moiyUxN1FkXHj8AzqEoU=" + }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", + "dev": true + }, + "stack-utils": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-1.0.2.tgz", + "integrity": "sha512-MTX+MeG5U994cazkjd/9KNAapsHnibjMLnfXodlkXw76JEea0UiNzrqidzo1emMwk7w5Qhc9jd4Bn9TBb1MFwA==", + "dev": true + }, + "static-extend": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", + "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", + "dev": true, + "requires": { + "define-property": "^0.2.5", + "object-copy": "^0.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=" + }, + "stdout-stream": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/stdout-stream/-/stdout-stream-1.4.1.tgz", + "integrity": "sha512-j4emi03KXqJWcIeF8eIXkjMFN1Cmb8gUlDYGeBALLPo5qdyTfA9bOtl8m33lRoC+vFMkP3gl0WsDr6+gzxbbTA==", + "dev": true, + "requires": { + "readable-stream": "^2.0.1" + } + }, + "stealthy-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/stealthy-require/-/stealthy-require-1.1.1.tgz", + "integrity": "sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=" + }, + "stream-browserify": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.2.tgz", + "integrity": "sha512-nX6hmklHs/gr2FuxYDltq8fJA1GDlxKQCz8O/IM4atRqBH8OORmBNgfvW5gG10GT/qQ9u0CzIvr2X5Pkt6ntqg==", + "dev": true, + "requires": { + "inherits": "~2.0.1", + "readable-stream": "^2.0.2" + } + }, + "stream-combiner": { + "version": "0.0.2", + "resolved": "http://registry.npmjs.org/stream-combiner/-/stream-combiner-0.0.2.tgz", + "integrity": "sha1-3+DnRnV0JWXnbGBWeI6lwjvZfbQ=", + "requires": { + "duplexer": "~0.0.3" + } + }, + "stream-each": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/stream-each/-/stream-each-1.2.3.tgz", + "integrity": "sha512-vlMC2f8I2u/bZGqkdfLQW/13Zihpej/7PmSiMQsbYddxuTsJp8vRe2x2FvVExZg7FaOds43ROAuFJwPR4MTZLw==", + "dev": true, + "requires": { + "end-of-stream": "^1.1.0", + "stream-shift": "^1.0.0" + } + }, + "stream-events": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/stream-events/-/stream-events-1.0.5.tgz", + "integrity": "sha512-E1GUzBSgvct8Jsb3v2X15pjzN1tYebtbLaMg+eBOUOAxgbLoSbT2NS91ckc5lJD1KfLjId+jXJRgo0qnV5Nerg==", + "requires": { + "stubs": "^3.0.0" + } + }, + "stream-exhaust": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/stream-exhaust/-/stream-exhaust-1.0.2.tgz", + "integrity": "sha512-b/qaq/GlBK5xaq1yrK9/zFcyRSTNxmcZwFLGSTG0mXgZl/4Z6GgiyYOXOvY7N3eEvFRAG1bkDRz5EPGSvPYQlw==", + "dev": true + }, + "stream-http": { + "version": "2.8.3", + "resolved": "https://registry.npmjs.org/stream-http/-/stream-http-2.8.3.tgz", + "integrity": "sha512-+TSkfINHDo4J+ZobQLWiMouQYB+UVYFttRA94FpEzzJ7ZdqcL4uUUQ7WkdkI4DSozGmgBUE/a47L+38PenXhUw==", + "dev": true, + "requires": { + "builtin-status-codes": "^3.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.3.6", + "to-arraybuffer": "^1.0.0", + "xtend": "^4.0.0" + }, + "dependencies": { + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "stream-serializer": { + "version": "1.1.2", + "resolved": "http://registry.npmjs.org/stream-serializer/-/stream-serializer-1.1.2.tgz", + "integrity": "sha1-wfl9FdolH1lK4n1B7IraCahG408=" + }, + "stream-shift": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.0.tgz", + "integrity": "sha1-1cdSgl5TZ+eG944Y5EXqIjoVWVI=" + }, + "string-length": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-2.0.0.tgz", + "integrity": "sha1-1A27aGo6zpYMHP/KVivyxF+DY+0=", + "dev": true, + "requires": { + "astral-regex": "^1.0.0", + "strip-ansi": "^4.0.0" + } + }, + "string-width": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "dev": true, + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + } + }, + "strip-bom": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-0.3.1.tgz", + "integrity": "sha1-noo57/RW/5q8LwWfXyIluw8/fKU=", + "requires": { + "first-chunk-stream": "^0.1.0", + "is-utf8": "^0.2.0" + } + }, + "strip-eof": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=" + }, + "strip-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-1.0.1.tgz", + "integrity": "sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI=", + "dev": true, + "requires": { + "get-stdin": "^4.0.1" + } + }, + "strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", + "dev": true + }, + "strong-error-handler": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/strong-error-handler/-/strong-error-handler-2.3.2.tgz", + "integrity": "sha512-MT68SXVUPB1MNKEkIOUEgKOUCXWf3QV3TmgQRxJHyVplV/IbKFW/60UhAapViDt18cwr1XmgrNbtZ/2cF2qKdg==", + "requires": { + "accepts": "^1.3.3", + "debug": "^2.2.0", + "ejs": "^2.5.7", + "http-status": "^1.0.0", + "js2xmlparser": "^3.0.0", + "strong-globalize": "^3.1.0" + }, + "dependencies": { + "async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", + "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", + "requires": { + "lodash": "^4.17.11" + } + }, + "cross-spawn": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-5.1.0.tgz", + "integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=", + "requires": { + "lru-cache": "^4.0.1", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "execa": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-0.7.0.tgz", + "integrity": "sha1-lEvs00zEHuMqY6n68nrVpl/Fl3c=", + "requires": { + "cross-spawn": "^5.0.1", + "get-stream": "^3.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + } + }, + "get-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz", + "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=" + }, + "invert-kv": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz", + "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=" + }, + "lcid": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz", + "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", + "requires": { + "invert-kv": "^1.0.0" + } + }, + "lru-cache": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", + "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "mem": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/mem/-/mem-1.1.0.tgz", + "integrity": "sha1-Xt1StIXKHZAP5kiVUFOZoN+kX3Y=", + "requires": { + "mimic-fn": "^1.0.0" + } + }, + "mimic-fn": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", + "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==" + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "os-locale": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-2.1.0.tgz", + "integrity": "sha512-3sslG3zJbEYcaC4YVAvDorjGxc7tv6KVATnLPZONiljsUncvihe9BQoVCEs0RZ1kmf4Hk9OBqlZfJZWI4GanKA==", + "requires": { + "execa": "^0.7.0", + "lcid": "^1.0.0", + "mem": "^1.1.0" + } + }, + "strong-globalize": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/strong-globalize/-/strong-globalize-3.3.0.tgz", + "integrity": "sha512-WrCZPABG/c4e55aH9S1mIW4054YL492cFwJFoF1WZZsJQ39gBYgGjdccTYI5Kj6uTlXH5hjepCQfwE5gCHJnKQ==", + "requires": { + "accept-language": "^3.0.18", + "async": "^2.4.1", + "debug": "^3.1.0", + "esprima": "^4.0.0", + "estraverse": "^4.2.0", + "g11n-pipeline": "^2.0.1", + "globalize": "^1.3.0", + "htmlparser2": "^3.9.2", + "lodash": "^4.17.4", + "md5": "^2.2.1", + "mkdirp": "^0.5.1", + "mktmpdir": "^0.1.1", + "optional": "^0.1.3", + "os-locale": "^2.0.0", + "posix-getopt": "^1.2.0", + "word-count": "^0.2.2", + "xtend": "^4.0.1", + "yamljs": "^0.3.0" + }, + "dependencies": { + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + } + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=" + }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=" + } + } + }, + "strong-globalize": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/strong-globalize/-/strong-globalize-4.1.3.tgz", + "integrity": "sha512-SJegV7w5D4AodEspZJtJ7rls3fmi+Zc0PdyJCqBsg4RN9B8TC80/uAI2fikC+s1Jp9FLvr2vDX8f0Fqc62M4OA==", + "requires": { + "accept-language": "^3.0.18", + "debug": "^4.1.1", + "globalize": "^1.4.2", + "lodash": "^4.17.4", + "md5": "^2.2.1", + "mkdirp": "^0.5.1", + "os-locale": "^3.1.0", + "yamljs": "^0.3.0" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "strong-remoting": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/strong-remoting/-/strong-remoting-3.14.0.tgz", + "integrity": "sha512-kBOVMBIGW8fCv37G8uyvxBLO+ed0mF9z+gulAgOZfdIXWa0AgXhndpjTqAWvde+2iXt/n6odiyYvCUbXCrfBsQ==", + "requires": { + "async": "^2.0.1", + "body-parser": "^1.12.4", + "debug": "^3.1.0", + "depd": "^1.1.0", + "escape-string-regexp": "^1.0.5", + "eventemitter2": "^5.0.1", + "express": "4.x", + "inflection": "^1.7.1", + "jayson": "^2.0.5", + "js2xmlparser": "^3.0.0", + "loopback-datatype-geopoint": "^1.0.0", + "loopback-phase": "^3.1.0", + "mux-demux": "^3.7.9", + "qs": "^6.2.1", + "request": "^2.83.0", + "sse": "0.0.8", + "strong-error-handler": "^3.0.0", + "strong-globalize": "^4.1.0", + "traverse": "^0.6.6", + "xml2js": "^0.4.8" + }, + "dependencies": { + "async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", + "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", + "requires": { + "lodash": "^4.17.11" + } + }, + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "strong-error-handler": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/strong-error-handler/-/strong-error-handler-3.2.0.tgz", + "integrity": "sha512-WBU5itMkVPoEPf1W3ptb0AjtPvRWabDzVO4Lcy8MbJQUbo8vdWngLAcNQptQovdFoMGLgQAgJzZkelm6FRADuQ==", + "requires": { + "@types/express": "^4.16.0", + "accepts": "^1.3.3", + "debug": "^3.1.0", + "ejs": "^2.6.1", + "http-status": "^1.1.2", + "js2xmlparser": "^3.0.0", + "strong-globalize": "^4.1.0" + } + } + } + }, + "stubs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/stubs/-/stubs-3.0.0.tgz", + "integrity": "sha1-6NK6H6nJBXAwPAMLaQD31fiavls=" + }, + "style-loader": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/style-loader/-/style-loader-0.23.1.tgz", + "integrity": "sha512-XK+uv9kWwhZMZ1y7mysB+zoihsEj4wneFWAS5qoiLwzW0WzSqMrrsIy+a3zkQJq0ipFtBpX5W3MqyRIBF/WFGg==", + "dev": true, + "requires": { + "loader-utils": "^1.1.0", + "schema-utils": "^1.0.0" + } + }, + "sumchecker": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.0.tgz", + "integrity": "sha512-yreseuC/z4iaodVoq07XULEOO9p4jnQazO7mbrnDSvWAU/y2cbyIKs+gWJptfcGu9R+1l27K8Rkj0bfvqnBpgQ==", + "requires": { + "debug": "^4.1.0" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "supports-color": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-1.2.0.tgz", + "integrity": "sha1-/x7R5hFp0Gs88tWI4YixjYhH4X4=" + }, + "sver-compat": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/sver-compat/-/sver-compat-1.5.0.tgz", + "integrity": "sha1-PPh9/rTQe0o/FIJ7wYaz/QxkXNg=", + "dev": true, + "requires": { + "es6-iterator": "^2.0.1", + "es6-symbol": "^3.1.1" + } + }, + "swagger-client": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/swagger-client/-/swagger-client-3.9.0.tgz", + "integrity": "sha512-uyCq2xoaAtmE0oIQ0fCfnsDoy/v97ANnAZywtyk4yumBP74xXp4NFlpZaqZJHN9K9dbPzgs3MH98VocZeM0ExQ==", + "requires": { + "@kyleshockey/js-yaml": "^1.0.1", + "@kyleshockey/object-assign-deep": "^0.4.0", + "babel-runtime": "^6.26.0", + "btoa": "1.1.2", + "buffer": "^5.1.0", + "cookie": "^0.3.1", + "cross-fetch": "0.0.8", + "deep-extend": "^0.5.1", + "encode-3986": "^1.0.0", + "fast-json-patch": "^2.0.6", + "isomorphic-form-data": "0.0.1", + "lodash": "^4.16.2", + "qs": "^6.3.0", + "querystring-browser": "^1.0.4", + "traverse": "^0.6.6", + "url": "^0.11.0", + "utf8-bytes": "0.0.1", + "utfstring": "^2.0.0" + }, + "dependencies": { + "@kyleshockey/js-yaml": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@kyleshockey/js-yaml/-/js-yaml-1.0.1.tgz", + "integrity": "sha512-coFyIk1LvTscq1cUU4nCCfYwv+cmG4fCP+wgDKgYZjhM4f++YwZy+g0k+1tUqa4GuUpBTEOGH2KUqKFFWdT73g==", + "requires": { + "argparse": "^1.0.7" + } + }, + "buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.2.1.tgz", + "integrity": "sha512-c+Ko0loDaFfuPWiL02ls9Xd3GO3cPVmUobQ6t3rXNUk304u6hGq+8N/kFi+QEIKhzK3uwolVhLzszmfLmMLnqg==", + "requires": { + "base64-js": "^1.0.2", + "ieee754": "^1.1.4" + } + }, + "cookie": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz", + "integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=" + }, + "punycode": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", + "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=" + }, + "url": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", + "integrity": "sha1-ODjpfPxgUh63PFJajlW/3Z4uKPE=", + "requires": { + "punycode": "1.3.2", + "querystring": "0.2.0" + } + } + } + }, + "swagger-ui": { + "version": "2.2.10", + "resolved": "https://registry.npmjs.org/swagger-ui/-/swagger-ui-2.2.10.tgz", + "integrity": "sha1-sl56IWZOXZC/OR2zDbCN5B6FLXs=" + }, + "symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true + }, + "table": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/table/-/table-5.4.1.tgz", + "integrity": "sha512-E6CK1/pZe2N75rGZQotFOdmzWQ1AILtgYbMAbAjvms0S1l5IDB47zG3nCnFGB/w+7nB3vKofbLXCH7HPBo864w==", + "dev": true, + "requires": { + "ajv": "^6.9.1", + "lodash": "^4.17.11", + "slice-ansi": "^2.1.0", + "string-width": "^3.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true + }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + } + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" + } + } + } + }, + "tapable": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-1.1.3.tgz", + "integrity": "sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA==", + "dev": true + }, + "tar": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/tar/-/tar-2.2.2.tgz", + "integrity": "sha512-FCEhQ/4rE1zYv9rYXJw/msRqsnmlje5jHP6huWeBZ704jUTy02c5AZyWujpMR1ax6mVw9NyJMfuK2CMDWVIfgA==", + "dev": true, + "requires": { + "block-stream": "*", + "fstream": "^1.0.12", + "inherits": "2" + } + }, + "taskgroup": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/taskgroup/-/taskgroup-4.3.1.tgz", + "integrity": "sha1-feGT/r12gnPEV3MElwJNUSwnkVo=", + "requires": { + "ambi": "^2.2.0", + "csextends": "^1.0.3" + } + }, + "teeny-request": { + "version": "3.11.3", + "resolved": "https://registry.npmjs.org/teeny-request/-/teeny-request-3.11.3.tgz", + "integrity": "sha512-CKncqSF7sH6p4rzCgkb/z/Pcos5efl0DmolzvlqRQUNcpRIruOhY9+T1FsIlyEbfWd7MsFpodROOwHYh2BaXzw==", + "requires": { + "https-proxy-agent": "^2.2.1", + "node-fetch": "^2.2.0", + "uuid": "^3.3.2" + } + }, + "term-size": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/term-size/-/term-size-1.2.0.tgz", + "integrity": "sha1-RYuDiH8oj8Vtb/+/rSYuJmOO+mk=", + "dev": true, + "requires": { + "execa": "^0.7.0" + }, + "dependencies": { + "cross-spawn": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-5.1.0.tgz", + "integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=", + "dev": true, + "requires": { + "lru-cache": "^4.0.1", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "execa": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-0.7.0.tgz", + "integrity": "sha1-lEvs00zEHuMqY6n68nrVpl/Fl3c=", + "dev": true, + "requires": { + "cross-spawn": "^5.0.1", + "get-stream": "^3.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + } + }, + "get-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz", + "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=", + "dev": true + }, + "lru-cache": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", + "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", + "dev": true, + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", + "dev": true + } + } + }, + "terser": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/terser/-/terser-4.0.2.tgz", + "integrity": "sha512-IWLuJqTvx97KP3uTYkFVn93cXO+EtlzJu8TdJylq+H0VBDlPMIfQA9MBS5Vc5t3xTEUG1q0hIfHMpAP2R+gWTw==", + "dev": true, + "requires": { + "commander": "^2.19.0", + "source-map": "~0.6.1", + "source-map-support": "~0.5.10" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "terser-webpack-plugin": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-1.3.0.tgz", + "integrity": "sha512-W2YWmxPjjkUcOWa4pBEv4OP4er1aeQJlSo2UhtCFQCuRXEHjOFscO8VyWHj9JLlA0RzQb8Y2/Ta78XZvT54uGg==", + "dev": true, + "requires": { + "cacache": "^11.3.2", + "find-cache-dir": "^2.0.0", + "is-wsl": "^1.1.0", + "loader-utils": "^1.2.3", + "schema-utils": "^1.0.0", + "serialize-javascript": "^1.7.0", + "source-map": "^0.6.1", + "terser": "^4.0.0", + "webpack-sources": "^1.3.0", + "worker-farm": "^1.7.0" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "test-exclude": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-5.2.3.tgz", + "integrity": "sha512-M+oxtseCFO3EDtAaGH7iiej3CBkzXqFMbzqYAACdzKui4eZA+pq3tZEwChvOdNfa7xxy8BfbmgJSIr43cC/+2g==", + "dev": true, + "requires": { + "glob": "^7.1.3", + "minimatch": "^3.0.4", + "read-pkg-up": "^4.0.0", + "require-main-filename": "^2.0.0" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "load-json-file": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", + "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^4.0.0", + "pify": "^3.0.0", + "strip-bom": "^3.0.0" + } + }, + "parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", + "dev": true, + "requires": { + "error-ex": "^1.3.1", + "json-parse-better-errors": "^1.0.1" + } + }, + "path-type": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", + "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", + "dev": true, + "requires": { + "pify": "^3.0.0" + } + }, + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true + }, + "read-pkg": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", + "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", + "dev": true, + "requires": { + "load-json-file": "^4.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^3.0.0" + } + }, + "read-pkg-up": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-4.0.0.tgz", + "integrity": "sha512-6etQSH7nJGsK0RbG/2TeDzZFa8shjQ1um+SwQQ5cwKy0dhSXdOncEhb1CPpvQG4h7FyOV6EB6YlV0yJvZQNAkA==", + "dev": true, + "requires": { + "find-up": "^3.0.0", + "read-pkg": "^3.0.0" + } + }, + "require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "dev": true + }, + "strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "dev": true + } + } + }, + "text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", + "dev": true + }, + "throat": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/throat/-/throat-4.1.0.tgz", + "integrity": "sha1-iQN8vJLFarGJJua6TLsgDhVnKmo=", + "dev": true + }, + "throttleit": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/throttleit/-/throttleit-0.0.2.tgz", + "integrity": "sha1-z+34jmDADdlpe2H90qg0OptoDq8=", + "dev": true + }, + "through": { + "version": "2.3.8", + "resolved": "http://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=" + }, + "through2": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/through2/-/through2-3.0.1.tgz", + "integrity": "sha512-M96dvTalPT3YbYLaKaCuwu+j06D/8Jfib0o/PxbVt6Amhv3dUAtW6rTV1jPgJSBG83I/e04Y6xkVdVhSRhi0ww==", + "requires": { + "readable-stream": "2 || 3" + } + }, + "through2-filter": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/through2-filter/-/through2-filter-3.0.0.tgz", + "integrity": "sha512-jaRjI2WxN3W1V8/FMZ9HKIBXixtiqs3SQSX4/YGIiP3gL6djW48VoZq9tDqeCWs3MT8YY5wb/zli8VW8snY1CA==", + "dev": true, + "requires": { + "through2": "~2.0.0", + "xtend": "~4.0.0" + }, + "dependencies": { + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "thunky": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.0.3.tgz", + "integrity": "sha512-YwT8pjmNcAXBZqrubu22P4FYsh2D4dxRmnWBOL8Jk8bUcRUtc5326kx32tuTmFDAZtLOGEVNl8POAR8j896Iow==", + "dev": true + }, + "time-stamp": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/time-stamp/-/time-stamp-1.1.0.tgz", + "integrity": "sha1-dkpaEa9QVhkhsTPztE5hhofg9cM=", + "dev": true + }, + "timed-out": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/timed-out/-/timed-out-4.0.1.tgz", + "integrity": "sha1-8y6srFoXW+ol1/q1Zas+2HQe9W8=", + "dev": true + }, + "timers-browserify": { + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-2.0.10.tgz", + "integrity": "sha512-YvC1SV1XdOUaL6gx5CoGroT3Gu49pK9+TZ38ErPldOWW4j49GI1HKs9DV+KGq/w6y+LZ72W1c8cKz2vzY+qpzg==", + "dev": true, + "requires": { + "setimmediate": "^1.0.4" + } + }, + "tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "requires": { + "os-tmpdir": "~1.0.2" + } + }, + "tmpl": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.4.tgz", + "integrity": "sha1-I2QN17QtAEM5ERQIIOXPRA5SHdE=", + "dev": true + }, + "to-absolute-glob": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/to-absolute-glob/-/to-absolute-glob-2.0.2.tgz", + "integrity": "sha1-GGX0PZ50sIItufFFt4z/fQ98hJs=", + "dev": true, + "requires": { + "is-absolute": "^1.0.0", + "is-negated-glob": "^1.0.0" + } + }, + "to-arraybuffer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz", + "integrity": "sha1-fSKbH8xjfkZsoIEYCDanqr/4P0M=", + "dev": true + }, + "to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", + "dev": true + }, + "to-iso-string": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/to-iso-string/-/to-iso-string-0.0.2.tgz", + "integrity": "sha1-TcGeZk38y+Jb2NtQiwDG2hWCVdE=" + }, + "to-object-path": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", + "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "to-readable-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/to-readable-stream/-/to-readable-stream-1.0.0.tgz", + "integrity": "sha512-Iq25XBt6zD5npPhlLVXGFN3/gyR2/qODcKNNyTMd4vbm39HUaOiAM4PMq0eMVC/Tkxz+Zjdsc55g9yyz+Yq00Q==" + }, + "to-regex": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.2.tgz", + "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==", + "dev": true, + "requires": { + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "regex-not": "^1.0.2", + "safe-regex": "^1.1.0" + } + }, + "to-regex-range": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz", + "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "repeat-string": "^1.6.1" + } + }, + "to-through": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-through/-/to-through-2.0.0.tgz", + "integrity": "sha1-/JKtq6ByZHvAtn1rA2ZKoZUJOvY=", + "dev": true, + "requires": { + "through2": "^2.0.3" + }, + "dependencies": { + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "to-utf8": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/to-utf8/-/to-utf8-0.0.1.tgz", + "integrity": "sha1-0Xrqcv8vujm55DYBvns/9y4ImFI=" + }, + "toidentifier": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", + "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==" + }, + "toposort": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/toposort/-/toposort-2.0.2.tgz", + "integrity": "sha1-riF2gXXRVZ1IvvNUILL0li8JwzA=" + }, + "touch": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.0.tgz", + "integrity": "sha1-/jZfX3XsntTlaCXgu3bSSrdK+Ds=", + "dev": true, + "requires": { + "nopt": "~1.0.10" + }, + "dependencies": { + "nopt": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz", + "integrity": "sha1-bd0hvSoxQXuScn3Vhfim83YI6+4=", + "dev": true, + "requires": { + "abbrev": "1" + } + } + } + }, + "tough-cookie": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.4.3.tgz", + "integrity": "sha512-Q5srk/4vDM54WJsJio3XNn6K2sCG+CQ8G5Wz6bZhRZoAe/+TxjWB/GlFAnYEbkYVlON9FMk/fE3h2RLpPXo4lQ==", + "requires": { + "psl": "^1.1.24", + "punycode": "^1.4.1" + }, + "dependencies": { + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=" + } + } + }, + "tr46": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-1.0.1.tgz", + "integrity": "sha1-qLE/1r/SSJUZZ0zN5VujaTtwbQk=", + "dev": true, + "requires": { + "punycode": "^2.1.0" + } + }, + "traverse": { + "version": "0.6.6", + "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.6.6.tgz", + "integrity": "sha1-y99WD9e5r2MlAv7UD5GMFX6pcTc=" + }, + "trim-newlines": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-1.0.0.tgz", + "integrity": "sha1-WIeWa7WCpFA6QetST301ARgVphM=", + "dev": true + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "true-case-path": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/true-case-path/-/true-case-path-1.0.3.tgz", + "integrity": "sha512-m6s2OdQe5wgpFMC+pAJ+q9djG82O2jcHPOI6RNg1yy9rCYR+WD6Nbpl32fDpfC56nirdRy+opFa/Vk7HYhqaew==", + "dev": true, + "requires": { + "glob": "^7.1.2" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + } + } + }, + "truncate-utf8-bytes": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/truncate-utf8-bytes/-/truncate-utf8-bytes-1.0.2.tgz", + "integrity": "sha1-QFkjkJWS1W94pYGENLC3hInKXys=", + "requires": { + "utf8-byte-length": "^1.0.1" + } + }, + "tryit": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tryit/-/tryit-1.0.3.tgz", + "integrity": "sha1-OTvnMKlEb9Hq1tpZoBQwjzbCics=", + "dev": true + }, + "tslib": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.10.0.tgz", + "integrity": "sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ==", + "dev": true + }, + "tty-browserify": { + "version": "0.0.0", + "resolved": "http://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", + "integrity": "sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=", + "dev": true + }, + "tunnel": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz", + "integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==", + "optional": true + }, + "tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=" + }, + "type": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/type/-/type-1.0.1.tgz", + "integrity": "sha512-MAM5dBMJCJNKs9E7JXo4CXRAansRfG0nlJxW7Wf6GZzSOvH31zClSaHdIMWLehe/EGMBkqeC55rrkaOr5Oo7Nw==", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2" + } + }, + "type-fest": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", + "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", + "optional": true + }, + "type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "requires": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + } + }, + "typechecker": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/typechecker/-/typechecker-2.1.0.tgz", + "integrity": "sha1-0cIJOlT/ihn1jP+HfuqlTyJC04M=" + }, + "typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=" + }, + "uglify-js": { + "version": "3.4.10", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.4.10.tgz", + "integrity": "sha512-Y2VsbPVs0FIshJztycsO2SfPk7/KAF/T72qzv9u5EpQ4kB2hQoHlhNQTsNyy6ul7lQtqJN/AoWeS23OzEiEFxw==", + "dev": true, + "requires": { + "commander": "~2.19.0", + "source-map": "~0.6.1" + }, + "dependencies": { + "commander": { + "version": "2.19.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", + "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "uid2": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/uid2/-/uid2-0.0.3.tgz", + "integrity": "sha1-SDEm4Rd03y9xuLY53NeZw3YWK4I=" + }, + "unc-path-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/unc-path-regex/-/unc-path-regex-0.1.2.tgz", + "integrity": "sha1-5z3T17DXxe2G+6xrCufYxqadUPo=", + "dev": true + }, + "undefsafe": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.2.tgz", + "integrity": "sha1-Il9rngM3Zj4Njnz9aG/Cg2zKznY=", + "dev": true, + "requires": { + "debug": "^2.2.0" + } + }, + "underscore": { + "version": "1.7.0", + "resolved": "http://registry.npmjs.org/underscore/-/underscore-1.7.0.tgz", + "integrity": "sha1-a7rwh3UA02vjTsqlhODbn+8DUgk=" + }, + "underscore.string": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/underscore.string/-/underscore.string-3.3.5.tgz", + "integrity": "sha512-g+dpmgn+XBneLmXXo+sGlW5xQEt4ErkS3mgeN2GFbremYeMBSJKr9Wf2KJplQVaiPY/f7FN6atosWYNm9ovrYg==", + "requires": { + "sprintf-js": "^1.0.3", + "util-deprecate": "^1.0.2" + } + }, + "undertaker": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/undertaker/-/undertaker-1.2.1.tgz", + "integrity": "sha512-71WxIzDkgYk9ZS+spIB8iZXchFhAdEo2YU8xYqBYJ39DIUIqziK78ftm26eecoIY49X0J2MLhG4hr18Yp6/CMA==", + "dev": true, + "requires": { + "arr-flatten": "^1.0.1", + "arr-map": "^2.0.0", + "bach": "^1.0.0", + "collection-map": "^1.0.0", + "es6-weak-map": "^2.0.1", + "last-run": "^1.1.0", + "object.defaults": "^1.0.0", + "object.reduce": "^1.0.0", + "undertaker-registry": "^1.0.0" + } + }, + "undertaker-registry": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/undertaker-registry/-/undertaker-registry-1.0.1.tgz", + "integrity": "sha1-XkvaMI5KiirlhPm5pDWaSZglzFA=", + "dev": true + }, + "unicode-canonical-property-names-ecmascript": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-1.0.4.tgz", + "integrity": "sha512-jDrNnXWHd4oHiTZnx/ZG7gtUTVp+gCcTTKr8L0HjlwphROEW3+Him+IpvC+xcJEFegapiMZyZe02CyuOnRmbnQ==", + "dev": true + }, + "unicode-match-property-ecmascript": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-1.0.4.tgz", + "integrity": "sha512-L4Qoh15vTfntsn4P1zqnHulG0LdXgjSO035fEpdtp6YxXhMT51Q6vgM5lYdG/5X3MjS+k/Y9Xw4SFCY9IkR0rg==", + "dev": true, + "requires": { + "unicode-canonical-property-names-ecmascript": "^1.0.4", + "unicode-property-aliases-ecmascript": "^1.0.4" + } + }, + "unicode-match-property-value-ecmascript": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-1.1.0.tgz", + "integrity": "sha512-hDTHvaBk3RmFzvSl0UVrUmC3PuW9wKVnpoUDYH0JDkSIovzw+J5viQmeYHxVSBptubnr7PbH2e0fnpDRQnQl5g==", + "dev": true + }, + "unicode-property-aliases-ecmascript": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-1.0.5.tgz", + "integrity": "sha512-L5RAqCfXqAwR3RriF8pM0lU0w4Ryf/GgzONwi6KnL1taJQa7x1TCxdJnILX59WIGOwR57IVxn7Nej0fz1Ny6fw==", + "dev": true + }, + "union-value": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz", + "integrity": "sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg==", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "get-value": "^2.0.6", + "is-extendable": "^0.1.1", + "set-value": "^2.0.1" + } + }, + "uniq": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/uniq/-/uniq-1.0.1.tgz", + "integrity": "sha1-sxxa6CVIRKOoKBVBzisEuGWnNP8=", + "dev": true + }, + "unique-filename": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-1.1.1.tgz", + "integrity": "sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==", + "dev": true, + "requires": { + "unique-slug": "^2.0.0" + } + }, + "unique-slug": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.2.tgz", + "integrity": "sha512-zoWr9ObaxALD3DOPfjPSqxt4fnZiWblxHIgeWqW8x7UqDzEtHEQLzji2cuJYQFCU6KmoJikOYAZlrTHHebjx2w==", + "dev": true, + "requires": { + "imurmurhash": "^0.1.4" + } + }, + "unique-stream": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/unique-stream/-/unique-stream-2.3.1.tgz", + "integrity": "sha512-2nY4TnBE70yoxHkDli7DMazpWiP7xMdCYqU2nBRO0UB+ZpEkGsSija7MvmvnZFUeC+mrgiUfcHSr3LmRFIg4+A==", + "dev": true, + "requires": { + "json-stable-stringify-without-jsonify": "^1.0.1", + "through2-filter": "^3.0.0" + } + }, + "unique-string": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-1.0.0.tgz", + "integrity": "sha1-nhBXzKhRq7kzmPizOuGHuZyuwRo=", + "requires": { + "crypto-random-string": "^1.0.0" + } + }, + "universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==" + }, + "unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=" + }, + "unset-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", + "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", + "dev": true, + "requires": { + "has-value": "^0.3.1", + "isobject": "^3.0.0" + }, + "dependencies": { + "has-value": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz", + "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", + "dev": true, + "requires": { + "get-value": "^2.0.3", + "has-values": "^0.1.4", + "isobject": "^2.0.0" + }, + "dependencies": { + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "dev": true, + "requires": { + "isarray": "1.0.0" + } + } + } + }, + "has-values": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", + "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", + "dev": true + } + } + }, + "unzip-response": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/unzip-response/-/unzip-response-2.0.1.tgz", + "integrity": "sha1-0vD3N9FrBhXnKmk17QQhRXLVb5c=", + "dev": true + }, + "upath": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/upath/-/upath-1.1.2.tgz", + "integrity": "sha512-kXpym8nmDmlCBr7nKdIx8P2jNBa+pBpIUFRnKJ4dr8htyYGJFokkr2ZvERRtUN+9SY+JqXouNgUPtv6JQva/2Q==", + "dev": true + }, + "update-notifier": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/update-notifier/-/update-notifier-2.5.0.tgz", + "integrity": "sha512-gwMdhgJHGuj/+wHJJs9e6PcCszpxR1b236igrOkUofGhqJuG+amlIKwApH1IW1WWl7ovZxsX49lMBWLxSdm5Dw==", + "dev": true, + "requires": { + "boxen": "^1.2.1", + "chalk": "^2.0.1", + "configstore": "^3.0.0", + "import-lazy": "^2.1.0", + "is-ci": "^1.0.10", + "is-installed-globally": "^0.1.0", + "is-npm": "^1.0.0", + "latest-version": "^3.0.0", + "semver-diff": "^2.0.0", + "xdg-basedir": "^3.0.0" + }, + "dependencies": { + "configstore": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/configstore/-/configstore-3.1.2.tgz", + "integrity": "sha512-vtv5HtGjcYUgFrXc6Kx747B83MRRVS5R1VTEQoXvuP+kMI+if6uywV0nDGoiydJRy4yk7h9od5Og0kxx4zUXmw==", + "dev": true, + "requires": { + "dot-prop": "^4.1.0", + "graceful-fs": "^4.1.2", + "make-dir": "^1.0.0", + "unique-string": "^1.0.0", + "write-file-atomic": "^2.0.0", + "xdg-basedir": "^3.0.0" + } + } + } + }, + "upper-case": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/upper-case/-/upper-case-1.1.3.tgz", + "integrity": "sha1-9rRQHC7EzdJrp4vnIilh3ndiFZg=", + "dev": true + }, + "uri-js": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", + "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", + "requires": { + "punycode": "^2.1.0" + } + }, + "urix": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", + "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", + "dev": true + }, + "url": { + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/url/-/url-0.10.3.tgz", + "integrity": "sha1-Ah5NnHcF8hu/N9A861h2dAJ3TGQ=", + "requires": { + "punycode": "1.3.2", + "querystring": "0.2.0" + }, + "dependencies": { + "punycode": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", + "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=" + } + } + }, + "url-join": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-4.0.0.tgz", + "integrity": "sha1-TTNA6AfTdzvamZH4MFrNzCpmXSo=" + }, + "url-parse": { + "version": "1.4.7", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.4.7.tgz", + "integrity": "sha512-d3uaVyzDB9tQoSXFvuSUNFibTd9zxd2bkVrDRvF5TmvWWQwqE4lgYJ5m+x1DbecWkw+LK4RNl2CU1hHuOKPVlg==", + "dev": true, + "requires": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, + "url-parse-lax": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-1.0.0.tgz", + "integrity": "sha1-evjzA2Rem9eaJy56FKxovAYJ2nM=", + "dev": true, + "requires": { + "prepend-http": "^1.0.1" + } + }, + "use": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", + "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==", + "dev": true + }, + "utf8-byte-length": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/utf8-byte-length/-/utf8-byte-length-1.0.4.tgz", + "integrity": "sha1-9F8VDExm7uloGGUFq5P8u4rWv2E=" + }, + "utf8-bytes": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/utf8-bytes/-/utf8-bytes-0.0.1.tgz", + "integrity": "sha1-EWsCVEjJtQAIHN+/H01sbDfYg30=" + }, + "utfstring": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/utfstring/-/utfstring-2.0.0.tgz", + "integrity": "sha512-/ugBfyvIoLe9xqkFHio3CxXnpUKQ1p2LfTxPr6QTRj6GiwpHo73YGdh03UmAzDQNOWpNIE0J5nLss00L4xlWgg==" + }, + "util": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/util/-/util-0.11.1.tgz", + "integrity": "sha512-HShAsny+zS2TZfaXxD9tYj4HQGlBezXZMZuM/S5PKLLoZkShZiGk9o5CzukI1LVHZvjdvZ2Sj1aW/Ndn2NB/HQ==", + "dev": true, + "requires": { + "inherits": "2.0.3" + }, + "dependencies": { + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + } + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + }, + "util.promisify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/util.promisify/-/util.promisify-1.0.0.tgz", + "integrity": "sha512-i+6qA2MPhvoKLuxnJNpXAGhg7HphQOSUq2LKMZD0m15EiskXUkMvKdF4Uui0WYeCUGea+o2cw/ZuwehtfsrNkA==", + "dev": true, + "requires": { + "define-properties": "^1.1.2", + "object.getownpropertydescriptors": "^2.0.3" + } + }, + "utila": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/utila/-/utila-0.4.0.tgz", + "integrity": "sha1-ihagXURWV6Oupe7MWxKk+lN5dyw=", + "dev": true + }, + "utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=" + }, + "uuid": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", + "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==" + }, + "v8-compile-cache": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.0.3.tgz", + "integrity": "sha512-CNmdbwQMBjwr9Gsmohvm0pbL954tJrNzf6gWL3K+QMQf00PF7ERGrEiLgjuU3mKreLC2MeGhUsNV9ybTbLgd3w==", + "dev": true + }, + "v8flags": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/v8flags/-/v8flags-3.1.3.tgz", + "integrity": "sha512-amh9CCg3ZxkzQ48Mhcb8iX7xpAfYJgePHxWMQCBWECpOSqJUXgY26ncA61UTV0BkPqfhcy6mzwCIoP4ygxpW8w==", + "dev": true, + "requires": { + "homedir-polyfill": "^1.0.1" + } + }, + "validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dev": true, + "requires": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "value-or-function": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/value-or-function/-/value-or-function-3.0.0.tgz", + "integrity": "sha1-HCQ6ULWVwb5Up1S/7OhWO5/42BM=", + "dev": true + }, + "vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=" + }, + "verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "requires": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "vinyl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-2.2.0.tgz", + "integrity": "sha512-MBH+yP0kC/GQ5GwBqrTPTzEfiiLjta7hTtvQtbxBgTeSXsmKQRQecjibMbxIXzVT3Y9KJK+drOz1/k+vsu8Nkg==", + "dev": true, + "requires": { + "clone": "^2.1.1", + "clone-buffer": "^1.0.0", + "clone-stats": "^1.0.0", + "cloneable-readable": "^1.0.0", + "remove-trailing-separator": "^1.0.1", + "replace-ext": "^1.0.0" + } + }, + "vinyl-bufferstream": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/vinyl-bufferstream/-/vinyl-bufferstream-1.0.1.tgz", + "integrity": "sha1-BTeGn1gO/6TKRay0dXnkuf5jCBo=", + "dev": true, + "requires": { + "bufferstreams": "1.0.1" + } + }, + "vinyl-fs": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/vinyl-fs/-/vinyl-fs-3.0.3.tgz", + "integrity": "sha512-vIu34EkyNyJxmP0jscNzWBSygh7VWhqun6RmqVfXePrOwi9lhvRs//dOaGOTRUQr4tx7/zd26Tk5WeSVZitgng==", + "dev": true, + "requires": { + "fs-mkdirp-stream": "^1.0.0", + "glob-stream": "^6.1.0", + "graceful-fs": "^4.0.0", + "is-valid-glob": "^1.0.0", + "lazystream": "^1.0.0", + "lead": "^1.0.0", + "object.assign": "^4.0.4", + "pumpify": "^1.3.5", + "readable-stream": "^2.3.3", + "remove-bom-buffer": "^3.0.0", + "remove-bom-stream": "^1.2.0", + "resolve-options": "^1.1.0", + "through2": "^2.0.0", + "to-through": "^2.0.0", + "value-or-function": "^3.0.0", + "vinyl": "^2.0.0", + "vinyl-sourcemap": "^1.1.0" + }, + "dependencies": { + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + } + } + }, + "vinyl-sourcemap": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/vinyl-sourcemap/-/vinyl-sourcemap-1.1.0.tgz", + "integrity": "sha1-kqgAWTo4cDqM2xHYswCtS+Y7PhY=", + "dev": true, + "requires": { + "append-buffer": "^1.0.2", + "convert-source-map": "^1.5.0", + "graceful-fs": "^4.1.6", + "normalize-path": "^2.1.1", + "now-and-later": "^2.0.0", + "remove-bom-buffer": "^3.0.0", + "vinyl": "^2.0.0" + }, + "dependencies": { + "normalize-path": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", + "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", + "dev": true, + "requires": { + "remove-trailing-separator": "^1.0.1" + } + } + } + }, + "vm-browserify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.0.tgz", + "integrity": "sha512-iq+S7vZJE60yejDYM0ek6zg308+UZsdtPExWP9VZoCFCz1zkJoXFnAX7aZfd/ZwrkidzdUZL0C/ryW+JwAiIGw==", + "dev": true + }, + "vn-loopback": { + "version": "file:loopback" + }, + "w3c-hr-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.1.tgz", + "integrity": "sha1-gqwr/2PZUOqeMYmlimViX+3xkEU=", + "dev": true, + "requires": { + "browser-process-hrtime": "^0.1.2" + } + }, + "walker": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.7.tgz", + "integrity": "sha1-L3+bj9ENZ3JisYqITijRlhjgKPs=", + "dev": true, + "requires": { + "makeerror": "1.0.x" + } + }, + "watchpack": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-1.6.0.tgz", + "integrity": "sha512-i6dHe3EyLjMmDlU1/bGQpEw25XSjkJULPuAVKCbNRefQVq48yXKUpwg538F7AZTf9kyr57zj++pQFltUa5H7yA==", + "dev": true, + "requires": { + "chokidar": "^2.0.2", + "graceful-fs": "^4.1.2", + "neo-async": "^2.5.0" + } + }, + "watchr": { + "version": "2.4.13", + "resolved": "https://registry.npmjs.org/watchr/-/watchr-2.4.13.tgz", + "integrity": "sha1-10hHu01vkPYf4sdPn2hmKqDgdgE=", + "requires": { + "eachr": "^2.0.2", + "extendr": "^2.1.0", + "extract-opts": "^2.2.0", + "ignorefs": "^1.0.0", + "safefs": "^3.1.2", + "scandirectory": "^2.5.0", + "taskgroup": "^4.2.0", + "typechecker": "^2.0.8" + } + }, + "wbuf": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/wbuf/-/wbuf-1.7.3.tgz", + "integrity": "sha512-O84QOnr0icsbFGLS0O3bI5FswxzRr8/gHwWkDlQFskhSPryQXvrTMxjxGP4+iWYoauLoBvfDpkrOauZ+0iZpDA==", + "dev": true, + "requires": { + "minimalistic-assert": "^1.0.0" + } + }, + "webidl-conversions": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz", + "integrity": "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==", + "dev": true + }, + "webpack": { + "version": "4.35.2", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-4.35.2.tgz", + "integrity": "sha512-TZAmorNymV4q66gAM/h90cEjG+N3627Q2MnkSgKlX/z3DlNVKUtqy57lz1WmZU2+FUZwzM+qm7cGaO95PyrX5A==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-module-context": "1.8.5", + "@webassemblyjs/wasm-edit": "1.8.5", + "@webassemblyjs/wasm-parser": "1.8.5", + "acorn": "^6.0.5", + "acorn-dynamic-import": "^4.0.0", + "ajv": "^6.1.0", + "ajv-keywords": "^3.1.0", + "chrome-trace-event": "^1.0.0", + "enhanced-resolve": "^4.1.0", + "eslint-scope": "^4.0.0", + "json-parse-better-errors": "^1.0.2", + "loader-runner": "^2.3.0", + "loader-utils": "^1.1.0", + "memory-fs": "~0.4.1", + "micromatch": "^3.1.8", + "mkdirp": "~0.5.0", + "neo-async": "^2.5.0", + "node-libs-browser": "^2.0.0", + "schema-utils": "^1.0.0", + "tapable": "^1.1.0", + "terser-webpack-plugin": "^1.1.0", + "watchpack": "^1.5.0", + "webpack-sources": "^1.3.0" + } + }, + "webpack-cli": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-3.3.5.tgz", + "integrity": "sha512-w0j/s42c5UhchwTmV/45MLQnTVwRoaUTu9fM5LuyOd/8lFoCNCELDogFoecx5NzRUndO0yD/gF2b02XKMnmAWQ==", + "dev": true, + "requires": { + "chalk": "2.4.2", + "cross-spawn": "6.0.5", + "enhanced-resolve": "4.1.0", + "findup-sync": "3.0.0", + "global-modules": "2.0.0", + "import-local": "2.0.0", + "interpret": "1.2.0", + "loader-utils": "1.2.3", + "supports-color": "6.1.0", + "v8-compile-cache": "2.0.3", + "yargs": "13.2.4" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true + }, + "cliui": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", + "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", + "dev": true, + "requires": { + "string-width": "^3.1.0", + "strip-ansi": "^5.2.0", + "wrap-ansi": "^5.1.0" + } + }, + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true + }, + "global-modules": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-2.0.0.tgz", + "integrity": "sha512-NGbfmJBp9x8IxyJSd1P+otYK8vonoJactOogrVfFRIAEY1ukil8RSKDz2Yo7wh1oihl51l/r6W4epkeKJHqL8A==", + "dev": true, + "requires": { + "global-prefix": "^3.0.0" + } + }, + "global-prefix": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-3.0.0.tgz", + "integrity": "sha512-awConJSVCHVGND6x3tmMaKcQvwXLhjdkmomy2W+Goaui8YPgYgXJZewhg3fWC+DlfqqQuWg8AwqjGTD2nAPVWg==", + "dev": true, + "requires": { + "ini": "^1.3.5", + "kind-of": "^6.0.2", + "which": "^1.3.1" + } + }, + "require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "dev": true + }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + } + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" + } + }, + "supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "which-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", + "dev": true + }, + "wrap-ansi": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.0", + "string-width": "^3.0.0", + "strip-ansi": "^5.0.0" + } + }, + "y18n": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", + "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==", + "dev": true + }, + "yargs": { + "version": "13.2.4", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.2.4.tgz", + "integrity": "sha512-HG/DWAJa1PAnHT9JAhNa8AbAv3FPaiLzioSjCcmuXXhP8MlpHO5vwls4g4j6n30Z74GVQj8Xa62dWVx1QCGklg==", + "dev": true, + "requires": { + "cliui": "^5.0.0", + "find-up": "^3.0.0", + "get-caller-file": "^2.0.1", + "os-locale": "^3.1.0", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^3.0.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^13.1.0" + } + }, + "yargs-parser": { + "version": "13.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.1.tgz", + "integrity": "sha512-oVAVsHz6uFrg3XQheFII8ESO2ssAf9luWuAd6Wexsu4F3OtIW0o8IribPXYrD4WC24LWtPrJlGy87y5udK+dxQ==", + "dev": true, + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + } + } + }, + "webpack-dev-server": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-3.7.2.tgz", + "integrity": "sha512-mjWtrKJW2T9SsjJ4/dxDC2fkFVUw8jlpemDERqV0ZJIkjjjamR2AbQlr3oz+j4JLhYCHImHnXZK5H06P2wvUew==", + "dev": true, + "requires": { + "ansi-html": "0.0.7", + "bonjour": "^3.5.0", + "chokidar": "^2.1.6", + "compression": "^1.7.4", + "connect-history-api-fallback": "^1.6.0", + "debug": "^4.1.1", + "del": "^4.1.1", + "express": "^4.17.1", + "html-entities": "^1.2.1", + "http-proxy-middleware": "^0.19.1", + "import-local": "^2.0.0", + "internal-ip": "^4.3.0", + "ip": "^1.1.5", + "killable": "^1.0.1", + "loglevel": "^1.6.3", + "opn": "^5.5.0", + "p-retry": "^3.0.1", + "portfinder": "^1.0.20", + "schema-utils": "^1.0.0", + "selfsigned": "^1.10.4", + "semver": "^6.1.1", + "serve-index": "^1.9.1", + "sockjs": "0.3.19", + "sockjs-client": "1.3.0", + "spdy": "^4.0.0", + "strip-ansi": "^3.0.1", + "supports-color": "^6.1.0", + "url": "^0.11.0", + "webpack-dev-middleware": "^3.7.0", + "webpack-log": "^2.0.0", + "yargs": "12.0.5" + }, + "dependencies": { + "ansi-colors": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-3.2.4.tgz", + "integrity": "sha512-hHUXGagefjN2iRrID63xckIvotOXOojhQKWIPUZ4mNUZ9nLZW+7FMNoE1lOkEhNWYsx/7ysGIuJYCiMAA9FnrA==", + "dev": true + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "cliui": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-4.1.0.tgz", + "integrity": "sha512-4FG+RSG9DL7uEwRUZXZn3SS34DiDPfzP0VOiEwtUWlE+AR2EIg+hSyvrIgUUfhdgR/UkAeW2QHgeP+hWrXs7jQ==", + "dev": true, + "requires": { + "string-width": "^2.1.1", + "strip-ansi": "^4.0.0", + "wrap-ansi": "^2.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "dev": true + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "del": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/del/-/del-4.1.1.tgz", + "integrity": "sha512-QwGuEUouP2kVwQenAsOof5Fv8K9t3D8Ca8NxcXKrIpEHjTXK5J2nXLdP+ALI1cgv8wj7KuwBhTwBkOZSJKM5XQ==", + "dev": true, + "requires": { + "@types/glob": "^7.1.1", + "globby": "^6.1.0", + "is-path-cwd": "^2.0.0", + "is-path-in-cwd": "^2.0.0", + "p-map": "^2.0.0", + "pify": "^4.0.1", + "rimraf": "^2.6.3" + } + }, + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "globby": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-6.1.0.tgz", + "integrity": "sha1-9abXDoOV4hyFj7BInWTfAkJNUGw=", + "dev": true, + "requires": { + "array-union": "^1.0.1", + "glob": "^7.0.3", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + }, + "dependencies": { + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=", + "dev": true + } + } + }, + "is-path-cwd": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-2.1.0.tgz", + "integrity": "sha512-Sc5j3/YnM8tDeyCsVeKlm/0p95075DyLmDEIkSgQ7mXkrOX+uTCtmQFm0CYzVyJwcCCmO3k8qfJt17SxQwB5Zw==", + "dev": true + }, + "is-path-in-cwd": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-path-in-cwd/-/is-path-in-cwd-2.1.0.tgz", + "integrity": "sha512-rNocXHgipO+rvnP6dk3zI20RpOtrAM/kzbB258Uw5BWr3TpXi861yzjo16Dn4hUox07iw5AyeMLHWsujkjzvRQ==", + "dev": true, + "requires": { + "is-path-inside": "^2.1.0" + } + }, + "is-path-inside": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-2.1.0.tgz", + "integrity": "sha512-wiyhTzfDWsvwAW53OBWF5zuvaOGlZ6PwYxAbPVDhpm+gM09xKQGjBq/8uYN12aDvMxnAnq3dxTyoSoRNmg5YFg==", + "dev": true, + "requires": { + "path-is-inside": "^1.0.2" + } + }, + "mime": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.4.tgz", + "integrity": "sha512-LRxmNwziLPT828z+4YkNzloCFC2YM4wrB99k+AV5ZbEyfGNWfG8SO1FUXLmLDBSo89NrJZ4DIWeLjy1CHGhMGA==", + "dev": true + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "punycode": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", + "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=", + "dev": true + }, + "rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "semver": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.2.0.tgz", + "integrity": "sha512-jdFC1VdUGT/2Scgbimf7FSx9iJLXoqfglSF+gJeuNWVpiE37OIbc1jywR/GJyFdz3mnkz2/id0L0J/cr0izR5A==", + "dev": true + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "url": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", + "integrity": "sha1-ODjpfPxgUh63PFJajlW/3Z4uKPE=", + "dev": true, + "requires": { + "punycode": "1.3.2", + "querystring": "0.2.0" + } + }, + "webpack-dev-middleware": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-3.7.0.tgz", + "integrity": "sha512-qvDesR1QZRIAZHOE3iQ4CXLZZSQ1lAUsSpnQmlB1PBfoN/xdRjmge3Dok0W4IdaVLJOGJy3sGI4sZHwjRU0PCA==", + "dev": true, + "requires": { + "memory-fs": "^0.4.1", + "mime": "^2.4.2", + "range-parser": "^1.2.1", + "webpack-log": "^2.0.0" + } + }, + "webpack-log": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/webpack-log/-/webpack-log-2.0.0.tgz", + "integrity": "sha512-cX8G2vR/85UYG59FgkoMamwHUIkSSlV3bBMRsbxVXVUk2j6NleCKjQ/WE9eYg9WY4w25O9w8wKP4rzNZFmUcUg==", + "dev": true, + "requires": { + "ansi-colors": "^3.0.0", + "uuid": "^3.3.2" + } + }, + "which-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", + "dev": true + }, + "yargs": { + "version": "12.0.5", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-12.0.5.tgz", + "integrity": "sha512-Lhz8TLaYnxq/2ObqHDql8dX8CJi97oHxrjUcYtzKbbykPtVW9WB+poxI+NM2UIzsMgNCZTIf0AQwsjK5yMAqZw==", + "dev": true, + "requires": { + "cliui": "^4.0.0", + "decamelize": "^1.2.0", + "find-up": "^3.0.0", + "get-caller-file": "^1.0.1", + "os-locale": "^3.0.0", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^2.0.0", + "which-module": "^2.0.0", + "y18n": "^3.2.1 || ^4.0.0", + "yargs-parser": "^11.1.1" + } + }, + "yargs-parser": { + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-11.1.1.tgz", + "integrity": "sha512-C6kB/WJDiaxONLJQnF8ccx9SEeoTTLek8RVbaOIsrAUS8VrBEXfmeSnCZxygc+XC2sNMBIwOOnfcxiynjHsVSQ==", + "dev": true, + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + } + } + }, + "webpack-merge": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-4.2.1.tgz", + "integrity": "sha512-4p8WQyS98bUJcCvFMbdGZyZmsKuWjWVnVHnAS3FFg0HDaRVrPbkivx2RYCre8UiemD67RsiFFLfn4JhLAin8Vw==", + "dev": true, + "requires": { + "lodash": "^4.17.5" + } + }, + "webpack-sources": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.3.0.tgz", + "integrity": "sha512-OiVgSrbGu7NEnEvQJJgdSFPl2qWKkWq5lHMhgiToIiN9w34EBnjYzSYs+VbL5KoYiLNtFFa7BZIKxRED3I32pA==", + "dev": true, + "requires": { + "source-list-map": "^2.0.0", + "source-map": "~0.6.1" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "websocket-driver": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.3.tgz", + "integrity": "sha512-bpxWlvbbB459Mlipc5GBzzZwhoZgGEZLuqPaR0INBGnPAY1vdBX6hPnoFXiw+3yWxDuHyQjO2oXTMyS8A5haFg==", + "dev": true, + "requires": { + "http-parser-js": ">=0.4.0 <0.4.11", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + } + }, + "websocket-extensions": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.3.tgz", + "integrity": "sha512-nqHUnMXmBzT0w570r2JpJxfiSD1IzoI+HGVdd3aZ0yNi3ngvQ4jv1dtHt5VGxfI2yj5yqImPhOK4vmIh2xMbGg==", + "dev": true + }, + "whatwg-encoding": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz", + "integrity": "sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw==", + "dev": true, + "requires": { + "iconv-lite": "0.4.24" + } + }, + "whatwg-fetch": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-2.0.3.tgz", + "integrity": "sha1-nITsLc9oGH/wC8ZOEnS0QhduHIQ=" + }, + "whatwg-mimetype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz", + "integrity": "sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==", + "dev": true + }, + "whatwg-url": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-6.5.0.tgz", + "integrity": "sha512-rhRZRqx/TLJQWUpQ6bmrt2UV4f0HCQ463yQuONJqC6fO2VoEb1pTYddbe59SkYq87aoM5A3bdhMZiUiVws+fzQ==", + "dev": true, + "requires": { + "lodash.sortby": "^4.7.0", + "tr46": "^1.0.1", + "webidl-conversions": "^4.0.2" + } + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "requires": { + "isexe": "^2.0.0" + } + }, + "which-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-1.0.0.tgz", + "integrity": "sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8=", + "dev": true + }, + "wide-align": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.3.tgz", + "integrity": "sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA==", + "dev": true, + "requires": { + "string-width": "^1.0.2 || 2" + } + }, + "widest-line": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-2.0.1.tgz", + "integrity": "sha512-Ba5m9/Fa4Xt9eb2ELXt77JxVDV8w7qQrH0zS/TWSJdLyAwQjWoOzpzj5lwVftDz6n/EOu3tNACS84v509qwnJA==", + "dev": true, + "requires": { + "string-width": "^2.1.1" + } + }, + "word-count": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/word-count/-/word-count-0.2.2.tgz", + "integrity": "sha1-aZGS/KaCn+k21Byw2V25JIxXBFE=" + }, + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + }, + "worker-farm": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/worker-farm/-/worker-farm-1.7.0.tgz", + "integrity": "sha512-rvw3QTZc8lAxyVrqcSGVm5yP/IJ2UcB3U0graE3LCFoZ0Yn2x4EoVSqJKdB/T5M+FLcRPjz4TDacRf3OCfNUzw==", + "dev": true, + "requires": { + "errno": "~0.1.7" + } + }, + "wrap-ansi": { + "version": "2.1.0", + "resolved": "http://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", + "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", + "dev": true, + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "dev": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "http://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "dev": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "write": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/write/-/write-1.0.3.tgz", + "integrity": "sha512-/lg70HAjtkUgWPVZhZcm+T4hkL8Zbtp1nFNOn3lRrxnlv50SRBv7cR7RqR+GMsd3hUXy9hWBo4CHTbFTcOYwig==", + "dev": true, + "requires": { + "mkdirp": "^0.5.1" + } + }, + "write-file-atomic": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", + "requires": { + "graceful-fs": "^4.1.11", + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.2" + } + }, + "x-xss-protection": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/x-xss-protection/-/x-xss-protection-1.3.0.tgz", + "integrity": "sha512-kpyBI9TlVipZO4diReZMAHWtS0MMa/7Kgx8hwG/EuZLiA6sg4Ah/4TRdASHhRRN3boobzcYgFRUFSgHRge6Qhg==" + }, + "xdg-basedir": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-3.0.0.tgz", + "integrity": "sha1-SWsswQnsqNus/i3HK2A8F8WHCtQ=" + }, + "xml": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/xml/-/xml-1.0.1.tgz", + "integrity": "sha1-eLpyAgApxbyHuKgaPPzXS0ovweU=", + "dev": true + }, + "xml-crypto": { + "version": "0.8.5", + "resolved": "https://registry.npmjs.org/xml-crypto/-/xml-crypto-0.8.5.tgz", + "integrity": "sha1-K7z7PrM/OoKiGLgiv2craxwg5Tg=", + "requires": { + "xmldom": "=0.1.19", + "xpath.js": ">=0.0.3" + } + }, + "xml-name-validator": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-3.0.0.tgz", + "integrity": "sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==", + "dev": true + }, + "xml2js": { + "version": "0.4.19", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.19.tgz", + "integrity": "sha512-esZnJZJOiJR9wWKMyuvSE1y6Dq5LCuJanqhxslH2bxM6duahNZ+HMpCLhBQGZkbX6xRf8x1Y2eJlgt2q3qo49Q==", + "requires": { + "sax": ">=0.6.0", + "xmlbuilder": "~9.0.1" + } + }, + "xmlbuilder": { + "version": "9.0.7", + "resolved": "http://registry.npmjs.org/xmlbuilder/-/xmlbuilder-9.0.7.tgz", + "integrity": "sha1-Ey7mPS7FVlxVfiD0wi35rKaGsQ0=" + }, + "xmlcreate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-1.0.2.tgz", + "integrity": "sha1-+mv3YqYKQT+z3Y9LA8WyaSONMI8=" + }, + "xmldom": { + "version": "0.1.19", + "resolved": "https://registry.npmjs.org/xmldom/-/xmldom-0.1.19.tgz", + "integrity": "sha1-Yx/Ad3bv2EEYvyUXGzftTQdaCrw=" + }, + "xpath.js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/xpath.js/-/xpath.js-1.1.0.tgz", + "integrity": "sha512-jg+qkfS4K8E7965sqaUl8mRngXiKb3WZGfONgE18pr03FUQiuSV6G+Ej4tS55B+rIQSFEIw3phdVAQ4pPqNWfQ==" + }, + "xregexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/xregexp/-/xregexp-2.0.0.tgz", + "integrity": "sha1-UqY+VsoLhKfzpfPWGHLxJq16WUM=" + }, + "xtend": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-1.0.3.tgz", + "integrity": "sha1-P12Tc1PM7Y4IU5mlY/2yJUHClgo=" + }, + "y18n": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz", + "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=", + "dev": true + }, + "yallist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.0.3.tgz", + "integrity": "sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A==" + }, + "yaml-loader": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/yaml-loader/-/yaml-loader-0.5.0.tgz", + "integrity": "sha512-p9QIzcFSNm4mCw/m5NdyMfN4RE4aFZJWRRb01ERVNGCym8VNbKtw3OYZXnvUIkim6U/EjqE/2yIh9F/msShH9A==", + "dev": true, + "requires": { + "js-yaml": "^3.5.2" + } + }, + "yamljs": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/yamljs/-/yamljs-0.3.0.tgz", + "integrity": "sha512-C/FsVVhht4iPQYXOInoxUM/1ELSf9EsgKH34FofQOp6hwCPrW4vG4w5++TED3xRUo8gD7l0P1J1dLlDYzODsTQ==", + "requires": { + "argparse": "^1.0.7", + "glob": "^7.0.5" + }, + "dependencies": { + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + } + } + }, + "yargs": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-7.1.0.tgz", + "integrity": "sha1-a6MY6xaWFyf10oT46gA+jWFU0Mg=", + "dev": true, + "requires": { + "camelcase": "^3.0.0", + "cliui": "^3.2.0", + "decamelize": "^1.1.1", + "get-caller-file": "^1.0.1", + "os-locale": "^1.4.0", + "read-pkg-up": "^1.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^1.0.2", + "which-module": "^1.0.0", + "y18n": "^3.2.1", + "yargs-parser": "^5.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "camelcase": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", + "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=", + "dev": true + }, + "invert-kv": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz", + "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "dev": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "lcid": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz", + "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", + "dev": true, + "requires": { + "invert-kv": "^1.0.0" + } + }, + "os-locale": { + "version": "1.4.0", + "resolved": "http://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz", + "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=", + "dev": true, + "requires": { + "lcid": "^1.0.0" + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "http://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "dev": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, + "yargs-parser": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-5.0.0.tgz", + "integrity": "sha1-J17PDX/+Bcd+ZOfIbkzZS/DhIoo=", + "dev": true, + "requires": { + "camelcase": "^3.0.0" + }, + "dependencies": { + "camelcase": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", + "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=", + "dev": true + } + } + }, + "yauzl": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.4.1.tgz", + "integrity": "sha1-lSj0QtqxsihOWLQ3m7GU4i4MQAU=", + "requires": { + "fd-slicer": "~1.0.1" + } } - } - }, - "ws": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/ws/-/ws-1.1.2.tgz", - "integrity": "sha1-iiRPoFJAHgjJiGz0SoUYnh/UBn8=", - "dev": true, - "requires": { - "options": "0.0.6", - "ultron": "1.0.2" - } - }, - "wtf-8": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/wtf-8/-/wtf-8-1.0.0.tgz", - "integrity": "sha1-OS2LotDxw00e4tYw8V0O+2jhBIo=", - "dev": true - }, - "xdg-basedir": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-3.0.0.tgz", - "integrity": "sha1-SWsswQnsqNus/i3HK2A8F8WHCtQ=", - "dev": true - }, - "xml-char-classes": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/xml-char-classes/-/xml-char-classes-1.0.0.tgz", - "integrity": "sha1-ZGV4SKIP/F31g6Qq2KJ3tFErvE0=", - "dev": true - }, - "xmlhttprequest-ssl": { - "version": "1.5.3", - "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-1.5.3.tgz", - "integrity": "sha1-GFqIjATspGw+QHDZn3tJ3jUomS0=", - "dev": true - }, - "xtend": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", - "dev": true - }, - "y18n": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz", - "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=", - "dev": true - }, - "yallist": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.0.0.tgz", - "integrity": "sha1-MGxUODXwnuGkyyO3vOmrNByRzdQ=" - }, - "yaml-loader": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/yaml-loader/-/yaml-loader-0.5.0.tgz", - "integrity": "sha512-p9QIzcFSNm4mCw/m5NdyMfN4RE4aFZJWRRb01ERVNGCym8VNbKtw3OYZXnvUIkim6U/EjqE/2yIh9F/msShH9A==", - "dev": true, - "requires": { - "js-yaml": "3.10.0" - } - }, - "yargs": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-7.1.0.tgz", - "integrity": "sha1-a6MY6xaWFyf10oT46gA+jWFU0Mg=", - "dev": true, - "requires": { - "camelcase": "3.0.0", - "cliui": "3.2.0", - "decamelize": "1.2.0", - "get-caller-file": "1.0.2", - "os-locale": "1.4.0", - "read-pkg-up": "1.0.1", - "require-directory": "2.1.1", - "require-main-filename": "1.0.1", - "set-blocking": "2.0.0", - "string-width": "1.0.2", - "which-module": "1.0.0", - "y18n": "3.2.1", - "yargs-parser": "5.0.0" - }, - "dependencies": { - "camelcase": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", - "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=", - "dev": true - } - } - }, - "yargs-parser": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-5.0.0.tgz", - "integrity": "sha1-J17PDX/+Bcd+ZOfIbkzZS/DhIoo=", - "dev": true, - "requires": { - "camelcase": "3.0.0" - }, - "dependencies": { - "camelcase": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz", - "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=", - "dev": true - } - } - }, - "yauzl": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.4.1.tgz", - "integrity": "sha1-lSj0QtqxsihOWLQ3m7GU4i4MQAU=", - "dev": true, - "requires": { - "fd-slicer": "1.0.1" - } - }, - "yeast": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/yeast/-/yeast-0.1.2.tgz", - "integrity": "sha1-AI4G2AlDIMNy28L47XagymyKxBk=", - "dev": true } - } } diff --git a/package.json b/package.json index 7b4c19023..d17e01ead 100644 --- a/package.json +++ b/package.json @@ -1,85 +1,97 @@ { - "name": "salix-app", - "version": "1.0.0", - "author": "Verdnatura Levante SL", - "description": "Salix application", - "license": "GPL-3.0", - "repository": { - "type": "git", - "url": "https://git.verdnatura.es/salix" - }, - "dependencies": { - "@uirouter/angularjs": "^1.0.3", - "angular": "^1.6.8", - "angular-cookies": "^1.6.4", - "angular-paging": "^2.2.2", - "angular-translate": "^2.17.0", - "angular-translate-loader-partial": "^2.17.0", - "flatpickr": "^2.6.3", - "fs-extra": "^5.0.0", - "material-design-lite": "^1.3.0", - "mg-crud": "^1.1.2", - "oclazyload": "^0.6.3", - "require-yaml": "0.0.1", - "validator": "^6.2.1" - }, - "devDependencies": { - "angular-mocks": "^1.6.6", - "assets-webpack-plugin": "^3.5.1", - "babel": "^6.23.0", - "babel-core": "^6.26.0", - "babel-loader": "^7.1.2", - "babel-preset-es2015": "^6.24.1", - "cors": "^2.8.1", - "css-loader": "^0.25.0", - "del": "^2.2.2", - "electron": "^1.7.9", - "eslint": "^3.19.0", - "eslint-config-angular": "^0.5.0", - "eslint-config-google": "^0.6.0", - "eslint-config-loopback": "^4.0.0", - "eslint-config-xo": "^0.17.0", - "eslint-plugin-jasmine": "^2.8.4", - "fancy-log": "^1.3.2", - "file-loader": "^1.1.6", - "gulp": "^3.9.1", - "gulp-concat": "^2.6.0", - "gulp-env": "^0.4.0", - "gulp-extend": "^0.2.0", - "gulp-install": "^1.1.0", - "gulp-jasmine": "^3.0.0", - "gulp-print": "^2.0.1", - "gulp-wrap": "^0.13.0", - "gulp-yaml": "^1.0.1", - "html-loader": "^0.4.4", - "jasmine": "^2.9.0", - "jasmine-spec-reporter": "^4.2.1", - "js-yaml": "^3.10.0", - "karma": "^1.7.1", - "karma-chrome-launcher": "^2.2.0", - "karma-firefox-launcher": "^1.1.0", - "karma-jasmine": "^1.1.1", - "karma-sourcemap-loader": "^0.3.7", - "karma-webpack": "^2.0.9", - "merge-stream": "^1.0.1", - "minimist": "^1.2.0", - "mustache": "^2.3.0", - "mysql2": "^1.5.2", - "nightmare": "^2.10.0", - "node-sass": "^4.7.2", - "nodemon": "^1.12.1", - "plugin-error": "^1.0.1", - "raw-loader": "*", - "run-sequence": "^2.2.0", - "sass-loader": "^6.0.6", - "style-loader": "^0.20.1", - "webpack": "^3.10.0", - "webpack-dev-server": "^2.11.1", - "webpack-merge": "^4.1.1", - "yaml-loader": "^0.5.0" - }, - "scripts": { - "test": "nodemon -q services_tests.js -w services", - "lint": "eslint ./ --cache --ignore-pattern .gitignore" - } + "name": "salix-back", + "version": "1.0.0", + "author": "Verdnatura Levante SL", + "description": "Salix backend", + "license": "GPL-3.0", + "repository": { + "type": "git", + "url": "https://gitea.verdnatura.es/verdnatura/salix" + }, + "dependencies": { + "compression": "^1.7.3", + "electron": "^7.1.2", + "fs-extra": "^5.0.0", + "helmet": "^3.21.1", + "i18n": "^0.8.3", + "loopback": "^3.26.0", + "loopback-boot": "^2.27.1", + "loopback-component-explorer": "^6.3.1", + "loopback-component-storage": "^3.6.1", + "loopback-connector-mysql": "^5.3.1", + "loopback-connector-remote": "^3.4.1", + "loopback-context": "^3.4.0", + "md5": "^2.2.1", + "object-diff": "0.0.4", + "object.pick": "^1.3.0", + "request": "^2.88.0", + "request-promise-native": "^1.0.7", + "require-yaml": "0.0.1", + "soap": "^0.26.0", + "strong-error-handler": "^2.3.2", + "uuid": "^3.3.2", + "vn-loopback": "file:./loopback", + "xml2js": "^0.4.19" + }, + "devDependencies": { + "@babel/core": "^7.6.0", + "@babel/plugin-syntax-dynamic-import": "^7.2.0", + "@babel/polyfill": "^7.2.5", + "@babel/preset-env": "^7.6.0", + "@babel/register": "^7.0.0", + "angular-mocks": "^1.7.7", + "babel-jest": "^24.9.0", + "babel-loader": "^8.0.6", + "babel-preset-es2015": "^6.24.1", + "css-loader": "^2.1.0", + "del": "^2.2.2", + "eslint": "^5.14.0", + "eslint-config-google": "^0.11.0", + "eslint-plugin-jasmine": "^2.10.1", + "fancy-log": "^1.3.2", + "file-loader": "^1.1.11", + "gulp": "^4.0.2", + "gulp-concat": "^2.6.1", + "gulp-env": "^0.4.0", + "gulp-file": "^0.4.0", + "gulp-install": "^1.1.0", + "gulp-jasmine": "^3.0.0", + "gulp-merge-json": "^1.3.1", + "gulp-nodemon": "^2.4.2", + "gulp-print": "^2.0.1", + "gulp-wrap": "^0.13.0", + "gulp-yaml": "^1.0.1", + "html-loader": "^0.4.5", + "html-loader-jest": "^0.2.1", + "html-webpack-plugin": "^4.0.0-beta.5", + "identity-obj-proxy": "^3.0.0", + "jasmine": "^3.4.0", + "jasmine-reporters": "^2.3.2", + "jasmine-spec-reporter": "^4.2.1", + "jest": "^24.9.0", + "jest-junit": "^8.0.0", + "json-loader": "^0.5.7", + "merge-stream": "^1.0.1", + "minimist": "^1.2.0", + "mysql2": "^1.6.5", + "nightmare": "^3.0.2", + "node-sass": "^4.9.3", + "nodemon": "^1.18.10", + "plugin-error": "^1.0.1", + "raw-loader": "^1.0.0", + "sass-loader": "^7.1.0", + "style-loader": "^0.23.1", + "webpack": "^4.29.5", + "webpack-cli": "^3.2.3", + "webpack-dev-server": "^3.1.14", + "webpack-merge": "^4.2.1", + "yaml-loader": "^0.5.0" + }, + "scripts": { + "dbtest": "nodemon -q db/tests.js -w db/tests", + "test": "jest --watch", + "back": "nodemon --inspect -w modules ./node_modules/gulp/bin/gulp.js back", + "lint": "eslint ./ --cache --ignore-pattern .gitignore", + "docker": "docker build -t salix-db ./db" + } } diff --git a/print/boot.js b/print/boot.js new file mode 100644 index 000000000..ae604db2c --- /dev/null +++ b/print/boot.js @@ -0,0 +1,56 @@ +const express = require('express'); +const path = require('path'); +const fs = require('fs'); + +const templatesPath = path.resolve(__dirname, './templates'); +const componentsPath = path.resolve(__dirname, './core/components'); + +module.exports = app => { + global.appPath = __dirname; + + process.env.OPENSSL_CONF = '/etc/ssl/'; + + // Extended locale intl polyfill + const IntlPolyfill = require('intl'); + Intl.NumberFormat = IntlPolyfill.NumberFormat; + Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat; + + // Init database instance + require('./core/database').init(); + // Init SMTP Instance + require('./core/smtp').init(); + require('./core/mixins'); + require('./core/filters'); + require('./core/directives'); + // Init router + require('./core/router')(app); + + /** + * Serve component static files + */ + const componentsDir = fs.readdirSync(componentsPath); + componentsDir.forEach(componentName => { + const componentDir = path.join(componentsPath, '/', componentName); + const assetsDir = `${componentDir}/assets`; + + app.use(`/api/${componentName}/assets`, express.static(assetsDir)); + }); + + /** + * Serve static files + */ + const templatesDir = fs.readdirSync(templatesPath); + templatesDir.forEach(directory => { + const templateTypeDir = path.join(templatesPath, '/', directory); + const templates = fs.readdirSync(templateTypeDir); + + templates.forEach(templateName => { + const templateDir = path.join(templatesPath, '/', directory, '/', templateName); + const assetsDir = `${templateDir}/assets`; + + app.use(`/api/${templateName}/assets`, express.static(assetsDir)); + }); + }); +}; + + diff --git a/print/common/css/email.css b/print/common/css/email.css new file mode 100644 index 000000000..6e6350ff5 --- /dev/null +++ b/print/common/css/email.css @@ -0,0 +1,33 @@ +/** + * Email only stylesheet + * +*/ +body { + -webkit-text-size-adjust: none; + -ms-text-size-adjust: none; + background-color: #FFF; + font-weight: 400; + color: #555; + margin: 0 +} + +.grid { + background-color: #FFF + +} + +.grid a { + color: #8dba25 +} + +.grid-block { + min-width: 300px; + max-width: 600px; + margin: 0 auto; + color: #333 +} + +h1 { + font-weight: 100; + font-size: 1.5em +} diff --git a/print/common/css/layout.css b/print/common/css/layout.css new file mode 100644 index 000000000..6be065a14 --- /dev/null +++ b/print/common/css/layout.css @@ -0,0 +1,251 @@ +/** + * CSS layout elements + * +*/ + +.grid { + font-family: Arial, sans-serif; + font-size: 16px !important; + width: 100% +} + +.grid-row { + background-color: transparent +} + +.grid-block { + box-sizing: border-box; + background-color: #FFF; + min-height: 40px +} + +.grid-block.empty { + height: 40px +} + +.columns { + overflow: hidden; + box-sizing: border-box; +} + +.columns .size100 { + width: 100%; + float: left +} + +.columns .size75 { + width: 75%; + float: left +} + +.columns .size50 { + box-sizing: border-box; + width: 50%; + float: left +} + +.columns .size33 { + width: 33.33%; + float: left +} + +.columns .size25 { + width: 25%; + float: left +} + +.clearfix { + overflow: hidden; + display: block; + clear: both +} + +.panel { + position: relative; + margin-bottom: 15px; + padding-top: 10px; + break-inside: avoid; + break-before: always; + break-after: always; +} + +.panel .header { + background-color: #FFF; + padding: 2.5px 10px; + position: absolute; + font-weight: bold; + top: 0px; + left: 17.5px; +} + +.panel .body { + border: 1px solid #CCC; + overflow: hidden; + padding: 20px +} + +.panel .body h3 { + margin-top: 0 +} + +.panel.dark .header { + border: 1px solid #808080; + background-color: #FFF; +} + +.panel.dark .body { + border: 1px solid #808080; + background-color: #c0c0c0 +} + +.field { + border-bottom: 1px solid #CCC; + border-left: 1px solid #CCC; + border-top: 1px solid #CCC; + float: left +} + +.field span { + border-right: 1px solid #CCC; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + display: table-cell; + vertical-align: middle; + text-align: center; + font-weight: bold +} + +.field.square span { + height: 35.4px; + width: 35.4px +} + +.emptyField { + border-bottom: 1px dotted grey; + min-height: 1em; + display: block +} + +.field.rectangle span { + height: 2em; + width: 8em +} + +.pull-left { + float: left !important +} + +.pull-right { + float: right !important +} + +.vertical-text { + -moz-transform: rotate(90deg); + -webkit-transform: rotate(90deg); + transform: rotate(90deg); + position: absolute; + text-align: center; + font-size: .65em; + right: -108px; + width: 200px; + top: 50% +} + +table { + border-collapse: collapse; + border-spacing: 0; +} + +.row-oriented, .column-oriented { + text-align: left; + width: 100% +} + +.column-oriented { + margin-bottom: 15px +} + +.column-oriented td, +.column-oriented th { + padding: 5px 10px +} + +.column-oriented thead { + background-color: #e5e5e5 +} + +.column-oriented thead tr { + border-bottom: 1px solid #808080; + border-top: 1px solid #808080; + background-color: #e5e5e5 +} + +.column-oriented tfoot { + border-top: 2px solid #808080; +} + +.column-oriented tfoot tr:first-child td { + padding-top: 20px !important; +} + +.column-oriented .description { + border-bottom: 1px solid #DDD; + font-size: 0.8em +} + +.panel .row-oriented td, .panel .row-oriented th { + padding: 8px 10px +} + +.row-oriented > tbody > tr > td { + width: 30% +} + +.row-oriented > tbody > tr > th { + padding-left: 30px; + width: 70% +} + +.row-oriented .description { + padding: 0 !important; + font-size: 0.6em; + color: #888 +} + +.line { + border-bottom: 1px solid #DDD; + border-right: 1px solid #DDD; + border-left: 1px solid #DDD; + position: relative; + margin-left: -1px; + margin-right: 1px; + margin-top: 10px; + padding: 5px 0; + color: #999; +} + +.line .vertical-aligned { + position: absolute; + text-align: center; + width: 100%; + +} + +.line span { + background-color: #FFF; + padding: 5px +} + +.signature { + width: 100% +} + +.signature section { + height: 150px +} + +.signature p { + margin-right: 50%; + margin-top: 140px +} diff --git a/print/common/css/misc.css b/print/common/css/misc.css new file mode 100644 index 000000000..093d5a974 --- /dev/null +++ b/print/common/css/misc.css @@ -0,0 +1,47 @@ +/** + * CSS misc classes + * +*/ +.uppercase { + text-transform: uppercase +} + +.justified { + text-align: justify +} + +.centered { + text-align: center +} + +.align-right { + text-align: right +} + +.align-left { + text-align: left +} + +.number { + text-align: right +} + +.font.gray { + color: #555 +} + +.font.light-gray { + color: #888 +} + +.font.small { + font-size: 0.65em +} + +.font.bold { + font-weight: bold +} + +.non-page-break { + page-break-inside: avoid; +} \ No newline at end of file diff --git a/print/common/css/report.css b/print/common/css/report.css new file mode 100644 index 000000000..5b8a1539b --- /dev/null +++ b/print/common/css/report.css @@ -0,0 +1,14 @@ +/** + * Report only stylesheet + * +*/ +body { + zoom: 0.53 +} + +.title { + margin-bottom: 20px; + font-weight: 100; + margin-top: 0; + font-size: 2em +} \ No newline at end of file diff --git a/print/common/css/spacing.css b/print/common/css/spacing.css new file mode 100644 index 000000000..670102d7c --- /dev/null +++ b/print/common/css/spacing.css @@ -0,0 +1,349 @@ +/** + * CSS spacing classes + * + * vn-[p|m][t|r|b|l|a|x|y]-[none|auto|xs|sm|md|lg|xl] + * T D S + * + * T - type + * - values: p (padding), m (margin) + * + * D - direction + * - values: + * t (top), r (right), b (bottom), l (left), + * a (all), x (both left & right), y (both top & bottom) + * + * S - size + * - values: + * none, + * auto (ONLY for specific margins: vn-ml-*, vn-mr-*, vn-mx-*), + * xs (extra small), + * sm (small), + * md (medium), + * lg (large), + * xl (extra large) + */ + +/* ++++++++++++++++++++++++++++++++++++++++++++++++ Padding */ + +.vn-pa-none { + padding: 0; +} +.vn-pl-none { + padding-left: 0; +} +.vn-pr-none { + padding-right: 0; +} +.vn-pt-none { + padding-top: 0; +} +.vn-pb-none { + padding-bottom: 0; +} +.vn-py-none { + padding-top: 0; + padding-bottom: 0; +} +.vn-px-none { + padding-left: 0; + padding-right: 0; +} + +.vn-pa-xs { + padding: 4px; +} +.vn-pl-xs { + padding-left: 4px; +} +.vn-pr-xs { + padding-right: 4px; +} +.vn-pt-xs { + padding-top: 4px; +} +.vn-pb-xs { + padding-bottom: 4px; +} +.vn-py-xs { + padding-top: 4px; + padding-bottom: 4px; +} +.vn-px-xs { + padding-left: 4px; + padding-right: 4px; +} + +/* Small */ + +.vn-pa-sm { + padding: 8px; +} +.vn-pl-sm { + padding-left: 8px; +} +.vn-pr-sm { + padding-right: 8px; +} +.vn-pt-sm { + padding-top: 8px; +} +.vn-pb-sm { + padding-bottom: 8px; +} +.vn-py-sm { + padding-top: 8px; + padding-bottom: 8px; +} +.vn-px-sm { + padding-left: 8px; + padding-right: 8px; +} + +/* Medium */ + +.vn-pa-md { + padding: 16px; +} +.vn-pl-md { + padding-left: 16px; +} +.vn-pr-md { + padding-right: 16px; +} +.vn-pt-md { + padding-top: 16px; +} +.vn-pb-md { + padding-bottom: 16px; +} +.vn-py-md { + padding-top: 16px; + padding-bottom: 16px; +} +.vn-px-md { + padding-left: 16px; + padding-right: 16px; +} + +/* Large */ + +.vn-pa-lg { + padding: 32px; +} +.vn-pl-lg { + padding-left: 32px; +} +.vn-pr-lg { + padding-right: 32px; +} +.vn-pt-lg { + padding-top: 32px; +} +.vn-pb-lg { + padding-bottom: 32px; +} +.vn-py-lg { + padding-top: 32px; + padding-bottom: 32px; +} +.vn-px-lg { + padding-left: 32px; + padding-right: 32px; +} + +/* Extra large */ + +.vn-pa-xl { + padding: 100px; +} +.vn-pl-xl { + padding-left: 100px; +} +.vn-pr-xl { + padding-right: 100px; +} +.vn-pt-xl { + padding-top: 100px; +} +.vn-pb-xl { + padding-bottom: 100px; +} +.vn-py-xl { + padding-top: 100px; + padding-bottom: 100px; +} +.vn-px-xl { + padding-left: 100px; + padding-right: 100px; +} + +/* ++++++++++++++++++++++++++++++++++++++++++++++++ Margin */ + +/* None */ + +.vn-ma-none { + padding: 0; +} +.vn-ml-none { + padding-left: 0; +} +.vn-mr-none { + padding-right: 0; +} +.vn-mt-none { + padding-top: 0; +} +.vn-mb-none { + padding-bottom: 0; +} +.vn-my-none { + padding-top: 0; + padding-bottom: 0; +} +.vn-mx-none { + padding-left: 0; + padding-right: 0; +} + +/* Auto */ + +.vn-ml-none { + padding-left: auto; +} +.vn-mr-none { + padding-right: auto; +} +.vn-mx-none { + padding-left: auto; + padding-right: auto; +} + +/* Extra small */ + +.vn-ma-xs { + margin: 4px; +} +.vn-mt-xs { + margin-top: 4px; +} +.vn-ml-xs { + margin-left: 4px; +} +.vn-mr-xs { + margin-right: 4px; +} +.vn-mb-xs { + margin-bottom: 4px; +} +.vn-my-xs { + margin-top: 4px; + margin-bottom: 4px; +} +.vn-mx-xs { + margin-left: 4px; + margin-right: 4px; +} + +/* Small */ + +.vn-ma-sm { + margin: 8px; +} +.vn-mt-sm { + margin-top: 8px; +} +.vn-ml-sm { + margin-left: 8px; +} +.vn-mr-sm { + margin-right: 8px; +} +.vn-mb-sm { + margin-bottom: 8px; +} +.vn-my-sm { + margin-top: 8px; + margin-bottom: 8px; +} +.vn-mx-sm { + margin-left: 8px; + margin-right: 8px; +} + +/* Medium */ + +.vn-ma-md { + margin: 16px; +} +.vn-mt-md { + margin-top: 16px; +} +.vn-ml-md { + margin-left: 16px; +} +.vn-mr-md { + margin-right: 16px; +} +.vn-mb-md { + margin-bottom: 16px; +} +.vn-my-md { + margin-top: 16px; + margin-bottom: 16px; +} +.vn-mx-md { + margin-left: 16px; + margin-right: 16px; +} + +/* Large */ + +.vn-ma-lg { + margin: 32px; +} +.vn-mt-lg { + margin-top: 32px; +} +.vn-ml-lg { + margin-left: 32px; +} +.vn-mr-lg { + margin-right: 32px; +} +.vn-mb-lg { + margin-bottom: 32px; +} +.vn-my-lg { + margin-top: 32px; + margin-bottom: 32px; +} +.vn-mx-lg { + margin-left: 32px; + margin-right: 32px; +} + +/* Extra large */ + +.vn-ma-xl { + margin: 100px; +} +.vn-mt-xl { + margin-top: 100px; +} +.vn-ml-xl { + margin-left: 100px; +} +.vn-mr-xl { + margin-right: 100px; +} +.vn-mb-xl { + margin-bottom: 100px; +} +.vn-my-xl { + margin-top: 100px; + margin-bottom: 100px; +} +.vn-mx-xl { + margin-left: 100px; + margin-right: 100px; +} diff --git a/print/config/print.json b/print/config/print.json new file mode 100755 index 000000000..e1a93e152 --- /dev/null +++ b/print/config/print.json @@ -0,0 +1,44 @@ +{ + "app": { + "host": "http://localhost:5000", + "port": 3000, + "senderEmail": "nocontestar@verdnatura.es", + "reportEmail": "cau@verdnatura.es", + "senderName": "Verdnatura" + }, + "i18n": { + "locale": "es", + "fallbackLocale": "es", + "silentTranslationWarn": false + }, + "pdf": { + "format": "A4", + "border": "1.5cm", + "footer": { + "height": "55px" + } + }, + "mysql": { + "host": "localhost", + "port": 3306, + "database": "vn", + "user": "root", + "password": "root" + }, + "smtp": { + "host": "localhost", + "port": 465, + "secure": true, + "auth": { + "user": "", + "pass": "" + }, + "tls": { + "rejectUnauthorized": false + }, + "pool": true + }, + "storage": { + "root": "./e2e/dms" + } +} \ No newline at end of file diff --git a/print/core/component.js b/print/core/component.js new file mode 100644 index 000000000..836b8c9d9 --- /dev/null +++ b/print/core/component.js @@ -0,0 +1,104 @@ +const Vue = require('vue'); +const VueI18n = require('vue-i18n'); +const renderer = require('vue-server-renderer').createRenderer(); +Vue.use(VueI18n); + +const fs = require('fs'); +const yaml = require('js-yaml'); +const juice = require('juice'); +const path = require('path'); +const config = require('./config'); + +class Component { + constructor(name) { + this.name = name; + } + + get path() { + return `./components/${this.name}`; + } + + get template() { + const templatePath = `${this.path}/${this.name}.html`; + const fullPath = path.resolve(__dirname, templatePath); + + return fs.readFileSync(fullPath, 'utf8'); + } + + get locale() { + if (!this._locale) + this.getLocale(); + + return this._locale; + } + + getLocale() { + const mergedLocale = {messages: {}}; + const localePath = path.resolve(__dirname, `${this.path}/locale`); + + if (!fs.existsSync(localePath)) + return mergedLocale; + + const localeDir = fs.readdirSync(localePath); + localeDir.forEach(locale => { + const fullPath = path.join(localePath, '/', locale); + const yamlLocale = fs.readFileSync(fullPath, 'utf8'); + const jsonLocale = yaml.safeLoad(yamlLocale); + const localeName = locale.replace('.yml', ''); + + mergedLocale.messages[localeName] = jsonLocale; + }); + + this._locale = mergedLocale; + } + + get stylesheet() { + let mergedStyles = ''; + const stylePath = path.resolve(__dirname, `${this.path}/assets/css`); + + if (!fs.existsSync(stylePath)) + return mergedStyles; + + return require(`${stylePath}/import`); + } + + get attachments() { + const attachmentsPath = `${this.path}/attachments.json`; + const fullPath = path.resolve(__dirname, attachmentsPath); + + if (!fs.existsSync(fullPath)) + return []; + + return require(fullPath); + } + + build() { + const fullPath = path.resolve(__dirname, this.path); + if (!fs.existsSync(fullPath)) + throw new Error(`Sample "${this.name}" not found`); + + const component = require(`${this.path}/${this.name}`); + component.i18n = this.locale; + component.attachments = this.attachments; + component.template = juice.inlineContent(this.template, this.stylesheet, { + inlinePseudoElements: true + }); + + return component; + } + + async render() { + const component = this.build(); + const i18n = new VueI18n(config.i18n); + const app = new Vue({ + i18n: i18n, + render: h => h(component, { + props: this.args + }) + }); + + return renderer.renderToString(app); + } +} + +module.exports = Component; diff --git a/print/core/components/attachment/assets/css/import.js b/print/core/components/attachment/assets/css/import.js new file mode 100644 index 000000000..c742fdf90 --- /dev/null +++ b/print/core/components/attachment/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/core/components/attachment/assets/css/style.css b/print/core/components/attachment/assets/css/style.css new file mode 100644 index 000000000..775c43ada --- /dev/null +++ b/print/core/components/attachment/assets/css/style.css @@ -0,0 +1,22 @@ +div { + display: inline-block; + box-sizing: border-box +} + +a { + background-color: #F5F5F5; + border: 1px solid #CCC; + display: flex; + vertical-align: middle; + box-sizing: border-box; + min-width: 150px; + text-decoration: none; + border-radius: 3px; + color: #8dba25 +} + +a > div.icon { + font-weight: bold; + font-size: 18px; + color: #555 +} \ No newline at end of file diff --git a/print/core/components/attachment/assets/images/attachment.svg b/print/core/components/attachment/assets/images/attachment.svg new file mode 100644 index 000000000..2cb630379 --- /dev/null +++ b/print/core/components/attachment/assets/images/attachment.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/print/core/components/attachment/attachment.html b/print/core/components/attachment/attachment.html new file mode 100644 index 000000000..d66746e99 --- /dev/null +++ b/print/core/components/attachment/attachment.html @@ -0,0 +1,6 @@ + \ No newline at end of file diff --git a/print/core/components/attachment/attachment.js b/print/core/components/attachment/attachment.js new file mode 100755 index 000000000..2d4e74cdc --- /dev/null +++ b/print/core/components/attachment/attachment.js @@ -0,0 +1,37 @@ +module.exports = { + name: 'attachment', + computed: { + path() { + const filename = this.attachment.filename; + const component = this.attachment.component; + if (this.attachment.cid) + return `/api/${component}/assets/files/${filename}`; + else + return `/api/report/${component}?${this.getHttpParams()}`; + } + }, + methods: { + getHttpParams() { + const props = this.args; + let query = ''; + for (let param in props) { + if (query != '') + query += '&'; + query += `${param}=${props[param]}`; + } + + return query; + } + }, + props: { + attachment: { + type: Object, + required: true + }, + args: { + type: Object, + required: false + } + } +}; + diff --git a/print/core/components/email-footer/assets/css/import.js b/print/core/components/email-footer/assets/css/import.js new file mode 100644 index 000000000..c742fdf90 --- /dev/null +++ b/print/core/components/email-footer/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/core/components/email-footer/assets/css/style.css b/print/core/components/email-footer/assets/css/style.css new file mode 100644 index 000000000..4bc22fdfd --- /dev/null +++ b/print/core/components/email-footer/assets/css/style.css @@ -0,0 +1,52 @@ +.buttons { + font-size: 14px !important; + width: 100% +} + +.buttons a { + text-decoration: none; + width: 100%; + color: #fff; +} + +.buttons .btn { + background-color: #333; + text-align: center +} + + +.buttons .btn .icon { + background-color: #95d831; + box-sizing: border-box; + font-weight: bold; + text-align: center; + color: #333; + float: left +} + + +.buttons .btn .text { + + display: inline-block; +} + +.networks { + background-color: #555; + text-align: center; + padding: 20px 0 +} + +.networks a { + text-decoration: none; + margin-right: 5px +} + +.networks a img { + margin: 0 +} + +.privacy { + padding: 20px 0; + font-size: 10px; + font-weight: 100 +} \ No newline at end of file diff --git a/services/mailer/application/template/footer/image/action.png b/print/core/components/email-footer/assets/images/action.png similarity index 100% rename from services/mailer/application/template/footer/image/action.png rename to print/core/components/email-footer/assets/images/action.png diff --git a/services/mailer/application/template/footer/image/facebook.png b/print/core/components/email-footer/assets/images/facebook.png similarity index 100% rename from services/mailer/application/template/footer/image/facebook.png rename to print/core/components/email-footer/assets/images/facebook.png diff --git a/services/mailer/application/template/footer/image/info.png b/print/core/components/email-footer/assets/images/info.png similarity index 100% rename from services/mailer/application/template/footer/image/info.png rename to print/core/components/email-footer/assets/images/info.png diff --git a/services/mailer/application/template/footer/image/instagram.png b/print/core/components/email-footer/assets/images/instagram.png similarity index 100% rename from services/mailer/application/template/footer/image/instagram.png rename to print/core/components/email-footer/assets/images/instagram.png diff --git a/services/mailer/application/template/footer/image/linkedin.png b/print/core/components/email-footer/assets/images/linkedin.png similarity index 100% rename from services/mailer/application/template/footer/image/linkedin.png rename to print/core/components/email-footer/assets/images/linkedin.png diff --git a/services/mailer/application/template/footer/image/pinterest.png b/print/core/components/email-footer/assets/images/pinterest.png similarity index 100% rename from services/mailer/application/template/footer/image/pinterest.png rename to print/core/components/email-footer/assets/images/pinterest.png diff --git a/services/mailer/application/template/footer/image/twitter.png b/print/core/components/email-footer/assets/images/twitter.png similarity index 100% rename from services/mailer/application/template/footer/image/twitter.png rename to print/core/components/email-footer/assets/images/twitter.png diff --git a/services/mailer/application/template/footer/image/youtube.png b/print/core/components/email-footer/assets/images/youtube.png similarity index 100% rename from services/mailer/application/template/footer/image/youtube.png rename to print/core/components/email-footer/assets/images/youtube.png diff --git a/print/core/components/email-footer/attachments.json b/print/core/components/email-footer/attachments.json new file mode 100644 index 000000000..0d339b76f --- /dev/null +++ b/print/core/components/email-footer/attachments.json @@ -0,0 +1,22 @@ +[ + { + "filename": "facebook.png", + "path": "/assets/images/facebook.png", + "cid": "facebook.png" + }, + { + "filename": "twitter.png", + "path": "/assets/images/twitter.png", + "cid": "twitter.png" + }, + { + "filename": "instagram.png", + "path": "/assets/images/instagram.png", + "cid": "instagram.png" + }, + { + "filename": "linkedin.png", + "path": "/assets/images/linkedin.png", + "cid": "linkedin.png" + } +] \ No newline at end of file diff --git a/print/core/components/email-footer/email-footer.html b/print/core/components/email-footer/email-footer.html new file mode 100644 index 000000000..a033ec633 --- /dev/null +++ b/print/core/components/email-footer/email-footer.html @@ -0,0 +1,47 @@ + \ No newline at end of file diff --git a/print/core/components/email-footer/email-footer.js b/print/core/components/email-footer/email-footer.js new file mode 100755 index 000000000..d21ad348e --- /dev/null +++ b/print/core/components/email-footer/email-footer.js @@ -0,0 +1,3 @@ +module.exports = { + name: 'email-footer' +}; diff --git a/print/core/components/email-footer/locale/en.yml b/print/core/components/email-footer/locale/en.yml new file mode 100644 index 000000000..ccc0832e8 --- /dev/null +++ b/print/core/components/email-footer/locale/en.yml @@ -0,0 +1,17 @@ +buttons: + webAcccess: Visit our website + info: Help us to improve +fiscalAddress: VERDNATURA LEVANTE SL, B97367486 Avda. Espioca, 100, 46460 Silla + · www.verdnatura.es · clientes@verdnatura.es +disclaimer: '- NOTICE - This message is private and confidential, and should be used + exclusively by the person receiving it. If you have received this message by mistake, + please notify the sender and delete that message and any attached documents that it may contain. + Verdnatura Levante SL does not waive confidentiality or any privilege due to erroneous + transmission or malfunction. Likewise, it is not responsible for the changes, alterations, + errors or omissions that could be made to the message once sent.' +privacy: 'In compliance with the provisions of Organic Law 15/1999, on the + Protection of Personal Data, we inform you that the personal data you provide + will be included in automated files of VERDNATURA LEVANTE SL, being able at all + times to exercise the rights of access, rectification, cancellation and opposition, + communicating it in writing to the registered office of the entity. + The purpose of the file is administrative management, accounting, and billing.' diff --git a/print/core/components/email-footer/locale/es.yml b/print/core/components/email-footer/locale/es.yml new file mode 100644 index 000000000..7f4b13045 --- /dev/null +++ b/print/core/components/email-footer/locale/es.yml @@ -0,0 +1,18 @@ +buttons: + webAcccess: Visita nuestra Web + info: Ayúdanos a mejorar +fiscalAddress: VERDNATURA LEVANTE SL, B97367486 Avda. Espioca, 100, 46460 Silla + · www.verdnatura.es · clientes@verdnatura.es +disclaimer: '- AVISO - Este mensaje es privado y confidencial, y debe ser utilizado + exclusivamente por la persona destinataria del mismo. Si has recibido este mensaje + por error, te rogamos lo comuniques al remitente y borres dicho mensaje y cualquier + documento adjunto que pudiera contener. Verdnatura Levante SL no renuncia a la + confidencialidad ni a ningún privilegio por causa de transmisión errónea o mal + funcionamiento. Igualmente no se hace responsable de los cambios, alteraciones, + errores u omisiones que pudieran hacerse al mensaje una vez enviado.' +privacy: En cumplimiento de lo dispuesto en la Ley Orgánica 15/1999, de Protección de + Datos de Carácter Personal, te comunicamos que los datos personales que facilites + se incluirán en ficheros automatizados de VERDNATURA LEVANTE S.L., pudiendo en + todo momento ejercitar los derechos de acceso, rectificación, cancelación y oposición, + comunicándolo por escrito al domicilio social de la entidad. La finalidad del + fichero es la gestión administrativa, contabilidad, y facturación. diff --git a/print/core/components/email-footer/locale/fr.yml b/print/core/components/email-footer/locale/fr.yml new file mode 100644 index 000000000..d93f9769e --- /dev/null +++ b/print/core/components/email-footer/locale/fr.yml @@ -0,0 +1,18 @@ +buttons: + webAcccess: Visitez notre site web + info: Aidez-nous à améliorer +fiscalAddress: VERDNATURA LEVANTE SL, B97367486 Avda. Espioca, 100, 46460 Silla + · www.verdnatura.es · clientes@verdnatura.es +disclaimer: "- AVIS - Ce message est privé et confidentiel et doit être utilisé + exclusivement par le destinataire. Si vous avez reçu ce message par erreur, + veuillez en informer l'expéditeur et supprimer ce message ainsi que tous les + documents joints qu'il pourrait contenir. Verdnatura Levante SL ne renonce pas à la + confidentialité ni aux privilèges résultant d'une transmission erronée ou d'un dysfonctionnement. + De même, il n'est pas responsable des modifications, altérations, erreurs ou + omissions qui pourraient être apportées au message une fois envoyé." +privacy: Conformément aux dispositions de la loi organique 15/1999 sur la protection + des données personnelles, nous vous informons que les données personnelles que + vous fournissez seront incluses dans des dossiers. VERDNATURA LEVANTE S.L., vous + pouvez à tout moment, exercer les droits d'accès, de rectification, d'annulation + et d'opposition, en communiquant par écrit au siège social de la société. Le dossier + a pour objet la gestion administrative, la comptabilité et la facturation. diff --git a/print/core/components/email-footer/locale/pt.yml b/print/core/components/email-footer/locale/pt.yml new file mode 100644 index 000000000..d7267dbaf --- /dev/null +++ b/print/core/components/email-footer/locale/pt.yml @@ -0,0 +1,17 @@ +buttons: + webAcccess: Visite o nosso site + info: Ajude-nos a melhorar +fiscalAddress: VERDNATURA LEVANTE SL, B97367486 Avda. Espioca, 100, 46460 Silla + · www.verdnatura.es · clientes@verdnatura.es +disclaimer: '- AVISO - Esta mensagem é privada e confidencial e deve ser usada exclusivamente + pela pessoa que a recebe. Se você recebeu esta mensagem por engano, notifique o remetente e + exclua essa mensagem e todos os documentos anexos que ela possa conter. + A Verdnatura Levante SL não renuncia à confidencialidade ou a qualquer privilégio devido a + transmissão ou mau funcionamento incorretos. Da mesma forma, não se responsabiliza pelas alterações, + alterações, erros ou omissões que possam ser feitos na mensagem após o envio.' +privacy: Em cumprimento do disposto na lei Orgânica 15/1999, de Protecção de Dados + de Carácter Pessoal, comunicamos que os dados pessoais que facilite se incluirão + nos ficheiros automatizados de VERDNATURA LEVANTE S.L., podendo em todo momento + exercer os direitos de acesso, rectificação, cancelação e oposição, comunicando + por escrito ao domicílio social da entidade. A finalidade do ficheiro é a gestão + administrativa, contabilidade e facturação. diff --git a/print/core/components/email-header/assets/css/import.js b/print/core/components/email-header/assets/css/import.js new file mode 100644 index 000000000..c742fdf90 --- /dev/null +++ b/print/core/components/email-header/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/core/components/email-header/assets/css/style.css b/print/core/components/email-header/assets/css/style.css new file mode 100644 index 000000000..4db5e2b2e --- /dev/null +++ b/print/core/components/email-header/assets/css/style.css @@ -0,0 +1,19 @@ +header .logo { + margin-bottom: 15px; +} + +header .logo img { + width: 50% +} + +header .topbar { + background-color: #95d831; + height: 10px +} + +.topbar:after { + overflow: hidden; + display: block; + content: ' '; + clear: both; +} \ No newline at end of file diff --git a/services/mailer/application/template/footer/image/header.png b/print/core/components/email-header/assets/images/email-logo.png similarity index 100% rename from services/mailer/application/template/footer/image/header.png rename to print/core/components/email-header/assets/images/email-logo.png diff --git a/print/core/components/email-header/assets/images/logo-black.png b/print/core/components/email-header/assets/images/logo-black.png new file mode 100644 index 000000000..e93065d90 Binary files /dev/null and b/print/core/components/email-header/assets/images/logo-black.png differ diff --git a/services/print/application/template/header/image/logo.svg b/print/core/components/email-header/assets/images/logo-black.svg similarity index 100% rename from services/print/application/template/header/image/logo.svg rename to print/core/components/email-header/assets/images/logo-black.svg diff --git a/print/core/components/email-header/assets/images/logo-white.svg b/print/core/components/email-header/assets/images/logo-white.svg new file mode 100644 index 000000000..a4ce32490 --- /dev/null +++ b/print/core/components/email-header/assets/images/logo-white.svg @@ -0,0 +1,131 @@ + + + +image/svg+xml \ No newline at end of file diff --git a/print/core/components/email-header/attachments.json b/print/core/components/email-header/attachments.json new file mode 100644 index 000000000..924eddc4d --- /dev/null +++ b/print/core/components/email-header/attachments.json @@ -0,0 +1,7 @@ +[ + { + "filename": "logo-black.png", + "path": "/assets/images/logo-black.png", + "cid": "logo-black.png" + } +] \ No newline at end of file diff --git a/print/core/components/email-header/email-header.html b/print/core/components/email-header/email-header.html new file mode 100644 index 000000000..87834e2ae --- /dev/null +++ b/print/core/components/email-header/email-header.html @@ -0,0 +1,8 @@ +
    + +
    +
    diff --git a/print/core/components/email-header/email-header.js b/print/core/components/email-header/email-header.js new file mode 100755 index 000000000..0f5a6845d --- /dev/null +++ b/print/core/components/email-header/email-header.js @@ -0,0 +1,3 @@ +module.exports = { + name: 'email-header' +}; diff --git a/print/core/components/report-footer/assets/css/import.js b/print/core/components/report-footer/assets/css/import.js new file mode 100644 index 000000000..a2a9334cb --- /dev/null +++ b/print/core/components/report-footer/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${appPath}/common/css/misc.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/core/components/report-footer/assets/css/style.css b/print/core/components/report-footer/assets/css/style.css new file mode 100644 index 000000000..e7ee162a8 --- /dev/null +++ b/print/core/components/report-footer/assets/css/style.css @@ -0,0 +1,24 @@ +footer { + font-family: "Roboto", "Helvetica", "Arial", sans-serif; + font-size: 0.55em; + color: #555; + zoom: 0.65 +} + +footer, footer p { + text-align: center +} + +p.privacy { + font-size: 0.8em +} + +footer .page { + border-bottom: 2px solid #CCC; + padding-bottom: 2px +} + +footer .page > section { + display: inline-block; + width: 33% +} \ No newline at end of file diff --git a/print/core/components/report-footer/locale/en.yml b/print/core/components/report-footer/locale/en.yml new file mode 100644 index 000000000..404c7e7a4 --- /dev/null +++ b/print/core/components/report-footer/locale/en.yml @@ -0,0 +1,8 @@ +numPages: Page {{page}} of {{pages}} +law: + privacy: 'In compliance with the provisions of Organic Law 15/1999, on the + Protection of Personal Data, we inform you that the personal data you provide + will be included in automated files of VERDNATURA LEVANTE SL, being able at all + times to exercise the rights of access, rectification, cancellation and opposition, + communicating it in writing to the registered office of the entity. + The purpose of the file is administrative management, accounting, and billing.' diff --git a/print/core/components/report-footer/locale/es.yml b/print/core/components/report-footer/locale/es.yml new file mode 100644 index 000000000..39dae8b58 --- /dev/null +++ b/print/core/components/report-footer/locale/es.yml @@ -0,0 +1,8 @@ +numPages: Página {{page}} de {{pages}} +law: + privacy: En cumplimiento de lo dispuesto en la Ley Orgánica 15/1999, de Protección + de Datos de Carácter Personal, le comunicamos que los datos personales que facilite + se incluirán en ficheros automatizados de VERDNATURA LEVANTE S.L., pudiendo en + todo momento ejercitar los derechos de acceso, rectificación, cancelación y oposición, + comunicándolo por escrito al domicilio social de la entidad. La finalidad del + fichero es la gestión administrativa, contabilidad, y facturación. diff --git a/print/core/components/report-footer/locale/fr.yml b/print/core/components/report-footer/locale/fr.yml new file mode 100644 index 000000000..8f2543640 --- /dev/null +++ b/print/core/components/report-footer/locale/fr.yml @@ -0,0 +1,8 @@ +numPages: Page {{page}} de {{pages}} +law: + privacy: Conformément aux dispositions de la loi organique 15/1999 sur la protection + des données personnelles, nous vous informons que les données personnelles que + vous fournissez seront incluses dans des dossiers. VERDNATURA LEVANTE S.L., vous + pouvez à tout moment, exercer les droits d'accès, de rectification, d'annulation + et d'opposition, en communiquant par écrit au siège social de la société. Le dossier + a pour objet la gestion administrative, la comptabilité et la facturation. diff --git a/print/core/components/report-footer/locale/pt.yml b/print/core/components/report-footer/locale/pt.yml new file mode 100644 index 000000000..8b4987bb7 --- /dev/null +++ b/print/core/components/report-footer/locale/pt.yml @@ -0,0 +1,8 @@ +numPages: Página {{page}} de {{pages}} +law: + privacy: Em cumprimento do disposto na lei Orgânica 15/1999, de Protecção de Dados + de Carácter Pessoal, comunicamos que os dados pessoais que facilite se incluirão + nos ficheiros automatizados de VERDNATURA LEVANTE S.L., podendo em todo momento + exercer os direitos de acesso, rectificação, cancelação e oposição, comunicando + por escrito ao domicílio social da entidade. A finalidade do ficheiro é a gestão + administrativa, contabilidade e facturação. diff --git a/print/core/components/report-footer/report-footer.html b/print/core/components/report-footer/report-footer.html new file mode 100644 index 000000000..4e0b7e327 --- /dev/null +++ b/print/core/components/report-footer/report-footer.html @@ -0,0 +1,9 @@ +
    +
    +
    {{leftText}}
    +
    {{centerText}}
    +
    {{$t('numPages')}}
    +
    +

    {{phytosanitary}}

    +

    +
    diff --git a/print/core/components/report-footer/report-footer.js b/print/core/components/report-footer/report-footer.js new file mode 100755 index 000000000..749170a0a --- /dev/null +++ b/print/core/components/report-footer/report-footer.js @@ -0,0 +1,18 @@ +const db = require('../../database'); + +module.exports = { + name: 'report-footer', + async serverPrefetch() { + const companyCode = this.companyCode || 'VNL'; + + this.phytosanitary = await this.getPhytosanitary(companyCode); + }, + methods: { + getPhytosanitary(code) { + return db.findValue(` + SELECT phytosanitary FROM company c + WHERE c.code = :code`, {code}); + } + }, + props: ['companyCode', 'showPhytosanitary', 'leftText', 'centerText'] +}; diff --git a/print/core/components/report-header/assets/css/import.js b/print/core/components/report-header/assets/css/import.js new file mode 100644 index 000000000..a2a9334cb --- /dev/null +++ b/print/core/components/report-header/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${appPath}/common/css/misc.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/core/components/report-header/assets/css/style.css b/print/core/components/report-header/assets/css/style.css new file mode 100644 index 000000000..cb8cd55c0 --- /dev/null +++ b/print/core/components/report-header/assets/css/style.css @@ -0,0 +1,14 @@ +header { + font-family: "Roboto", "Helvetica", "Arial", sans-serif; + border-bottom: 1px solid #DDD; + padding-bottom: 10px; + margin-bottom: 20px; + text-align: center; + font-size: 0.55em; + color: #555 +} + +header img { + margin-bottom: 10px; + width: 350px +} \ No newline at end of file diff --git a/print/core/components/report-header/assets/images/report-logo.png b/print/core/components/report-header/assets/images/report-logo.png new file mode 100644 index 000000000..27c560449 Binary files /dev/null and b/print/core/components/report-header/assets/images/report-logo.png differ diff --git a/services/print/application/template/letter-debtor/image/logo.svg b/print/core/components/report-header/assets/images/report-logo.svg similarity index 100% rename from services/print/application/template/letter-debtor/image/logo.svg rename to print/core/components/report-header/assets/images/report-logo.svg diff --git a/print/core/components/report-header/locale/en.yml b/print/core/components/report-header/locale/en.yml new file mode 100644 index 000000000..334f50ce9 --- /dev/null +++ b/print/core/components/report-header/locale/en.yml @@ -0,0 +1,2 @@ +company: + contactData: www.verdnatura.es - clientes@verdnatura.es \ No newline at end of file diff --git a/print/core/components/report-header/locale/es.yml b/print/core/components/report-header/locale/es.yml new file mode 100644 index 000000000..fe4222eb0 --- /dev/null +++ b/print/core/components/report-header/locale/es.yml @@ -0,0 +1,2 @@ +company: + contactData: www.verdnatura.es - clientes@verdnatura.es diff --git a/print/core/components/report-header/locale/fr.yml b/print/core/components/report-header/locale/fr.yml new file mode 100644 index 000000000..fe4222eb0 --- /dev/null +++ b/print/core/components/report-header/locale/fr.yml @@ -0,0 +1,2 @@ +company: + contactData: www.verdnatura.es - clientes@verdnatura.es diff --git a/print/core/components/report-header/locale/pt.yml b/print/core/components/report-header/locale/pt.yml new file mode 100644 index 000000000..4e138c69c --- /dev/null +++ b/print/core/components/report-header/locale/pt.yml @@ -0,0 +1,2 @@ +company: + contactData: · www.verdnatura.es · clientes@verdnatura.es \ No newline at end of file diff --git a/print/core/components/report-header/report-header.html b/print/core/components/report-header/report-header.html new file mode 100644 index 000000000..2667f14ed --- /dev/null +++ b/print/core/components/report-header/report-header.html @@ -0,0 +1,10 @@ +
    + Verdnatura +
    + {{companyName}}. {{company.street}}. + {{company.postCode}} {{company.city}}. + ☎ {{companyPhone}} + · {{$t('company.contactData')}} +
    +
    CIF: {{fiscalAddress.nif}} {{fiscalAddress.register}}
    +
    diff --git a/print/core/components/report-header/report-header.js b/print/core/components/report-header/report-header.js new file mode 100755 index 000000000..9d501d3ba --- /dev/null +++ b/print/core/components/report-header/report-header.js @@ -0,0 +1,46 @@ +const db = require('../../database'); + +module.exports = { + name: 'report-header', + async serverPrefetch() { + const companyCode = this.companyCode || 'VNL'; + + this.company = await this.getCompany(companyCode); + this.fiscalAddress = await this.getFiscalAddress(companyCode); + }, + computed: { + companyName() { + if (!this.company.name) return; + + return this.company.name.toUpperCase(); + }, + companyPhone() { + if (!this.company.phone) return; + + let phone = this.company.phone; + + if (phone.length >= 13) { + const prefix = parseInt(phone.substr(0, 4)); + const number = phone.substr(5, phone.length); + return `+${prefix} ${number}`; + } else + return phone; + } + }, + methods: { + getCompany(code) { + return db.findOne(` + SELECT s.name, s.street, s.postCode, s.city, s.phone + FROM company c + JOIN supplier s ON s.id = c.id + WHERE c.code = :code`, {code}); + }, + getFiscalAddress(code) { + return db.findOne(` + SELECT nif, register FROM company c + JOIN supplier s ON s.id = c.id + WHERE c.code = :code`, {code}); + } + }, + props: ['companyCode'] +}; diff --git a/print/core/config.js b/print/core/config.js new file mode 100644 index 000000000..864e1658a --- /dev/null +++ b/print/core/config.js @@ -0,0 +1,24 @@ +const fs = require('fs-extra'); +let env = process.env.NODE_ENV ? process.env.NODE_ENV : 'development'; + +let configPath = `/etc/salix`; +let config = require('../config/print.json'); +let configFiles = [ + `${appPath}/config/print.local.json`, + `${appPath}/config/print.${env}.json`, + `${configPath}/print.json`, + `${configPath}/print.local.json`, + `${configPath}/print.${env}.json` +]; + +for (let configFile of configFiles) { + if (fs.existsSync(configFile)) { + const conf = require(configFile); + for (let prop in conf) + Object.assign(config[prop], conf[prop]); + } +} + +config.env = env; + +module.exports = config; diff --git a/print/core/database.js b/print/core/database.js new file mode 100644 index 000000000..a2e6e9573 --- /dev/null +++ b/print/core/database.js @@ -0,0 +1,50 @@ +const mysql = require('mysql2/promise'); +const config = require('./config.js'); + +module.exports = { + init() { + if (!this.pool) { + this.pool = mysql.createPool(config.mysql); + this.pool.on('connection', connection => { + connection.config.namedPlaceholders = true; + }); + } + }, + /** + * Makes a query from a raw sql + * @param {String} query - The raw SQL query + * @param {Object} params - Parameterized values + * + * @return {Object} - Result promise + */ + rawSql(query, params) { + return this.pool.query(query, params).then(([rows]) => { + return rows; + }); + }, + /** + * Returns the first row from a given raw sql + * @param {String} query - The raw SQL query + * @param {Object} params - Parameterized values + * + * @return {Object} - Result promise + */ + findOne(query, params) { + return this.rawSql(query, params).then(([row]) => row); + }, + /** + * Returns the first property from a given raw sql + * @param {String} query - The raw SQL query + * @param {Object} params - Parameterized values + * + * @return {Object} - Result promise + */ + findValue(query, params) { + return this.findOne(query, params).then(row => { + return Object.values(row)[0]; + }); + }, + findFromDef() { + + } +}; diff --git a/print/core/directives/index.js b/print/core/directives/index.js new file mode 100644 index 000000000..3ba4d8895 --- /dev/null +++ b/print/core/directives/index.js @@ -0,0 +1,2 @@ +// Import global directives +require('./pin'); diff --git a/print/core/directives/pin.js b/print/core/directives/pin.js new file mode 100644 index 000000000..bf4bb6e6e --- /dev/null +++ b/print/core/directives/pin.js @@ -0,0 +1,9 @@ +// DIRECTIVES NOT WORKING +const Vue = require('vue'); +Vue.directive('pin', { + bind: function(el, binding, vnode) { + el.style.position = 'fixed'; + el.style.top = binding.value + 'px'; + el.style.backgroundColor = 'red'; + } +}); diff --git a/print/core/email.js b/print/core/email.js new file mode 100644 index 000000000..25d44df65 --- /dev/null +++ b/print/core/email.js @@ -0,0 +1,93 @@ +const path = require('path'); +const smtp = require('./smtp'); +const Component = require('./component'); +const Report = require('./report'); +const db = require('./database'); +const config = require('./config'); + +if (!process.env.OPENSSL_CONF) + process.env.OPENSSL_CONF = '/etc/ssl/'; + +class Email extends Component { + constructor(name, args) { + super(name); + + this.args = args; + } + + get path() { + return `../templates/email/${this.name}`; + } + + + async getSubject() { + if (!this.lang) await this.getLang(); + const locale = this.locale.messages; + const userLocale = locale[this.lang]; + + if (!userLocale) { + const fallbackLocale = config.i18n.fallbackLocale; + + return locale[fallbackLocale].subject; + } + + return userLocale.subject; + } + + async getLang() { + const clientId = this.args.clientId; + const lang = await db.findOne(` + SELECT lang FROM account.user + WHERE id = ?`, [clientId]).then(rows => { + return rows.lang; + }); + this.lang = lang; + } + + async send() { + const instance = this.build(); + const rendered = await this.render(); + const attachments = []; + const getAttachments = async(componentPath, files) => { + for (file of files) { + const fileCopy = Object.assign({}, file); + if (fileCopy.cid) { + const templatePath = `${componentPath}/${file.path}`; + const fullFilePath = path.resolve(__dirname, templatePath); + + fileCopy.path = path.resolve(__dirname, fullFilePath); + } else { + const reportName = fileCopy.filename.replace('.pdf', ''); + const report = new Report(reportName, this.args); + fileCopy.content = await report.toPdfStream(); + } + + attachments.push(fileCopy); + } + }; + + if (instance.components) { + const components = instance.components; + for (let componentName in components) { + const component = components[componentName]; + const componentPath = `./components/${componentName}`; + await getAttachments(componentPath, component.attachments); + } + } + + if (this.attachments) + await getAttachments(this.path, this.attachments); + + const localeSubject = await this.getSubject(); + const options = { + to: this.args.recipient, + subject: localeSubject, + html: rendered, + attachments: attachments + }; + + return smtp.send(options); + } +} + +module.exports = Email; diff --git a/print/core/filters/currency.js b/print/core/filters/currency.js new file mode 100644 index 000000000..ec6808906 --- /dev/null +++ b/print/core/filters/currency.js @@ -0,0 +1,10 @@ +const Vue = require('vue'); +const config = require('../config'); +const defaultLocale = config.i18n.locale; + +Vue.filter('currency', function(value, currency = 'EUR', locale = defaultLocale) { + if (!locale) locale = defaultLocale; + return new Intl.NumberFormat(locale, { + style: 'currency', currency + }).format(parseFloat(value)); +}); diff --git a/print/core/filters/date.js b/print/core/filters/date.js new file mode 100644 index 000000000..0988eda75 --- /dev/null +++ b/print/core/filters/date.js @@ -0,0 +1,6 @@ +const Vue = require('vue'); +const strftime = require('strftime'); + +Vue.filter('date', function(value, specifiers = '%d-%m-%Y') { + return strftime(specifiers, value); +}); diff --git a/print/core/filters/index.js b/print/core/filters/index.js new file mode 100644 index 000000000..1d2eb182c --- /dev/null +++ b/print/core/filters/index.js @@ -0,0 +1,5 @@ +// Import global filters +require('./date'); +require('./uppercase'); +require('./currency'); +require('./percentage'); diff --git a/print/core/filters/percentage.js b/print/core/filters/percentage.js new file mode 100644 index 000000000..078d2fd89 --- /dev/null +++ b/print/core/filters/percentage.js @@ -0,0 +1,12 @@ +const Vue = require('vue'); +const config = require('../config'); +const defaultLocale = config.i18n.locale; + +Vue.filter('percentage', function(value, minFraction = 2, maxFraction = 2, locale = defaultLocale) { + if (!locale) locale = defaultLocale; + return new Intl.NumberFormat(locale, { + style: 'percent', + minimumFractionDigits: minFraction, + maximumFractionDigits: maxFraction + }).format(parseFloat(value)); +}); diff --git a/print/core/filters/uppercase.js b/print/core/filters/uppercase.js new file mode 100644 index 000000000..a4a826070 --- /dev/null +++ b/print/core/filters/uppercase.js @@ -0,0 +1,5 @@ +const Vue = require('vue'); + +Vue.filter('uppercase', function(value) { + return value.toUpperCase(); +}); diff --git a/print/core/mixins/image-src.js b/print/core/mixins/image-src.js new file mode 100644 index 000000000..7fd557410 --- /dev/null +++ b/print/core/mixins/image-src.js @@ -0,0 +1,23 @@ +const Vue = require('vue'); +const config = require('../config'); + +const imageSrc = { + methods: { + getEmailSrc(image) { + let src = `cid:${image}`; + + if (this.isPreview === 'true') + src = `/api/${this.$options.name}/assets/images/${image}`; + + return src; + }, + getReportSrc(image) { + const assetsPath = `${config.app.host}/api/${this.$options.name}`; + const imagePath = `${assetsPath}/assets/images/${image}`; + + return imagePath; + } + } +}; + +Vue.mixin(imageSrc); diff --git a/print/core/mixins/index.js b/print/core/mixins/index.js new file mode 100644 index 000000000..ea8205d75 --- /dev/null +++ b/print/core/mixins/index.js @@ -0,0 +1,4 @@ +// Import global mixins +require('./image-src'); +require('./user-locale'); +require('./prop-validator'); diff --git a/print/core/mixins/prop-validator.js b/print/core/mixins/prop-validator.js new file mode 100644 index 000000000..a73197ebf --- /dev/null +++ b/print/core/mixins/prop-validator.js @@ -0,0 +1,26 @@ +const Vue = require('vue'); +const validator = { + created() { + const props = this.$options.props; + const invalidProps = []; + + for (prop in props) { + const isObject = typeof props[prop] === 'object'; + const isRequired = props[prop].required; + const isNotDefined = this[prop] === undefined; + + if (isObject && isRequired && isNotDefined) + invalidProps.push(prop); + } + + if (invalidProps.length > 0) { + const required = invalidProps.join(', '); + + throw new Error(`Required properties not found [${required}]`); + } + }, + props: ['isPreview'] +}; + + +Vue.mixin(validator); diff --git a/print/core/mixins/user-locale.js b/print/core/mixins/user-locale.js new file mode 100644 index 000000000..f30bc0b28 --- /dev/null +++ b/print/core/mixins/user-locale.js @@ -0,0 +1,31 @@ +const Vue = require('vue'); +const db = require('../database'); +const config = require('../config'); +const fallbackLocale = config.i18n.fallbackLocale; +const userLocale = { + async serverPrefetch() { + if (this.clientId) + this.locale = await this.getLocale(this.clientId); + + if (this.locale) + this.$i18n.locale = this.locale; + }, + methods: { + getLocale(clientId) { + return db.findOne(` + SELECT IF(u.lang IS NOT NULL, u.lang, LOWER(ct.code)) lang + FROM client c + JOIN country ct ON ct.id = c.countryFk + JOIN account.user u ON u.id = c.id + WHERE c.id = ?`, [clientId]).then(rows => { + if (rows) + return rows.lang; + else return fallbackLocale; + }); + } + }, + props: ['clientId'] +}; + + +Vue.mixin(userLocale); diff --git a/print/core/report.js b/print/core/report.js new file mode 100644 index 000000000..db4c9f427 --- /dev/null +++ b/print/core/report.js @@ -0,0 +1,38 @@ +const fs = require('fs'); +const pdf = require('html-pdf'); +const path = require('path'); +const config = require('./config'); +const Component = require('./component'); + +if (!process.env.OPENSSL_CONF) + process.env.OPENSSL_CONF = '/etc/ssl/'; + +class Report extends Component { + constructor(name, args) { + super(name); + + this.args = args; + } + + get path() { + return `../templates/reports/${this.name}`; + } + + async toPdfStream() { + const template = await this.render(); + let options = config.pdf; + + const optionsPath = `${this.path}/options.json`; + const fullPath = path.resolve(__dirname, optionsPath); + if (fs.existsSync(fullPath)) + options = Object.assign(options, require(optionsPath)); + + return new Promise(resolve => { + pdf.create(template, options).toStream((err, stream) => { + resolve(stream); + }); + }); + } +} + +module.exports = Report; diff --git a/print/core/router.js b/print/core/router.js new file mode 100644 index 000000000..f015ac03b --- /dev/null +++ b/print/core/router.js @@ -0,0 +1,6 @@ +module.exports = app => { + // Import methods + require('../methods/closure')(app); + require('../methods/report')(app); + require('../methods/email')(app); +}; diff --git a/print/core/smtp.js b/print/core/smtp.js new file mode 100644 index 000000000..b274eafa3 --- /dev/null +++ b/print/core/smtp.js @@ -0,0 +1,38 @@ +const nodemailer = require('nodemailer'); +const config = require('./config'); +const db = require('./database'); + +module.exports = { + init() { + if (!this.transporter) + this.transporter = nodemailer.createTransport(config.smtp); + }, + + send(options) { + options.from = `${config.app.senderName} <${config.app.senderEmail}>`; + + if (process.env.NODE_ENV !== 'production') { + if (!config.smtp.auth.user) + return Promise.resolve(true); + + options.to = config.app.senderEmail; + } + + let error; + return this.transporter.sendMail(options).catch(err => { + error = err; + + throw err; + }).finally(async() => { + await db.rawSql(` + INSERT INTO vn.mail (sender, replyTo, sent, subject, body, status) + VALUES (:recipient, :sender, 1, :subject, :body, :status)`, { + sender: config.app.senderEmail, + recipient: options.to, + subject: options.subject, + body: options.text || options.html, + status: error && error.message || 'Sent' + }); + }); + } +}; diff --git a/print/core/stylesheet.js b/print/core/stylesheet.js new file mode 100644 index 000000000..ffa141968 --- /dev/null +++ b/print/core/stylesheet.js @@ -0,0 +1,18 @@ +const fs = require('fs-extra'); + +class Stylesheet { + constructor(files) { + this.files = files; + this.css = []; + } + + mergeStyles() { + this.files.forEach(file => { + this.css.push(fs.readFileSync(file)); + }); + + return this.css.join('\n'); + } +} + +module.exports = Stylesheet; diff --git a/print/methods/closure.js b/print/methods/closure.js new file mode 100644 index 000000000..4b25c5abc --- /dev/null +++ b/print/methods/closure.js @@ -0,0 +1,66 @@ +const db = require('../core/database'); +const Email = require('../core/email'); +const smtp = require('../core/smtp'); +const config = require('../core/config'); + +module.exports = app => { + app.get('/api/closure', async function(req, res) { + const failedtickets = []; + const tickets = await db.rawSql(` + SELECT + t.id, + t.clientFk, + c.email recipient + FROM expedition e + JOIN ticket t ON t.id = e.ticketFk + JOIN client c ON c.id = t.clientFk + JOIN warehouse w ON w.id = t.warehouseFk AND hasComission + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + WHERE ts.code = 'PACKED' + AND DATE(t.shipped) BETWEEN DATE_ADD(CURDATE(), INTERVAL -2 DAY) AND CURDATE() + AND t.refFk IS NULL + GROUP BY e.ticketFk`); + + for (const ticket of tickets) { + try { + await db.rawSql(`CALL vn.ticketClosureTicket(:ticketId)`, { + ticketId: ticket.id + }); + + const args = { + ticketId: ticket.id, + clientId: ticket.clientFk, + recipient: ticket.recipient + }; + const email = new Email('delivery-note-link', args); + await email.send(); + } catch (error) { + // Save tickets on a list of failed ids + failedtickets.push({ + id: ticket.id, + stacktrace: error + }); + } + } + + // Send email with failed tickets + if (failedtickets.length > 0) { + let body = 'This following tickets has failed:

    '; + + for (ticket of failedtickets) { + body += `Ticket: ${ticket.id} +
    ${ticket.stacktrace}

    `; + } + + smtp.send({ + to: config.app.reportEmail, + subject: '[API] Nightly ticket closure has failed', + html: body + }); + } + + res.status(200).json({ + message: 'Closure executed successfully' + }); + }); +}; diff --git a/print/methods/email.js b/print/methods/email.js new file mode 100644 index 000000000..a56798820 --- /dev/null +++ b/print/methods/email.js @@ -0,0 +1,32 @@ +const Email = require('../core/email'); + +module.exports = app => { + app.get(`/api/email/:name`, async(req, res, next) => { + const args = req.query; + const requiredArgs = ['clientId', 'recipient']; + const argList = requiredArgs.join(','); + const hasRequiredArgs = requiredArgs.every(arg => { + return args[arg]; + }); + + try { + if (!hasRequiredArgs) + throw new Error(`Required properties not found [${argList}]`); + + const email = new Email(req.params.name, args); + if (args.isPreview === 'true') { + const rendered = await email.render(); + + res.send(rendered); + } else { + await email.send(); + + res.status(200).json({ + message: 'Sent' + }); + } + } catch (e) { + next(e); + } + }); +}; diff --git a/print/methods/report.js b/print/methods/report.js new file mode 100644 index 000000000..626830c39 --- /dev/null +++ b/print/methods/report.js @@ -0,0 +1,24 @@ +const Report = require('../core/report'); + +module.exports = app => { + app.get(`/api/report/:name`, async(req, res, next) => { + const args = req.query; + const requiredArgs = ['clientId']; + const argList = requiredArgs.join(','); + const hasRequiredArgs = requiredArgs.every(arg => { + return args[arg]; + }); + + try { + if (!hasRequiredArgs) + throw new Error(`Required properties not found [${argList}]`); + + const report = new Report(req.params.name, args); + const stream = await report.toPdfStream(); + res.setHeader('Content-type', 'application/pdf'); + stream.pipe(res); + } catch (error) { + next(error); + } + }); +}; diff --git a/print/package-lock.json b/print/package-lock.json new file mode 100644 index 000000000..0704fec0f --- /dev/null +++ b/print/package-lock.json @@ -0,0 +1,1509 @@ +{ + "name": "vn-print", + "version": "2.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "ajv": { + "version": "6.7.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.7.0.tgz", + "integrity": "sha512-RZXPviBTtfmtka9n9sy1N5M5b82CbxWIR6HIis4s3WQTXDJamc/0gpCWNGz6EWdWp4DOfjzJfhz/AS9zVPjjWg==", + "requires": { + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "asn1": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", + "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", + "requires": { + "safer-buffer": "~2.1.0" + } + }, + "assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=" + }, + "async": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/async/-/async-3.1.0.tgz", + "integrity": "sha512-4vx/aaY6j/j3Lw3fbCHNWP0pPaTCew3F6F3hYyl/tHs/ndmV1q7NW9T5yuJ2XAGwdQrP+6Wu20x06U4APo/iQQ==" + }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" + }, + "aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=" + }, + "aws4": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.8.0.tgz", + "integrity": "sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ==" + }, + "bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "requires": { + "tweetnacl": "^0.14.3" + } + }, + "boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha1-aN/1++YMUes3cl6p4+0xDcwed24=" + }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "optional": true + }, + "camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==" + }, + "caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "cheerio": { + "version": "0.22.0", + "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-0.22.0.tgz", + "integrity": "sha1-qbqoYKP5tZWmuBsahocxIe06Jp4=", + "requires": { + "css-select": "~1.2.0", + "dom-serializer": "~0.1.0", + "entities": "~1.1.1", + "htmlparser2": "^3.9.1", + "lodash.assignin": "^4.0.9", + "lodash.bind": "^4.1.4", + "lodash.defaults": "^4.0.1", + "lodash.filter": "^4.4.0", + "lodash.flatten": "^4.2.0", + "lodash.foreach": "^4.3.0", + "lodash.map": "^4.4.0", + "lodash.merge": "^4.4.0", + "lodash.pick": "^4.2.1", + "lodash.reduce": "^4.4.0", + "lodash.reject": "^4.4.0", + "lodash.some": "^4.4.0" + } + }, + "cliui": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", + "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", + "requires": { + "string-width": "^3.1.0", + "strip-ansi": "^5.2.0", + "wrap-ansi": "^5.1.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "requires": { + "ansi-regex": "^4.1.0" + } + } + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + }, + "combined-stream": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.7.tgz", + "integrity": "sha512-brWl9y6vOB1xYPZcpZde3N9zDByXTosAeMDo4p1wzo6UMOX4vumB+TP1RZ76sfE6Md68Q0NJSrE/gbezd4Ul+w==", + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==" + }, + "concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "optional": true, + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", + "optional": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "optional": true, + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + }, + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "css-select": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-1.2.0.tgz", + "integrity": "sha1-KzoRBTnFNV8c2NMUYj6HCxIeyFg=", + "requires": { + "boolbase": "~1.0.0", + "css-what": "2.1", + "domutils": "1.5.1", + "nth-check": "~1.0.1" + } + }, + "css-what": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-2.1.3.tgz", + "integrity": "sha512-a+EPoD+uZiNfh+5fxw2nO9QwFa6nJe2Or35fGY6Ipw1R3R4AGz1d1TEZrCegvw2YTmZ0jXirGYlzxxpYSHwpEg==" + }, + "dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "requires": { + "assert-plus": "^1.0.0" + } + }, + "datauri": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/datauri/-/datauri-2.0.0.tgz", + "integrity": "sha512-zS2HSf9pI5XPlNZgIqJg/wCJpecgU/HA6E/uv2EfaWnW1EiTGLfy/EexTIsC9c99yoCOTXlqeeWk4FkCSuO3/g==", + "requires": { + "image-size": "^0.7.3", + "mimer": "^1.0.0" + } + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "optional": true, + "requires": { + "ms": "2.0.0" + } + }, + "decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=" + }, + "deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==" + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" + }, + "denque": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/denque/-/denque-1.4.1.tgz", + "integrity": "sha512-OfzPuSZKGcgr96rf1oODnfjqBFmr1DVoc/TrItj3Ohe0Ah1C5WX5Baquw/9U9KovnQ88EqmJbD66rKYUQYN1tQ==" + }, + "dijkstrajs": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.1.tgz", + "integrity": "sha1-082BIh4+pAdCz83lVtTpnpjdxxs=" + }, + "dom-serializer": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.1.tgz", + "integrity": "sha512-l0IU0pPzLWSHBcieZbpOKgkIn3ts3vAh7ZuFyXNwJxJXk/c4Gwj9xaTJwIDVQCXawWD0qb3IzMGH5rglQaO0XA==", + "requires": { + "domelementtype": "^1.3.0", + "entities": "^1.1.1" + } + }, + "domelementtype": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz", + "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==" + }, + "domhandler": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.4.2.tgz", + "integrity": "sha512-JiK04h0Ht5u/80fdLMCEmV4zkNh2BcoMFBmZ/91WtYZ8qVXSKjiw7fXMgFPnHcSZgOo3XdinHvmnDUeMf5R4wA==", + "requires": { + "domelementtype": "1" + } + }, + "domutils": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz", + "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=", + "requires": { + "dom-serializer": "0", + "domelementtype": "1" + } + }, + "ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", + "requires": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==" + }, + "entities": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.2.tgz", + "integrity": "sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w==" + }, + "es6-promise": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.5.tgz", + "integrity": "sha512-n6wvpdE43VFtJq+lUDYDBFUwV8TZbuGXLV4D6wKafg13ldznKsyEvatubnmUe31zcvelSzOHF+XbaT+Bl9ObDg==", + "optional": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" + }, + "extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + }, + "extract-zip": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-1.6.7.tgz", + "integrity": "sha1-qEC0uK9kAyZMjbV/Txp0Mz74H+k=", + "optional": true, + "requires": { + "concat-stream": "1.6.2", + "debug": "2.6.9", + "mkdirp": "0.5.1", + "yauzl": "2.4.1" + } + }, + "extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=" + }, + "fast-deep-equal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", + "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=" + }, + "fast-json-stable-stringify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", + "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=" + }, + "fd-slicer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.0.1.tgz", + "integrity": "sha1-i1vL2ewyfFBBv5qwI/1nUPEXfmU=", + "optional": true, + "requires": { + "pend": "~1.2.0" + } + }, + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "requires": { + "locate-path": "^3.0.0" + } + }, + "forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=" + }, + "form-data": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", + "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + } + }, + "fs-extra": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz", + "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", + "requires": { + "graceful-fs": "^4.1.2", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + } + }, + "generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "requires": { + "is-property": "^1.0.2" + } + }, + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" + }, + "getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "requires": { + "assert-plus": "^1.0.0" + } + }, + "graceful-fs": { + "version": "4.1.15", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", + "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==" + }, + "har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=" + }, + "har-validator": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.3.tgz", + "integrity": "sha512-sNvOCzEQNr/qrvJgc3UG/kD4QtlHycrzwS+6mfTrrSq97BvaYcPZZI1ZSqGSPR73Cxn4LKTD4PttRwfU7jWq5g==", + "requires": { + "ajv": "^6.5.5", + "har-schema": "^2.0.0" + } + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + }, + "hash-sum": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/hash-sum/-/hash-sum-1.0.2.tgz", + "integrity": "sha1-M7QHd3VMZDJXPBIMw4CLvRDUfwQ=" + }, + "hasha": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/hasha/-/hasha-2.2.0.tgz", + "integrity": "sha1-eNfL/B5tZjA/55g3NlmEUXsvbuE=", + "optional": true, + "requires": { + "is-stream": "^1.0.1", + "pinkie-promise": "^2.0.0" + } + }, + "he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==" + }, + "html-pdf": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/html-pdf/-/html-pdf-2.2.0.tgz", + "integrity": "sha1-S8+Rwky1YOR6o/rP0DPg4b8kG5E=", + "requires": { + "phantomjs-prebuilt": "^2.1.4" + } + }, + "htmlparser2": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.10.1.tgz", + "integrity": "sha512-IgieNijUMbkDovyoKObU1DUhm1iwNYE/fuifEoEHfd1oZKZDaONBSkal7Y01shxsM49R4XaMdGez3WnF9UfiCQ==", + "requires": { + "domelementtype": "^1.3.1", + "domhandler": "^2.3.0", + "domutils": "^1.5.1", + "entities": "^1.1.1", + "inherits": "^2.0.1", + "readable-stream": "^3.1.1" + } + }, + "http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "requires": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + } + }, + "iconv-lite": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.5.0.tgz", + "integrity": "sha512-NnEhI9hIEKHOzJ4f697DMz9IQEXr/MMJ5w64vN2/4Ai+wRnvV7SBrL0KLoRlwaKVghOc7LQ5YkPLuX146b6Ydw==", + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "image-size": { + "version": "0.7.5", + "resolved": "https://registry.npmjs.org/image-size/-/image-size-0.7.5.tgz", + "integrity": "sha512-Hiyv+mXHfFEP7LzUL/llg9RwFxxY+o9N3JVLIeG5E7iFIFAalxvRU9UZthBdYDEVnzHMgjnKJPPpay5BWf1g9g==" + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + }, + "intl": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/intl/-/intl-1.2.5.tgz", + "integrity": "sha1-giRKIZDE5Bn4Nx9ao02qNCDiq94=" + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=" + }, + "is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha1-V/4cTkhHTt1lsJkR8msc1Ald2oQ=" + }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", + "optional": true + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "optional": true + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" + }, + "js-yaml": { + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=" + }, + "json-schema": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", + "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=" + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" + }, + "json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "requires": { + "graceful-fs": "^4.1.6" + } + }, + "jsprim": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", + "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.2.3", + "verror": "1.10.0" + } + }, + "juice": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/juice/-/juice-5.2.0.tgz", + "integrity": "sha512-0l6GZmT3efexyaaay3SchKT5kG311N59TEFP5lfvEy0nz9SNqjx311plJ3b4jze7arsmDsiHQLh/xnAuk0HFTQ==", + "requires": { + "cheerio": "^0.22.0", + "commander": "^2.15.1", + "cross-spawn": "^6.0.5", + "deep-extend": "^0.6.0", + "mensch": "^0.3.3", + "slick": "^1.12.2", + "web-resource-inliner": "^4.3.1" + } + }, + "kew": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/kew/-/kew-0.7.0.tgz", + "integrity": "sha1-edk9LTM2PW/dKXCzNdkUGtWR15s=", + "optional": true + }, + "klaw": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/klaw/-/klaw-1.3.1.tgz", + "integrity": "sha1-QIhDO0azsbolnXh4XY6W9zugJDk=", + "optional": true, + "requires": { + "graceful-fs": "^4.1.9" + } + }, + "locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "lodash._reinterpolate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz", + "integrity": "sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=" + }, + "lodash.assignin": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.assignin/-/lodash.assignin-4.2.0.tgz", + "integrity": "sha1-uo31+4QesKPoBEIysOJjqNxqKKI=" + }, + "lodash.bind": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/lodash.bind/-/lodash.bind-4.2.1.tgz", + "integrity": "sha1-euMBfpOWIqwxt9fX3LGzTbFpDTU=" + }, + "lodash.defaults": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", + "integrity": "sha1-0JF4cW/+pN3p5ft7N/bwgCJ0WAw=" + }, + "lodash.filter": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.filter/-/lodash.filter-4.6.0.tgz", + "integrity": "sha1-ZosdSYFgOuHMWm+nYBQ+SAtMSs4=" + }, + "lodash.flatten": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz", + "integrity": "sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8=" + }, + "lodash.foreach": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.foreach/-/lodash.foreach-4.5.0.tgz", + "integrity": "sha1-Gmo16s5AEoDH8G3d7DUWWrJ+PlM=" + }, + "lodash.map": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.map/-/lodash.map-4.6.0.tgz", + "integrity": "sha1-dx7Hg540c9nEzeKLGTlMNWL09tM=" + }, + "lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==" + }, + "lodash.pick": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/lodash.pick/-/lodash.pick-4.4.0.tgz", + "integrity": "sha1-UvBWEP/53tQiYRRB7R/BI6AwAbM=" + }, + "lodash.reduce": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.reduce/-/lodash.reduce-4.6.0.tgz", + "integrity": "sha1-8atrg5KZrUj3hKu/R2WW8DuRTTs=" + }, + "lodash.reject": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.reject/-/lodash.reject-4.6.0.tgz", + "integrity": "sha1-gNZJLcFHCGS79YNTO2UfQqn1JBU=" + }, + "lodash.some": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.some/-/lodash.some-4.6.0.tgz", + "integrity": "sha1-G7nzFO9ri63tE7VJFpsqlF62jk0=" + }, + "lodash.template": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-4.5.0.tgz", + "integrity": "sha512-84vYFxIkmidUiFxidA/KjjH9pAycqW+h980j7Fuz5qxRtO9pgB7MDFTdys1N7A5mcucRiDyEq4fusljItR1T/A==", + "requires": { + "lodash._reinterpolate": "^3.0.0", + "lodash.templatesettings": "^4.0.0" + } + }, + "lodash.templatesettings": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.templatesettings/-/lodash.templatesettings-4.2.0.tgz", + "integrity": "sha512-stgLz+i3Aa9mZgnjr/O+v9ruKZsPsndy7qPZOchbqk2cnTU1ZaldKK+v7m54WoKIyxiuMZTKT2H81F8BeAc3ZQ==", + "requires": { + "lodash._reinterpolate": "^3.0.0" + } + }, + "lodash.unescape": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.unescape/-/lodash.unescape-4.0.1.tgz", + "integrity": "sha1-vyJJiGzlFM2hEvrpIYzcBlIR/Jw=" + }, + "lodash.uniq": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", + "integrity": "sha1-0CJTc662Uq3BvILklFM5qEJ1R3M=" + }, + "long": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", + "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" + }, + "lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "requires": { + "yallist": "^3.0.2" + } + }, + "mensch": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/mensch/-/mensch-0.3.3.tgz", + "integrity": "sha1-4gD/TdgjcX+OBWOzLj9UgfyiYrI=" + }, + "mime-db": { + "version": "1.37.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.37.0.tgz", + "integrity": "sha512-R3C4db6bgQhlIhPU48fUtdVmKnflq+hRdad7IyKhtFj06VPNVdk2RhiYL3UjQIlso8L+YxAtFkobT0VK+S/ybg==" + }, + "mime-types": { + "version": "2.1.21", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.21.tgz", + "integrity": "sha512-3iL6DbwpyLzjR3xHSFNFeb9Nz/M8WDkX33t1GFQnFOllWk8pOrh/LSrB5OXlnlW5P9LH73X6loW/eogc+F5lJg==", + "requires": { + "mime-db": "~1.37.0" + } + }, + "mimer": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/mimer/-/mimer-1.0.0.tgz", + "integrity": "sha512-4ZJvCzfcwsBgPbkKXUzGoVZMWjv8IDIygkGzVc7uUYhgnK0t2LmGxxjdgH1i+pn0/KQfB5F/VKUJlfyTSOFQjg==" + }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "optional": true + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "optional": true, + "requires": { + "minimist": "0.0.8" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "optional": true + }, + "mysql2": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-1.7.0.tgz", + "integrity": "sha512-xTWWQPjP5rcrceZQ7CSTKR/4XIDeH/cRkNH/uzvVGQ7W5c7EJ0dXeJUusk7OKhIoHj7uFKUxDVSCfLIl+jluog==", + "requires": { + "denque": "^1.4.1", + "generate-function": "^2.3.1", + "iconv-lite": "^0.5.0", + "long": "^4.0.0", + "lru-cache": "^5.1.1", + "named-placeholders": "^1.1.2", + "seq-queue": "^0.0.5", + "sqlstring": "^2.3.1" + } + }, + "named-placeholders": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.2.tgz", + "integrity": "sha512-wiFWqxoLL3PGVReSZpjLVxyJ1bRqe+KKJVbr4hGs1KWfTZTQyezHFBbuKj9hsizHyGV2ne7EMjHdxEGAybD5SA==", + "requires": { + "lru-cache": "^4.1.3" + }, + "dependencies": { + "lru-cache": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", + "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=" + } + } + }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==" + }, + "nodemailer": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-4.7.0.tgz", + "integrity": "sha512-IludxDypFpYw4xpzKdMAozBSkzKHmNBvGanUREjJItgJ2NYcK/s8+PggVhj7c2yGFQykKsnnmv1+Aqo0ZfjHmw==" + }, + "nth-check": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-1.0.2.tgz", + "integrity": "sha512-WeBOdju8SnzPN5vTUJYxYUxLeXpCaVP5i5e0LF8fg7WORF2Wd7wFX/pk0tYZk7s8T+J7VLy0Da6J1+wCT0AtHg==", + "requires": { + "boolbase": "~1.0.0" + } + }, + "oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==" + }, + "p-limit": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.1.tgz", + "integrity": "sha512-85Tk+90UCVWvbDavCLKPOLC9vvY8OwEX/RtKF+/1OADJMVlFfEHOiMTPVyxg7mk/dKa+ipdHm0OUkTvCpMTuwg==", + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "requires": { + "p-limit": "^2.0.0" + } + }, + "p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==" + }, + "path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=" + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=" + }, + "path-parse": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", + "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==" + }, + "pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha1-elfrVQpng/kRUzH89GY9XI4AelA=", + "optional": true + }, + "performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=" + }, + "phantomjs-prebuilt": { + "version": "2.1.16", + "resolved": "https://registry.npmjs.org/phantomjs-prebuilt/-/phantomjs-prebuilt-2.1.16.tgz", + "integrity": "sha1-79ISpKOWbTZHaE6ouniFSb4q7+8=", + "optional": true, + "requires": { + "es6-promise": "^4.0.3", + "extract-zip": "^1.6.5", + "fs-extra": "^1.0.0", + "hasha": "^2.2.0", + "kew": "^0.7.0", + "progress": "^1.1.8", + "request": "^2.81.0", + "request-progress": "^2.0.1", + "which": "^1.2.10" + }, + "dependencies": { + "fs-extra": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-1.0.0.tgz", + "integrity": "sha1-zTzl9+fLYUWIP8rjGR6Yd/hYeVA=", + "optional": true, + "requires": { + "graceful-fs": "^4.1.2", + "jsonfile": "^2.1.0", + "klaw": "^1.0.0" + } + }, + "jsonfile": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-2.4.0.tgz", + "integrity": "sha1-NzaitCi4e72gzIO1P6PWM6NcKug=", + "optional": true, + "requires": { + "graceful-fs": "^4.1.6" + } + } + } + }, + "pinkie": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", + "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=", + "optional": true + }, + "pinkie-promise": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", + "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", + "optional": true, + "requires": { + "pinkie": "^2.0.0" + } + }, + "pngjs": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-3.4.0.tgz", + "integrity": "sha512-NCrCHhWmnQklfH4MtJMRjZ2a8c80qXeMlQMv2uVp9ISJMTt562SbGd6n2oq0PaPgKm7Z6pL9E2UlLIhC+SHL3w==" + }, + "process-nextick-args": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", + "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==", + "optional": true + }, + "progress": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/progress/-/progress-1.1.8.tgz", + "integrity": "sha1-4mDHj2Fhzdmw5WzD4Khd4Xx6V74=", + "optional": true + }, + "pseudomap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", + "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=" + }, + "psl": { + "version": "1.1.31", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.1.31.tgz", + "integrity": "sha512-/6pt4+C+T+wZUieKR620OpzN/LlnNKuWjy1iFLQ/UG35JqHlR/89MP1d96dUfkf6Dne3TuLQzOYEYshJ+Hx8mw==" + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" + }, + "qrcode": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.4.2.tgz", + "integrity": "sha512-eR6RgxFYPDFH+zFLTJKtoNP/RlsHANQb52AUmQ2bGDPMuUw7jJb0F+DNEgx7qQGIElrbFxWYMc0/B91zLZPF9Q==", + "requires": { + "dijkstrajs": "^1.0.1", + "isarray": "^2.0.1", + "pngjs": "^3.3.0", + "yargs": "^13.2.4" + }, + "dependencies": { + "isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==" + } + } + }, + "qs": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", + "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==" + }, + "readable-stream": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.4.0.tgz", + "integrity": "sha512-jItXPLmrSR8jmTRmRWJXCnGJsfy85mB3Wd/uINMXA65yrnFo0cPClFIUWzo2najVNSl+mx7/4W8ttlLWJe99pQ==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + }, + "request": { + "version": "2.88.0", + "resolved": "https://registry.npmjs.org/request/-/request-2.88.0.tgz", + "integrity": "sha512-NAqBSrijGLZdM0WZNsInLJpkJokL72XYjUpnB0iwsRgxh7dB6COrHnTBNwN0E+lHDAJzu7kLAkDeY08z2/A0hg==", + "requires": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.0", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.4.3", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + } + }, + "request-progress": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/request-progress/-/request-progress-2.0.1.tgz", + "integrity": "sha1-XTa7V5YcZzqlt4jbyBQf3yO0Tgg=", + "optional": true, + "requires": { + "throttleit": "^1.0.0" + } + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=" + }, + "require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" + }, + "resolve": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.12.0.tgz", + "integrity": "sha512-B/dOmuoAik5bKcD6s6nXDCjzUKnaDvdkRyAk6rsmsKLipWj4797iothd7jmmUhWTfinVMU+wc56rYKsit2Qy4w==", + "requires": { + "path-parse": "^1.0.6" + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + }, + "seq-queue": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz", + "integrity": "sha1-1WgS4cAXpuTnw+Ojeh2m143TyT4=" + }, + "serialize-javascript": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-1.9.1.tgz", + "integrity": "sha512-0Vb/54WJ6k5v8sSWN09S0ora+Hnr+cX40r9F170nT+mSkaxltoE/7R3OrIdBSUv1OoiobH1QoWQbCnAO+e8J1A==" + }, + "set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=" + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=" + }, + "slick": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/slick/-/slick-1.12.2.tgz", + "integrity": "sha1-vQSN23TefRymkV+qSldXCzVQwtc=" + }, + "source-map": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.6.tgz", + "integrity": "sha1-dc449SvwczxafwwRjYEzSiu19BI=" + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" + }, + "sqlstring": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz", + "integrity": "sha1-R1OT/56RR5rqYtyvDKPRSYOn+0A=" + }, + "sshpk": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.0.tgz", + "integrity": "sha512-Zhev35/y7hRMcID/upReIvRse+I9SVhyVre/KTJSJQWMz3C3+G+HpO7m1wK/yckEtujKZ7dS4hkVxAnmHaIGVQ==", + "requires": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + } + }, + "strftime": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/strftime/-/strftime-0.10.0.tgz", + "integrity": "sha1-s/D6QZKVICpaKJ9ta+n0kJphcZM=" + }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "requires": { + "ansi-regex": "^4.1.0" + } + } + } + }, + "string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "requires": { + "safe-buffer": "~5.2.0" + }, + "dependencies": { + "safe-buffer": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", + "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==" + } + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + }, + "throttleit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/throttleit/-/throttleit-1.0.0.tgz", + "integrity": "sha1-nnhYNtr0Z0MUWlmEtiaNgoUorGw=", + "optional": true + }, + "tough-cookie": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.4.3.tgz", + "integrity": "sha512-Q5srk/4vDM54WJsJio3XNn6K2sCG+CQ8G5Wz6bZhRZoAe/+TxjWB/GlFAnYEbkYVlON9FMk/fE3h2RLpPXo4lQ==", + "requires": { + "psl": "^1.1.24", + "punycode": "^1.4.1" + }, + "dependencies": { + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=" + } + } + }, + "tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=" + }, + "typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", + "optional": true + }, + "universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==" + }, + "uri-js": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", + "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", + "requires": { + "punycode": "^2.1.0" + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + }, + "uuid": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", + "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==" + }, + "valid-data-url": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/valid-data-url/-/valid-data-url-2.0.0.tgz", + "integrity": "sha512-dyCZnv3aCey7yfTgIqdZanKl7xWAEEKCbgmR7SKqyK6QT/Z07ROactrgD1eA37C69ODRj7rNOjzKWVPh0EUjBA==" + }, + "verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "requires": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "vue": { + "version": "2.6.10", + "resolved": "https://registry.npmjs.org/vue/-/vue-2.6.10.tgz", + "integrity": "sha512-ImThpeNU9HbdZL3utgMCq0oiMzAkt1mcgy3/E6zWC/G6AaQoeuFdsl9nDhTDU3X1R6FK7nsIUuRACVcjI+A2GQ==" + }, + "vue-i18n": { + "version": "8.15.0", + "resolved": "https://registry.npmjs.org/vue-i18n/-/vue-i18n-8.15.0.tgz", + "integrity": "sha512-juJ/avAP39bOMycC+qQDLJ8U9z9LtLF/9PsRoJLBSfsYZo9bqYntyyX5QPicwlb1emJKjgxhZ3YofHiQcXBu0Q==" + }, + "vue-server-renderer": { + "version": "2.6.10", + "resolved": "https://registry.npmjs.org/vue-server-renderer/-/vue-server-renderer-2.6.10.tgz", + "integrity": "sha512-UYoCEutBpKzL2fKCwx8zlRtRtwxbPZXKTqbl2iIF4yRZUNO/ovrHyDAJDljft0kd+K0tZhN53XRHkgvCZoIhug==", + "requires": { + "chalk": "^1.1.3", + "hash-sum": "^1.0.2", + "he": "^1.1.0", + "lodash.template": "^4.4.0", + "lodash.uniq": "^4.5.0", + "resolve": "^1.2.0", + "serialize-javascript": "^1.3.0", + "source-map": "0.5.6" + }, + "dependencies": { + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" + }, + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" + } + } + }, + "web-resource-inliner": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/web-resource-inliner/-/web-resource-inliner-4.3.3.tgz", + "integrity": "sha512-Qk19pohqZs3SoFUW4ZlOHlM8hsOnXhTpCrQ16b1qtJtKzJgO7NZLGP+/lcb2g3hWDQD39/LE/JYOn1Sjy7tn1A==", + "requires": { + "async": "^3.1.0", + "chalk": "^2.4.2", + "datauri": "^2.0.0", + "htmlparser2": "^3.9.2", + "lodash.unescape": "^4.0.1", + "request": "^2.78.0", + "safer-buffer": "^2.1.2", + "valid-data-url": "^2.0.0", + "xtend": "^4.0.2" + } + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "requires": { + "isexe": "^2.0.0" + } + }, + "which-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=" + }, + "wrap-ansi": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "requires": { + "ansi-styles": "^3.2.0", + "string-width": "^3.0.0", + "strip-ansi": "^5.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "requires": { + "ansi-regex": "^4.1.0" + } + } + } + }, + "xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==" + }, + "y18n": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", + "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==" + }, + "yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==" + }, + "yargs": { + "version": "13.3.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.0.tgz", + "integrity": "sha512-2eehun/8ALW8TLoIl7MVaRUrg+yCnenu8B4kBlRxj3GJGDKU1Og7sMXPNm1BYyM1DOJmTZ4YeN/Nwxv+8XJsUA==", + "requires": { + "cliui": "^5.0.0", + "find-up": "^3.0.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^3.0.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^13.1.1" + } + }, + "yargs-parser": { + "version": "13.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.1.tgz", + "integrity": "sha512-oVAVsHz6uFrg3XQheFII8ESO2ssAf9luWuAd6Wexsu4F3OtIW0o8IribPXYrD4WC24LWtPrJlGy87y5udK+dxQ==", + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + }, + "yauzl": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.4.1.tgz", + "integrity": "sha1-lSj0QtqxsihOWLQ3m7GU4i4MQAU=", + "optional": true, + "requires": { + "fd-slicer": "~1.0.1" + } + } + } +} diff --git a/print/package.json b/print/package.json new file mode 100755 index 000000000..971e74c74 --- /dev/null +++ b/print/package.json @@ -0,0 +1,29 @@ +{ + "name": "vn-print", + "version": "2.0.0", + "description": "Print service", + "main": "server/server.js", + "scripts": { + "start": "node server/server.js", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://git.verdnatura.es/salix" + }, + "license": "GPL-3.0", + "dependencies": { + "fs-extra": "^7.0.1", + "html-pdf": "^2.2.0", + "intl": "^1.2.5", + "js-yaml": "^3.13.1", + "juice": "^5.2.0", + "mysql2": "^1.7.0", + "nodemailer": "^4.7.0", + "qrcode": "^1.4.2", + "strftime": "^0.10.0", + "vue": "^2.6.10", + "vue-i18n": "^8.15.0", + "vue-server-renderer": "^2.6.10" + } +} diff --git a/print/templates/email/buyer-week-waste/assets/css/import.js b/print/templates/email/buyer-week-waste/assets/css/import.js new file mode 100644 index 000000000..c742fdf90 --- /dev/null +++ b/print/templates/email/buyer-week-waste/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/email/buyer-week-waste/assets/css/style.css b/print/templates/email/buyer-week-waste/assets/css/style.css new file mode 100644 index 000000000..5db85befa --- /dev/null +++ b/print/templates/email/buyer-week-waste/assets/css/style.css @@ -0,0 +1,5 @@ +.external-link { + border: 2px dashed #8dba25; + border-radius: 3px; + text-align: center +} \ No newline at end of file diff --git a/print/templates/email/buyer-week-waste/buyer-week-waste.html b/print/templates/email/buyer-week-waste/buyer-week-waste.html new file mode 100644 index 000000000..b9ebd6175 --- /dev/null +++ b/print/templates/email/buyer-week-waste/buyer-week-waste.html @@ -0,0 +1,76 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    {{ $t('title') }}

    +

    {{$t('dear')}},

    +

    +
    +
    + +
    +
    + + + + + + + + + + + + + + + + + +
    {{$t('buyer')}}{{$t('percentage')}}{{$t('dwindle')}}{{$t('total')}}
    {{waste.buyer}}{{(waste.percentage / 100) | percentage(2, 2, locale)}}{{waste.dwindle | currency('EUR', locale)}}{{waste.total | currency('EUR', locale)}}
    +

    + +
    +
    + + +
    +
    + +
    +
    + +
    +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/email/buyer-week-waste/buyer-week-waste.js b/print/templates/email/buyer-week-waste/buyer-week-waste.js new file mode 100755 index 000000000..4639e7d5b --- /dev/null +++ b/print/templates/email/buyer-week-waste/buyer-week-waste.js @@ -0,0 +1,31 @@ +const Component = require(`${appPath}/core/component`); +const db = require(`${appPath}/core/database`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); + +module.exports = { + name: 'buyer-week-waste', + async serverPrefetch() { + this.wastes = await this.fetchWastes(); + + if (!this.wastes) + throw new Error('Something went wrong'); + }, + computed: { + dated: function() { + const filters = this.$options.filters; + + return filters.date(new Date(), '%d-%m-%Y'); + } + }, + methods: { + fetchWastes() { + return db.findOne(`CALL bs.weekWaste()`); + } + }, + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build() + }, + props: {} +}; diff --git a/print/templates/email/buyer-week-waste/locale/es.yml b/print/templates/email/buyer-week-waste/locale/es.yml new file mode 100644 index 000000000..d4220dd91 --- /dev/null +++ b/print/templates/email/buyer-week-waste/locale/es.yml @@ -0,0 +1,9 @@ +subject: Merma semanal +title: Merma semanal +dear: Hola +description: A continuación se muestra la merma semanal a fecha de {0}. +buyer: Comprador +percentage: Porcentaje +dwindle: Merma +total: Total +wasteDetailLink: 'Para ver el desglose de mermas haz clic en el siguiente enlace:' \ No newline at end of file diff --git a/print/templates/email/campaign-metrics/assets/css/import.js b/print/templates/email/campaign-metrics/assets/css/import.js new file mode 100644 index 000000000..b44d6bd37 --- /dev/null +++ b/print/templates/email/campaign-metrics/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/campaign-metrics/attachments.json b/print/templates/email/campaign-metrics/attachments.json new file mode 100644 index 000000000..3f6a93bb5 --- /dev/null +++ b/print/templates/email/campaign-metrics/attachments.json @@ -0,0 +1,6 @@ +[ + { + "filename": "campaing-metrics", + "component": "campaign-metrics" + } +] \ No newline at end of file diff --git a/print/templates/email/campaign-metrics/campaign-metrics.html b/print/templates/email/campaign-metrics/campaign-metrics.html new file mode 100644 index 000000000..238d80d4a --- /dev/null +++ b/print/templates/email/campaign-metrics/campaign-metrics.html @@ -0,0 +1,46 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    {{ $t('title') }}

    +

    {{$t('dear')}},

    +

    {{$t('description')}}

    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/email/campaign-metrics/campaign-metrics.js b/print/templates/email/campaign-metrics/campaign-metrics.js new file mode 100755 index 000000000..cb01ca09e --- /dev/null +++ b/print/templates/email/campaign-metrics/campaign-metrics.js @@ -0,0 +1,23 @@ +const Component = require(`${appPath}/core/component`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); + +module.exports = { + name: 'campaign-metrics', + + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build() + }, + props: { + clientId: { + required: true + }, + from: { + required: true + }, + to: { + required: true + } + } +}; diff --git a/print/templates/email/campaign-metrics/locale/es.yml b/print/templates/email/campaign-metrics/locale/es.yml new file mode 100644 index 000000000..e662ca614 --- /dev/null +++ b/print/templates/email/campaign-metrics/locale/es.yml @@ -0,0 +1,7 @@ +subject: Informe consumo campaña +title: Informe consumo campaña +dear: Estimado cliente +description: Con motivo de esta próxima campaña, me complace + relacionarle a continuación el consumo que nos consta en su cuenta para las + mismas fechas del año pasado. Espero le sea de utilidad para preparar su pedido. + Al mismo tiempo aprovecho la ocasión para saludarle cordialmente. diff --git a/print/templates/email/claim-pickup-order/assets/css/import.js b/print/templates/email/claim-pickup-order/assets/css/import.js new file mode 100644 index 000000000..b44d6bd37 --- /dev/null +++ b/print/templates/email/claim-pickup-order/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/claim-pickup-order/attachments.json b/print/templates/email/claim-pickup-order/attachments.json new file mode 100644 index 000000000..5d7c15fb9 --- /dev/null +++ b/print/templates/email/claim-pickup-order/attachments.json @@ -0,0 +1,6 @@ +[ + { + "filename": "claim-pickup-order.pdf", + "component": "claim-pickup" + } +] \ No newline at end of file diff --git a/print/templates/email/claim-pickup-order/claim-pickup-order.html b/print/templates/email/claim-pickup-order/claim-pickup-order.html new file mode 100644 index 000000000..b00338467 --- /dev/null +++ b/print/templates/email/claim-pickup-order/claim-pickup-order.html @@ -0,0 +1,46 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    {{ $t('title') }}

    +

    {{$t('description.dear')}},

    +

    {{$t('description.instructions')}}

    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/email/claim-pickup-order/claim-pickup-order.js b/print/templates/email/claim-pickup-order/claim-pickup-order.js new file mode 100755 index 000000000..4396b144a --- /dev/null +++ b/print/templates/email/claim-pickup-order/claim-pickup-order.js @@ -0,0 +1,16 @@ +const Component = require(`${appPath}/core/component`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); + +module.exports = { + name: 'claim-pickup-order', + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build() + }, + props: { + claimId: { + required: true + } + } +}; diff --git a/print/templates/email/claim-pickup-order/locale/es.yml b/print/templates/email/claim-pickup-order/locale/es.yml new file mode 100644 index 000000000..1d49b2b2b --- /dev/null +++ b/print/templates/email/claim-pickup-order/locale/es.yml @@ -0,0 +1,23 @@ +subject: Orden de recogida +title: Orden de recogida +description: + dear: Estimado cliente + instructions: Aqui tienes tu orden de recogida. +sections: + howToBuy: + title: Cómo hacer un pedido + description: 'Para realizar un pedido en nuestra web, debes configurarlo indicando:' + requeriments: + - Si quieres recibir el pedido (por agencia o por nuestro propio reparto) o si + lo prefieres recoger en alguno de nuestros almacenes. + - La fecha en la que quieres recibir el pedido (se preparará el día anterior). + - La dirección de entrega o el almacén donde quieres recoger el pedido. + stock: En nuestra web y aplicaciones puedes visualizar el stock disponible de + flor cortada, verdes, plantas, complementos y artificial. Ten en cuenta que + dicho stock puede variar en función de la fecha seleccionada al configurar el + pedido. Es importante CONFIRMAR los pedidos para que la mercancía quede reservada. + delivery: El reparto se realiza de lunes a sábado según la zona en la que te encuentres. + Por regla general, los pedidos que se entregan por agencia, deben estar confirmados + y pagados antes de las 17h del día en que se preparan (el día anterior a recibirlos), + aunque esto puede variar si el pedido se envía a través de nuestro reparto y + según la zona. diff --git a/print/templates/email/client-welcome/assets/css/import.js b/print/templates/email/client-welcome/assets/css/import.js new file mode 100644 index 000000000..b44d6bd37 --- /dev/null +++ b/print/templates/email/client-welcome/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/client-welcome/client-welcome.html b/print/templates/email/client-welcome/client-welcome.html new file mode 100644 index 000000000..c5f203621 --- /dev/null +++ b/print/templates/email/client-welcome/client-welcome.html @@ -0,0 +1,92 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    {{ $t('title') }}

    +

    {{$t('dearClient')}},

    +

    + +

    +

    {{$t('clientId')}}: {{client.id}}
    +
    {{$t('user')}}: {{client.userName}}
    +
    {{$t('password')}}: ******** + ({{$t('passwordResetText')}}) +
    +

    + +

    {{$t('sections.howToBuy.title')}}

    +

    {{$t('sections.howToBuy.description')}}

    +
      +
    1. + +
    2. +
    +

    {{$t('sections.howToBuy.stock')}}

    +

    {{$t('sections.howToBuy.delivery')}}

    + +

    {{$t('sections.howToPay.title')}}

    +

    {{$t('sections.howToPay.description')}}

    +
      +
    • + +
    • +
    + +

    {{$t('sections.toConsider.title')}}

    +

    {{$t('sections.toConsider.description')}}

    + +

    {{$t('sections.claimsPolicy.title')}}

    +

    {{$t('sections.claimsPolicy.description')}}

    + +

    +

    +

    + {{$t('salesPersonName')}}: {{client.salesPersonName}} +
    +
    + {{$t('salesPersonPhone')}}: {{client.salesPersonPhone}} +
    +
    + {{$t('salesPersonEmail')}}: + {{client.salesPersonEmail}} +
    +

    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/email/client-welcome/client-welcome.js b/print/templates/email/client-welcome/client-welcome.js new file mode 100755 index 000000000..35b373bc4 --- /dev/null +++ b/print/templates/email/client-welcome/client-welcome.js @@ -0,0 +1,36 @@ +const Component = require(`${appPath}/core/component`); +const db = require(`${appPath}/core/database`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); + +module.exports = { + name: 'client-welcome', + async serverPrefetch() { + this.client = await this.fetchClient(this.clientId); + }, + methods: { + fetchClient(clientId) { + return db.findOne(` + SELECT + c.id, + u.name AS userName, + CONCAT(w.lastName, ' ', w.firstName) salesPersonName, + w.phone AS salesPersonPhone, + CONCAT(wu.name, '@verdnatura.es') AS salesPersonEmail + FROM client c + JOIN account.user u ON u.id = c.id + LEFT JOIN worker w ON w.id = c.salesPersonFk + LEFT JOIN account.user wu ON wu.id = w.userFk + WHERE c.id = ?`, [clientId]); + }, + }, + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build() + }, + props: { + clientId: { + required: true + } + } +}; diff --git a/print/templates/email/client-welcome/locale/es.yml b/print/templates/email/client-welcome/locale/es.yml new file mode 100644 index 000000000..ac43a7cc6 --- /dev/null +++ b/print/templates/email/client-welcome/locale/es.yml @@ -0,0 +1,55 @@ +subject: Bienvenido a Verdnatura +title: "¡Te damos la bienvenida!" +dearClient: Estimado cliente +clientData: 'Tus datos para poder comprar en la web de Verdnatura (https://www.verdnatura.es) + o en nuestras aplicaciones para iOS y Android (Ver tutorial de uso), son' +clientId: Identificador de cliente +user: Usuario +password: Contraseña +passwordResetText: Haz clic en '¿Has olvidado tu contraseña?' +sections: + howToBuy: + title: Cómo hacer un pedido + description: 'Para realizar un pedido en nuestra web, debes configurarlo indicando:' + requeriments: + - Si quieres recibir el pedido (por agencia o por nuestro propio reparto) o si + lo prefieres recoger en alguno de nuestros almacenes. + - La fecha en la que quieres recibir el pedido (se preparará el día anterior). + - La dirección de entrega o el almacén donde quieres recoger el pedido. + stock: En nuestra web y aplicaciones puedes visualizar el stock disponible de + flor cortada, verdes, plantas, complementos y artificial. Ten en cuenta que + dicho stock puede variar en función de la fecha seleccionada al configurar el + pedido. Es importante CONFIRMAR los pedidos para que la mercancía quede reservada. + delivery: El reparto se realiza de lunes a sábado según la zona en la que te encuentres. + Por regla general, los pedidos que se entregan por agencia, deben estar confirmados + y pagados antes de las 17h del día en que se preparan (el día anterior a recibirlos), + aunque esto puede variar si el pedido se envía a través de nuestro reparto y + según la zona. + howToPay: + title: Cómo pagar + description: 'Las formas de pago admitidas en Verdnatura son:' + options: + - Con tarjeta a través de nuestra plataforma web (al confirmar + el pedido). + - Mediante giro bancario mensual, modalidad que hay que solicitar + y tramitar. + toConsider: + title: Cosas a tener en cuenta + description: Verdnatura vende EXCLUSIVAMENTE a profesionales, por lo que debes + remitirnos el Modelo 036 ó 037, para comprobar que está dado/a de alta en el + epígrafe correspondiente al comercio de flores. + claimsPolicy: + title: POLÍTICA DE RECLAMACIONES + description: Verdnatura aceptará las reclamaciones que se realicen dentro de los + dos días naturales siguientes a la recepción del pedido (incluyendo el mismo + día de la recepción). Pasado este plazo no se aceptará ninguna reclamación. +help: Cualquier duda que te surja, no dudes en consultarla, ¡estamos para + atenderte! +salesPersonName: Soy tu comercial y mi nombre es +salesPersonPhone: Teléfono y whatsapp +salesPersonEmail: Dirección de e-mail diff --git a/print/templates/email/delivery-note-link/assets/css/import.js b/print/templates/email/delivery-note-link/assets/css/import.js new file mode 100644 index 000000000..c742fdf90 --- /dev/null +++ b/print/templates/email/delivery-note-link/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/email/delivery-note-link/assets/css/style.css b/print/templates/email/delivery-note-link/assets/css/style.css new file mode 100644 index 000000000..5db85befa --- /dev/null +++ b/print/templates/email/delivery-note-link/assets/css/style.css @@ -0,0 +1,5 @@ +.external-link { + border: 2px dashed #8dba25; + border-radius: 3px; + text-align: center +} \ No newline at end of file diff --git a/print/templates/email/delivery-note-link/delivery-note-link.html b/print/templates/email/delivery-note-link/delivery-note-link.html new file mode 100644 index 000000000..28dbc7922 --- /dev/null +++ b/print/templates/email/delivery-note-link/delivery-note-link.html @@ -0,0 +1,69 @@ + + + + + + {{ $t('subject') }} + + + + + + + + + +
    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    {{ $t('title') }}

    +

    {{$t('dear')}}

    +

    +
    +
    + +
    +
    +

    {{$t('copyLink')}}

    + +
    +
    + +
    +
    +

    +

    +

    +
    +
    + + +
    +
    + +
    +
    + +
    +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/email/delivery-note-link/delivery-note-link.js b/print/templates/email/delivery-note-link/delivery-note-link.js new file mode 100755 index 000000000..009fe7b5b --- /dev/null +++ b/print/templates/email/delivery-note-link/delivery-note-link.js @@ -0,0 +1,16 @@ +const Component = require(`${appPath}/core/component`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); + +module.exports = { + name: 'delivery-note-link', + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build() + }, + props: { + ticketId: { + required: true + } + } +}; diff --git a/print/templates/email/delivery-note-link/locale/es.yml b/print/templates/email/delivery-note-link/locale/es.yml new file mode 100644 index 000000000..47c7f11da --- /dev/null +++ b/print/templates/email/delivery-note-link/locale/es.yml @@ -0,0 +1,11 @@ +subject: Aquí tienes tu albarán +title: "Aquí tienes tu albarán" +dear: Estimado cliente +description: Ya está disponible el albarán correspondiente al pedido {0}.
    + Puedes verlo haciendo clic en este enlace. +copyLink: 'Como alternativa, puedes copiar el siguiente enlace en tu navegador:' +poll: Si lo deseas, puedes responder a nuestra encuesta de satisfacción para + ayudarnos a prestar un mejor servicio. ¡Tu opinión es muy importante para nosotros! +help: Cualquier duda que te surja, no dudes en consultarla, ¡estamos para + atenderte! +conclusion: ¡Gracias por tu atención! diff --git a/print/templates/email/delivery-note-link/locale/fr.yml b/print/templates/email/delivery-note-link/locale/fr.yml new file mode 100644 index 000000000..3ecf357e1 --- /dev/null +++ b/print/templates/email/delivery-note-link/locale/fr.yml @@ -0,0 +1,10 @@ +subject: Voici votre bon de livraison +title: "Voici votre bon de livraison" +dear: Cher client, +description: Le bon de livraison correspondant à la commande {0} est maintenant disponible.
    + Vous pouvez le voir en cliquant sur ce lien. +copyLink: 'Vous pouvez également copier le lien suivant dans votre navigateur:' +poll: Si vous le souhaitez, vous pouvez répondre à notre questionaire de satisfaction + pour nous aider à améliorer notre service. Votre avis est très important pour nous! +help: N'hésitez pas nous envoyer toute doute ou question, nous sommes là pour vous aider! +conclusion: Merci pour votre attention! diff --git a/print/templates/email/delivery-note-link/locale/pt.yml b/print/templates/email/delivery-note-link/locale/pt.yml new file mode 100644 index 000000000..c008ea2c7 --- /dev/null +++ b/print/templates/email/delivery-note-link/locale/pt.yml @@ -0,0 +1,10 @@ +subject: Vossa Nota de Entrega +title: "Esta é vossa nota de entrega!" +dear: Estimado cliente +description: Já está disponível sua nota de entrega correspondente a encomenda numero {0}.
    + Para ver-lo faça um clique neste link. +copyLink: 'Como alternativa, podes copiar o siguinte link no teu navegador:' +poll: Si o deseja, podes responder nosso questionário de satiscação para ajudar-nos a prestar-vos um melhor serviço. Tua opinião é muito importante para nós! +help: Cualquer dúvida que surja, no hesites em consultar-la, Estamos aqui para + atender-te! +conclusion: Obrigado por tua atenção! \ No newline at end of file diff --git a/print/templates/email/delivery-note/assets/css/import.js b/print/templates/email/delivery-note/assets/css/import.js new file mode 100644 index 000000000..b44d6bd37 --- /dev/null +++ b/print/templates/email/delivery-note/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/delivery-note/attachments.json b/print/templates/email/delivery-note/attachments.json new file mode 100644 index 000000000..19519a387 --- /dev/null +++ b/print/templates/email/delivery-note/attachments.json @@ -0,0 +1,6 @@ +[ + { + "filename": "delivery-note.pdf", + "component": "delivery-note" + } +] \ No newline at end of file diff --git a/print/templates/email/delivery-note/delivery-note.html b/print/templates/email/delivery-note/delivery-note.html new file mode 100644 index 000000000..0ee59a26f --- /dev/null +++ b/print/templates/email/delivery-note/delivery-note.html @@ -0,0 +1,49 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    {{ $t('title') }}

    +

    {{$t('dear')}},

    +

    +

    +

    +

    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/email/delivery-note/delivery-note.js b/print/templates/email/delivery-note/delivery-note.js new file mode 100755 index 000000000..64839b8e0 --- /dev/null +++ b/print/templates/email/delivery-note/delivery-note.js @@ -0,0 +1,17 @@ +const Component = require(`${appPath}/core/component`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); + +module.exports = { + name: 'delivery-note', + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build() + }, + props: { + ticketId: { + type: String, + required: true + } + } +}; diff --git a/print/templates/email/delivery-note/locale/es.yml b/print/templates/email/delivery-note/locale/es.yml new file mode 100644 index 000000000..3294b2316 --- /dev/null +++ b/print/templates/email/delivery-note/locale/es.yml @@ -0,0 +1,10 @@ +subject: Aquí tienes tu albarán +title: "¡Este es tu albarán!" +dear: Estimado cliente +description: Ya está disponible el albarán correspondiente al pedido {0}.
    + Puedes descargarlo haciendo clic en el adjunto de este correo. +poll: Si lo deseas, puedes responder a nuestra encuesta de satisfacción para + ayudarnos a prestar un mejor servicio. ¡Tu opinión es muy importante para nosotros! +help: Cualquier duda que te surja, no dudes en consultarla, ¡estamos para + atenderte! +conclusion: ¡Gracias por tu atención! diff --git a/print/templates/email/delivery-note/locale/fr.yml b/print/templates/email/delivery-note/locale/fr.yml new file mode 100644 index 000000000..fdaf6e320 --- /dev/null +++ b/print/templates/email/delivery-note/locale/fr.yml @@ -0,0 +1,9 @@ +subject: Voici votre bon de livraison +title: "Voici votre bon de livraison!" +dear: Cher client, +description: Le bon de livraison correspondant à la commande {0} est maintenant disponible.
    + Vous pouvez le télécharger en cliquant sur la pièce jointe dans cet email. +poll: Si vous le souhaitez, vous pouvez répondre à notre questionaire de satisfaction + pour nous aider à améliorer notre service. Votre avis est très important pour nous! +help: N'hésitez pas nous envoyer toute doute ou question, nous sommes là pour vous aider! +conclusion: Merci pour votre attention! diff --git a/print/templates/email/delivery-note/locale/pt.yml b/print/templates/email/delivery-note/locale/pt.yml new file mode 100644 index 000000000..cbca170a3 --- /dev/null +++ b/print/templates/email/delivery-note/locale/pt.yml @@ -0,0 +1,9 @@ +subject: Vossa Nota de Entrega +title: "Esta é vossa nota de entrega!" +dear: Estimado cliente +description: Já está disponível sua nota de entrega correspondente a encomenda {0}.
    + Podes descarregar-la fazendo um clique no arquivo anexado ao e-mail. +poll: Si o deseja, podes responder nosso questionário de satiscação para ajudar-nos a prestar-vos um melhor serviço. Tua opinião é muito importante para nós! +help: Cualquer dúvida que surja, no hesites em consultar-la, Estamos aqui para + atender-te! +conclusion: Obrigado por tua atenção! \ No newline at end of file diff --git a/print/templates/email/driver-route/assets/css/import.js b/print/templates/email/driver-route/assets/css/import.js new file mode 100644 index 000000000..b44d6bd37 --- /dev/null +++ b/print/templates/email/driver-route/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/driver-route/attachments.json b/print/templates/email/driver-route/attachments.json new file mode 100644 index 000000000..01111c464 --- /dev/null +++ b/print/templates/email/driver-route/attachments.json @@ -0,0 +1,6 @@ +[ + { + "filename": "driver-route.pdf", + "component": "driver-route" + } +] \ No newline at end of file diff --git a/print/templates/email/driver-route/driver-route.html b/print/templates/email/driver-route/driver-route.html new file mode 100644 index 000000000..b9d0aeab5 --- /dev/null +++ b/print/templates/email/driver-route/driver-route.html @@ -0,0 +1,45 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    {{ $t('title') }}

    +

    {{$t('description.instructions')}}

    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/email/driver-route/driver-route.js b/print/templates/email/driver-route/driver-route.js new file mode 100755 index 000000000..de1dd9c39 --- /dev/null +++ b/print/templates/email/driver-route/driver-route.js @@ -0,0 +1,17 @@ +const Component = require(`${appPath}/core/component`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); + +module.exports = { + name: 'driver-route', + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build() + }, + props: { + routeId: { + type: String, + required: true + } + } +}; diff --git a/print/templates/email/driver-route/locale/es.yml b/print/templates/email/driver-route/locale/es.yml new file mode 100644 index 000000000..f5ed12e5d --- /dev/null +++ b/print/templates/email/driver-route/locale/es.yml @@ -0,0 +1,4 @@ +subject: Hoja de ruta +title: Hoja de ruta +description: + instructions: Adjuntamos tu hoja de ruta. \ No newline at end of file diff --git a/print/templates/email/letter-debtor-nd/assets/css/import.js b/print/templates/email/letter-debtor-nd/assets/css/import.js new file mode 100644 index 000000000..624404a6c --- /dev/null +++ b/print/templates/email/letter-debtor-nd/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`]) + .mergeStyles(); + diff --git a/print/templates/email/letter-debtor-nd/attachments.json b/print/templates/email/letter-debtor-nd/attachments.json new file mode 100644 index 000000000..1e21ea343 --- /dev/null +++ b/print/templates/email/letter-debtor-nd/attachments.json @@ -0,0 +1,6 @@ +[ + { + "filename": "letter-debtor.pdf", + "component": "letter-debtor" + } +] \ No newline at end of file diff --git a/print/templates/email/letter-debtor-nd/letter-debtor-nd.html b/print/templates/email/letter-debtor-nd/letter-debtor-nd.html new file mode 100644 index 000000000..c7a6faebc --- /dev/null +++ b/print/templates/email/letter-debtor-nd/letter-debtor-nd.html @@ -0,0 +1,88 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    {{ $t('title') }}

    +

    {{ $t('sections.introduction.title') }},

    +

    {{ $t('sections.introduction.description') }}

    +

    {{ $t('sections.introduction.terms') }}

    + +

    + {{ $t('sections.payMethod.description') }}: +

      +
    1. + {{ option }} +
    2. +
    +

    + +

    + {{ $t('sections.legalAction.description') }}: +

      +
    1. + {{ option }} +
    2. +
    +

    + +

    +

    + +

    +

    +
    {{debtor.bankName}}
    +
    {{debtor.iban}}
    +
    +
    {{$t('transferAccount') }}
    +
    +
    +

    +
    +
    + +
    +
    + + +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/email/letter-debtor-nd/letter-debtor-nd.js b/print/templates/email/letter-debtor-nd/letter-debtor-nd.js new file mode 100755 index 000000000..7d7cc84ef --- /dev/null +++ b/print/templates/email/letter-debtor-nd/letter-debtor-nd.js @@ -0,0 +1,47 @@ +const Component = require(`${appPath}/core/component`); +const db = require(`${appPath}/core/database`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); +const attachment = new Component('attachment'); +const attachments = require('./attachments.json'); + +module.exports = { + name: 'letter-debtor-nd', + async serverPrefetch() { + this.debtor = await this.fetchDebtor(this.clientId, this.companyId); + + if (!this.debtor) + throw new Error('Something went wrong'); + }, + data() { + return {attachments}; + }, + methods: { + fetchDebtor(clientId, companyId) { + return db.findOne(` + SELECT + c.dueDay, + c.iban, + sa.iban, + be.name AS bankName + FROM client c + JOIN company AS cny + JOIN supplierAccount AS sa ON sa.id = cny.supplierAccountFk + JOIN bankEntity be ON be.id = sa.bankEntityFk + WHERE c.id = ? AND cny.id = ?`, [clientId, companyId]); + } + }, + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build(), + 'attachment': attachment.build() + }, + props: { + clientId: { + required: true + }, + companyId: { + required: true + } + } +}; diff --git a/print/templates/email/letter-debtor-nd/locale/es.yml b/print/templates/email/letter-debtor-nd/locale/es.yml new file mode 100644 index 000000000..506c55dd6 --- /dev/null +++ b/print/templates/email/letter-debtor-nd/locale/es.yml @@ -0,0 +1,26 @@ +subject: Reiteración de aviso por saldo deudor +title: Aviso reiterado +sections: + introduction: + title: Estimado cliente + description: Nos dirigimos a ti nuevamente para informarte que sigue pendiente + tu deuda con nuestra empresa, tal y como puedes comprobar en el extracto adjunto. + terms: Dado que los plazos de pago acordados están ampliamente superados, no procede + mayor dilación en la liquidación del importe adeudado. + payMethod: + description: Para ello dispones de las siguientes formas de pago + options: + - Pago online desde nuestra web. + - Ingreso o transferencia al número de cuenta que detallamos al pie de esta carta, + indicando el número de cliente. + legalAction: + description: En caso de no ser atendido este apremio de pago, nos veremos obligados + a iniciar las acciones legales que procedan, entre las que están + options: + - Inclusión en ficheros negativos sobre solvencia patrimonial y crédito. + - Reclamación judicial. + - Cesión de deuda a una empresa de gestión de cobro. +contactPhone: Para consultas, puedes ponerte en contacto con nosotros en el 96 + 324 21 00. +conclusion: En espera de tus noticias.
    Gracias por tu atención. +transferAccount: Datos para transferencia bancaria \ No newline at end of file diff --git a/print/templates/email/letter-debtor-st/assets/css/import.js b/print/templates/email/letter-debtor-st/assets/css/import.js new file mode 100644 index 000000000..624404a6c --- /dev/null +++ b/print/templates/email/letter-debtor-st/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`]) + .mergeStyles(); + diff --git a/print/templates/email/letter-debtor-st/attachments.json b/print/templates/email/letter-debtor-st/attachments.json new file mode 100644 index 000000000..1e21ea343 --- /dev/null +++ b/print/templates/email/letter-debtor-st/attachments.json @@ -0,0 +1,6 @@ +[ + { + "filename": "letter-debtor.pdf", + "component": "letter-debtor" + } +] \ No newline at end of file diff --git a/print/templates/email/letter-debtor-st/letter-debtor-st.html b/print/templates/email/letter-debtor-st/letter-debtor-st.html new file mode 100644 index 000000000..d277d363a --- /dev/null +++ b/print/templates/email/letter-debtor-st/letter-debtor-st.html @@ -0,0 +1,71 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    {{ $t('title') }}

    +

    {{ $t('sections.introduction.title') }},

    +

    {{ $t('sections.introduction.description') }}

    + +

    {{ $t('checkExtract') }}

    +

    {{ $t('checkValidData') }}

    +

    {{ $t('payMethod') }}

    +

    {{ $t('conclusion') }}

    + +

    +

    +
    {{debtor.bankName}}
    +
    {{debtor.iban}}
    +
    +
    {{$t('transferAccount') }}
    +
    +
    +

    +
    +
    + +
    +
    + + +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/email/letter-debtor-st/letter-debtor-st.js b/print/templates/email/letter-debtor-st/letter-debtor-st.js new file mode 100755 index 000000000..c34a9320a --- /dev/null +++ b/print/templates/email/letter-debtor-st/letter-debtor-st.js @@ -0,0 +1,47 @@ +const Component = require(`${appPath}/core/component`); +const db = require(`${appPath}/core/database`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); +const attachment = new Component('attachment'); +const attachments = require('./attachments.json'); + +module.exports = { + name: 'letter-debtor-st', + async serverPrefetch() { + this.debtor = await this.fetchDebtor(this.clientId, this.companyId); + + if (!this.debtor) + throw new Error('Something went wrong'); + }, + data() { + return {attachments}; + }, + methods: { + fetchDebtor(clientId, companyId) { + return db.findOne(` + SELECT + c.dueDay, + c.iban, + sa.iban, + be.name AS bankName + FROM client c + JOIN company AS cny + JOIN supplierAccount AS sa ON sa.id = cny.supplierAccountFk + JOIN bankEntity be ON be.id = sa.bankEntityFk + WHERE c.id = ? AND cny.id = ?`, [clientId, companyId]); + } + }, + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build(), + 'attachment': attachment.build() + }, + props: { + clientId: { + required: true + }, + companyId: { + required: true + } + } +}; diff --git a/print/templates/email/letter-debtor-st/locale/es.yml b/print/templates/email/letter-debtor-st/locale/es.yml new file mode 100644 index 000000000..d65014a1d --- /dev/null +++ b/print/templates/email/letter-debtor-st/locale/es.yml @@ -0,0 +1,19 @@ +subject: Aviso inicial por saldo deudor +title: Aviso inicial por saldo deudor +sections: + introduction: + title: Estimado cliente + description: Por el presente escrito te comunicamos que, según nuestros datos + contables, tu cuenta tiene un saldo pendiente de liquidar. +checkExtract: Te solicitamos compruebes que el extracto adjunto corresponde con los + datos de que dispones. Nuestro departamento de administración te aclarará gustosamente + cualquier duda que puedas tener, e igualmente te facilitará cualquier documento + que solicites. +checkValidData: Si al comprobar los datos aportados resultaran correctos, te rogamos + procedas a regularizar tu situación. +payMethod: Si no deseas desplazarte personalmente hasta nuestras oficinas, puedes + realizar el pago mediante transferencia bancaria a la cuenta que figura al pie del + comunicado, indicando tu número de cliente, o bien puedes realizar el pago online + desde nuestra página web. +conclusion: De antemano te agradecemos tu amable colaboración. +transferAccount: Datos para transferencia bancaria diff --git a/print/templates/email/payment-update/assets/css/import.js b/print/templates/email/payment-update/assets/css/import.js new file mode 100644 index 000000000..b44d6bd37 --- /dev/null +++ b/print/templates/email/payment-update/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/payment-update/locale/es.yml b/print/templates/email/payment-update/locale/es.yml new file mode 100644 index 000000000..464b52591 --- /dev/null +++ b/print/templates/email/payment-update/locale/es.yml @@ -0,0 +1,18 @@ +subject: Cambios en las condiciones de pago +title: Cambios en las condiciones +sections: + introduction: + title: Estimado cliente + description: Te informamos que han cambiado las condiciones de pago de tu cuenta. +
    A continuación te indicamos las nuevas condiciones + pay: + method: Método de pago + day: Día de pago + dueDay: "{0} de cada mes" + cardImplicates: Tu modo de pago actual implica que deberás abonar el importe de + los pedidos realizados en el mismo día para que se puedan enviar. + accountImplicates: Tu modo de pago actual implica que se te pasará un cargo a + la cuenta terminada en '{0}' por el importe pendiente, al vencimiento + establecido en las condiciones. +notifyAnError: En el caso de detectar algún error en los datos indicados o para cualquier + aclaración, debes dirigirte a tu comercial. diff --git a/print/templates/email/payment-update/locale/fr.yml b/print/templates/email/payment-update/locale/fr.yml new file mode 100644 index 000000000..20fa7a5f4 --- /dev/null +++ b/print/templates/email/payment-update/locale/fr.yml @@ -0,0 +1,17 @@ +subject: Changement des C.G.V +title: Changement des C.G.V +sections: + introduction: + title: Chèr client + description: Nous vous informons que les conditions de paiement ont changé.
    Voici + les nouvelles conditions + pay: + method: Méthode de paiement + day: Date paiement + dueDay: "{0} de chaque mois" + cardImplicates: Avec votre mode de règlement vous devrez payer le montant des + commandes avant son départ. + accountImplicates: Avec ce mode de règlement nous vous passerons un prélèvement + automatique dans votre compte bancaire se termine dans '{0}' + our le montant dû, au date à terme établi en nos conditions. +notifyAnError: Pour tout renseignement contactez votre commercial. diff --git a/print/templates/email/payment-update/payment-update.html b/print/templates/email/payment-update/payment-update.html new file mode 100644 index 000000000..6bba77308 --- /dev/null +++ b/print/templates/email/payment-update/payment-update.html @@ -0,0 +1,66 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    {{ $t('title') }}

    +

    {{ $t('sections.introduction.title') }},

    +

    + +

    +

    + {{ $t('sections.pay.method') }}: + {{payMethod.name}} +
    +
    + {{ $t('sections.pay.day') }}: + {{ $t('sections.pay.dueDay', [payMethod.dueDay]) }} +
    +

    + +

    +

    +

    + {{ $t('sections.pay.cardImplicates') }} +

    + +

    {{ $t('notifyAnError') }}

    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/email/payment-update/payment-update.js b/print/templates/email/payment-update/payment-update.js new file mode 100755 index 000000000..4479deb81 --- /dev/null +++ b/print/templates/email/payment-update/payment-update.js @@ -0,0 +1,41 @@ +const Component = require(`${appPath}/core/component`); +const db = require(`${appPath}/core/database`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); + +module.exports = { + name: 'payment-update', + async serverPrefetch() { + this.payMethod = await this.fetchPayMethod(this.clientId); + + if (!this.payMethod) + throw new Error('Something went wrong'); + }, + computed: { + accountAddress: function() { + return this.payMethod.iban.slice(-4); + }, + }, + methods: { + fetchPayMethod(clientId) { + return db.findOne( + `SELECT + c.dueDay, + c.iban, + pm.name, + pm.code + FROM client c + JOIN payMethod pm ON pm.id = c.payMethodFk + WHERE c.id = :clientId`, {clientId: clientId}); + } + }, + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build() + }, + props: { + clientId: { + required: true + } + } +}; diff --git a/print/templates/email/printer-setup/assets/css/import.js b/print/templates/email/printer-setup/assets/css/import.js new file mode 100644 index 000000000..b44d6bd37 --- /dev/null +++ b/print/templates/email/printer-setup/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/printer-setup/assets/files/model.ezp b/print/templates/email/printer-setup/assets/files/model.ezp new file mode 100644 index 000000000..98e3302bc Binary files /dev/null and b/print/templates/email/printer-setup/assets/files/model.ezp differ diff --git a/print/templates/email/printer-setup/assets/files/port.png b/print/templates/email/printer-setup/assets/files/port.png new file mode 100644 index 000000000..237d1057b Binary files /dev/null and b/print/templates/email/printer-setup/assets/files/port.png differ diff --git a/print/templates/email/printer-setup/attachments.json b/print/templates/email/printer-setup/attachments.json new file mode 100644 index 000000000..1e1f710c3 --- /dev/null +++ b/print/templates/email/printer-setup/attachments.json @@ -0,0 +1,14 @@ +[ + { + "filename": "model.ezp", + "component": "printer-setup", + "path": "/assets/files/model.ezp", + "cid": "model.ezp" + }, + { + "filename": "port.png", + "component": "printer-setup", + "path": "/assets/files/port.png", + "cid": "port.png" + } +] \ No newline at end of file diff --git a/print/templates/email/printer-setup/locale/es.yml b/print/templates/email/printer-setup/locale/es.yml new file mode 100644 index 000000000..39568bd1b --- /dev/null +++ b/print/templates/email/printer-setup/locale/es.yml @@ -0,0 +1,50 @@ +subject: Instalación y configuración de impresora +title: "¡Gracias por tu confianza!" +description: + dear: Estimado cliente + instructions: Sigue las instrucciones especificadas en este correo para llevar a + cabo la instalación de la impresora. + followGuide: Puedes utilizar como guía, el vídeo del montaje del ribon y la cinta + https://www.youtube.com/watch?v=qhb0kgQF3o8. También + necesitarás el QLabel, el programa para imprimir las cintas. + downloadFrom: Puedes descargarlo desde este enlace https://godex.s3-accelerate.amazonaws.com/gGnOPoojkP6vC1lgmrbEqQ.file?v01 +sections: + QLabel: + title: Utilización de QLabel + description: Para utilizar el programa de impresión de cintas sigue estos pasos + steps: + - Abre el programa QLabel + - Haz clic en el icono de la barra superior con forma de 'carpeta' + - Selecciona el archivo llamado 'model.ezp' adjunto en este correo, y haz clic + en abrir + - Ve a 'File' -> 'Save as' y guárdalo en el escritorio con otro nombre + - Cierra el Qlabel y abre el archivo que acabamos de guardar + - Haz clic encima del texto con el botón secundario del ratón + - Elige la primera opción 'setup' + - Cambia el texto para imprimir + - Haz clic en el botón 'Ok' + - Desplázate con el ratón para ver la medida máxima que ocupa el texto + - Haz clic encima del texto con el botón secundario del ratón + - Elige la segunda opción 'Setup printer' + - Haz clic en la primera pestaña 'Label Setup' + - Modifica la propiedad 'Paper Height' con la medida máxima consultada anteriormente + - 'Comprueba el puerto de la impresora, botón de de la derecha ''SETUP PRINTER'' + y en la parte derecha, igual como la imagen que adjuntamos, seleccionar la que + ponga ''USB00x: GODEX''' + - Haz clic en el botón 'Ok' + - Haz clic sobre el icono de la impresora + - Haz clic en 'Print' + help: + title: "¿Necesitas ayuda?" + description: Si necesitas ayuda, descárgate nuestro programa de soporte para poder + conectarnos remotamente a tu equipo y hacerte la instalación. Proporciónanos + un horario de contacto para atenderte, y contactaremos contigo. + remoteSupport: Puedes descargarte el programa desde este enlace http://soporte.verdnatura.es. +help: Cualquier duda que te surja, no dudes en consultarla, ¡estamos para + atenderte! +salesPersonName: Soy tu comercial y mi nombre es +salesPersonPhone: Teléfono y whatsapp +salesPersonEmail: Dirección de e-mail \ No newline at end of file diff --git a/print/templates/email/printer-setup/printer-setup.html b/print/templates/email/printer-setup/printer-setup.html new file mode 100644 index 000000000..12dcf4877 --- /dev/null +++ b/print/templates/email/printer-setup/printer-setup.html @@ -0,0 +1,89 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    {{ $t('title') }}

    +

    {{$t('description.dear')}},

    +

    {{$t('description.instructions')}}

    +

    +

    + +

    {{$t('sections.QLabel.title')}}

    +

    {{$t('sections.QLabel.description')}}:

    +
      +
    1. + +
    2. +
    +
    +
    + +
    +
    +

    {{$t('sections.help.title')}}

    +

    {{$t('sections.help.description')}}

    +

    +
    +
    + +
    +
    +
    + {{$t('salesPersonName')}}: {{client.salesPersonName}} +
    +
    + {{$t('salesPersonPhone')}}: {{client.salesPersonPhone}} +
    +
    + {{$t('salesPersonEmail')}}: + {{client.salesPersonEmail}} +
    +
    +
    + +
    +
    + + +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/email/printer-setup/printer-setup.js b/print/templates/email/printer-setup/printer-setup.js new file mode 100755 index 000000000..86ae0044a --- /dev/null +++ b/print/templates/email/printer-setup/printer-setup.js @@ -0,0 +1,44 @@ +const Component = require(`${appPath}/core/component`); +const db = require(`${appPath}/core/database`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); +const attachment = new Component('attachment'); +const attachments = require('./attachments.json'); + +module.exports = { + name: 'printer-setup', + async serverPrefetch() { + this.client = await this.fetchClient(this.clientId); + }, + data() { + return {attachments}; + }, + methods: { + fetchClient(clientId) { + return db.findOne(` + SELECT + c.id, + u.lang locale, + u.name AS userName, + c.email recipient, + CONCAT(w.lastName, ' ', w.firstName) salesPersonName, + w.phone AS salesPersonPhone, + CONCAT(wu.name, '@verdnatura.es') AS salesPersonEmail + FROM client c + JOIN account.user u ON u.id = c.id + LEFT JOIN worker w ON w.id = c.salesPersonFk + LEFT JOIN account.user wu ON wu.id = w.userFk + WHERE c.id = ?`, [clientId]); + } + }, + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build(), + 'attachment': attachment.build() + }, + props: { + clientId: { + required: true + } + } +}; diff --git a/print/templates/email/sepa-core/assets/css/import.js b/print/templates/email/sepa-core/assets/css/import.js new file mode 100644 index 000000000..b44d6bd37 --- /dev/null +++ b/print/templates/email/sepa-core/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/sepa-core/attachments.json b/print/templates/email/sepa-core/attachments.json new file mode 100644 index 000000000..e5ddc0aff --- /dev/null +++ b/print/templates/email/sepa-core/attachments.json @@ -0,0 +1,4 @@ +[{ + "filename": "sepa-core.pdf", + "component": "sepa-core" +}] \ No newline at end of file diff --git a/print/templates/email/sepa-core/locale/es.yml b/print/templates/email/sepa-core/locale/es.yml new file mode 100644 index 000000000..10a1d32fe --- /dev/null +++ b/print/templates/email/sepa-core/locale/es.yml @@ -0,0 +1,18 @@ +subject: Solicitud de domiciliación bancaria +title: Domiciliación SEPA CORE +description: + dear: Estimado cliente + instructions:

    Dadas las excelentes relaciones existentes entre nuestras + dos empresas y para facilitar los procesos de pago de nuestras facturas, + sugerimos el uso del sistema de domiciliación bancaria SEPA CORE.

    +

    Este servicio consiste en emitir nuestros recibos a su empresa de + forma automatizada y electrónicamente, lo que supone para usted una reducción + sustancial de costos en términos de honorarios y gastos bancarios.

    +

    En caso de que acepte nuestra propuesta, a la fecha de vencimiento de cada efecto, + se debitará a su cuenta automáticamente a través de su entidad bancaria. + Por tanto, le pedimos que firme y envíe a su banco la autorización original adjunta, + debidamente cumplimentada, y nos devuelva una fotocopia de dicha autorización.

    +

    Este sistema se basa en la transmisión electrónica de datos; + el manejo de documentos físicos ha sido eliminado.

    +

    Le agradecemos su cooperación,

    + conclusion: ¡Gracias por su atención! diff --git a/print/templates/email/sepa-core/locale/fr.yml b/print/templates/email/sepa-core/locale/fr.yml new file mode 100644 index 000000000..98bd7593a --- /dev/null +++ b/print/templates/email/sepa-core/locale/fr.yml @@ -0,0 +1,27 @@ +subject: Autorisation pour débit +title: Autorisation pour débit +description: + dear: Messieurs + instructions:

    Étant donné les excellentes relations existantes entre nos + deux sociétés et en vue de faciliter les processus de + paiement de nos factures, nous vous suggérons l'utilisation + du système française de compensation LCR.

    +

    Ce service consiste à effectuer des recouvrements + automatiques, de manière électronique, de nos effets - + lettres de change et billets à ordre - tirés sur votre société + en Euro, qui présente comme principal avantage pour vous + la substantielle réduction de coûts dans des termes de frais + et commissions bancaires.

    +

    Dans le cas où vous accepteriez notre proposition, à + l’échéance de chaque effet, votre compte sera débité + automatiquement par votre Banque. + Ainsi, nous vous demandons de signer et envoyer à votre + Banque l'original de l'autorisation pour débit en annexe, + dûment remplie, et de nous retourner une photocopie de la + dite autorisation.

    +

    Ce système étant basé sur la transmission de données de + manière électronique, le maniement de documents + physiques á été éliminé

    +

    En vous remercieront pour votre collaboration, nous vous + prions d’agréer, Messieurs, nos salutations distinguées.

    + conclusion: Bien cordialement diff --git a/print/templates/email/sepa-core/locale/pt.yml b/print/templates/email/sepa-core/locale/pt.yml new file mode 100644 index 000000000..9999dbc6a --- /dev/null +++ b/print/templates/email/sepa-core/locale/pt.yml @@ -0,0 +1,8 @@ +subject: Autorização de débito directo SEPA CORE +title: Débito directo SEPA CORE +description: + dear: Prezado Cliente + instructions: Para poder tramitar vossa solicitação de forma de pagamento a Débito + Automático, anexamos os documentos correspondentes à Lei de Pagamentos, que deves + preencher e reenviar-nos. + conclusion: Obrigado pela atenção. diff --git a/print/templates/email/sepa-core/sepa-core.html b/print/templates/email/sepa-core/sepa-core.html new file mode 100644 index 000000000..b71c8e10f --- /dev/null +++ b/print/templates/email/sepa-core/sepa-core.html @@ -0,0 +1,57 @@ + + + + + + {{ $t('subject') }} + + + + + + + + +
    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    {{ $t('title') }}

    +

    {{$t('description.dear')}},

    +
    +

    {{$t('description.conclusion')}}

    +
    +
    + +
    +
    + + +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/email/sepa-core/sepa-core.js b/print/templates/email/sepa-core/sepa-core.js new file mode 100755 index 000000000..31afb1115 --- /dev/null +++ b/print/templates/email/sepa-core/sepa-core.js @@ -0,0 +1,25 @@ +const Component = require(`${appPath}/core/component`); +const emailHeader = new Component('email-header'); +const emailFooter = new Component('email-footer'); +const attachment = new Component('attachment'); +const attachments = require('./attachments.json'); + +module.exports = { + name: 'sepa-core', + data() { + return {attachments}; + }, + components: { + 'email-header': emailHeader.build(), + 'email-footer': emailFooter.build(), + 'attachment': attachment.build() + }, + props: { + clientId: { + required: true + }, + companyId: { + required: true + } + } +}; diff --git a/print/templates/reports/campaign-metrics/assets/css/import.js b/print/templates/reports/campaign-metrics/assets/css/import.js new file mode 100644 index 000000000..fd8796c2b --- /dev/null +++ b/print/templates/reports/campaign-metrics/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/reports/campaign-metrics/assets/css/style.css b/print/templates/reports/campaign-metrics/assets/css/style.css new file mode 100644 index 000000000..6e730869e --- /dev/null +++ b/print/templates/reports/campaign-metrics/assets/css/style.css @@ -0,0 +1,11 @@ +.column-oriented { + margin-top: 50px !important; +} + +.bottom-line > tr { + border-bottom: 1px solid #ccc; +} + +.bottom-line tr:nth-last-child() { + border-bottom: none; +} diff --git a/print/templates/reports/campaign-metrics/campaign-metrics.html b/print/templates/reports/campaign-metrics/campaign-metrics.html new file mode 100644 index 000000000..5e4bc7d08 --- /dev/null +++ b/print/templates/reports/campaign-metrics/campaign-metrics.html @@ -0,0 +1,100 @@ + + + + + + + + + +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    +

    {{$t('title')}}

    +
    + + + + + + + + + + + + + + + +
    {{$t('Client')}}{{client.id}}
    {{$t('From')}}{{from | date('%d-%m-%Y')}}
    {{$t('To')}}{{to | date('%d-%m-%Y')}}
    +
    +
    +
    +
    +
    {{$t('clientData')}}
    +
    +

    {{client.socialName}}

    +
    + {{client.street}} +
    +
    + {{client.postcode}}, {{client.city}} ({{client.province}}) +
    +
    + {{client.country}} +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + +
    {{$t('Code')}}{{$t('Quantity')}}{{$t('Concept')}}
    {{sale.itemFk}}{{Math.trunc(sale.subtotal)}} + {{sale.concept}} {{sale.subName | uppercase}} +
    + {{sale.tag5}} + {{sale.value5}} + {{sale.tag6}} + {{sale.value6}} + {{sale.tag7}} + {{sale.value7}} +
    +
    +
    +
    + +
    +
    + + +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/reports/campaign-metrics/campaign-metrics.js b/print/templates/reports/campaign-metrics/campaign-metrics.js new file mode 100755 index 000000000..f72069260 --- /dev/null +++ b/print/templates/reports/campaign-metrics/campaign-metrics.js @@ -0,0 +1,78 @@ +const Component = require(`${appPath}/core/component`); +const db = require(`${appPath}/core/database`); +const reportHeader = new Component('report-header'); +const reportFooter = new Component('report-footer'); + +module.exports = { + name: 'campaign-metrics', + async serverPrefetch() { + this.to = new Date(this.to); + this.from = new Date(this.from); + + this.client = await this.fetchClient(this.clientId); + + this.sales = await this.fetchSales(this.clientId, this.from, this.to); + + if (!this.client) + throw new Error('Something went wrong'); + }, + methods: { + fetchClient(clientId) { + return db.findOne( + `SELECT + c.street, + c.socialName, + c.city, + c.postcode, + c.id, + c.name AS clientName, + p.name AS province, + co.country + FROM client c + JOIN province p ON c.provinceFk = p.id + JOIN country co ON c.countryFk = co.id + WHERE + c.id = ?`, [clientId]); + }, + fetchSales(clientId, from, to) { + return db.rawSql( + `SELECT + SUM(s.quantity) AS subtotal, + s.itemFk, + s.concept, + i.subName, + i.tag5, + i.value5, + i.tag6, + i.value6, + i.tag7, + i.value7 + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE + t.clientFk = ? AND it.isPackaging = FALSE + AND DATE(t.shipped) BETWEEN ? AND ? + GROUP BY s.itemFk + ORDER BY i.typeFk , i.name , i.size`, [clientId, from, to]); + }, + }, + components: { + 'report-header': reportHeader.build(), + 'report-footer': reportFooter.build() + }, + props: { + clientId: { + required: true + }, + from: { + required: true, + type: Date + }, + to: { + required: true, + type: Date + } + } +}; diff --git a/print/templates/reports/campaign-metrics/locale/es.yml b/print/templates/reports/campaign-metrics/locale/es.yml new file mode 100644 index 000000000..df0c91971 --- /dev/null +++ b/print/templates/reports/campaign-metrics/locale/es.yml @@ -0,0 +1,11 @@ +title: Consumo de campaña +Client: Cliente +clientData: Datos del cliente +dated: Fecha +From: Desde +To: Hasta +client: Cliente {0} +Code: Código +Quantity: Cantidad +Stems: Tallos +Concept: Concepto \ No newline at end of file diff --git a/print/templates/reports/claim-pickup-order/assets/css/import.js b/print/templates/reports/claim-pickup-order/assets/css/import.js new file mode 100644 index 000000000..fd8796c2b --- /dev/null +++ b/print/templates/reports/claim-pickup-order/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/reports/claim-pickup-order/assets/css/style.css b/print/templates/reports/claim-pickup-order/assets/css/style.css new file mode 100644 index 000000000..c3b21a257 --- /dev/null +++ b/print/templates/reports/claim-pickup-order/assets/css/style.css @@ -0,0 +1,12 @@ +table.column-oriented { + margin-top: 50px !important +} + +.sign { + margin: 150px auto; + width: 300px +} + +.sign .body { + height: 150px +} \ No newline at end of file diff --git a/print/templates/reports/claim-pickup-order/claim-pickup-order.html b/print/templates/reports/claim-pickup-order/claim-pickup-order.html new file mode 100644 index 000000000..9c6b0fa4e --- /dev/null +++ b/print/templates/reports/claim-pickup-order/claim-pickup-order.html @@ -0,0 +1,102 @@ + + + + + + + + + +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    +
    +

    {{$t('title')}}

    + + + + + + + + + + + + + + + +
    {{$t('claimId')}}{{claimId}}
    {{$t('clientId')}}{{client.id}}
    {{$t('date')}}{{dated}}
    +
    +
    +
    +
    +
    {{$t('clientData')}}
    +
    +

    {{client.nickname}}

    +
    + {{client.street}} +
    +
    + {{client.postalCode}}, {{client.city}} ({{client.province}}) +
    +
    + {{client.country}} +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + +
    {{$t('reference')}}{{$t('quantity')}}{{$t('claims')}}{{$t('concept')}}
    {{sale.id}}{{sale.quantity}}{{sale.claimQuantity}}{{sale.concept}}
    + +
    +
    {{$t('clientSignature')}}
    +
    +

    {{client.name}}

    +
    +
    + +

    +
    +
    + +
    +
    + + +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/reports/claim-pickup-order/claim-pickup-order.js b/print/templates/reports/claim-pickup-order/claim-pickup-order.js new file mode 100755 index 000000000..a18e6d0e0 --- /dev/null +++ b/print/templates/reports/claim-pickup-order/claim-pickup-order.js @@ -0,0 +1,66 @@ +const Component = require(`${appPath}/core/component`); +const db = require(`${appPath}/core/database`); +const reportHeader = new Component('report-header'); +const reportFooter = new Component('report-footer'); + +module.exports = { + name: 'claim-pickup-order', + async serverPrefetch() { + this.client = await this.fetchClient(this.claimId); + this.sales = await this.fetchSales(this.claimId); + + if (!this.client) + throw new Error('Something went wrong'); + }, + computed: { + dated: function() { + const filters = this.$options.filters; + + return filters.date(new Date(), '%d-%m-%Y'); + } + }, + methods: { + fetchClient(claimId) { + return db.findOne( + `SELECT + c.id, + c.socialName, + c.name, + c.fi, + a.city, + a.postalCode, + a.street, + a.nickname, + p.name AS province, + ct.country + FROM claim cl + JOIN client c ON c.id = cl.clientFk + JOIN account.user u ON u.id = c.id + JOIN country ct ON ct.id = c.countryFk + JOIN ticket t ON t.id = cl.ticketFk + JOIN address a ON a.id = t.addressFk + LEFT JOIN province p ON p.id = c.provinceFk + WHERE cl.id = ?`, [claimId]); + }, + fetchSales(claimId) { + return db.rawSql( + `SELECT + s.id, + s.quantity, + s.concept, + cb.quantity claimQuantity + FROM claimBeginning cb + JOIN sale s ON s.id = cb.saleFk + WHERE cb.claimFk = ?`, [claimId]); + }, + }, + components: { + 'report-header': reportHeader.build(), + 'report-footer': reportFooter.build() + }, + props: { + claimId: { + required: true + } + } +}; diff --git a/print/templates/reports/claim-pickup-order/locale/es.yml b/print/templates/reports/claim-pickup-order/locale/es.yml new file mode 100644 index 000000000..b37793b70 --- /dev/null +++ b/print/templates/reports/claim-pickup-order/locale/es.yml @@ -0,0 +1,15 @@ +title: Ord. recogida +claimId: Reclamación +clientId: Cliente +date: Fecha +clientData: Dirección de recogida +quantity: Cantidad +claims: Reclama +reference: Referencia +concept: Concepto +clientSignature: Firma del cliente +claim: Reclamación {0} +sections: + agency: + description: 'Para agilizar tu recogida, por favor, pónte en contacto con la oficina + de integrados.
    Tlf: 96 166 77 88 - Ana Gómez (Ext. 2113) (agomezf@integra2.es)' diff --git a/print/templates/reports/delivery-note/assets/css/import.js b/print/templates/reports/delivery-note/assets/css/import.js new file mode 100644 index 000000000..fd8796c2b --- /dev/null +++ b/print/templates/reports/delivery-note/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/reports/delivery-note/assets/css/style.css b/print/templates/reports/delivery-note/assets/css/style.css new file mode 100644 index 000000000..04474d4c8 --- /dev/null +++ b/print/templates/reports/delivery-note/assets/css/style.css @@ -0,0 +1,19 @@ +#signature { + padding-right: 10px +} + +#signature img { + -webkit-filter: brightness(0%); + filter: brightness(0%); + margin-bottom: 10px; + max-width: 150px +} + +.description.phytosanitary { + background-color: #e5e5e5 +} + +h3 { + font-weight: 100; + color: #555 +} \ No newline at end of file diff --git a/print/templates/reports/delivery-note/delivery-note.html b/print/templates/reports/delivery-note/delivery-note.html new file mode 100644 index 000000000..77f214c07 --- /dev/null +++ b/print/templates/reports/delivery-note/delivery-note.html @@ -0,0 +1,259 @@ + + + + + + + + + +
    + +
    +
    + + +
    +
    + +
    +
    +
    +
    +
    +

    {{$t('title')}}

    + + + + + + + + + + + + + + + +
    {{$t('clientId')}}{{client.id}}
    {{$t('ticketId')}}{{ticket.id}}
    {{$t('date')}}{{ticket.shipped | date('%d-%m-%Y')}}
    +
    +
    +
    +
    +
    {{$t('deliveryAddress')}}
    +
    +

    {{address.nickname}}

    +
    + {{address.street}} +
    +
    + {{address.postalCode}}, {{address.city}} ({{address.province}}) +
    +
    +
    + +
    +
    {{$t('fiscalData')}}
    +
    +
    + {{client.socialName}} +
    +
    + {{client.street}} +
    +
    + {{client.fi}} +
    +
    +
    +
    +
    + + +

    {{$t('saleLines')}}

    + + + + + + + + + + + + + + + + + + + + + + + + +
    {{$t('reference')}}{{$t('quantity')}}{{$t('concept')}}{{$t('price')}}{{$t('discount')}}{{$t('vat')}}{{$t('amount')}}
    + {{$t('subtotal')}} + {{getSubTotal() | currency('EUR', locale)}}
    + + +
    + +
    +

    {{$t('services')}}

    + + + + + + + + + + + + + + + + + + + + + + + +
    {{$t('concept')}}{{$t('quantity')}}{{$t('vatType')}}{{$t('amount')}}
    {{service.description}}{{service.quantity}}{{service.taxDescription}}{{service.price | currency('EUR', locale)}}
    {{$t('total')}} {{serviceTotal | currency('EUR', locale)}}
    +
    + + + +
    +

    {{$t('taxBreakdown')}}

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    {{$t('type')}}{{$t('taxBase')}}{{$t('tax')}}{{$t('fee')}}
    {{tax.name}}{{tax.Base | currency('EUR', locale)}}{{tax.vatPercent | percentage}}{{tax.tax | currency('EUR', locale)}}
    {{$t('subtotal')}}{{getTotalBase() | currency('EUR', locale)}}{{getTotalTax()| currency('EUR', locale)}}
    {{$t('total')}}{{getTotal() | currency('EUR', locale)}}
    +
    + + + +
    +

    {{$t('packagings')}}

    + + + + + + + + + + + + + + + +
    Id{{$t('concept')}}{{$t('quantity')}}
    {{packaging.itemFk}}{{packaging.name}}{{packaging.quantity}}
    +
    + + + +
    +
    +
    {{$t('digitalSignature')}}
    +
    + +
    {{signature.created | date('%d-%m-%Y')}}
    +
    +
    +
    + +
    +
    +
    + +
    +
    + + +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/reports/delivery-note/delivery-note.js b/print/templates/reports/delivery-note/delivery-note.js new file mode 100755 index 000000000..f22d7694a --- /dev/null +++ b/print/templates/reports/delivery-note/delivery-note.js @@ -0,0 +1,208 @@ +const config = require(`${appPath}/core/config`); +const db = require(`${appPath}/core/database`); +const Component = require(`${appPath}/core/component`); +const reportHeader = new Component('report-header'); +const reportFooter = new Component('report-footer'); +const md5 = require('md5'); + +module.exports = { + name: 'delivery-note', + async serverPrefetch() { + this.client = await this.fetchClient(this.ticketId); + this.ticket = await this.fetchTicket(this.ticketId); + this.sales = await this.fetchSales(this.ticketId); + this.address = await this.fetchAddress(this.ticketId); + this.services = await this.fetchServices(this.ticketId); + this.taxes = await this.fetchTaxes(this.ticketId); + this.packagings = await this.fetchPackagings(this.ticketId); + this.signature = await this.fetchSignature(this.ticketId); + + if (!this.ticket) + throw new Error('Something went wrong'); + }, + data() { + return {totalBalance: 0.00}; + }, + computed: { + dmsPath() { + const pathHash = md5(this.signature.id.toString()).substring(0, 3); + const hostPath = `file:///${config.storage.root}/${pathHash}`; + + if (this.signature && this.signature.id) + return `${hostPath}/${this.signature.id}.png`; + }, + serviceTotal() { + let total = 0.00; + this.services.forEach(service => { + total += parseFloat(service.price) * service.quantity; + }); + + return total; + } + }, + methods: { + fetchClient(ticketId) { + return db.findOne( + `SELECT + c.id, + c.socialName, + c.street, + c.fi + FROM ticket t + JOIN client c ON c.id = t.clientFk + WHERE t.id = ?`, [ticketId]); + }, + fetchTicket(ticketId) { + return db.findOne( + `SELECT + t.id, + t.shipped, + c.code companyCode + FROM ticket t + JOIN company c ON c.id = t.companyFk + WHERE t.id = ?`, [ticketId]); + }, + fetchAddress(ticketId) { + return db.findOne( + `SELECT + a.nickname, + a.street, + a.postalCode, + a.city, + p.name province + FROM ticket t + JOIN address a ON a.clientFk = t.clientFk + LEFT JOIN province p ON p.id = a.provinceFk + WHERE t.id = ?`, [ticketId]); + }, + + fetchSales(ticketId) { + return db.rawSql( + `SELECT + s.id, + s.itemFk, + s.concept, + s.quantity, + s.price, + s.price - SUM(IF(ctr.id = 6, + sc.value, + 0)) netPrice, + s.discount, + i.size, + i.stems, + i.category, + it.id itemTypeId, + o.code AS origin, + i.inkFk, + s.ticketFk, + tcl.code vatType, + ibwg.ediBotanic, ppa.denomination, pp.number passportNumber, + be.isProtectedZone, c.code AS countryCode, + i.tag5, i.value5, + i.tag6, i.value6, i.tag7, i.value7 + FROM vn.sale s + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN component cr ON cr.id = sc.componentFk + LEFT JOIN componentType ctr ON ctr.id = cr.typeFk + LEFT JOIN item i ON i.id = s.itemFk + LEFT JOIN ticket t ON t.id = s.ticketFk + LEFT JOIN origin o ON o.id = i.originFk + LEFT JOIN country c ON c.id = o.countryFk + LEFT JOIN supplier sp ON sp.id = t.companyFk + LEFT JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemTaxCountry itc ON itc.itemFk = i.id + AND itc.countryFk = sp.countryFk + LEFT JOIN taxClass tcl ON tcl.id = itc.taxClassFk + LEFT JOIN plantpassport pp ON pp.producerFk = i.producerFk + LEFT JOIN plantpassportAuthority ppa ON ppa.id = pp.plantpassportAuthorityFk + LEFT JOIN itemBotanicalWithGenus ibwg ON ibwg.itemFk = i.id + LEFT JOIN botanicExport be ON be.restriction = 'pasaporte fitosanitario' + LEFT JOIN ediGenus eg ON eg.id = be.ediGenusFk + LEFT JOIN ediSpecie es ON es.id = be.ediSpecieFk + AND ibwg.ediBotanic LIKE CONCAT( + IFNULL(eg.latinGenusName, ''), + IF(es.latinSpeciesName > '', + CONCAT(' ', es.latinSpeciesName), ''), + '%') + WHERE s.ticketFk = ? + GROUP BY s.id + ORDER BY (it.isPackaging), s.concept, s.itemFk`, [ticketId]); + }, + fetchTaxes(ticketId) { + return db.rawSql(`CALL vn.ticketGetTaxAdd(?)`, [ticketId]).then(rows => { + return rows[0]; + }); + }, + fetchPackagings(ticketId) { + return db.rawSql( + `SELECT + tp.quantity, + i.name, + p.itemFk + FROM ticketPackaging tp + JOIN packaging p ON p.id = tp.packagingFk + JOIN item i ON i.id = p.itemFk + WHERE tp.ticketFk = ? + ORDER BY itemFk`, [ticketId]); + }, + fetchServices(ticketId) { + return db.rawSql( + `SELECT + tc.description taxDescription, + ts.description, + ts.quantity, + ts.price + FROM ticketService ts + JOIN taxClass tc ON tc.id = ts.taxClassFk + WHERE ts.ticketFk = ?`, [ticketId]); + }, + fetchSignature(ticketId) { + return db.findOne( + `SELECT + d.id, + d.created + FROM ticket t + JOIN ticketDms dt ON dt.ticketFk = t.id + JOIN dms d ON d.id = dt.dmsFk + AND d.file LIKE '%.png' + WHERE t.id = ?`, [ticketId]); + }, + getSubTotal() { + let subTotal = 0.00; + this.sales.forEach(sale => { + subTotal += sale.quantity * sale.price * (1 - sale.discount / 100); + }); + + return subTotal; + }, + getTotalBase() { + let totalBase = 0.00; + this.taxes.forEach(tax => { + totalBase += parseFloat(tax.Base); + }); + + return totalBase; + }, + getTotalTax() { + let totalTax = 0.00; + this.taxes.forEach(tax => { + totalTax += parseFloat(tax.tax); + }); + + return totalTax; + }, + getTotal() { + return this.getTotalBase() + this.getTotalTax(); + }, + }, + components: { + 'report-header': reportHeader.build(), + 'report-footer': reportFooter.build() + }, + props: { + ticketId: { + type: String, + required: true + } + } +}; diff --git a/print/templates/reports/delivery-note/locale/en.yml b/print/templates/reports/delivery-note/locale/en.yml new file mode 100644 index 000000000..8810a7595 --- /dev/null +++ b/print/templates/reports/delivery-note/locale/en.yml @@ -0,0 +1,26 @@ +title: Delivery note +ticketId: Delivery note +clientId: Client +deliveryAddress: Delivery address +fiscalData: Fiscal data +saleLines: Line items +date: Date +reference: Ref. +quantity: Qty. +concept: Concept +price: PSP/u +discount: Disc. +vat: VAT +amount: Amount +type: Type +taxBase: Tax base +tax: Tax +fee: Fee +total: Total +subtotal: Subtotal +taxBreakdown: Tax breakdown +packagings: Buckets and packaging +services: Services +vatType: VAT Type +digitalSignature: Digital signature +ticket: Delivery note {0} \ No newline at end of file diff --git a/print/templates/reports/delivery-note/locale/es.yml b/print/templates/reports/delivery-note/locale/es.yml new file mode 100644 index 000000000..4dc7d4ff9 --- /dev/null +++ b/print/templates/reports/delivery-note/locale/es.yml @@ -0,0 +1,26 @@ +title: Albarán +ticketId: Albarán +clientId: Cliente +deliveryAddress: Dirección de entrega +fiscalData: Datos fiscales +saleLines: Líneas de pedido +date: Fecha +reference: Ref. +quantity: Cant. +concept: Concepto +price: PVP/u +discount: Dto. +vat: IVA +amount: Importe +type: Tipo +taxBase: Base imp. +tax: Tasa +fee: Cuota +total: Total +subtotal: Subtotal +taxBreakdown: Desglose impositivo +packagings: Cubos y embalajes +services: Servicios +vatType: Tipo de IVA +digitalSignature: Firma digital +ticket: Albarán {0} \ No newline at end of file diff --git a/print/templates/reports/delivery-note/locale/fr.yml b/print/templates/reports/delivery-note/locale/fr.yml new file mode 100644 index 000000000..820a1f589 --- /dev/null +++ b/print/templates/reports/delivery-note/locale/fr.yml @@ -0,0 +1,26 @@ +title: Bon de livraison +ticketId: BL +clientId: Client +deliveryAddress: Adresse de livraison +fiscalData: Coordonnées +saleLines: Lignes de la commande +date: Date +reference: Ref. +quantity: Quant. +concept: Concept +price: PRIX/u +discount: Remise +vat: TVA +amount: Montant +type: Type +taxBase: Base imposable +tax: Taxe +fee: Quote +total: Total +subtotal: Total partiel +taxBreakdown: Répartition taxes +packagings: Bacs et emballages +services: Service +vatType: Type de TVA +digitalSignature: Signature numérique +ticket: BL {0} \ No newline at end of file diff --git a/print/templates/reports/delivery-note/locale/pt.yml b/print/templates/reports/delivery-note/locale/pt.yml new file mode 100644 index 000000000..29d94c0cd --- /dev/null +++ b/print/templates/reports/delivery-note/locale/pt.yml @@ -0,0 +1,26 @@ +title: Nota de Entrega +ticketId: Nota de Entrega +clientId: Cliente +deliveryAddress: Morada de Entrega +fiscalData: Dados Fiscais +saleLines: Linhas da encomenda +date: Data +reference: Ref. +quantity: Qtde. +concept: Conceito +price: PVP/u +discount: Dto. +vat: IVA +amount: Importe +type: Tipo +taxBase: Base imp. +tax: Taxa +fee: Quota +total: Total +subtotal: Sub-total +taxBreakdown: Desglose impositivo +packagings: Baldes e Embalagens +services: Serviços +vatType: Tipo de IVA +digitalSignature: Assinatura digital +ticket: Nota de Entrega {0} \ No newline at end of file diff --git a/print/templates/reports/driver-route/assets/css/import.js b/print/templates/reports/driver-route/assets/css/import.js new file mode 100644 index 000000000..fd8796c2b --- /dev/null +++ b/print/templates/reports/driver-route/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/reports/driver-route/assets/css/style.css b/print/templates/reports/driver-route/assets/css/style.css new file mode 100644 index 000000000..2e7ec4dab --- /dev/null +++ b/print/templates/reports/driver-route/assets/css/style.css @@ -0,0 +1,49 @@ +h1 { + text-align: center; +} + +th.align-right { + padding-right: 1em; +} + +.gap { + width: 3em; +} + +.contained { + padding-top: 20px; +} + +.middle { + margin: auto; +} + +p.small { + width: 8em; +} + +.black-container { + padding-top: 0.19em; + padding-right: 0.2em; + padding-left: 0.2em; + background-color: black; + color: white; + font-size: 1.3em; +} + +table.repeatable { + margin-top: 1em; + margin-bottom: 1em; +} + +table.repeatable > tbody > tr > td { + padding-top: 0.5em; +} + +section.text-area { + margin-top: 1em; + padding: 0.19em; + padding-left: 1em; + padding-right: 1em; + background-color: #e5e5e5; +} diff --git a/print/templates/reports/driver-route/driver-route.html b/print/templates/reports/driver-route/driver-route.html new file mode 100644 index 000000000..bfeba3b8a --- /dev/null +++ b/print/templates/reports/driver-route/driver-route.html @@ -0,0 +1,170 @@ + + + + + + + + + +
    + +
    +
    + +
    +
    + +
    +
    +

    {{$t('title')}}

    +
    +
    {{$t('information')}}
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    {{$t('route')}}{{route.id}}{{$t('driver')}}{{route.userNickName}}
    {{$t('date')}}{{route.created | date('%d-%m-%Y')}}{{$t('vehicle')}}{{route.vehicleTradeMark}} {{route.vehicleModel}}
    {{$t('time')}}{{route.time | date('%H:%M')}}{{route.plateNumber}}
    {{$t('volume')}}{{route.m3}}{{$t('agency')}}{{route.agencyName}}
    +
    + + + + + + + + + + + + + + + +
    +

    Hora inicio

    +
    +

    Hora fin

    +
    +

    Km inicio

    +
    +

    Km fin

    +
    +
    + +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + +
    {{$t('order')}}{{$t('ticket')}}{{$t('client')}}{{$t('address')}}{{$t('packages')}}
    {{ticket.priority}}{{ticket.id}}{{ticket.clientFk}} {{ticket.addressName}} + {{ticket.addressFk.toString().substr(0, ticket.addressFk.toString().length - 3)}} + + {{ticket.addressFk.toString().substr(-3, 3)}} + + {{ticket.packages}}
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    {{$t('street')}}{{ticket.street}}{{$t('postcode')}}{{ticket.postalCode}}
    {{$t('city')}}{{ticket.city}}{{$t('agency')}}{{ticket.ticketAgency}}
    {{$t('mobile')}}{{ticket.mobile}}{{$t('phone')}}{{ticket.phone}}
    {{$t('warehouse')}}{{ticket.warehouseName}}{{$t('salesPerson')}}{{ticket.salesPersonName}}
    {{$t('import')}}{{ticket.import}}
    +
    +

    {{ticket.description}}

    +

    {{$t('stowaway')}}: {{ticket.shipFk}}

    +
    +
    +
    +
    +
    + +
    +
    + + +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/reports/driver-route/driver-route.js b/print/templates/reports/driver-route/driver-route.js new file mode 100755 index 000000000..498666cc6 --- /dev/null +++ b/print/templates/reports/driver-route/driver-route.js @@ -0,0 +1,82 @@ +const Component = require(`${appPath}/core/component`); +const db = require(`${appPath}/core/database`); +const reportHeader = new Component('report-header'); +const reportFooter = new Component('report-footer'); + +module.exports = { + name: 'driver-route', + async serverPrefetch() { + this.route = await this.fetchRoute(this.routeId); + this.tickets = await this.fetchTickets(this.routeId); + + if (!this.route) + throw new Error('Something went wrong'); + }, + methods: { + fetchRoute(id) { + return db.findOne( + `SELECT + r.id, + r.m3, + r.created, + r.time, + u.nickName userNickName, + v.tradeMark vehicleTradeMark, + v.model vehicleModel, + v.numberPlate plateNumber, + am.name agencyName + FROM route r + LEFT JOIN vehicle v ON v.id = r.vehicleFk + LEFT JOIN worker w ON w.id = r.workerFk + LEFT JOIN account.user u ON u.id = w.userFk + LEFT JOIN agencyMode am ON am.id = r.agencyModeFk + WHERE r.id = :routeId`, {routeId: id}); + }, + // Redmine #1855 Replace function Averiguar_ComercialCliente_Id() + fetchTickets(routeId) { + return db.rawSql( + `SELECT + t.nickname addressName, + t.packages, + t.priority, + t.id, + t.clientFk, + t.companyFk, + if(a.phone, a.phone, c.phone) AS phone, + if(a.mobile, a.mobile, c.mobile) AS mobile, + wh.name warehouseName, + a.city, + a.street, + a.postalCode, + LPAD(a.id, 5, '0') AS addressFk, + p.name province, + vn.ticketGetTotal(t.id) AS import, + am.name ticketAgency, + tob.description, + s.shipFk, + u.nickName salesPersonName + FROM route r + LEFT JOIN ticket t ON t.routeFk = r.id + LEFT JOIN address a ON a.id = t.addressFk + LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN worker w ON w.id = client_getSalesPerson(t.clientFk, CURDATE()) + LEFT JOIN account.user u ON u.id = w.userFk + LEFT JOIN ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 3 + LEFT JOIN province p ON a.provinceFk = p.id + LEFT JOIN warehouse wh ON wh.id = t.warehouseFk + LEFT JOIN agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN stowaway s ON s.id = t.id + WHERE r.id = ? + ORDER BY t.priority, t.id`, [routeId]); + } + }, + components: { + 'report-header': reportHeader.build(), + 'report-footer': reportFooter.build() + }, + props: { + routeId: { + required: true + } + } +}; diff --git a/print/templates/reports/driver-route/locale/es.yml b/print/templates/reports/driver-route/locale/es.yml new file mode 100644 index 000000000..25c830e5c --- /dev/null +++ b/print/templates/reports/driver-route/locale/es.yml @@ -0,0 +1,24 @@ +title: Hoja de ruta +information: Información +date: Fecha +time: Hora +volume: Cubicaje +driver: Conductor +vehicle: Vehículo +agency: Agencia +order: Orden +client: Cliente +address: Consignatario +packages: Bultos +street: Dirección +postcode: Código Postal +city: Ciudad +mobile: Móvil +phone: Teléfono +warehouse: Almacén +salesPerson: Comercial +import: Importe +stowaway: Encajado dentro del ticket +route: Ruta +routeId: Ruta {0} +ticket: Tiquet \ No newline at end of file diff --git a/print/templates/reports/item-label/assets/css/import.js b/print/templates/reports/item-label/assets/css/import.js new file mode 100644 index 000000000..fd8796c2b --- /dev/null +++ b/print/templates/reports/item-label/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/reports/item-label/assets/css/style.css b/print/templates/reports/item-label/assets/css/style.css new file mode 100644 index 000000000..1101604b9 --- /dev/null +++ b/print/templates/reports/item-label/assets/css/style.css @@ -0,0 +1,88 @@ +* { + box-sizing: border-box; +} +.label { + font-size: 1.2em; +} + +.barcode { + float: left; + width: 40%; +} + +.barcode h1 { + text-align: center; + font-size: 1.8em; + margin: 0 0 10px 0 +} + +.barcode .image { + text-align: center +} + +.barcode .image img { + width: 170px +} + +.data { + float: left; + width: 60%; +} + +.data .header { + background-color: #000; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + margin-bottom: 25px; + text-align: right; + font-size: 1.2em; + padding: 0.2em; + color: #FFF +} + +.data .color, +.data .producer { + text-transform: uppercase; + text-align: right; + font-size: 1.5em; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; +} + +.data .producer { + text-justify: inter-character; +} + +.data .details { + border-top: 4px solid #000; + padding-top: 2px; +} + +.data .details .package { + padding-right: 5px; + float: left; + width: 50%; +} + +.package .packing, +.package .dated, +.package .labelNumber { + text-align: right +} + +.package .packing { + font-size: 1.8em; + font-weight: 400 +} + +.data .details .size { + background-color: #000; + text-align: center; + font-size: 3em; + padding: 0.2em 0; + float: left; + width: 50%; + color: #FFF +} \ No newline at end of file diff --git a/print/templates/reports/item-label/item-label.html b/print/templates/reports/item-label/item-label.html new file mode 100644 index 000000000..0cb351b27 --- /dev/null +++ b/print/templates/reports/item-label/item-label.html @@ -0,0 +1,35 @@ + + + + + + + + + +
    +
    +
    +

    {{item.id}}

    +
    + +
    +
    +
    +
    {{item.name}}
    +
    {{tags.color}}
    +
    {{tags.producer}}
    +
    +
    +
    {{packing()}}
    +
    {{dated}}
    +
    {{labelPage}}
    +
    +
    {{item.size}}
    +
    +
    +
    +
    + + + diff --git a/print/templates/reports/item-label/item-label.js b/print/templates/reports/item-label/item-label.js new file mode 100755 index 000000000..60139bbb2 --- /dev/null +++ b/print/templates/reports/item-label/item-label.js @@ -0,0 +1,85 @@ +const Component = require(`${appPath}/core/component`); +const db = require(`${appPath}/core/database`); +const reportHeader = new Component('report-header'); +const reportFooter = new Component('report-footer'); +const qrcode = require('qrcode'); + +module.exports = { + name: 'item-label', + async serverPrefetch() { + this.item = await this.fetchItem(this.itemId, this.warehouseId); + this.tags = await this.fetchItemTags(this.itemId); + this.barcode = await this.getBarcodeBase64(this.itemId); + + if (!this.item) + throw new Error('Something went wrong'); + }, + + computed: { + dated() { + const filters = this.$options.filters; + + return filters.date(new Date(), '%W/%d'); + }, + labelPage() { + const labelNumber = this.labelNumber ? this.labelNumber : 1; + const totalLabels = this.totalLabels ? this.totalLabels : 1; + + return `${labelNumber}/${totalLabels}`; + } + }, + methods: { + fetchItem(id, warehouseId) { + return db.findOne( + `SELECT + i.id, + i.name, + i.stems, + i.size, + b.packing + FROM vn.item i + JOIN cache.last_buy clb ON clb.item_id = i.id + JOIN vn.buy b ON b.id = clb.buy_id + JOIN vn.entry e ON e.id = b.entryFk + WHERE i.id = ? AND clb.warehouse_id = ?`, [id, warehouseId]); + }, + fetchItemTags(itemId) { + return db.rawSql( + `SELECT t.code, t.name, it.value + FROM vn.itemTag it + JOIN vn.tag t ON t.id = it.tagFk + WHERE it.itemFk = ? + `, [itemId]).then(rows => { + const tags = {}; + rows.forEach(row => tags[row.code] = row.value); + + return tags; + }); + }, + getBarcodeBase64(itemId) { + return qrcode.toDataURL(itemId, {margin: 0}); + }, + packing() { + const stems = this.item.stems ? this.item.stems : 1; + return `${this.item.packing}x${stems}`; + } + }, + components: { + 'report-header': reportHeader.build(), + 'report-footer': reportFooter.build() + }, + props: { + itemId: { + required: true + }, + warehouseId: { + required: true + }, + labelNumber: { + type: String + }, + totalLabels: { + type: String + } + } +}; diff --git a/print/templates/reports/item-label/options.json b/print/templates/reports/item-label/options.json new file mode 100644 index 000000000..6b00b0443 --- /dev/null +++ b/print/templates/reports/item-label/options.json @@ -0,0 +1,10 @@ +{ + "format": "A4", + "orientation": "landscape", + "width": "10.4cm", + "height": "4.8cm", + "border": "0cm", + "footer": { + "height": "0" + } +} \ No newline at end of file diff --git a/print/templates/reports/letter-debtor/assets/css/import.js b/print/templates/reports/letter-debtor/assets/css/import.js new file mode 100644 index 000000000..fd8796c2b --- /dev/null +++ b/print/templates/reports/letter-debtor/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/reports/letter-debtor/assets/css/style.css b/print/templates/reports/letter-debtor/assets/css/style.css new file mode 100644 index 000000000..e621f3e23 --- /dev/null +++ b/print/templates/reports/letter-debtor/assets/css/style.css @@ -0,0 +1,3 @@ +table.column-oriented { + margin-top: 50px !important +} \ No newline at end of file diff --git a/print/templates/reports/letter-debtor/letter-debtor.html b/print/templates/reports/letter-debtor/letter-debtor.html new file mode 100644 index 000000000..93e59bba1 --- /dev/null +++ b/print/templates/reports/letter-debtor/letter-debtor.html @@ -0,0 +1,100 @@ + + + + + + + + + +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    +
    +

    {{$t('title')}}

    + + + + + + + + + + + +
    {{$t('clientId')}}{{client.id}}
    {{$t('dated')}}{{dated}}
    +
    +
    +
    +
    +
    {{$t('clientData')}}
    +
    +

    {{client.socialName}}

    +
    + {{client.street}} +
    +
    + {{client.postcode}}, {{client.city}} ({{client.province}}) +
    +
    + {{client.country}} +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    {{$t('date')}}{{$t('concept')}}{{$t('invoiced')}}{{$t('payed')}}{{$t('balance')}}
    {{sale.issued | date('%d-%m-%Y')}}{{sale.ref}}{{sale.debtOut}}{{sale.debtIn}}{{getBalance(sale)}}
    Total {{getTotalDebtOut()}}{{getTotalDebtIn()}}{{totalBalance}}
    +
    +
    + +
    +
    + + +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/reports/letter-debtor/letter-debtor.js b/print/templates/reports/letter-debtor/letter-debtor.js new file mode 100755 index 000000000..f099c1869 --- /dev/null +++ b/print/templates/reports/letter-debtor/letter-debtor.js @@ -0,0 +1,89 @@ +const Component = require(`${appPath}/core/component`); +const db = require(`${appPath}/core/database`); +const reportHeader = new Component('report-header'); +const reportFooter = new Component('report-footer'); + +module.exports = { + name: 'letter-debtor', + async serverPrefetch() { + this.client = await this.fetchClient(this.clientId); + this.sales = await this.fetchSales(this.clientId, this.companyId); + + if (!this.client) + throw new Error('Something went wrong'); + }, + computed: { + dated: function() { + const filters = this.$options.filters; + + return filters.date(new Date(), '%d-%m-%Y'); + } + }, + data() { + return {totalBalance: 0.00}; + }, + methods: { + fetchClient(clientId) { + return db.findOne( + `SELECT + c.id, + c.socialName, + c.street, + c.postcode, + c.city, + c.fi, + p.name AS province, + ct.country + FROM client c + JOIN country ct ON ct.id = c.countryFk + LEFT JOIN province p ON p.id = c.provinceFk + WHERE c.id = ?`, [clientId]); + }, + fetchSales(clientId, companyId) { + return db.rawSql( + `CALL vn.clientGetDebtDiary(:clientId, :companyId)`, { + clientId: clientId, + companyId: companyId, + }).then(rows => { + return rows[0]; + }); + }, + getBalance(sale) { + if (sale.debtOut) + this.totalBalance += parseFloat(sale.debtOut); + + if (sale.debtIn) + this.totalBalance -= parseFloat(sale.debtIn); + + return parseFloat(this.totalBalance.toFixed(2)); + }, + getTotalDebtOut() { + let debtOut = 0.00; + this.sales.forEach(sale => { + debtOut += sale.debtOut ? parseFloat(sale.debtOut) : 0; + }); + + return debtOut.toFixed(2); + }, + getTotalDebtIn() { + let debtIn = 0.00; + this.sales.forEach(sale => { + debtIn += sale.debtIn ? parseFloat(sale.debtIn) : 0; + }); + + return debtIn.toFixed(2); + }, + }, + components: { + 'report-header': reportHeader.build(), + 'report-footer': reportFooter.build() + }, + props: { + clientId: { + required: true + }, + companyId: { + required: true + } + } +}; diff --git a/print/templates/reports/letter-debtor/locale/es.yml b/print/templates/reports/letter-debtor/locale/es.yml new file mode 100644 index 000000000..09a31ee5b --- /dev/null +++ b/print/templates/reports/letter-debtor/locale/es.yml @@ -0,0 +1,10 @@ +title: Extracto +claimId: Reclamación +clientId: Cliente +clientData: Datos del cliente +dated: Fecha +concept: Concepto +invoiced: Facturado +payed: Pagado +balance: Saldo +client: Cliente {0} \ No newline at end of file diff --git a/print/templates/reports/receipt/assets/css/import.js b/print/templates/reports/receipt/assets/css/import.js new file mode 100644 index 000000000..a2a9334cb --- /dev/null +++ b/print/templates/reports/receipt/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${appPath}/common/css/misc.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/reports/receipt/assets/css/style.css b/print/templates/reports/receipt/assets/css/style.css new file mode 100644 index 000000000..350925428 --- /dev/null +++ b/print/templates/reports/receipt/assets/css/style.css @@ -0,0 +1,21 @@ +p { + font-size: 1.2em; + margin: 0 +} + + +.content { + position: absolute; + margin-top: -200px; + height: 400px; + top: 50% +} + +.signature { + text-align: center; + margin-top: 150px +} + +.signature img { + width: 400px +} \ No newline at end of file diff --git a/print/templates/reports/receipt/assets/images/signature.png b/print/templates/reports/receipt/assets/images/signature.png new file mode 100644 index 000000000..c69cc4798 Binary files /dev/null and b/print/templates/reports/receipt/assets/images/signature.png differ diff --git a/services/mailer/application/template/client-welcome/style.css b/print/templates/reports/receipt/locale/en.yml similarity index 100% rename from services/mailer/application/template/client-welcome/style.css rename to print/templates/reports/receipt/locale/en.yml diff --git a/print/templates/reports/receipt/locale/es.yml b/print/templates/reports/receipt/locale/es.yml new file mode 100644 index 000000000..67b9a948f --- /dev/null +++ b/print/templates/reports/receipt/locale/es.yml @@ -0,0 +1,17 @@ +title: 'Recibo' +date: 'Fecha' +payed: 'En {0}, a {1} de {2} de {3}' +client: 'Cliente {0}' +months: + - 'Enero' + - 'Febrero' + - 'Marzo' + - 'Abril' + - 'Mayo' + - 'Junio' + - 'Julio' + - 'Agosto' + - 'Septiembre' + - 'Octubre' + - 'Noviembre' + - 'Diciembre' \ No newline at end of file diff --git a/print/templates/reports/receipt/receipt.html b/print/templates/reports/receipt/receipt.html new file mode 100644 index 000000000..5538b7c3f --- /dev/null +++ b/print/templates/reports/receipt/receipt.html @@ -0,0 +1,53 @@ + + + + + + + + + +
    + +
    +
    + +
    +
    + +
    +
    +
    +

    {{$t('title')}}

    +

    + Recibo de {{client.socialName}}, + la cantidad de {{receipt.amountPaid}} € en concepto de 'entrega a cuenta', + quedando pendiente en la cuenta del cliente + un saldo de {{receipt.amountUnpaid}} €. +

    +
    + +

    {{$t('payed', [ + 'Silla', + receipt.payed.getDate(), + $t('months')[receipt.payed.getMonth()], + receipt.payed.getFullYear()]) + }} +

    +
    +
    +
    +
    + +
    +
    + + +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/reports/receipt/receipt.js b/print/templates/reports/receipt/receipt.js new file mode 100755 index 000000000..1b220bdda --- /dev/null +++ b/print/templates/reports/receipt/receipt.js @@ -0,0 +1,49 @@ +const Component = require(`${appPath}/core/component`); +const db = require(`${appPath}/core/database`); +const reportHeader = new Component('report-header'); +const reportFooter = new Component('report-footer'); + +module.exports = { + name: 'receipt', + async serverPrefetch() { + this.client = await this.fetchClient(this.receiptId); + this.receipt = await this.fetchReceipt(this.receiptId); + + if (!this.receipt) + throw new Error('Something went wrong'); + }, + methods: { + fetchClient(receiptId) { + return db.findOne( + `SELECT + c.id, + c.socialName, + u.lang locale + FROM receipt r + JOIN client c ON c.id = r.clientFk + JOIN account.user u ON u.id = c.id + WHERE r.id = ?`, [receiptId]); + }, + fetchReceipt(receiptId) { + return db.findOne( + `SELECT + r.id, + r.amountPaid, + r.amountUnpaid, + r.payed, + r.companyFk + FROM receipt r + JOIN client c ON c.id = r.clientFk + WHERE r.id = ?`, [receiptId]); + } + }, + components: { + 'report-header': reportHeader.build(), + 'report-footer': reportFooter.build() + }, + props: { + receiptId: { + required: true + } + } +}; diff --git a/print/templates/reports/sepa-core/assets/css/import.js b/print/templates/reports/sepa-core/assets/css/import.js new file mode 100644 index 000000000..fd8796c2b --- /dev/null +++ b/print/templates/reports/sepa-core/assets/css/import.js @@ -0,0 +1,9 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/spacing.css`, + `${appPath}/common/css/misc.css`, + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/reports/sepa-core/assets/css/style.css b/print/templates/reports/sepa-core/assets/css/style.css new file mode 100644 index 000000000..89d458332 --- /dev/null +++ b/print/templates/reports/sepa-core/assets/css/style.css @@ -0,0 +1,15 @@ +.payment-type { + width: auto +} + +.payment-type th:nth-child(2), .payment-type th:nth-child(5) { + padding: 10px !important +} + +.payment-type th:nth-child(3){ + padding: 0 50px !important +} + +.wide { + width: 900px !important +} diff --git a/print/templates/reports/sepa-core/locale/es.yml b/print/templates/reports/sepa-core/locale/es.yml new file mode 100644 index 000000000..66fe889b9 --- /dev/null +++ b/print/templates/reports/sepa-core/locale/es.yml @@ -0,0 +1,41 @@ +title: Orden de domiciliación de adeudo SEPA CORE +description: Mediante la firma de esta orden de domiciliación, el deudor autoriza + (A) al acreedor a enviar instrucciones a la entidad del deudor para adeudar su cuenta + y (B) a la entidad para efectuar los adeudos en su cuenta siguiendo las instrucciones + del acreedor.Como parte de sus derechos, el deudor está legitimado al reembolso + por su entidad en los términos y condiciones del contrato suscrito con la misma. + La solicitud de reembolso deberá efectuarse dentro de las ocho semanas que adeudo + en cuenta. Puede obtener información adicional sobre sus derechos en su entidad + financiera. +documentCopy: Debe llevar a su Entidad Bancaria una copia del documento firmado para + que lo registre y evitar la devolución. +mandatoryFields: TODOS LOS CAMPOS HAN DE SER CUMPLIMENTADOS OBLIGATORIAMENTE. +sendOrder: UNA VEZ FIRMADA ESTA ORDEN DE DOMICILIACIÓN DEBE SER ENVIADA AL ACREEDOR + PARA SU CUSTODIA Y ES RECOMENDABLE FACILITAR UNA COPIA A SU ENTIDAD BANCARIA. +supplier: + toCompleteBySupplier: A cumplimentar por el acreedor + orderReference: Referencia de la orden de domiciliación + identifier: Identificador del acreedor + name: Nombre del acreedor + street: Dirección + location: CP - Población - Provincia + country: País +client: + toCompleteByClient: A cumplimentar por el deudor + name: Nombre del deudor/es + street: Dirección del deudor + location: CP - Población - Provincia + country: País del deudor + swift: Swift BIC + accountNumber: Número de cuenta - IBAN + accountHolder: "(Titular/es de la cuenta de cargo)" + accountNumberFormat: En {0} el IBAN consta de {1} posiciones comenzando siempre por {2} + paymentType: Tipo de pago + recurrent: Recurrente + unique: Único + signLocation: Fecha - Localidad + sign: Firma del deudor y sello +order: Ord. domiciliación {0} +Francia: Francia +España: España +Portugal: Portugal \ No newline at end of file diff --git a/print/templates/reports/sepa-core/locale/fr.yml b/print/templates/reports/sepa-core/locale/fr.yml new file mode 100644 index 000000000..9489fa277 --- /dev/null +++ b/print/templates/reports/sepa-core/locale/fr.yml @@ -0,0 +1,38 @@ +title: Mandat de domiciliation Européene +description: En signant ce formulaire de mandat, vous autorisez VERDNATURA LEVANTE SL + à envoyer des instructions à votre banque pour débiter votre compte, et (B) votre banque + à débiter votre compte conformément aux instructions de VERDNATURA LEVANTE SL. + Vous bénéficiez d’un droit au remboursement par votre banque selon les conditions décrites + dans la convention que vous avez passée avec elle. Toute demande de remboursement doit être + présentée dans les 8 semaines suivant la date de débit de votre compte. + Votre banque peut vous renseigner au sujet de vos droits relatifs à ce mandat. +documentCopy: Veuillez dater, signer et retourner ce document à votre banque. +mandatoryFields: TOUS LES CHAMPS DOIVENT ÊTRE REINSEGNÉS IMPÉRATIVEMENT. +sendOrder: APRÈS SIGNATURA, RENVOYER AU CRÉANCIER ET AU VOTRE ÉTABLISSEMENT FINANCIER. +supplier: + toCompleteBySupplier: Á compléter pour le créancier + orderReference: Numéro de référence du mandat + identifier: Identifiant créancier + name: Nom du céancier + street: Adresse + location: CP - Commune - Départament + country: Pays +client: + toCompleteByClient: Á compléter pour le débiteur + name: Nom du débiteur(s) + street: Adresse du(des) débiteur(s) + location: CP - Commune - Départament + country: País du(des) débiteur(s) + swift: Swift BIC + accountNumber: Numéro de compte - IBAN + accountHolder: (Débiteur(s) de compte) + accountNumberFormat: En {0} l'IBAN compte {1} postes commençant toujours par {2} + paymentType: Type de paiemen + recurrent: Versement périodique + unique: Paiement unique + signLocation: Date - Commune + sign: Signature du débiteur et tampon +order: Réf. mandat {0} +Francia: France +España: Espagne +Portugal: Portugal \ No newline at end of file diff --git a/print/templates/reports/sepa-core/locale/pt.yml b/print/templates/reports/sepa-core/locale/pt.yml new file mode 100644 index 000000000..5b71fbdf5 --- /dev/null +++ b/print/templates/reports/sepa-core/locale/pt.yml @@ -0,0 +1,41 @@ +title: Autorização de débito directo SEPA CORE +description: Ao subscrever esta autorização, está a autorizar a (A) Verdnatura Levante + S.L. a enviar instruções ao seu banco para debitar a sua conta e (B) seu banco a + debitar a sua conta, de acordo com as instruções da Verdnatura Levante S.L. Os seus + direitos incluem a possibilidade de exigir do seu banco o reembolso do montante + debitado, nos termos e condições acordados com o seu banco. O reembolso deve ser + solicitado até um prazo de oito semanas, a contar da data do débito na sua conta. + Os seus direitos, referentes à autorização acima referida, são explicados em declaração + que pode obter no seu banco. +documentCopy: Deve levar à sua Entidade Bancária uma cópia do documento assinado para + que o registre e evitar a devolução +mandatoryFields: TODOS OS CAMPOS DEVEM SER PREENCHIDOS OBRIGATORIAMENTE. +sendOrder: UMA VEZ ASSINADA, ESTA AUTORIZAÇÃO DE DÉBITO DEVE SER ENVIADA AO CREDOR + PARA SUA CUSTÓDIA E É RECOMENDÁVEL FACILITAR UMA CÓPIA À SUA ENTIDADE BANCÁRIA. +supplier: + toCompleteBySupplier: A preencher pelo credor + orderReference: Referência da ordem + identifier: Identificador do Credor + name: Nome do Credor + street: Morada + location: CP - Município - Distrito + country: País +client: + toCompleteByClient: A preencher pelo devedor + name: Nome do devedor + street: Dirección del deudor + location: Cod. Postal - Município - Distrito + country: País do devedor + swift: Swift BIC + accountNumber: Número de Conta IBAN + accountHolder: "(Titular(es) da conta)" + accountNumberFormat: Em {0} o IBAN é composto pelo {1} dígitos e começa sempre pelo {2} + paymentType: Tipos de pagamento Pagamento + recurrent: Recorrente + unique: Pagamento pontual + signLocation: Data - Localidade + sign: Assinatura e carimbo do devedor +order: Referência da ordem {0} +Francia: França +España: Espanha +Portugal: Portugal \ No newline at end of file diff --git a/print/templates/reports/sepa-core/sepa-core.html b/print/templates/reports/sepa-core/sepa-core.html new file mode 100644 index 000000000..720f70058 --- /dev/null +++ b/print/templates/reports/sepa-core/sepa-core.html @@ -0,0 +1,183 @@ + + + + + + + + + +
    + +
    +
    + +
    +
    + +
    +
    +

    {{$t('title')}}

    +
    +
    +
    + {{$t('supplier.toCompleteBySupplier')}} +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    {{$t('supplier.orderReference')}}{{supplier.mandateCode}}
    {{$t('supplier.identifier')}} +
    ES89000B97367486
    +
    B97367486-000
    +
    {{$t('supplier.name')}}{{supplier.name}}
    {{$t('supplier.street')}}{{supplier.street}}
    {{$t('supplier.location')}}{{supplier.postCode}}, {{supplier.city}} ({{supplier.province}})
    {{$t('supplier.country')}}{{supplier.country}}
    +
    +
    + +

    {{$t('description')}}

    +

    + {{$t('documentCopy')}} +

    + +
    +
    +
    + {{$t('client.toCompleteByClient')}} +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + {{$t('client.name')}} +
    {{$t('client.accountHolder')}}
    +
    {{client.socialName}}
    {{$t('client.street')}}{{client.street}}
    {{$t('client.location')}}{{client.postcode}}, {{client.city}} ({{client.province}})
    {{$t('client.country')}}{{client.country}}
    {{$t('client.swift')}} +
    + +
    +
    {{$t('client.accountNumber')}}
    +
    + {{client.countryCode.substr(0, 1)}} + {{client.countryCode.substr(1, 1)}} + +
    +
    +
    + {{client.countryCode.substr(0, 1)}} + {{client.countryCode.substr(1, 1)}} + +
    +
    +
    + {{$t('client.accountNumberFormat', [ + $t(`${client.country}`), + client.ibanLength, + client.countryCode + ])}} + +
    +
    {{$t('client.paymentType')}} + + + + + + + + +
    +
    + X +
    +
    {{$t('client.recurrent')}}O +
    + +
    +
    {{$t('client.unique')}}
    +
    {{$t('client.signLocation')}}{{dated}}, {{client.province}}
    {{$t('client.sign')}}
    +
    +
    + +

    {{$t('mandatoryFields')}}

    +

    {{$t('sendOrder')}}

    +
    +
    + +
    +
    + + +
    +
    +
    + + \ No newline at end of file diff --git a/print/templates/reports/sepa-core/sepa-core.js b/print/templates/reports/sepa-core/sepa-core.js new file mode 100755 index 000000000..de3a2983d --- /dev/null +++ b/print/templates/reports/sepa-core/sepa-core.js @@ -0,0 +1,80 @@ +const Component = require(`${appPath}/core/component`); +const db = require(`${appPath}/core/database`); +const reportHeader = new Component('report-header'); +const reportFooter = new Component('report-footer'); + +const rptSepaCore = { + name: 'sepa-core', + async serverPrefetch() { + this.client = await this.fetchClient(this.clientId, this.companyId); + this.supplier = await this.fetchSupplier(this.clientId, this.companyId); + + if (!this.client) + throw new Error('Something went wrong'); + }, + computed: { + dated: function() { + const filters = this.$options.filters; + + return filters.date(new Date(), '%d-%m-%Y'); + } + }, + methods: { + fetchClient(clientId, companyId) { + return db.findOne( + `SELECT + c.id, + m.code mandateCode, + c.socialName, + c.street, + c.postcode, + c.city, + p.name AS province, + ct.country, + ct.code AS countryCode, + ct.ibanLength AS ibanLength + FROM client c + JOIN country ct ON ct.id = c.countryFk + LEFT JOIN mandate m ON m.clientFk = c.id + AND m.companyFk = :companyId AND m.finished IS NULL + LEFT JOIN province p ON p.id = c.provinceFk + WHERE (m.companyFk = :companyId OR m.companyFk IS NULL) AND c.id = :clientId + ORDER BY m.created DESC LIMIT 1`, {companyId, clientId}); + }, + fetchSupplier(clientId, companyId) { + return db.findOne( + `SELECT + m.code mandateCode, + s.name, + s.street, + sc.country, + s.postCode, + s.city, + sp.name province + FROM client c + LEFT JOIN mandate m ON m.clientFk = c.id + AND m.companyFk = :companyId AND m.finished IS NULL + LEFT JOIN supplier s ON s.id = m.companyFk + LEFT JOIN country sc ON sc.id = s.countryFk + LEFT JOIN province sp ON sp.id = s.provinceFk + LEFT JOIN province p ON p.id = c.provinceFk + WHERE (m.companyFk = :companyId OR m.companyFk IS NULL) AND c.id = :clientId + ORDER BY m.created DESC LIMIT 1`, {companyId, clientId}); + } + }, + components: { + 'report-header': reportHeader.build(), + 'report-footer': reportFooter.build() + }, + props: { + clientId: { + required: true + }, + companyId: { + required: true + } + } +}; + + +module.exports = rptSepaCore; diff --git a/print/templates/reports/zone/assets/css/import.js b/print/templates/reports/zone/assets/css/import.js new file mode 100644 index 000000000..a2a9334cb --- /dev/null +++ b/print/templates/reports/zone/assets/css/import.js @@ -0,0 +1,8 @@ +const Stylesheet = require(`${appPath}/core/stylesheet`); + +module.exports = new Stylesheet([ + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${appPath}/common/css/misc.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/reports/zone/assets/css/style.css b/print/templates/reports/zone/assets/css/style.css new file mode 100644 index 000000000..50d5518f5 --- /dev/null +++ b/print/templates/reports/zone/assets/css/style.css @@ -0,0 +1,9 @@ +div.text { + font-family: Tahoma; + font-weight: bold; + color: white; + font-size: 7.5em; + text-align: center; + background-color: black; + margin-bottom: 0.2em +} \ No newline at end of file diff --git a/print/templates/reports/zone/zone.html b/print/templates/reports/zone/zone.html new file mode 100644 index 000000000..8e6406ad4 --- /dev/null +++ b/print/templates/reports/zone/zone.html @@ -0,0 +1,16 @@ + + + + + + + + + +
    +
    {{zone.agencyName}}
    +
    {{zone.id}}
    +
    {{zone.plateNumber}} {{zone.time | date('%H:%M')}}
    +
    + + \ No newline at end of file diff --git a/print/templates/reports/zone/zone.js b/print/templates/reports/zone/zone.js new file mode 100755 index 000000000..458762563 --- /dev/null +++ b/print/templates/reports/zone/zone.js @@ -0,0 +1,30 @@ +const db = require(`${appPath}/core/database`); + +module.exports = { + name: 'zone', + async serverPrefetch() { + this.zone = await this.fetchZone(this.routeId); + + if (!this.zone) + throw new Error('Something went wrong'); + }, + methods: { + fetchZone(routeId) { + return db.findOne( + `SELECT + r.id, + r.time, + am.name agencyName, + v.numberPlate plateNumber + FROM route r + JOIN agencyMode am ON am.id = r.agencyModeFk + JOIN vehicle v ON v.id = r.vehicleFk + WHERE r.id = :routeId`, {routeId}); + } + }, + props: { + routeId: { + required: true + } + } +}; diff --git a/services/.gitignore b/services/.gitignore deleted file mode 100644 index 9792c4ca5..000000000 --- a/services/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -datasources.test.json -datasources.development.json -db.json diff --git a/services/.yo-rc.json b/services/.yo-rc.json deleted file mode 100644 index 02f3fc17b..000000000 --- a/services/.yo-rc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "generator-loopback": {} -} \ No newline at end of file diff --git a/services/auth/Dockerfile b/services/auth/Dockerfile deleted file mode 100644 index 3a151e289..000000000 --- a/services/auth/Dockerfile +++ /dev/null @@ -1,12 +0,0 @@ -FROM node:8.9.4 - -COPY auth /app -COPY loopback /loopback -COPY nginx/static/webpack-assets.json /loopback/client/ - -WORKDIR /app - -RUN npm install -RUN npm -g install pm2 - -CMD ["pm2-docker", "./server/server.js"] diff --git a/services/auth/client/index.ejs b/services/auth/client/index.ejs deleted file mode 100644 index 83e71146f..000000000 --- a/services/auth/client/index.ejs +++ /dev/null @@ -1,13 +0,0 @@ - - - - - Salix - - - - <% for (let jsFile of assets('auth', ['vendor'])) { %> - - <% } %> - - diff --git a/services/auth/package.json b/services/auth/package.json deleted file mode 100644 index f959ddc95..000000000 --- a/services/auth/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "vn-auth", - "version": "1.0.0", - "main": "server/server.js", - "scripts": { - "lint": "eslint .", - "start": "node .", - "posttest": "npm run lint && nsp check" - }, - "dependencies": { - "md5": "^2.2.1" - }, - "repository": { - "type": "git", - "url": "https://git.verdnatura.es/salix" - }, - "license": "GPL-3.0", - "description": "Authentication service" -} diff --git a/services/auth/server/application.json b/services/auth/server/application.json deleted file mode 100644 index 8dfbe63d7..000000000 --- a/services/auth/server/application.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "default": "/login", - "salix": "/login" -} \ No newline at end of file diff --git a/services/auth/server/boot/routes.js b/services/auth/server/boot/routes.js deleted file mode 100644 index 5460afb5a..000000000 --- a/services/auth/server/boot/routes.js +++ /dev/null @@ -1,92 +0,0 @@ -var url = require('url'); -var md5 = require('md5'); - -module.exports = function(app) { - let User = app.models.User; - let applications = app.get('applications'); - - app.get('/', function(req, res) { - app.renderIndex(res); - }); - - app.post('/login', function(req, res) { - let body = req.body; - let user = body.user; - let password = body.password; - let syncOnFail = true; - let usesEmail = user && user.indexOf('@') !== -1; - - login(); - - function login() { - let loginInfo = {password: password}; - - if (usesEmail) - loginInfo.email = user; - else - loginInfo.username = user; - - User.login(loginInfo, 'user', loginCb); - } - function loginCb(err, token) { - if (err) { - if (syncOnFail && !usesEmail) { - syncOnFail = false; - let filter = {where: {name: user}}; - app.models.Account.findOne(filter, findCb); - } else - badLogin(); - return; - } - - let apiKey; - let continueUrl; - - try { - let query = url.parse(req.body.location, true).query; - apiKey = query.apiKey; - continueUrl = query.continue; - } catch (e) { - apiKey = 'default'; - continueUrl = null; - } - - let loginUrl = applications[apiKey]; - - res.json({ - token: token.id, - continue: continueUrl, - loginUrl: loginUrl - }); - } - function findCb(err, instance) { - if (err || !instance || instance.password !== md5(password)) { - badLogin(); - return; - } - - let where = {id: instance.id}; - let userData = { - id: instance.id, - username: user, - password: password, - email: instance.email, - created: instance.created, - updated: instance.updated - }; - User.upsertWithWhere(where, userData, login); - } - function badLogin() { - res.status(401); - res.json({ - message: 'Login failed' - }); - } - }); - - app.get('/logout', function(req, res) { - User.logout(req.accessToken.id, () => { - res.redirect('/'); - }); - }); -}; diff --git a/services/auth/server/boot/specs/routes.spec.js b/services/auth/server/boot/specs/routes.spec.js deleted file mode 100644 index 20b41b489..000000000 --- a/services/auth/server/boot/specs/routes.spec.js +++ /dev/null @@ -1,108 +0,0 @@ -const app = require('../../../server/server'); -const routes = require('../routes'); -const restoreFixtures = require('../../../../../services/db/testing_fixtures'); - -describe('Auth routes', () => { - let sqlStatements = {deletes: ` - DELETE FROM salix.user WHERE id = 102; - `, inserts: ``, updates: ``}; - - beforeEach(() => { - restoreFixtures(sqlStatements); - }); - - afterAll(() => { - restoreFixtures(sqlStatements); - }); - - let User = app.models.User; - let loginFunction; - let logoutFunction; - let res; - let req; - - beforeEach(() => { - spyOn(app, 'post'); - spyOn(app, 'get').and.callThrough(); - routes(app); - loginFunction = app.post.calls.mostRecent().args[1]; - logoutFunction = app.get.calls.argsFor(2)[1]; - res = {}; - req = {body: {}}; - }); - - describe('when the user doesnt exist but the client does and the password is correct', () => { - it('should create the user login and return the token', done => { - spyOn(User, 'upsertWithWhere').and.callThrough(); - req.body.user = 'PetterParker'; - req.body.password = 'nightmare'; - res.json = response => { - expect(User.upsertWithWhere).toHaveBeenCalledWith(jasmine.any(Object), jasmine.any(Object), jasmine.any(Function)); - expect(response.token).toBeDefined(); - done(); - }; - loginFunction(req, res); - }); - }); - - describe('when the user exists and the password is correct', () => { - it('should login and return the token', done => { - req.body.user = 'developer'; - req.body.password = 'nightmare'; - res.json = response => { - expect(response.token).toBeDefined(); - done(); - }; - loginFunction(req, res); - }); - - it('should define the url to continue upon login', done => { - req.body.user = 'developer'; - req.body.password = 'nightmare'; - req.body.location = 'http://localhost:5000/auth/?apiKey=salix&continue="continueURL"'; - res.json = response => { - expect(response.continue).toBeDefined(); - done(); - }; - loginFunction(req, res); - }); - - it('should define the loginUrl upon login', done => { - req.body.user = 'developer'; - req.body.password = 'nightmare'; - req.body.location = 'http://localhost:5000/auth/?apiKey=salix'; - res.json = response => { - expect(response.loginUrl).toBeDefined(); - done(); - }; - loginFunction(req, res); - }); - - it('should logout after login', done => { - spyOn(User, 'logout').and.callThrough(); - req.accessToken = {id: 'testingTokenId'}; - logoutFunction(req, res); - res.redirect = url => { - expect(User.logout).toHaveBeenCalledWith('testingTokenId', jasmine.any(Function)); - expect(url).toBe('/'); - done(); - }; - }); - }); - - describe('when the user is incorrect', () => { - it('should return a 401 unauthorized', done => { - req.body.user = 'IDontExist'; - req.body.password = 'TotallyWrongPassword'; - res.status = status => { - expect(status).toBe(401); - }; - - res.json = response => { - expect(response.message).toBe('Login failed'); - done(); - }; - loginFunction(req, res); - }); - }); -}); diff --git a/services/auth/server/server.js b/services/auth/server/server.js deleted file mode 100644 index 2819f5729..000000000 --- a/services/auth/server/server.js +++ /dev/null @@ -1,6 +0,0 @@ - -var vnLoopback = require('../../loopback/server/server.js'); - -var app = module.exports = vnLoopback.loopback(); -app.set('applications', require('./application.json')); -vnLoopback.boot(app, __dirname, module); diff --git a/services/client/Dockerfile b/services/client/Dockerfile deleted file mode 100644 index 4f58e5ccf..000000000 --- a/services/client/Dockerfile +++ /dev/null @@ -1,12 +0,0 @@ -FROM node:8.9.4 - -COPY client /app -COPY loopback /loopback - -WORKDIR /app - -RUN npm install -RUN npm -g install pm2 - -CMD ["pm2-docker", "./server/server.js"] - diff --git a/services/client/common/methods/address/crudAddressObservations.js b/services/client/common/methods/address/crudAddressObservations.js deleted file mode 100644 index 9487319e4..000000000 --- a/services/client/common/methods/address/crudAddressObservations.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = Self => { - Self.installCrudModel('crudAddressObservations'); -}; diff --git a/services/client/common/methods/greuge/filter.js b/services/client/common/methods/greuge/filter.js deleted file mode 100644 index dba4e8ef6..000000000 --- a/services/client/common/methods/greuge/filter.js +++ /dev/null @@ -1,20 +0,0 @@ -module.exports = Self => { - Self.installMethod('filter', filterParams); - - function filterParams(params) { - return { - where: { - clientFk: params.clientFk - }, - skip: (params.page - 1) * params.size, - limit: params.size, - order: params.order || 'shipped DESC', - include: { - relation: "greugeType", - scope: { - fields: ["id", "name"] - } - } - }; - } -}; diff --git a/services/client/common/methods/greuge/specs/sumAmount.spec.js b/services/client/common/methods/greuge/specs/sumAmount.spec.js deleted file mode 100644 index 41339702a..000000000 --- a/services/client/common/methods/greuge/specs/sumAmount.spec.js +++ /dev/null @@ -1,19 +0,0 @@ -const totalGreuge = require('../sumAmount'); -const catchErrors = require('../../../../../../services/utils/jasmineHelpers').catchErrors; - -describe('Greuge totalGreuge()', () => { - it('should call the sumAmount method', done => { - let clientFk = 1; - let self = jasmine.createSpyObj('self', ['remoteMethod', 'rawSql']); - self.rawSql.and.returnValue(Promise.resolve([{sumAmount: 6000}])); - totalGreuge(self); - - let callback = (error, result) => { - if (error) return catchErrors(done)(error); - - expect(result).toBe(6000); - done(); - }; - self.sumAmount(clientFk, callback); - }); -}); diff --git a/services/client/common/methods/greuge/sumAmount.js b/services/client/common/methods/greuge/sumAmount.js deleted file mode 100644 index 0fa8d9034..000000000 --- a/services/client/common/methods/greuge/sumAmount.js +++ /dev/null @@ -1,31 +0,0 @@ -module.exports = Self => { - Self.remoteMethod('sumAmount', { - description: 'Returns the sum of greuge for a client', - accessType: 'READ', - accepts: [{ - arg: 'id', - type: 'number', - required: true, - description: 'clientFk', - http: {source: 'path'} - }], - returns: { - arg: 'sumAmount' - }, - http: { - path: `/:id/sumAmount`, - verb: 'get' - } - }); - - Self.sumAmount = (clientFk, callback) => { - let query = `SELECT SUM(amount) AS sumAmount FROM vn.greuge WHERE clientFk = ?`; - Self.rawSql(query, [clientFk]) - .then(response => { - callback(null, response.length ? response[0].sumAmount : 0); - }) - .catch(err => { - callback(err); - }); - }; -}; diff --git a/services/client/common/methods/invoiceOut/filter.js b/services/client/common/methods/invoiceOut/filter.js deleted file mode 100644 index 0927f9b02..000000000 --- a/services/client/common/methods/invoiceOut/filter.js +++ /dev/null @@ -1,14 +0,0 @@ -module.exports = Self => { - Self.installMethod('filter', filterParams); - - function filterParams(params) { - return { - where: { - clientFk: params.clientFk - }, - skip: (params.page - 1) * params.size, - limit: params.size, - order: params.order, - }; - } -}; diff --git a/services/client/common/methods/invoiceOut/sumAmount.js b/services/client/common/methods/invoiceOut/sumAmount.js deleted file mode 100644 index 9f03687ff..000000000 --- a/services/client/common/methods/invoiceOut/sumAmount.js +++ /dev/null @@ -1,27 +0,0 @@ -module.exports = Self => { - Self.remoteMethod('sumAmount', { - description: 'Returns the sum of invoices amount for a client', - accessType: 'READ', - accepts: [{ - arg: 'id', - description: 'The client Id', - type: 'number', - required: true, - http: {source: 'path'} - }], - returns: { - arg: 'sumAmount', - type: 'number' - }, - http: { - path: `/:id/sumAmount`, - verb: 'GET' - } - }); - - Self.sumAmount = async id => { - let query = `SELECT SUM(amount) AS sumAmount FROM vn.invoiceOut WHERE clientFk = ?`; - let result = await Self.rawSql(query, [id]); - return result[0].sumAmount; - }; -}; diff --git a/services/client/common/methods/mandate/filter.js b/services/client/common/methods/mandate/filter.js deleted file mode 100644 index 03482cd72..000000000 --- a/services/client/common/methods/mandate/filter.js +++ /dev/null @@ -1,28 +0,0 @@ -module.exports = Self => { - Self.installMethod('filter', filterParams); - - function filterParams(params) { - return { - where: { - clientFk: params.clientFk - }, - skip: (params.page - 1) * params.size, - limit: params.size, - order: params.order || 'created DESC', - include: [ - { - relation: "mandateType", - scope: { - fields: ["id", "name"] - } - }, - { - relation: "company", - scope: { - fields: ["id", "code"] - } - } - ] - }; - } -}; diff --git a/services/client/common/methods/recovery/filter.js b/services/client/common/methods/recovery/filter.js deleted file mode 100644 index 88263d79b..000000000 --- a/services/client/common/methods/recovery/filter.js +++ /dev/null @@ -1,14 +0,0 @@ -module.exports = Self => { - Self.installMethod('filter', filterParams); - - function filterParams(params) { - return { - where: { - clientFk: params.clientFk - }, - skip: (params.page - 1) * params.size, - limit: params.size, - order: params.order - }; - } -}; diff --git a/services/client/common/models/address-observation.js b/services/client/common/models/address-observation.js deleted file mode 100644 index 579a47adf..000000000 --- a/services/client/common/models/address-observation.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function(Self) { - require('../methods/address/crudAddressObservations.js')(Self); -}; diff --git a/services/client/common/models/address-observation.json b/services/client/common/models/address-observation.json deleted file mode 100644 index 53b6155ec..000000000 --- a/services/client/common/models/address-observation.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "AddressObservation", - "base": "VnModel", - "options": { - "mysql": { - "table": "addressObservation", - "database": "vn" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "description": { - "type": "string", - "required": true - } - }, - "relations": { - "address": { - "type": "belongsTo", - "model": "Address", - "foreignKey": "addressFk" - }, - "observationType": { - "type": "belongsTo", - "model": "ObservationType", - "foreignKey": "observationTypeFk" - } - } - } - \ No newline at end of file diff --git a/services/client/common/models/client-credit.js b/services/client/common/models/client-credit.js deleted file mode 100644 index 7a85976ca..000000000 --- a/services/client/common/models/client-credit.js +++ /dev/null @@ -1,20 +0,0 @@ -module.exports = function(Self) { - Self.installMethod('filter', filterParams); - - function filterParams(params) { - return { - where: { - clientFk: params.clientFk - }, - skip: (params.page - 1) * params.size, - limit: params.size, - order: params.order || 'created DESC', - include: { - relation: "worker", - scope: { - fields: ["id", "firstName", "name"] - } - } - }; - } -}; diff --git a/services/client/common/models/client-observation.json b/services/client/common/models/client-observation.json deleted file mode 100644 index 47654b134..000000000 --- a/services/client/common/models/client-observation.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "ClientObservation", - "description": "Client notes", - "base": "VnModel", - "options": { - "mysql": { - "table": "clientObservation" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "clientFk": { - "type": "Number" - }, - "text": { - "type": "string", - "description": "Text" - }, - "created": { - "type": "date", - "description": "Creation date and time" - } - }, - "relations": { - "worker": { - "type": "belongsTo", - "model": "Worker", - "foreignKey": "workerFk" - }, - "client": { - "type": "hasOne", - "model": "Client", - "foreignKey": "id" - } - }, - "scope": { - "include": "worker" - } -} diff --git a/services/client/common/models/company.json b/services/client/common/models/company.json deleted file mode 100644 index d3700bad6..000000000 --- a/services/client/common/models/company.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "Company", - "description": "Companies", - "base": "VnModel", - "options": { - "mysql": { - "table": "company" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "description": "Identifier" - }, - "code": { - "type": "String" - } - } - } \ No newline at end of file diff --git a/services/client/common/models/credit-insurance.json b/services/client/common/models/credit-insurance.json deleted file mode 100644 index a6d280bc6..000000000 --- a/services/client/common/models/credit-insurance.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "CreditInsurance", - "description": "Credit insurance", - "base": "VnModel", - "options": { - "mysql": { - "table": "creditInsurance" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "description": "Identifier" - }, - "credit": { - "type": "Number" - }, - "created": { - "type": "date", - "mysql": { - "columnName": "creationDate" - } - }, - "grade": { - "type": "Number" - } - }, - "relations": { - "creditClassification": { - "type": "belongsTo", - "model": "CreditClassification", - "foreignKey": "creditClassification" - } - } -} \ No newline at end of file diff --git a/services/client/common/models/greuge.js b/services/client/common/models/greuge.js deleted file mode 100644 index 85a8b3c84..000000000 --- a/services/client/common/models/greuge.js +++ /dev/null @@ -1,9 +0,0 @@ -module.exports = function(Self) { - require('../methods/greuge/filter.js')(Self); - require('../methods/greuge/sumAmount.js')(Self); - - Self.validatesLengthOf('description', { - max: 45, - message: 'La description debe tener maximo 45 caracteres' - }); -}; diff --git a/services/client/common/models/greuge.json b/services/client/common/models/greuge.json deleted file mode 100644 index 8524d3e19..000000000 --- a/services/client/common/models/greuge.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "Greuge", - "base": "VnModel", - "options": { - "mysql": { - "table": "greuge" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "description": "Identifier" - }, - "description": { - "type": "String", - "required": true - }, - "amount": { - "type": "Number", - "required": true - }, - "shipped": { - "type": "date" - }, - "created": { - "type": "date" - } - }, - "relations": { - "client": { - "type": "belongsTo", - "model": "Client", - "foreignKey": "clientFk" - }, - "greugeType": { - "type": "belongsTo", - "model": "GreugeType", - "foreignKey": "greugeTypeFk", - "required": true - } - } - } \ No newline at end of file diff --git a/services/client/common/models/invoice-out.js b/services/client/common/models/invoice-out.js deleted file mode 100644 index c4c5e0dbd..000000000 --- a/services/client/common/models/invoice-out.js +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = function(Self) { - require('../methods/invoiceOut/filter.js')(Self); - require('../methods/invoiceOut/sumAmount.js')(Self); -}; diff --git a/services/client/common/models/invoice-out.json b/services/client/common/models/invoice-out.json deleted file mode 100644 index 704901b08..000000000 --- a/services/client/common/models/invoice-out.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "InvoiceOut", - "base": "VnModel", - "options": { - "mysql": { - "table": "invoiceOut" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "description": "Identifier" - }, - "ref": { - "id": true, - "type": "String", - "required": true - }, - "serial": { - "type": "String" - }, - "issued": { - "type": "date" - }, - "amount": { - "type": "Number" - }, - "created": { - "type": "date" - }, - "dued": { - "type": "date" - }, - "booked": { - "type": "date" - }, - "pdf": { - "type": "Number" - } - }, - "relations": { - "client": { - "type": "belongsTo", - "model": "Client", - "foreignKey": "clientFk" - }, - "company": { - "type": "belongsTo", - "model": "Company", - "foreignKey": "companyFk", - "required": true - } - } - } \ No newline at end of file diff --git a/services/client/common/models/mandate.js b/services/client/common/models/mandate.js deleted file mode 100644 index 82fbd6bb4..000000000 --- a/services/client/common/models/mandate.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function(Self) { - require('../methods/mandate/filter.js')(Self); -}; diff --git a/services/client/common/models/observation-type.json b/services/client/common/models/observation-type.json deleted file mode 100644 index ac3b84092..000000000 --- a/services/client/common/models/observation-type.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "ObservationType", - "base": "VnModel", - "options": { - "mysql": { - "table": "observationType", - "database": "vn" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "description": { - "type": "string", - "required": true - } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ] - } - \ No newline at end of file diff --git a/services/client/common/models/recovery.js b/services/client/common/models/recovery.js deleted file mode 100644 index f3d42d71c..000000000 --- a/services/client/common/models/recovery.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function(Self) { - require('../methods/recovery/filter.js')(Self); -}; diff --git a/services/client/package.json b/services/client/package.json deleted file mode 100644 index d6a815f19..000000000 --- a/services/client/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "vn-client", - "description": "Client service", - "version": "1.0.0", - "license": "GPL-3.0", - "main": "server/server.js", - "scripts": { - "start": "node .", - "posttest": "npm run lint && nsp check" - }, - "repository": { - "type": "git", - "url": "https://git.verdnatura.es/salix" - }, - "dependencies": { - "request": "^2.83.0" - } -} diff --git a/services/client/server/model-config.json b/services/client/server/model-config.json deleted file mode 100644 index ca33ffc1e..000000000 --- a/services/client/server/model-config.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "AddressObservation": { - "dataSource": "vn" - }, - "ClientCredit": { - "dataSource": "vn" - }, - "ClientObservation": { - "dataSource": "vn" - }, - "Company": { - "dataSource": "vn" - }, - "Greuge": { - "dataSource": "vn" - }, - "GreugeType": { - "dataSource": "vn" - }, - "Mandate": { - "dataSource": "vn" - }, - "MandateType": { - "dataSource": "vn" - }, - "ObservationType": { - "dataSource": "vn" - }, - "Recovery": { - "dataSource": "vn" - }, - "InvoiceOut": { - "dataSource": "vn" - }, - "CreditInsurance": { - "dataSource": "vn" - }, - "CreditClassification": { - "dataSource": "vn" - } -} diff --git a/services/client/server/server.js b/services/client/server/server.js deleted file mode 100644 index 030bbc1b4..000000000 --- a/services/client/server/server.js +++ /dev/null @@ -1,5 +0,0 @@ - -var vnLoopback = require('../../loopback/server/server.js'); - -var app = module.exports = vnLoopback.loopback(); -vnLoopback.boot(app, __dirname, module); diff --git a/services/db/.gitignore b/services/db/.gitignore deleted file mode 100644 index f26f7a0a6..000000000 --- a/services/db/.gitignore +++ /dev/null @@ -1 +0,0 @@ -connect.ini diff --git a/services/db/00-truncateAll.sql b/services/db/00-truncateAll.sql deleted file mode 100644 index 9135f7860..000000000 --- a/services/db/00-truncateAll.sql +++ /dev/null @@ -1,37 +0,0 @@ -DROP PROCEDURE IF EXISTS mysql.truncateAll; -DELIMITER $$ -CREATE PROCEDURE mysql.truncateAll() -BEGIN - DECLARE vSchema VARCHAR(255); - DECLARE vTable VARCHAR(255); - DECLARE vDone BOOL; - - DECLARE cTables CURSOR FOR - SELECT `TABLE_SCHEMA`, `TABLE_NAME` - FROM `information_schema`.`TABLES` - WHERE `TABLE_TYPE` = 'BASE TABLE' - AND `TABLE_SCHEMA` NOT IN ('information_schema', 'mysql', 'performance_schema'); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - SET FOREIGN_KEY_CHECKS = FALSE; - OPEN cTables; - - l: LOOP - SET vDone = FALSE; - FETCH cTables INTO vSchema, vTable; - - IF vDone THEN - LEAVE l; - END IF; - - SET @stmt = CONCAT('TRUNCATE TABLE `', vSchema, '`.`', vTable, '`'); - PREPARE stmt FROM @stmt; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END LOOP; - - CLOSE cTables; - SET FOREIGN_KEY_CHECKS = TRUE; -END$$ -DELIMITER ; \ No newline at end of file diff --git a/services/db/01-structure.sql b/services/db/01-structure.sql deleted file mode 100644 index df95b77bc..000000000 --- a/services/db/01-structure.sql +++ /dev/null @@ -1,75631 +0,0 @@ --- MySQL dump 10.13 Distrib 5.7.17, for Win64 (x86_64) --- --- Host: db.verdnatura.es Database: account --- ------------------------------------------------------ --- Server version 5.6.25-4-log - -/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; -/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; -/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; -/*!40101 SET NAMES utf8 */; -/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; -/*!40103 SET TIME_ZONE='+00:00' */; -/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; -/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; -/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; - --- --- Current Database: `account` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `account` /*!40100 DEFAULT CHARACTER SET utf8 */; - -USE `account`; - --- --- Table structure for table `account` --- - -DROP TABLE IF EXISTS `account`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `account` ( - `id` int(10) unsigned NOT NULL, - PRIMARY KEY (`id`), - CONSTRAINT `account_ibfk_3` FOREIGN KEY (`id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Users allowed to have an account'; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `account`.`accountAfterInsert` - AFTER INSERT ON `account` - FOR EACH ROW -BEGIN - UPDATE user SET sync = FALSE - WHERE id = NEW.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_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `account`.`accountAfterDelete` - AFTER DELETE ON `account` - FOR EACH ROW -BEGIN - UPDATE user SET sync = FALSE - WHERE id = OLD.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 */ ; - --- --- Table structure for table `accountConfig` --- - -DROP TABLE IF EXISTS `accountConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `accountConfig` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `homedir` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The base folder for users home directories', - `shell` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The default shell', - `min` smallint(6) NOT NULL, - `max` smallint(6) NOT NULL, - `warn` smallint(6) NOT NULL, - `inact` smallint(6) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration parameters for accounts'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `accountDovecot` --- - -DROP TABLE IF EXISTS `accountDovecot`; -/*!50001 DROP VIEW IF EXISTS `accountDovecot`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `accountDovecot` AS SELECT - 1 AS `name`, - 1 AS `password`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `accountLog` --- - -DROP TABLE IF EXISTS `accountLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `accountLog` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `msg` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `pid` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `user` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `host` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `rhost` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `time` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `accountPam` --- - -DROP TABLE IF EXISTS `accountPam`; -/*!50001 DROP VIEW IF EXISTS `accountPam`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `accountPam` AS SELECT - 1 AS `name`, - 1 AS `password`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `ldapConfig` --- - -DROP TABLE IF EXISTS `ldapConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ldapConfig` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `host` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The hostname of LDAP server', - `rdn` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The LDAP user', - `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Base64 encoded password', - `baseDn` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The base DN to do the query', - `filter` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Filter to apply to the query', - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='LDAP server configuration parameters'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `mailAlias` --- - -DROP TABLE IF EXISTS `mailAlias`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mailAlias` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `alias` varchar(50) CHARACTER SET utf8 NOT NULL, - `isPublic` tinyint(4) NOT NULL DEFAULT '1', - PRIMARY KEY (`id`), - UNIQUE KEY `alias` (`alias`) -) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Mail aliases'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `mailAliasAccount` --- - -DROP TABLE IF EXISTS `mailAliasAccount`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mailAliasAccount` ( - `mailAlias` int(10) unsigned NOT NULL, - `account` int(10) unsigned NOT NULL, - PRIMARY KEY (`mailAlias`,`account`), - KEY `account` (`account`), - CONSTRAINT `account` FOREIGN KEY (`account`) REFERENCES `account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `mailAlias` FOREIGN KEY (`mailAlias`) REFERENCES `mailAlias` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Mail alias that is assigned to each account'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `mailConfig` --- - -DROP TABLE IF EXISTS `mailConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mailConfig` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `domain` varchar(255) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `mailForward` --- - -DROP TABLE IF EXISTS `mailForward`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mailForward` ( - `account` int(10) unsigned NOT NULL, - `forwardTo` varchar(250) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`account`), - CONSTRAINT `mailForward_ibfk_1` FOREIGN KEY (`account`) REFERENCES `account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Mail forwarding'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `role` --- - -DROP TABLE IF EXISTS `role`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `role` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, - `description` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - `hasLogin` tinyint(3) unsigned NOT NULL DEFAULT '0', - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - UNIQUE KEY `name` (`name`) -) ENGINE=InnoDB AUTO_INCREMENT=56 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Roles'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `roleInherit` --- - -DROP TABLE IF EXISTS `roleInherit`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `roleInherit` ( - `role` int(10) unsigned NOT NULL, - `inheritsFrom` int(10) unsigned NOT NULL, - PRIMARY KEY (`role`,`inheritsFrom`), - KEY `owner_id` (`inheritsFrom`), - CONSTRAINT `roleInherit_ibfk_1` FOREIGN KEY (`role`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `roleInherit_ibfk_2` FOREIGN KEY (`inheritsFrom`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Role inheritance'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `roleRole` --- - -DROP TABLE IF EXISTS `roleRole`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `roleRole` ( - `role` int(10) unsigned NOT NULL, - `inheritsFrom` int(10) unsigned NOT NULL, - UNIQUE KEY `role` (`role`,`inheritsFrom`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Calculated role inheritance'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `sambaConfig` --- - -DROP TABLE IF EXISTS `sambaConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `sambaConfig` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `host` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The hosname of Samba server', - `sshUser` varchar(30) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The SSH user to connect to servers', - `sshPass` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The SSH password base64 encoded', - `uidBase` int(10) unsigned NOT NULL DEFAULT '10000' COMMENT 'The base for Unix uids', - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration parameters for accounts'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `user` --- - -DROP TABLE IF EXISTS `user`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `user` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(30) CHARACTER SET utf8 NOT NULL, - `nickname` varchar(127) COLLATE utf8_unicode_ci NOT NULL, - `password` char(64) COLLATE utf8_unicode_ci NOT NULL, - `role` int(10) unsigned NOT NULL DEFAULT '2', - `active` tinyint(1) NOT NULL DEFAULT '1', - `email` varchar(255) CHARACTER SET utf8 DEFAULT NULL, - `lang` char(2) CHARACTER SET utf8 DEFAULT NULL, - `sync` tinyint(4) NOT NULL DEFAULT '0', - `recoverPass` tinyint(3) unsigned NOT NULL DEFAULT '1', - `lastPassChange` datetime DEFAULT NULL, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - UNIQUE KEY `name` (`name`), - KEY `role` (`role`), - KEY `email` (`email`), - KEY `nickname` (`nickname`), - KEY `lang` (`lang`), - CONSTRAINT `user_ibfk_2` FOREIGN KEY (`role`) REFERENCES `role` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=102559 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global users'; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `account`.`userBeforeInsert` - BEFORE INSERT ON `user` - FOR EACH ROW -BEGIN - CALL userCheckName (NEW.`name`); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `account`.`userBeforeUpdate` - BEFORE UPDATE ON `user` - FOR EACH ROW -BEGIN - IF NOT (NEW.`name` <=> OLD.`name`) THEN - CALL userCheckName (NEW.`name`); - END IF; - - IF NOT (NEW.`password` <=> OLD.`password`) THEN - SET NEW.lastPassChange = NOW(); - END IF; - - IF NEW.`sync` <=> OLD.`sync` THEN - SET NEW.`sync` = FALSE; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `userAfterUpdate` - AFTER UPDATE ON `user` - FOR EACH ROW -BEGIN - IF NOT (NEW.`role` <=> OLD.`role`) - THEN - INSERT INTO vn2008.mail SET - `to` = 'jgallego@verdnatura.es', - `reply_to` = 'jgallego@verdnatura.es', - `subject` = 'Rol modificado', - `text` = CONCAT(account.userGetName(), ' ha modificado el rol del usuario ', - NEW.`name`, ' de ', OLD.role, ' a ', NEW.role); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `userConfig` --- - -DROP TABLE IF EXISTS `userConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `userConfig` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `loginKey` varchar(255) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `userPassword` --- - -DROP TABLE IF EXISTS `userPassword`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `userPassword` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `length` tinyint(3) unsigned NOT NULL, - `nAlpha` tinyint(3) unsigned NOT NULL, - `nUpper` tinyint(3) unsigned NOT NULL, - `nDigits` tinyint(3) unsigned NOT NULL, - `nPunct` tinyint(3) unsigned NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Restrictions on user passwords'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `userRole` --- - -DROP TABLE IF EXISTS `userRole`; -/*!50001 DROP VIEW IF EXISTS `userRole`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `userRole` AS SELECT - 1 AS `id`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `userView` --- - -DROP TABLE IF EXISTS `userView`; -/*!50001 DROP VIEW IF EXISTS `userView`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `userView` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `active`, - 1 AS `email`, - 1 AS `nickname`, - 1 AS `lang`, - 1 AS `role`, - 1 AS `recoverPass`*/; -SET character_set_client = @saved_cs_client; - --- --- Dumping events for database 'account' --- - --- --- Dumping routines for database 'account' --- -/*!50003 DROP FUNCTION IF EXISTS `passwordGenerate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `passwordGenerate`() RETURNS text CHARSET utf8 -BEGIN -/** - * Genera una contraseña aleatoria - * cumpliendo los requisitos mínimos. - * - * @return Generated password - */ - DECLARE vMinLength TINYINT(3); - DECLARE vMinAlpha TINYINT(3); - DECLARE vMinUpper TINYINT(3); - DECLARE vMinDigits TINYINT(3); - DECLARE vMinPunct TINYINT(3); - DECLARE vAlpha TINYINT(3) DEFAULT 0; - DECLARE vUpper TINYINT(3) DEFAULT 0; - DECLARE vDigits TINYINT(3) DEFAULT 0; - DECLARE vPunct TINYINT(3) DEFAULT 0; - DECLARE vRandIndex INT; - DECLARE vPwd TEXT DEFAULT ''; - - DECLARE vAlphaChars TEXT DEFAULT 'abcdefghijklmnopqrstuvwxyz'; - DECLARE vUpperChars TEXT DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - DECLARE vDigitChars TEXT DEFAULT '1234567890'; - DECLARE vPunctChars TEXT DEFAULT '!$%&()=.'; - - SELECT length, nAlpha, nUpper, nDigits, nPunct - INTO vMinLength, vMinAlpha, vMinUpper, vMinDigits, vMinPunct FROM userPassword; - - WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha - OR vUpper < vMinUpper OR vDigits < vMinDigits OR vPunct < vMinPunct DO - SET vRandIndex = FLOOR((RAND() * 4) + 1); - - CASE - WHEN vRandIndex = 1 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vAlphaChars, FLOOR((RAND() * 26) + 1), 1)); - SET vAlpha = vAlpha + 1; - WHEN vRandIndex = 2 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vUpperChars, FLOOR((RAND() * 26) + 1), 1)); - SET vUpper = vUpper + 1; - WHEN vRandIndex = 3 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vDigitChars, FLOOR((RAND() * 10) + 1), 1)); - SET vDigits = vDigits + 1; - WHEN vRandIndex = 4 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vPunctChars, FLOOR((RAND() * LENGTH(vPunctChars)) + 1), 1)); - SET vPunct = vPunct + 1; - END CASE; - END WHILE; -RETURN vPwd; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `toUnixDays` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `toUnixDays`(vDate DATE) RETURNS int(11) - DETERMINISTIC -BEGIN -/** - * Devuelve el timestamp unix en días de una fecha. - * - * @param vData La fecha - * @return Unix timestamp en días - */ - RETURN UNIX_TIMESTAMP(vDate) DIV 86400; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `userCheckLogin` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `userCheckLogin`() RETURNS tinyint(1) - READS SQL DATA - DETERMINISTIC -BEGIN -/** - * Checks that variables @userId and @userName haven't been altered. - * - * @return %TRUE if they are unaltered or unset, otherwise %FALSE - */ - DECLARE vSignature VARCHAR(128); - DECLARE vKey VARCHAR(255); - - IF @userId IS NOT NULL - AND @userName IS NOT NULL - AND @userSignature IS NOT NULL - THEN - SELECT loginKey INTO vKey FROM userConfig; - SET vSignature = util.hmacSha2(256, CONCAT_WS('/', @userId, @userName), vKey); - RETURN vSignature = @userSignature; - END IF; - - RETURN FALSE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `userGetId` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `USERGETID`() RETURNS int(11) - READS SQL DATA - DETERMINISTIC -BEGIN -/** - * Returns the current user id. - * - * @return The user id - */ - DECLARE vUser INT DEFAULT NULL; - - IF userCheckLogin() - THEN - SET vUser = @userId; - ELSE - SELECT id INTO vUser FROM user - WHERE name = LEFT(USER(), INSTR(USER(), '@') - 1); - END IF; - - RETURN vUser; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `userGetMysqlRole` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `userGetMysqlRole`(vUserName VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 -BEGIN -/** - * A partir de un nombre de usuario devuelve el rol - * de MySQL asociado y con el que deberia autenticarse - * cuando se utilice sistemas de autenticación externos. - * - * @param vUserName El nombre de usuario - * @return El rol de MySQL asociado - */ - DECLARE vRole VARCHAR(255); - - SELECT CONCAT(IF(r.hasLogin, 'z-', ''), r.name) INTO vRole - FROM role r - JOIN user u ON u.role = r.id - WHERE u.name = vUserName; - - RETURN vRole; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `userGetName` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `userGetName`() RETURNS varchar(30) CHARSET utf8 - NO SQL - DETERMINISTIC -BEGIN -/** - * Returns the current user name. - * - * @return The user name - */ - DECLARE vUser VARCHAR(30) DEFAULT NULL; - - IF userCheckLogin() - THEN - SET vUser = @userName; - ELSE - SET vUser = LEFT(USER(), INSTR(USER(), '@') - 1); - END IF; - - RETURN vUser; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `userGetNameFromId` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `userGetNameFromId`(vId INT) RETURNS varchar(30) CHARSET utf8 -BEGIN -/** - * Obtener nombre de usuari a partir de su id - * - * @param vId Id del usuario - * @return Nombre de usuario - */ - DECLARE vName VARCHAR(30); - - SELECT `name` INTO vName - FROM user - WHERE id = vId; - - RETURN vName; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `userHasRole` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `userHasRole`(vRoleName VARCHAR(255)) RETURNS tinyint(1) - DETERMINISTIC -BEGIN -/** - * Comprueba si el usuario actual tiene asociado un rol. - * - * @param vRoleName Nombre del rol a comprobar - * @return %TRUE si tiene el rol, %FALSE en caso contrario - */ - DECLARE vRoleId INT; - - SELECT id INTO vRoleId - FROM role - WHERE `name` = vRoleName COLLATE 'utf8_unicode_ci'; - - RETURN userHasRoleId (vRoleId); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `userHasRoleId` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `userHasRoleId`(vRoleId INT) RETURNS tinyint(1) - DETERMINISTIC -BEGIN -/** - * Comprueba si el usuario actual tiene asociado un rol. - * - * @param vRoleId Identificador del rol a comprobar - * @return %TRUE si tiene el rol, %FALSE en caso contrario - */ - DECLARE vHasRole BOOL DEFAULT FALSE; - - SELECT COUNT(*) > 0 INTO vHasRole - FROM userRole - WHERE id = vRoleId; - - RETURN vHasRole; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `privSync` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `privSync`() -proc: BEGIN -/** - * Sincroniza los permisos de los usuarios 'rol' de MySQL - * en base a la jerarquía de roles. Los usuarios rol resultantes - * de la mezcla de permisos serán nombrados singuiendo el patrón - * z-[nombre_rol]. - * - * Para que el procedimiento funcione debe de existir un usuario - * any@% que se usara como plantilla base. - * - * ¡Atención! Este procedimiento solo debe ser llamado cuando se - * modifiquen los privilegios de MySQL. Si se modifica la jerarquía - * de roles, se debe llamar al procedimiento roleSync() que llama a - * este internamente. - */ - DECLARE vTplUser VARCHAR(255) DEFAULT 'any'; - DECLARE vHost VARCHAR(255) DEFAULT '%'; - DECLARE vPrefix VARCHAR(2) DEFAULT 'z-'; - - DECLARE vTplExists BOOL; - DECLARE vTplHost VARCHAR(255); - DECLARE vPrefixedLike VARCHAR(255); - - -- Comprueba que el usuario plantilla existe - - SELECT COUNT(*) > 0, `Host` - INTO vTplExists, vTplHost - FROM mysql.user - WHERE `User` = vTplUser - LIMIT 1; - - IF NOT vTplExists THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'TEMPLATE_USER_NOT_EXISTS'; - END IF; - - -- Borra todos los privilegios calculados - - SET vPrefixedLike = CONCAT(vPrefix, '%'); - - DELETE FROM mysql.user - WHERE `User` LIKE vPrefixedLike; - - DELETE FROM mysql.db - WHERE `User` LIKE vPrefixedLike; - - DELETE FROM mysql.tables_priv - WHERE `User` LIKE vPrefixedLike; - - DELETE FROM mysql.columns_priv - WHERE `User` LIKE vPrefixedLike; - - DELETE FROM mysql.procs_priv - WHERE `User` LIKE vPrefixedLike; - - DELETE FROM mysql.proxies_priv - WHERE `Proxied_user` LIKE vPrefixedLike; - - -- Tablas temporales - - DROP TEMPORARY TABLE IF EXISTS tRole; - CREATE TEMPORARY TABLE tRole - ENGINE = MEMORY - SELECT - `name` role, - CONCAT(vPrefix, `name`) prefixedRole - FROM role - WHERE hasLogin; - - DROP TEMPORARY TABLE IF EXISTS tRoleInherit; - CREATE TEMPORARY TABLE tRoleInherit - (INDEX (inheritsFrom)) - ENGINE = MEMORY - SELECT - CONCAT(vPrefix, r.`name`) prefixedRole, - ri.`name` inheritsFrom - FROM role r - JOIN roleRole rr ON rr.role = r.id - JOIN role ri ON ri.id = rr.inheritsFrom; - - -- Vueve a crear el usuario - - INSERT INTO mysql.user ( - `User`, - `Host`, - `Password`, - `ssl_type`, - `ssl_cipher`, - `x509_issuer`, - `x509_subject`, - `max_questions`, - `max_updates`, - `max_connections`, - `max_user_connections` - ) - SELECT - r.prefixedRole, - vTplHost, - IF('' != u.`Password`, - u.`Password`, t.`Password`), - IF('' != u.`ssl_type`, - u.`ssl_type`, t.`ssl_type`), - IF('' != u.`ssl_cipher`, - u.`ssl_cipher`, t.`ssl_cipher`), - IF('' != u.`x509_issuer`, - u.`x509_issuer`, t.`x509_issuer`), - IF('' != u.`x509_subject`, - u.`x509_subject`, t.`x509_subject`), - IF(0 != u.`max_questions`, - u.`max_questions`, t.`max_questions`), - IF(0 != u.`max_updates`, - u.`max_updates`, t.`max_updates`), - IF(0 != u.`max_connections`, - u.`max_connections`, t.`max_connections`), - IF(0 != u.`max_user_connections`, - u.`max_user_connections`, t.`max_user_connections`) - FROM tRole r - JOIN mysql.user t - ON t.`User` = vTplUser - AND t.`Host` = vTplHost - LEFT JOIN mysql.user u - ON u.`User` = r.role - AND u.`Host` = vHost; - - INSERT INTO mysql.proxies_priv ( - `User`, - `Host`, - `Proxied_user`, - `Proxied_host`, - `Grantor` - ) - SELECT - '', - vHost, - prefixedRole, - vHost, - CONCAT(prefixedRole, '@', vTplHost) - FROM tRole; - - -- Copia los privilegios globales del usuario - - DROP TEMPORARY TABLE IF EXISTS tUserPriv; - CREATE TEMPORARY TABLE tUserPriv - (INDEX (prefixedRole)) - ENGINE = MEMORY - SELECT - r.prefixedRole, - MAX(u.`Select_priv`) `Select_priv`, - MAX(u.`Insert_priv`) `Insert_priv`, - MAX(u.`Update_priv`) `Update_priv`, - MAX(u.`Delete_priv`) `Delete_priv`, - MAX(u.`Create_priv`) `Create_priv`, - MAX(u.`Drop_priv`) `Drop_priv`, - MAX(u.`Reload_priv`) `Reload_priv`, - MAX(u.`Shutdown_priv`) `Shutdown_priv`, - MAX(u.`Process_priv`) `Process_priv`, - MAX(u.`File_priv`) `File_priv`, - MAX(u.`Grant_priv`) `Grant_priv`, - MAX(u.`References_priv`) `References_priv`, - MAX(u.`Index_priv`) `Index_priv`, - MAX(u.`Alter_priv`) `Alter_priv`, - MAX(u.`Show_db_priv`) `Show_db_priv`, - MAX(u.`Super_priv`) `Super_priv`, - MAX(u.`Create_tmp_table_priv`) `Create_tmp_table_priv`, - MAX(u.`Lock_tables_priv`) `Lock_tables_priv`, - MAX(u.`Execute_priv`) `Execute_priv`, - MAX(u.`Repl_slave_priv`) `Repl_slave_priv`, - MAX(u.`Repl_client_priv`) `Repl_client_priv`, - MAX(u.`Create_view_priv`) `Create_view_priv`, - MAX(u.`Show_view_priv`) `Show_view_priv`, - MAX(u.`Create_routine_priv`) `Create_routine_priv`, - MAX(u.`Alter_routine_priv`) `Alter_routine_priv`, - MAX(u.`Create_user_priv`) `Create_user_priv`, - MAX(u.`Event_priv`) `Event_priv`, - MAX(u.`Trigger_priv`) `Trigger_priv`, - MAX(u.`Create_tablespace_priv`) `Create_tablespace_priv` - FROM tRoleInherit r - JOIN mysql.user u - ON u.`User` = r.inheritsFrom - AND u.`Host`= vHost - GROUP BY r.prefixedRole; - - UPDATE mysql.user u - JOIN tUserPriv t - ON u.`User` = t.prefixedRole - AND u.`Host` = vHost - SET - u.`Select_priv` - = t.`Select_priv`, - u.`Insert_priv` - = t.`Insert_priv`, - u.`Update_priv` - = t.`Update_priv`, - u.`Delete_priv` - = t.`Delete_priv`, - u.`Create_priv` - = t.`Create_priv`, - u.`Drop_priv` - = t.`Drop_priv`, - u.`Reload_priv` - = t.`Reload_priv`, - u.`Shutdown_priv` - = t.`Shutdown_priv`, - u.`Process_priv` - = t.`Process_priv`, - u.`File_priv` - = t.`File_priv`, - u.`Grant_priv` - = t.`Grant_priv`, - u.`References_priv` - = t.`References_priv`, - u.`Index_priv` - = t.`Index_priv`, - u.`Alter_priv` - = t.`Alter_priv`, - u.`Show_db_priv` - = t.`Show_db_priv`, - u.`Super_priv` - = t.`Super_priv`, - u.`Create_tmp_table_priv` - = t.`Create_tmp_table_priv`, - u.`Lock_tables_priv` - = t.`Lock_tables_priv`, - u.`Execute_priv` - = t.`Execute_priv`, - u.`Repl_slave_priv` - = t.`Repl_slave_priv`, - u.`Repl_client_priv` - = t.`Repl_client_priv`, - u.`Create_view_priv` - = t.`Create_view_priv`, - u.`Show_view_priv` - = t.`Show_view_priv`, - u.`Create_routine_priv` - = t.`Create_routine_priv`, - u.`Alter_routine_priv` - = t.`Alter_routine_priv`, - u.`Create_user_priv` - = t.`Create_user_priv`, - u.`Event_priv` - = t.`Event_priv`, - u.`Trigger_priv` - = t.`Trigger_priv`, - u.`Create_tablespace_priv` - = t.`Create_tablespace_priv`; - - DROP TEMPORARY TABLE tUserPriv; - - -- Copia los privilegios a nivel de esquema - - INSERT INTO mysql.db ( - `User`, - `Host`, - `Db`, - `Select_priv`, - `Insert_priv`, - `Update_priv`, - `Delete_priv`, - `Create_priv`, - `Drop_priv`, - `Grant_priv`, - `References_priv`, - `Index_priv`, - `Alter_priv`, - `Create_tmp_table_priv`, - `Lock_tables_priv`, - `Create_view_priv`, - `Show_view_priv`, - `Create_routine_priv`, - `Alter_routine_priv`, - `Execute_priv`, - `Event_priv`, - `Trigger_priv` - ) - SELECT - r.prefixedRole, - vTplHost, - t.`Db`, - MAX(t.`Select_priv`), - MAX(t.`Insert_priv`), - MAX(t.`Update_priv`), - MAX(t.`Delete_priv`), - MAX(t.`Create_priv`), - MAX(t.`Drop_priv`), - MAX(t.`Grant_priv`), - MAX(t.`References_priv`), - MAX(t.`Index_priv`), - MAX(t.`Alter_priv`), - MAX(t.`Create_tmp_table_priv`), - MAX(t.`Lock_tables_priv`), - MAX(t.`Create_view_priv`), - MAX(t.`Show_view_priv`), - MAX(t.`Create_routine_priv`), - MAX(t.`Alter_routine_priv`), - MAX(t.`Execute_priv`), - MAX(t.`Event_priv`), - MAX(t.`Trigger_priv`) - FROM tRoleInherit r - JOIN mysql.db t - ON t.`User` = r.inheritsFrom - AND t.`Host`= vHost - GROUP BY r.prefixedRole, t.`Db`; - - -- Copia los privilegios a nivel de tabla - - INSERT INTO mysql.tables_priv ( - `User`, - `Host`, - `Db`, - `Table_name`, - `Grantor`, - `Timestamp`, - `Table_priv`, - `Column_priv` - ) - SELECT - r.prefixedRole, - vTplHost, - t.`Db`, - t.`Table_name`, - t.`Grantor`, - MAX(t.`Timestamp`), - GROUP_CONCAT(CONCAT(t.`Table_priv`, ',')), - GROUP_CONCAT(CONCAT(t.`Column_priv`, ',')) - FROM tRoleInherit r - JOIN mysql.tables_priv t - ON t.`User` = r.inheritsFrom - AND t.`Host`= vHost - GROUP BY r.prefixedRole, t.`Db`, t.`Table_name`; - - -- Copia los privilegios a nivel de columna - - INSERT INTO mysql.columns_priv ( - `User`, - `Host`, - `Db`, - `Table_name`, - `Column_name`, - `Timestamp`, - `Column_priv` - ) - SELECT - r.prefixedRole, - vTplHost, - t.`Db`, - t.`Table_name`, - t.`Column_name`, - MAX(t.`Timestamp`), - GROUP_CONCAT(CONCAT(t.`Column_priv`, ',')) - FROM tRoleInherit r - JOIN mysql.columns_priv t - ON t.`User` = r.inheritsFrom - AND t.`Host`= vHost - GROUP BY r.prefixedRole, t.`Db`, t.`Table_name`, t.`Column_name`; - - -- Copia los privilegios de los procedimientos - - INSERT IGNORE INTO mysql.procs_priv ( - `User`, - `Host`, - `Db`, - `Routine_name`, - `Routine_type`, - `Grantor`, - `Timestamp`, - `Proc_priv` - ) - SELECT - r.prefixedRole, - vTplHost, - t.`Db`, - t.`Routine_name`, - t.`Routine_type`, - t.`Grantor`, - t.`Timestamp`, - t.`Proc_priv` - FROM tRoleInherit r - JOIN mysql.procs_priv t - ON t.`User` = r.inheritsFrom - AND t.`Host`= vHost; - - -- Libera memoria - - DROP TEMPORARY TABLE - tRole, - tRoleInherit; - - FLUSH PRIVILEGES; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `roleGetDescendents` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `roleGetDescendents`(vRole INT) -BEGIN -/** - * Obtiene los identificadores de todos los subroles - * implementados por un rol (Incluido el mismo). - * - * @param vRole Identificador del rol - * @table tmp.role Subroles implementados por el rol - */ - DECLARE vIsRoot BOOL; - - DROP TEMPORARY TABLE IF EXISTS - tmp.role, parents, childs; - - CREATE TEMPORARY TABLE tmp.role - (UNIQUE (id)) - ENGINE = MEMORY - SELECT vRole AS id; - - CREATE TEMPORARY TABLE parents - ENGINE = MEMORY - SELECT vRole AS id; - - CREATE TEMPORARY TABLE childs - LIKE parents; - - REPEAT - DELETE FROM childs; - INSERT INTO childs - SELECT DISTINCT r.inheritsFrom id - FROM parents p - JOIN roleInherit r ON r.role = p.id - LEFT JOIN tmp.role t ON t.id = r.inheritsFrom - WHERE t.id IS NULL; - - DELETE FROM parents; - INSERT INTO parents - SELECT * FROM childs; - - INSERT INTO tmp.role - SELECT * FROM childs; - - UNTIL ROW_COUNT() <= 0 - END REPEAT; - - -- If it is root all the roles are added - - SELECT COUNT(*) > 0 INTO vIsRoot - FROM tmp.role - WHERE id = 0; - - IF vIsRoot THEN - INSERT IGNORE INTO tmp.role (id) - SELECT id FROM role; - END IF; - - -- Cleaning - - DROP TEMPORARY TABLE - parents, childs; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `roleSync` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `roleSync`() -BEGIN -/** - * Sincroniza la tabla @roleRole con la jerarquía de roles - * actual. Este procedimiento debe ser llamado cada vez que - * se modifique la tabla @roleInherit para que los cambios - * realizados sobre esta sean efectivos. - */ - DECLARE vRoleId INT; - DECLARE vDone BOOL; - - DECLARE cur CURSOR FOR - SELECT id FROM role; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - TRUNCATE TABLE roleRole; - - OPEN cur; - - l: LOOP - SET vDone = FALSE; - FETCH cur INTO vRoleId; - - IF vDone THEN - LEAVE l; - END IF; - - CALL roleGetDescendents (vRoleId); - - INSERT INTO roleRole (role, inheritsFrom) - SELECT vRoleId, id FROM tmp.role; - - DROP TEMPORARY TABLE tmp.role; - END LOOP; - - CLOSE cur; - - CALL privSync(); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `userChangePassword` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `userChangePassword`(vOldPassword VARCHAR(255), vPassword VARCHAR(255)) -BEGIN -/** - * Changes the current user password, if user is in recovery - * mode ignores the current password. - * - * @param vOldPassword The current password - * @param vPassword The new password - */ - DECLARE vPasswordOk BOOL; - - SELECT `password` = MD5(vOldPassword) OR recoverPass - INTO vPasswordOk - FROM user WHERE id = account.userGetId(); - - IF NOT vPasswordOk THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'Invalid password'; - END IF; - - CALL userSetPassword (userGetName(), vPassword); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `userCheckName` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `userCheckName`(vUserName VARCHAR(255)) -BEGIN -/** - * Comprueba que el nombre de usuario reune los requisitos - * de sintaxis necesarios, en caso contrario lanza una - * excepción. - * El nombre de usuario solo debe contener letras minúsculas - * o, a partir del segundo carácter, números o subguiones. - */ - IF vUserName NOT REGEXP '^[a-z0-9_]*$' THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'INVALID_USER_NAME'; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `userCheckPassword` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `userCheckPassword`(vPassword VARCHAR(255)) -BEGIN -/** - * Comprueba si la contraseña cumple los requisitos de seguridad - * establecidos. Lanza una excepción si no se cumplen. - * - * @param vPassword Contraseña a comprobar - */ - DECLARE vChr CHAR(1); - DECLARE vPasswordOk TINYINT; - DECLARE vI TINYINT DEFAULT 1; - DECLARE vNAlpha TINYINT DEFAULT 0; - DECLARE vNUpper TINYINT DEFAULT 0; - DECLARE vNDigits TINYINT DEFAULT 0; - DECLARE vNPunct TINYINT DEFAULT 0; - - WHILE vI <= CHAR_LENGTH(vPassword) - DO - SET vChr = SUBSTRING(vPassword, vI, 1); - - IF vChr REGEXP '[[:alpha:]]' - THEN - SET vNAlpha = vNAlpha+1; - - IF vChr REGEXP '[A-Z]' - THEN - SET vNUpper = vNUpper+1; - END IF; - ELSEIF vChr REGEXP '[[:digit:]]' - THEN - SET vNDigits = vNDigits+1; - ELSEIF vChr REGEXP '[[:punct:]]' - THEN - SET vNPunct = vNPunct+1; - END IF; - - SET vI = vI+1; - END WHILE; - - SELECT - CHAR_LENGTH(vPassword) >= length - AND vNAlpha >= nAlpha - AND vNUpper >= nUpper - AND vNDigits >= nDigits - AND vNPunct >= nPunct - INTO vPasswordOk - FROM userPassword LIMIT 1; - - IF NOT vPasswordOk THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'Password does not meet requirements'; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `userLogin` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `userLogin`(vUserName VARCHAR(255), vPassword VARCHAR(255)) - READS SQL DATA -BEGIN -/** - * Logs in using the user credentials. - * - * @param vUserName The user name - * @param vPassword The user password - */ - DECLARE vAuthIsOk BOOLEAN DEFAULT FALSE; - - SELECT COUNT(*) = 1 INTO vAuthIsOk FROM user - WHERE name = vUserName - AND password = MD5(vPassword) - AND active; - - IF vAuthIsOk - THEN - CALL userLoginWithName (vUserName); - ELSE - CALL util.throw ('INVALID_CREDENTIALS'); - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `userLoginWithName` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `userLoginWithName`(vUserName VARCHAR(255)) - READS SQL DATA -BEGIN -/** - * Logs in using only the user name. This procedure is - * intended to be executed by users with a high level - * of privileges so that normal users should not have - * execute permissions on it - * - * @param vUserName The user name - */ - DECLARE vUserId INT DEFAULT NULL; - DECLARE vKey VARCHAR(255); - - SELECT id INTO vUserId FROM user - WHERE name = vUserName; - - SELECT loginKey INTO vKey FROM userConfig; - - SET @userId = vUserId; - SET @userName = vUserName; - SET @userSignature = util.hmacSha2(256, CONCAT_WS('/', vUserId, vUserName), vKey); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `userLogout` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `userLogout`() -BEGIN -/** - * Logouts the user. - */ - SET @userId = NULL; - SET @userName = NULL; - SET @userSignature = NULL; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `userSetPassword` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `userSetPassword`(vUserName VARCHAR(255), vPassword VARCHAR(255)) -BEGIN -/** - * Cambia la contraseña del usuario pasado como parámetro. - * Solo los administradores deberian de tener privilegios de - * ejecución sobre el procedimiento ya que no solicita la - * contraseña actual del usuario. - * - * @param vUserName Nombre de usuario - * @param vPassword Nueva contraseña - */ - CALL userCheckPassword (vPassword); - - UPDATE user SET - password = MD5(vPassword), - recoverPass = FALSE - WHERE `name` = vUserName; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Current Database: `util` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `util` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `util`; - --- --- 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(10) unsigned NOT NULL AUTO_INCREMENT, - `dbVersion` char(11) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The current database version', - `hasTriggersDisabled` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Defines if triggers are disabled', - `environment` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The current Database environment', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration table'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `debug` --- - -DROP TABLE IF EXISTS `debug`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `debug` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `connectionId` int(10) unsigned DEFAULT NULL, - `user` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `host` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `variable` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Log de depuración'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'util' --- - --- --- Dumping routines for database 'util' --- -/*!50003 DROP FUNCTION IF EXISTS `capitalizeFirst` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `capitalizeFirst`(vString VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 - NO SQL - DETERMINISTIC -BEGIN -/** - * Pass the first letter of every word in a string to uppercase. - * - * @param vString String to tranform - * @return Transformed string - */ - DECLARE vNewString VARCHAR(255) DEFAULT ''; - DECLARE vI INT DEFAULT 1; - DECLARE vSpaceIni, vWordIni INT; - DECLARE vLen INT DEFAULT CHAR_LENGTH(vString); - - WHILE vI < vLen - DO - SET vSpaceIni = vI; - - WHILE MID(vString, vI, 1) REGEXP '[[:space:]]' DO - SET vI = vI + 1; - END WHILE; - - SET vWordIni = vI; - SET vI = vWordIni + 1; - - WHILE vI <= vLen AND MID(vString, vI, 1) NOT REGEXP '[[:space:]]' DO - SET vI = vI + 1; - END WHILE; - - SET vNewString = CONCAT(vNewString - ,MID(vString, vSpaceIni, vWordIni - vSpaceIni) - ,UPPER(MID(vString, vWordIni, 1)) - ,MID(vString, vWordIni + 1, vI - vWordIni - 1) - ); - END WHILE; - - RETURN vNewString; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `dayEnd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `dayEnd`(vDated DATE) RETURNS datetime - NO SQL - DETERMINISTIC -BEGIN -/** - * Formats a date to the end of the day. - * - * @param vDated The date to format - * @return The formatted date - */ - RETURN TIMESTAMP(vDated, '23:59:59'); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `firstDayOfMonth` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `firstDayOfMonth`(vDate DATE) RETURNS date - NO SQL - DETERMINISTIC -BEGIN -/** - * Returns the date formatted to the first day of month. - * - * @param vDate The date to format - * @return The formatted date - */ - RETURN DATE_FORMAT(vDate, '%Y-%m-01'); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `hmacSha2` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `hmacSha2`(`vAlg` SMALLINT, `vMsg` MEDIUMBLOB, `vKey` MEDIUMBLOB) RETURNS varchar(128) CHARSET utf8 - NO SQL - DETERMINISTIC -BEGIN -/** - * HMAC function based on SHA2 vAlgorythms. - */ - DECLARE vHashlen INT UNSIGNED; - DECLARE vOpad, vIpad TINYBLOB; - - CASE vAlg - WHEN 224 THEN SET vHashlen = 64; - WHEN 256 THEN SET vHashlen = 64; - WHEN 384 THEN SET vHashlen = 128; - WHEN 512 THEN SET vHashlen = 128; - ELSE CALL throw ('WRONG_vALGORYTHM_IDENTIFICATOR_USED'); - END CASE; - - IF LENGTH(vKey) > vHashlen THEN - SET vKey = UNHEX(SHA2(vKey, vAlg)); - END IF; - - SET vKey = RPAD(vKey, vHashlen, 0x00); - - SET vIpad = stringXor(vKey, 0x36); - SET vOpad = stringXor(vKey, 0x5C); - - RETURN SHA2(CONCAT(vOpad, UNHEX(SHA2(CONCAT(vIpad, vMsg), vAlg))), vAlg); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `lang` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `lang`() RETURNS char(2) CHARSET utf8 - NO SQL - DETERMINISTIC -BEGIN -/** - * Returns the current language code. - * - * @return The language code - */ - RETURN IFNULL(@lang, SUBSTR(@@lc_messages, 1, 2)); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `nextWeek` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `nextWeek`(vYearWeek INT) RETURNS int(11) - DETERMINISTIC -BEGIN -/** - * A partir de un perido año/semana en formato AAAASS devuelve el siguiente - * periodo. Esta función trabaja de la misma forma que la función WEEK() en - * modo 3. - */ - DECLARE vYear INT DEFAULT FLOOR(vYearWeek / 100); - - IF vYearWeek < YEARWEEK(CONCAT(vYear, '-12-31'), 3) THEN - RETURN vYearWeek + 1; - ELSE - RETURN ((vYear + 1) * 100) + 1; - 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 */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP FUNCTION IF EXISTS `stringXor` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `stringXor`(vString MEDIUMBLOB, vConst TINYINT UNSIGNED) RETURNS mediumblob - NO SQL - DETERMINISTIC -BEGIN -/** - * Returns XOR of binary string and an 8-bit constant. - */ - DECLARE vLen, vPos INT UNSIGNED; - DECLARE vResult MEDIUMBLOB; - - SET vLen = LENGTH(vString); - SET vPos = 1; - SET vResult = ''; - - WHILE vPos <= vLen DO - SET vResult = CONCAT(vResult, LPAD(HEX( ORD(SUBSTR(vString, vPos, 1)) ^ vConst), 2, '0')); - SET vPos = vPos + 1; - END WHILE; - - RETURN UNHEX(vResult); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `today` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `today`() RETURNS date - DETERMINISTIC -BEGIN -/** - * Devuelve la fecha actual. Usar en lugar de la función nativa - * CURDATE() en aquellos que se necesite rendimiento ya que la - * la última no es determinista. - * - * @return La fecha actual - */ - RETURN CURDATE(); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP FUNCTION IF EXISTS `twoDaysAgo` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `twoDaysAgo`() RETURNS date - DETERMINISTIC -BEGIN -/** - * Devuelve la fecha de antes de ayer. - * - * @return La fecha de antes de ayer - */ - RETURN TIMESTAMPADD(DAY, -2, CURDATE()); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP FUNCTION IF EXISTS `yearRelativePosition` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `yearRelativePosition`(vYear INT) RETURNS varchar(20) CHARSET utf8 - DETERMINISTIC -BEGIN -/** - * Devuelve la posicion del año relativa al año actual. - * Se utiliza como cabecera en informes de balances. - * - * @param vYear Año a evaluar - * @return La posicion relativa del año - */ - DECLARE vCurYear INT DEFAULT YEAR(CURDATE()); - - IF vYear = vCurYear THEN - RETURN 'curYear'; - END IF; - - IF vYear = vCurYear - 1 THEN - RETURN 'lastYear'; - END IF; - - IF vYear = vCurYear - 2 THEN - RETURN 'twoYearsAgo'; - END IF; - - RETURN 'other'; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP FUNCTION IF EXISTS `yesterday` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `yesterday`() RETURNS date - DETERMINISTIC -BEGIN -/** - * Devuelve la fecha de ayer. - * - * @return La fecha de ayer - */ - RETURN TIMESTAMPADD(DAY, -1, CURDATE()); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `debugAdd` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `debugAdd`(vVariable VARCHAR(255), vValue VARCHAR(255)) - MODIFIES SQL DATA -BEGIN -/** - * Añade una entrada de depuración en la tabla @debug. - * - * @param vVariable Nombre de variable - * @param vValue Valor de la variable - */ - DECLARE vIndex INT DEFAULT INSTR(USER(), '@'); - - INSERT INTO debug SET - `connectionId` = CONNECTION_ID(), - `user` = LEFT(USER(), vIndex - 1), - `host` = RIGHT(USER(), CHAR_LENGTH(USER()) - vIndex), - `variable` = vVariable, - `value` = vValue; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `exec` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `exec`(vSqlQuery TEXT) -BEGIN -/** - * Executes a string with an SQL query. - * - * @param vSqlQuery The SQL string - */ - SET @sqlQuery = vSqlQuery; - - PREPARE stmt FROM @sqlQuery; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - - SET @sqlQuery = NULL; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `findObject` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `findObject`(vChain VARCHAR(45)) - READS SQL DATA -BEGIN -/** - * Devuelve un listado de todos los procedimientos, funciones - * eventos, disparadores y vistas que inluyen una cadena dada. - * - * @param vChain Cadena a buscar - * @select Listado de objetos - */ - SET vChain = CONCAT('%', vChain, '%'); - - SELECT * FROM - ( - SELECT - `db`, - `name`, - `type`, - `body`, - `created`, - `modified` - FROM `mysql`.`proc` - WHERE `body` LIKE vChain COLLATE utf8_general_ci - UNION ALL - SELECT - `db`, - `name`, - 'EVENT', - `body_utf8`, - `created`, - `modified` - FROM `mysql`.`event` - WHERE `body_utf8` LIKE vChain COLLATE utf8_general_ci - UNION ALL - SELECT - `EVENT_OBJECT_SCHEMA`, - `TRIGGER_NAME`, - 'TRIGGER', - `ACTION_STATEMENT`, - NULL, - NULL - FROM `information_schema`.`TRIGGERS` - WHERE `ACTION_STATEMENT` LIKE vChain COLLATE utf8_general_ci - UNION ALL - SELECT - `TABLE_SCHEMA`, - `TABLE_NAME`, - 'VIEW', - `VIEW_DEFINITION`, - NULL, - NULL - FROM `information_schema`.`VIEWS` - WHERE `VIEW_DEFINITION` LIKE vChain COLLATE utf8_general_ci - ) t - ORDER BY `db`, `name`; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `throw` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `throw`(vMessage CHAR(35)) -BEGIN -/** - * Throws a user-defined exception. - * - * @param vMessage The error message - */ - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = vMessage; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `warn` */; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`z-developer`@`%` PROCEDURE `warn`(vCode CHAR(35)) -BEGIN - DECLARE w VARCHAR(1) DEFAULT '__'; - SET @warn = vCode; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- --- Current Database: `vn2008` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `vn2008`; - --- --- Table structure for table `Agencias` --- - -DROP TABLE IF EXISTS `Agencias`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Agencias` ( - `Id_Agencia` int(11) NOT NULL AUTO_INCREMENT, - `Agencia` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `description` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Vista` int(11) DEFAULT '0', - `m3` double DEFAULT '0', - `cod71` tinyint(3) unsigned DEFAULT '0', - `web` smallint(1) unsigned zerofill NOT NULL DEFAULT '0', - `agency_id` smallint(6) NOT NULL, - `agency_service_id` tinyint(4) NOT NULL DEFAULT '1', - `inflacion` decimal(5,2) NOT NULL DEFAULT '0.00' COMMENT 'Este valor se utiliza para aumentar el valor del componente porte.', - `is_volumetric` tinyint(1) NOT NULL DEFAULT '0', - `send_mail` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - `show_AgencyName` tinyint(1) DEFAULT '1', - `tpv` tinyint(1) NOT NULL DEFAULT '1', - `externalAgency` tinyint(1) NOT NULL DEFAULT '0', - `flag` blob, - PRIMARY KEY (`Id_Agencia`), - KEY `Agencias` (`Agencia`), - KEY `Vista` (`Vista`) -) ENGINE=InnoDB AUTO_INCREMENT=1203 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Agencias_dits` --- - -DROP TABLE IF EXISTS `Agencias_dits`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Agencias_dits` ( - `idAgencia_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) COLLATE utf8_unicode_ci DEFAULT NULL, - `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`idAgencia_dits`) -) ENGINE=InnoDB AUTO_INCREMENT=16044 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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', - 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 `province` (`province_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `Agencias_province_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `Agencias_province_ibfk_3` FOREIGN KEY (`agency_id`) REFERENCES `agency` (`agency_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Agencias_zonas` --- - -DROP TABLE IF EXISTS `Agencias_zonas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Agencias_zonas` ( - `Id_Agencia` int(11) NOT NULL, - `zona` tinyint(4) NOT NULL, - `price` double NOT NULL, - `Id_Article` int(10) NOT NULL DEFAULT '71', - `warehouse_id` smallint(6) NOT NULL DEFAULT '1', - `porte_minimo` tinyint(1) NOT NULL DEFAULT '0', - `inflacion` decimal(5,2) NOT NULL DEFAULT '1.00', - PRIMARY KEY (`Id_Agencia`,`zona`,`Id_Article`,`warehouse_id`), - KEY `Id_Article` (`Id_Article`), - CONSTRAINT `Agencias_zonas_ibfk_1` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `Agencias_zonas_ibfk_2` FOREIGN KEY (`Id_Agencia`) REFERENCES `Agencias` (`Id_Agencia`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Articles` --- - -DROP TABLE IF EXISTS `Articles`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Articles` ( - `Id_Article` int(11) NOT NULL AUTO_INCREMENT, - `Equivalente` int(11) unsigned DEFAULT NULL, - `Article` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Medida` int(10) unsigned DEFAULT NULL, - `Tallos` int(11) DEFAULT '1', - `PVP` double DEFAULT '0', - `Imprimir` tinyint(1) NOT NULL DEFAULT '0', - `Albaranero` tinyint(1) NOT NULL DEFAULT '0', - `iva_group_id` tinyint(4) unsigned NOT NULL DEFAULT '1', - `Familia` varchar(3) COLLATE utf8_unicode_ci DEFAULT 'VT', - `caja` tinyint(1) NOT NULL DEFAULT '0', - `Categoria` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `id_origen` tinyint(2) unsigned NOT NULL, - `do_photo` tinyint(4) NOT NULL DEFAULT '0', - `Foto` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Color` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `Nicho` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `Codintrastat` int(8) unsigned zerofill DEFAULT NULL, - `Min` tinyint(1) NOT NULL DEFAULT '0', - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `offer` tinyint(4) NOT NULL DEFAULT '0', - `bargain` tinyint(4) NOT NULL DEFAULT '0', - `comments` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'renombrar: reference', - `tipo_id` smallint(5) unsigned NOT NULL, - `generic` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0', - `producer_id` mediumint(3) unsigned DEFAULT NULL, - `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `density` double NOT NULL DEFAULT '167' COMMENT 'Almacena la densidad en kg/m3 para el calculo de los portes, si no se especifica se pone por defecto la del tipo en un trigger', - `relevancy` tinyint(1) NOT NULL DEFAULT '0', - `expenceFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '7001000000', - PRIMARY KEY (`Id_Article`), - KEY `Article` (`Article`), - KEY `Color` (`Color`), - KEY `id_origen` (`id_origen`), - KEY `Codintrastat` (`Codintrastat`), - KEY `iva_group_id` (`iva_group_id`), - KEY `tipo_id` (`tipo_id`), - KEY `producer_id` (`producer_id`), - KEY `expenceFk_idx` (`expenceFk`), - CONSTRAINT `Articles_ibfk_1` FOREIGN KEY (`id_origen`) REFERENCES `Origen` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Articles_ibfk_2` FOREIGN KEY (`Codintrastat`) REFERENCES `Intrastat` (`Codintrastat`) ON UPDATE CASCADE, - CONSTRAINT `Articles_ibfk_4` FOREIGN KEY (`iva_group_id`) REFERENCES `iva_group` (`iva_group_id`) ON UPDATE CASCADE, - CONSTRAINT `Articles_ibfk_5` FOREIGN KEY (`tipo_id`) REFERENCES `Tipos` (`tipo_id`) ON UPDATE CASCADE, - CONSTRAINT `expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `Gastos` (`Id_Gasto`) ON UPDATE CASCADE, - CONSTRAINT `producer_id` FOREIGN KEY (`producer_id`) REFERENCES `producer` (`producer_id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=303660 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`ArticlesBeforeInsert` - BEFORE INSERT ON `Articles` FOR EACH ROW -BEGIN - DECLARE vDensity DOUBLE; - DECLARE vInsertId INT; - - IF NEW.density IS NULL - THEN - SELECT density INTO vDensity - FROM Tipos WHERE tipo_id = NEW.tipo_id; - - SET NEW.density = vDensity; - END IF; - - IF NEW.Foto IS NULL - THEN - SELECT `auto_increment` INTO vInsertId - FROM `information_schema`.TABLES - WHERE `table_name` = 'Articles' - AND `table_schema` = DATABASE(); - - SET NEW.Foto = vInsertId; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`Articles_AFTER_INSERT` AFTER INSERT ON `Articles` FOR EACH ROW -BEGIN - - CALL itemTagArrangedUpdate(NEW.Id_Article); - - INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk) - SELECT NEW.Id_Article, 1, NEW.iva_group_id; - - INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk) - SELECT NEW.Id_Article, 5, NEW.iva_group_id; - - INSERT INTO vn.itemTaxCountry(itemFk, countryFk, taxClassFk) - SELECT NEW.Id_Article, 30, NEW.iva_group_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_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`Articles_AFTER_UPDATE` AFTER UPDATE ON `Articles` FOR EACH ROW -BEGIN - - CALL itemTagArrangedUpdate(NEW.Id_Article); - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `Articles_PVP` --- - -DROP TABLE IF EXISTS `Articles_PVP`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Articles_PVP` ( - `Id_Article` int(11) NOT NULL, - `PVP` double DEFAULT NULL, - `Id_Cliente` int(11) NOT NULL, - `Fecha` date NOT NULL, - KEY `id_article_pvp_idx` (`Id_Article`), - KEY `id_cliente_pvp_idx` (`Id_Cliente`), - CONSTRAINT `id_article_pvp` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `id_cliente_pvp` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los precios para etiquetar los articulos a los clientes'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Articles_botanical` --- - -DROP TABLE IF EXISTS `Articles_botanical`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Articles_botanical` ( - `Id_Article` int(11) NOT NULL, - `botanical` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `genus_id` mediumint(8) unsigned DEFAULT NULL, - `specie_id` mediumint(8) unsigned DEFAULT NULL, - PRIMARY KEY (`Id_Article`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Sustituye a antiguo NomBotanic de Articles'; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `Articles_botanical_bi` BEFORE INSERT ON `Articles_botanical` FOR EACH ROW -BEGIN - IF NEW.botanical = '' THEN - SET NEW.botanical = NULL; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `Articles_botanical_bu` BEFORE UPDATE ON `Articles_botanical` FOR EACH ROW -BEGIN - IF NEW.botanical = '' THEN - SET NEW.botanical = NULL; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `Articles_dits` --- - -DROP TABLE IF EXISTS `Articles_dits`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Articles_dits` ( - `idArticles_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) COLLATE utf8_unicode_ci DEFAULT NULL, - `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`idArticles_dits`), - KEY `fgkey1_idx` (`idaccion_dits`), - KEY `fgkey2_idx` (`Id_Ticket`), - KEY `fgkey3_idx` (`Id_Trabajador`) -) ENGINE=InnoDB AUTO_INCREMENT=19761 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Articles_nicho` --- - -DROP TABLE IF EXISTS `Articles_nicho`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Articles_nicho` ( - `Id_Article` int(11) NOT NULL, - `warehouse_id` smallint(6) unsigned NOT NULL DEFAULT '1', - `nicho` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `modificationDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `id` int(11) NOT NULL AUTO_INCREMENT, - PRIMARY KEY (`id`), - UNIQUE KEY `Id_Article_UNIQUE` (`Id_Article`,`warehouse_id`), - KEY `Articles_nicho_wh_fk` (`warehouse_id`), - CONSTRAINT `Articles_nicho_wh_fk` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `Articles_nichos_fk` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=402653 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Articles_old` --- - -DROP TABLE IF EXISTS `Articles_old`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Articles_old` ( - `Id_Article` int(11) NOT NULL DEFAULT '0', - `Equivalente` int(11) unsigned DEFAULT NULL, - `Article` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Medida` int(10) unsigned DEFAULT NULL, - `Tallos` int(11) DEFAULT '1', - `PVP` double DEFAULT '0', - `Imprimir` tinyint(1) NOT NULL DEFAULT '0', - `Albaranero` tinyint(1) NOT NULL DEFAULT '0', - `iva_group_id` tinyint(4) unsigned NOT NULL DEFAULT '1', - `Familia` varchar(3) COLLATE utf8_unicode_ci DEFAULT 'VT', - `caja` tinyint(1) NOT NULL DEFAULT '0', - `Categoria` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `id_origen` tinyint(2) unsigned NOT NULL, - `do_photo` tinyint(4) NOT NULL DEFAULT '0', - `Foto` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Color` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `Nicho` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `Codintrastat` int(8) unsigned zerofill DEFAULT NULL, - `Min` tinyint(1) NOT NULL DEFAULT '0', - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `offer` tinyint(4) NOT NULL DEFAULT '0', - `bargain` tinyint(4) NOT NULL DEFAULT '0', - `comments` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'renombrar: reference', - `tipo_id` smallint(5) unsigned NOT NULL, - `generic` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0', - `producer_id` mediumint(3) unsigned DEFAULT NULL, - `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Bancos` --- - -DROP TABLE IF EXISTS `Bancos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Bancos` ( - `Id_Banco` int(11) NOT NULL DEFAULT '0', - `Banco` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Cuenta` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `cash` smallint(6) NOT NULL DEFAULT '0', - `warehouse_id` smallint(5) unsigned NOT NULL DEFAULT '1', - `entity_id` int(10) unsigned NOT NULL, - `activo` tinyint(4) NOT NULL DEFAULT '1', - PRIMARY KEY (`Id_Banco`), - KEY `BancosBanco` (`Banco`), - KEY `fk_Bancos_entity1_idx` (`entity_id`), - KEY `foreignkey1_idx` (`cash`), - CONSTRAINT `foreignkey1` FOREIGN KEY (`cash`) REFERENCES `vn`.`accountingType` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Apunta a la vista vn.Accounting\nLa columna cash es la FK de vn.AccountingType'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Bancos_poliza` --- - -DROP TABLE IF EXISTS `Bancos_poliza`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Bancos_poliza` ( - `poliza_id` int(11) NOT NULL AUTO_INCREMENT, - `referencia` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `importe` double NOT NULL, - `com_dispuesto` double DEFAULT NULL, - `com_no_dispuesto` double DEFAULT NULL, - `com_anual` double DEFAULT NULL, - `apertura` date NOT NULL, - `cierre` date DEFAULT NULL, - `Id_Banco` int(11) NOT NULL, - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - PRIMARY KEY (`poliza_id`), - KEY `Id_Banco_Poliza_idx` (`Id_Banco`), - KEY `Id_Poliza_Empresa_idx` (`empresa_id`), - CONSTRAINT `Id_Banco_Poliza` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE, - CONSTRAINT `Id_Poliza_Empresa` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lineas de credito asociadas a cuentas corrientes'; -/*!40101 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) COLLATE utf8_unicode_ci 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=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Cajas` --- - -DROP TABLE IF EXISTS `Cajas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Cajas` ( - `Id_Caja` int(11) NOT NULL AUTO_INCREMENT, - `Cajafecha` date NOT NULL, - `Partida` tinyint(1) NOT NULL DEFAULT '0', - `Serie` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, - `Numero` int(11) DEFAULT NULL, - `Concepto` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `Entrada` decimal(10,2) DEFAULT NULL, - `Salida` decimal(10,2) DEFAULT NULL, - `Id_Banco` int(11) DEFAULT '1', - `Id_Trabajador` int(11) DEFAULT NULL, - `empresa_id` smallint(5) unsigned DEFAULT NULL COMMENT 'kakear', - `linked` tinyint(4) DEFAULT '0', - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `ok` tinyint(4) NOT NULL DEFAULT '0', - `warehouse_id` smallint(5) unsigned NOT NULL DEFAULT '1' COMMENT 'to kak\n', - `conciliado` int(2) NOT NULL DEFAULT '0', - `Proveedores_account_Id` mediumint(8) unsigned NOT NULL, - `id_calculated` varchar(90) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`Id_Caja`), - UNIQUE KEY `id_calculated_UNIQUE` (`id_calculated`), - KEY `CajasCajafecha` (`Cajafecha`), - KEY `Id_Banco` (`Id_Banco`), - KEY `Id_Trabajador` (`Id_Trabajador`), - KEY `empresa_id` (`empresa_id`), - KEY `warehouse_id` (`warehouse_id`), - KEY `fk_Cajas_Proveedores_account1_idx` (`Proveedores_account_Id`), - CONSTRAINT `Cajas_ibfk_2` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=561976 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`CajasBeforeInsert` BEFORE INSERT ON `Cajas` FOR EACH ROW -BEGIN - IF IFNULL(NEW.Concepto,"") = "" THEN - CALL util.throw ('Error. El concepto esta vacío'); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `Cajas eliminadas` --- - -DROP TABLE IF EXISTS `Cajas eliminadas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Cajas eliminadas` ( - `Id_Caja` int(11) NOT NULL DEFAULT '0', - `Cajafecha` datetime DEFAULT NULL, - `Partida` tinyint(1) NOT NULL DEFAULT '0', - `Serie` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, - `Numero` int(11) DEFAULT NULL, - `Concepto` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `Entrada` double DEFAULT NULL, - `Salida` double DEFAULT NULL, - PRIMARY KEY (`Id_Caja`), - KEY `CajasCajafecha` (`Cajafecha`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`Id_Clase`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Clientes` --- - -DROP TABLE IF EXISTS `Clientes`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Clientes` ( - `id_cliente` int(11) NOT NULL AUTO_INCREMENT, - `cliente` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `descuento` tinyint(3) unsigned NOT NULL DEFAULT '0', - `default_address` int(11) DEFAULT NULL, - `domicilio` longtext COLLATE utf8_unicode_ci, - `if` varchar(14) COLLATE utf8_unicode_ci DEFAULT NULL, - `telefono` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `fax` varchar(11) COLLATE utf8_unicode_ci DEFAULT NULL, - `e-mail` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, - `cc` varchar(23) COLLATE utf8_unicode_ci DEFAULT NULL, - `vencimiento` smallint(6) NOT NULL DEFAULT '5', - `recibo` int(11) DEFAULT '1' COMMENT 'Deprecated', - `oficial` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Deprecated', - `contabilizado` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Deprecated', - `movil` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `Cuenta` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `RE` tinyint(1) NOT NULL DEFAULT '0', - `poblacion` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL, - `province_id` smallint(5) unsigned DEFAULT NULL, - `codPostal` varchar(8) COLLATE utf8_unicode_ci DEFAULT NULL, - `razonSocial` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL, - `contacto` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `mayorista` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Deprecated', - `reexpedicion` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Deprecated', - `invoice` tinyint(1) NOT NULL DEFAULT '1', - `notas` text COLLATE utf8_unicode_ci COMMENT 'Deprecated', - `notas_administracion` text COLLATE utf8_unicode_ci NOT NULL COMMENT 'Deprecated', - `copiaFactura` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Deprecated', - `retener` tinyint(1) NOT NULL DEFAULT '0', - `congelado` tinyint(1) NOT NULL DEFAULT '0', - `Id_Trabajador` int(11) DEFAULT NULL, - `credito` decimal(10,2) NOT NULL DEFAULT '0.00', - `cyc` double DEFAULT NULL, - `Id_Pais` mediumint(8) unsigned NOT NULL DEFAULT '1', - `activo` tinyint(1) NOT NULL DEFAULT '1', - `gestdoc_id` int(11) DEFAULT NULL, - `calidad` int(2) DEFAULT '11', - `pay_met_id` tinyint(3) unsigned NOT NULL DEFAULT '5', - `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `mail` tinyint(1) NOT NULL DEFAULT '1', - `chanel_id` smallint(6) DEFAULT NULL, - `vies` tinyint(4) NOT NULL DEFAULT '0', - `split_holland` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'eliminar', - `sepaFth` tinyint(1) DEFAULT '0' COMMENT 'campo para recibir los escritos de los clientes para el sepa', - `sepaVnl` tinyint(1) DEFAULT '0', - `coreFth` tinyint(1) DEFAULT '0', - `coreVnl` tinyint(1) DEFAULT '0', - `risk_calculated` date NOT NULL, - `coreVnh` tinyint(1) DEFAULT '0', - `real` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Define los clientes cuyas ventas hay que tener en cuenta en los calculos estadisticos.', - `clientes_tipo_id` int(11) NOT NULL DEFAULT '1', - `postcode_id` int(11) unsigned DEFAULT NULL, - `mail_address` int(11) DEFAULT NULL, - `codpos` char(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `creditInsurance` int(11) DEFAULT NULL, - `EYPBC` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Email\nYesterday\nPurchases\nBy\nConsigna', - `invoiceByAddress` tinyint(1) DEFAULT '0', - `cplusTerIdNifFk` int(11) NOT NULL DEFAULT '1' COMMENT 'OBSOLETO', - `isCreatedAsServed` tinyint(1) DEFAULT '0', - `hasInvoiceSimplified` tinyint(1) NOT NULL DEFAULT '0', - `iban` varchar(45) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`id_cliente`), - UNIQUE KEY `IF` (`if`), - KEY `Id_Trabajador` (`Id_Trabajador`), - KEY `Id_Pais` (`Id_Pais`), - KEY `pay_met_id` (`pay_met_id`), - KEY `canal_nuevo_cliente` (`chanel_id`), - KEY `Cuenta` (`Cuenta`), - KEY `province_id` (`province_id`), - KEY `default_address` (`default_address`), - KEY `Telefono` (`telefono`), - KEY `movil` (`movil`), - KEY `tipos_de_cliente_idx` (`clientes_tipo_id`), - KEY `codpos` (`codpos`,`codPostal`), - CONSTRAINT `Clientes_ibfk_1` FOREIGN KEY (`Id_Pais`) REFERENCES `Paises` (`Id`) ON UPDATE CASCADE, - CONSTRAINT `Clientes_ibfk_2` FOREIGN KEY (`pay_met_id`) REFERENCES `pay_met` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Clientes_ibfk_3` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `Clientes_ibfk_4` FOREIGN KEY (`default_address`) REFERENCES `Consignatarios` (`id_consigna`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `Clientes_ibfk_5` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON UPDATE CASCADE, - CONSTRAINT `canal_nuevo_cliente` FOREIGN KEY (`chanel_id`) REFERENCES `chanel` (`chanel_id`) ON UPDATE CASCADE, - CONSTRAINT `tipos_de_cliente` FOREIGN KEY (`clientes_tipo_id`) REFERENCES `clientes_tipo` (`clientes_tipo_id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=102559 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `ClientesBeforeInsert` - BEFORE INSERT ON `Clientes` - FOR EACH ROW -BEGIN - DECLARE isAlreadyUsedIf BOOL; - - SELECT COUNT(*) INTO isAlreadyUsedIf - FROM Clientes - WHERE `IF` = TRIM(NEW.`IF`); - - IF isAlreadyUsedIf THEN - CALL util.throw ('Error. El NIF/CIF está repetido'); - END IF; - - CALL pbx.phoneIsValid (NEW.telefono); - CALL pbx.phoneIsValid (NEW.movil); - CALL pbx.phoneIsValid (NEW.fax); - - SET NEW.cuenta = 4300000000 + NEW.Id_Cliente; - - IF NEW.pay_met_id = 4 AND NEW.Vencimiento = 0 THEN - SET NEW.Vencimiento = 5; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`ClientesAfterInsert` - AFTER INSERT ON `vn2008`.`Clientes` - FOR EACH ROW -BEGIN - INSERT INTO Consignatarios SET - Id_Cliente = NEW.Id_Cliente, - Domicilio = NEW.domicilio, - Poblacion = NEW.POBLACION, - province_id = NEW.province_id, - Codpostal = NEW.CODPOSTAL, - Consignatario = NEW.Cliente, - Predeterminada = TRUE, - Id_Agencia = 2, - isEqualizated = NEW.RE; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `ClientesBeforeUpdate` - BEFORE UPDATE ON `Clientes` - FOR EACH ROW -BEGIN - DECLARE vText VARCHAR(255) DEFAULT NULL; - DECLARE isAlreadyUsedIf BOOLEAN; - - SELECT (COUNT(*) > 1) INTO isAlreadyUsedIf - FROM Clientes - WHERE `IF` = TRIM(NEW.`IF`); - - IF isAlreadyUsedIf THEN - CALL util.throw ('Error. El NIF/CIF está repetido'); - END IF; - - -- Comprueba que el formato de los teléfonos es válido - - IF !(NEW.telefono <=> OLD.telefono) THEN - CALL pbx.phoneIsValid (NEW.telefono); - END IF; - - IF !(NEW.movil <=> OLD.movil) THEN - CALL pbx.phoneIsValid (NEW.movil); - END IF; - - IF !(NEW.fax <=> OLD.fax) THEN - CALL pbx.phoneIsValid (NEW.fax); - END IF; - - -- Actualiza el log del crédito - - IF !(NEW.Credito <=> OLD.Credito) AND IFNULL(NEW.Credito, 0) >= 0 - THEN - INSERT INTO credit SET - Id_Cliente = NEW.Id_Cliente, - amount = NEW.Credito, - Id_Trabajador = vn.getWorker(); - END IF; - - -- Avisar al comercial si ha llegado la documentación sepa/core - - IF NEW.sepavnl AND !OLD.sepavnl THEN - SET vText = 'Sepa de VNL'; - END IF; - - IF NEW.corevnl AND !OLD.corevnl THEN - SET vText = 'Core de VNL'; - END IF; - - IF vText IS NOT NULL - THEN - INSERT INTO mail(`to`, reply_to, subject, text) - SELECT - CONCAT(IF(ac.id,name, 'jgallego'), '@verdnatura.es'), - 'administracion@verdnatura.es', - CONCAT('Cliente ', NEW.Id_Cliente), - CONCAT('Recibida la documentación: ', vText) - FROM Trabajadores t - LEFT JOIN account.user u ON t.user_id = u.id AND active - LEFT JOIN account.account ac ON ac.id = u.id - WHERE t.Id_Trabajador = NEW.Id_Trabajador; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `Clientes_cedidos` --- - -DROP TABLE IF EXISTS `Clientes_cedidos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Clientes_cedidos` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `Id_Cliente` int(11) NOT NULL, - `Id_Trabajador_old` int(11) NOT NULL, - `Id_Trabajador_new` int(11) NOT NULL, - `datSTART` date NOT NULL, - `datEND` date NOT NULL, - `comision_old` double NOT NULL DEFAULT '0.5', - `comision_new` double NOT NULL DEFAULT '0.5', - PRIMARY KEY (`id`), - KEY `trabajador_fk_idx` (`Id_Trabajador_old`), - KEY `new_trabajador_fk_idx` (`Id_Trabajador_new`), - KEY `cliente_cedido_fk_idx` (`Id_Cliente`), - CONSTRAINT `cliente_cedido_fk` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `new_trabajador_fk` FOREIGN KEY (`Id_Trabajador_new`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `trabajador_fk` FOREIGN KEY (`Id_Trabajador_old`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Clientes que se han cambiado de comercial, pero durante un tiempo comisionan a los dos, al anterior y al actual'; -/*!40101 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) COLLATE utf8_unicode_ci DEFAULT NULL, - `value_new` varchar(100) COLLATE utf8_unicode_ci 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 AUTO_INCREMENT=71651 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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` smallint(5) 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 `empresa_id` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON DELETE NO ACTION -) ENGINE=InnoDB AUTO_INCREMENT=470507 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Empresa por defecto para crear los tickets'; -/*!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 `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `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) COLLATE utf8_unicode_ci DEFAULT NULL, - `ACTIVIDAD` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `NOMBRE` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `PROVINCIA` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL, - `POBLACION` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `CP` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `DIR_POSTAL` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `TELEFONO` varchar(12) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `TELEFONO2` varchar(12) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `FAX` varchar(12) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `E-MAIL` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `pagweb` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `SERVICIOS` varchar(45) COLLATE utf8_unicode_ci 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) COLLATE utf8_unicode_ci DEFAULT NULL, - `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`NOMBRE`,`POBLACION`,`DIR_POSTAL`,`TELEFONO`,`TELEFONO2`,`FAX`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Colas` --- - -DROP TABLE IF EXISTS `Colas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Colas` ( - `Id_Cola` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Id_Impresora` tinyint(3) unsigned DEFAULT '0', - `Id_Prioridad` tinyint(3) unsigned DEFAULT '2', - `Id_Informe` tinyint(3) unsigned DEFAULT '0', - `Id_Estado` tinyint(3) unsigned DEFAULT '1', - `Hora_Inicio` datetime DEFAULT NULL, - `Hora_Fin` datetime DEFAULT NULL, - `Cola` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Id_Trabajador` int(11) DEFAULT '20', - `Cola2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `Cola3` text COLLATE utf8_unicode_ci, - `error` text COLLATE utf8_unicode_ci, - PRIMARY KEY (`Id_Cola`), - UNIQUE KEY `Id_Impresora_2` (`Id_Impresora`,`Id_Prioridad`,`Id_Informe`,`Id_Estado`,`Cola`,`Id_Trabajador`,`Cola2`), - KEY `Id_estado` (`Id_Estado`), - KEY `Id_Impresora` (`Id_Impresora`), - KEY `Id_Informe` (`Id_Informe`), - KEY `Id_Prioridad` (`Id_Prioridad`), - KEY `Id_Trabajador` (`Id_Trabajador`), - CONSTRAINT `Colas_ibfk_1` FOREIGN KEY (`Id_Informe`) REFERENCES `Informes` (`Id_Informe`) ON UPDATE CASCADE, - CONSTRAINT `Colas_ibfk_2` FOREIGN KEY (`Id_Estado`) REFERENCES `Estados` (`Id_Estado`) ON UPDATE CASCADE, - CONSTRAINT `Colas_ibfk_3` FOREIGN KEY (`Id_Prioridad`) REFERENCES `Prioridades` (`Id_Prioridad`) ON UPDATE CASCADE, - CONSTRAINT `Colas_ibfk_4` FOREIGN KEY (`Id_Impresora`) REFERENCES `Impresoras` (`Id_Impresora`) ON UPDATE CASCADE, - CONSTRAINT `Colas_ibfk_5` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=83645 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Colores` --- - -DROP TABLE IF EXISTS `Colores`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Colores` ( - `Id_Color` int(11) NOT NULL DEFAULT '0', - `Color` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`Id_Color`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Comparativa` --- - -DROP TABLE IF EXISTS `Comparativa`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Comparativa` ( - `Periodo` int(11) NOT NULL, - `Id_Article` bigint(20) NOT NULL, - `warehouse_id` int(11) NOT NULL, - `Cantidad` mediumint(9) NOT NULL DEFAULT '0', - `price` mediumint(8) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`Periodo`,`Id_Article`,`warehouse_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Compres` --- - -DROP TABLE IF EXISTS `Compres`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Compres` ( - `Id_Compra` int(11) NOT NULL AUTO_INCREMENT, - `Id_Entrada` int(11) NOT NULL DEFAULT '0', - `Id_Article` int(11) NOT NULL DEFAULT '90', - `Cantidad` int(11) DEFAULT '0', - `dispatched` int(11) NOT NULL DEFAULT '0', - `Costefijo` decimal(10,3) DEFAULT '0.000', - `Portefijo` decimal(10,3) DEFAULT '0.000', - `Novincular` tinyint(1) NOT NULL DEFAULT '0', - `Etiquetas` int(11) DEFAULT '0', - `Packing` int(11) DEFAULT '0', - `grouping` smallint(5) unsigned NOT NULL DEFAULT '1', - `caja` tinyint(4) NOT NULL COMMENT '0=sin obligar 1=groping 2=packing', - `container_id` smallint(5) unsigned NOT NULL DEFAULT '36', - `Comisionfija` decimal(10,3) DEFAULT '0.000', - `Embalajefijo` decimal(10,3) DEFAULT '0.000', - `Nicho` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `Id_Cubo` varchar(10) COLLATE utf8_unicode_ci DEFAULT '--', - `Tarifa1` decimal(10,2) DEFAULT '0.00', - `Tarifa2` decimal(10,2) DEFAULT '0.00', - `Tarifa3` decimal(10,2) DEFAULT '0.00', - `PVP` decimal(10,2) DEFAULT '0.00', - `Productor` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Vida` int(11) DEFAULT '0', - `Id_Trabajador` int(11) DEFAULT '0', - `punteo` tinyint(1) NOT NULL DEFAULT '0', - `Volumenkk` int(11) DEFAULT NULL, - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `cm2kk` int(10) unsigned NOT NULL DEFAULT '0', - `buy_edi_id` int(11) DEFAULT NULL, - PRIMARY KEY (`Id_Compra`), - KEY `CompresId_Trabajador` (`Id_Trabajador`), - KEY `Id_Cubo` (`Id_Cubo`), - KEY `Id_Entrada` (`Id_Entrada`), - KEY `container_id` (`container_id`), - KEY `buy_edi_id` (`buy_edi_id`), - KEY `itemFk_entryFk` (`Id_Article`,`Id_Entrada`), - CONSTRAINT `Compres_ibfk_1` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON UPDATE CASCADE, - CONSTRAINT `Compres_ibfk_2` FOREIGN KEY (`Id_Cubo`) REFERENCES `Cubos` (`Id_Cubo`) ON UPDATE CASCADE, - CONSTRAINT `Compres_ibfk_3` FOREIGN KEY (`container_id`) REFERENCES `container` (`container_id`) ON UPDATE CASCADE, - CONSTRAINT `buy_id` FOREIGN KEY (`Id_Entrada`) REFERENCES `Entradas` (`Id_Entrada`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=241963558 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`compresBeforeInsert` - BEFORE INSERT ON `vn2008`.`Compres` FOR EACH ROW -BEGIN - DECLARE vWarehouse INT; - DECLARE vLanding DATE; - DECLARE vGroup INT; - DECLARE vIsBox BOOL; - - IF NEW.grouping = 0 THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT ='ERROR_GROUPING_ZERO'; - END IF; - - SELECT warehouse_id, landing INTO vWarehouse, vLanding - FROM Entradas E - JOIN travel T ON T.id = E.travel_id - WHERE E.Id_Entrada = NEW.Id_Entrada; - - SELECT grouping, caja INTO vGroup, vIsBox - FROM Compres C - JOIN Entradas E USING(Id_Entrada) - JOIN travel T ON T.id = E.travel_id - WHERE T.landing <= vLanding - AND C.Id_Article = NEW.Id_Article - AND NOT C.Novincular - ORDER BY warehouse_id = vWarehouse DESC,landing DESC, Id_Compra DESC - LIMIT 1; - - SET NEW.grouping = IFNULL(vGroup,IFNULL( NEW.grouping,1)); - SET NEW.caja = IFNULL(vIsBox, IFNULL( NEW.caja,0)); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `CompresAfterInsert` AFTER INSERT ON `Compres` FOR EACH ROW BEGIN - DECLARE vWarehouse INT; - DECLARE vWarehouseOut INT; - - CALL stock.queueAdd ('buy', NEW.Id_Compra, NULL); - - SELECT warehouse_id, warehouse_id_out INTO vWarehouse, vWarehouseOut - FROM Entradas E - JOIN travel T ON T.id = E.travel_id - WHERE E.Id_Entrada = NEW.Id_Entrada; - - -- Actualiza el volumen unitario - - REPLACE bi.rotacion(Id_Article, warehouse_id, cm3) - VALUES (NEW.Id_ARticle, vWarehouse, vn2008.cm3_unidad(NEW.Id_Compra)); - - IF (SELECT fuente FROM warehouse where id = vWarehouseOut AND id <> 13) AND - (SELECT has_notify_passport(NEW.Id_Article,NEW.Id_Compra)) - THEN - CALL notify_passport(NEW.Id_Article, NEW.Etiquetas, NEW.Packing,NEW.Id_Compra); - CALL insert_producer_plantpassport(NEW.Id_Compra); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `CompresBeforeUpdate` - BEFORE UPDATE ON `Compres` FOR EACH ROW -BEGIN - IF NEW.grouping = 0 AND OLD.grouping <> 0 THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT ='ERROR_GROUPING_ZERO'; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `CompresAfterUpdate` - AFTER UPDATE ON `Compres` FOR EACH ROW -BEGIN - DECLARE vWarehouse INT; - DECLARE vWarehouseOut INT; - - CALL stock.queueAdd ('buy', NEW.Id_Compra, OLD.Id_Compra); - - SELECT warehouse_id, warehouse_id_out INTO vWarehouse, vWarehouseOut - FROM Entradas E - JOIN travel T ON T.id = E.travel_id - WHERE E.Id_Entrada = NEW.Id_Entrada; - - IF NOT(NEW.Id_Cubo <=> OLD.Id_Cubo AND NEW.Id_Entrada <=> OLD.Id_Entrada) - THEN - REPLACE bi.rotacion(Id_Article, warehouse_id, cm3) - VALUES (NEW.Id_ARticle, vWarehouse, vn2008.cm3_unidad(NEW.Id_Compra)); - END IF; - - IF (SELECT fuente FROM warehouse where id = vWarehouseOut AND id <> 13) AND - (SELECT has_notify_passport(NEW.Id_Article,NEW.Id_Compra)) > 0 - THEN - CALL notify_passport(NEW.Id_Article, NEW.Etiquetas, NEW.Packing,NEW.Id_Compra); - CALL insert_producer_plantpassport(NEW.Id_Compra); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`CompresAfterDelete` - AFTER DELETE ON `Compres` FOR EACH ROW -BEGIN - DECLARE vProvider INT; - - CALL stock.queueAdd ('buy', NULL, OLD.Id_Compra); - - SELECT Id_Proveedor INTO vProvider - FROM Entradas WHERE Id_Entrada = OLD.Id_Entrada; - - IF OLD.Vida > 0 AND vProvider <> 4 THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT ='ERROR_DELETING_LIFE'; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `Compres_2014_kk` --- - -DROP TABLE IF EXISTS `Compres_2014_kk`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Compres_2014_kk` ( - `Id_Compra` int(11) NOT NULL AUTO_INCREMENT, - `Id_Entrada` int(11) NOT NULL DEFAULT '0', - `Id_Article` int(11) NOT NULL DEFAULT '90', - `Cantidad` int(11) DEFAULT '0', - `Costefijo` decimal(10,3) DEFAULT '0.000', - `Portefijo` decimal(10,3) DEFAULT '0.000', - `Novincular` tinyint(1) NOT NULL DEFAULT '0', - `Etiquetas` int(11) DEFAULT '0', - `Packing` int(11) DEFAULT '0', - `grouping` smallint(5) unsigned NOT NULL DEFAULT '1', - `caja` tinyint(4) NOT NULL COMMENT '0=sin obligar 1=groping 2=packing', - `container_id` smallint(5) unsigned NOT NULL DEFAULT '36', - `Comisionfija` decimal(10,3) DEFAULT '0.000', - `Embalajefijo` decimal(10,3) DEFAULT '0.000', - `Nicho` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `Id_Cubo` varchar(10) COLLATE utf8_unicode_ci DEFAULT '--', - `Tarifa1` decimal(10,2) DEFAULT '0.00', - `Tarifa2` decimal(10,2) DEFAULT '0.00', - `Tarifa3` decimal(10,2) DEFAULT '0.00', - `PVP` decimal(10,2) DEFAULT '0.00', - `Productor` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Vida` int(11) DEFAULT '0', - `Id_Trabajador` int(11) DEFAULT '0', - `punteo` tinyint(1) NOT NULL DEFAULT '0', - `Volumenkk` int(11) DEFAULT NULL, - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `cm2kk` int(10) unsigned NOT NULL DEFAULT '0', - `buy_edi_id` int(11) DEFAULT NULL, - PRIMARY KEY (`Id_Compra`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Compres_mark` --- - -DROP TABLE IF EXISTS `Compres_mark`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Compres_mark` ( - `Id_Compra` int(11) NOT NULL, - `comment` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `mark` tinyint(1) DEFAULT NULL, - `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`Id_Compra`), - CONSTRAINT `Compres_mark_ibfk_1` FOREIGN KEY (`Id_Compra`) REFERENCES `Compres` (`Id_Compra`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `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(11) NOT NULL, - `Id_Accion` varchar(45) COLLATE utf8_unicode_ci 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`), - CONSTRAINT `Compres_ok_ibfk_1` FOREIGN KEY (`Id_Compra`) REFERENCES `Compres` (`Id_Compra`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=16747 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Consignatarios` --- - -DROP TABLE IF EXISTS `Consignatarios`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Consignatarios` ( - `id_consigna` int(11) NOT NULL AUTO_INCREMENT, - `Id_cliente` int(11) NOT NULL DEFAULT '0', - `warehouse_id` smallint(6) unsigned DEFAULT '1', - `domicilio` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `poblacion` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL, - `province_id` smallint(5) unsigned DEFAULT NULL, - `codPostal` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `telefono` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `movil` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `consignatario` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL, - `predeterminada` tinyint(1) NOT NULL DEFAULT '1', - `Id_Agencia` int(11) NOT NULL DEFAULT '2', - `especificaciones` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `seguro` tinyint(1) NOT NULL DEFAULT '0', - `porte` double DEFAULT NULL, - `active` tinyint(4) NOT NULL DEFAULT '1', - `postcode_id` int(11) unsigned DEFAULT NULL, - `longitude` decimal(11,7) DEFAULT NULL, - `latitude` decimal(11,7) DEFAULT NULL, - `codPos` char(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `isEqualizated` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`id_consigna`), - KEY `Id_Agencia` (`Id_Agencia`), - KEY `Id_cliente` (`Id_cliente`), - KEY `warehouse_id` (`warehouse_id`), - KEY `province_id` (`province_id`), - KEY `telefono` (`telefono`), - KEY `movil` (`movil`), - KEY `CODPOSTAL` (`codPostal`), - CONSTRAINT `Consignatarios_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `Consignatarios_ibfk_3` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON UPDATE CASCADE, - CONSTRAINT `Consignatarios_ibfk_4` FOREIGN KEY (`Id_Agencia`) REFERENCES `Agencias` (`Id_Agencia`) ON UPDATE CASCADE, - CONSTRAINT `address_customer_id` FOREIGN KEY (`Id_cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=24415 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`ConsignatariosBeforeInsert` -BEFORE INSERT ON `vn2008`.`Consignatarios` -FOR EACH ROW -BEGIN - DECLARE v_has_default BOOLEAN; - DECLARE vIsEqualizated BOOLEAN; - - CALL pbx.phoneIsValid (NEW.telefono); - CALL pbx.phoneIsValid (NEW.movil); - - SELECT COUNT(*) > 0 INTO v_has_default - FROM Consignatarios - WHERE Id_Cliente = NEW.Id_Cliente - AND Predeterminada <> FALSE; - - IF NEW.Predeterminada AND v_has_default THEN - SET NEW.Predeterminada = FALSE; - END IF; - - IF NEW.isEqualizated IS NULL THEN - SELECT RE - INTO vIsEqualizated - FROM Clientes - WHERE Id_Cliente = NEW.Id_Cliente; - - SET NEW.isEqualizated = vIsEqualizated; - END IF; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`ConsignatariosBeforeUpdate` -BEFORE UPDATE ON `vn2008`.`Consignatarios` -FOR EACH ROW -BEGIN - DECLARE vHasDefault BOOLEAN; - - CALL pbx.phoneIsValid (NEW.telefono); - CALL pbx.phoneIsValid (NEW.movil); - - SELECT COUNT(*) > 0 INTO vHasDefault - FROM Consignatarios - WHERE Id_Cliente = NEW.Id_Cliente - AND Predeterminada <> FALSE; - - IF NOT OLD.Predeterminada AND NEW.Predeterminada AND vHasDefault THEN - SET NEW.Predeterminada = FALSE; - END IF; - - IF NOT NEW.active AND (NEW.active != OLD.active) AND NEW.Predeterminada THEN - CALL util.throw ('NO SE PUEDE DESACTIVAR EL CONSIGNATARIO PREDETERMINADO'); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`ConsignatariosAfterUpdate` AFTER UPDATE ON `Consignatarios` FOR EACH ROW -BEGIN - DECLARE vCurDefault INT; - DECLARE vNewDefault INT; - - IF NEW.Predeterminada AND (NEW.Predeterminada != OLD.Predeterminada) - THEN - UPDATE Clientes SET default_address = NEW.Id_Consigna - WHERE Id_cliente = NEW.Id_cliente; - END IF; - - IF NOT NEW.active AND (NEW.active != OLD.active) - THEN - SELECT default_address INTO vCurDefault - FROM Clientes - WHERE Id_Cliente = NEW.Id_Cliente; - - IF vCurDefault = NEW.Id_Consigna - THEN - SELECT Id_Consigna INTO vNewDefault - FROM Consignatarios - WHERE Id_Cliente = NEW.Id_Cliente AND active - LIMIT 1; - - UPDATE Clientes SET default_address = vNewDefault - WHERE Id_Cliente = NEW.Id_Cliente; - END IF; - END IF; - - -- Recargos de equivalencia distintos implican facturacion por consignatario - IF NEW.isEqualizated != OLD.isEqualizated THEN - - IF - (SELECT COUNT(*) FROM - ( - SELECT DISTINCT (isEqualizated = FALSE) as Equ - FROM Consignatarios - WHERE Id_Cliente = NEW.Id_Cliente - ) t1 - ) > 1 - - THEN - - UPDATE Clientes - SET invoiceByAddress = TRUE - WHERE Id_Cliente = NEW.Id_Cliente; - - END IF; - - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `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) COLLATE utf8_unicode_ci NOT NULL, - `notas` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`Id_Consigna`,`serialNumber`), - CONSTRAINT `Condigna_devices` FOREIGN KEY (`Id_Consigna`) REFERENCES `Consignatarios` (`id_consigna`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Contactos` --- - -DROP TABLE IF EXISTS `Contactos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Contactos` ( - `Id_Contacto` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Nombre` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `Apellidos` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `Empresa` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `Cargo` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `Telefono` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `Movil` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `email` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL, - `Fax` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `Notas` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`Id_Contacto`), - KEY `Telefono` (`Telefono`), - KEY `Movil` (`Movil`) -) ENGINE=InnoDB AUTO_INCREMENT=2601 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`ContactosBeforeInsert` -BEFORE INSERT ON `Contactos` FOR EACH ROW -BEGIN - CALL pbx.phoneIsValid (NEW.telefono); - CALL pbx.phoneIsValid (NEW.movil); - CALL pbx.phoneIsValid (NEW.fax); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`ContactosBeforeUpdate` -BEFORE UPDATE ON `Contactos` FOR EACH ROW -BEGIN - CALL pbx.phoneIsValid (NEW.telefono); - CALL pbx.phoneIsValid (NEW.movil); - CALL pbx.phoneIsValid (NEW.fax); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `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) COLLATE utf8_unicode_ci DEFAULT NULL, - `warehouse_id` int(10) unsigned NOT NULL DEFAULT '1', - PRIMARY KEY (`Id_Conteo`) -) ENGINE=MyISAM AUTO_INCREMENT=1080422 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `Conteo_ai` AFTER INSERT ON `Conteo` FOR EACH ROW -BEGIN - DECLARE intTravel INTEGER; - SELECT t.id INTO intTravel FROM Compres c JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel t ON t.id = e.travel_id - WHERE landing = CURDATE() AND c.Id_Article = NEW.Id_Article AND warehouse_id = NEW.warehouse_id AND received <> TRUE LIMIT 1; - IF (intTravel) then - UPDATE travel SET received = TRUE WHERE id = intTravel; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `Cubos` --- - -DROP TABLE IF EXISTS `Cubos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Cubos` ( - `Id_Cubo` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `Volumen` decimal(10,2) DEFAULT '0.00', - `X` decimal(10,2) DEFAULT '0.00', - `Y` decimal(10,2) DEFAULT '0.00', - `Z` decimal(10,2) DEFAULT '0.00', - `Valor` decimal(10,2) DEFAULT '0.00', - `Retornable` tinyint(1) NOT NULL DEFAULT '0', - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `idCubos_Retorno` int(11) DEFAULT NULL, - `Bajan` int(11) DEFAULT NULL, - `Suben` int(11) DEFAULT NULL, - `Base` decimal(10,2) DEFAULT NULL, - `item_id` int(11) DEFAULT NULL, - `pvp` decimal(10,2) NOT NULL, - `box` tinyint(1) NOT NULL DEFAULT '0', - `bultoCubico` decimal(10,2) DEFAULT NULL, - `costeRetorno` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`Id_Cubo`), - KEY `Article` (`item_id`), - CONSTRAINT `Article` FOREIGN KEY (`item_id`) REFERENCES `Articles` (`Id_Article`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Cubos_Retorno` --- - -DROP TABLE IF EXISTS `Cubos_Retorno`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Cubos_Retorno` ( - `idCubos_Retorno` int(11) NOT NULL AUTO_INCREMENT, - `Soporte` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - `Vacio` double NOT NULL DEFAULT '0', - `Lleno` double NOT NULL DEFAULT '0', - PRIMARY KEY (`idCubos_Retorno`) -) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Enlaces Facturas` --- - -DROP TABLE IF EXISTS `Enlaces Facturas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Enlaces Facturas` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `Asiento` int(11) DEFAULT '0', - `Apunte` int(11) DEFAULT '0', - `Data` datetime DEFAULT NULL, - `Concepto` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL, - `Cuenta` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `Debe` double DEFAULT NULL, - `Haber` double DEFAULT NULL, - `Contrapartida` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `Contabilizado` tinyint(1) NOT NULL DEFAULT '0', - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - PRIMARY KEY (`id`), - KEY `empresa_id` (`empresa_id`), - CONSTRAINT `Enlaces@0020Facturas_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=23889 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Entradas` --- - -DROP TABLE IF EXISTS `Entradas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Entradas` ( - `Id_Entrada` int(11) NOT NULL AUTO_INCREMENT, - `Id_Proveedor` int(11) NOT NULL DEFAULT '644', - `Fecha` datetime NOT NULL, - `Referencia` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Anotadoencaja` tinyint(1) NOT NULL DEFAULT '0', - `Inventario` tinyint(1) NOT NULL DEFAULT '0', - `Notas` longtext COLLATE utf8_unicode_ci, - `Confirmada` tinyint(1) NOT NULL DEFAULT '0', - `Pedida` tinyint(1) NOT NULL DEFAULT '0', - `Redada` tinyint(1) NOT NULL DEFAULT '0', - `comision` float NOT NULL DEFAULT '0', - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `Notas_Eva` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `travel_id` int(11) unsigned DEFAULT NULL, - `Id_Moneda` tinyint(3) unsigned DEFAULT '1', - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - `gestdoc_id` int(11) DEFAULT NULL, - `recibida_id` mediumint(8) unsigned DEFAULT NULL, - `blocked` tinyint(4) NOT NULL DEFAULT '0', - `loadPriority` int(11) DEFAULT NULL, - PRIMARY KEY (`Id_Entrada`), - KEY `Id_Proveedor` (`Id_Proveedor`), - KEY `Fecha` (`Fecha`), - KEY `travel_id` (`travel_id`), - KEY `empresa_id` (`empresa_id`), - KEY `gestdoc_id` (`gestdoc_id`), - KEY `recibida_id` (`recibida_id`), - CONSTRAINT `Entradas_ibfk_1` FOREIGN KEY (`Id_Proveedor`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE, - CONSTRAINT `Entradas_ibfk_6` FOREIGN KEY (`travel_id`) REFERENCES `travel` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Entradas_ibfk_7` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=136543 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='InnoDB free: 88064 kB; (`Id_Proveedor`) REFER `vn2008/Provee'; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`EntradasBeforeInsert` - BEFORE INSERT ON `Entradas` FOR EACH ROW -BEGIN - IF (SELECT cuenta LIKE '___4______' FROM Proveedores WHERE Id_Proveedor = NEW.Id_Proveedor) THEN - SET NEW.Id_Moneda = 2; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`EntradasBeforeUpdate` - BEFORE UPDATE ON `vn2008`.`Entradas` FOR EACH ROW -BEGIN - IF (SELECT Id_Entrada FROM Entradas_Auto WHERE Id_Entrada = NEW.Id_Entrada) AND (NEW.travel_id <> OLD.travel_id) THEN - IF - (SELECT warehouse_id FROM travel WHERE id = NEW.travel_id) <> (SELECT warehouse_id FROM travel WHERE id = OLD.travel_id) OR - (SELECT warehouse_id_out FROM travel WHERE id = NEW.travel_id) <> (SELECT warehouse_id_out FROM travel WHERE id = OLD.travel_id) - THEN - SET NEW.travel_id = OLD.travel_id; - END IF; - END IF; - - IF (NEW.gestdoc_id IS NOT NULL) AND (NEW.gestdoc_id <> OLD.gestdoc_id) THEN - UPDATE - recibida_entrada re - INNER JOIN recibida r ON re.recibida_id = r.id - INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada - SET r.gestdoc_id = e.gestdoc_id - WHERE - e.Id_Entrada = NEW.Id_Entrada - AND r.gestdoc_id IS NULL; - END IF; - - IF NEW.anotadoencaja <> OLD.anotadoencaja THEN - INSERT INTO Entradas_dits (idaccion_dits,Id_Trabajador,Id_Ticket,value_old,value_new) - VALUES (105,get_Trabajador(),NEW.Id_Entrada,OLD.anotadoencaja,NEW.anotadoencaja); - END IF; - - IF NEW.Id_Proveedor <> OLD.Id_Proveedor THEN - IF (SELECT cuenta LIKE '___4______' FROM Proveedores WHERE Id_Proveedor = NEW.Id_Proveedor) THEN - SET NEW.Id_Moneda = 2; - END IF; - END IF; - - IF NEW.Id_Moneda = 2 THEN - SET NEW.comision = getComision(NEW.Id_Entrada, NEW.Id_Moneda); - END IF; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`EntradasAfterUpdate` - AFTER UPDATE ON `Entradas` FOR EACH ROW -BEGIN - CALL stock.queueAdd ('entry', NEW.Id_Entrada, OLD.Id_Entrada); - - - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`EntradasAfterDelete` - AFTER DELETE ON `Entradas` FOR EACH ROW -BEGIN - CALL stock.queueAdd ('entry', NULL, OLD.Id_Entrada); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `Entradas_Auto` --- - -DROP TABLE IF EXISTS `Entradas_Auto`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Entradas_Auto` ( - `Id_Entrada` int(11) NOT NULL, - PRIMARY KEY (`Id_Entrada`), - CONSTRAINT `Entradas_Auto_ibfk_1` FOREIGN KEY (`Id_Entrada`) REFERENCES `Entradas` (`Id_Entrada`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Entradas_dits` --- - -DROP TABLE IF EXISTS `Entradas_dits`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Entradas_dits` ( - `idEntrada_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) COLLATE utf8_unicode_ci DEFAULT NULL, - `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`idEntrada_dits`), - KEY `fgkey_entradas_1_idx` (`idaccion_dits`), - KEY `fgkey_entradas_2_idx` (`Id_Ticket`), - KEY `fgkey_entradas_3_idx` (`Id_Trabajador`), - CONSTRAINT `Entradas_dits_ibfk_1` FOREIGN KEY (`Id_Ticket`) REFERENCES `Entradas` (`Id_Entrada`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fgkey_entradas_1` FOREIGN KEY (`idaccion_dits`) REFERENCES `accion_dits` (`idaccion_dits`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `fgkey_entradas_3` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2614566 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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 `Entradas` (`Id_Entrada`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=391 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Relaciona las entradas con los origenes de compra'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Entradas_orden` --- - -DROP TABLE IF EXISTS `Entradas_orden`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Entradas_orden` ( - `Id_Entrada` int(11) NOT NULL, - `orden` int(11) NOT NULL DEFAULT '1' COMMENT '1.- Ordenar por articulo\n2.- Ordenar por compra\n', - PRIMARY KEY (`Id_Entrada`), - CONSTRAINT `entradas_entradas_orden` FOREIGN KEY (`Id_Entrada`) REFERENCES `Entradas` (`Id_Entrada`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Entradas_stack` --- - -DROP TABLE IF EXISTS `Entradas_stack`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Entradas_stack` ( - `Id_Entrada` int(11) NOT NULL, - `label_number` smallint(6) DEFAULT '0', - PRIMARY KEY (`Id_Entrada`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Entradas_turno` --- - -DROP TABLE IF EXISTS `Entradas_turno`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Entradas_turno` ( - `Id_Entrada` int(11) NOT NULL, - `weekDay` tinyint(2) NOT NULL DEFAULT '0', - PRIMARY KEY (`Id_Entrada`), - CONSTRAINT `entrada_entrada_turno` FOREIGN KEY (`Id_Entrada`) REFERENCES `Entradas` (`Id_Entrada`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Estas entradas se clonan al mismo tiempo que los turnos'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `EnvioMasivo` --- - -DROP TABLE IF EXISTS `EnvioMasivo`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `EnvioMasivo` ( - `Id` int(11) NOT NULL AUTO_INCREMENT, - `Cliente` varchar(40) COLLATE utf8_unicode_ci NOT NULL, - `Direccion` varchar(80) COLLATE utf8_unicode_ci NOT NULL, - `CP` varchar(5) COLLATE utf8_unicode_ci NOT NULL, - `Poblacion` varchar(40) COLLATE utf8_unicode_ci NOT NULL, - `Telefono` varchar(9) COLLATE utf8_unicode_ci NOT NULL, - `Bultos` int(11) NOT NULL, - `Observaciones` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL, - `IdTicket` int(11) NOT NULL, - PRIMARY KEY (`Id`) -) ENGINE=MyISAM AUTO_INCREMENT=3373 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Generación de etiquetas a través de Zeleris con los clientes de esta tabla'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Equipos` --- - -DROP TABLE IF EXISTS `Equipos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Equipos` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `alias` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `trabajador_id` int(11) DEFAULT NULL, - `descripcion` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `predet` int(1) unsigned zerofill DEFAULT '0', - `Left` int(5) DEFAULT '3000', - `Top` int(5) DEFAULT '3000', - `Width` int(5) DEFAULT '6360', - `Height` int(5) DEFAULT '5595', - PRIMARY KEY (`id`), - KEY `trabajador_id` (`trabajador_id`), - CONSTRAINT `Equipos_ibfk_1` FOREIGN KEY (`trabajador_id`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=143 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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) COLLATE utf8_unicode_ci 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=MyISAM AUTO_INCREMENT=75648 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`Id_Estado`) -) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Estanterias` --- - -DROP TABLE IF EXISTS `Estanterias`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Estanterias` ( - `Id_Estanterias` int(11) NOT NULL AUTO_INCREMENT, - `w` int(11) DEFAULT NULL, - `d` int(11) DEFAULT NULL, - `modelo` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`Id_Estanterias`) -) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Estanterias_distri` --- - -DROP TABLE IF EXISTS `Estanterias_distri`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Estanterias_distri` ( - `idEstanterias_distri` int(11) NOT NULL, - `posinicial` int(11) NOT NULL, - `posfinal` int(11) NOT NULL, - `Id_Estanterias` int(11) NOT NULL, - PRIMARY KEY (`Id_Estanterias`,`idEstanterias_distri`), - KEY `Estanterias_fgkey1_idx` (`Id_Estanterias`), - KEY `est_distrib_fgkey1_idx` (`idEstanterias_distri`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Estanterias_distri_name` --- - -DROP TABLE IF EXISTS `Estanterias_distri_name`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Estanterias_distri_name` ( - `idEstanterias_distri` int(11) NOT NULL AUTO_INCREMENT, - `Descripcion` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`idEstanterias_distri`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Extractos` --- - -DROP TABLE IF EXISTS `Extractos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Extractos` ( - `Id_Extracto` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Fecha` datetime NOT NULL, - `Concepto` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `Debe` double unsigned zerofill NOT NULL DEFAULT '0000000000000000000000', - `Haber` double unsigned zerofill NOT NULL DEFAULT '0000000000000000000000', - `Concepto2` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `Concepto3` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`Id_Extracto`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Facturas` --- - -DROP TABLE IF EXISTS `Facturas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Facturas` ( - `factura_id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Id_Factura` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - `Serie` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `Fecha` date DEFAULT NULL, - `Importe` decimal(12,2) DEFAULT '0.00', - `Vencimiento` datetime DEFAULT NULL, - `Id_Banco` int(11) DEFAULT '0', - `Id_Cliente` int(11) DEFAULT '0', - `Id_Remesa` int(11) DEFAULT NULL, - `Remesar` tinyint(1) NOT NULL DEFAULT '0', - `BI7` decimal(12,2) DEFAULT '0.00', - `BI16` decimal(12,2) DEFAULT '0.00', - `RE1` decimal(12,2) DEFAULT '0.00', - `RE4` decimal(12,2) DEFAULT '0.00', - `IVA7` decimal(12,2) DEFAULT '0.00', - `IVA16` decimal(12,2) DEFAULT '0.00', - `Id_Trabajador` int(11) DEFAULT '0', - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - `liquidacion` smallint(6) DEFAULT '0', - `pdf` tinyint(3) unsigned NOT NULL DEFAULT '0', - `booked` date DEFAULT NULL, - `cplusInvoiceType477Fk` int(10) unsigned NOT NULL DEFAULT '1', - `cplusTaxBreakFk` int(10) unsigned NOT NULL DEFAULT '1', - `cplusSubjectOpFk` int(10) unsigned NOT NULL DEFAULT '1', - `cplusTrascendency477Fk` int(10) unsigned NOT NULL DEFAULT '1', - PRIMARY KEY (`factura_id`,`Id_Factura`), - UNIQUE KEY `Id_Factura` (`Id_Factura`), - KEY `Id_Banco` (`Id_Banco`), - KEY `Id_Cliente` (`Id_Cliente`), - KEY `Id_Remesa` (`Id_Remesa`), - KEY `Id_Trabajador` (`Id_Trabajador`), - KEY `empresa_id` (`empresa_id`), - KEY `Fecha` (`Fecha`), - KEY `Facturas_ibfk_2_idx` (`cplusInvoiceType477Fk`), - KEY `Facturas_ibfk_3_idx` (`cplusSubjectOpFk`), - KEY `Facturas_ibfk_4_idx` (`cplusTaxBreakFk`), - KEY `Facturas_ibfk_5_idx` (`cplusTrascendency477Fk`), - CONSTRAINT `Facturas_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Facturas_ibfk_2` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `vn`.`cplusInvoiceType477` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Facturas_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `vn`.`cplusSubjectOp` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Facturas_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `vn`.`cplusTaxBreak` (`id`) ON UPDATE CASCADE, - CONSTRAINT `invoice_bank_id` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE, - CONSTRAINT `invoice_customer_id` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=446219 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `FacturasBeforeInsert` -BEFORE INSERT ON `Facturas` FOR EACH ROW --- Edit trigger body code below this line. Do not edit lines above this one -BEGIN - - DECLARE v_Id_Factura_serie CHAR(9) DEFAULT '0000001'; - DECLARE v_Id_Factura INT; - DECLARE max_id, intLast, intProv INT; - - -- Evitamos la generacion de nuevas facturas tras el cese de actividad de EFL - IF NEW.empresa_id = 792 AND NEW.Fecha > '2012-12-20' THEN - SET NEW.empresa_id = 791; - END IF; - - SELECT IFNULL(MAX(factura_id),0) into max_id - from Facturas - WHERE Serie LIKE NEW.Serie - AND ((Year(NEW.Fecha) = Year(Fecha) - AND empresa_id = NEW.empresa_id)); - - IF max_id THEN - - SELECT right(max(Id_Factura), LENGTH(Id_Factura)-1) + 1 - into v_Id_Factura_serie - from Facturas - WHERE Serie LIKE NEW.Serie - AND ((Year(NEW.Fecha) = Year(Fecha) - AND length(Id_Factura) > 6 - AND empresa_id = NEW.empresa_id) /*OR (NEW.Serie LIKE 'B' AND length(Id_Factura) > 7)*/); - - - ELSE - - SELECT CONCAT(digito_factura,RIGHT(YEAR(CURDATE()),1),'00001') INTO v_Id_Factura_serie - FROM empresa WHERE id = NEW.empresa_id; - -/*Primer digito la empresa, segundo el año, despues la numeracion correlativa con 5 digitos*/ - - - END IF; - - -SELECT CONCAT(NEW.serie, lpad(v_Id_Factura_serie,7,'0')) into v_Id_Factura_serie; -SET NEW.Id_Factura = v_Id_Factura_serie; - - - -/* - IF intProv > 0 THEN -- No contabiliza bien las facturas holandesas - INSERT INTO recibida(proveedor_id,fecha,sref,empresa_id) - VALUES (NEW.empresa_id,NEW.Fecha,NEW.Id_Factura,intProv); - - SELECT LAST_INSERT_ID() INTO intLast; - - IF NEW.BI7 > 0 THEN - INSERT INTO recibida_iva(recibida_id,iva_id,bi,gastos_id) - VALUES(intLast,57,NEW.BI7,'6001000000'); - END IF; - - IF NEW.BI16 > 0 THEN - INSERT INTO recibida_iva(recibida_id,iva_id,bi,gastos_id) - VALUES(intLast,58,NEW.BI16,'6001000000'); - END IF; - - INSERT INTO recibida_vencimiento(recibida_id,fecha,banco_id,cantidad) - SELECT intLast,TIMESTAMPADD(DAY,15,NEW.Fecha),3117,SUM((1 + (IVA / 100)) * bi) - FROM recibida r INNER JOIN recibida_iva ri ON r.id = ri.recibida_id - INNER JOIN iva_codigo AS i ON ri.iva_id=i.id INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id - LEFT JOIN (SELECT recibida_id, SUM(cantidad) cantidad FROM recibida_vencimiento rv WHERE rv.recibida_id = intLast - GROUP BY recibida_id) t ON t.recibida_id = r.id WHERE r.id = intLast ; - UPDATE recibida SET contabilizada = 0 WHERE id = intLast; - UPDATE recibida SET contabilizada = 1 WHERE id = intLast; - END IF; -*/ - END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`FacturasAfterInsert` -AFTER INSERT ON `Facturas` -FOR EACH ROW - CALL bi.customer_risk_update (NEW.Id_Cliente, NEW.empresa_id, NEW.Importe) */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`FacturasBeforeUpdate` -BEFORE UPDATE ON `Facturas` -FOR EACH ROW -BEGIN - CALL bi.customer_risk_update (OLD.Id_Cliente, OLD.empresa_id, -OLD.Importe); - CALL bi.customer_risk_update (NEW.Id_Cliente, NEW.empresa_id, NEW.Importe); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`FacturasBeforeDelete` -BEFORE DELETE ON `Facturas` -FOR EACH ROW - CALL bi.customer_risk_update (OLD.Id_Cliente, OLD.empresa_id, -OLD.Importe) */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `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) COLLATE utf8_unicode_ci NOT NULL, - `Subcuenta` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `Descripcion` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`Familia`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Gastos` --- - -DROP TABLE IF EXISTS `Gastos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Gastos` ( - `Id_Gasto` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `iva_tipo_id` tinyint(4) NOT NULL, - `Gasto` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `conbase` tinyint(4) NOT NULL DEFAULT '1', - `isWithheld` tinyint(4) NOT NULL DEFAULT '0', - `isForSale` tinyint(4) NOT NULL DEFAULT '0', - PRIMARY KEY (`Id_Gasto`,`iva_tipo_id`), - KEY `iva_tipo_id` (`iva_tipo_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Greuges` --- - -DROP TABLE IF EXISTS `Greuges`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Greuges` ( - `Id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Id_Cliente` int(10) unsigned NOT NULL, - `Comentario` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `Importe` decimal(10,2) NOT NULL, - `Fecha` datetime NOT NULL, - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `Greuges_type_id` int(11) DEFAULT NULL, - `Id_Ticket` int(11) DEFAULT NULL, - PRIMARY KEY (`Id`), - KEY `greuges_type_fk_idx` (`Greuges_type_id`), - KEY `Id_Ticket_Greuge_Ticket_idx` (`Id_Ticket`), - CONSTRAINT `Id_Ticket_Greuge_Ticket` FOREIGN KEY (`Id_Ticket`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `greuges_type_fk` FOREIGN KEY (`Greuges_type_id`) REFERENCES `Greuges_type` (`Greuges_type_id`) ON DELETE SET NULL ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=1855894 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=FIXED; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`Greuges_BEFORE_UPDATE` BEFORE UPDATE ON `Greuges` FOR EACH ROW -BEGIN - - DECLARE vMaxDate DATETIME DEFAULT TIMESTAMPADD(YEAR,1,CURDATE()); - - IF NEW.Fecha > vMaxDate THEN - - SET NEW.Fecha = vMaxDate; - - END IF; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `Greuges_type` --- - -DROP TABLE IF EXISTS `Greuges_type`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Greuges_type` ( - `Greuges_type_id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`Greuges_type_id`) -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci NOT NULL, - `Grupo` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `observation_type_id` tinyint(3) unsigned NOT NULL, - PRIMARY KEY (`id`), - KEY `name` (`name`) -) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Impresoras` --- - -DROP TABLE IF EXISTS `Impresoras`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Impresoras` ( - `Id_Impresora` tinyint(3) unsigned NOT NULL, - `Ruta` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Impresora` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `referencia` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `2C` tinyint(4) DEFAULT '0', - PRIMARY KEY (`Id_Impresora`), - UNIQUE KEY `referencia` (`referencia`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`Id_Informe`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Intrastat` --- - -DROP TABLE IF EXISTS `Intrastat`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Intrastat` ( - `Codintrastat` int(8) unsigned zerofill NOT NULL, - `Definicion` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `import` tinyint(4) NOT NULL DEFAULT '0', - `iva_group_id` tinyint(3) unsigned NOT NULL DEFAULT '2', - `iva_codigo_id` tinyint(2) unsigned NOT NULL DEFAULT '64', - PRIMARY KEY (`Codintrastat`), - KEY `iva_group_id` (`iva_group_id`), - CONSTRAINT `Intrastat_ibfk_1` FOREIGN KEY (`iva_group_id`) REFERENCES `iva_group` (`iva_group_id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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(11) NOT NULL, - `Id_Jefe` int(11) NOT NULL, - `Departamento` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`Id_Trabajador`,`Id_Jefe`), - KEY `trabajador_jefe_idx` (`Id_Jefe`), - CONSTRAINT `trabajador_jefe` FOREIGN KEY (`Id_Jefe`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Es una tabla que se rellena desde la comparativa, tomando los datos de postgress.'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Monedas` --- - -DROP TABLE IF EXISTS `Monedas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Monedas` ( - `Id_Moneda` tinyint(3) unsigned NOT NULL, - `Moneda` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `Descripcion` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `Cambio` double NOT NULL DEFAULT '1', - PRIMARY KEY (`Id_Moneda`), - UNIQUE KEY `Moneda_UNIQUE` (`Moneda`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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` int(11) NOT NULL, - `user_id` int(11) 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_ibfk_1` FOREIGN KEY (`equipo_id`) REFERENCES `Equipos` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Monitoring_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE, - CONSTRAINT `Monitoring_ibfk_3` FOREIGN KEY (`form_id`) REFERENCES `Forms` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Movimientos` --- - -DROP TABLE IF EXISTS `Movimientos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Movimientos` ( - `Id_Movimiento` int(11) NOT NULL AUTO_INCREMENT, - `Id_Article` int(11) NOT NULL, - `Id_Ticket` int(11) NOT NULL, - `Concepte` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Cantidad` decimal(10,2) NOT NULL DEFAULT '0.00', - `quantity` double(9,1) DEFAULT NULL, - `Preu` decimal(10,2) DEFAULT '0.00', - `Descuento` tinyint(2) unsigned NOT NULL DEFAULT '0', - `CostFixat` decimal(10,2) NOT NULL DEFAULT '0.00', - `Reservado` tinyint(1) NOT NULL DEFAULT '0', - `OK` tinyint(1) NOT NULL DEFAULT '0', - `PrecioFijado` tinyint(1) NOT NULL DEFAULT '0', - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`Id_Movimiento`), - KEY `Id_Ticket` (`Id_Ticket`), - KEY `itemFk_ticketFk` (`Id_Article`,`Id_Ticket`), - CONSTRAINT `Movimientos_ibfk_1` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON UPDATE CASCADE, - CONSTRAINT `movement_ticket_id` FOREIGN KEY (`Id_Ticket`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=20082659 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`MovimientosAfterInsert` - AFTER INSERT ON `Movimientos` FOR EACH ROW -BEGIN - CALL stock.queueAdd ('sale', NEW.Id_Movimiento, NULL); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `MovimientosBeforeUpdate` - BEFORE UPDATE ON `Movimientos` FOR EACH ROW -BEGIN - IF NEW.Descuento > 100 THEN - SET NEW.Descuento = 0; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`MovimientosAfterUpdate` - AFTER UPDATE ON `Movimientos` FOR EACH ROW -BEGIN - CALL stock.queueAdd ('sale', NEW.Id_Movimiento, OLD.Id_Movimiento); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`MovimientosAfterDelete` - AFTER DELETE ON `Movimientos` FOR EACH ROW -BEGIN - CALL stock.queueAdd ('sale', NULL, OLD.Id_Movimiento); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `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 `Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Movimientos_checked` --- - -DROP TABLE IF EXISTS `Movimientos_checked`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Movimientos_checked` ( - `Id_Movimiento` int(11) NOT NULL, - `checked` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`Id_Movimiento`), - CONSTRAINT `fk_Movimientos_checked_1` FOREIGN KEY (`Id_Movimiento`) REFERENCES `Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Movimientos_componentes` --- - -DROP TABLE IF EXISTS `Movimientos_componentes`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Movimientos_componentes` ( - `Id_Movimiento` int(11) NOT NULL, - `Id_Componente` int(11) NOT NULL, - `Valor` double NOT NULL, - `greuge` tinyint(4) NOT NULL DEFAULT '0', - PRIMARY KEY (`Id_Movimiento`,`Id_Componente`), - KEY `fk_mov_comp_idx` (`Id_Componente`), - CONSTRAINT `mc_fk1` FOREIGN KEY (`Id_Movimiento`) REFERENCES `Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `mc_fk2` FOREIGN KEY (`Id_Componente`) REFERENCES `bi`.`tarifa_componentes` (`Id_Componente`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Movimientos_mark` --- - -DROP TABLE IF EXISTS `Movimientos_mark`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Movimientos_mark` ( - `Id_Movimiento` 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(11) NOT NULL, - `Id_Accion` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `Id_Movimiento_mark` int(11) NOT NULL AUTO_INCREMENT, - PRIMARY KEY (`Id_Movimiento_mark`), - KEY `Id_Movimiento` (`Id_Movimiento`) -) ENGINE=InnoDB AUTO_INCREMENT=9556205 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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) COLLATE utf8_unicode_ci 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 `Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `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=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Ordenes` --- - -DROP TABLE IF EXISTS `Ordenes`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Ordenes` ( - `Id_ORDEN` int(11) NOT NULL AUTO_INCREMENT, - `ORDEN` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `datORDEN` datetime DEFAULT NULL, - `datTICKET` datetime DEFAULT NULL, - `CodVENDEDOR` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `CodCOMPRADOR` varchar(3) CHARACTER SET utf8 NOT NULL DEFAULT 'NOE', - `CANTIDAD` int(11) DEFAULT NULL, - `PRECIOMAX` double DEFAULT NULL, - `PREU` double DEFAULT NULL, - `Id_ARTICLE` double DEFAULT NULL, - `Id_CLIENTE` int(11) DEFAULT NULL, - `COMENTARIO` longtext COLLATE utf8_unicode_ci, - `OK` tinyint(1) NOT NULL DEFAULT '0', - `TOTAL` int(11) DEFAULT NULL, - `datCOMPRA` datetime DEFAULT NULL, - `KO` tinyint(1) NOT NULL DEFAULT '0', - `Id_Movimiento` int(11) DEFAULT NULL, - `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`Id_ORDEN`), - UNIQUE KEY `Id_Movimiento_UNIQUE` (`Id_Movimiento`), - KEY `Id_ARTICLE` (`Id_ARTICLE`), - KEY `Id_CLIENTE` (`Id_CLIENTE`), - KEY `Id_Comprador` (`CodCOMPRADOR`), - KEY `Id_Movimiento` (`Id_Movimiento`), - KEY `Id_Vendedor` (`CodVENDEDOR`) -) ENGINE=InnoDB AUTO_INCREMENT=27213 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Origen` --- - -DROP TABLE IF EXISTS `Origen`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Origen` ( - `id` tinyint(2) unsigned NOT NULL AUTO_INCREMENT, - `Abreviatura` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `Origen` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `warehouse_id` smallint(5) unsigned DEFAULT '4', - `bandera` blob, - `nl` tinyint(4) NOT NULL DEFAULT '0', - `Id_Paises` mediumint(8) unsigned NOT NULL DEFAULT '1', - PRIMARY KEY (`id`), - UNIQUE KEY `Abreviatura` (`Abreviatura`), - KEY `warehouse_id` (`warehouse_id`), - KEY `Id_Paises` (`Id_Paises`), - CONSTRAINT `Origen_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Pagares` --- - -DROP TABLE IF EXISTS `Pagares`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Pagares` ( - `kk_Vencimiento` datetime DEFAULT NULL, - `kk_Importe` double DEFAULT '0', - `Fechaemision` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `Id_Pagare` int(11) NOT NULL AUTO_INCREMENT, - `Concepto` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `kk_id_proveedor` int(11) DEFAULT NULL, - `kk_empresa_id` smallint(5) unsigned DEFAULT NULL, - `pago_id` int(10) unsigned DEFAULT NULL, - PRIMARY KEY (`Id_Pagare`), - KEY `empresa_id` (`kk_empresa_id`), - KEY `pago_id` (`pago_id`), - CONSTRAINT `Pagares_ibfk_2` FOREIGN KEY (`pago_id`) REFERENCES `pago` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2835 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Paises` --- - -DROP TABLE IF EXISTS `Paises`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Paises` ( - `Id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `Pais` varchar(25) COLLATE utf8_unicode_ci NOT NULL, - `CEE` tinyint(1) NOT NULL DEFAULT '1', - `Codigo` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, - `Id_Moneda` tinyint(3) unsigned NOT NULL DEFAULT '1', - `Id_Paisreal` mediumint(8) unsigned NOT NULL COMMENT 'Pais Real(apaño por culpa del España Exento)', - `nst_geo_id` int(11) DEFAULT NULL, - `nst_name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `geoFk` int(11) DEFAULT NULL, - `isUeeMember` tinyint(4) NOT NULL DEFAULT '0', - PRIMARY KEY (`Id`), - KEY `Id_Paisreal` (`Id_Paisreal`) -) ENGINE=InnoDB AUTO_INCREMENT=68 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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` smallint(5) unsigned NOT NULL DEFAULT '442', - PRIMARY KEY (`Id_Grupo`,`Id_Trabajador`), - KEY `empresa_id` (`empresa_id`), - CONSTRAINT `Permisos_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `Permisos_ibfk_2` FOREIGN KEY (`Id_Grupo`) REFERENCES `Grupos` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `PreciosEspeciales` --- - -DROP TABLE IF EXISTS `PreciosEspeciales`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `PreciosEspeciales` ( - `Id_PrecioEspecial` int(11) NOT NULL AUTO_INCREMENT, - `Id_Cliente` int(11) NOT NULL DEFAULT '0', - `Id_Article` int(11) NOT NULL DEFAULT '0', - `PrecioEspecial` double NOT NULL DEFAULT '0', - PRIMARY KEY (`Id_PrecioEspecial`), - UNIQUE KEY `Id_Cliente_2` (`Id_Cliente`,`Id_Article`), - KEY `Id_Article` (`Id_Article`), - KEY `Id_Cliente` (`Id_Cliente`), - CONSTRAINT `sp_article_id` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON UPDATE CASCADE, - CONSTRAINT `sp_customer_id` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE, - CONSTRAINT `{01A99AF1-3D3F-4B15-AC0C-C7A834F319A3}` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `{EE4ADEF6-0AC6-401F-B7C4-D797972FC065}` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=690 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Prioridades` --- - -DROP TABLE IF EXISTS `Prioridades`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Prioridades` ( - `Id_Prioridad` tinyint(3) unsigned NOT NULL DEFAULT '0', - `Prioridad` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`Id_Prioridad`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Proveedores` --- - -DROP TABLE IF EXISTS `Proveedores`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Proveedores` ( - `Id_Proveedor` int(11) NOT NULL AUTO_INCREMENT, - `Proveedor` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `cuenta` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `Domicilio` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `CP` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `Localidad` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `provinciakk` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `province_id` smallint(5) unsigned DEFAULT NULL, - `pais_id` mediumint(8) unsigned DEFAULT NULL, - `NIF` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `oficial` tinyint(1) NOT NULL DEFAULT '1', - `Agricola` tinyint(1) NOT NULL DEFAULT '0', - `cuentaret` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `Telefono` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL, - `Fax` varchar(16) COLLATE utf8_unicode_ci DEFAULT NULL, - `ComisionProveedor` float NOT NULL DEFAULT '0', - `Alias` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `pay_met_id` tinyint(3) unsigned NOT NULL, - `pay_day` tinyint(4) unsigned DEFAULT NULL, - `pay_dem_id` tinyint(3) unsigned NOT NULL DEFAULT '7', - `odbc_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `serious` tinyint(1) unsigned zerofill DEFAULT '1', - `notas` text COLLATE utf8_unicode_ci, - `postcode_id` int(11) unsigned DEFAULT NULL, - `codpos` char(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `active` tinyint(4) DEFAULT '1', - PRIMARY KEY (`Id_Proveedor`), - UNIQUE KEY `cuenta` (`cuenta`), - UNIQUE KEY `NIF` (`NIF`), - KEY `pais_id` (`pais_id`), - KEY `pay_met_id` (`pay_met_id`), - KEY `province_id` (`province_id`), - KEY `pay_dem_id` (`pay_dem_id`), - KEY `codpos` (`codpos`,`CP`), - CONSTRAINT `Id_Pais` FOREIGN KEY (`pais_id`) REFERENCES `Paises` (`Id`) ON UPDATE CASCADE, - CONSTRAINT `pay_dem_id` FOREIGN KEY (`pay_dem_id`) REFERENCES `pay_dem` (`id`) ON UPDATE CASCADE, - CONSTRAINT `pay_met_id` FOREIGN KEY (`pay_met_id`) REFERENCES `pay_met` (`id`) ON UPDATE CASCADE, - CONSTRAINT `province_id` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2455 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Proveedores_account` --- - -DROP TABLE IF EXISTS `Proveedores_account`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Proveedores_account` ( - `Id_Proveedores_account` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `Id_Proveedor` int(11) NOT NULL, - `IBAN` varchar(30) CHARACTER SET utf8 DEFAULT NULL, - `office` varchar(4) CHARACTER SET utf8 DEFAULT NULL, - `DC` varchar(2) CHARACTER SET utf8 DEFAULT NULL, - `number` varchar(10) CHARACTER SET utf8 DEFAULT NULL, - `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `bic_sufix` varchar(3) CHARACTER SET utf8 NOT NULL DEFAULT '', - `entity_id` int(10) DEFAULT NULL, - `Id_Banco` int(11) DEFAULT NULL, - PRIMARY KEY (`Id_Proveedores_account`), - KEY `fk_proveedores_proveedores_account_idx` (`Id_Proveedor`), - KEY `fk_Proveedores_account_entity1_idx` (`entity_id`), - KEY `fk_banco_prov_account_idx` (`Id_Banco`), - CONSTRAINT `fk_banco_prov_account` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=607 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Proveedores_cargueras` --- - -DROP TABLE IF EXISTS `Proveedores_cargueras`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Proveedores_cargueras` ( - `Id_Proveedor` int(11) NOT NULL, - PRIMARY KEY (`Id_Proveedor`), - CONSTRAINT `proveedores_cargueras_fk1` FOREIGN KEY (`Id_Proveedor`) REFERENCES `Proveedores` (`Id_Proveedor`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla de espcializacion para señalar las compañias que prestan servicio de transitario'; -/*!40101 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_Proveedor` int(11) NOT NULL, - `escrito_id` int(11) NOT NULL, - `fecha` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - KEY `Proveedor` (`Id_Proveedor`), - KEY `Escrito` (`escrito_id`), - CONSTRAINT `Proveedores_comunicados_ibfk_3` FOREIGN KEY (`Id_Proveedor`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE, - CONSTRAINT `Proveedores_comunicados_ibfk_4` FOREIGN KEY (`escrito_id`) REFERENCES `Proveedores_escritos` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci NOT NULL, - `informe` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Proveedores_gestdoc` --- - -DROP TABLE IF EXISTS `Proveedores_gestdoc`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Proveedores_gestdoc` ( - `Id_Proveedor` int(11) NOT NULL, - `gestdoc_id` int(11) NOT NULL, - PRIMARY KEY (`Id_Proveedor`,`gestdoc_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Recibos` --- - -DROP TABLE IF EXISTS `Recibos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Recibos` ( - `Id` int(11) NOT NULL AUTO_INCREMENT, - `Id_Factura` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Entregado` decimal(10,2) NOT NULL DEFAULT '0.00', - `Pendiente` decimal(10,2) NOT NULL DEFAULT '0.00', - `Fechacobro` datetime DEFAULT NULL, - `Id_Trabajador` int(11) DEFAULT '0', - `Id_Banco` int(11) DEFAULT '0', - `Id_Cliente` int(11) DEFAULT '0', - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - `conciliado` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0', - PRIMARY KEY (`Id`), - KEY `Id_Banco` (`Id_Banco`), - KEY `Id_Trabajador` (`Id_Trabajador`), - KEY `empresa_id` (`empresa_id`), - KEY `clientDate` (`Id_Cliente`,`Fechacobro`), - CONSTRAINT `Recibos_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Recibos_ibfk_2` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE, - CONSTRAINT `recibo_customer_id` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=444548 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`RecibosAfterInsert` -AFTER INSERT ON `Recibos` -FOR EACH ROW - CALL bi.customer_risk_update (NEW.Id_Cliente, NEW.empresa_id, -NEW.Entregado) */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`RecibosBeforeUpdate` -BEFORE UPDATE ON `Recibos` -FOR EACH ROW -BEGIN - CALL bi.customer_risk_update (OLD.Id_Cliente, OLD.empresa_id, OLD.Entregado); - CALL bi.customer_risk_update (NEW.Id_Cliente, NEW.empresa_id, -NEW.Entregado); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`RecibosBeforeDelete` -BEFORE DELETE ON `Recibos` -FOR EACH ROW - CALL bi.customer_risk_update (OLD.Id_Cliente, OLD.empresa_id, OLD.Entregado) */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `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 `Recibos` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Recibos (Contrareembolso) contabilizados'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Relaciones` --- - -DROP TABLE IF EXISTS `Relaciones`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Relaciones` ( - `Id_Relacion` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Id_Contacto` int(10) unsigned NOT NULL, - `Id_Proveedor` int(10) unsigned DEFAULT NULL, - `Id_Cliente` int(10) unsigned DEFAULT NULL, - PRIMARY KEY (`Id_Relacion`), - KEY `Id_Contacto` (`Id_Contacto`), - KEY `Id_Proveedor` (`Id_Proveedor`), - KEY `Id_Cliente` (`Id_Cliente`) -) ENGINE=InnoDB AUTO_INCREMENT=2602 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Remesas` --- - -DROP TABLE IF EXISTS `Remesas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Remesas` ( - `Id_Remesa` int(11) NOT NULL AUTO_INCREMENT, - `Fecha Remesa` datetime DEFAULT NULL, - `Banco` int(11) DEFAULT '0', - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - PRIMARY KEY (`Id_Remesa`), - KEY `Id_Banco` (`Banco`), - KEY `empresa_id` (`empresa_id`), - CONSTRAINT `Remesas_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Remesas_ibfk_2` FOREIGN KEY (`Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=1020 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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) COLLATE utf8_unicode_ci DEFAULT NULL, - `article` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `medida` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `categoria` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `color` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `origen` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `cantidad` int(11) DEFAULT '0', - `Id_Article` double DEFAULT '0', - PRIMARY KEY (`Id_Reserva`), - KEY `Id_1` (`Id_Ticket`), - KEY `Id_Article` (`Id_Article`) -) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Rutas` --- - -DROP TABLE IF EXISTS `Rutas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Rutas` ( - `Id_Ruta` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Id_Trabajador` int(10) unsigned DEFAULT NULL, - `Fecha` date NOT NULL, - `Id_Vehiculo` int(10) unsigned DEFAULT NULL, - `Id_Agencia` int(11) DEFAULT NULL, - `Hora` datetime DEFAULT NULL, - `ok` tinyint(1) unsigned NOT NULL DEFAULT '0', - `km_start` mediumint(9) NOT NULL, - `km_end` mediumint(9) NOT NULL, - `date_start` datetime NOT NULL, - `date_end` datetime NOT NULL, - `gestdoc_id` int(11) DEFAULT NULL, - `cost` double unsigned DEFAULT NULL, - `m3` decimal(10,1) unsigned DEFAULT NULL, - `description` text COLLATE utf8_unicode_ci, - PRIMARY KEY (`Id_Ruta`), - KEY `Id_Agencia` (`Id_Agencia`), - KEY `Fecha` (`Fecha`), - KEY `gestdoc_id` (`gestdoc_id`), - CONSTRAINT `Rutas_ibfk_1` FOREIGN KEY (`gestdoc_id`) REFERENCES `gestdoc` (`id`) ON DELETE SET NULL ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=36243 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `Rutas_au` AFTER UPDATE ON `Rutas` FOR EACH ROW -BEGIN - - IF IFNULL(NEW.gestdoc_id,0) <> IFNULL(OLD.gestdoc_id,0) AND NEW.gestdoc_id > 0 THEN - -- JGF 09/09/14 cuando se añade un gestdoc a una ruta, se le asigna automagicamente a todos sus Tickets - - -- Inserta el gestdoc en todos los tickets de la ruta - INSERT INTO tickets_gestdoc(Id_Ticket,gestdoc_id) - SELECT Id_Ticket, NEW.gestdoc_id FROM Tickets WHERE Id_Ruta = NEW.Id_Ruta - ON DUPLICATE KEY UPDATE gestdoc_id = NEW.gestdoc_id; - - -- Update del firmado - UPDATE Tickets t JOIN tickets_gestdoc tg ON t.Id_Ticket = tg.Id_Ticket - SET Firmado = 1 WHERE t.Id_Ruta = NEW.Id_Ruta; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `Rutas_Master` --- - -DROP TABLE IF EXISTS `Rutas_Master`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Rutas_Master` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `warehouse_id` smallint(6) unsigned DEFAULT NULL, - `km` int(11) DEFAULT NULL, - `bultos` int(11) NOT NULL, - `vehiculos_coste` decimal(10,2) DEFAULT NULL, - `personal_coste` decimal(10,2) DEFAULT NULL, - `vehiculos_numero` decimal(10,2) DEFAULT NULL, - `personal_numero` decimal(10,2) DEFAULT NULL, - `gasoil` int(11) DEFAULT NULL, - `autonomos` decimal(10,2) DEFAULT NULL, - `año` int(11) DEFAULT NULL, - `mes` int(11) DEFAULT NULL, - `gastos` decimal(10,2) DEFAULT NULL, - `bultos_autonomos` int(11) DEFAULT NULL, - `coste_km` decimal(10,2) DEFAULT NULL, - `coste_bulto` decimal(10,2) DEFAULT NULL, - `coste_bulto_autonomo` decimal(10,2) DEFAULT NULL, - `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `fk_rutas_warehouse_id_idx` (`warehouse_id`), - CONSTRAINT `fk_rutas_warehouse_id` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Rutas_dits` --- - -DROP TABLE IF EXISTS `Rutas_dits`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Rutas_dits` ( - `idRutas_dits` int(11) unsigned NOT NULL AUTO_INCREMENT, - `idaccion_dits` int(11) NOT NULL, - `ODBC_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `Id_Ticket` int(11) unsigned NOT NULL, - `Id_Trabajador` int(11) NOT NULL, - `value_old` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`idRutas_dits`), - KEY `index2` (`idaccion_dits`), - KEY `index3` (`Id_Ticket`), - KEY `index4` (`Id_Trabajador`), - CONSTRAINT `fk_Id_Trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE, - CONSTRAINT `fk_Id_ruta` FOREIGN KEY (`Id_Ticket`) REFERENCES `Rutas` (`Id_Ruta`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_action_dits` FOREIGN KEY (`idaccion_dits`) REFERENCES `accion_dits` (`idaccion_dits`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=300164 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Rutas_monitor` --- - -DROP TABLE IF EXISTS `Rutas_monitor`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Rutas_monitor` ( - `Id_Ruta` int(10) unsigned NOT NULL, - `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `Ubicacion` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `pedidosEncajados` int(11) DEFAULT NULL, - `pedidosLibres` int(11) DEFAULT NULL, - `bultos` int(11) DEFAULT NULL, - `notas` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `pedidosProduccion` int(11) DEFAULT NULL, - `fecha` date DEFAULT NULL, - `dockFk` int(11) DEFAULT NULL, - PRIMARY KEY (`Id_Ruta`), - KEY `Rutas_monitor_fk_2_idx` (`dockFk`), - CONSTRAINT `Rutas_monitor_fk_1` FOREIGN KEY (`Id_Ruta`) REFERENCES `Rutas` (`Id_Ruta`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `Rutas_monitor_fk_2` FOREIGN KEY (`dockFk`) REFERENCES `dock` (`id`) ON DELETE SET NULL ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Permite ubicar y controlar el estado de preparacion de las rutas'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Salarios` --- - -DROP TABLE IF EXISTS `Salarios`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Salarios` ( - `Id_Trabajador` int(11) NOT NULL, - `Salario_Bruto` double DEFAULT '0', - `Incentivo` double DEFAULT '0', - `SS` double DEFAULT '0', - `warehouse_id` smallint(6) NOT NULL DEFAULT '1', - PRIMARY KEY (`Id_Trabajador`), - CONSTRAINT `trabajadaor_id` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Saldos_Prevision` --- - -DROP TABLE IF EXISTS `Saldos_Prevision`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Saldos_Prevision` ( - `Saldos_Prevision_id` int(11) NOT NULL AUTO_INCREMENT, - `Descripcion` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `Importe` double NOT NULL DEFAULT '0', - `Fecha` date NOT NULL, - `Id_Banco` int(11) DEFAULT NULL, - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - PRIMARY KEY (`Saldos_Prevision_id`), - KEY `Fecha_indice` (`Fecha`), - KEY `banco_prevision_idx` (`Id_Banco`), - KEY `empresa_prevision_idx` (`empresa_id`), - CONSTRAINT `banco_prevision` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE, - CONSTRAINT `empresa_prevision` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=95 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Aqui ponemos los gastos e ingresos pendientes de introducir '; -/*!40101 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) COLLATE utf8_unicode_ci NOT NULL, - `Serie` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, - `Cuenta` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`Id_Serie`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Split_lines` --- - -DROP TABLE IF EXISTS `Split_lines`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Split_lines` ( - `Id_Split_lines` int(11) NOT NULL AUTO_INCREMENT, - `Id_Split` int(11) NOT NULL, - `Id_Article` int(11) DEFAULT NULL, - `Id_Compra` int(11) DEFAULT NULL, - PRIMARY KEY (`Id_Split_lines`), - KEY `Id_Split` (`Id_Split`), - KEY `Id_Compra` (`Id_Compra`), - CONSTRAINT `Id_Compra` FOREIGN KEY (`Id_Compra`) REFERENCES `Compres` (`Id_Compra`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `Split_lines_ibfk_1` FOREIGN KEY (`Id_Split`) REFERENCES `Splits` (`Id_Split`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=314176 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Splits` --- - -DROP TABLE IF EXISTS `Splits`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Splits` ( - `Id_Split` int(11) NOT NULL AUTO_INCREMENT, - `Id_Ticket` int(11) DEFAULT NULL, - `Id_Entrada` int(11) DEFAULT NULL, - `Fecha` datetime DEFAULT NULL, - `Notas` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`Id_Split`), - KEY `Id_Entrada` (`Id_Entrada`) -) ENGINE=InnoDB AUTO_INCREMENT=36145 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Stockcontrol` --- - -DROP TABLE IF EXISTS `Stockcontrol`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Stockcontrol` ( - `Id_Control` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Id_Article` int(11) NOT NULL, - `Id_Remitente` int(11) NOT NULL, - `Id_Solver` int(11) NOT NULL, - `Problema` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `Solucion` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `Listo` tinyint(1) NOT NULL, - `Air` tinyint(1) NOT NULL, - `Datestart` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `Dateend` datetime DEFAULT NULL, - PRIMARY KEY (`Id_Control`), - KEY `Id_Article` (`Id_Article`), - KEY `Id_Remitente` (`Id_Remitente`), - KEY `Id_Solver` (`Id_Solver`), - CONSTRAINT `Stockcontrol_ibfk_1` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `Stockcontrol_ibfk_2` FOREIGN KEY (`Id_Remitente`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `Stockcontrol_ibfk_3` FOREIGN KEY (`Id_Solver`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=23336 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Tickets` --- - -DROP TABLE IF EXISTS `Tickets`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Tickets` ( - `Id_Ticket` int(11) NOT NULL AUTO_INCREMENT, - `Id_Cliente` int(11) NOT NULL DEFAULT '0', - `warehouse_id` smallint(6) unsigned NOT NULL DEFAULT '1', - `Fecha` datetime NOT NULL, - `Alias` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Notas` longtext COLLATE utf8_unicode_ci, - `Factura` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `factura_id` int(10) unsigned DEFAULT NULL COMMENT 'eliminar', - `Anotadoencaja` tinyint(1) NOT NULL DEFAULT '0', - `Id_Consigna` int(11) NOT NULL DEFAULT '0', - `Id_Trabajador` int(11) DEFAULT NULL, - `Observaciones` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'eliminar', - `Firmado` tinyint(1) NOT NULL DEFAULT '0', - `Etiquetasemitidas` tinyint(1) NOT NULL DEFAULT '0', - `PedidoImpreso` tinyint(1) NOT NULL DEFAULT '0', - `Bultos` smallint(10) unsigned DEFAULT '0', - `Localizacion` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `Hora` int(11) DEFAULT '0', - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `blocked` tinyint(1) NOT NULL DEFAULT '1', - `Solucion` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `Id_Ruta` int(10) unsigned DEFAULT NULL, - `Prioridad` tinyint(3) unsigned DEFAULT NULL, - `priority` tinyint(1) unsigned NOT NULL DEFAULT '1', - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - `Id_Agencia` int(11) NOT NULL, - `landing` date DEFAULT NULL, - `boxed` tinyint(2) NOT NULL DEFAULT '0', - PRIMARY KEY (`Id_Ticket`), - KEY `Id_Cliente` (`Id_Cliente`), - KEY `Id_Consigna` (`Id_Consigna`), - KEY `Id_Trabajador` (`Id_Trabajador`), - KEY `warehouse_id` (`warehouse_id`), - KEY `empresa_id` (`empresa_id`), - KEY `Id_Agencia` (`Id_Agencia`), - KEY `Factura` (`Factura`), - KEY `Fecha` (`Fecha`), - KEY `Id_Ruta` (`Id_Ruta`), - KEY `warehouse_date` (`warehouse_id`,`Fecha`), - CONSTRAINT `Tickets_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Tickets_ibfk_5` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Tickets_ibfk_6` FOREIGN KEY (`Id_Consigna`) REFERENCES `Consignatarios` (`id_consigna`) ON UPDATE CASCADE, - CONSTRAINT `Tickets_ibfk_8` FOREIGN KEY (`Id_Agencia`) REFERENCES `Agencias` (`Id_Agencia`), - CONSTRAINT `Tickets_ibfk_9` FOREIGN KEY (`Id_Ruta`) REFERENCES `Rutas` (`Id_Ruta`) ON UPDATE CASCADE, - CONSTRAINT `ticket_customer_id` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE, - CONSTRAINT `tickets_fk10` FOREIGN KEY (`Factura`) REFERENCES `Facturas` (`Id_Factura`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=1788324 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `TicketsBeforeInsert` - BEFORE INSERT ON `Tickets` FOR EACH ROW -BEGIN -/* - DECLARE strEspecif VARCHAR(255); - DECLARE intId_Agencia INTEGER; - DECLARE auxprovince INTEGER; - DECLARE intemp INTEGER; - - -- Si el cliente es de Canarias se le asigna la empresa ORN - - SELECT province_id INTO auxprovince - FROM Consignatarios WHERE Id_Consigna = NEW.Id_Consigna; - - IF (auxprovince = 49 OR auxprovince = 33) AND NEW.Id_Cliente <> 5270 THEN - SET intemp = 1381; - END IF; - - IF intemp THEN - SET NEW.empresa_id = intemp; - END IF; - */ -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`TicketsAfterInsert` - AFTER INSERT ON `vn2008`.`Tickets` FOR EACH ROW -BEGIN - /* borrar cuando se canvie el insert ticket en la APP mobil */ - DECLARE vEmployee INT; - - SELECT Id_Trabajador INTO vEmployee - FROM Trabajadores WHERE user_id = account.userGetId(); - - IF vEmployee IS NULL THEN - SET vEmployee = 20; - END IF; - - IF NEW.Id_Cliente = 400 OR NEW.Id_Cliente = 200 - THEN - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, NEW.Id_Ticket, vEmployee - FROM state - WHERE `code` = 'DELIVERED'; - END IF; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `TicketsBeforeUpdate` - BEFORE UPDATE ON `Tickets` FOR EACH ROW -BEGIN - DECLARE vAgency INT; - DECLARE vEmployee INT; - DECLARE vIsCee TINYINT; - DECLARE vHasVies TINYINT; - - SELECT Id_Trabajador INTO vEmployee - FROM Trabajadores WHERE user_id = account.userGetId(); - - IF vEmployee IS NULL THEN - SET vEmployee = 20; - END IF; - - -- Comprobación de VIES - IF NEW.empresa_id <> OLD.empresa_id THEN - - SELECT CEE INTO vIsCee - FROM Proveedores AS pr - INNER JOIN Paises p ON p.Id = pr.pais_id - WHERE Id_Proveedor = NEW.empresa_id; - - SELECT isVies INTO vHasVies - FROM vn.`client` - WHERE id = OLD.Id_Cliente; - - IF vIsCee = 1 AND NOT vHasVies Then - CALL util.throw("NO_VALID_VIES"); - END IF; - END IF; - - IF NEW.Fecha < '2001-01-01' - THEN - SET NEW.Id_Ruta = NULL; - - IF NEW.Fecha < '2000-01-01' then - SET NEW.Fecha = OLD.Fecha; - END IF; - - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - VALUES(17, NEW.Id_Ticket, vEmployee); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`TicketsAfterUpdate` - AFTER UPDATE ON `Tickets` FOR EACH ROW -BEGIN - IF NEW.Id_Ruta IS NULL AND OLD.Id_Ruta IS NOT NULL THEN - INSERT INTO vn.routeLog(originFk, userFk, `action`, description) - VALUES (OLD.Id_Ruta, account.userGetId(), 'update', CONCAT('Saca el ticket ', OLD.Id_Ticket, ' de la ruta')); - ELSEIF NOT (NEW.Id_Ruta <=> OLD.Id_Ruta) THEN - INSERT INTO vn.routeLog(originFk, userFk, `action`, description) - VALUES (NEW.Id_Ruta, account.userGetId(), 'update', CONCAT('Añade el ticket ', OLD.Id_Ticket, ' a la ruta')); - END IF; - - CALL stock.queueAdd ('ticket', NEW.Id_Ticket, OLD.Id_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_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`z-developer`@`%`*/ /*!50003 TRIGGER `vn2008`.`Tickets_BEFORE_DELETE` BEFORE DELETE ON `Tickets` FOR EACH ROW -BEGIN - /*INSERT INTO vn2008.mail SET - `to` = 'jgallego@verdnatura.es', - `reply_to` = 'jgallego@verdnatura.es', - `subject` = 'Ticket Eliminado', - `text` = CONCAT(USER(), ' ha eliminado el ticket ', - OLD.`Id_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 */ ; - --- --- Table structure for table `Tickets_dits` --- - -DROP TABLE IF EXISTS `Tickets_dits`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Tickets_dits` ( - `idTickets_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) COLLATE utf8_unicode_ci DEFAULT NULL, - `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`idTickets_dits`), - KEY `fgkey1_idx` (`idaccion_dits`), - KEY `fgkey2_idx` (`Id_Ticket`), - KEY `fgkey3_idx` (`Id_Trabajador`), - CONSTRAINT `Tickets_dits_ibfk_1` FOREIGN KEY (`Id_Ticket`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fgkey1` FOREIGN KEY (`idaccion_dits`) REFERENCES `accion_dits` (`idaccion_dits`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `fgkey3` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=57478959 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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=utf8 COLLATE=utf8_unicode_ci COMMENT='Orden para imprimir los F5.Se borra autom. lo de 2 meses'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Tickets_state` --- - -DROP TABLE IF EXISTS `Tickets_state`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Tickets_state` ( - `Id_Ticket` int(11) NOT NULL DEFAULT '0', - `inter_id` int(11) NOT NULL, - `state_name` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`Id_Ticket`), - KEY `double_foreign` (`Id_Ticket`,`inter_id`), - CONSTRAINT `Id_Ticket` FOREIGN KEY (`Id_Ticket`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `double_foreign` FOREIGN KEY (`Id_Ticket`, `inter_id`) REFERENCES `vncontrol`.`inter` (`Id_Ticket`, `inter_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Tickets_turno` --- - -DROP TABLE IF EXISTS `Tickets_turno`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Tickets_turno` ( - `Id_Ticket` int(11) NOT NULL AUTO_INCREMENT, - `weekDay` tinyint(1) DEFAULT NULL COMMENT 'funcion de mysql Lunes = 0, Domingo = 6', - PRIMARY KEY (`Id_Ticket`), - CONSTRAINT `Id_Ticket_fk` FOREIGN KEY (`Id_Ticket`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=1786572 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Tintas` --- - -DROP TABLE IF EXISTS `Tintas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Tintas` ( - `Id_Tinta` char(3) COLLATE utf8_unicode_ci NOT NULL, - `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Tinta` blob NOT NULL, - `Orden` int(11) NOT NULL, - `ball` blob, - `cargex` tinyint(4) NOT NULL DEFAULT '0', - PRIMARY KEY (`Id_Tinta`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Tipos` --- - -DROP TABLE IF EXISTS `Tipos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Tipos` ( - `tipo_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `Id_Tipo` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `Tipo` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `Orden` int(11) DEFAULT '0', - `Temperatura` tinyint(1) unsigned NOT NULL DEFAULT '0', - `reino_id` int(10) unsigned NOT NULL, - `Id_Trabajador` int(11) NOT NULL, - `inventory` tinyint(4) NOT NULL DEFAULT '1', - `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `f11` tinyint(4) NOT NULL DEFAULT '0', - `father_id` smallint(5) DEFAULT NULL, - `transaction` tinyint(4) NOT NULL DEFAULT '0', - `confeccion` int(10) unsigned DEFAULT NULL, - `location` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `life` smallint(5) unsigned DEFAULT NULL, - `maneuver` double NOT NULL DEFAULT '0.21', - `target` double NOT NULL DEFAULT '0.15', - `top_margin` double NOT NULL DEFAULT '0.3', - `profit` double NOT NULL DEFAULT '0.02', - `FV` tinyint(3) DEFAULT '1', - `density` double NOT NULL DEFAULT '167' COMMENT 'Almacena el valor por defecto de la densidad en kg/m3 para el calculo de los portes aereos, en articulos se guarda la correcta', - `promo` double NOT NULL DEFAULT '0', - `box` tinyint(4) NOT NULL DEFAULT '0', - `CYM` int(11) NOT NULL DEFAULT '0', - `isPackaging` tinyint(1) NOT NULL DEFAULT '0', - `hasComponents` tinyint(1) NOT NULL DEFAULT '1', - PRIMARY KEY (`Id_Tipo`), - UNIQUE KEY `tipo_id_UNIQUE` (`tipo_id`), - KEY `Trabajador` (`Id_Trabajador`), - KEY `reino_id` (`reino_id`), - KEY `Tipos_fk3_idx` (`confeccion`), - CONSTRAINT `Tipos_fk3` FOREIGN KEY (`confeccion`) REFERENCES `vn`.`confectionType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `Tipos_ibfk_1` FOREIGN KEY (`reino_id`) REFERENCES `reinos` (`id`) ON UPDATE CASCADE, - CONSTRAINT `Trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=226 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Protege la tabla tipos de updates para los 4 parámetros de los compradores, en funcion del valor del campo CodigoRojo de tblContadores.'; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `Tipos_bu` BEFORE UPDATE ON `Tipos` FOR EACH ROW --- Edit trigger body code below this line. Do not edit lines above this one -BEGIN - DECLARE strCOD VARCHAR(40); - - SELECT CodigoRojo INTO strCOD FROM tblContadores LIMIT 1; - - IF strCOD <> 'tipos' - THEN - SET NEW.maneuver = OLD.maneuver ; - SET NEW.target = OLD.target ; - SET NEW.top_margin = OLD.top_margin ; - SET NEW.profit = OLD.profit ; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `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) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`f11_id`) -) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Trabajadores` --- - -DROP TABLE IF EXISTS `Trabajadores`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Trabajadores` ( - `Id_Trabajador` int(11) NOT NULL AUTO_INCREMENT, - `CodigoTrabajador` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `Nombre` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Apellidos` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Password` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `email` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `extension` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `sub` int(11) unsigned DEFAULT NULL, - `user` varchar(20) CHARACTER SET utf8 DEFAULT NULL, - `Contrato_Tipo` varchar(30) CHARACTER SET utf8 DEFAULT 'no dejar vacio' COMMENT 'campo obsoleto, actualmente se rellena en laboral', - `Categoria_Laboral` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `Fecha_Inicio` datetime DEFAULT NULL, - `Fecha_Fin` datetime DEFAULT NULL, - `Notas` varchar(254) COLLATE utf8_unicode_ci DEFAULT NULL, - `Foto` blob, - `dni` varchar(9) COLLATE utf8_unicode_ci DEFAULT NULL, - `address` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `date_birth` date NOT NULL, - `marital_status` enum('soltero/a','casado/a') COLLATE utf8_unicode_ci NOT NULL, - `phone` varchar(9) COLLATE utf8_unicode_ci NOT NULL, - `empresa_id` smallint(5) unsigned NOT NULL, - `Id_Cliente_Interno` int(11) DEFAULT NULL, - `user_id` int(10) unsigned DEFAULT NULL, - `boss` int(11) NOT NULL DEFAULT '2', - `DniExpiration` datetime DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`), - UNIQUE KEY `CodigoTrabajador_UNIQUE` (`CodigoTrabajador`), - UNIQUE KEY `user` (`user`), - UNIQUE KEY `user_id_UNIQUE` (`user_id`), - UNIQUE KEY `Id_Cliente_Interno` (`Id_Cliente_Interno`), - KEY `sub` (`sub`), - CONSTRAINT `Clientes` FOREIGN KEY (`Id_Cliente_Interno`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE, - CONSTRAINT `Trabajadores_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=1056 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`TrabajadoresBeforeInsert` - BEFORE INSERT ON `Trabajadores` - FOR EACH ROW -BEGIN - IF NEW.password = '' THEN - SET NEW.password = 'FALLO'; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`TrabajadoresBeforeUpdate` - BEFORE UPDATE ON `Trabajadores` - FOR EACH ROW -BEGIN - IF NEW.password = '' THEN - SET NEW.password = 'FALLO'; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `Tramos` --- - -DROP TABLE IF EXISTS `Tramos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Tramos` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `Tramo` time NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `Tramo` (`Tramo`) -) ENGINE=MyISAM AUTO_INCREMENT=50 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Ubicator` --- - -DROP TABLE IF EXISTS `Ubicator`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Ubicator` ( - `Id_Estanterias` int(11) NOT NULL, - `Date` date NOT NULL, - `w` int(11) DEFAULT '0', - `d` int(11) DEFAULT '0', - `h` int(11) DEFAULT '0', - `Id_Cubo` int(11) NOT NULL, - `Id_Article` int(11) NOT NULL -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `V_edi_item_track` --- - -DROP TABLE IF EXISTS `V_edi_item_track`; -/*!50001 DROP VIEW IF EXISTS `V_edi_item_track`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `V_edi_item_track` AS SELECT - 1 AS `item_id`, - 1 AS `s1`, - 1 AS `s2`, - 1 AS `s3`, - 1 AS `s4`, - 1 AS `s5`, - 1 AS `s6`, - 1 AS `kop`, - 1 AS `pac`, - 1 AS `cat`, - 1 AS `ori`, - 1 AS `pro`, - 1 AS `sub`, - 1 AS `package`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `Vehiculos` --- - -DROP TABLE IF EXISTS `Vehiculos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Vehiculos` ( - `Id_Vehiculo` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Matricula` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `Modelo` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `Marca` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - `m3` double DEFAULT NULL, - `active` tinyint(4) NOT NULL DEFAULT '1', - `warehouseFk` smallint(6) unsigned DEFAULT NULL, - `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`Id_Vehiculo`), - KEY `empresa_id` (`empresa_id`), - KEY `provinceFk_idx` (`warehouseFk`), - CONSTRAINT `Vehiculos_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE, - CONSTRAINT `provinceFk` FOREIGN KEY (`warehouseFk`) REFERENCES `province` (`province_id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB AUTO_INCREMENT=367 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Vehiculos_consumo` --- - -DROP TABLE IF EXISTS `Vehiculos_consumo`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Vehiculos_consumo` ( - `Vehiculos_consumo_id` int(11) NOT NULL AUTO_INCREMENT, - `Id_Vehiculo` int(10) unsigned NOT NULL, - `fecha` date NOT NULL, - `km` int(20) unsigned NOT NULL, - `litros` double unsigned NOT NULL, - `precio` double unsigned NOT NULL, - `adblue` decimal(10,2) NOT NULL DEFAULT '0.00', - `peajes` double DEFAULT NULL, - `descuento` double DEFAULT NULL, - `silla` int(11) NOT NULL DEFAULT '0' COMMENT 'indica si han repostado en la gasolinera de la rotonda', - `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `otros` double DEFAULT NULL, - PRIMARY KEY (`Vehiculos_consumo_id`,`Id_Vehiculo`), - KEY `fk_Vehiculos_consumo_Vehiculos_idx` (`Id_Vehiculo`), - CONSTRAINT `fk_Vehiculos_consumo_Vehiculos` FOREIGN KEY (`Id_Vehiculo`) REFERENCES `Vehiculos` (`Id_Vehiculo`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=7450 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='En esta tabla apuntan el importe de los tickets de la gasolinera solred, con quien tenemos un contrato y nos facturan mensualmente'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `VerEspionaje` --- - -DROP TABLE IF EXISTS `VerEspionaje`; -/*!50001 DROP VIEW IF EXISTS `VerEspionaje`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `VerEspionaje` AS SELECT - 1 AS `CodigoTrabajador`, - 1 AS `Fecha`, - 1 AS `HoraEntrada`, - 1 AS `HoraSalida`, - 1 AS `Id_Equipo`, - 1 AS `Id_Trabajador`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `Vistas` --- - -DROP TABLE IF EXISTS `Vistas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Vistas` ( - `vista_id` int(11) NOT NULL AUTO_INCREMENT, - `vista` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `code` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`vista_id`), - UNIQUE KEY `code` (`code`) -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `XDiario` --- - -DROP TABLE IF EXISTS `XDiario`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `XDiario` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `ASIEN` double DEFAULT NULL, - `FECHA` datetime DEFAULT NULL, - `SUBCTA` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL, - `CONTRA` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL, - `CONCEPTO` varchar(50) CHARACTER SET utf8 DEFAULT NULL, - `EURODEBE` decimal(10,2) DEFAULT NULL, - `EUROHABER` decimal(10,2) DEFAULT NULL, - `BASEEURO` decimal(10,2) DEFAULT NULL, - `SERIE` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `FACTURA` varchar(8) COLLATE utf8_unicode_ci DEFAULT '0', - `BASEIMPO` decimal(10,2) DEFAULT NULL, - `IVA` decimal(10,2) DEFAULT NULL, - `RECEQUIV` decimal(10,2) DEFAULT '0.00', - `DOCUMENTO` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `DEPARTA` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `CLAVE` int(11) DEFAULT NULL, - `ESTADO` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `NCASADO` decimal(10,2) DEFAULT NULL, - `TCASADO` decimal(10,2) DEFAULT NULL, - `TRANS` decimal(10,2) DEFAULT NULL, - `CAMBIO` decimal(10,2) DEFAULT NULL, - `DEBEME` decimal(10,2) DEFAULT NULL, - `HABERME` decimal(10,2) DEFAULT NULL, - `PTAHABER` decimal(10,2) DEFAULT NULL, - `AUXILIAR` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `SUCURSAL` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL, - `PTADEBE` decimal(10,2) DEFAULT NULL, - `CODDIVISA` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `IMPAUXME` decimal(10,2) DEFAULT NULL, - `MONEDAUSO` varchar(1) COLLATE utf8_unicode_ci DEFAULT '2', - `NOCONV` tinyint(1) NOT NULL DEFAULT '0', - `NUMEROINV` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `TIPOOPE` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `NFACTICK` tinyint(1) NOT NULL DEFAULT '1', - `TERIDNIF` tinyint(1) NOT NULL DEFAULT '2', - `TERNIF` varchar(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'I.F.', - `TERNOM` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Nombre Importador', - `OPBIENES` tinyint(1) NOT NULL DEFAULT '1', - `TIPOFAC` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `TIPOIVA` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `L340` tinyint(2) NOT NULL DEFAULT '0', - `enlazado` tinyint(1) NOT NULL DEFAULT '0', - `FECHA_EX` date DEFAULT NULL COMMENT 'FEcha de expedicion de la factura', - `LRECT349` tinyint(1) NOT NULL DEFAULT '0', - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - `LDIFADUAN` tinyint(4) NOT NULL DEFAULT '0', - `METAL` tinyint(1) NOT NULL DEFAULT '0', - `METALIMP` decimal(10,2) NOT NULL DEFAULT '0.00', - `CLIENTE` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL, - `METALEJE` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL, - `FECHA_OP` date DEFAULT NULL COMMENT 'FEcha de operacion', - `FACTURAEX` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Numero de factura del proveedor', - `TIPOCLAVE` int(3) DEFAULT NULL, - `TIPOEXENCI` int(3) DEFAULT NULL, - `TIPONOSUJE` int(3) DEFAULT NULL, - `TIPOFACT` int(3) DEFAULT NULL, - `TIPORECTIF` int(3) DEFAULT NULL, - `SERIE_RT` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, - `FACTU_RT` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `BASEIMP_RT` decimal(10,2) DEFAULT NULL, - `BASEIMP_RF` decimal(10,2) DEFAULT NULL, - `RECTIFICA` int(1) NOT NULL DEFAULT '0', - `FECHA_RT` date DEFAULT NULL, - `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `updated` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `FECREGCON` date DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `empresa_id` (`empresa_id`), - CONSTRAINT `XDiario_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=3220097 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `XDiario_KK` --- - -DROP TABLE IF EXISTS `XDiario_KK`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `XDiario_KK` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `ASIEN` double DEFAULT NULL, - `FECHA` date DEFAULT NULL, - `SUBCTA` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL, - `CONTRA` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL, - `CONCEPTO` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL, - `EURODEBE` decimal(10,2) DEFAULT NULL, - `EUROHABER` decimal(10,2) DEFAULT NULL, - `BASEEURO` decimal(10,2) DEFAULT NULL, - `SERIE` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `FACTURA` varchar(8) COLLATE utf8_unicode_ci DEFAULT '0', - `BASEIMPO` decimal(10,2) DEFAULT NULL, - `IVA` decimal(10,2) DEFAULT NULL, - `RECEQUIV` decimal(10,2) DEFAULT '0.00', - `DOCUMENTO` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `DEPARTA` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `CLAVE` int(11) DEFAULT NULL, - `ESTADO` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `NCASADO` decimal(10,2) DEFAULT NULL, - `TCASADO` decimal(10,2) DEFAULT NULL, - `TRANS` decimal(10,2) DEFAULT NULL, - `CAMBIO` decimal(10,2) DEFAULT NULL, - `DEBEME` decimal(10,2) DEFAULT NULL, - `HABERME` decimal(10,2) DEFAULT NULL, - `PTAHABER` decimal(10,2) DEFAULT NULL, - `AUXILIAR` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `SUCURSAL` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL, - `PTADEBE` decimal(10,2) DEFAULT NULL, - `CODDIVISA` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `IMPAUXME` decimal(10,2) DEFAULT NULL, - `MONEDAUSO` varchar(1) COLLATE utf8_unicode_ci DEFAULT '2', - `NOCONV` tinyint(1) NOT NULL DEFAULT '0', - `NUMEROINV` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `TIPOOPE` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `NFACTICK` tinyint(1) NOT NULL DEFAULT '1', - `TERIDNIF` tinyint(1) NOT NULL DEFAULT '2', - `TERNIF` varchar(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'I.F.', - `TERNOM` varchar(30) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Nombre Importador', - `OPBIENES` tinyint(1) NOT NULL DEFAULT '1', - `TIPOFAC` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `TIPOIVA` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `L340` tinyint(2) NOT NULL DEFAULT '0', - `enlazado` tinyint(1) NOT NULL DEFAULT '0', - `FECHA_EX` date DEFAULT NULL COMMENT 'FEcha de expedicion de la factura', - `LRECT349` tinyint(1) NOT NULL DEFAULT '0', - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - `LDIFADUAN` tinyint(4) NOT NULL DEFAULT '0', - `METAL` tinyint(1) NOT NULL DEFAULT '0', - `METALIMP` decimal(10,2) NOT NULL DEFAULT '0.00', - `FECHA_OP` date DEFAULT NULL COMMENT 'FEcha de operacion', - `FACTURAEX` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Numero de factura del proveedor', - `TIPOCLAVE` int(3) DEFAULT NULL, - `TIPOEXENCI` int(3) DEFAULT NULL, - `TIPONOSUJE` int(3) DEFAULT NULL, - `TIPOFACT` int(3) DEFAULT NULL, - `TIPORECTIF` int(3) DEFAULT NULL, - `SERIE_RT` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, - `FACTU_RT` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `BASEIMP_RT` decimal(10,2) DEFAULT NULL, - `BASEIMP_RF` decimal(10,2) DEFAULT NULL, - `RECTIFICA` int(1) NOT NULL DEFAULT '0', - `FECHA_RT` date DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `empresa_id` (`empresa_id`) -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `__Cartera_Ventas` --- - -DROP TABLE IF EXISTS `__Cartera_Ventas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `__Cartera_Ventas` ( - `CodigoTrabajador` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `Mes` int(2) DEFAULT NULL, - `Año` int(4) DEFAULT NULL, - `Motivo` varchar(6) COLLATE utf8_unicode_ci DEFAULT NULL, - `Importe` double DEFAULT NULL, - `Id_Ticket` bigint(20) DEFAULT NULL, - `Semana` int(2) DEFAULT NULL, - `Cliente` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - KEY `INDEX1` (`Id_Ticket`), - KEY `INDEX2` (`Mes`,`Año`,`Id_Ticket`), - KEY `INDEX3` (`CodigoTrabajador`,`Mes`,`Año`,`Id_Ticket`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`idaccion_dits`), - UNIQUE KEY `accion_UNIQUE` (`accion`) -) ENGINE=InnoDB AUTO_INCREMENT=166 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `account_conciliacion` --- - -DROP TABLE IF EXISTS `account_conciliacion`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `account_conciliacion` ( - `idaccount_conciliacion` int(11) NOT NULL AUTO_INCREMENT, - `Id_Proveedores_account` mediumint(8) unsigned NOT NULL, - `Fechaoperacion` datetime NOT NULL, - `FechaValor` datetime NOT NULL, - `importe` double NOT NULL, - `Concepto` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `DebeHaber` smallint(6) NOT NULL, - `id_calculated` varchar(90) COLLATE utf8_unicode_ci DEFAULT NULL, - `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`idaccount_conciliacion`), - UNIQUE KEY `idaccount_conciliacion_UNIQUE` (`idaccount_conciliacion`), - KEY `fg_accconciliacion_key1_idx` (`Id_Proveedores_account`), - KEY `index_id_calculated` (`id_calculated`), - CONSTRAINT `fg_key1_accountconc` FOREIGN KEY (`Id_Proveedores_account`) REFERENCES `Proveedores_account` (`Id_Proveedores_account`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=30713 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`account_conciliacion_BEFORE_INSERT` -BEFORE INSERT ON `account_conciliacion` FOR EACH ROW - -set new.id_calculated = replace( - replace( - replace( - replace( - concat(new.Id_Proveedores_account,new.Fechaoperacion,new.importe,new.Concepto,new.DebeHaber) - ,' ','') - ,":",'') - ,'-','') - ,'.','') */;; -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 */ ; - --- --- Temporary view structure for view `account_customer` --- - -DROP TABLE IF EXISTS `account_customer`; -/*!50001 DROP VIEW IF EXISTS `account_customer`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `account_customer` AS SELECT - 1 AS `description`, - 1 AS `iban`, - 1 AS `entity_id`, - 1 AS `office`, - 1 AS `dc`, - 1 AS `number`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `account_detail` --- - -DROP TABLE IF EXISTS `account_detail`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `account_detail` ( - `account_detail_id` int(11) NOT NULL AUTO_INCREMENT, - `value` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `account_detail_type_id` int(11) NOT NULL, - `Id_Proveedores_account` mediumint(8) unsigned NOT NULL, - PRIMARY KEY (`account_detail_id`), - KEY `fk_account_detail_account_detail_type1_idx` (`account_detail_type_id`), - KEY `fk_account_detail_Proveedores_account1_idx` (`Id_Proveedores_account`), - CONSTRAINT `fk_account_detail_account_detail_type1` FOREIGN KEY (`account_detail_type_id`) REFERENCES `account_detail_type` (`account_detail_type_id`) ON UPDATE CASCADE, - CONSTRAINT `fk_account_detail_account_id_proveedores_account` FOREIGN KEY (`Id_Proveedores_account`) REFERENCES `Proveedores_account` (`Id_Proveedores_account`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=70 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `account_detail_type` --- - -DROP TABLE IF EXISTS `account_detail_type`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `account_detail_type` ( - `account_detail_type_id` int(11) NOT NULL AUTO_INCREMENT, - `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`account_detail_type_id`) -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `accumulatorsReadingDate` --- - -DROP TABLE IF EXISTS `accumulatorsReadingDate`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `accumulatorsReadingDate` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `pagoSdcfk` int(11) NOT NULL, - `readingDate` date NOT NULL COMMENT 'dia en que se revisa la cotizacion del dolar', - `amount` double DEFAULT NULL COMMENT 'cantidad aumentada tras la lectura del tipo de cambio', - PRIMARY KEY (`id`), - KEY `pagoSdcFk_idx` (`pagoSdcfk`), - CONSTRAINT `pagoSdcFk` FOREIGN KEY (`pagoSdcfk`) REFERENCES `pago_sdc` (`pago_sdc_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=271 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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) COLLATE utf8_unicode_ci NOT NULL, - `Tipo` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`agencia_descuadre_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `agency` --- - -DROP TABLE IF EXISTS `agency`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `agency` ( - `agency_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, - `warehouse_id` smallint(5) unsigned DEFAULT NULL COMMENT 'A nulo si se puede enrutar desde todos los almacenes', - `por_volumen` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Si el calculo del porte se hacer por volumen', - `Id_Banco` int(11) NOT NULL DEFAULT '8' COMMENT 'para realizar los reembolsos', - `warehouse_alias_id` smallint(5) unsigned DEFAULT NULL, - `propios` tinyint(1) NOT NULL DEFAULT '0', - `zone_label` tinyint(4) NOT NULL DEFAULT '0', - PRIMARY KEY (`agency_id`), - KEY `warehouse_id` (`warehouse_id`), - KEY `Id_Banco` (`Id_Banco`), - KEY `agencias_alias_idx` (`warehouse_alias_id`), - CONSTRAINT `agency_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, - CONSTRAINT `agency_ibfk_2` FOREIGN KEY (`Id_Banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=229 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`agency_ai` -AFTER INSERT ON `vn2008`.`agency` -FOR EACH ROW -BEGIN - INSERT INTO Agencias(Agencia,agency_id) VALUES(NEW.name,NEW.agency_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 */ ; - --- --- 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 `agency` (`agency_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `agency_hour_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `agency_hour_ibfk_3` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=4338 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`agency_hourBeforeInsert` BEFORE INSERT ON `agency_hour` FOR EACH ROW -BEGIN - DECLARE vAlreadyExists BOOLEAN DEFAULT FALSE; - IF NEW.week_day IS NULL AND NEW.province_id IS NULL AND NEW.subtract_day = 0 AND NEW.max_hour = 0 THEN - CALL util.throw ('FILL_MORE_FIELDS'); - END IF; - - SELECT COUNT(*) INTO vAlreadyExists - FROM vn2008.agency_hour - WHERE NEW.week_day <=> week_day AND NEW.province_id <=> province_id - AND NEW.warehouse_id <=> warehouse_id AND NEW.max_hour <=> max_hour - AND NEW.agency_id <=> agency_id; - - IF vAlreadyExists > 1 THEN - CALL util.throw('ALREADY_EXISTS'); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`agency_hour_AFTER_UPDATE` AFTER UPDATE ON `agency_hour` FOR EACH ROW -BEGIN -DECLARE vAlreadyExists BOOLEAN DEFAULT FALSE; - - SELECT COUNT(*) INTO vAlreadyExists - FROM vn2008.agency_hour - WHERE NEW.week_day <=> week_day AND NEW.province_id <=> province_id - AND NEW.warehouse_id <=> warehouse_id AND NEW.max_hour <=> max_hour - AND NEW.agency_id <=> agency_id; - - IF vAlreadyExists > 1 THEN - CALL util.throw('ALREADY_EXISTS'); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `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 `agency` (`agency_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `agency_warehouse_ibfk_2` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Indica la vista para cada agencia'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `agency_weekday_bonus` --- - -DROP TABLE IF EXISTS `agency_weekday_bonus`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `agency_weekday_bonus` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `warehouse_id` smallint(6) unsigned DEFAULT NULL, - `agency_id` smallint(5) unsigned DEFAULT NULL, - `weekDay` tinyint(3) unsigned NOT NULL, - `zona` tinyint(4) DEFAULT NULL, - `bonus` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`id`), - UNIQUE KEY `warehouse_id` (`warehouse_id`,`agency_id`,`weekDay`,`zona`) -) ENGINE=InnoDB AUTO_INCREMENT=134 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `airline` --- - -DROP TABLE IF EXISTS `airline`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `airline` ( - `airline_id` smallint(2) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`airline_id`) -) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `airport` --- - -DROP TABLE IF EXISTS `airport`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `airport` ( - `airport_id` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `name` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`airport_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `albaran` --- - -DROP TABLE IF EXISTS `albaran`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `albaran` ( - `albaran_id` int(11) NOT NULL AUTO_INCREMENT, - `ref` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `note` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, - `fecha` date NOT NULL, - `fecha_entrega` date DEFAULT NULL, - `valor` double DEFAULT NULL, - `Id_Proveedor` int(11) NOT NULL, - `empresa_id` smallint(5) unsigned NOT NULL, - `warehouse_id` smallint(6) unsigned NOT NULL, - `albaran_state_id` int(11) NOT NULL, - `Id_Trabajador` int(11) NOT NULL COMMENT 'Id_Trabajador hace referencia a la persona que ha introducido el albarán', - `Id_Responsable` int(11) NOT NULL, - `department_id` int(11) NOT NULL, - `recibida_id` mediumint(8) unsigned DEFAULT NULL, - PRIMARY KEY (`albaran_id`), - KEY `fk_albaran_Proveedores_idx` (`Id_Proveedor`), - KEY `fk_albaran_empresa1_idx` (`empresa_id`), - KEY `fk_albaran_warehouse1_idx` (`warehouse_id`), - KEY `fk_albaran_albaran_state1_idx` (`albaran_state_id`), - KEY `fk_albaran_Trabajadores1_idx` (`Id_Trabajador`), - KEY `fk_albaran_Trabajadores2_idx` (`Id_Responsable`), - KEY `fk_albaran_department1_idx` (`department_id`), - KEY `fk_albaran_recibida_idx` (`recibida_id`), - CONSTRAINT `fk_albaran_Proveedores` FOREIGN KEY (`Id_Proveedor`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE, - CONSTRAINT `fk_albaran_Trabajadores1` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE, - CONSTRAINT `fk_albaran_Trabajadores2` FOREIGN KEY (`Id_Responsable`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE, - CONSTRAINT `fk_albaran_albaran_state1` FOREIGN KEY (`albaran_state_id`) REFERENCES `albaran_state` (`albaran_state_id`) ON UPDATE CASCADE, - CONSTRAINT `fk_albaran_department1` FOREIGN KEY (`department_id`) REFERENCES `department` (`department_id`) ON UPDATE CASCADE, - CONSTRAINT `fk_albaran_empresa1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE, - CONSTRAINT `fk_albaran_recibida` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `fk_albaran_warehouse1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2100 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `albaran_gestdoc` --- - -DROP TABLE IF EXISTS `albaran_gestdoc`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `albaran_gestdoc` ( - `gestdoc_id` int(11) NOT NULL, - `albaran_id` int(11) NOT NULL, - PRIMARY KEY (`gestdoc_id`,`albaran_id`), - KEY `fk_albaran_gestdoc_gestdoc1_idx` (`gestdoc_id`), - KEY `fk_albaran_gestdoc_albaran1_idx` (`albaran_id`), - CONSTRAINT `fk_albaran_gestdoc_albaran1` FOREIGN KEY (`albaran_id`) REFERENCES `albaran` (`albaran_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_albaran_gestdoc_gestdoc1` FOREIGN KEY (`gestdoc_id`) REFERENCES `gestdoc` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `albaran_state` --- - -DROP TABLE IF EXISTS `albaran_state`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `albaran_state` ( - `albaran_state_id` int(11) NOT NULL AUTO_INCREMENT, - `state` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`albaran_state_id`) -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `awb` --- - -DROP TABLE IF EXISTS `awb`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `awb` ( - `id` smallint(11) unsigned NOT NULL AUTO_INCREMENT, - `codigo` varchar(18) COLLATE utf8_unicode_ci NOT NULL, - `bultos` float unsigned NOT NULL, - `peso` float unsigned DEFAULT NULL, - `MYSQL_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `transitario_id` int(11) NOT NULL DEFAULT '582', - `iva_id` tinyint(3) unsigned DEFAULT '62', - `duakk` varchar(18) COLLATE utf8_unicode_ci DEFAULT NULL, - `gestdoc_id` int(11) DEFAULT NULL, - `importe` double NOT NULL DEFAULT '0', - `carguera_id` int(11) DEFAULT NULL, - `m3` double unsigned DEFAULT NULL, - `stems` int(10) unsigned DEFAULT NULL, - `flight_id` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `volume_weight` float unsigned DEFAULT NULL, - `hb` decimal(10,1) unsigned DEFAULT NULL, - `rate` decimal(10,2) unsigned DEFAULT NULL, - `booked` datetime DEFAULT NULL, - `issued` datetime DEFAULT NULL, - `operated` datetime DEFAULT NULL, - `bookEntried` date DEFAULT NULL, - `invoiceInFk` mediumint(8) unsigned DEFAULT NULL, - `isChecked` tinyint(3) DEFAULT '0', - `isTransitoryChecked` tinyint(3) DEFAULT '0', - PRIMARY KEY (`id`), - UNIQUE KEY `codigo_UNIQUE` (`codigo`), - KEY `proveedor_id` (`transitario_id`), - KEY `iva_id` (`iva_id`), - KEY `carguera_id` (`carguera_id`), - KEY `flight_id` (`flight_id`), - KEY `awbInvoiceIn` (`invoiceInFk`), - CONSTRAINT `awbInvoiceIn` FOREIGN KEY (`invoiceInFk`) REFERENCES `recibida` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `awbTransitoryFk` FOREIGN KEY (`transitario_id`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE, - CONSTRAINT `awb_ibfk_1` FOREIGN KEY (`iva_id`) REFERENCES `iva_codigo` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2396 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `awb_ai` AFTER INSERT ON `awb` FOR EACH ROW -BEGIN -DECLARE lastrecibida_id INT; -INSERT INTO recibida(proveedor_id,fecha,empresa_id) - VALUES(NEW.transitario_id,CURDATE(),442); - -SELECT last_insert_id() into lastrecibida_id; - -INSERT INTO awb_recibida(awb_id,recibida_id) - VALUES(NEW.id,lastrecibida_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_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`awb_au` AFTER UPDATE ON `awb` FOR EACH ROW -begin - -IF NEW.importe <> OLD.importe THEN - - CALL buy_tarifas_awb(NEW.codigo); - -END IF; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `awb_cargo` --- - -DROP TABLE IF EXISTS `awb_cargo`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `awb_cargo` ( - `awbFk` smallint(11) unsigned NOT NULL, - `id` int(11) DEFAULT NULL, - `awb` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL, - `awbmaster` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL, - `descripcion` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `numawb` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL, - `codcliente` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL, - `nomcliente` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `codbroker` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL, - `nombroker` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `numawbmaster` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL, - `codclientemaster` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL, - `tipoawb` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `fechaexportacion` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `cupo` int(11) DEFAULT NULL, - `pesonetocajaestiamdo` double DEFAULT NULL, - `pesovolumencajaestiamdo` double DEFAULT NULL, - `pesonetoestiamdo` double DEFAULT NULL, - `pesovolumenestiamdo` double DEFAULT NULL, - `aeropuertosalida` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `aeropuertollegada` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `codvuelo` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL, - `numvuelo` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL, - `ruta1` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `ruta2` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `ruta3` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `destinofinal` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, - `puertodestinofinal` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `tipopago` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `codbodegaentrega` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `bodegaentrega` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `codpaletizadora` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `paletizadora` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `mrn` varchar(24) COLLATE utf8_unicode_ci DEFAULT NULL, - `cierre` int(11) DEFAULT NULL, - `numebarque` int(11) DEFAULT NULL, - `pesonetocorte` double DEFAULT NULL, - `pesovolumencorte` double DEFAULT NULL, - `pcsreservadas` int(11) DEFAULT NULL, - `bxsreservadas` double DEFAULT NULL, - `pcsconfirmadas` int(11) DEFAULT NULL, - `bxsconfirmadas` double DEFAULT NULL, - `codlineacamion` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`awbFk`), - KEY `awb_cargo_fk1_idx` (`awbFk`), - CONSTRAINT `awb_cargo_fk1` FOREIGN KEY (`awbFk`) REFERENCES `awb` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Aloja los datos correspondientes al embarque relativos a la carguera'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `awb_component` --- - -DROP TABLE IF EXISTS `awb_component`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `awb_component` ( - `awb_id` smallint(11) unsigned DEFAULT NULL, - `Id_Proveedor` int(11) NOT NULL, - `Fecha` date NOT NULL, - `awb_component_type_id` mediumint(3) unsigned DEFAULT NULL, - `awb_role_id` tinyint(1) unsigned NOT NULL DEFAULT '1', - `awb_unit_id` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `value` decimal(10,2) DEFAULT NULL, - `Id_Moneda` tinyint(3) unsigned NOT NULL DEFAULT '2', - `recibida_id` mediumint(8) unsigned DEFAULT NULL, - UNIQUE KEY `unique_idx` (`awb_id`,`Id_Proveedor`,`awb_component_type_id`,`Fecha`), - KEY `Id_Moneda` (`Id_Moneda`), - KEY `awb_component_fk` (`awb_component_type_id`), - KEY `awb_role_fk` (`awb_role_id`), - KEY `awb_unit_fk` (`awb_unit_id`), - CONSTRAINT `Id_Monedafk` FOREIGN KEY (`Id_Moneda`) REFERENCES `Monedas` (`Id_Moneda`) ON DELETE CASCADE, - CONSTRAINT `awb_component_` FOREIGN KEY (`awb_component_type_id`) REFERENCES `awb_component_type` (`awb_component_type_id`) ON UPDATE CASCADE, - CONSTRAINT `awb_role_fk` FOREIGN KEY (`awb_role_id`) REFERENCES `awb_role` (`awb_role_id`) ON UPDATE CASCADE, - CONSTRAINT `awb_unit_fk` FOREIGN KEY (`awb_unit_id`) REFERENCES `awb_unit` (`awb_unit_id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `awb_component_template` --- - -DROP TABLE IF EXISTS `awb_component_template`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `awb_component_template` ( - `awb_component_template_id` int(11) NOT NULL AUTO_INCREMENT, - `carguera_id` int(11) DEFAULT NULL, - `airport_in` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `airport_out` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `airline_id` smallint(2) unsigned DEFAULT NULL, - `awb_component_type_id` mediumint(3) unsigned NOT NULL, - `Fecha` date NOT NULL, - `awb_role_id` tinyint(1) unsigned NOT NULL, - `awb_unit_id` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `value` decimal(10,3) DEFAULT NULL, - `max_value` decimal(10,2) unsigned DEFAULT NULL, - `min_value` decimal(10,2) unsigned DEFAULT NULL, - `Id_Moneda` tinyint(3) unsigned NOT NULL DEFAULT '2', - `days` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`awb_component_template_id`), - UNIQUE KEY `carguera_id_UNIQUE` (`carguera_id`,`airport_in`,`airport_out`,`airline_id`,`awb_component_type_id`,`Fecha`,`days`), - KEY `Id_Moneda` (`Id_Moneda`), - KEY `airline_idx` (`airline_id`), - KEY `role_idx` (`awb_role_id`), - KEY `awb_unit_fk1` (`awb_unit_id`), - CONSTRAINT `Id_Moneda` FOREIGN KEY (`Id_Moneda`) REFERENCES `Monedas` (`Id_Moneda`) ON UPDATE CASCADE, - CONSTRAINT `awb_unit_fk1` FOREIGN KEY (`awb_unit_id`) REFERENCES `awb_unit` (`awb_unit_id`) ON UPDATE CASCADE, - CONSTRAINT `role_fk` FOREIGN KEY (`awb_role_id`) REFERENCES `awb_role` (`awb_role_id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=488 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `awb_component_type` --- - -DROP TABLE IF EXISTS `awb_component_type`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `awb_component_type` ( - `awb_component_type_id` mediumint(3) unsigned NOT NULL AUTO_INCREMENT, - `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`awb_component_type_id`) -) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT=' '; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `awb_coordinacion` --- - -DROP TABLE IF EXISTS `awb_coordinacion`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `awb_coordinacion` ( - `hawb` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - `awb` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL, - `codexportador` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL, - `nomexportador` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `pcs` int(11) DEFAULT NULL, - `bxs` double DEFAULT NULL, - `producto` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `numdae` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `id` int(11) DEFAULT NULL, - `descripcion` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `awbFk` smallint(11) unsigned DEFAULT NULL, - PRIMARY KEY (`hawb`), - KEY `awb_coordinacion_fk1_idx` (`awbFk`), - CONSTRAINT `awb_coordinacion_fk1` FOREIGN KEY (`awbFk`) REFERENCES `awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Soporta la información relativa a las facturas que componen un embarque'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `awb_daes` --- - -DROP TABLE IF EXISTS `awb_daes`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `awb_daes` ( - `id` int(11) NOT NULL, - `descripcion` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `numdae` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `fechainicial` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `fechafinal` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - `aeropuertosalida` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `codpais` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, - `codexportador` varchar(8) COLLATE utf8_unicode_ci DEFAULT NULL, - `supplierFk` int(11) DEFAULT NULL, - PRIMARY KEY (`numdae`), - KEY `awb_daes_fk1_idx` (`supplierFk`), - CONSTRAINT `awb_daes_fk1` FOREIGN KEY (`supplierFk`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `awb_gestdoc` --- - -DROP TABLE IF EXISTS `awb_gestdoc`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `awb_gestdoc` ( - `awb_gestdoc_id` int(11) NOT NULL AUTO_INCREMENT, - `awb_id` smallint(11) unsigned NOT NULL, - `gestdoc_id` int(11) NOT NULL, - PRIMARY KEY (`awb_gestdoc_id`), - KEY `awb_gestdoc_awb_fk` (`awb_id`), - KEY `awb_gestdoc_gestdoc_fk` (`gestdoc_id`), - CONSTRAINT `awb_gestdoc_awb_fk` FOREIGN KEY (`awb_id`) REFERENCES `awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `awb_gestdoc_gestdoc_fk` FOREIGN KEY (`gestdoc_id`) REFERENCES `gestdoc` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2098 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `awb_recibida` --- - -DROP TABLE IF EXISTS `awb_recibida`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `awb_recibida` ( - `awb_id` smallint(5) unsigned NOT NULL, - `recibida_id` mediumint(8) unsigned NOT NULL, - `dua` varchar(18) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`recibida_id`), - KEY `awb_id` (`awb_id`), - CONSTRAINT `awb_recibida_ibfk_1` FOREIGN KEY (`awb_id`) REFERENCES `awb` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `awb_recibida_ibfk_2` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `awb_recibida_ad` AFTER DELETE ON `awb_recibida` FOR EACH ROW -IF (SELECT COUNT(*) FROM recibida_iva where recibida_id = OLD.recibida_id) = 0 - AND - (SELECT COUNT(*) FROM recibida_vencimiento where recibida_id = OLD.recibida_id) = 0 - AND - (SELECT contabilizada FROM recibida WHERE id = OLD.recibida_id) = 0 -THEN - DELETE FROM recibida WHERE id = OLD.recibida_id; -END IF */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `awb_role` --- - -DROP TABLE IF EXISTS `awb_role`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `awb_role` ( - `awb_role_id` tinyint(1) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`awb_role_id`) -) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT=' '; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `awb_unit` --- - -DROP TABLE IF EXISTS `awb_unit`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `awb_unit` ( - `awb_unit_id` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `operation` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`awb_unit_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='tipos de unidades'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `awb_volume` --- - -DROP TABLE IF EXISTS `awb_volume`; -/*!50001 DROP VIEW IF EXISTS `awb_volume`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `awb_volume` AS SELECT - 1 AS `awb_id`, - 1 AS `volume`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `balance_nest_tree` --- - -DROP TABLE IF EXISTS `balance_nest_tree`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `balance_nest_tree` ( - `lft` int(11) DEFAULT NULL, - `rgt` int(11) DEFAULT NULL, - `name` text COLLATE utf8_unicode_ci, - `id` int(11) NOT NULL AUTO_INCREMENT, - `Id_Gasto` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=383 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `barcodes` --- - -DROP TABLE IF EXISTS `barcodes`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `barcodes` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Id_Article` int(11) NOT NULL, - `code` varchar(22) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `code` (`code`), - UNIQUE KEY `Id_Article_2` (`Id_Article`,`code`), - KEY `Id_Article` (`Id_Article`), - CONSTRAINT `barcodes_ibfk_1` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=34507 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `bionic_updating_options` --- - -DROP TABLE IF EXISTS `bionic_updating_options`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `bionic_updating_options` ( - `buo_id` int(11) NOT NULL AUTO_INCREMENT, - `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`buo_id`) -) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='En esta tabla pondremos las distintas opciones que se ofrecen al comecial o al cliente al cambiar alguno de los parametros básicos de un ticket'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `botanic_export` --- - -DROP TABLE IF EXISTS `botanic_export`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `botanic_export` ( - `botanic_export_id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `edi_genus_id` mediumint(8) unsigned NOT NULL, - `edi_specie_id` mediumint(8) unsigned DEFAULT NULL, - `Id_Paises` mediumint(8) unsigned DEFAULT NULL, - `restriction` enum('Sin restriccion','Importacion Prohibida','Se Requiere Certificado','pasaporte individual','declaracion origen') CHARACTER SET utf8 NOT NULL, - `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`botanic_export_id`), - KEY `Id_Paises` (`Id_Paises`), - CONSTRAINT `botanic_export_ibfk_1` FOREIGN KEY (`Id_Paises`) REFERENCES `Paises` (`Id`) -) ENGINE=InnoDB AUTO_INCREMENT=274 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Especifica los generos y especies prohibidos en paises'; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`botanic_exportBeforeInsert` BEFORE INSERT ON `botanic_export` FOR EACH ROW -BEGIN - IF (SELECT botanic_export_is_updatable (NEW.edi_genus_id, NEW.edi_specie_id, NEW.id_Paises, NEW.restriction) ) > 0 THEN - CALL util.throw ('Datos duplicados'); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `businessReasonEnd` --- - -DROP TABLE IF EXISTS `businessReasonEnd`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `businessReasonEnd` ( - `id` tinyint(3) NOT NULL AUTO_INCREMENT, - `reason` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `business_labour_payrroll` --- - -DROP TABLE IF EXISTS `business_labour_payrroll`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `business_labour_payrroll` ( - `business_id` int(11) NOT NULL, - `cod_tarifa` int(11) NOT NULL, - `cod_categoria` int(11) NOT NULL, - `cod_contrato` int(11) NOT NULL, - `importepactado` double NOT NULL DEFAULT '0', - PRIMARY KEY (`business_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `buy_edi` --- - -DROP TABLE IF EXISTS `buy_edi`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `buy_edi` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `barcode` char(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `entry_year` smallint(5) unsigned NOT NULL, - `delivery_number` bigint(20) unsigned DEFAULT NULL, - `fec` date DEFAULT NULL, - `hor` time DEFAULT NULL, - `now` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `ptj` mediumint(8) unsigned DEFAULT NULL, - `ref` int(11) NOT NULL, - `item` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `pac` int(11) DEFAULT '0', - `qty` int(10) unsigned NOT NULL, - `ori` varchar(3) COLLATE utf8_unicode_ci DEFAULT 'NL', - `cat` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, - `agj` int(11) DEFAULT NULL, - `kop` int(11) DEFAULT NULL, - `ptd` varchar(6) COLLATE utf8_unicode_ci DEFAULT NULL, - `sub` mediumint(8) unsigned DEFAULT NULL, - `pro` mediumint(8) unsigned NOT NULL, - `pri` double NOT NULL, - `package` int(10) unsigned DEFAULT NULL, - `auction` smallint(5) unsigned DEFAULT NULL, - `klo` smallint(5) unsigned DEFAULT NULL, - `k01` smallint(5) unsigned DEFAULT NULL, - `k02` smallint(5) unsigned DEFAULT NULL, - `k03` tinyint(3) unsigned DEFAULT NULL, - `k04` tinyint(3) unsigned DEFAULT NULL, - `s1` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `s2` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `s3` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `s4` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL, - `s5` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `s6` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `ok` tinyint(4) NOT NULL DEFAULT '0', - `trolley_id` int(11) DEFAULT NULL, - `scanned` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`id`) USING BTREE, - UNIQUE KEY `barcode_year` (`barcode`,`entry_year`), - UNIQUE KEY `delivery_number` (`delivery_number`), - KEY `ref` (`ref`), - KEY `ptj` (`ptj`), - KEY `pro` (`pro`), - KEY `kop` (`kop`), - KEY `barcode` (`barcode`), - KEY `fec` (`fec`) -) ENGINE=InnoDB AUTO_INCREMENT=652104 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `buy_edi_k012` --- - -DROP TABLE IF EXISTS `buy_edi_k012`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `buy_edi_k012` ( - `buy_edi_k012_id` smallint(6) unsigned NOT NULL, - `description` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`buy_edi_k012_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Características negativas de los articulos de subasta'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `buy_edi_k03` --- - -DROP TABLE IF EXISTS `buy_edi_k03`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `buy_edi_k03` ( - `buy_edi_k03_id` tinyint(3) unsigned NOT NULL, - `description` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`buy_edi_k03_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Características fitosanitarias de los articulos de subasta'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `buy_edi_k04` --- - -DROP TABLE IF EXISTS `buy_edi_k04`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `buy_edi_k04` ( - `buy_edi_k04_id` tinyint(3) unsigned NOT NULL, - `description` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`buy_edi_k04_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Características calidad de los articulos de subasta'; -/*!40101 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 COLLATE utf8_unicode_ci NOT NULL, - `Conclusio` tinyint(3) unsigned NOT NULL, - `Id_Cliente` int(11) NOT NULL, - `fecha` date NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=164 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `callings` --- - -DROP TABLE IF EXISTS `callings`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `callings` ( - `id` int(11) NOT NULL, - `motivo` varchar(105) COLLATE utf8_unicode_ci DEFAULT NULL, - `tel1` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `tel2` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `situacion` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `callingtasksKK` --- - -DROP TABLE IF EXISTS `callingtasksKK`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `callingtasksKK` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `instruccion` varchar(99) COLLATE utf8_unicode_ci DEFAULT NULL, - `tel1` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `tel2` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `situacion` varchar(99) COLLATE utf8_unicode_ci DEFAULT NULL, - `closed` tinyint(1) DEFAULT '0', - `Id_Trabajador` tinyint(4) DEFAULT NULL, - `Id_Prioridad` tinyint(4) DEFAULT '2', - `selected` tinyint(4) DEFAULT '0', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `cdr` --- - -DROP TABLE IF EXISTS `cdr`; -/*!50001 DROP VIEW IF EXISTS `cdr`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `cdr` AS SELECT - 1 AS `calldate`, - 1 AS `clid`, - 1 AS `src`, - 1 AS `dst`, - 1 AS `dcontext`, - 1 AS `channel`, - 1 AS `dstchannel`, - 1 AS `lastapp`, - 1 AS `lastdata`, - 1 AS `duration`, - 1 AS `billsec`, - 1 AS `disposition`, - 1 AS `amaflags`, - 1 AS `accountcode`, - 1 AS `uniqueid`, - 1 AS `userfield`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `chanel` --- - -DROP TABLE IF EXISTS `chanel`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `chanel` ( - `chanel_id` smallint(6) NOT NULL AUTO_INCREMENT, - `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`chanel_id`) -) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Canal por el que nos ha conocido un cliente y se ha dado de'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `chat` --- - -DROP TABLE IF EXISTS `chat`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `chat` ( - `chat_id` int(11) NOT NULL AUTO_INCREMENT, - `Id_Trabajador` int(11) NOT NULL, - `msg` varchar(254) COLLATE utf8_unicode_ci DEFAULT NULL, - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`chat_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Para chatear los compradores, en el frmRESERVE de la COMPARATIVA'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `city` --- - -DROP TABLE IF EXISTS `city`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `city` ( - `city_id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `province_id` smallint(6) unsigned DEFAULT NULL, - `nst_geo_id` int(11) DEFAULT NULL, - `nst_name` varchar(50) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`city_id`), - UNIQUE KEY `province_city_pk` (`province_id`,`name`), - KEY `NST_CITY_FK_idx` (`nst_geo_id`), - CONSTRAINT `nst_geo_city` FOREIGN KEY (`nst_geo_id`) REFERENCES `nst`.`geo` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `province_city_fk` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=4423 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`city_BEFORE_INSERT` BEFORE INSERT ON `city` FOR EACH ROW -BEGIN - -SET new.nst_name = new.`name`; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`city_AFTER_DELETE` AFTER DELETE ON `city` FOR EACH ROW -BEGIN - -CALL nst.del(OLD.nst_geo_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 */ ; - --- --- Table structure for table `cl_act` --- - -DROP TABLE IF EXISTS `cl_act`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cl_act` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Id_Movimiento` int(11) DEFAULT NULL, - `cl_main_id` int(10) unsigned NOT NULL, - `Id_Trabajador` int(11) NOT NULL DEFAULT '20', - `cl_sol_id` tinyint(4) DEFAULT NULL, - `greuge` tinyint(4) NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - KEY `cl_main_id` (`cl_main_id`), - KEY `Id_Trabajador` (`Id_Trabajador`), - KEY `Id_Movimiento` (`Id_Movimiento`), - KEY `cl_sol_id` (`cl_sol_id`), - CONSTRAINT `cl_act_ibfk_1` FOREIGN KEY (`Id_Movimiento`) REFERENCES `Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `cl_act_ibfk_3` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE, - CONSTRAINT `cl_act_ibfk_4` FOREIGN KEY (`cl_main_id`) REFERENCES `cl_main` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=78358 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Acciones en respuesta a las reclamaciones'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cl_cau` --- - -DROP TABLE IF EXISTS `cl_cau`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cl_cau` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `cl_main_id` int(10) unsigned NOT NULL, - `cl_res_id` int(10) unsigned NOT NULL DEFAULT '1', - `Id_Trabajador` int(11) NOT NULL DEFAULT '20', - `cl_mot_id` int(10) unsigned NOT NULL DEFAULT '1', - `cl_con_id` int(10) unsigned NOT NULL DEFAULT '1', - `cl_dev` tinyint(3) unsigned NOT NULL DEFAULT '1', - `cl_sol` tinyint(3) unsigned NOT NULL DEFAULT '2', - PRIMARY KEY (`id`), - KEY `cl_main_id` (`cl_main_id`), - KEY `cl_res_id` (`cl_res_id`), - KEY `Id_Trabajador` (`Id_Trabajador`), - KEY `cl_mot_id` (`cl_mot_id`), - KEY `cl_con_id` (`cl_con_id`), - KEY `cl_dev` (`cl_dev`), - KEY `cl_sol` (`cl_sol`), - CONSTRAINT `cl_cau_ibfk_10` FOREIGN KEY (`cl_main_id`) REFERENCES `cl_main` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `cl_cau_ibfk_11` FOREIGN KEY (`cl_dev`) REFERENCES `cl_dev` (`id`) ON UPDATE CASCADE, - CONSTRAINT `cl_cau_ibfk_12` FOREIGN KEY (`cl_sol`) REFERENCES `cl_sol` (`id`) ON UPDATE CASCADE, - CONSTRAINT `cl_cau_ibfk_6` FOREIGN KEY (`cl_res_id`) REFERENCES `cl_res` (`id`) ON UPDATE CASCADE, - CONSTRAINT `cl_cau_ibfk_7` FOREIGN KEY (`cl_mot_id`) REFERENCES `cl_mot` (`id`) ON UPDATE CASCADE, - CONSTRAINT `cl_cau_ibfk_8` FOREIGN KEY (`cl_con_id`) REFERENCES `cl_con` (`id`) ON UPDATE CASCADE, - CONSTRAINT `cl_cau_ibfk_9` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=43355 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Causas de las reclamaciones'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cl_con` --- - -DROP TABLE IF EXISTS `cl_con`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cl_con` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `consecuencia` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Consecuencias de los motivos'; -/*!40101 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) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Departamentos para las quejas'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cl_det` --- - -DROP TABLE IF EXISTS `cl_det`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cl_det` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `cl_main_id` int(10) unsigned NOT NULL, - `Id_Movimiento` int(11) DEFAULT NULL, - `cl_que_id` int(10) unsigned NOT NULL DEFAULT '1', - `cl_pet_id` int(1) unsigned NOT NULL DEFAULT '1', - `numero` double DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `Id_Movimiento` (`Id_Movimiento`), - KEY `cl_pet_id` (`cl_pet_id`), - KEY `cl_que_id` (`cl_que_id`), - KEY `cl_main_id` (`cl_main_id`), - CONSTRAINT `cl_det_ibfk_5` FOREIGN KEY (`cl_que_id`) REFERENCES `cl_que` (`id`) ON UPDATE CASCADE, - CONSTRAINT `cl_det_ibfk_6` FOREIGN KEY (`cl_pet_id`) REFERENCES `cl_pet` (`id`) ON UPDATE CASCADE, - CONSTRAINT `cl_det_ibfk_7` FOREIGN KEY (`Id_Movimiento`) REFERENCES `Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `cl_det_ibfk_8` FOREIGN KEY (`cl_main_id`) REFERENCES `cl_main` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=108577 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalle de las reclamaciones'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cl_dev` --- - -DROP TABLE IF EXISTS `cl_dev`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cl_dev` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `devolucion` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Método por el cual el cliente nos devuelve la mercancía'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cl_est` --- - -DROP TABLE IF EXISTS `cl_est`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cl_est` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `estado` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Estados posibles de las reclamaciones'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cl_main` --- - -DROP TABLE IF EXISTS `cl_main`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cl_main` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Fecha` datetime NOT NULL, - `cl_dep_id` tinyint(3) unsigned DEFAULT NULL, - `cl_est_id` int(10) unsigned NOT NULL DEFAULT '1', - `notas` text COLLATE utf8_unicode_ci, - `Id_Cliente` int(11) NOT NULL, - `Id_Trabajador` int(11) NOT NULL, - `sensib` int(1) unsigned NOT NULL DEFAULT '3', - `mana` tinyint(1) NOT NULL DEFAULT '0', - `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `cl_dep_id` (`cl_dep_id`), - KEY `cl_est_id` (`cl_est_id`), - KEY `Id_Cliente` (`Id_Cliente`), - KEY `Id_Trabajador` (`Id_Trabajador`), - CONSTRAINT `cl_main_ibfk_3` FOREIGN KEY (`cl_est_id`) REFERENCES `cl_est` (`id`) ON UPDATE CASCADE, - CONSTRAINT `cl_main_ibfk_4` FOREIGN KEY (`cl_dep_id`) REFERENCES `cl_dep` (`id`) ON UPDATE CASCADE, - CONSTRAINT `cl_main_ibfk_5` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=46420 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Reclamaciones, tabla principal'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cl_mot` --- - -DROP TABLE IF EXISTS `cl_mot`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cl_mot` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `motivo` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Motivos de las fallos'; -/*!40101 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) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Peticiones de los cliente en relacion a las quejas'; -/*!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) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Queja por linea de las reclamaciones'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cl_res` --- - -DROP TABLE IF EXISTS `cl_res`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cl_res` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `responsable` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `sensibility` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'if=1 >sensib >culpa', - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Responsables de las causas'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cl_sol` --- - -DROP TABLE IF EXISTS `cl_sol`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cl_sol` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `solucion` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Solucion ofrecida a la reclamación'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `clientMana` --- - -DROP TABLE IF EXISTS `clientMana`; -/*!50001 DROP VIEW IF EXISTS `clientMana`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `clientMana` AS SELECT - 1 AS `Id_Cliente`, - 1 AS `ManaUnitario`, - 1 AS `ManaTotal`, - 1 AS `Id_Ticket`, - 1 AS `Id_Article`, - 1 AS `Concepte`, - 1 AS `Cantidad`, - 1 AS `Preu`, - 1 AS `Fecha`, - 1 AS `Id_Movimiento`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `client_observation` --- - -DROP TABLE IF EXISTS `client_observation`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `client_observation` ( - `client_observation_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `Id_Cliente` int(11) NOT NULL, - `Id_Trabajador` int(11) NOT NULL, - `text` text COLLATE utf8_unicode_ci NOT NULL, - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`client_observation_id`), - KEY `Id_Trabajador` (`Id_Trabajador`), - KEY `Id_Cliente` (`Id_Cliente`), - CONSTRAINT `client_observation_ibfk_1` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `client_observation_ibfk_2` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=58973 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Todas las observaciones referentes a un ticket'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `clientes_gestdoc` --- - -DROP TABLE IF EXISTS `clientes_gestdoc`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `clientes_gestdoc` ( - `Id_Cliente` int(11) NOT NULL, - `gest_doc_id` int(11) NOT NULL, - PRIMARY KEY (`Id_Cliente`,`gest_doc_id`), - KEY `gest_doc_id` (`gest_doc_id`), - CONSTRAINT `clientes_gestdoc_ibfk_2` FOREIGN KEY (`gest_doc_id`) REFERENCES `gestdoc` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `clientes_gestdoc_ibfk_3` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `clientes_regalos_enc` --- - -DROP TABLE IF EXISTS `clientes_regalos_enc`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `clientes_regalos_enc` ( - `Id_Cliente` int(11) NOT NULL, - `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `Id_Regalo` int(11) NOT NULL, - PRIMARY KEY (`Id_Cliente`,`Id_Regalo`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `clientes_regalos_lista_enc` --- - -DROP TABLE IF EXISTS `clientes_regalos_lista_enc`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `clientes_regalos_lista_enc` ( - `Id_Regalo` int(11) NOT NULL AUTO_INCREMENT, - `Descripcion` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `Activo` bit(1) NOT NULL DEFAULT b'0', - `foto` blob, - `datstart` date DEFAULT NULL, - `datend` date DEFAULT NULL, - `warehouse_id` smallint(6) unsigned DEFAULT '1', - `province_id` smallint(5) unsigned DEFAULT NULL, - PRIMARY KEY (`Id_Regalo`) -) ENGINE=MyISAM AUTO_INCREMENT=29 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `clientes_tipo` --- - -DROP TABLE IF EXISTS `clientes_tipo`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `clientes_tipo` ( - `clientes_tipo_id` int(11) NOT NULL AUTO_INCREMENT, - `code` varchar(20) CHARACTER SET utf8 NOT NULL, - `tipo` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`clientes_tipo_id`), - UNIQUE KEY `code_UNIQUE` (`code`) -) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Establece categorias para poder agrupar las ventas'; -/*!40101 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=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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', - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `config_host` --- - -DROP TABLE IF EXISTS `config_host`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `config_host` ( - `config_host_id` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - `warehouse` smallint(6) unsigned NOT NULL DEFAULT '1', - `empresa_id` smallint(6) unsigned NOT NULL DEFAULT '442', - `caja` int(11) DEFAULT '13', - `Id_Impresora` tinyint(3) unsigned DEFAULT '27', - `Permanente` tinyint(1) unsigned DEFAULT '1', - `route_days_before` smallint(6) DEFAULT '2', - `route_days_after` smallint(6) DEFAULT '1', - PRIMARY KEY (`config_host_id`), - KEY `warehouse` (`warehouse`), - KEY `empresa_id` (`empresa_id`), - KEY `caja` (`caja`), - KEY `Id_Impresora` (`Id_Impresora`), - CONSTRAINT `config_host_ibfk_1` FOREIGN KEY (`caja`) REFERENCES `Bancos` (`Id_Banco`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `config_host_ibfk_2` FOREIGN KEY (`warehouse`) REFERENCES `warehouse` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `config_host_ibfk_3` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `config_host_ibfk_4` FOREIGN KEY (`Id_Impresora`) REFERENCES `Impresoras` (`Id_Impresora`) ON DELETE NO ACTION ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Sustituye al antiguo TPV_Settings'; -/*!40101 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(15) COLLATE utf8_unicode_ci NOT NULL, - `formname` varchar(56) COLLATE utf8_unicode_ci 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_form_ibfk_1` FOREIGN KEY (`config_host_id`) REFERENCES `config_host` (`config_host_id`) ON DELETE NO ACTION ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Registra las posiciones de los formularios'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `consignatarios_observation` --- - -DROP TABLE IF EXISTS `consignatarios_observation`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `consignatarios_observation` ( - `consignatarios_observation_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `Id_Consigna` int(11) NOT NULL, - `observation_type_id` tinyint(3) unsigned NOT NULL, - `text` text COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`consignatarios_observation_id`), - UNIQUE KEY `Id_Consigna` (`Id_Consigna`,`observation_type_id`) -) ENGINE=InnoDB AUTO_INCREMENT=2957 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Observaciones de los consignatarios'; -/*!40101 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) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`container_id`) -) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`cooler_path_id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Define el orden en que se imprimen los F5'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cooler_path_detail` --- - -DROP TABLE IF EXISTS `cooler_path_detail`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cooler_path_detail` ( - `cooler_path_detail_id` int(11) NOT NULL AUTO_INCREMENT, - `cooler_path_id` int(11) NOT NULL DEFAULT '1', - `pasillo` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`cooler_path_id`,`pasillo`), - UNIQUE KEY `cooler_path_detail_id_UNIQUE` (`cooler_path_detail_id`) -) ENGINE=InnoDB AUTO_INCREMENT=94 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`cp_id`) -) ENGINE=InnoDB AUTO_INCREMENT=77 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Relacio de codis postals i el municipi al qual se asigna'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `credit` --- - -DROP TABLE IF EXISTS `credit`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `credit` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `Id_Cliente` int(11) NOT NULL, - `amount` double unsigned NOT NULL, - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `Id_Trabajador` int(11) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `workers_fk_idx` (`Id_Trabajador`), - KEY `credit_ClienteFk` (`Id_Cliente`), - CONSTRAINT `credit_ClienteFk` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `workers_fk` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=60393 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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) COLLATE utf8_unicode_ci 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) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`credit_card_id`), - KEY `Id_Cliente` (`Id_Cliente`), - CONSTRAINT `credit_card_ibfk_1` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=956 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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 `Clientes` (`id_cliente`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=467096 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalla los clientes que estan clasificados en Credito y Cau'; -/*!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 `Facturas` (`factura_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Registro de las facturas declaradas a cyc'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `daily_task_log` --- - -DROP TABLE IF EXISTS `daily_task_log`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `daily_task_log` ( - `consulta` varchar(250) COLLATE utf8_unicode_ci NOT NULL, - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='No he encontrado el lugar en el que vicente almacena la hora en que se ejecutan las daily tasks, asi que he hecho esta tabla, a eliminar cuando se considere oportuno'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `definitivo` --- - -DROP TABLE IF EXISTS `definitivo`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `definitivo` ( - `definitivo_id` int(11) NOT NULL, - `empresa_id` int(11) NOT NULL, - `desde` bigint(20) NOT NULL, - `hasta` bigint(20) NOT NULL, - `fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`definitivo_id`,`empresa_id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `department` --- - -DROP TABLE IF EXISTS `department`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `department` ( - `department_id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `lft` int(11) NOT NULL, - `rgt` int(11) NOT NULL, - `Id_Trabajador` int(11) DEFAULT NULL COMMENT 'Id_Trabajador es el jefe del departamento', - PRIMARY KEY (`department_id`), - UNIQUE KEY `lft_UNIQUE` (`lft`), - UNIQUE KEY `rgt_UNIQUE` (`rgt`), - UNIQUE KEY `name_UNIQUE` (`name`), - KEY `fk_department_Trabajadores1_idx` (`Id_Trabajador`), - CONSTRAINT `fk_department_Trabajadores1` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `device` --- - -DROP TABLE IF EXISTS `device`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `device` ( - `device_id` int(11) NOT NULL AUTO_INCREMENT, - `sn` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `model` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`device_id`), - UNIQUE KEY `device_id_UNIQUE` (`device_id`), - UNIQUE KEY `sn_UNIQUE` (`sn`) -) ENGINE=InnoDB AUTO_INCREMENT=178 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `device_user` --- - -DROP TABLE IF EXISTS `device_user`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `device_user` ( - `device_id` int(11) NOT NULL, - `user_id` int(11) NOT NULL, - PRIMARY KEY (`device_id`,`user_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `dhl` --- - -DROP TABLE IF EXISTS `dhl`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `dhl` ( - `codigo_postal` mediumint(8) unsigned NOT NULL, - `frecuencia` tinyint(3) unsigned NOT NULL, - PRIMARY KEY (`codigo_postal`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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) COLLATE utf8_unicode_ci NOT NULL, - `xPos` int(11) DEFAULT NULL, - `yPos` int(11) DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `code_UNIQUE` (`code`) -) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Soporta la estructura de muelles de paletizacion'; -/*!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) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`,`ticketFk`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `edi_article` --- - -DROP TABLE IF EXISTS `edi_article`; -/*!50001 DROP VIEW IF EXISTS `edi_article`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `edi_article` AS SELECT - 1 AS `id`, - 1 AS `product_name`, - 1 AS `name`, - 1 AS `plant_id`, - 1 AS `group_id`, - 1 AS `entry_date`, - 1 AS `expiry_date`, - 1 AS `change_date_time`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `edi_bucket` --- - -DROP TABLE IF EXISTS `edi_bucket`; -/*!50001 DROP VIEW IF EXISTS `edi_bucket`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `edi_bucket` AS SELECT - 1 AS `bucket_id`, - 1 AS `bucket_type_id`, - 1 AS `description`, - 1 AS `x_size`, - 1 AS `y_size`, - 1 AS `z_size`, - 1 AS `entry_date`, - 1 AS `expiry_date`, - 1 AS `change_date_time`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `edi_bucket_type` --- - -DROP TABLE IF EXISTS `edi_bucket_type`; -/*!50001 DROP VIEW IF EXISTS `edi_bucket_type`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `edi_bucket_type` AS SELECT - 1 AS `bucket_type_id`, - 1 AS `description`, - 1 AS `entry_date`, - 1 AS `expiry_date`, - 1 AS `change_date_time`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `edi_feature` --- - -DROP TABLE IF EXISTS `edi_feature`; -/*!50001 DROP VIEW IF EXISTS `edi_feature`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `edi_feature` AS SELECT - 1 AS `item_id`, - 1 AS `feature_type_id`, - 1 AS `feature_value`, - 1 AS `entry_date`, - 1 AS `expiry_date`, - 1 AS `change_date_time`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `edi_genus` --- - -DROP TABLE IF EXISTS `edi_genus`; -/*!50001 DROP VIEW IF EXISTS `edi_genus`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `edi_genus` AS SELECT - 1 AS `genus_id`, - 1 AS `latin_genus_name`, - 1 AS `entry_date`, - 1 AS `expiry_date`, - 1 AS `change_date_time`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `edi_item_feature` --- - -DROP TABLE IF EXISTS `edi_item_feature`; -/*!50001 DROP VIEW IF EXISTS `edi_item_feature`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `edi_item_feature` AS SELECT - 1 AS `item_id`, - 1 AS `presentation_order`, - 1 AS `feature`, - 1 AS `regulation_type`, - 1 AS `entry_date`, - 1 AS `expiry_date`, - 1 AS `change_date_time`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `edi_plant` --- - -DROP TABLE IF EXISTS `edi_plant`; -/*!50001 DROP VIEW IF EXISTS `edi_plant`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `edi_plant` AS SELECT - 1 AS `plant_id`, - 1 AS `genus_id`, - 1 AS `specie_id`, - 1 AS `entry_date`, - 1 AS `expiry_date`, - 1 AS `change_date_time`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `edi_specie` --- - -DROP TABLE IF EXISTS `edi_specie`; -/*!50001 DROP VIEW IF EXISTS `edi_specie`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `edi_specie` AS SELECT - 1 AS `specie_id`, - 1 AS `genus_id`, - 1 AS `latin_species_name`, - 1 AS `entry_date`, - 1 AS `expiry_date`, - 1 AS `change_date_time`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `edi_supplier` --- - -DROP TABLE IF EXISTS `edi_supplier`; -/*!50001 DROP VIEW IF EXISTS `edi_supplier`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `edi_supplier` AS SELECT - 1 AS `supplier_id`, - 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) COLLATE utf8_unicode_ci NOT NULL, - `field` varchar(32) COLLATE utf8_unicode_ci NOT NULL, - `testigo` varchar(5) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `edi_type` --- - -DROP TABLE IF EXISTS `edi_type`; -/*!50001 DROP VIEW IF EXISTS `edi_type`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `edi_type` AS SELECT - 1 AS `type_id`, - 1 AS `type_group_id`, - 1 AS `description`, - 1 AS `entry_date`, - 1 AS `expiry_date`, - 1 AS `change_date_time`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `edi_value` --- - -DROP TABLE IF EXISTS `edi_value`; -/*!50001 DROP VIEW IF EXISTS `edi_value`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `edi_value` AS SELECT - 1 AS `type_id`, - 1 AS `type_value`, - 1 AS `type_description`, - 1 AS `entry_date`, - 1 AS `expiry_date`, - 1 AS `change_date_time`*/; -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=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `empresa` --- - -DROP TABLE IF EXISTS `empresa`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `empresa` ( - `id` smallint(5) unsigned NOT NULL, - `abbreviation` char(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `registro` varchar(120) COLLATE utf8_unicode_ci NOT NULL, - `gerente_id` int(11) NOT NULL, - `alta` date NOT NULL, - `baja` date DEFAULT NULL, - `logo` longblob, - `oficial` tinyint(1) unsigned NOT NULL DEFAULT '1', - `cyc` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0', - `rgb` varchar(6) COLLATE utf8_unicode_ci NOT NULL, - `mail` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `cuno` blob, - `ODBC_DATE` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP, - `Id_Cliente` int(11) DEFAULT NULL, - `digito_factura` int(2) DEFAULT NULL, - `Id_Proveedores_account` mediumint(8) unsigned DEFAULT NULL, - `morosidad` tinyint(4) NOT NULL DEFAULT '0', - `empresa_grupo` int(11) NOT NULL DEFAULT '1', - `CodigoEmpresa` int(2) DEFAULT NULL COMMENT 'Campo para movConta', - PRIMARY KEY (`id`), - KEY `gerente_id` (`gerente_id`), - KEY `empresa_cliente_idx` (`Id_Cliente`), - KEY `Id_Proveedores_account` (`Id_Proveedores_account`), - KEY `empresa_grupo_fk_idx` (`empresa_grupo`), - CONSTRAINT `empresa_cliente` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT `empresa_ibfk_1` FOREIGN KEY (`gerente_id`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE, - CONSTRAINT `fk_empresa_grupo` FOREIGN KEY (`empresa_grupo`) REFERENCES `empresa_grupo` (`empresa_grupo_id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `empresa_grupo` --- - -DROP TABLE IF EXISTS `empresa_grupo`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `empresa_grupo` ( - `empresa_grupo_id` int(11) NOT NULL AUTO_INCREMENT, - `grupo` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`empresa_grupo_id`) -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `entity` --- - -DROP TABLE IF EXISTS `entity`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `entity` ( - `pais_id` mediumint(8) unsigned NOT NULL DEFAULT '1', - `entity_id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `bic` varchar(11) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`entity_id`), - UNIQUE KEY `bic_UNIQUE` (`bic`), - KEY `fg_entity1_idx` (`pais_id`), - CONSTRAINT `fg_entity1` FOREIGN KEY (`pais_id`) REFERENCES `Paises` (`Id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=30004 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Entidades bancarias '; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `escritos` --- - -DROP TABLE IF EXISTS `escritos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `escritos` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `abrev` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `descripcion` varchar(105) COLLATE utf8_unicode_ci NOT NULL, - `visible` tinyint(4) NOT NULL DEFAULT '1', - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `escritos_det` --- - -DROP TABLE IF EXISTS `escritos_det`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `escritos_det` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Id_Cliente` int(10) unsigned NOT NULL, - `escritos_id` int(10) unsigned NOT NULL, - `fecha` datetime NOT NULL, - `Id_Trabajador` int(10) unsigned NOT NULL, - `Saldo` float NOT NULL, - `empresa_id` smallint(5) unsigned DEFAULT NULL, - `escritos_detcol` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `userFk` int(11) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `empresa_id` (`empresa_id`), - CONSTRAINT `escritos_det_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=14806 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `expeditions` --- - -DROP TABLE IF EXISTS `expeditions`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `expeditions` ( - `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, - `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', - `workerFk` int(11) DEFAULT NULL, - PRIMARY KEY (`expeditions_id`), - KEY `index1` (`agency_id`), - KEY `index2` (`EsBulto`), - KEY `index3` (`odbc_date`), - KEY `index4` (`ticket_id`), - CONSTRAINT `Id_Agencia` FOREIGN KEY (`agency_id`) REFERENCES `Agencias` (`Id_Agencia`) ON UPDATE CASCADE, - CONSTRAINT `ticket_id` FOREIGN KEY (`ticket_id`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2267551 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `expeditionsBeforeInsert` -BEFORE INSERT ON `expeditions` FOR EACH ROW --- Edit trigger body code below this line. Do not edit lines above this one -BEGIN - DECLARE intcounter INT; - - IF NEW.EsBulto > 0 THEN - - UPDATE Tickets SET Bultos = nz(Bultos) + 1 WHERE Id_Ticket = NEW.ticket_id; - SELECT IFNULL(MAX(counter),0) +1 INTO intcounter FROM expeditions e - INNER JOIN Tickets t1 ON e.ticket_id = t1.Id_Ticket - LEFT JOIN vn.ticketState ts ON ts.ticket = t1.Id_Ticket - INNER JOIN Tickets t2 ON t2.Id_Consigna = t1.Id_Consigna AND DATE(t2.Fecha) = DATE(t1.Fecha) AND t1.warehouse_id = t2.warehouse_id - WHERE t2.Id_Ticket = NEW.ticket_id AND ts.alertLevel < 3 AND t1.empresa_id = t2.empresa_id AND t1.Id_Agencia = t2.Id_Agencia; - SET NEW.`counter` = intcounter; - END IF; - SET NEW.workerFk=get_Trabajador(); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`expeditionsBeforeUpdate` -BEFORE UPDATE ON `vn2008`.`expeditions` -FOR EACH ROW --- Edit trigger body code below this line. Do not edit lines above this one -BEGIN - IF NEW.counter <> OLD.counter THEN - IF (SELECT COUNT(*) FROM expeditions e - INNER JOIN Tickets t1 ON e.ticket_id = t1.Id_Ticket - INNER JOIN Tickets t2 ON t2.Id_Consigna = t1.Id_Consigna AND DATE(t2.Fecha) = DATE(t1.Fecha) - WHERE t1.Id_Ticket = NEW.ticket_id AND counter = NEW.counter) > 0 THEN - SET NEW.expeditions_id = NULL; - END IF; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`expeditionsAfterUpdate` -AFTER UPDATE ON `expeditions` FOR EACH ROW -BEGIN - CALL cache.barcodes_expeditions_update(NEW.expeditions_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_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`expeditionsBeforeDelete` -BEFORE DELETE ON `expeditions` FOR EACH ROW -BEGIN - DECLARE trabajador integer DEFAULT NULL; - - - SELECT Id_Trabajador into trabajador from Trabajadores where user_id = account.userGetId(); - if trabajador is null then - SET trabajador = 33; - end if; - UPDATE Tickets SET Bultos = (SELECT COUNT(counter)-1 FROM expeditions WHERE ticket_id = OLD.ticket_id and EsBulto) WHERE Id_Ticket = OLD.ticket_id; - - INSERT INTO Tickets_dits (idaccion_dits,Id_Trabajador,Id_Ticket,value_old,value_new) - SELECT 133/*Borra expedition*/,trabajador,OLD.ticket_id,CONCAT(OLD.odbc_date,',Bultos:',OLD.counter,',Embalaje:',OLD.EsBulto),user() - FROM Tickets - WHERE Id_Ticket = OLD.ticket_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 */ ; - --- --- 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) COLLATE utf8_unicode_ci 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 AUTO_INCREMENT=2267374 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci NOT NULL, - `sql` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `Estanteria` tinyint(1) DEFAULT '0', - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=137 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `financialProductType` --- - -DROP TABLE IF EXISTS `financialProductType`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `financialProductType` ( - `id` varchar(2) COLLATE utf8_unicode_ci NOT NULL, - `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `description_UNIQUE` (`description`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Distintos tipos de productos financieros: seguros de cambio, polizas de credito, acumuladores....'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `flight` --- - -DROP TABLE IF EXISTS `flight`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `flight` ( - `flight_id` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `duration` tinyint(2) unsigned DEFAULT NULL, - `route` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `days` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL, - `airline_id` smallint(2) unsigned DEFAULT NULL, - `airport_out` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `airport_in` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`flight_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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) COLLATE utf8_unicode_ci NOT NULL, - `response1` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `response2` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `type_id` enum('gest_doc') COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`form_query_id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `gastos_resumen` --- - -DROP TABLE IF EXISTS `gastos_resumen`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `gastos_resumen` ( - `Id_Gasto` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `year` int(4) NOT NULL, - `month` int(2) NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - `empresa_id` int(11) NOT NULL, - PRIMARY KEY (`Id_Gasto`,`year`,`month`,`empresa_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Sirve para resumir los gastos que se ponen a mano en el contaplus'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `gestdoc` --- - -DROP TABLE IF EXISTS `gestdoc`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `gestdoc` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `gesttip_id` int(11) NOT NULL DEFAULT '1', - `sref` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `brief` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL, - `emp_id` smallint(5) unsigned NOT NULL DEFAULT '791', - `orden` mediumint(8) unsigned DEFAULT NULL, - `file` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, - `original` tinyint(4) NOT NULL DEFAULT '0', - `trabajador_id` int(11) NOT NULL, - `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `gestdoccol` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `warehouse_id` smallint(5) unsigned NOT NULL DEFAULT '1', - PRIMARY KEY (`id`), - UNIQUE KEY `emp_id` (`emp_id`,`orden`,`warehouse_id`), - KEY `trabajador_id` (`trabajador_id`), - KEY `warehouse_id` (`warehouse_id`) -) ENGINE=InnoDB AUTO_INCREMENT=853237 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`gestdoc_bi` -BEFORE INSERT ON `vn2008`.`gestdoc` -FOR EACH ROW -BEGIN - - DECLARE intORD int; - IF NEW.warehouse_id = 44 THEN - SET NEW.warehouse_id = 1; - END IF; - IF NEW.original THEN - SELECT 1 + MAX(orden) INTO intORD FROM gestdoc WHERE emp_id = NEW.emp_id AND warehouse_id = NEW.warehouse_id ; - - SET NEW.orden = IFNULL(intORD,1) ; - END IF; --- Marca Firmado a uno cada vez que se escanea un Ticket de forma que desaparezca del TNAC JGF 27/08/13 - IF NEW.gesttip_id = 14 THEN - UPDATE Tickets SET Firmado = 1 WHERE Id_Ticket = NEW.sref; - END IF; - END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`gestdoc_bu` -BEFORE UPDATE ON `vn2008`.`gestdoc` -FOR EACH ROW -BEGIN - - DECLARE intORD int; - IF (NEW.original <> 0) AND (OLD.original = 0) AND (NEW.orden IS NULL) THEN - - SELECT 1 + MAX(orden) INTO intORD FROM gestdoc WHERE emp_id = NEW.emp_id AND warehouse_id = NEW.warehouse_id; - SET NEW.orden = IFNULL(intORD,1); - - END IF; -IF ((NEW.orden = 0) OR NEW.orden IS NULL) AND (OLD.orden <> 0) THEN - - SET NEW.original = 0; - END IF; - END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `gesttip` --- - -DROP TABLE IF EXISTS `gesttip`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `gesttip` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `tipo` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `path` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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=utf8 COLLATE=utf8_unicode_ci; -/*!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=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `integra2` --- - -DROP TABLE IF EXISTS `integra2`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `integra2` ( - `postal_code` mediumint(8) unsigned NOT NULL, - `frequency` tinyint(3) unsigned NOT NULL, - `warehouse_id` smallint(5) unsigned NOT NULL, - PRIMARY KEY (`postal_code`,`frequency`,`warehouse_id`), - KEY `postal_code` (`postal_code`), - KEY `warehouse_id` (`warehouse_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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 `province` (`province_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `warehouse_escala` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `integra2_province` --- - -DROP TABLE IF EXISTS `integra2_province`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `integra2_province` ( - `province_id` smallint(6) unsigned NOT NULL, - `franquicia` varchar(65) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`province_id`), - CONSTRAINT `integra2_province_id` FOREIGN KEY (`province_id`) REFERENCES `province` (`province_id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `intervalos` --- - -DROP TABLE IF EXISTS `intervalos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `intervalos` ( - `id` int(11) NOT NULL, - `hour` time NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `intrastat_data` --- - -DROP TABLE IF EXISTS `intrastat_data`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `intrastat_data` ( - `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `recibida_id` mediumint(8) unsigned NOT NULL, - `neto` decimal(10,2) DEFAULT NULL, - `intrastat_id` int(8) unsigned zerofill NOT NULL DEFAULT '06049190', - `importe` double NOT NULL, - `unidades` int(11) NOT NULL, - `Paises_Id` mediumint(8) unsigned DEFAULT NULL, - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `valorestadistico` double NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - KEY `intrastat_id` (`intrastat_id`), - KEY `recibida` (`recibida_id`), - CONSTRAINT `intrastat_data_ibfk_1` FOREIGN KEY (`intrastat_id`) REFERENCES `Intrastat` (`Codintrastat`) ON UPDATE CASCADE, - CONSTRAINT `intrastat_data_ibfk_2` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=62709 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `invoiceCorrection` --- - -DROP TABLE IF EXISTS `invoiceCorrection`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `invoiceCorrection` ( - `correctingFk` int(10) unsigned NOT NULL COMMENT 'Factura rectificativa', - `correctedFk` int(10) unsigned NOT NULL COMMENT 'Factura rectificada', - `cplusRectificationTypeFk` int(10) unsigned NOT NULL, - `cplusInvoiceType477Fk` int(10) unsigned NOT NULL, - `invoiceCorrectionTypeFk` int(11) NOT NULL DEFAULT '3', - PRIMARY KEY (`correctingFk`), - KEY `correctedFk_idx` (`correctedFk`), - KEY `invoiceCorrection_ibfk_1_idx` (`cplusRectificationTypeFk`), - KEY `cplusInvoiceTyoeFk_idx` (`cplusInvoiceType477Fk`), - KEY `invoiceCorrectionTypeFk_idx` (`invoiceCorrectionTypeFk`), - CONSTRAINT `corrected_fk` FOREIGN KEY (`correctedFk`) REFERENCES `Facturas` (`factura_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `correcting_fk` FOREIGN KEY (`correctingFk`) REFERENCES `Facturas` (`factura_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `cplusInvoiceTyoeFk` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `vn`.`cplusInvoiceType477` (`id`) ON UPDATE CASCADE, - CONSTRAINT `invoiceCorrectionType_Fk33` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `vn`.`invoiceCorrectionType` (`id`) ON UPDATE CASCADE, - CONSTRAINT `invoiceCorrection_ibfk_1` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `vn`.`cplusRectificationType` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Relacion entre las facturas rectificativas y las rectificadas.'; -/*!40101 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) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '0', - `text` text COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`invoice_observation_id`) -) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `itemTag` --- - -DROP TABLE IF EXISTS `itemTag`; -/*!50001 DROP VIEW IF EXISTS `itemTag`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `itemTag` AS SELECT - 1 AS `id`, - 1 AS `itemFk`, - 1 AS `tagFk`, - 1 AS `value`, - 1 AS `priority`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `itemTagArranged` --- - -DROP TABLE IF EXISTS `itemTagArranged`; -/*!50001 DROP VIEW IF EXISTS `itemTagArranged`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `itemTagArranged` AS SELECT - 1 AS `itemFk`, - 1 AS `tag1`, - 1 AS `val1`, - 1 AS `tag2`, - 1 AS `val2`, - 1 AS `tag3`, - 1 AS `val3`, - 1 AS `tag4`, - 1 AS `val4`, - 1 AS `tag5`, - 1 AS `val5`, - 1 AS `tag6`, - 1 AS `val6`, - 1 AS `description`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `item_catalog` --- - -DROP TABLE IF EXISTS `item_catalog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `item_catalog` ( - `item_id` int(11) unsigned NOT NULL, - `available` mediumint(9) NOT NULL, - `fixed` tinyint(1) NOT NULL DEFAULT '0', - `price` double DEFAULT NULL, - `s1` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `s2` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `discount` tinyint(3) unsigned, - `grouping` decimal(10,0) DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `item_entry_in` --- - -DROP TABLE IF EXISTS `item_entry_in`; -/*!50001 DROP VIEW IF EXISTS `item_entry_in`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `item_entry_in` AS SELECT - 1 AS `warehouse_id`, - 1 AS `dat`, - 1 AS `item_id`, - 1 AS `amount`, - 1 AS `received`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `item_entry_out` --- - -DROP TABLE IF EXISTS `item_entry_out`; -/*!50001 DROP VIEW IF EXISTS `item_entry_out`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `item_entry_out` AS SELECT - 1 AS `warehouse_id`, - 1 AS `dat`, - 1 AS `item_id`, - 1 AS `amount`, - 1 AS `delivered`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `item_entry_outkk` --- - -DROP TABLE IF EXISTS `item_entry_outkk`; -/*!50001 DROP VIEW IF EXISTS `item_entry_outkk`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `item_entry_outkk` AS SELECT - 1 AS `warehouse_id`, - 1 AS `dat`, - 1 AS `item_id`, - 1 AS `amount`, - 1 AS `delivered`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `item_out` --- - -DROP TABLE IF EXISTS `item_out`; -/*!50001 DROP VIEW IF EXISTS `item_out`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `item_out` AS SELECT - 1 AS `warehouse_id`, - 1 AS `dat`, - 1 AS `item_id`, - 1 AS `amount`, - 1 AS `ok`, - 1 AS `Reservado`, - 1 AS `ready`, - 1 AS `invoice`, - 1 AS `alertLevel`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `iva_codigo` --- - -DROP TABLE IF EXISTS `iva_codigo`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `iva_codigo` ( - `id` tinyint(2) unsigned NOT NULL AUTO_INCREMENT, - `fecha` date NOT NULL, - `codigo` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `iva_tipo_id` tinyint(2) NOT NULL, - `iva` decimal(4,1) NOT NULL DEFAULT '0.0', - `recargo` decimal(4,1) NOT NULL DEFAULT '0.0', - `tipo` char(1) COLLATE utf8_unicode_ci NOT NULL, - `link` tinyint(4) unsigned NOT NULL DEFAULT '0' COMMENT 'las que tienen el mismo valor se contabilizan emparejadas', - `isActive` tinyint(2) NOT NULL DEFAULT '1', - `updated` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `transactionCode` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `iva_tipo_id` (`iva_tipo_id`), - KEY `codigo` (`codigo`), - KEY `tipo_index` (`tipo`), - CONSTRAINT `iva_codigo_ibfk_1` FOREIGN KEY (`iva_tipo_id`) REFERENCES `iva_tipo` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=121 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `iva_group` --- - -DROP TABLE IF EXISTS `iva_group`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `iva_group` ( - `iva_group_id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `description` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `code` varchar(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'R', - PRIMARY KEY (`iva_group_id`) -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `iva_group_codigo` --- - -DROP TABLE IF EXISTS `iva_group_codigo`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `iva_group_codigo` ( - `iva_group_id` tinyint(3) unsigned NOT NULL, - `date` date NOT NULL, - `iva_codigo_id` tinyint(3) unsigned NOT NULL, - PRIMARY KEY (`iva_group_id`,`date`,`iva_codigo_id`), - KEY `iva_codigo_id` (`iva_codigo_id`), - CONSTRAINT `iva_group_codigo_ibfk_1` FOREIGN KEY (`iva_group_id`) REFERENCES `iva_group` (`iva_group_id`) ON UPDATE CASCADE, - CONSTRAINT `iva_group_codigo_ibfk_2` FOREIGN KEY (`iva_codigo_id`) REFERENCES `iva_codigo` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `iva_tipo` --- - -DROP TABLE IF EXISTS `iva_tipo`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `iva_tipo` ( - `id` tinyint(2) NOT NULL AUTO_INCREMENT, - `alias` varchar(6) COLLATE utf8_unicode_ci NOT NULL, - `isAccrued` tinyint(4) NOT NULL DEFAULT '0', - `serie_id` char(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `TIPOOPE` varchar(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT ' ', - `descripcion` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - `Id_Pais` mediumint(8) unsigned NOT NULL, - PRIMARY KEY (`id`), - KEY `serie_id` (`serie_id`), - KEY `Id_Pais` (`Id_Pais`), - CONSTRAINT `iva_tipo_ibfk_1` FOREIGN KEY (`Id_Pais`) REFERENCES `Paises` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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(11) NOT NULL, - `boss_id` int(11) NOT NULL, - `vinculado` tinyint(3) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`worker_id`,`boss_id`), - KEY `worker_trabajador` (`worker_id`), - KEY `boss_trabajador` (`boss_id`), - CONSTRAINT `boss_trabajador` FOREIGN KEY (`boss_id`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE, - CONSTRAINT `worker_trabajador` FOREIGN KEY (`worker_id`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `killme` --- - -DROP TABLE IF EXISTS `killme`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `killme` ( - `Id_Article` int(11) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci NOT NULL, - `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `active` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`code`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `log_articles` --- - -DROP TABLE IF EXISTS `log_articles`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `log_articles` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `Id_Article` int(11) NOT NULL, - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `Fecha_old` datetime DEFAULT NULL, - `cantidad_old` double DEFAULT NULL, - `Id_Ticket_old` int(11) DEFAULT NULL, - `wh_old` smallint(6) unsigned DEFAULT NULL, - `Fecha_new` datetime DEFAULT NULL, - `cantidad_new` double DEFAULT NULL, - `Id_Ticket_new` int(11) DEFAULT NULL, - `wh_new` smallint(6) DEFAULT NULL, - `accion` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `Id_Article_log` (`Id_Article`), - KEY `Id_Ticket_log` (`Id_Ticket_old`), - KEY `Id_Ticket_new_log` (`Id_Ticket_new`), - CONSTRAINT `Id_Article_log_Articles` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE NO ACTION ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los movimientos de los articulos para intentar encontrar los procesos que generan negativos'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `mail` --- - -DROP TABLE IF EXISTS `mail`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mail` ( - `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `to` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `reply_to` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `subject` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `text` text COLLATE utf8_unicode_ci NOT NULL, - `sent` tinyint(2) NOT NULL DEFAULT '0', - `DATE_ODBC` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `path` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - `error` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'OK', - `senderFk` int(11) DEFAULT NULL, - `recipientFk` int(11) DEFAULT NULL, - `plainTextBody` text COLLATE utf8_unicode_ci, - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=1268459 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `mail_templates` --- - -DROP TABLE IF EXISTS `mail_templates`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mail_templates` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `countryCode` char(2) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'ES', - `name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, - `subject` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `body` text COLLATE utf8_unicode_ci NOT NULL, - `attachment` text COLLATE utf8_unicode_ci, - PRIMARY KEY (`id`,`countryCode`,`name`) -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `mandato` --- - -DROP TABLE IF EXISTS `mandato`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mandato` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `Id_Cliente` int(11) NOT NULL, - `empresa_id` smallint(5) unsigned NOT NULL, - `Id_mandato` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL, - `FAlta` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `Fbaja` timestamp NULL DEFAULT NULL, - `idmandato_tipo` smallint(5) NOT NULL, - PRIMARY KEY (`id`), - KEY `mandato_fgkey1_idx` (`Id_Cliente`), - KEY `mandato_fgkey2_idx` (`empresa_id`), - KEY `mandato_fgkey3_idx` (`idmandato_tipo`), - CONSTRAINT `mandato_fgkey1` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `mandato_fgkey2` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `mandato_fgkey3` FOREIGN KEY (`idmandato_tipo`) REFERENCES `mandato_tipo` (`idmandato_tipo`) ON DELETE NO ACTION ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=14523 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 trigger mandato_ins before insert -on mandato -for each row -begin - if (NEW.Id_mandato IS NULL) THEN - SET NEW.Id_mandato=CONCAT(NEW.Id_Cliente,'-',(SELECT AUTO_INCREMENT - from information_schema.TABLES - where TABLE_SCHEMA='vn2008' and TABLE_NAME='mandato')); - end if; -end */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `mandato_tipo` --- - -DROP TABLE IF EXISTS `mandato_tipo`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mandato_tipo` ( - `idmandato_tipo` smallint(5) NOT NULL AUTO_INCREMENT, - `Nombre` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`idmandato_tipo`) -) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `movement_label` --- - -DROP TABLE IF EXISTS `movement_label`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `movement_label` ( - `Id_movimiento` int(11) NOT NULL, - `label` mediumint(8) unsigned NOT NULL, - `stem` mediumint(8) unsigned NOT NULL, - PRIMARY KEY (`Id_movimiento`), - CONSTRAINT `movement_label_ibfk_1` FOREIGN KEY (`Id_movimiento`) REFERENCES `Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `movement_label_au` AFTER UPDATE ON `movement_label` FOR EACH ROW --- Edit trigger body code below this line. Do not edit lines above this one -IF NEW.stem >= (SELECT Cantidad FROM Movimientos WHERE Id_Movimiento = NEW.Id_Movimiento) THEN - UPDATE Movimientos SET OK = 1 WHERE Id_Movimiento = NEW.Id_Movimiento; -END IF */;; -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 */ ; - --- --- Temporary view structure for view `new_viewkk` --- - -DROP TABLE IF EXISTS `new_viewkk`; -/*!50001 DROP VIEW IF EXISTS `new_viewkk`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `new_viewkk` AS SELECT - 1 AS `id`, - 1 AS `worker`, - 1 AS `document`*/; -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) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `observation_type` --- - -DROP TABLE IF EXISTS `observation_type`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `observation_type` ( - `observation_type_id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `description` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`observation_type_id`) -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `order` --- - -DROP TABLE IF EXISTS `order`; -/*!50001 DROP VIEW IF EXISTS `order`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `order` AS SELECT - 1 AS `id`, - 1 AS `date_make`, - 1 AS `date_send`, - 1 AS `customer_id`, - 1 AS `delivery_method_id`, - 1 AS `agency_id`, - 1 AS `address_id`, - 1 AS `note`, - 1 AS `confirmed`, - 1 AS `is_bionic`, - 1 AS `source_app`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `order_Tickets` --- - -DROP TABLE IF EXISTS `order_Tickets`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `order_Tickets` ( - `order_id` int(10) unsigned NOT NULL, - `Id_Ticket` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`Id_Ticket`,`order_id`), - KEY `order_id` (`order_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `order_component` --- - -DROP TABLE IF EXISTS `order_component`; -/*!50001 DROP VIEW IF EXISTS `order_component`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `order_component` AS SELECT - 1 AS `order_row_id`, - 1 AS `component_id`, - 1 AS `price`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `order_row` --- - -DROP TABLE IF EXISTS `order_row`; -/*!50001 DROP VIEW IF EXISTS `order_row`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `order_row` AS SELECT - 1 AS `id`, - 1 AS `order_id`, - 1 AS `item_id`, - 1 AS `warehouse_id`, - 1 AS `shipment`, - 1 AS `amount`, - 1 AS `price`, - 1 AS `rate`, - 1 AS `created`, - 1 AS `Id_Movimiento`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `pago` --- - -DROP TABLE IF EXISTS `pago`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `pago` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `fecha` date NOT NULL, - `id_proveedor` int(11) NOT NULL, - `importe` decimal(10,2) NOT NULL DEFAULT '0.00', - `id_moneda` tinyint(3) unsigned NOT NULL DEFAULT '1', - `divisa` decimal(10,2) DEFAULT NULL, - `id_banco` int(11) NOT NULL DEFAULT '0', - `pay_met_id` tinyint(3) unsigned NOT NULL, - `g_bancarios` double(6,2) unsigned NOT NULL DEFAULT '0.00', - `concepte` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `conciliado` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0', - `pago_sdc_id` int(11) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `empresa_id` (`empresa_id`), - KEY `id_banco` (`id_banco`), - KEY `id_moneda` (`id_moneda`), - KEY `pay_met` (`pay_met_id`), - KEY `proveedor_pago` (`id_proveedor`), - KEY `fk_pago_pago_sdc1_idx` (`pago_sdc_id`), - CONSTRAINT `pago_ibfk_1` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE, - CONSTRAINT `pago_ibfk_2` FOREIGN KEY (`id_banco`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE, - CONSTRAINT `pago_moneda` FOREIGN KEY (`id_moneda`) REFERENCES `Monedas` (`Id_Moneda`) ON UPDATE CASCADE, - CONSTRAINT `pago_pay_met` FOREIGN KEY (`pay_met_id`) REFERENCES `pay_met` (`id`) ON UPDATE CASCADE, - CONSTRAINT `proveedor_pago` FOREIGN KEY (`id_proveedor`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=39712 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pago_bi` BEFORE INSERT ON `pago` FOR EACH ROW --- Edit trigger body code below this line. Do not edit lines above this one -BEGIN - DECLARE cuenta_banco,cuenta_proveedor DOUBLE; - DECLARE max_asien INT; - DECLARE bolCASH BOOLEAN; - - - - -- PAK 10/02/15 No se asientan los pagos directamente, salvo en el caso de las cajas de CASH - SELECT (cash = 1) INTO bolCASH FROM Bancos WHERE Bancos.Id_Banco = NEW.id_banco ; - - IF bolCASH THEN -- AND NEW.id_pago <> 1 - - SELECT Cuenta INTO cuenta_banco FROM Bancos WHERE Id_Banco = NEW.id_banco; - SELECT Cuenta INTO cuenta_proveedor FROM Proveedores WHERE Id_Proveedor=NEW.id_proveedor; - SELECT MAX(asien)+1 INTO max_asien FROM XDiario; - - INSERT INTO XDiario (ASIEN,FECHA,SUBCTA,CONTRA,CONCEPTO,EURODEBE,EUROHABER,empresa_id) - SELECT max_asien,NEW.fecha,SUBCTA,CONTRA,NEW.concepte,EURODEBE,EUROHABER,NEW.empresa_id FROM - ( SELECT cuenta_banco SUBCTA,cuenta_proveedor CONTRA, - 0 EURODEBE, NEW.importe + NEW.g_bancarios EUROHABER - UNION ALL - SELECT cuenta_proveedor SUBCTA, cuenta_banco CONTRA, - NEW.importe EURODEBE, 0 EUROHABER) gf; - - IF NEW.g_bancarios <> 0 THEN - INSERT INTO XDiario (ASIEN,FECHA,SUBCTA,CONTRA,CONCEPTO,EURODEBE,EUROHABER,empresa_id) - SELECT max_asien,NEW.fecha,IF(Id = 1,6260000002,IF(CEE = 1,6260000003,6260000004)),cuenta_banco,NEW.concepte, - NEW.g_bancarios,0,NEW.empresa_id FROM Proveedores pr - JOIN Paises pa ON pr.pais_id = pa.Id WHERE Id_Proveedor = NEW.id_proveedor; - END IF; - - - END IF; - END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `pago_sdc` --- - -DROP TABLE IF EXISTS `pago_sdc`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `pago_sdc` ( - `pago_sdc_id` int(11) NOT NULL AUTO_INCREMENT, - `importe` decimal(10,2) NOT NULL, - `fecha` date NOT NULL, - `vencimiento` date NOT NULL, - `entity_id` int(10) unsigned NOT NULL, - `ref` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `rate` decimal(10,4) NOT NULL, - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - `financialProductTypefk` varchar(2) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'SC', - `pago_sdccol` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `upperBarrier` decimal(10,2) DEFAULT NULL, - `lowerBarrier` decimal(10,2) DEFAULT NULL, - `strike` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`pago_sdc_id`), - KEY `empresa_sdc_idx` (`empresa_id`), - KEY `financial_type_fk_idx` (`financialProductTypefk`), - KEY `pago_sdc_entity_fk_idx` (`entity_id`), - CONSTRAINT `empresa_sdc` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE, - CONSTRAINT `financial_type_fk` FOREIGN KEY (`financialProductTypefk`) REFERENCES `financialProductType` (`id`) ON UPDATE CASCADE, - CONSTRAINT `pago_sdc_entity_fk` FOREIGN KEY (`entity_id`) REFERENCES `entity` (`entity_id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Seguros de cambio'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `pay_dem` --- - -DROP TABLE IF EXISTS `pay_dem`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `pay_dem` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `pay_dem` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `pay_dem_det` --- - -DROP TABLE IF EXISTS `pay_dem_det`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `pay_dem_det` ( - `id` tinyint(3) unsigned NOT NULL, - `detalle` tinyint(3) unsigned NOT NULL, - PRIMARY KEY (`id`,`detalle`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `pay_met` --- - -DROP TABLE IF EXISTS `pay_met`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `pay_met` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `solucion` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `deudaviva` tinyint(3) unsigned zerofill NOT NULL DEFAULT '000', - `graceDays` int(11) unsigned NOT NULL DEFAULT '0', - `ibanRequired` tinyint(3) DEFAULT '0', - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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 `payroll_centros` (`empresa_id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payroll_categorias` --- - -DROP TABLE IF EXISTS `payroll_categorias`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payroll_categorias` ( - `codcategoria` int(11) NOT NULL, - `descripcion` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `Tarifa` tinyint(4) NOT NULL, - PRIMARY KEY (`codcategoria`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payroll_centros` --- - -DROP TABLE IF EXISTS `payroll_centros`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payroll_centros` ( - `cod_centro` int(11) NOT NULL, - `Centro` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `nss_cotizacion` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - `domicilio` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `poblacion` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `cp` varchar(5) COLLATE utf8_unicode_ci NOT NULL, - `empresa_id` int(10) NOT NULL, - `codempresa` int(11) DEFAULT NULL, - PRIMARY KEY (`cod_centro`,`empresa_id`), - KEY `payroll_centros_ix1` (`empresa_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payroll_conceptos` --- - -DROP TABLE IF EXISTS `payroll_conceptos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payroll_conceptos` ( - `conceptoid` int(11) NOT NULL, - `concepto` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`conceptoid`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payroll_contratos` --- - -DROP TABLE IF EXISTS `payroll_contratos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payroll_contratos` ( - `CodContrato` int(11) NOT NULL, - `TipoCotizacion` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `DescContrato` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`CodContrato`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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 `payroll_conceptos` (`conceptoid`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payroll_employee` --- - -DROP TABLE IF EXISTS `payroll_employee`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payroll_employee` ( - `CodTrabajador` int(11) NOT NULL, - `Person_id` int(11) NOT NULL, - `nss` varchar(23) COLLATE utf8_unicode_ci NOT NULL, - `codpuesto` int(10) NOT NULL, - `codempresa` int(10) NOT NULL, - `codcontrato` int(10) NOT NULL, - `FAntiguedad` date NOT NULL, - `grupotarifa` int(10) NOT NULL, - `codcategoria` int(10) NOT NULL, - `ContratoTemporal` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`CodTrabajador`,`codempresa`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payroll_pagarini` --- - -DROP TABLE IF EXISTS `payroll_pagarini`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payroll_pagarini` ( - `fecha` date NOT NULL, - `person_id` int(11) NOT NULL, - `saldotpv` double NOT NULL DEFAULT '0', - `saldolab` double NOT NULL DEFAULT '0', - `saldoprod` double NOT NULL DEFAULT '0', - `saldobruto` double NOT NULL DEFAULT '0', - `business_id` int(11) NOT NULL, - `exportado` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`fecha`,`person_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payroll_pais` --- - -DROP TABLE IF EXISTS `payroll_pais`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payroll_pais` ( - `codpais` int(11) NOT NULL, - `pais` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`codpais`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id_payroll_tipobasess`) -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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 AUTO_INCREMENT=1654 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `person_user` --- - -DROP TABLE IF EXISTS `person_user`; -/*!50001 DROP VIEW IF EXISTS `person_user`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `person_user` AS SELECT - 1 AS `id`, - 1 AS `mysql_user_id`, - 1 AS `name`, - 1 AS `password`, - 1 AS `active`, - 1 AS `last_pass_change`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `person_user_idtrabajador` --- - -DROP TABLE IF EXISTS `person_user_idtrabajador`; -/*!50001 DROP VIEW IF EXISTS `person_user_idtrabajador`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `person_user_idtrabajador` AS SELECT - 1 AS `Id_Trabajador`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `plantpassport` --- - -DROP TABLE IF EXISTS `plantpassport`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `plantpassport` ( - `producer_id` mediumint(3) unsigned NOT NULL, - `plantpassport_authority_id` mediumint(3) unsigned NOT NULL, - `number` varchar(25) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`producer_id`,`plantpassport_authority_id`), - KEY `plantpassport_authority_idx` (`plantpassport_authority_id`), - KEY `producer_id_idx` (`producer_id`), - CONSTRAINT `plantpassport_authority` FOREIGN KEY (`plantpassport_authority_id`) REFERENCES `plantpassport_authority` (`plantpassport_authority_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `producer` FOREIGN KEY (`producer_id`) REFERENCES `producer` (`producer_id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='tiene la asignacion de cada productor con la autoridad certificadora'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `plantpassport_authority` --- - -DROP TABLE IF EXISTS `plantpassport_authority`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `plantpassport_authority` ( - `plantpassport_authority_id` mediumint(3) unsigned NOT NULL, - `denomination` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `Paises_Id` mediumint(8) unsigned DEFAULT NULL, - PRIMARY KEY (`plantpassport_authority_id`), - UNIQUE KEY `denomination_UNIQUE` (`denomination`), - KEY `Pais_id_idx` (`Paises_Id`), - CONSTRAINT `Pais_id` FOREIGN KEY (`Paises_Id`) REFERENCES `Paises` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='entidades certificadoras'; -/*!40101 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=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `preparation_percentage` --- - -DROP TABLE IF EXISTS `preparation_percentage`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `preparation_percentage` ( - `week_day` tinyint(1) unsigned NOT NULL COMMENT 'preparation day. Funcion de mysql Lunes = 0, Domingo = 6', - `warehouse_id` smallint(6) unsigned DEFAULT NULL, - `percentage` tinyint(2) NOT NULL DEFAULT '0', - UNIQUE KEY `week_day_UNIQUE` (`week_day`), - UNIQUE KEY `warehouse_id_UNIQUE` (`warehouse_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `price_fixed` --- - -DROP TABLE IF EXISTS `price_fixed`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `price_fixed` ( - `item_id` int(10) NOT NULL, - `rate_0` double NOT NULL, - `rate_1` double NOT NULL, - `rate_2` double NOT NULL, - `rate_3` double NOT NULL, - `date_start` date NOT NULL, - `date_end` date NOT NULL, - `bonus` double NOT NULL DEFAULT '0', - `warehouse_id` smallint(5) unsigned NOT NULL DEFAULT '0', - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `price_fixed_id` int(11) NOT NULL AUTO_INCREMENT, - `grouping` smallint(5) DEFAULT NULL, - `Packing` int(11) DEFAULT NULL, - `caja` tinyint(4) DEFAULT NULL, - PRIMARY KEY (`item_id`,`date_start`,`date_end`,`warehouse_id`), - UNIQUE KEY `price_fixed_id_UNIQUE` (`price_fixed_id`), - KEY `item_id` (`item_id`), - KEY `date_start` (`date_start`), - KEY `date_end` (`date_end`), - KEY `warehouse_id` (`warehouse_id`), - CONSTRAINT `price_fixed_ibfk_1` FOREIGN KEY (`item_id`) REFERENCES `Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=51998 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`price_fixed_bi` BEFORE INSERT ON `vn2008`.`price_fixed` - FOR EACH ROW BEGIN - DECLARE v_aux DATE; - IF NEW.date_start > NEW.date_end THEN - SET v_aux = NEW.date_start; - SET NEW.date_start = NEW.date_end; - SET NEW.date_end = v_aux; - END IF; - END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`price_fixed_bu` BEFORE UPDATE ON `vn2008`.`price_fixed` - FOR EACH ROW BEGIN - DECLARE v_aux DATE; - IF NEW.date_start > NEW.date_end THEN - SET v_aux = NEW.date_start; - SET NEW.date_start = NEW.date_end; - SET NEW.date_end = v_aux; - END IF; - END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `producer` --- - -DROP TABLE IF EXISTS `producer`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `producer` ( - `producer_id` mediumint(3) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `visible` tinyint(1) NOT NULL DEFAULT '1', - PRIMARY KEY (`producer_id`), - UNIQUE KEY `name_UNIQUE` (`name`) -) ENGINE=InnoDB AUTO_INCREMENT=3860 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `profile_labour_payroll` --- - -DROP TABLE IF EXISTS `profile_labour_payroll`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `profile_labour_payroll` ( - `profile_id` int(11) NOT NULL, - `codpais` int(11) NOT NULL, - `nivelformativo` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `NSSProvincia` tinyint(2) unsigned zerofill NOT NULL, - `NssNumero` varchar(8) COLLATE utf8_unicode_ci NOT NULL, - `NssDC` char(2) COLLATE utf8_unicode_ci NOT NULL, - `sexo` enum('H','M') COLLATE utf8_unicode_ci NOT NULL, - `estadocivil` enum('S','C') COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`profile_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `proveedores_clientes` --- - -DROP TABLE IF EXISTS `proveedores_clientes`; -/*!50001 DROP VIEW IF EXISTS `proveedores_clientes`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `proveedores_clientes` AS SELECT - 1 AS `Id_Proveedor`, - 1 AS `Proveedor`, - 1 AS `Id_Cliente`, - 1 AS `Cliente`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `provider_account_customer` --- - -DROP TABLE IF EXISTS `provider_account_customer`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `provider_account_customer` ( - `account_id` mediumint(8) unsigned NOT NULL, - PRIMARY KEY (`account_id`), - CONSTRAINT `provider_account_customer_ibfk_1` FOREIGN KEY (`account_id`) REFERENCES `Proveedores_account` (`Id_Proveedores_account`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Bank accounts used for customer transfers'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `province` --- - -DROP TABLE IF EXISTS `province`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `province` ( - `province_id` smallint(6) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `Paises_Id` mediumint(8) unsigned NOT NULL, - `warehouse_id` smallint(6) unsigned DEFAULT NULL COMMENT 'warehouse responsable de las rutas', - `zone` tinyint(4) DEFAULT NULL, - `nst_geo_id` int(11) DEFAULT NULL, - `nst_name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `geoFk` int(11) DEFAULT NULL, - PRIMARY KEY (`province_id`), - KEY `Paises_Id` (`Paises_Id`), - KEY `warehouse_Id` (`warehouse_id`), - KEY `provicne_zone_fk_idx` (`zone`), - CONSTRAINT `province_ibfk_1` FOREIGN KEY (`Paises_Id`) REFERENCES `Paises` (`Id`) ON UPDATE CASCADE, - CONSTRAINT `province_zone_fk` FOREIGN KEY (`zone`) REFERENCES `zones` (`zone_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `warehouse_Id` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE SET NULL ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=192 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`provinceBeforeInsert` - BEFORE INSERT ON `province` FOR EACH ROW -BEGIN - IF NEW.`name` = '' THEN - CALL util.throw ('EMPTY_NAME'); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`provinceBeforeUpdate` - BEFORE UPDATE ON `province` FOR EACH ROW -BEGIN - IF NEW.`name` = '' THEN - CALL util.throw ('EMPTY_NAME'); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `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) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`Id_Article`,`denominacion`), - KEY `id_article_rec_idx` (`Id_Article`), - CONSTRAINT `id_article_rec` FOREIGN KEY (`Id_Article`) REFERENCES `Articles` (`Id_Article`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Equipara las denominaciones de las fincas de ecuador con nuestro Id_Article'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `recibida` --- - -DROP TABLE IF EXISTS `recibida`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `recibida` ( - `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `num_recibida` mediumint(11) unsigned DEFAULT NULL COMMENT 'insertado por Trigger', - `serie` char(1) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'R', - `proveedor_id` int(11) NOT NULL, - `fecha` date NOT NULL COMMENT 'Fecha de emision de la factura', - `sref` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0', - `contabilizada` tinyint(1) NOT NULL DEFAULT '0', - `moneda_id` tinyint(3) unsigned NOT NULL DEFAULT '1', - `MYSQL_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - `gestdoc_id` int(11) DEFAULT NULL, - `dateBooking` date DEFAULT NULL COMMENT 'Fecha de contabilizacion', - `dateOperation` date DEFAULT NULL COMMENT 'Fecha de entrega de la mercancia o el suministro', - `cplusInvoiceType472Fk` int(10) unsigned DEFAULT '1', - `cplusRectificationTypeFk` int(10) unsigned DEFAULT '1', - `cplusSubjectOpFk` int(10) unsigned DEFAULT '1', - `cplusTaxBreakFk` int(10) unsigned DEFAULT '1', - `cplusTrascendency472Fk` int(10) unsigned DEFAULT '1', - `bookEntried` date DEFAULT NULL, - `isVatDeductible` tinyint(1) NOT NULL DEFAULT '1', - PRIMARY KEY (`id`), - KEY `proveedor_id` (`proveedor_id`), - KEY `empresa_id` (`empresa_id`), - KEY `serie` (`serie`), - KEY `num_recibida_2` (`num_recibida`), - KEY `gestdoc_id` (`gestdoc_id`), - KEY `fecha` (`fecha`), - KEY `recibida_ibfk_3_idx` (`cplusSubjectOpFk`), - KEY `recibida_ibfk_4_idx` (`cplusTaxBreakFk`), - KEY `recibida_ibfk_5_idx` (`cplusInvoiceType472Fk`), - KEY `recibida_ibfk_6` (`cplusRectificationTypeFk`), - KEY `recibida_ibfk_7` (`cplusTrascendency472Fk`), - CONSTRAINT `recibida_ibfk_1` FOREIGN KEY (`proveedor_id`) REFERENCES `Proveedores` (`Id_Proveedor`) ON UPDATE CASCADE, - CONSTRAINT `recibida_ibfk_2` FOREIGN KEY (`empresa_id`) REFERENCES `empresa` (`id`) ON UPDATE CASCADE, - CONSTRAINT `recibida_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `vn`.`cplusSubjectOp` (`id`) ON UPDATE CASCADE, - CONSTRAINT `recibida_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `vn`.`cplusTaxBreak` (`id`) ON UPDATE CASCADE, - CONSTRAINT `recibida_ibfk_5` FOREIGN KEY (`cplusInvoiceType472Fk`) REFERENCES `vn`.`cplusInvoiceType472` (`id`) ON UPDATE CASCADE, - CONSTRAINT `recibida_ibfk_6` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `vn`.`cplusRectificationType` (`id`) ON UPDATE CASCADE, - CONSTRAINT `recibida_ibfk_7` FOREIGN KEY (`cplusTrascendency472Fk`) REFERENCES `vn`.`cplusTrascendency472` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=64959 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`recibida_bi` -BEFORE INSERT ON `vn2008`.`recibida` -FOR EACH ROW -BEGIN - DECLARE v_serie CHAR(1) DEFAULT 'R'; - DECLARE v_num_recibida INT; - DECLARE pais_emisor, pais_receptor INT; - DECLARE vActive TINYINT; - - - SELECT pais_id, active into pais_emisor, vActive FROM Proveedores WHERE Id_Proveedor = NEW.proveedor_id; - SELECT pais_id into pais_receptor FROM Proveedores WHERE Id_Proveedor = NEW.empresa_id; - - IF vActive = 0 THEN - CALL util.throw('INACTIVE_PROVIDER'); - END IF; - - SELECT CASE WHEN (SELECT Cuenta FROM Proveedores where Id_Proveedor = NEW.proveedor_id) LIKE '___3______' THEN 'C' - WHEN (SELECT pais_emisor=pais_receptor from Paises p1 join Paises p2 ON p2.Id = pais_receptor AND p1.Id = pais_emisor - where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'R' - WHEN (SELECT pais_emisor <> pais_receptor from Paises p1 join Paises p2 ON p2.Id = pais_receptor AND p1.Id = pais_emisor - where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'E' - WHEN (SELECT pais_emisor<>pais_receptor from Paises p1 join Paises p2 ON p2.Id = pais_receptor AND p1.Id = pais_emisor - where NOT p1.CEE < 2 AND not p1.Id = 1) = 1 THEN 'W' - END INTO v_serie; - - SET NEW.serie = v_serie; - - IF v_serie LIKE 'W' THEN - - SELECT IFNULL(MAX(num_recibida) + 1,1) INTO v_num_recibida FROM recibida - WHERE serie LIKE NEW.serie - AND YEAR(fecha) = YEAR(NEW.fecha) - AND empresa_id = NEW.empresa_id; - - SET NEW.num_recibida = v_num_recibida; - - END IF; - - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `recibida_bu` BEFORE UPDATE ON `recibida` FOR EACH ROW --- Edit trigger body code below this line. Do not edit lines above this one -BEGIN - - DECLARE cta_proveed VARCHAR(10); - DECLARE cta_proveeda VARCHAR(10); - DECLARE v_num_recibida INT; - DECLARE dblRefRate,dblRefMin,dblRef DOUBLE; - DECLARE vActive TINYINT; - - SELECT active INTO vActive FROM Proveedores WHERE Id_Proveedor = NEW.proveedor_id; - - IF vActive = 0 THEN - CALL util.throw('INACTIVE_PROVIDER'); - END IF; - - IF NEW.empresa_id <> OLD.empresa_id THEN - SET NEW.num_recibida = NULL; - SET NEW.contabilizada = FALSE ; - END IF; - - - -/* PAK 27/11/17 ESto tiene pinta de no hacer falta.... - -IF NEW.contabilizada = 1 AND OLD.contabilizada = 0 AND NEW.fecha < '2017-07-01' THEN - - SELECT rate INTO dblRefRate FROM reference_rate WHERE date = (SELECT MAX(date) FROM reference_rate - WHERE date <= (SELECT t.shipment FROM - recibida_entrada re - INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada - LEFT JOIN travel t ON t.id = e.travel_id - WHERE re.awb_recibida = NEW.id GROUP BY re.awb_recibida)); - - SELECT rate INTO dblRefMin FROM reference_min WHERE date=(SELECT MAX(date) FROM reference_min - WHERE date<=(SELECT t.shipment FROM - recibida_entrada re - INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada - LEFT JOIN travel t ON t.id = e.travel_id - WHERE re.awb_recibida = NEW.id GROUP BY re.awb_recibida)); - - -- IF dblRefMin < dblRefRate THEN - -- SET dblRef = dblRefRate; - -- ELSE - -- SET dblRef =dblRefMin; - -- END IF; - SELECT IFNULL(MAX(r.num_recibida) + 1,1) INTO v_num_recibida FROM recibida r - WHERE r.serie LIKE NEW.serie - AND YEAR(r.fecha) = YEAR(NEW.fecha) - AND r.empresa_id = NEW.empresa_id GROUP BY r.empresa_id; - - SET NEW.num_recibida = IFNULL(v_num_recibida,1); - SELECT REPLACE(cuenta,' ','') INTO cta_proveed FROM Proveedores WHERE Id_Proveedor=NEW.proveedor_id; - - INSERT INTO XDiario(ASIEN,FECHA,SUBCTA,CONTRA,CONCEPTO,EURODEBE, EUROHABER,BASEEURO, SERIE,FACTURA,IVA,DOCUMENTO, - L340,LRECT349,TIPOOPE,AUXILIAR,empresa_id,LDIFADUAN) -SELECT a,NEW.fecha,subcta,contra,concepto,eurodebe,eurohaber,baseeuro,serie,NEW.sref,iva, - (SELECT CONCAT(serie,'/', LPAD(v_num_recibida,5,'0'))),l340,LRECT349,TIPOOPE,AUXILIAR,NEW.empresa_id,LDIFADUAN - FROM - - (SELECT MAX(ASIEN) + 1 as a FROM XDiario) t - - INNER JOIN - - ( - - SELECT *,NEW.serie,0 LDIFADUAN FROM - - (SELECT CONCAT('s/fra',RIGHT(sref,8),':',LEFT(Proveedor, 10)) concepto FROM Proveedores - - INNER JOIN recibida ON Id_Proveedor = proveedor_id WHERE id = NEW.id) t4 - - INNER JOIN( - -- Linea del proveedor/acreedor - SELECT subcta,'' contra,eurodebe,ROUND(SUM(eurohaber) + 0.0001,2) eurohaber,baseeuro,0 iva, l340,LRECT349,TIPOOPE,'' AUXILIAR - - FROM ( - - SELECT cta_proveed subcta, - - NULL eurodebe, ROUND((1+(iva/100)*(r.serie = 'R'))*SUM(bi),2) eurohaber, NULL baseeuro,ri.recibida_id, 0 l340,0 LRECT349,' ' TIPOOPE - - FROM recibida r - - INNER JOIN recibida_iva ri ON ri.recibida_id = r.id INNER JOIN iva_codigo ic ON ri.iva_id = ic.id - - INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id - INNER JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id - - WHERE r.id = NEW.id GROUP BY iva) t - - GROUP BY recibida_id - - UNION ALL - -- Linea de iva - SELECT ic.codigo,cta_proveed contra, - - ROUND(iva/100*SUM(ri.bi) + 0.0001,2) eurodebe, NULL eurohaber, - - ROUND(SUM(ri.bi),2) baseeuro,iva, 1 l340,(NOT ((p.pais_id <> p2.pais_id) AND pa.CEE < 2)) LRECT349,TIPOOPE, - IF(pa.CEE < 2 AND ri2.gastos_id IS NULL,'','*') AUXILIAR - FROM recibida r - - INNER JOIN recibida_iva ri ON ri.recibida_id = r.id - - LEFT JOIN recibida_iva ri2 ON ri2.recibida_id = r.id AND ri2.gastos_id LIKE '4751______' - - INNER JOIN iva_codigo ic ON ri.iva_id = ic.id - - INNER JOIN iva_tipo it ON it.id = ic.iva_tipo_id - - INNER JOIN Gastos g ON ri.gastos_id = g.Id_Gasto AND g.iva_tipo_id = ic.iva_tipo_id - - INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id - - INNER JOIN Paises pa ON p.pais_id = pa.Id - - INNER JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id - - INNER JOIN Paises pa2 ON p2.pais_id = pa2.Id - WHERE r.id = NEW.id AND ic.tipo <> '-' AND link GROUP BY iva - -- JGF 2016-05-05 g.conbase - UNION ALL - -- Linea iva inversor sujeto pasivo - SELECT ic2.codigo,cta_proveed contra, - - NULL eurodebe, ROUND(ic2.iva/100*SUM(bi) + 0.0001,2) eurohaber, - - ROUND(SUM(bi),2) baseeuro,ic2.iva, 1 l340,0 LRECT349,TIPOOPE,'*' AUXILIAR - - FROM recibida r - - INNER JOIN recibida_iva ri ON ri.recibida_id = r.id - - INNER JOIN iva_codigo ic ON ri.iva_id = ic.id - - INNER JOIN iva_codigo ic2 ON ic2.link = ic.link AND ic.id <> ic2.id - - INNER JOIN iva_tipo it ON ic.iva_tipo_id = it.id - - WHERE r.id = NEW.id AND ic2.link GROUP BY ic2.iva - - UNION ALL - -- Linea de Gastos - SELECT if(gastos_id LIKE '4751______',LPAD(RIGHT(cta_proveed ,5),10,gastos_id),gastos_id),cta_proveed , - - if(gastos_id LIKE '4751______',NULL,ABS(ROUND(SUM(bi),2))) , - - if(gastos_id LIKE '4751______',ABS(ROUND(SUM(bi),2)),NULL) , - - NULL ,0, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR - - FROM recibida r - - INNER JOIN recibida_iva ri ON ri.recibida_id = r.id - - INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id - - WHERE r.id = NEW.id AND gastos_id <> 5660000002 GROUP BY gastos_id - - UNION ALL - -- Iva Importacion pendiente - -- JGF 17/02/15 cambia la forma de declarar este tipo de importaciones, sólo afecta a transitarios - SELECT '4700000999',NULL,NULL ,ROUND(SUM(importe * (iva/100)),2),NULL ,0, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR - - FROM recibida r - JOIN recibida_intrastat ri ON r.id = ri.recibida_id - JOIN Intrastat i ON i.Codintrastat = ri.Codintrastat - JOIN iva_codigo ic ON ic.id = i.iva_codigo_id - WHERE ri.recibida_id = NEW.id GROUP BY ri.recibida_id - - ) t2 - - UNION ALL - - - -- Extracomunitarias gasto contra proveedor/acreedor - SELECT CONCAT('COMPRA s/fra ',sref,':',LEFT(p.Proveedor, 10)) concepto ,gastos_id,cuenta, - - ROUND(SUM(bi)/IF(r.serie='W' AND ri.divisa IS NULL,dblRefRate,1)* (re.percentage / 100),2),NULL ,IF( @a:=@a+1 ,NULL,NULL) ,0, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR,r.serie,0 LDIFADUAN - - FROM recibida_entrada re - - INNER JOIN recibida_iva ri ON re.recibida_id = ri.recibida_id - - INNER JOIN recibida r ON r.id = ri.recibida_id - - INNER JOIN Proveedores p ON p.Id_Proveedor = r.proveedor_id - - INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada - - LEFT JOIN travel t ON t.id = e.travel_id - - INNER JOIN (SELECT @a:=0,@cont:=1,@total:=0,@base:=2) t1 - - WHERE re.awb_recibida = NEW.id AND re.percentage GROUP BY r.id - -UNION ALL - - -- Extracomunitarias proveedor contra gasto - SELECT CONCAT('COMPRA s/fra ',sref,':',LEFT(p.Proveedor, 10)) concepto ,p.cuenta subcta,gastos_id, - - NULL eurodebe, ROUND((1+(iva/100)*(r.serie = 'R'))*SUM(bi)/IF(r.serie='W' AND ri.divisa IS NULL,dblRefRate,1)* (re.percentage / 100),2) eurohaber, - - NULL baseeuro,0 iva, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR,r.serie,0 LDIFADUAN - -- antes sols iva - FROM recibida_entrada re - - INNER JOIN recibida_iva ri ON re.recibida_id = ri.recibida_id - - INNER JOIN recibida r ON r.id = ri.recibida_id - - INNER JOIN iva_codigo ic ON ri.iva_id = ic.id - - INNER JOIN Proveedores p ON Id_Proveedor = r.proveedor_id - - INNER JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id - - WHERE re.awb_recibida = NEW.id AND re.percentage GROUP BY r.id - -UNION ALL - - -- Linea de iva adquisicion - SELECT CONCAT('ADQUI. INTRA FRA ',sref),ic.codigo,p.cuenta contra, - - ROUND(iva/100*SUM(ri.importe) + 0.0001,2) eurodebe, NULL eurohaber, - - ROUND(SUM(ri.importe),2) baseeuro,iva, 1 l340,1 LRECT349,TIPOOPE,'' AUXILIAR,r.serie,0 LDIFADUAN - - FROM awb_recibida ar - - JOIN awb a ON ar.awb_id = a.id - - JOIN iva_codigo ic ON a.iva_id = ic.id - - JOIN iva_tipo it ON ic.iva_tipo_id = it.id - - JOIN Proveedores p ON a.transitario_id = p.Id_Proveedor - - JOIN recibida_intrastat ri ON ri.recibida_id = ar.recibida_id - - JOIN recibida r ON r.id = ri.recibida_id - - JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id - - WHERE ar.recibida_id = NEW.id AND (p.pais_id <> p2.pais_id) - GROUP BY iva - - UNION ALL - - -- Linea de iva adquisicion - SELECT CONCAT('ADQUI. INTRA FRA ',sref),ic2.codigo,p.cuenta contra, - - NULL eurodebe, ROUND(ic2.iva/100*SUM(ri.importe) + 0.0001,2) eurohaber, - - ROUND(SUM(ri.importe),2) baseeuro,ic2.iva, 1 l340,0 LRECT349, TIPOOPE,'' AUXILIAR,r.serie,0 LDIFADUAN - - FROM awb_recibida ar - - JOIN awb a ON ar.awb_id = a.id - - JOIN iva_codigo ic ON a.iva_id = ic.id - - JOIN iva_codigo ic2 ON ic2.link = ic.link AND ic.id <> ic2.id - - JOIN iva_tipo it ON ic.iva_tipo_id = it.id - - JOIN Proveedores p ON a.transitario_id = p.Id_Proveedor - - JOIN recibida_intrastat ri ON ri.recibida_id = ar.recibida_id - - JOIN recibida r ON r.id = ar.recibida_id - - JOIN Proveedores p1 ON p1.Id_Proveedor = r.proveedor_id - - JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id - - WHERE ar.recibida_id = NEW.id AND (p.pais_id <> p2.pais_id) GROUP BY ic2.iva - - UNION ALL - -- Linea iva importacion - SELECT concepto,subcta,Cuenta, - IF (NOT ((ppais_id <> p2pais_id) AND CEE < 2), - - eurodebe - ,NULL)eurodebe,eurohaber,baseeuro, iva, - IF(@total:=@total+eurodebe ,0,0) l340, 0 LRECT349, - IF(@cont:=@cont+1,'','') TIPOOPE,'*' AUXILIAR,serie,1 LDIFADUAN FROM ( - - SELECT CONCAT('COMPRA FRA ',p.Proveedor) concepto,ic2.codigo subcta,p.Cuenta,ic2.iva, - ROUND(sum(costefijo * Cantidad / sub1.costetotal * sub2.importe)*(ic2.iva/100),2) eurodebe,NULL eurohaber, -- JGF 17/02/15 canvie 0.21 per ic.iva - ROUND(sum(costefijo * Cantidad / sub1.costetotal * sub2.importe),2) baseeuro,r.serie,pa.CEE,pa.Id_Paisreal ppais_id, - p2.pais_id p2pais_id,SUM(sub3.SumIntrastat *(ic2.iva/100)) SumIntrastat, p.Id_Proveedor,Codintrastat - - FROM awb_recibida ar - - JOIN recibida_entrada re ON ar.recibida_id = re.awb_recibida - - JOIN Compres c ON c.Id_Entrada = re.Id_Entrada - - INNER JOIN Articles a ON a.Id_Article = c.Id_Article - - INNER JOIN ( - - SELECT a.Codintrastat, sum(c.costefijo * c.Cantidad) as costetotal - - FROM Compres c - - JOIN Articles a ON a.Id_Article = c.Id_Article - - JOIN recibida_entrada re ON re.Id_Entrada = c.Id_Entrada - - JOIN awb_recibida ar ON ar.recibida_id = re.awb_recibida - - JOIN awb aw ON ar.awb_id = aw.id - - WHERE ar.recibida_id = NEW.id AND re.percentage - - GROUP BY a.Codintrastat - - ) sub1 USING(Codintrastat) - - INNER JOIN ( - - SELECT Codintrastat,ri.importe, i.iva_codigo_id - - FROM recibida_intrastat ri - JOIN Intrastat i USING(Codintrastat) - - WHERE ri.recibida_id = NEW.id - - ) sub2 USING(Codintrastat) - - INNER JOIN ( - - SELECT SUM(ri.importe) SumIntrastat - - FROM recibida_intrastat ri - - WHERE ri.recibida_id = NEW.id - - ) sub3 - - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - - JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor - - JOIN Paises pa ON p.pais_id = pa.Id - - JOIN recibida r ON r.id = re.recibida_id - - JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id - - JOIN iva_codigo ic2 ON ic2.id = sub2.iva_codigo_id -- JGF 15/04/15 nou canvi llei (Ali) - - WHERE re.awb_recibida = NEW.id AND re.percentage - -- canvie el cta_proveed like '___1______' per cero cuidao en les van de put - - GROUP BY p.Id_Proveedor, sub2.iva_codigo_id - -) t3 GROUP BY Id_Proveedor, iva)t4; - --- linea que estava a l'ultim WHERE -END IF; -*/ - END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`recibida_au` AFTER UPDATE ON `recibida` FOR EACH ROW -BEGIN - - IF NEW.fecha != OLD.fecha - OR - NEW.moneda_id != OLD.moneda_id - THEN - - CALL recibidaIvaDivisaUpdate(NEW.id); - - END IF; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `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 `recibida` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `recibida_entrada` --- - -DROP TABLE IF EXISTS `recibida_entrada`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `recibida_entrada` ( - `recibida_entrada_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `recibida_id` mediumint(8) unsigned NOT NULL, - `Id_Entrada` int(11) NOT NULL, - `percentage` decimal(10,2) unsigned NOT NULL DEFAULT '0.00', - `awb_recibida` mediumint(8) unsigned NOT NULL, - `Contabilizado` tinyint(3) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`recibida_entrada_id`), - KEY `awb_recibida` (`awb_recibida`), - KEY `Id_Entrada` (`Id_Entrada`), - KEY `recibida_id` (`recibida_id`), - CONSTRAINT `recibida_entrada_ibfk_2` FOREIGN KEY (`Id_Entrada`) REFERENCES `Entradas` (`Id_Entrada`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=10104 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `recibida_entrada_bi` BEFORE INSERT ON `recibida_entrada` FOR EACH ROW -BEGIN - DECLARE intRecibida INT; - IF NEW.recibida_id = 0 THEN - SELECT recibida_id INTO intRecibida FROM recibida_entrada WHERE Id_Entrada = NEW.Id_Entrada; - SET NEW.recibida_id = intRecibida; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `recibida_entrada_bu` BEFORE UPDATE ON `recibida_entrada` FOR EACH ROW -BEGIN - DECLARE intRecibida INT; - IF NEW.recibida_id = 0 THEN - SELECT recibida_id INTO intRecibida FROM recibida_entrada WHERE Id_Entrada = NEW.Id_Entrada; - SET NEW.recibida_id = intRecibida; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `recibida_intrastat` --- - -DROP TABLE IF EXISTS `recibida_intrastat`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `recibida_intrastat` ( - `recibida_id` mediumint(8) unsigned NOT NULL, - `Codintrastat` int(8) unsigned zerofill NOT NULL, - `importe` decimal(10,2) NOT NULL, - PRIMARY KEY (`recibida_id`,`Codintrastat`), - KEY `Codintrastat` (`Codintrastat`), - KEY `recibida_id` (`recibida_id`), - CONSTRAINT `recibida_intrastat_ibfk_1` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `recibida_intrastat_ibfk_2` FOREIGN KEY (`Codintrastat`) REFERENCES `Intrastat` (`Codintrastat`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `recibida_iva` --- - -DROP TABLE IF EXISTS `recibida_iva`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `recibida_iva` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `recibida_id` mediumint(8) unsigned NOT NULL, - `iva_id` tinyint(2) unsigned NOT NULL, - `bi` decimal(10,2) NOT NULL, - `gastos_id` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `divisa` decimal(10,2) DEFAULT NULL, - `MYSQL_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `gastos_id` (`gastos_id`), - KEY `recibida_id` (`recibida_id`), - KEY `recibida_iva_ibfk_2` (`iva_id`), - CONSTRAINT `recibida_iva_ibfk_2` FOREIGN KEY (`iva_id`) REFERENCES `iva_codigo` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `recibida_iva_ibfk_5` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `recibida_iva_ibfk_6` FOREIGN KEY (`gastos_id`) REFERENCES `Gastos` (`Id_Gasto`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB AUTO_INCREMENT=86376 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `recibida_vencimiento` --- - -DROP TABLE IF EXISTS `recibida_vencimiento`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `recibida_vencimiento` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `recibida_id` mediumint(8) unsigned NOT NULL, - `fecha` date NOT NULL, - `banco_id` int(11) NOT NULL DEFAULT '3117', - `cantidad` decimal(10,2) NOT NULL DEFAULT '0.00', - `divisa` decimal(10,2) DEFAULT NULL, - `stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `recibida_id` (`recibida_id`), - KEY `banco_id` (`banco_id`), - CONSTRAINT `recibida_vencimiento_ibfk_6` FOREIGN KEY (`banco_id`) REFERENCES `Bancos` (`Id_Banco`) ON UPDATE CASCADE, - CONSTRAINT `recibida_vencimiento_ibfk_7` FOREIGN KEY (`recibida_id`) REFERENCES `recibida` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=84057 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`recibida_vencimiento_bi` -BEFORE INSERT ON `vn2008`.`recibida_vencimiento` -FOR EACH ROW -BEGIN - IF NEW.cantidad = 0 THEN - SET NEW.id = 5; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `recovery` --- - -DROP TABLE IF EXISTS `recovery`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `recovery` ( - `recovery_id` int(11) NOT NULL AUTO_INCREMENT, - `Id_Cliente` int(11) NOT NULL DEFAULT '0', - `dstart` date NOT NULL COMMENT 'Fecha a partir de la que comienza el recobro', - `dend` date DEFAULT NULL COMMENT 'Fecha en la que acaba', - `amount` double NOT NULL, - `period` tinyint(3) unsigned NOT NULL DEFAULT '7' COMMENT 'numero de dias que indica cada cuanto hare el recobro', - PRIMARY KEY (`recovery_id`), - KEY `cliente_idx` (`Id_Cliente`), - CONSTRAINT `cliente333` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE, - CONSTRAINT `cliente_cliente` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=248 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='En esta tabla apuntaremos los acuerdos de recobro semanal a '; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `recovery_asset` --- - -DROP TABLE IF EXISTS `recovery_asset`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `recovery_asset` ( - `recovery_asset_id` int(11) NOT NULL AUTO_INCREMENT, - `dreceipt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `amount` double NOT NULL, - `Id_Cliente` int(11) NOT NULL, - PRIMARY KEY (`recovery_asset_id`), - KEY `Cliente_Recovery_detalle_idx` (`Id_Cliente`), - CONSTRAINT `Cliente_Recovery_detalle` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=723 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='En esta tabla se registra el detalle de los recobros definid'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `reference_min` --- - -DROP TABLE IF EXISTS `reference_min`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `reference_min` ( - `date` date NOT NULL, - `rate` decimal(10,4) NOT NULL, - `moneda_id` tinyint(3) unsigned NOT NULL, - PRIMARY KEY (`date`,`moneda_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `reference_rate` --- - -DROP TABLE IF EXISTS `reference_rate`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `reference_rate` ( - `moneda_id` tinyint(3) unsigned NOT NULL, - `date` date NOT NULL, - `rate` float unsigned NOT NULL, - PRIMARY KEY (`moneda_id`,`date`), - KEY `date` (`date`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `reinos` --- - -DROP TABLE IF EXISTS `reinos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `reinos` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `reino` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `orden` int(10) unsigned DEFAULT NULL, - `display` tinyint(4) NOT NULL DEFAULT '1', - `color` char(6) COLLATE utf8_unicode_ci DEFAULT NULL, - `efimero` int(11) NOT NULL DEFAULT '0' COMMENT 'Sirve para filtrar aquellos reinos que tienen precios estables', - `mercancia` tinyint(1) NOT NULL DEFAULT '1', - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `reparacion` --- - -DROP TABLE IF EXISTS `reparacion`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `reparacion` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `id_user` int(2) DEFAULT NULL, - `config_host` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - `problema` text COLLATE utf8_unicode_ci NOT NULL, - `solucion` text COLLATE utf8_unicode_ci NOT NULL, - `estado` enum('No atendida','Vista','En Proceso','Solucionada') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'No atendida', - `fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `id_reparador` int(2) DEFAULT NULL, - `ref` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `articulo` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, - `marca` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `config_host` (`config_host`), - KEY `id_user` (`id_user`), - KEY `id_reparador` (`id_reparador`), - CONSTRAINT `reparacion_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `reparacion_ibfk_2` FOREIGN KEY (`config_host`) REFERENCES `config_host` (`config_host_id`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `reparacion_ibfk_4` FOREIGN KEY (`id_reparador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `rolekk` --- - -DROP TABLE IF EXISTS `rolekk`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `rolekk` ( - `role_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `description` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`role_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ruta_location` --- - -DROP TABLE IF EXISTS `ruta_location`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ruta_location` ( - `Id_Ruta` int(10) unsigned NOT NULL, - `longitude` decimal(11,7) NOT NULL, - `latitude` decimal(11,7) NOT NULL, - `time_location` datetime NOT NULL, - PRIMARY KEY (`Id_Ruta`), - CONSTRAINT `Id_Ruta_Location` FOREIGN KEY (`Id_Ruta`) REFERENCES `Rutas` (`Id_Ruta`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `salarioDits` --- - -DROP TABLE IF EXISTS `salarioDits`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `salarioDits` ( - `idSalario_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) COLLATE utf8_unicode_ci DEFAULT NULL, - `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`idSalario_dits`) -) ENGINE=InnoDB AUTO_INCREMENT=96 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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 utf8 DEFAULT NULL, - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=48191 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Se borra automaticamente 8 dias en el pasado desde vn2008.clean'; -/*!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` longtext CHARACTER SET utf8, - `lft` int(11) NOT NULL, - `rgt` int(11) NOT NULL, - `depth` bigint(22) NOT NULL DEFAULT '0', - `sons` decimal(10,0) DEFAULT NULL, - `lastScanned` datetime DEFAULT NULL, - `routeCount` int(11) DEFAULT NULL, - `minRoute` int(11) DEFAULT NULL, - `maxRoute` int(11) DEFAULT NULL, - `scanned` int(11) DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci 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 AUTO_INCREMENT=626820 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `sharingcart` --- - -DROP TABLE IF EXISTS `sharingcart`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `sharingcart` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `Id_Trabajador` int(11) NOT NULL, - `datSTART` date NOT NULL, - `datEND` date NOT NULL, - `Id_Suplente` int(11) NOT NULL, - `odbc_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `Worker` (`Id_Trabajador`), - KEY `Suplent` (`Id_Suplente`), - CONSTRAINT `Suplent_key` FOREIGN KEY (`Id_Suplente`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE, - CONSTRAINT `Trabajador_key` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=1713 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sharingcart_bi` BEFORE INSERT ON `sharingcart` FOR EACH ROW - -BEGIN - - SET NEW.datSTART = GREATEST(CURDATE(),NEW.datSTART); - SET NEW.datEND = GREATEST(CURDATE(),NEW.datEND); - - IF NEW.Id_Trabajador = NEW.Id_Suplente THEN - SET NEW.Id_Trabajador = NULL; - - - -END IF; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sharingcart_bu` BEFORE UPDATE ON `sharingcart` FOR EACH ROW - -BEGIN - - SET NEW.datSTART = GREATEST(CURDATE(),NEW.datSTART); - SET NEW.datEND = GREATEST(CURDATE(),NEW.datEND); - - IF NEW.Id_Trabajador = NEW.Id_Suplente THEN - SET NEW.Id_Trabajador = NULL; - - -END IF; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `sharingclient` --- - -DROP TABLE IF EXISTS `sharingclient`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `sharingclient` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `Id_Trabajador` int(11) NOT NULL, - `datSTART` date NOT NULL, - `datEND` date NOT NULL, - `Id_Cliente` int(11) NOT NULL, - PRIMARY KEY (`id`), - KEY `Worker` (`Id_Trabajador`), - KEY `Client` (`Id_Cliente`), - CONSTRAINT `Clients_key` FOREIGN KEY (`Id_Cliente`) REFERENCES `Clientes` (`id_cliente`) ON UPDATE CASCADE, - CONSTRAINT `Trabajadores_key` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`sharingclient_BEFORE_INSERT` BEFORE INSERT ON `sharingclient` FOR EACH ROW -BEGIN - -SET NEW.datEND = GREATEST(CURDATE(),NEW.datEND); -SET NEW.datSTART = GREATEST(CURDATE(),NEW.datSTART); - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`sharingclient_BEFORE_UPDATE` BEFORE UPDATE ON `sharingclient` FOR EACH ROW -BEGIN - -SET NEW.datEND = GREATEST(CURDATE(),NEW.datEND); -SET NEW.datSTART = GREATEST(CURDATE(),NEW.datSTART); - -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 */ ; - --- --- Temporary view structure for view `sms` --- - -DROP TABLE IF EXISTS `sms`; -/*!50001 DROP VIEW IF EXISTS `sms`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `sms` AS SELECT - 1 AS `id`, - 1 AS `Id_trabajador`, - 1 AS `Id_Cliente`, - 1 AS `from`, - 1 AS `to`, - 1 AS `text`, - 1 AS `sent`, - 1 AS `response`, - 1 AS `DATE_ODBC`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `split` --- - -DROP TABLE IF EXISTS `split`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `split` ( - `edi_id` int(11) NOT NULL, - `customer_id` int(11) NOT NULL, - `quantity` int(11) NOT NULL, - KEY `edi_id` (`edi_id`,`customer_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `state` --- - -DROP TABLE IF EXISTS `state`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `state` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - `order` tinyint(3) unsigned DEFAULT NULL, - `alert_level` int(11) NOT NULL DEFAULT '0', - `code` varchar(45) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `code_UNIQUE` (`code`) -) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `tag` --- - -DROP TABLE IF EXISTS `tag`; -/*!50001 DROP VIEW IF EXISTS `tag`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `tag` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `isFree`, - 1 AS `isQuantitatif`, - 1 AS `sourceTable`, - 1 AS `unit`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `tarifa_componentes` --- - -DROP TABLE IF EXISTS `tarifa_componentes`; -/*!50001 DROP VIEW IF EXISTS `tarifa_componentes`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `tarifa_componentes` AS SELECT - 1 AS `Id_Componente`, - 1 AS `Componente`, - 1 AS `tarifa_componentes_series_id`, - 1 AS `tarifa_class`, - 1 AS `tax`, - 1 AS `is_renewable`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `tarifa_componentes_series` --- - -DROP TABLE IF EXISTS `tarifa_componentes_series`; -/*!50001 DROP VIEW IF EXISTS `tarifa_componentes_series`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `tarifa_componentes_series` AS SELECT - 1 AS `tarifa_componentes_series_id`, - 1 AS `Serie`, - 1 AS `base`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `tarifas` --- - -DROP TABLE IF EXISTS `tarifas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tarifas` ( - `tarifa_id` int(11) NOT NULL AUTO_INCREMENT, - `fecha` date NOT NULL, - `warehouse_id` smallint(6) unsigned NOT NULL, - `t0` double NOT NULL, - `t1` double NOT NULL, - `t2` double NOT NULL, - `t3` double NOT NULL, - PRIMARY KEY (`tarifa_id`), - KEY `tarifa_warehouse` (`warehouse_id`), - CONSTRAINT `tarifa_warehouse` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=140 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tblContadores` --- - -DROP TABLE IF EXISTS `tblContadores`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tblContadores` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `ochoa` int(10) unsigned NOT NULL, - `nfactura` int(11) DEFAULT '0', - `nasiento` int(11) DEFAULT '0', - `serieA` int(11) DEFAULT '0', - `serieE` int(11) DEFAULT '0', - `serieR` int(11) DEFAULT '0', - `serieC` int(11) DEFAULT '0', - `SerieH` int(11) NOT NULL, - `serieP` int(11) DEFAULT '0', - `serieT` int(11) DEFAULT '0', - `FechaInventario` datetime DEFAULT NULL, - `serieM` int(11) DEFAULT '0', - `HistoricoArticulo` int(11) DEFAULT '0', - `week_goal` int(11) DEFAULT NULL, - `Rutafotos` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `numCaja` int(11) DEFAULT '0', - `CodigoRojo` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Tablet_Hora` datetime DEFAULT NULL, - `t0` int(11) NOT NULL DEFAULT '0', - `t1` int(11) NOT NULL DEFAULT '0', - `t2` int(11) NOT NULL DEFAULT '0', - `t3` int(11) NOT NULL DEFAULT '0', - `cc` double NOT NULL DEFAULT '0', - `palet` double NOT NULL DEFAULT '0', - `campaign` datetime NOT NULL, - `campaign_life` tinyint(3) unsigned NOT NULL, - `truck_days` tinyint(3) unsigned NOT NULL, - `tasa_transporte` double NOT NULL, - `escaner_path` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `turnoimpreso` int(4) DEFAULT NULL, - `truck_length` int(11) DEFAULT '24', - `fuel_consumption` int(11) DEFAULT NULL, - `petrol` decimal(10,1) DEFAULT NULL, - `maintenance` decimal(10,1) DEFAULT NULL, - `hour_price` decimal(10,1) DEFAULT NULL, - `meter_price` decimal(10,1) DEFAULT NULL, - `km_price` decimal(10,1) DEFAULT NULL, - `route_option` int(11) DEFAULT '1', - `dbproduccion` tinyint(1) NOT NULL DEFAULT '1', - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`tblContadores_bi` BEFORE INSERT ON `tblContadores` FOR EACH ROW -BEGIN - DECLARE v_count INT; - - SELECT COUNT(*) INTO v_count FROM tblContadores; - - IF v_count > 0 THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'ONLY_ONE_ROW_ALLOWED'; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `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) COLLATE utf8_unicode_ci 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=utf8 COLLATE=utf8_unicode_ci; -/*!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=utf8 COLLATE=utf8_unicode_ci; -/*!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', - KEY `item_id` (`item_id`), - KEY `item_warehouse` (`item_id`,`warehouse_id`) USING HASH -) ENGINE=MEMORY DEFAULT CHARSET=utf8; -/*!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, - KEY `item_id` (`item_id`) USING BTREE -) ENGINE=MEMORY DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `thermograph` --- - -DROP TABLE IF EXISTS `thermograph`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `thermograph` ( - `thermograph_id` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `model` enum('TL30','SENSITECH','TREKVIEW1','TREKVIEW2','DISPOSABLE') COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`thermograph_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `ticketCreationData` --- - -DROP TABLE IF EXISTS `ticketCreationData`; -/*!50001 DROP VIEW IF EXISTS `ticketCreationData`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ticketCreationData` AS SELECT - 1 AS `DiadelaSemana`, - 1 AS `Hora`, - 1 AS `Fecha`, - 1 AS `Dispositivo`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `ticket_location` --- - -DROP TABLE IF EXISTS `ticket_location`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ticket_location` ( - `Id_Ticket` int(11) NOT NULL, - `longitude` decimal(11,7) DEFAULT NULL, - `latitude` decimal(11,7) DEFAULT NULL, - PRIMARY KEY (`Id_Ticket`), - CONSTRAINT `Id_Ticket_Location` FOREIGN KEY (`Id_Ticket`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ticket_observation` --- - -DROP TABLE IF EXISTS `ticket_observation`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ticket_observation` ( - `ticket_observation_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `Id_Ticket` int(11) NOT NULL, - `observation_type_id` tinyint(3) unsigned NOT NULL, - `text` text COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`ticket_observation_id`), - UNIQUE KEY `Id_Ticket` (`Id_Ticket`,`observation_type_id`), - KEY `observation_type_id` (`observation_type_id`), - CONSTRAINT `ticket_observation_ibfk_1` FOREIGN KEY (`Id_Ticket`) REFERENCES `Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `ticket_observation_ibfk_2` FOREIGN KEY (`observation_type_id`) REFERENCES `observation_type` (`observation_type_id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=1007858 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Todas las observaciones referentes a un ticket'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tickets_gestdoc` --- - -DROP TABLE IF EXISTS `tickets_gestdoc`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tickets_gestdoc` ( - `Id_Ticket` int(11) NOT NULL, - `gestdoc_id` int(11) NOT NULL, - PRIMARY KEY (`Id_Ticket`,`gestdoc_id`), - KEY `gestdoc_id` (`gestdoc_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `time` --- - -DROP TABLE IF EXISTS `time`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `time` ( - `date` date NOT NULL, - `period` int(6) NOT NULL, - `month` int(2) NOT NULL, - `year` int(4) NOT NULL, - `day` int(2) NOT NULL, - `week` int(2) NOT NULL, - `yearMonth` int(6) NOT NULL, - PRIMARY KEY (`date`), - KEY `day_index` (`day`) USING HASH, - KEY `week_index` (`week`) USING HASH, - KEY `year_index` (`year`) USING HASH, - KEY `month_index` (`month`) USING HASH, - KEY `periodo` (`period`) USING HASH, - KEY `yearMonth` (`yearMonth`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla de referencia para las semanas, años y meses'; -/*!40101 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=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci 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=utf8 COLLATE=utf8_unicode_ci; -/*!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=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `travel` --- - -DROP TABLE IF EXISTS `travel`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `travel` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `shipment` date DEFAULT NULL, - `shipment_hour` time DEFAULT NULL, - `landing` date NOT NULL, - `landing_hour` time DEFAULT NULL, - `warehouse_id` smallint(6) unsigned DEFAULT NULL, - `warehouse_id_out` smallint(6) unsigned DEFAULT NULL, - `agency_id` int(11) DEFAULT NULL, - `ref` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `delivered` tinyint(1) NOT NULL DEFAULT '0', - `received` tinyint(1) NOT NULL DEFAULT '0', - `m3` decimal(10,2) unsigned DEFAULT NULL, - `kg` decimal(10,0) unsigned DEFAULT NULL, - `cargoSupplierFk` int(11) DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `shipment_2` (`shipment`,`landing`,`warehouse_id`,`warehouse_id_out`,`agency_id`,`ref`), - KEY `agency_id` (`agency_id`), - KEY `shipment` (`shipment`), - KEY `landing` (`landing`), - KEY `warehouse_landing` (`warehouse_id`,`landing`), - KEY `warehouse_out_shipment` (`warehouse_id_out`,`shipment`), - KEY `travel_ibfk_4_idx` (`cargoSupplierFk`), - CONSTRAINT `travel_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, - CONSTRAINT `travel_ibfk_2` FOREIGN KEY (`warehouse_id_out`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, - CONSTRAINT `travel_ibfk_3` FOREIGN KEY (`agency_id`) REFERENCES `Agencias` (`Id_Agencia`) ON UPDATE CASCADE, - CONSTRAINT `travel_ibfk_4` FOREIGN KEY (`cargoSupplierFk`) REFERENCES `Proveedores` (`Id_Proveedor`) ON DELETE SET NULL ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=101307 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `travelBeforeInsert` - BEFORE INSERT ON `travel` FOR EACH ROW -BEGIN - -- Evita fechas absurdas - - IF NEW.landing < TIMESTAMPADD(YEAR, -10, CURDATE()) - OR NEW.shipment < TIMESTAMPADD(YEAR, -10, CURDATE()) - OR NEW.landing < NEW.shipment - THEN - SET NEW.landing = NULL; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `travelBeforeUpdate` - BEFORE UPDATE ON `travel` FOR EACH ROW -BEGIN - DECLARE trabajador INT; - - -- Volem permetre dates iguals de eixida i arribada per al magatzems filiats en warehouse_tree - - IF NEW.landing < NEW.shipment THEN - SET NEW.shipment = NEW.landing; - END IF; - - -- Evita fechas absurdas - - IF NEW.landing < TIMESTAMPADD(YEAR,-10, CURDATE()) - OR NEW.shipment < TIMESTAMPADD(YEAR,-10,CURDATE()) - THEN - SET NEW.landing = NULL; - END IF; - - -- Ditacio para averiguar cuando se marca como delivered = true los travels, pues aparecen por la mañana sin explicacion - - IF ABS(NEW.delivered) > ABS(OLD.delivered) - THEN - SELECT Id_Trabajador into trabajador from Trabajadores where user_id = account.userGetId(); - - INSERT INTO travel_dits (idaccion_dits,Id_Trabajador,Id_Ticket,value_old,value_new) - VALUES (89/*Cambia delivered*/,IFNULL(trabajador,20),NEW.id,OLD.delivered,CONCAT(NEW.delivered,' desde ' ,user())); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`travelAfterUpdate` - AFTER UPDATE ON `travel` FOR EACH ROW -BEGIN - CALL stock.queueAdd ('travel', NEW.id, OLD.id); - - IF NEW.shipment != OLD.shipment THEN - - UPDATE Entradas - SET comision = getComision(Id_Entrada, Id_Moneda) - WHERE travel_id = NEW.id; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn2008`.`travelAfterDelete` - AFTER DELETE ON `travel` FOR EACH ROW -BEGIN - CALL stock.queueAdd ('travel', NULL, OLD.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 */ ; - --- --- Table structure for table `travel_dits` --- - -DROP TABLE IF EXISTS `travel_dits`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `travel_dits` ( - `idtravel_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) COLLATE utf8_unicode_ci DEFAULT NULL, - `value_new` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`idtravel_dits`), - KEY `fgkey1_idx` (`idaccion_dits`), - KEY `fgkey2_idx` (`Id_Ticket`), - KEY `fgkey3_idx` (`Id_Trabajador`), - CONSTRAINT `travel_dits_ibfk_1` FOREIGN KEY (`Id_Trabajador`) REFERENCES `Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=154573 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`travel_pattern_id`), - KEY `warehouse_out` (`warehouse_out`), - KEY `warehouse_in` (`warehouse_in`), - KEY `agency_id` (`agency_id`), - CONSTRAINT `travel_pattern_ibfk_3` FOREIGN KEY (`warehouse_out`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, - CONSTRAINT `travel_pattern_ibfk_4` FOREIGN KEY (`agency_id`) REFERENCES `Agencias` (`Id_Agencia`) ON UPDATE CASCADE, - CONSTRAINT `travel_pattern_ibfk_5` FOREIGN KEY (`warehouse_in`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=320 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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 `travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='En esta tabla almacenamos los m3 que cada comprador tiene asignados, por travel.'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `travel_thermograph` --- - -DROP TABLE IF EXISTS `travel_thermograph`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `travel_thermograph` ( - `thermograph_id` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `odbc_date` date NOT NULL, - `warehouse_id` smallint(6) unsigned NOT NULL, - `travel_id` int(10) unsigned DEFAULT NULL, - `temperature` enum('COOL','WARM') COLLATE utf8_unicode_ci NOT NULL, - `result` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `gestdoc_id` int(11) DEFAULT NULL, - PRIMARY KEY (`thermograph_id`,`odbc_date`), - KEY `thermograph_fk_idx` (`thermograph_id`), - KEY `gestdoc_fk_idx` (`gestdoc_id`), - KEY `travel_id` (`travel_id`), - KEY `warehouse_id` (`warehouse_id`), - CONSTRAINT `gestdoc_fk` FOREIGN KEY (`gestdoc_id`) REFERENCES `gestdoc` (`id`) ON UPDATE CASCADE, - CONSTRAINT `thermograph_fk` FOREIGN KEY (`thermograph_id`) REFERENCES `thermograph` (`thermograph_id`) ON UPDATE CASCADE, - CONSTRAINT `travel_fk` FOREIGN KEY (`travel_id`) REFERENCES `travel` (`id`), - CONSTRAINT `travel_thermograph_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Registra cada termografo que se ha introducido en cada travel'; -/*!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) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=132 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `turn` --- - -DROP TABLE IF EXISTS `turn`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `turn` ( - `number` int(11) NOT NULL, - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`number`,`odbc_date`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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 AUTO_INCREMENT=883 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci NOT NULL, - `filter` text COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci DEFAULT NULL, - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `type` set('BUYS','EXPEDITIONS') COLLATE utf8_unicode_ci 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=utf8 COLLATE=utf8_unicode_ci; -/*!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) COLLATE utf8_unicode_ci 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 AUTO_INCREMENT=8462 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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 `Articles` (`Id_Article`) 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=utf8 COLLATE=utf8_unicode_ci; -/*!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 `expeditions` (`expeditions_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `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) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`name`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `v_Agenda` --- - -DROP TABLE IF EXISTS `v_Agenda`; -/*!50001 DROP VIEW IF EXISTS `v_Agenda`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_Agenda` AS SELECT - 1 AS `Tipo`, - 1 AS `Id`, - 1 AS `Nombre`, - 1 AS `Telephone`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_Agenda2` --- - -DROP TABLE IF EXISTS `v_Agenda2`; -/*!50001 DROP VIEW IF EXISTS `v_Agenda2`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_Agenda2` AS SELECT - 1 AS `Tipo`, - 1 AS `Id`, - 1 AS `Nombre`, - 1 AS `Telefono`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_Articles_botanical` --- - -DROP TABLE IF EXISTS `v_Articles_botanical`; -/*!50001 DROP VIEW IF EXISTS `v_Articles_botanical`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_Articles_botanical` AS SELECT - 1 AS `Id_Article`, - 1 AS `edi_botanic`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_Movimientos_Volumen_shipping_charge` --- - -DROP TABLE IF EXISTS `v_Movimientos_Volumen_shipping_charge`; -/*!50001 DROP VIEW IF EXISTS `v_Movimientos_Volumen_shipping_charge`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_Movimientos_Volumen_shipping_charge` AS SELECT - 1 AS `Id_Ticket`, - 1 AS `Id_Movimiento`, - 1 AS `Fecha`, - 1 AS `price`, - 1 AS `freight`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_Ordenes` --- - -DROP TABLE IF EXISTS `v_Ordenes`; -/*!50001 DROP VIEW IF EXISTS `v_Ordenes`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_Ordenes` AS SELECT - 1 AS `Id_ORDEN`, - 1 AS `ORDEN`, - 1 AS `datORDEN`, - 1 AS `datTICKET`, - 1 AS `CodVENDEDOR`, - 1 AS `CodCOMPRADOR`, - 1 AS `CANTIDAD`, - 1 AS `PRECIOMAX`, - 1 AS `PREU`, - 1 AS `Id_ARTICLE`, - 1 AS `Id_CLIENTE`, - 1 AS `COMENTARIO`, - 1 AS `OK`, - 1 AS `TOTAL`, - 1 AS `datCOMPRA`, - 1 AS `KO`, - 1 AS `Id_Movimiento`, - 1 AS `odbc_date`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_XDiario_ALL` --- - -DROP TABLE IF EXISTS `v_XDiario_ALL`; -/*!50001 DROP VIEW IF EXISTS `v_XDiario_ALL`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_XDiario_ALL` AS SELECT - 1 AS `empresa_id`, - 1 AS `SUBCTA`, - 1 AS `Eurodebe`, - 1 AS `Eurohaber`, - 1 AS `Fecha`, - 1 AS `FECHA_EX`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_accion` --- - -DROP TABLE IF EXISTS `v_accion`; -/*!50001 DROP VIEW IF EXISTS `v_accion`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_accion` AS SELECT - 1 AS `accion_id`, - 1 AS `accion`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_account` --- - -DROP TABLE IF EXISTS `v_account`; -/*!50001 DROP VIEW IF EXISTS `v_account`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_account` AS SELECT - 1 AS `user_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_analisis_ventas` --- - -DROP TABLE IF EXISTS `v_analisis_ventas`; -/*!50001 DROP VIEW IF EXISTS `v_analisis_ventas`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_analisis_ventas` AS SELECT - 1 AS `Familia`, - 1 AS `Reino`, - 1 AS `Comercial`, - 1 AS `Comprador`, - 1 AS `Provincia`, - 1 AS `almacen`, - 1 AS `Año`, - 1 AS `Mes`, - 1 AS `Semana`, - 1 AS `Vista`, - 1 AS `Importe`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_awb_volumen` --- - -DROP TABLE IF EXISTS `v_awb_volumen`; -/*!50001 DROP VIEW IF EXISTS `v_awb_volumen`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_awb_volumen` AS SELECT - 1 AS `awb_id`, - 1 AS `codigo`, - 1 AS `importe`, - 1 AS `Vol_Total`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_barcodes` --- - -DROP TABLE IF EXISTS `v_barcodes`; -/*!50001 DROP VIEW IF EXISTS `v_barcodes`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_barcodes` AS SELECT - 1 AS `code`, - 1 AS `Id_Article`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_barcodes_plus` --- - -DROP TABLE IF EXISTS `v_barcodes_plus`; -/*!50001 DROP VIEW IF EXISTS `v_barcodes_plus`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_barcodes_plus` AS SELECT - 1 AS `code`, - 1 AS `Id_Article`, - 1 AS `Article`, - 1 AS `Medida`, - 1 AS `Color`, - 1 AS `Categoria`, - 1 AS `Producer`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_botanic_export` --- - -DROP TABLE IF EXISTS `v_botanic_export`; -/*!50001 DROP VIEW IF EXISTS `v_botanic_export`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_botanic_export` AS SELECT - 1 AS `Nom_botanic`, - 1 AS `Id_Paises`, - 1 AS `restriction`, - 1 AS `description`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_compres` --- - -DROP TABLE IF EXISTS `v_compres`; -/*!50001 DROP VIEW IF EXISTS `v_compres`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_compres` AS SELECT - 1 AS `Familia`, - 1 AS `reino_id`, - 1 AS `Id_Compra`, - 1 AS `Id_Entrada`, - 1 AS `Id_Article`, - 1 AS `Cantidad`, - 1 AS `Costefijo`, - 1 AS `Portefijo`, - 1 AS `Novincular`, - 1 AS `Etiquetas`, - 1 AS `Packing`, - 1 AS `grouping`, - 1 AS `Comisionfija`, - 1 AS `Embalajefijo`, - 1 AS `Nicho`, - 1 AS `Id_Cubo`, - 1 AS `Tarifa1`, - 1 AS `Tarifa2`, - 1 AS `Tarifa3`, - 1 AS `PVP`, - 1 AS `Vida`, - 1 AS `Id_Trabajador`, - 1 AS `punteo`, - 1 AS `odbc_date`, - 1 AS `Inventario`, - 1 AS `Id_Proveedor`, - 1 AS `Fecha`, - 1 AS `Confirmada`, - 1 AS `Redada`, - 1 AS `empresa_id`, - 1 AS `travel_id`, - 1 AS `Pedida`, - 1 AS `recibida_id`, - 1 AS `id`, - 1 AS `shipment`, - 1 AS `landing`, - 1 AS `warehouse_id`, - 1 AS `warehouse_id_out`, - 1 AS `agency_id`, - 1 AS `ref`, - 1 AS `delivered`, - 1 AS `received`, - 1 AS `Article`, - 1 AS `Medida`, - 1 AS `Tallos`, - 1 AS `caja`, - 1 AS `Categoria`, - 1 AS `id_origen`, - 1 AS `Tipo`, - 1 AS `tipo_id`, - 1 AS `Color`, - 1 AS `Min`, - 1 AS `Coste`, - 1 AS `fuente`, - 1 AS `iva_group_id`, - 1 AS `cm3`, - 1 AS `producer_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_departure_limit` --- - -DROP TABLE IF EXISTS `v_departure_limit`; -/*!50001 DROP VIEW IF EXISTS `v_departure_limit`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_departure_limit` AS SELECT - 1 AS `warehouse_id`, - 1 AS `fecha`, - 1 AS `hora`, - 1 AS `minSpeed`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_descuadre_bionic` --- - -DROP TABLE IF EXISTS `v_descuadre_bionic`; -/*!50001 DROP VIEW IF EXISTS `v_descuadre_bionic`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_descuadre_bionic` AS SELECT - 1 AS `Id_Ticket`, - 1 AS `Alias`, - 1 AS `Concepte`, - 1 AS `suma_componente`, - 1 AS `Preu`, - 1 AS `Descuento`, - 1 AS `diferencia`, - 1 AS `Fecha`, - 1 AS `benvenut`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_descuadre_porte` --- - -DROP TABLE IF EXISTS `v_descuadre_porte`; -/*!50001 DROP VIEW IF EXISTS `v_descuadre_porte`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_descuadre_porte` AS SELECT - 1 AS `Id_Ticket`, - 1 AS `suma_componente`, - 1 AS `teorico_agencia`, - 1 AS `diferencia`, - 1 AS `Fecha`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_descuadre_porte2` --- - -DROP TABLE IF EXISTS `v_descuadre_porte2`; -/*!50001 DROP VIEW IF EXISTS `v_descuadre_porte2`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_descuadre_porte2` AS SELECT - 1 AS `Id_Ticket`, - 1 AS `suma_componente`, - 1 AS `Fecha`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_empresa` --- - -DROP TABLE IF EXISTS `v_empresa`; -/*!50001 DROP VIEW IF EXISTS `v_empresa`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_empresa` AS SELECT - 1 AS `logo`, - 1 AS `id`, - 1 AS `registro`, - 1 AS `gerente_id`, - 1 AS `alta`, - 1 AS `Nombre`, - 1 AS `Apellidos`, - 1 AS `Proveedor`, - 1 AS `Domicilio`, - 1 AS `CP`, - 1 AS `Localidad`, - 1 AS `NIF`, - 1 AS `Telefono`, - 1 AS `Alias`, - 1 AS `abbreviation`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_encajado` --- - -DROP TABLE IF EXISTS `v_encajado`; -/*!50001 DROP VIEW IF EXISTS `v_encajado`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_encajado` AS SELECT - 1 AS `hora`, - 1 AS `minuto`, - 1 AS `cm3`, - 1 AS `warehouse_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_encajado_ultima_hora` --- - -DROP TABLE IF EXISTS `v_encajado_ultima_hora`; -/*!50001 DROP VIEW IF EXISTS `v_encajado_ultima_hora`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_encajado_ultima_hora` AS SELECT - 1 AS `m3`, - 1 AS `warehouse_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_expeditions_shipping_charge` --- - -DROP TABLE IF EXISTS `v_expeditions_shipping_charge`; -/*!50001 DROP VIEW IF EXISTS `v_expeditions_shipping_charge`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_expeditions_shipping_charge` AS SELECT - 1 AS `Id_Ticket`, - 1 AS `shipping_charge`, - 1 AS `Fecha`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_expeditions_shipping_charge2` --- - -DROP TABLE IF EXISTS `v_expeditions_shipping_charge2`; -/*!50001 DROP VIEW IF EXISTS `v_expeditions_shipping_charge2`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_expeditions_shipping_charge2` AS SELECT - 1 AS `Id_Ticket`, - 1 AS `shipping_charge`, - 1 AS `Fecha`, - 1 AS `warehouse_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_fallo` --- - -DROP TABLE IF EXISTS `v_fallo`; -/*!50001 DROP VIEW IF EXISTS `v_fallo`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_fallo` AS SELECT - 1 AS `queja_id`, - 1 AS `accion_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_inter` --- - -DROP TABLE IF EXISTS `v_inter`; -/*!50001 DROP VIEW IF EXISTS `v_inter`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_inter` AS SELECT - 1 AS `inter_id`, - 1 AS `state_id`, - 1 AS `nota`, - 1 AS `odbc_date`, - 1 AS `Id_Ticket`, - 1 AS `Id_Trabajador`, - 1 AS `Id_supervisor`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_jerarquia` --- - -DROP TABLE IF EXISTS `v_jerarquia`; -/*!50001 DROP VIEW IF EXISTS `v_jerarquia`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_jerarquia` AS SELECT - 1 AS `Id_Trabajador`, - 1 AS `boss_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_location` --- - -DROP TABLE IF EXISTS `v_location`; -/*!50001 DROP VIEW IF EXISTS `v_location`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_location` AS SELECT - 1 AS `longitude`, - 1 AS `latitude`, - 1 AS `Id_Consigna`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_mana_spellers` --- - -DROP TABLE IF EXISTS `v_mana_spellers`; -/*!50001 DROP VIEW IF EXISTS `v_mana_spellers`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_mana_spellers` AS SELECT - 1 AS `Id_Trabajador`, - 1 AS `size`, - 1 AS `used`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_miriam` --- - -DROP TABLE IF EXISTS `v_miriam`; -/*!50001 DROP VIEW IF EXISTS `v_miriam`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_miriam` AS SELECT - 1 AS `Id_Article`, - 1 AS `Concepte`, - 1 AS `Cantidad`, - 1 AS `Preu`, - 1 AS `Descuento`, - 1 AS `Fecha`, - 1 AS `Id_Cliente`, - 1 AS `Importe`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_movimientos_log` --- - -DROP TABLE IF EXISTS `v_movimientos_log`; -/*!50001 DROP VIEW IF EXISTS `v_movimientos_log`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_movimientos_log` AS SELECT - 1 AS `idmovimientos_log`, - 1 AS `Id_Movimiento`, - 1 AS `odbc_date`, - 1 AS `Id_Trabajador`, - 1 AS `field_name`, - 1 AS `new_value`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_movimientos_mark` --- - -DROP TABLE IF EXISTS `v_movimientos_mark`; -/*!50001 DROP VIEW IF EXISTS `v_movimientos_mark`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_movimientos_mark` AS SELECT - 1 AS `Id_Movimiento`, - 1 AS `Accion`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_pedidos_auto_preparados` --- - -DROP TABLE IF EXISTS `v_pedidos_auto_preparados`; -/*!50001 DROP VIEW IF EXISTS `v_pedidos_auto_preparados`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_pedidos_auto_preparados` AS SELECT - 1 AS `CodigoTrabajador`, - 1 AS `Id_Ticket`, - 1 AS `Momento`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_pedidos_auto_preparadoskk` --- - -DROP TABLE IF EXISTS `v_pedidos_auto_preparadoskk`; -/*!50001 DROP VIEW IF EXISTS `v_pedidos_auto_preparadoskk`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_pedidos_auto_preparadoskk` AS SELECT - 1 AS `CodigoTrabajador`, - 1 AS `Fecha`, - 1 AS `Id_Ticket`, - 1 AS `Momento`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_phonebook` --- - -DROP TABLE IF EXISTS `v_phonebook`; -/*!50001 DROP VIEW IF EXISTS `v_phonebook`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_phonebook` AS SELECT - 1 AS `Id_Cliente`, - 1 AS `Telefono`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_price_fixed` --- - -DROP TABLE IF EXISTS `v_price_fixed`; -/*!50001 DROP VIEW IF EXISTS `v_price_fixed`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_price_fixed` AS SELECT - 1 AS `warehouse_id`, - 1 AS `item_id`, - 1 AS `rate_0`, - 1 AS `rate_1`, - 1 AS `rate_2`, - 1 AS `rate_3`, - 1 AS `date_start`, - 1 AS `date_end`, - 1 AS `bonus`, - 1 AS `grouping`, - 1 AS `Packing`, - 1 AS `caja`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_price_fixed_group` --- - -DROP TABLE IF EXISTS `v_price_fixed_group`; -/*!50001 DROP VIEW IF EXISTS `v_price_fixed_group`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_price_fixed_group` AS SELECT - 1 AS `warehouse_id`, - 1 AS `item_id`, - 1 AS `rate_0`, - 1 AS `rate_1`, - 1 AS `rate_2`, - 1 AS `rate_3`, - 1 AS `date_start`, - 1 AS `date_end`, - 1 AS `bonus`, - 1 AS `grouping`, - 1 AS `Packing`, - 1 AS `caja`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_session` --- - -DROP TABLE IF EXISTS `v_session`; -/*!50001 DROP VIEW IF EXISTS `v_session`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_session` AS SELECT - 1 AS `id`, - 1 AS `CodigoTrabajador`, - 1 AS `Id_Trabajador`, - 1 AS `Id_Cliente`, - 1 AS `Cliente`, - 1 AS `Fecha`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_ticket_amount` --- - -DROP TABLE IF EXISTS `v_ticket_amount`; -/*!50001 DROP VIEW IF EXISTS `v_ticket_amount`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_ticket_amount` AS SELECT - 1 AS `Id_Ticket`, - 1 AS `amount`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_trabajadores` --- - -DROP TABLE IF EXISTS `v_trabajadores`; -/*!50001 DROP VIEW IF EXISTS `v_trabajadores`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_trabajadores` AS SELECT - 1 AS `CodigoTrabajador`, - 1 AS `Nombre`, - 1 AS `Fecha_Inicio`, - 1 AS `Password`, - 1 AS `user`, - 1 AS `Apellidos`, - 1 AS `Id_Trabajador`, - 1 AS `Foto`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_user` --- - -DROP TABLE IF EXISTS `v_user`; -/*!50001 DROP VIEW IF EXISTS `v_user`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_user` AS SELECT - 1 AS `id`, - 1 AS `mysql_user_id`, - 1 AS `name`, - 1 AS `password`, - 1 AS `active`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_ventes` --- - -DROP TABLE IF EXISTS `v_ventes`; -/*!50001 DROP VIEW IF EXISTS `v_ventes`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_ventes` AS SELECT - 1 AS `Agencia`, - 1 AS `Categoria`, - 1 AS `tipo_id`, - 1 AS `Medida`, - 1 AS `Article`, - 1 AS `Color`, - 1 AS `Id_Cliente`, - 1 AS `Tipo`, - 1 AS `Factura`, - 1 AS `warehouse_id`, - 1 AS `Id_Movimiento`, - 1 AS `Id_Article`, - 1 AS `Familia`, - 1 AS `Id_Ticket`, - 1 AS `Concepte`, - 1 AS `Cantidad`, - 1 AS `quantity`, - 1 AS `Preu`, - 1 AS `Descuento`, - 1 AS `CostFixat`, - 1 AS `Reservado`, - 1 AS `OK`, - 1 AS `PrecioFijado`, - 1 AS `odbc_date`, - 1 AS `Fecha`, - 1 AS `FechaCompleta`, - 1 AS `Alias`, - 1 AS `Id_Consigna`, - 1 AS `Importe`, - 1 AS `Origen`, - 1 AS `reino_id`, - 1 AS `invoice`, - 1 AS `producer_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_venteskk` --- - -DROP TABLE IF EXISTS `v_venteskk`; -/*!50001 DROP VIEW IF EXISTS `v_venteskk`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_venteskk` AS SELECT - 1 AS `Agencia`, - 1 AS `Categoria`, - 1 AS `tipo_id`, - 1 AS `Medida`, - 1 AS `Article`, - 1 AS `Color`, - 1 AS `Id_Cliente`, - 1 AS `Tipo`, - 1 AS `Factura`, - 1 AS `warehouse_id`, - 1 AS `Id_Movimiento`, - 1 AS `Id_Article`, - 1 AS `Familia`, - 1 AS `Id_Ticket`, - 1 AS `Concepte`, - 1 AS `Cantidad`, - 1 AS `quantity`, - 1 AS `Preu`, - 1 AS `Descuento`, - 1 AS `CostFixat`, - 1 AS `Reservado`, - 1 AS `OK`, - 1 AS `PrecioFijado`, - 1 AS `odbc_date`, - 1 AS `Fecha`, - 1 AS `FechaCompleta`, - 1 AS `Alias`, - 1 AS `Id_Consigna`, - 1 AS `Importe`, - 1 AS `Origen`, - 1 AS `reino_id`, - 1 AS `invoice`, - 1 AS `producer_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_warehouse` --- - -DROP TABLE IF EXISTS `v_warehouse`; -/*!50001 DROP VIEW IF EXISTS `v_warehouse`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_warehouse` AS SELECT - 1 AS `id`, - 1 AS `almacen`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_xsubclien` --- - -DROP TABLE IF EXISTS `v_xsubclien`; -/*!50001 DROP VIEW IF EXISTS `v_xsubclien`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_xsubclien` AS SELECT - 1 AS `Id_Cliente`, - 1 AS `empresa_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_xsubcuentas` --- - -DROP TABLE IF EXISTS `v_xsubcuentas`; -/*!50001 DROP VIEW IF EXISTS `v_xsubcuentas`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_xsubcuentas` AS SELECT - 1 AS `COD`, - 1 AS `TITULO`, - 1 AS `NIF`, - 1 AS `DOMICILIO`, - 1 AS `POBLACION`, - 1 AS `PROVINCIA`, - 1 AS `CODPOSTAL`, - 1 AS `country_code`, - 1 AS `empresa_id`, - 1 AS `EMAIL`, - 1 AS `IDNIF`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_xsubprov` --- - -DROP TABLE IF EXISTS `v_xsubprov`; -/*!50001 DROP VIEW IF EXISTS `v_xsubprov`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_xsubprov` AS SELECT - 1 AS `proveedor_id`, - 1 AS `empresa_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `versiones` --- - -DROP TABLE IF EXISTS `versiones`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `versiones` ( - `programa` varchar(11) COLLATE utf8_unicode_ci NOT NULL, - `version` int(11) NOT NULL, - `critical` tinyint(4) NOT NULL DEFAULT '0', - PRIMARY KEY (`programa`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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) COLLATE utf8_unicode_ci NOT NULL, - `zona` tinyint(4) NOT NULL DEFAULT '2', - `m_t` tinyint(4) NOT NULL DEFAULT '0', - `POBLACION` varchar(25) COLLATE utf8_unicode_ci NOT NULL, - `PROVINCIA` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`codigo_postal`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `vnCreditClassification` --- - -DROP TABLE IF EXISTS `vnCreditClassification`; -/*!50001 DROP VIEW IF EXISTS `vnCreditClassification`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `vnCreditClassification` AS SELECT - 1 AS `id`, - 1 AS `client`, - 1 AS `dateStart`, - 1 AS `dateEnd`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `vnCreditInsurance` --- - -DROP TABLE IF EXISTS `vnCreditInsurance`; -/*!50001 DROP VIEW IF EXISTS `vnCreditInsurance`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `vnCreditInsurance` AS SELECT - 1 AS `id`, - 1 AS `creditClassification`, - 1 AS `credit`, - 1 AS `creationDate`, - 1 AS `grade`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `vnSolunionCAP` --- - -DROP TABLE IF EXISTS `vnSolunionCAP`; -/*!50001 DROP VIEW IF EXISTS `vnSolunionCAP`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `vnSolunionCAP` AS SELECT - 1 AS `creditInsurance`, - 1 AS `dateStart`, - 1 AS `dateEnd`, - 1 AS `dateLeaving`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `warehouse` --- - -DROP TABLE IF EXISTS `warehouse`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `warehouse` ( - `id` smallint(6) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `fuente` tinyint(1) unsigned NOT NULL DEFAULT '0', - `address_name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `delay` double NOT NULL DEFAULT '0.004', - `reserve` tinyint(4) NOT NULL DEFAULT '0', - `tpv` tinyint(2) unsigned zerofill NOT NULL DEFAULT '00', - `Id_Paises` mediumint(8) unsigned NOT NULL DEFAULT '1', - `zone_label` tinyint(4) NOT NULL DEFAULT '0', - `comisionantes` tinyint(4) NOT NULL DEFAULT '0', - `inventario` tinyint(2) NOT NULL DEFAULT '0', - `is_comparative` tinyint(2) NOT NULL DEFAULT '0' COMMENT 'Si esta a true,en la comparativa muestra el stock de este almacen, cuando no se especifica almacen.', - `valuatedInventory` tinyint(2) NOT NULL DEFAULT '0', - `isManaged` tinyint(2) NOT NULL DEFAULT '0' COMMENT 'Se añaden los cubos de expedition a la tabla ticketPackaging', - `hasConfectionTeam` tinyint(1) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - UNIQUE KEY `name_UNIQUE` (`name`), - KEY `Id_Paises` (`Id_Paises`), - CONSTRAINT `warehouse_ibfk_1` FOREIGN KEY (`Id_Paises`) REFERENCES `Paises` (`Id`) -) ENGINE=InnoDB AUTO_INCREMENT=56 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `warehouse_ai` AFTER INSERT ON `warehouse` FOR EACH ROW -begin - IF NEW.Fuente THEN - INSERT INTO warehouse_alias (alias) VALUES(NEW.`name`); - INSERT INTO warehouse_joined(warehouse_id,warehouse_alias_id) - VALUES(NEW.id,LAST_INSERT_ID()); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `warehouse_au` AFTER UPDATE ON `warehouse` FOR EACH ROW -begin - IF NEW.fuente IS TRUE and OLD.fuente IS FALSE then - INSERT INTO warehouse_alias (alias) VALUES(NEW.`name`); - INSERT INTO warehouse_joined(warehouse_id,warehouse_alias_id) - VALUES(NEW.id,LAST_INSERT_ID()); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `warehouse_alias` --- - -DROP TABLE IF EXISTS `warehouse_alias`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `warehouse_alias` ( - `warehouse_alias_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `alias` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`warehouse_alias_id`) -) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla que permite filtrar los almacenes que muestra la comparativa, recordando la selección personal del usuario'; -/*!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 `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `warehouse_group_alias` FOREIGN KEY (`warehouse_alias_id`) REFERENCES `warehouse_alias` (`warehouse_alias_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Agrupa warehouses '; -/*!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 `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- 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 `warehouse` (`id`) ON UPDATE CASCADE, - CONSTRAINT `whout_wh` FOREIGN KEY (`whout`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Warehouses cost for linking'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `warehouse_pickup` --- - -DROP TABLE IF EXISTS `warehouse_pickup`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `warehouse_pickup` ( - `warehouse_id` smallint(5) unsigned NOT NULL, - `agency_id` int(11) DEFAULT NULL, - PRIMARY KEY (`warehouse_id`), - UNIQUE KEY `agency_id` (`agency_id`,`warehouse_id`), - CONSTRAINT `warehouse_pickup_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `warehouse_pickup_ibfk_2` FOREIGN KEY (`agency_id`) REFERENCES `Agencias` (`Id_Agencia`) ON DELETE SET NULL ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `warehouse_tree_bidi` --- - -DROP TABLE IF EXISTS `warehouse_tree_bidi`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `warehouse_tree_bidi` ( - `father` tinyint(1) unsigned NOT NULL, - `son` tinyint(1) unsigned NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 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(11) 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 `Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE, - CONSTRAINT `Warehouse` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Permite que los usuarios seleccionen los almacenes que van a'; -/*!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=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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 COLLATE utf8_unicode_ci, - PRIMARY KEY (`id`) USING BTREE -) ENGINE=InnoDB AUTO_INCREMENT=626 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `workcenter_holiday` --- - -DROP TABLE IF EXISTS `workcenter_holiday`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `workcenter_holiday` ( - `workcenter_id` int(11) NOT NULL, - `day` double NOT NULL, - `year` smallint(6) NOT NULL, - PRIMARY KEY (`workcenter_id`,`day`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `workerDocument` --- - -DROP TABLE IF EXISTS `workerDocument`; -/*!50001 DROP VIEW IF EXISTS `workerDocument`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `workerDocument` AS SELECT - 1 AS `id`, - 1 AS `worker`, - 1 AS `document`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `workerTeam` --- - -DROP TABLE IF EXISTS `workerTeam`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `workerTeam` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `team` int(11) NOT NULL, - `user` int(10) unsigned NOT NULL, - PRIMARY KEY (`id`), - KEY `user_team_idx` (`user`), - CONSTRAINT `user_team` FOREIGN KEY (`user`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=124 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `workerTeamCollegues` --- - -DROP TABLE IF EXISTS `workerTeamCollegues`; -/*!50001 DROP VIEW IF EXISTS `workerTeamCollegues`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `workerTeamCollegues` AS SELECT - 1 AS `workerId`, - 1 AS `collegueId`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `workerTeam_kk` --- - -DROP TABLE IF EXISTS `workerTeam_kk`; -/*!50001 DROP VIEW IF EXISTS `workerTeam_kk`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `workerTeam_kk` AS SELECT - 1 AS `team`, - 1 AS `user`, - 1 AS `id`, - 1 AS `Id_Trabajador`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `zeleris` --- - -DROP TABLE IF EXISTS `zeleris`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `zeleris` ( - `codigo_postal` mediumint(8) unsigned NOT NULL, - `franja` tinyint(3) unsigned NOT NULL, - PRIMARY KEY (`codigo_postal`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `zoneNickname` --- - -DROP TABLE IF EXISTS `zoneNickname`; -/*!50001 DROP VIEW IF EXISTS `zoneNickname`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `zoneNickname` AS SELECT - 1 AS `warehouse_id`, - 1 AS `agency_id`, - 1 AS `zona`, - 1 AS `alias`*/; -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) COLLATE utf8_unicode_ci NOT NULL, - `printingOrder` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`zone_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Zonas de reparto'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'vn2008' --- -/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `cierre automatico` */; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `cierre automatico` ON SCHEDULE EVERY 1 DAY STARTS '2016-05-25 23:00:00' ON COMPLETION NOT PRESERVE DISABLE COMMENT 'Realiza el cierre de todos los Warehouse' DO INSERT INTO `vn2008`.`Colas` (`Id_Informe`,`Cola`) VALUES ('2',CURDATE()) */ ;; -/*!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 `closeTickets` */;; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `closeTickets` ON SCHEDULE EVERY 1 DAY STARTS '2017-06-23 07:20:00' ON COMPLETION NOT PRESERVE DISABLE COMMENT 'Vuelve a realizar el cierre del dia anterior por la mañana.' DO INSERT INTO `vn2008`.`Colas` (`Id_Informe`,`Cola`) VALUES ('2',DATE_ADD(CURDATE(), INTERVAL -1 DAY)) */ ;; -/*!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 `item_cache_cleaner` */;; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `item_cache_cleaner` ON SCHEDULE EVERY 30 SECOND STARTS '2014-06-30 13:38:27' ON COMPLETION NOT PRESERVE DISABLE COMMENT 'Cleans the item cache' DO CALL item_cache_cleaner () */ ;; -/*!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 `raidUpdate` */;; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8 */ ;; -/*!50003 SET character_set_results = utf8 */ ;; -/*!50003 SET collation_connection = utf8_general_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `raidUpdate` ON SCHEDULE EVERY 1 DAY STARTS '2017-12-29 00:05:00' ON COMPLETION PRESERVE ENABLE DO CALL raidUpdate */ ;; -/*!50003 SET time_zone = @saved_time_zone */ ;; -/*!50003 SET sql_mode = @saved_sql_mode */ ;; -/*!50003 SET character_set_client = @saved_cs_client */ ;; -/*!50003 SET character_set_results = @saved_cs_results */ ;; -/*!50003 SET collation_connection = @saved_col_connection */ ;; -DELIMITER ; -/*!50106 SET TIME_ZONE= @save_time_zone */ ; - --- --- Dumping routines for database 'vn2008' --- -/*!50003 DROP FUNCTION IF EXISTS `articod` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `articod`(intArt INT) RETURNS varchar(70) CHARSET utf8 COLLATE utf8_unicode_ci -BEGIN - DECLARE strArt VARCHAR(70); - SELECT CONCAT(Article,' ', Medida, ' ',Color) INTO strArt FROM Articles WHERE Id_Article = intArt; - - RETURN strArt; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `asiento` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `asiento`( - v_asiento INT - ,v_date DATE - ,v_subaccount VARCHAR(12) - ,v_account VARCHAR(12) - ,v_concept VARCHAR(25) - ,v_debit DOUBLE - ,v_credit DOUBLE - ,v_euro DOUBLE - ,v_serial CHAR(1) - ,v_invoice VARCHAR(8) - ,v_vat DOUBLE - ,v_re DOUBLE - ,v_aux TINYINT - ,v_company INT -) RETURNS int(11) -BEGIN - IF v_asiento IS NULL - THEN - SELECT MAX(ASIEN) + 1 INTO v_asiento FROM XDiario FOR UPDATE; - END IF; - - INSERT INTO XDiario - SET - ASIEN = v_asiento - ,FECHA = v_date - ,SUBCTA = v_subaccount - ,CONTRA = v_account - ,CONCEPTO = v_concept - ,EURODEBE = v_debit - ,EUROHABER = v_credit - ,BASEEURO = v_euro - ,SERIE = v_serial - ,FACTURA = v_invoice - ,IVA = v_vat - ,RECEQUIV = v_re - ,AUXILIAR = IF(v_aux = FALSE, NULL, '*') - ,MONEDAUSO = 2 - ,empresa_id = v_company; - - RETURN v_asiento; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `Averiguar_ComercialCliente` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `Averiguar_ComercialCliente`(v_customer INT, v_date DATE) RETURNS varchar(3) CHARSET utf8 - DETERMINISTIC -BEGIN -/** - * Dado un id cliente y una fecha, devuelve su comercial. - * Para más información ir a Averiguar_ComercialCliente_Id() - * - * @param v_customer El id del cliente - * @param v_date Fecha a comprobar - * @return El código del comercial para la fecha dada - **/ - DECLARE v_employee CHAR(3); - DECLARE v_salesperson INT; - - SET v_salesperson = Averiguar_ComercialCliente_Id(v_customer, v_date); - - SELECT CodigoTrabajador - INTO v_employee - FROM Trabajadores - WHERE Id_Trabajador = v_salesperson; - - RETURN IFNULL(v_employee, '---'); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `Averiguar_ComercialCliente_Id` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `Averiguar_ComercialCliente_Id`(v_customer INT, v_date DATE) RETURNS int(11) - DETERMINISTIC -BEGIN -/** - * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo - * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de - * sharingcart y tercero la de clientes. - * - * @param v_customer El id del cliente - * @param v_date Fecha a comprobar - * @return El id del comercial para la fecha dada - **/ - DECLARE v_salesperson INT DEFAULT NULL; - DECLARE v_substitute INT DEFAULT NULL; - DECLARE v_loop BOOLEAN; - - -- Obtiene el comercial original y el de sharingclient - - SELECT c.Id_Trabajador, s.Id_Trabajador - INTO v_salesperson, v_substitute - FROM Clientes c - LEFT JOIN sharingclient s - ON c.Id_Cliente = s.Id_Cliente - AND v_date BETWEEN s.datSTART AND s.datEND - WHERE c.Id_Cliente = v_customer - ORDER BY s.id - LIMIT 1; - - -- Si no hay ninguno en sharingclient busca en sharingcart - - IF v_substitute IS NOT NULL - THEN - SET v_salesperson = v_substitute; - ELSEIF v_salesperson IS NOT NULL - THEN - DROP TEMPORARY TABLE IF EXISTS tmp.stack; - CREATE TEMPORARY TABLE tmp.stack - (INDEX (substitute)) - ENGINE = MEMORY - SELECT v_salesperson substitute; - - l: LOOP - SELECT Id_Suplente INTO v_substitute - FROM sharingcart - WHERE v_date BETWEEN datSTART AND datEND - AND Id_Trabajador = v_salesperson - ORDER BY id - LIMIT 1; - - IF v_substitute IS NULL THEN - LEAVE l; - END IF; - - SELECT COUNT(*) > 0 INTO v_loop - FROM tmp.stack WHERE substitute = v_substitute; - - IF v_loop THEN - LEAVE l; - END IF; - - INSERT INTO tmp.stack SET - substitute = v_substitute; - - SET v_salesperson = v_substitute; - END LOOP; - - DROP TEMPORARY TABLE tmp.stack; - END IF; - - RETURN v_salesperson; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `Averiguar_ComercialCliente_IdTicket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `Averiguar_ComercialCliente_IdTicket`(v_ticket INT) RETURNS varchar(3) CHARSET utf8 - DETERMINISTIC -BEGIN -/** - * Dado un id ticket, devuelve su comercial. - * Para más información ir a Averiguar_ComercialCliente_Id() - * - * @param v_customer El id del cliente - * @param v_date Fecha a comprobar - * @return El código del comercial para la fecha dada - **/ - DECLARE v_customer INT; - DECLARE v_date DATE; - - SELECT id_cliente, fecha - INTO v_customer, v_date - FROM Tickets WHERE id_ticket = v_ticket; - - RETURN Averiguar_ComercialCliente(v_customer, v_date); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `Averiguar_ComercialCliente_IdTicket_Id` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `Averiguar_ComercialCliente_IdTicket_Id`(v_ticket INT) RETURNS int(11) - DETERMINISTIC -BEGIN -/** - * Dado un id ticket, devuelve su comercial. - * Para más información ir a Averiguar_ComercialCliente_Id() - * - * @param v_customer El id del cliente - * @param v_date Fecha a comprobar - * @return El id del comercial para la fecha dada - **/ - DECLARE v_customer INT; - DECLARE v_date DATE; - - SELECT id_cliente, fecha - INTO v_customer, v_date - FROM Tickets WHERE id_ticket = v_ticket; - - RETURN Averiguar_ComercialCliente_Id(v_customer, v_date); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `Averiguar_Comprador` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `Averiguar_Comprador`(idARTICLE INT) RETURNS varchar(3) CHARSET utf8 -BEGIN - --- Devuelve la abreviatura del comprador del articulo - -DECLARE buyer VARCHAR(3); - -SELECT CodigoTrabajador INTO buyer -FROM Trabajadores t -JOIN Tipos tp on tp.Id_Trabajador = t.Id_Trabajador -JOIN Articles a on a.tipo_id = tp.tipo_id -WHERE Id_Article = idARTICLE; - - -RETURN buyer; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `base_ticket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `base_ticket`(Id_Ticket INT) RETURNS double -BEGIN - - DECLARE base DOUBLE; - SELECT - red(SUM(Cantidad * Preu * (100 - Descuento) / 100)) into base - FROm - Movimientos m - INNER JOIN Tickets t USING (Id_Ticket) - WHERE t.Id_Ticket = Id_Ticket; - -RETURN base; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `bionicCalcReverse` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `bionicCalcReverse`(vWarehouse INT, - vMargin DECIMAL(10,3), - vRetailedPrice DECIMAL(10,3), - vM3 DECIMAL(10,3), - vConsigna INT, - vAgencia INT) RETURNS decimal(10,3) -BEGIN - DECLARE COEFICIENTE_DE_INFLACION_GENERAL INT DEFAULT 1.3; - DECLARE DENSIDAD_MINIMA_PESO_VOLUMETRICO INT DEFAULT 167; - DECLARE VOLUMEN_CAJA_VERDNATURA BIGINT DEFAULT 138000; - DECLARE vCost DECIMAL(10,4) DEFAULT 0; - DECLARE vCustomer INT; - DECLARE vRecovery DECIMAL(10,4) DEFAULT 0; - DECLARE vMana DECIMAL(10,4) DEFAULT 0; - DECLARE vPort DECIMAL(10,4) DEFAULT 0; - - SELECT Id_Cliente INTO vCustomer FROM Consignatarios WHERE Id_Consigna = vConsigna; - - -- Recobro - SELECT ROUND(LEAST(recobro,0.25), 3) INTO vRecovery - FROM bi.claims_ratio - WHERE Id_Cliente = vCustomer AND recobro > 0.009; - - -- Componente de maná automático, en función del maná acumulado por el comercial. - SELECT ROUND(prices_modifier_rate, 3) INTO vMana - FROM Clientes c - JOIN bs.mana_spellers ms ON c.Id_Trabajador = ms.Id_Trabajador - WHERE ms.prices_modifier_activated AND c.Id_Cliente = vCustomer; - - -- Reparto - SELECT COEFICIENTE_DE_INFLACION_GENERAL - * ROUND( - vM3 - * az.price - * az.inflacion - / VOLUMEN_CAJA_VERDNATURA, 4 - ) INTO vPort - FROM vn2008.Agencias a - JOIN vn2008.Consignatarios c ON c.Id_Consigna = vConsigna AND a.Id_Agencia = vAgencia - JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = vWarehouse AND ap.province_id = c.province_id - JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = vAgencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = vWarehouse; - - -- Modificacion de precio por dia de preparacion del pedido - -- No aplicada - - SET vCost = ((vRetailedPrice - vPort) / ( 1 + (vRecovery + vMana))) - vMargin; - - RETURN vCost; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `botanic_export_is_updatable` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `botanic_export_is_updatable`(v_edi_genus_id MEDIUMINT,v_edi_specie_id MEDIUMINT,v_id_Paises MEDIUMINT,v_restriction MEDIUMINT) RETURNS int(11) -BEGIN - DECLARE is_updatable INTEGER; - SELECT COUNT(*) INTO is_updatable FROM botanic_export - WHERE edi_genus_id = v_edi_genus_id - AND (v_edi_specie_id = edi_specie_id OR IFNULL(v_edi_specie_id,edi_specie_id) IS NULL) - AND (v_id_Paises = Id_Paises OR IFNULL(v_id_Paises,Id_Paises) IS NULL) - AND v_restriction = restriction; -RETURN is_updatable; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `buffer_name` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `buffer_name`(v_date DATE, v_wh INT) RETURNS varchar(11) CHARSET utf8 -BEGIN - RETURN CONCAT('b', YEAR(v_date), MONTH(v_date), DAY(v_date), IFNULL(v_wh, 0)); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `buyingAbsoluteCost` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `buyingAbsoluteCost`(vCompra BIGINT) RETURNS int(11) -BEGIN -/** - * Devuelve el coste completo de una compra - * - * @param vCompra Id_Compra a calcular - * @return Suma de los 4 componentes del coste - */ - -DECLARE vCost DOUBLE; - -SELECT IFNULL(Costefijo,0) + IFNULL(Portefijo,0) + IFNULL(Embalajefijo,0) + IFNULL(Comisionfija,0) -INTO vCost -FROM Compres -WHERE Id_Compra = vCompra; - -RETURN vCost; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `cc_to_iban` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `cc_to_iban`(cc VARCHAR(20)) RETURNS varchar(4) CHARSET utf8 - DETERMINISTIC -BEGIN - DECLARE iban VARCHAR(4); - select - CONCAT('ES', - RIGHT( - concat(0, - 98- - mod( - concat( - mod( - concat( - mod( - concat( - mod( - substring(cc,1,8), - 97), - substring(cc,9,8) - ), - 97), - substring( - concat( - cc, - 142800 - ), - 17, - 8 - ) - ), - 97), - substring( - concat( - cc, - 142800 - ), - 25, - 2 - ) - ), - 97) - ) - ,2) - )into iban; -RETURN iban; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `cm3` */; -/*!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 = latin1 */ ; -/*!50003 SET character_set_results = latin1 */ ; -/*!50003 SET collation_connection = latin1_swedish_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `cm3`(v_buy_id INT) RETURNS int(11) -BEGIN - DECLARE id_CUB VARCHAR(10); - DECLARE id_ART INT; - SELECT Id_Cubo, Id_Article INTO id_CUB, id_ART - FROM Compres c - WHERE c.Id_compra = v_buy_id; - - RETURN cm3_2(id_CUB, id_ART); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `cm3_2` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `cm3_2`(id_CUB VARCHAR(10), id_ART INT) RETURNS int(11) -BEGIN - DECLARE v_cm3 INT; - - SELECT SUM(IF(b.Volumen > 0, - b.Volumen, - x * y * IF(z = 0, Medida + 10, z) - )) INTO v_cm3 - FROM Cubos b - INNER JOIN Articles a ON Id_Article = id_ART - WHERE Id_Cubo = id_CUB; - - RETURN v_cm3; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `cm3_unidad` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `cm3_unidad`(v_buy_id INT) RETURNS int(11) -BEGIN - DECLARE id_CUB VARCHAR(10); - DECLARE id_ART INT; - DECLARE intPACK INT; - - SELECT Id_Cubo, Id_Article, Packing INTO id_CUB, id_ART, intPACK - FROM Compres c - WHERE c.Id_compra = v_buy_id; - - RETURN ifnull(round(cm3_2(id_CUB, id_ART)/intPACK),0); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `code_to_id` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `code_to_id`(idART VARCHAR(22)) RETURNS int(11) - DETERMINISTIC -BEGIN - DECLARE idchecked INT; - - set idchecked = (SELECT Id_Article FROM barcodes WHERE code = idART); - - IF idchecked THEN - RETURN idchecked; - END IF; - - IF idART > 6000000 THEN - SELECT Id_Article INTO idchecked - FROM Compres WHERE Id_Compra = idART; - ELSE - SET idchecked = CAST(idART AS SIGNED); - END IF; - - RETURN idchecked; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `code_to_id2` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `code_to_id2`(idART VARCHAR(22)) RETURNS int(11) -BEGIN - DECLARE idchecked INT; - - SELECT IFNULL(Id_Article,COUNT(*)) INTO idchecked - FROM barcodes - WHERE code = idART LIMIT 1; - - IF idchecked THEN - RETURN idchecked; - END IF; - - IF idART > 6000000 THEN - /*SELECT Id_Article INTO idchecked - FROM Compres WHERE Id_Compra = idART;*/ - SET idchecked = CAST(idART AS SIGNED); - ELSE - SET idchecked = CAST(idART AS SIGNED); - END IF; - - RETURN idchecked; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `cub` */; -/*!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 = latin1 */ ; -/*!50003 SET character_set_results = latin1 */ ; -/*!50003 SET collation_connection = latin1_swedish_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `cub`(v_buy_id INT) RETURNS int(11) -BEGIN - DECLARE v_cm3 INT; - - SELECT SUM(Etiquetas * IF(b.Volumen > 0, - b.Volumen, - IF(z = 0, - x * y * (Medida + 10), - x * y * z - ) - )) INTO v_cm3 - FROM Compres c - INNER JOIN Cubos b USING (Id_Cubo) - INNER JOIN Articles a USING (Id_Article) - WHERE c.Id_compra = v_buy_id; - - RETURN v_cm3; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `currate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `currate`() RETURNS double -BEGIN - -DECLARE dblRATE DOUBLE; - -SELECT rate INTO dblRATE FROM reference_rate ORDER BY date DESC LIMIT 1 ; - -RETURN dblRATE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `date_inv` */; -/*!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 = latin1 */ ; -/*!50003 SET character_set_results = latin1 */ ; -/*!50003 SET collation_connection = latin1_swedish_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `date_inv`() RETURNS datetime - DETERMINISTIC -BEGIN - RETURN (SELECT FechaInventario FROM tblContadores 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 DROP FUNCTION IF EXISTS `DAYEND` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `DAYEND`(v_date DATE) RETURNS datetime - DETERMINISTIC -BEGIN - RETURN TIMESTAMP(v_date,'23:59:59'); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `FIRSTDAYOFYEAR` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `FIRSTDAYOFYEAR`(datFEC DATE) RETURNS date -BEGIN - -DECLARE datRETURNS DATE; - -SELECT TIMESTAMPADD(DAY, -1 * DAYOFYEAR(datFEC) + 1, datFEC) INTO datRETURNS; - -RETURN datRETURNS; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `f_periodo` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `f_periodo`(datFEC date) RETURNS int(7) - DETERMINISTIC -BEGIN -DECLARE intPeriod INT; - -SELECT Year(datFEC) * 100 + week(datFEC) into intPeriod; - -RETURN intPeriod; - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `getBouquetId` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getBouquetId`( - vName VARCHAR(50), - vType int, - vSize int, - vColour VARCHAR(5) -) RETURNS int(11) -BEGIN -/** - * De vuelve el ID del ramo. Si no existe uno parecido, lo crea. - * - * @param vName Nombre del artículo - * @param vType Tipo de flor/planta - * @param vSize Tamaño del ramo - * @param vColour Color del ramo - * @return ID del ramo - */ - DECLARE bouquetId INT(11); - - CALL vn2008.createBouquet(vName, vType, vSize, vColour, @vItem); - - SET bouquetId = (SELECT @vItem); - -RETURN bouquetId; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `getComision` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getComision`(vEntry INT, vMoneda INT) RETURNS int(11) -BEGIN - - DECLARE vComision INT; - - SELECT IFNULL(round(-100 * (1 - (1 / rm.rate))),0) INTO vComision - FROM Entradas e - JOIN travel tr ON tr.id = e.travel_id - LEFT JOIN reference_min rm ON rm.moneda_id = vMoneda AND tr.shipment >= rm.`date` - WHERE e.Id_Entrada = vEntry - ORDER BY rm.date DESC - LIMIT 1; - - RETURN vComision; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `getInvoiceWeight` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getInvoiceWeight`(vInvoice VARCHAR(15)) RETURNS decimal(10,2) -BEGIN - DECLARE vTotalWeight DECIMAL(10,2); - - SELECT SUM(IFNULL(tallos,1) * Cantidad * a.density) sumTotal - INTO vTotalWeight FROM Tickets t - LEFT JOIN Movimientos m ON m.Id_Ticket = t.Id_Ticket - LEFT JOIN Articles a ON a.Id_Article = m.Id_Article - LEFT JOIN Tipos tp ON tp.tipo_id = a.tipo_id - WHERE t.Factura = vInvoice AND Codintrastat; - RETURN vTotalWeight; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `getShippingFromTicket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getShippingFromTicket`(vTicket INTEGER) RETURNS decimal(10,2) -BEGIN - DECLARE vValue DECIMAL(10,2); - SELECT - SUM(Valor * m.Cantidad) INTO vValue - FROM - Movimientos_componentes mc - JOIN - Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN - bi.tarifa_componentes tc ON mc.Id_Componente = tc.Id_Componente - JOIN - bi.tarifa_componentes_series tcs ON tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id - AND tcs.tarifa_componentes_series_id = 6 - - WHERE m.Id_Ticket = vTicket; - - RETURN vValue; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `get_special_price` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `get_special_price`(intArticle int(11),intCliente int(11)) RETURNS decimal(10,2) -BEGIN - DECLARE price DECIMAL(10,2); - - SELECT rate_3 INTO price FROM price_fixed WHERE item_id = intArticle AND CURDATE() BETWEEN date_start AND date_end order by odbc_date DESC limit 1; - - SELECT precioespecial INTO price FROM PreciosEspeciales WHERE Id_Article = intArticle and Id_Cliente = intCliente ; -RETURN price; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `get_Trabajador` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `get_Trabajador`() RETURNS int(11) - DETERMINISTIC -BEGIN - RETURN IFNULL((SELECT Id_Trabajador FROM Trabajadores WHERE user_id = account.userGetId()),20); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `has_notify_passport` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `has_notify_passport`(idA INT, idCompra INT) RETURNS tinyint(1) -BEGIN - DECLARE has_passport BOOLEAN; - DECLARE is_already_sent BOOLEAN; - - SELECT COUNT(*) INTO has_passport FROM vn2008.botanic_export be JOIN - vn2008.Articles_botanical ab ON be.edi_genus_id = ab.genus_id - AND IFNULL(be.edi_specie_id, ab.specie_id) = ab.specie_id - AND be.restriction = 'Se Requiere Certificado' - JOIN vn2008.Articles a ON a.Id_Article = ab.Id_Article - JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - WHERE ab.Id_Article = idA AND t.reino_id = 2; - - IF has_passport THEN - SELECT COUNT(*) INTO is_already_sent FROM mail M - JOIN vn2008.Compres c ON c.Id_Compra = idCompra - WHERE `text` LIKE CONCAT('%',c.buy_edi_id,'%') limit 1; - END IF; - RETURN has_passport && NOT is_already_sent; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `intrastat_neto` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `intrastat_neto`( intINSTRASTAT INTEGER,intUNIDADES INTEGER) RETURNS double -BEGIN - -DECLARE n DOUBLE; - -select ROUND(intUNIDADES / (sum(MEDIA) / count(media)),2) into n from ( -select *, unidades / neto MEDIA FROM intrastat_data WHERE intrastat_id = intINSTRASTAT and neto and unidades > 0 ORDER BY odbc_date DESC limit 50) t; --- JGF 01/06 per a evitar Kg en negatiu -RETURN n/2; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `is_bionic` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `is_bionic`(intTicket INT) RETURNS tinyint(1) -BEGIN - DECLARE bolIsBionic boolean; - SELECT (COUNT(*) > 0) INTO bolIsBionic FROM order_Tickets ot - WHERE ot.Id_Ticket = intTicket; - RETURN bolIsBionic; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `lang` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `lang`() RETURNS char(2) CHARSET utf8 - DETERMINISTIC -BEGIN - RETURN IFNULL(@lang, 'es'); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `next_venc` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `next_venc`( datFecha DATE,intDia INT,intPayDay INT) RETURNS date -BEGIN - -DECLARE n DATE; -DECLARE datVenc DATE; -DECLARE intVenc INT; - - SELECT TIMESTAMPADD(DAY,intDia,datFecha) INTO datVenc; - SELECT DAY(datVenc) INTO intVenc; - - SELECT MIN(TIMESTAMPADD(MONTH,(intVenc > intPayDay),DATE_FORMAT(datVenc,CONCAT('%y/%m/',intPayDay)))) INTO n; -RETURN n; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `next_venctesting` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `next_venctesting`( datFecha DATE,intDia INT,intPayDay INT) RETURNS date -BEGIN - -DECLARE n DATE; -DECLARE datVenc DATE; -DECLARE intVenc INT; - - SELECT TIMESTAMPADD(DAY,intDia,datFecha) INTO datVenc; - SELECT DAY(datVenc) INTO intVenc; - - SELECT IFNULL - ( - TIMESTAMPADD - ( - MONTH, - (intVenc > intPayDay), - DATE_FORMAT - ( - datVenc, - CONCAT('%y/%m/',intPayDay) - ) - ), - LAST_DAY(datVenc) - ) INTO n; -RETURN n; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `nz` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `nz`(dblCANTIDAD DOUBLE) RETURNS double - DETERMINISTIC -BEGIN - - DECLARE dblRESULT DOUBLE; - - SET dblRESULT = IFNULL(dblCANTIDAD,0); - - RETURN dblRESULT; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `paymentday` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `paymentday`(vDated DATE, vDayToPay INT) RETURNS date -BEGIN - -DECLARE vDued DATE; - -SET vDued = vn.getDueDate(vDated, vDayToPay); - -RETURN vDued; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `periodo` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `periodo`(datFEC DATETIME) RETURNS int(6) - DETERMINISTIC -BEGIN - -DECLARE intPERIODO INt; - -SET intPERIODO = YEAR(datFEC) * 100 + MONTH(datFEC); - -RETURN intPERIODO; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `periodo_day` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `periodo_day`(datFEC DATETIME) RETURNS int(8) - DETERMINISTIC -BEGIN - -DECLARE intPERIODO INt; - -SET intPERIODO = YEAR(datFEC) * 10000 + MONTH(datFEC) * 100 + DAY(datFEC); - -RETURN intPERIODO; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `porte` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `porte`(intId_Ticket INT) RETURNS double -BEGIN - - - DECLARE dblprice DOUBLE; - SELECT - SUM(`az`.`price`) INTO dblprice - FROM - (((((`expeditions` `e` - JOIN `Tickets` `t` ON ((`e`.`ticket_id` = `t`.`Id_Ticket`))) - JOIN `Consignatarios` `c` ON ((`c`.`Id_Consigna` = `t`.`Id_Consigna`))) - JOIN `Agencias` `a` ON ((`a`.`Id_Agencia` = `t`.`Id_Agencia`))) - JOIN `Agencias_province` `ap` ON (((`t`.`warehouse_id` = `ap`.`warehouse_id`) - AND (`ap`.`province_id` = `c`.`province_id`) - AND (`ap`.`agency_id` = `a`.`agency_id`)))) - JOIN `Agencias_zonas` `az` ON (((`az`.`Id_Agencia` = `t`.`Id_Agencia`) - AND (`az`.`zona` = `ap`.`zona`) - AND (`t`.`warehouse_id` = `az`.`warehouse_id`) - AND (`az`.`Id_Article` = `e`.`EsBulto`)))) - WHERE - ((`t`.`Fecha` >= '2015-10-01') - AND (`t`.`empresa_id` IN (442 , 791))) AND t.Id_Ticket = intId_Ticket - GROUP BY `t`.`Id_Ticket`; - - RETURN dblprice; - -/* - DECLARE intId_Agencia INT; - DECLARE int_agency_id SMALLINT; - DECLARE int_province_id SMALLINT; - DECLARE bolCOD71 TINYINT(1); - DECLARE intPorte DOUBLE DEFAULT -1; - DECLARE dayofweek TINYINT(1) default 0; - DECLARE suplemento DOUBLE DEFAULT 9.41; - DECLARE strCodPostal VARCHAR(5); - DECLARE intWarehouse_id SMALLINT; - DECLARE dbldescuento DOUBLE DEFAULT 0; - DECLARE intVista TINYINT(1); - DECLARE dblvolumen DOUBLE; - - SET @porte := 0; - SELECT a.agency_id, t.Id_Agencia, cod71, Porte,c.CODPOSTAL,t.warehouse_id,c.province_id,cli.Descuento,IFNULL(ag.Vista,a.Vista), por_volumen - INTO int_agency_id,intId_Agencia, bolCOD71,intPorte,strCodPostal,intWarehouse_id,int_province_id,dbldescuento,intVista,dblvolumen - FROM Tickets t - JOIN Consignatarios c USING(Id_Consigna) - JOIN Agencias a ON t.Id_Agencia = a.Id_Agencia - JOIN agency agn ON agn.agency_id = a.agency_id - JOIN Clientes cli on c.Id_Cliente=cli.Id_Cliente - LEFT JOIN agency_warehouse ag ON ag.agency_id = a.agency_id - WHERE Id_Ticket = intId_Ticket limit 1; - - - - - IF bolCOD71 THEN - - IF intId_Agencia = 47 THEN -- Si es viaxpress - SELECT price INTO dblprice FROM Agencias_zonas az INNER JOIN viaxpress USING(zona) - WHERE Id_Agencia = 47 AND codigo_postal = strCodPostal AND az.warehouse_id = intWarehouse_id; - ELSE - SELECT price INTO dblprice FROM Agencias_zonas az - WHERE Id_Agencia = intId_Agencia AND 71 = Id_Article AND az.warehouse_id = intWarehouse_id - AND zona = (SELECT zona FROM Agencias_province - WHERE warehouse_id = intWarehouse_id AND agency_id = int_agency_id and province_id = int_province_id); - END IF; - - ELSE - SELECT 0 INTO dblprice; - END IF; - - */ - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `red` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `red`( intCANTIDAD DOUBLE) RETURNS double - DETERMINISTIC -BEGIN - - DECLARE n DOUBLE; - - SET n = SIGN(intCANTIDAD) * TRUNCATE( (ABS(intCANTIDAD) * 100) + 0.5001 ,0) /100 ; - - RETURN n; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `riskKk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `riskKk`(datMax DATE, intCustomer INT) RETURNS decimal(10,2) -BEGIN -/** - * Deprecated - * - * Utilizar vn.clientGetDebt - **/ - - DECLARE decRisk DECIMAL(10,2) DEFAULT 0; - - SELECT vn.clientGetDebt(intCustomer,datMax) INTO decRisk; - - RETURN decRisk; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `semana` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `semana`(datFec DATETIME) RETURNS int(11) - DETERMINISTIC -BEGIN - /* DECLARE intWeek TINYINT DEFAULT WEEK(datFec, 1); - DECLARE intYear SMALLINT DEFAULT YEAR(datFec); - - --- La funcio week dona un error en els primers dies del any --- Por convención, consideraremos que el año tiene siempre 52 semanas, y la 53 se incorpora a la 1 del año siguiente. --- Mysql week function smells, so ... - - IF intWeek > 52 THEN - - SET intWeek = 1; - - IF MONTH(datFec) = 12 THEN - - SET intYear = intYear + 1; - - SET intWeek = 1; - - - END IF; - - END IF; - - RETURN intYear * 100 + intWeek; -*/ - - RETURN vnperiod(datFec); - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `shipmentDay` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `shipmentDay`(landingDay INT, intervalDays INT) RETURNS int(11) -BEGIN - -/* PAK 01/09/16 -* -* Devuelve el weekday resultante de restar al landingDay los dias de intervalDays -* -*/ - -DECLARE resultDay INT; - -SET resultDay = (landingDay + 7 - (intervalDays mod 7)) mod 7; - -RETURN resultDay; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `ticket_freight` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `ticket_freight`(idT INT) RETURNS decimal(10,3) -BEGIN - - DECLARE dblFreight DECIMAL(10,2); - - /* - DECLARE intWh INTEGER; - DECLARE datFecha DATE; - - - SELECT warehouse_id, Fecha INTO intWh,datFecha FROM Tickets WHERE Id_Ticket = idT; - - - CALL item_last_buy_(intWh,datFecha); - - SELECT SUM((`M`.`Cantidad` * (CM3(`b`.`buy_id`) / 1000000 /`C`.`Packing`) * `az`.`price` / 0.08)) INTO dblFreight - FROM Movimientos M - JOIN t_item_last_buy b on M.Id_Article = b.item_id - JOIN Compres C ON C.Id_Compra = b.buy_id - JOIN Tickets t on t.Id_Ticket = M.Id_Ticket - JOIN `Consignatarios` `cn` ON (`cn`.`Id_Consigna` = `t`.`Id_Consigna`) - JOIN `Agencias` `a` ON (`a`.`Id_Agencia` = `t`.`Id_Agencia`) - JOIN `Agencias_province` `ap` ON (`t`.`warehouse_id` = `ap`.`warehouse_id`) - AND (`ap`.`province_id` = `cn`.`province_id`) - AND (`ap`.`agency_id` = `a`.`agency_id`) - JOIN `Agencias_zonas` `az` ON (`az`.`Id_Agencia` = `t`.`Id_Agencia`) - AND (`az`.`zona` = `ap`.`zona`) - AND (`t`.`warehouse_id` = `az`.`warehouse_id`) - AND (`az`.`Id_Article` = 71) - WHERE M.Id_Ticket = idT; - - DROP TEMPORARY TABLE t_item_last_buy; - */ - - SELECT sum(freight) - INTO dblFreight - FROM v_Movimientos_Volumen_shipping_charge - WHERE Id_Ticket = idT; - - RETURN dblFreight; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `ticket_state` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `ticket_state`( - strFAC VARCHAR(15), - intIMP TINYINT(1), - intETI TINYINT(1), - intBLO TINYINT(1) - - ) RETURNS varchar(15) CHARSET utf8 -BEGIN -CASE - - WHEN strFAC IS NOT NULL AND strFAC != '' THEN RETURN 'FACTURADO'; - - WHEN intETI <> 0 THEN RETURN 'ALBARAN'; - - WHEN intIMP <> 0 THEN RETURN 'PREPARACION'; - - WHEN intBLO <> 0 THEN RETURN 'BLOQUEADO'; - - ELSE RETURN 'LIBRE'; - -END CASE; - - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `ticket_state_2` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `ticket_state_2`( - idTICKET INT(11) - - ) RETURNS varchar(15) CHARSET utf8 -BEGIN - -DECLARE strVAR VARCHAR(15); - - -SELECT ticket_state(Factura, PedidoImpreso, Etiquetasemitidas, Blocked) -INTO strVAR -FROM Tickets -WHERE Id_Ticket = idTICKET; - - - -RETURN strVAR; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `ticket_state_3` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `ticket_state_3`( - idTICKET INT(11) - - ) RETURNS varchar(15) CHARSET utf8 -BEGIN - -DECLARE strVAR VARCHAR(15); -DECLARE strNAM VARCHAR(15); -DECLARE fltID FLOAT DEFAULT 0; -DECLARE strfac VARCHAR(15); -DECLARE inteti tinyint; -DECLARE intimp tinyint; -DECLARE intblk tinyint; - -SELECT s.`name`,id INTO strNAM,fltID - FROM Tickets t INNER JOIN vncontrol.inter i USING(Id_Ticket) - INNER JOIN state s ON s.id = i.state_id - WHERE Id_Ticket = idTICKET ORDER BY i.odbc_date DESC,i.state_id DESC LIMIT 1; - -SELECT Factura, PedidoImpreso, Etiquetasemitidas, Blocked - INTO strfac,intimp,inteti,intblk - FROM Tickets - WHERE Id_Ticket = idTICKET; - -CASE - - - WHEN strfac <> '' AND fltID < 11 THEN RETURN 'FACTURADO'; - - WHEN inteti <> 0 AND fltID < 11 THEN RETURN 'ALBARAN' ; - - WHEN intimp <> 0 AND fltID <= 5 THEN RETURN 'EN PREPARACION'; - - WHEN fltID > 0 THEN RETURN strNAM; - - ELSE RETURN 'LIBRE'; - -END CASE; - - -RETURN strVAR; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `ticket_total` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `ticket_total`(ticket_id INT) RETURNS double -BEGIN -/** - * Calcula el total con IVA de un ticket. - * - * @deprecated Use function vn.ticketGetTotal() instead - * - * @param ticket_id Identificador del ticket - * @return Total del ticket - */ - -- TODO: Una vez provado el nuevo método con esta instrucción es suficiente - -- RETURN vn.ticketGetTotal (vTicketId); - - DECLARE v_total DOUBLE; - - DROP TEMPORARY TABLE IF EXISTS ticket_tmp; - - CREATE TEMPORARY TABLE ticket_tmp - (INDEX (ticket_id)) - ENGINE = MEMORY - SELECT ticket_id; - - CALL ticket_total; - - SELECT total INTO v_total FROM ticket_total; - - DROP TEMPORARY TABLE - ticket_total, - ticket_tmp; - - RETURN v_total; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `ticket_volumen` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `ticket_volumen`(idT INT) RETURNS decimal(10,3) -BEGIN - DECLARE intWh INTEGER; - DECLARE datFecha DATE; - DECLARE dblVolume DECIMAL(10,3); - - SELECT warehouse_id, Fecha - INTO intWh,datFecha - FROM Tickets - WHERE Id_Ticket = idT; - - SELECT IFNULL(SUM(m.Cantidad * cm3)/1000000,0) INTO dblVolume - FROM Movimientos m - JOIN bi.rotacion r on r.Id_Article = m.Id_Article AND r.warehouse_id = intWh - WHERE m.Id_Ticket = idT; - - RETURN dblVolume; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `ticket_volumen_encajado` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `ticket_volumen_encajado`(idT INT) RETURNS decimal(10,1) -BEGIN - -/* Devuelve el volumen estimado de un pedido, en cajas -* -* idT Numero de ticket -* -*/ - - - DECLARE vVolumenCajaM3 DOUBLE; - DECLARE vTicketVolumenEnCajas DECIMAL(10,1); - DECLARE CAJA VARCHAR(10) DEFAULT '94'; - - SELECT Volumen/1000000 INTO vVolumenCajaM3 FROM Cubos WHERE Id_Cubo = CAJA; - - SET vTicketVolumenEnCajas = ticket_volumen(idT) / vVolumenCajaM3; - - RETURN vTicketVolumenEnCajas; - -RETURN 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 DROP FUNCTION IF EXISTS `ticket_volumen_en_cajas` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `ticket_volumen_en_cajas`(idT INT) RETURNS decimal(10,1) -BEGIN - -/* Devuelve el volumen estimado de un pedido, en cajas -* -* idT Numero de ticket -* -* - - - DECLARE vVolumenCajaM3 DOUBLE; - DECLARE vTicketVolumenEnCajas DECIMAL(10,1); - DECLARE CAJA VARCHAR(10) DEFAULT '94'; - - SELECT Volumen/1000000 INTO vVolumenCajaM3 FROM Cubos WHERE Id_Cubo = CAJA; - - SET vTicketVolumenEnCajas = ticket_volumen(idT) / vVolumenCajaM3; - - RETURN vTicketVolumenEnCajas; -*/ -RETURN 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 DROP FUNCTION IF EXISTS `till_entry` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `till_entry`( - v_customer INT - ,v_bank INT - ,v_amount DOUBLE - ,v_concept VARCHAR(25) - ,v_date DATE - ,v_serial CHAR(1) - ,v_batch TINYINT - ,v_number INT - ,v_company SMALLINT - ,v_employee INT -) RETURNS int(11) -BEGIN - DECLARE v_account VARCHAR(12); - DECLARE v_subaccount VARCHAR(12); - DECLARE v_asiento INT DEFAULT NULL; - - -- Inserta el registro en cajas - - INSERT INTO Cajas - SET - Id_Trabajador = v_employee - ,Id_Banco = v_bank - ,Entrada = v_amount - ,Concepto = v_concept - ,Cajafecha = v_date - ,Serie = v_serial - ,Partida = v_batch - ,Numero = v_number - ,empresa_id = v_company; - - -- Inserta los asientos contables - - SELECT Cuenta INTO v_account - FROM Bancos WHERE Id_Banco = v_bank; - - SELECT Cuenta INTO v_subaccount - FROM Clientes WHERE Id_Cliente = v_customer; - - SET v_asiento = asiento - ( - v_asiento - ,v_date - ,v_account - ,v_subaccount - ,v_concept - ,v_amount - ,0 - ,0 - ,NULL -- Serie - ,NULL -- Factura - ,NULL -- IVA - ,NULL -- Recargo - ,FALSE -- Auxiliar - ,v_company - ); - DO asiento - ( - v_asiento - ,v_date - ,v_subaccount - ,v_account - ,v_concept - ,0 - ,v_amount - ,0 - ,NULL -- Serie - ,NULL -- Factura - ,NULL -- IVA - ,NULL -- Recargo - ,FALSE -- Auxiliar - ,v_company - ); - - RETURN NULL; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `to_weeks` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `to_weeks`(v_date DATE) RETURNS int(11) - DETERMINISTIC -BEGIN - RETURN FLOOR((TO_DAYS(v_date) - 366) / 7); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `ubicator_cabecaja` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `ubicator_cabecaja`(x SMALLINT,y SMALLINT,z SMALLINT,w SMALLINT,d SMALLINT,h SMALLINT) RETURNS tinyint(1) -BEGIN - -IF ((y>d) OR (x>w) OR (z>h)) THEN -- si no cabe alguna de las medidas en la balda. - RETURN FALSE; -END IF; -RETURN TRUE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `vnday` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `vnday`(datfec DATE) RETURNS int(11) - DETERMINISTIC -BEGIN - -DECLARE intper INT; - -SELECT day INTO intper FROM time WHERE date = datfec; - -RETURN intper; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `vndayname` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `vndayname`(datfec DATE) RETURNS varchar(10) CHARSET utf8 COLLATE utf8_unicode_ci - DETERMINISTIC -BEGIN - -DECLARE vDayName VARCHAR(10); - -CASE weekday(datfec) - - WHEN 6 then - SET vDayName = 'Domingo'; - - WHEN 0 then - SET vDayName = 'Lunes'; - - WHEN 1 then - SET vDayName = 'Martes'; - - WHEN 2 then - SET vDayName = 'Miercoles'; - - WHEN 3 then - SET vDayName = 'Jueves'; - - WHEN 4 then - SET vDayName = 'Viernes'; - - WHEN 5 then - SET vDayName = 'Sabado'; - -END CASE; - -RETURN vDayName; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `vnmonth` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `vnmonth`(datfec DATE) RETURNS int(11) - DETERMINISTIC -BEGIN - -DECLARE intper INT; - -SELECT month INTO intper FROM time WHERE date = datfec; - -RETURN intper; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `vnperiod` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `vnperiod`(datfec DATE) RETURNS int(6) - DETERMINISTIC -BEGIN - -DECLARE intper INT; - -SELECT period INTO intper FROM time WHERE date = datfec; - -RETURN intper; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `vntrimestre` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `vntrimestre`(datfec DATE) RETURNS int(11) - DETERMINISTIC -BEGIN - - CASE - WHEN MONTH(datfec)<=3 THEN RETURN 1; - WHEN MONTH(datfec)<=6 THEN RETURN 2; - WHEN MONTH(datfec)<=9 THEN RETURN 3; - ELSE return 4; - END CASE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `vnweek` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `vnweek`(datfec DATE) RETURNS int(11) - DETERMINISTIC -BEGIN - -DECLARE intper INT; - -SELECT week INTO intper FROM time WHERE date = datfec; - -RETURN intper; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `vnyear` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `vnyear`(datfec DATE) RETURNS int(11) - DETERMINISTIC -BEGIN - -DECLARE intper INT; - -SELECT year INTO intper FROM time WHERE date = datfec; - -RETURN intper; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `__AltaEmpleado` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `__AltaEmpleado`(strCodTrabajador varchar(3),strNombre varchar(50),strApellidos varchar(50),strDni varchar(9), - strDomicilio longtext,strCodPostal varchar(5),strPoblacion varchar(25),provinceId smallint(5), intempresa_id smallint(5),strMovil varchar(11)) RETURNS varchar(50) CHARSET utf8 -BEGIN - -DECLARE RETORNO varchar(50) DEFAULT 'Empleado creado CORRECTAMENTE'; -DECLARE tmpUserId INT(11) DEFAULT 0; -DECLARE intId_Cliente int(11) DEFAULT 0; -DECLARE Cod_Trabajador VARCHAR(8) DEFAULT strCodTrabajador; -DECLARE strPassword VARCHAR(50); -DECLARE strSambaNombre VARCHAR(30); - -samba:BEGIN - -proc:BEGIN - -- IF (boolCrearSamba) THEN - -- SELECT Id_Cliente_Interno INTO intId_Cliente FROM Trabajadores WHERE Nombre=strNombre and Apellidos=strApellidos; - -- SELECT CONCAT(IF(INSTR(StrApellidos,' ')=0,StrApellidos,LEFT(strApellidos,INSTR(StrApellidos,' ')-1)),'.',intId_Cliente) INTO strPassword; - -- LEAVE proc; - -- END IF; --- Tabla Clientes -SELECT COUNT(*) INTO intId_Cliente FROM Clientes WHERE `IF`=strDni; -IF (intId_Cliente=0) THEN - -- SELECT IFNULL(province_id,1) INTO intprovince_id FROM province WHERE `name`=strProvincia; - SELECT MAX(Id_Cliente)+1 INTO intId_Cliente FROM Clientes WHERE Id_Cliente<999999; - - INSERT INTO Clientes (Id_Cliente,Cliente,Domicilio,`IF`,Telefono,province_id,Poblacion,CodPostal,RazonSocial,Contacto,Oficial,Descuento) - SELECT intId_Cliente,Concat('TR ',strNombre,' ',StrApellidos),strDomicilio,strDni,strMovil,provinceId,strPoblacion,strCodPostal, - CONCAT(strApellidos,' ',strNombre),strNombre,1,3; -ELSE - SELECT id_cliente INTO intId_Cliente FROM Clientes WHERE `IF`=strDni; -END IF; - -SELECT CONCAT(IF(INSTR(StrApellidos,' ')=0,StrApellidos,LEFT(strApellidos,INSTR(StrApellidos,' ')-1)),'.',intId_Cliente) INTO strPassword; - --- Tabla Trabajadores -IF (SELECT COUNT(*) FROM Trabajadores WHERE Nombre=strNombre AND Apellidos=strApellidos)=0 THEN - - IF strCodTrabajador IS NULL THEN - SET Cod_Trabajador = CONCAT(LEFT(strNombre, 1), LEFT(strApellidos, 1), MID(strApellidos, (LOCATE(' ', strApellidos) + 1), 1)); - END IF; - - IF (SELECT COUNT(*) FROM Trabajadores WHERE CodigoTrabajador=Cod_Trabajador) > 0 THEN - SET Cod_Trabajador = CONCAT(Cod_Trabajador, (FLOOR(RAND() * 100))); - END IF; - - SELECT CONCAT(IF(INSTR(StrApellidos,' ')=0,StrApellidos,LEFT(strApellidos,INSTR(StrApellidos,' ')-1)),'.',intId_Cliente) INTO strPassword; - - INSERT INTO Trabajadores (CodigoTrabajador,Nombre,Apellidos,`Password`,dni,empresa_id,id_Cliente_Interno) - SELECT Cod_Trabajador,strNombre,strApellidos,LCASE(strPassword),strDni,intempresa_id,intId_Cliente; -ELSE - SET RETORNO="CodigoTrabajador Existente"; -END IF; - -- LEAVE SAMBA; -END; -- PROC - --- Tabla Account, lo crea como usuario y en samba --- Obtengo el nombre sin espacios -SET strSambaNombre = REPLACE(strNombre,' ',''); -IF (SELECT COUNT(*) FROM account.user WHERE `name`=convert(strNombre USING utf8) COLLATE utf8_general_ci)>0 THEN -- Si existe cojo la inicial del nombre+1º apellido - SELECT CONCAT(LEFT(strNombre,1),CONCAT(IF(INSTR(StrApellidos,' ')=0,StrApellidos,LEFT(strApellidos,INSTR(StrApellidos,' ')-1)),intId_Cliente)) - INTO strSambaNombre; -END IF; - - IF (SELECT COUNT(*) FROM account.user where id=intId_Cliente)=0 THEN - INSERT INTO account.user (id,role,`name`,`password`,active) VALUES (intId_Cliente,1,lcase(strSambaNombre),MD5(LCASE(strPassword)),1); - INSERT INTO account.account (id,lastchange,`expire`,user_id) values (intId_Cliente,CURRENT_DATE(),CURRENT_DATE(),intId_Cliente); - UPDATE Trabajadores SET user_id=intId_Cliente WHERE Id_Cliente_Interno=intId_Cliente; - ELSE - INSERT INTO account.user (role,`name`,`password`,active) VALUES (1,lcase(strSambaNombre),MD5(LCASE(strPassword)),1); - SET tmpUserId = LAST_INSERT_ID(); - INSERT INTO account.account (id,lastchange,`expire`,user_id) values (tmpUserId,CURRENT_DATE(),CURRENT_DATE(),tmpUserId); - UPDATE Trabajadores SET user_id=tmpUserId WHERE Id_Cliente_Interno=intId_Cliente; - END IF; - - REPLACE INTO account.mailAliasAccount(mailAlias, account) VALUES (48,intId_Cliente); - -END; -- samba - -RETURN RETORNO; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `account_conciliacion_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `account_conciliacion_add`() -BEGIN - -update account_conciliacion ac -join -( - select idaccount_conciliacion, @c:= if(@id = id_calculated, @c + 1, 1) contador - , @id:= id_calculated as id_calculated, concat(id_calculated,'(',@c,')') as new_id from account_conciliacion - join - ( - select id_calculated, count(*) rep, @c:= 0, @id:= concat('-',id_calculated) from account_conciliacion - group by id_calculated - having rep > 1 - ) sub using(id_calculated) -) sub2 using(idaccount_conciliacion) -set ac.id_calculated = sub2.new_id; - - -insert into Cajas(Cajafecha, Partida, Serie, Concepto, Entrada, Salida, Id_Banco, Id_Trabajador, empresa_id, warehouse_id, Proveedores_account_id, id_calculated) -select Fechaoperacion, TRUE, 'MB', ac.Concepto, IF(DebeHaber = 2, importe,null), IF(DebeHaber = 1, importe, null), pa.Id_Banco, 20 - , pa.Id_Proveedor, 1, ac.Id_Proveedores_account,ac.id_calculated -from account_conciliacion ac -join Proveedores_account pa on pa.Id_Proveedores_account = ac.Id_Proveedores_account -left join Cajas c on c.id_calculated = ac.id_calculated -where c.Id_Caja is null; - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `accumulatorsReadingDateUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `accumulatorsReadingDateUpdate`() -BEGIN - -/* Actualiza los valores de la tabla en función de la cotización del EUR/USD -* -*/ - -UPDATE accumulatorsReadingDate a - JOIN - ( - SELECT - d.id, - CASE - WHEN rr.rate between p.lowerBarrier and p.rate THEN p.strike - WHEN rr.rate between p.rate and p.upperBarrier AND p.financialProductTypefk = 'AC' THEN p.strike - WHEN rr.rate >= p.upperBarrier THEN p.strike * 2 - ELSE 0 - END AS Acumulado - FROM vn2008.reference_rate rr - JOIN accumulatorsReadingDate d ON d.readingDate = rr.date - JOIN pago_sdc p ON p.pago_sdc_id = d.pagoSdcfk - WHERE IFNULL(amount,0) = 0 - AND rr.rate >= p.lowerBarrier) sub ON sub.id = a.id - SET a.amount = sub.Acumulado - WHERE a.amount IS NULL; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `add_awb_component` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `add_awb_component`(IN v_awb SMALLINT) -BEGIN - - DECLARE vShipment DATE; - SELECT t.shipment INTO vShipment - FROM awb_recibida aw - JOIN recibida_entrada re ON re.awb_recibida = aw.recibida_id - JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada - JOIN travel t ON t.id = e.travel_id - WHERE awb_id = v_awb limit 1; - - INSERT IGNORE INTO awb_component (awb_id,Id_Proveedor,awb_component_type_id,awb_role_id,awb_unit_id,value,Id_Moneda) - SELECT id,Id_Proveedor,awb_component_type_id,awb_role_id,awb_unit_id,LEAST(GREATEST(value1,IFNULL(min_value,value1)),IFNULL(max_value,value1)),Id_Moneda - FROM ( - SELECT a.id,IFNULL(act.carguera_id,CASE awb_role_id WHEN 1 THEN a.carguera_id WHEN 2 THEN a.transitario_id WHEN 3 THEN f.airline_id END) Id_Proveedor, - act.awb_component_type_id,act.awb_role_id,act.awb_unit_id, value * - CASE awb_unit_id - WHEN '1000Tj-20' THEN ((CAST(stems AS SIGNED) - 20000)/1000) + (min_value / value) - WHEN '1000Tj-10' THEN ((CAST(stems AS SIGNED) - 10000)/1000) + (min_value / value) - WHEN '100GW' THEN peso/100 - WHEN 'AWB' THEN 1 -- No action - WHEN 'FB' THEN hb/2 - WHEN 'GW' THEN peso - WHEN 'TW' THEN GREATEST(peso,volume_weight) - END value1 - , value, - act.Id_Moneda, act.min_value, act.max_value - FROM awb a JOIN flight f ON f.flight_id = a.flight_id - LEFT JOIN awb_component_template act ON ((IFNULL(act.carguera_id, a.carguera_id) = a.carguera_id AND awb_role_id = 1) - OR (IFNULL(act.carguera_id, a.transitario_id) = a.transitario_id AND awb_role_id = 2)) - AND IFNULL(act.airport_out, f.airport_out) = f.airport_out AND IFNULL(act.airport_in, f.airport_in) = f.airport_in - AND IFNULL(act.airline_id, f.airline_id) = f.airline_id - WHERE a.id = v_awb AND Fecha <= vShipment ORDER BY Fecha DESC) t ; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `add_awb_componentKK` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `add_awb_componentKK`(IN v_awb SMALLINT) -BEGIN - - INSERT IGNORE INTO awb_component (awb_id,Id_Proveedor,awb_component_type_id,awb_role_id,awb_unit_id,value,Id_Moneda) - SELECT id,Id_Proveedor,awb_component_type_id,awb_role_id,awb_unit_id,LEAST(GREATEST(value1,IFNULL(min_value,value1)),IFNULL(max_value,value1)),Id_Moneda - FROM ( - SELECT a.id,IFNULL(act.carguera_id,CASE awb_role_id WHEN 1 THEN a.carguera_id WHEN 2 THEN a.transitario_id WHEN 3 THEN f.airline_id END) Id_Proveedor, - act.awb_component_type_id,act.awb_role_id,act.awb_unit_id, value * - CASE awb_unit_id - WHEN '1000Tj-20' THEN ((CAST(stems AS SIGNED) - 20000)/1000) + (min_value / value) - WHEN '1000Tj-10' THEN ((CAST(stems AS SIGNED) - 10000)/1000) + (min_value / value) - WHEN '100GW' THEN peso/100 - WHEN 'AWB' THEN 1 -- No action - WHEN 'FB' THEN hb/2 - WHEN 'GW' THEN peso - WHEN 'TW' THEN GREATEST(peso,volume_weight) - END value1 - , value, - act.Id_Moneda, act.min_value, act.max_value - FROM awb a JOIN flight f ON f.flight_id = a.flight_id - LEFT JOIN awb_component_template act ON ((IFNULL(act.carguera_id, a.carguera_id) = a.carguera_id AND awb_role_id = 1) - OR (IFNULL(act.carguera_id, a.transitario_id) = a.transitario_id AND awb_role_id = 2)) - AND IFNULL(act.airport_out, f.airport_out) = f.airport_out AND IFNULL(act.airport_in, f.airport_in) = f.airport_in - AND IFNULL(act.airline_id, f.airline_id) = f.airline_id - WHERE a.id = v_awb AND Fecha <= CURDATE() ORDER BY Fecha DESC) t ; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `adelantarTickets` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `adelantarTickets`(datCurrent DATE,datAttempted DATE) -BEGIN - DECLARE vWarehouse INTEGER; - DECLARE vFechedTicket INTEGER; - DECLARE done INT DEFAULT 0; - DECLARE vFetchCounter INT DEFAULT 0; - DECLARE cur1 CURSOR FOR - SELECT ticketId - FROM tmpTicketList; - DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1; - - OPEN cur1; - - SELECT warehouse_id INTO vWarehouse FROM tmpTicketList ttl JOIN Tickets t ON t.Id_Ticket = ttl.ticketId LIMIT 1; - CALL item_stock(vWarehouse,CURDATE(),NULL); - - DROP TEMPORARY TABLE IF EXISTS tmpAdelantarTickets; - CREATE TEMPORARY TABLE tmpAdelantarTickets( - Id_Ticket INT, - count INT, - media DOUBLE) - ENGINE = MEMORY; - - REPEAT - FETCH cur1 INTO vFechedTicket; - - INSERT INTO tmpAdelantarTickets - SELECT - vFechedTicket, - COUNT(Cantidad), - AVG(Cantidad <= IFNULL(Saldo, 0)) AS `AVG` - FROM Movimientos m - LEFT JOIN - (SELECT - * - FROM - (SELECT - Id_Article, Saldo - FROM - (SELECT - Dia, Id_Article, SUM(Entradas - Salidas) AS Saldo - FROM - ( - SELECT CURDATE() AS Dia, - item_id Id_Article, - stock AS Entradas, - 0 AS Salidas - FROM tmp_item ti - JOIN Movimientos m ON m.Id_Article = ti.item_id AND m.Id_Ticket = vFechedTicket - UNION ALL - SELECT DATE(t.Fecha) AS Dia, - mt.Id_Article, - 0 AS Entradas, - - m.Cantidad AS Salidas - FROM Tickets t - JOIN Movimientos m ON m.Id_Ticket = t.Id_Ticket AND t.warehouse_id = vWarehouse - JOIN Movimientos mt ON mt.Id_Article = m.Id_Article - WHERE mt.Id_Ticket = vFechedTicket AND - t.Fecha BETWEEN curdate() AND datCurrent - UNION ALL - SELECT tr.landing, c.Id_Article, c.Cantidad, 0 - FROM - Compres c - JOIN Movimientos mt ON mt.Id_Article = c.Id_Article - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel tr ON tr.id = travel_id and tr.warehouse_id = vWarehouse - WHERE mt.Id_Ticket = vFechedTicket AND - tr.landing BETWEEN curdate() AND datCurrent - UNION ALL - SELECT tr.shipment, c.Id_Article, - c.Cantidad, 0 - FROM - Compres c - JOIN Movimientos mt ON mt.Id_Article = c.Id_Article - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel tr ON tr.id = travel_id and tr.warehouse_id_out = vWarehouse - WHERE mt.Id_Ticket = vFechedTicket AND tr.shipment BETWEEN curdate() AND datCurrent - ) sub GROUP BY Dia , Id_Article) sub2 - ORDER BY Saldo) sub3 - GROUP BY Id_Article) sub4 USING (Id_Article) - WHERE m.Id_Ticket = vFechedTicket; - - UNTIL done END REPEAT; - - select * from tmpAdelantarTickets; - CLOSE cur1; - DROP TEMPORARY TABLE IF EXISTS tmpAdelantarTickets; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `agencia_descuadre` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `agencia_descuadre`(datSince DATE, datTo DATE, intAgency INT, intWarehouseAlias INT) -BEGIN - - - DECLARE isFile boolean; - DECLARE datTo2359 DATETIME; - - SET datTo2359 = util.dayEnd(datTo); - - SELECT SUM(price) INTO isFile FROM agencia_descuadre; - - IF NOT IFNULL(isFile,0) THEN - - SELECT t.Id_Ticket,0 AS Total_Agencia,t.Id_Consigna,t.empresa_id,t.warehouse_id, - v.suma_componente AS VN, v.suma_componente - shipping_charge AS Difer, - e.shipping_charge AS teorico,t.Id_Agencia, t.Bultos,t.Id_Cliente, ap.zona - - FROM Tickets t LEFT JOIN - (SELECT Id_Ticket, SUM(suma_componente) suma_componente,Fecha - FROM v_descuadre_porte2 - WHERE Fecha BETWEEN datSince AND datTo2359 - GROUP BY Id_Ticket) v ON t.Id_Ticket = v.Id_Ticket - LEFT JOIN (SELECT Id_Ticket, SUM(shipping_charge) shipping_charge, Fecha - FROM v_expeditions_shipping_charge2 - WHERE Fecha BETWEEN datSince AND datTo2359 - GROUP BY Id_Ticket - ) e ON t.Id_Ticket = e.Id_Ticket - JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia - JOIN Consignatarios c ON t.Id_Consigna = c.Id_Consigna - JOIN Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = t.warehouse_id AND ap.province_id = c.province_id - JOIN warehouse_group wg ON wg.warehouse_id =t.warehouse_id - WHERE DATE(t.Fecha) BETWEEN datSince AND datTo2359 AND a.agency_id = intAgency and wg.warehouse_alias_id = intWarehouseAlias; - - ELSE - - SELECT t.Id_Ticket, Round(sum_price , 2) AS Total_Agencia,t.Id_Consigna,t.empresa_id,t.warehouse_id, - v.suma_componente AS VN, IF(isFile,Round(sum_price, 2) - v.suma_componente,v.diferencia) AS Difer, - v.teorico_agencia AS teorico,zd.Id_Agencia, t.Bultos,t.Id_Cliente - FROM - (SELECT - *, SUM(price) sum_price - FROM - (select - t.Id_Ticket, zd.price,t.Id_Consigna, zd.date,t.empresa_id,t.warehouse_id,c.Descuento,t.Id_Agencia - from - agencia_descuadre zd - LEFT JOIN Tickets t ON t.Id_Ticket = zd.Id_Ticket - LEFT JOIN Clientes c ON c.Id_Cliente = t.Id_Cliente - ORDER BY t.Id_Cliente DESC) t - GROUP BY Id_Ticket,`date`) zd - LEFT JOIN - Tickets t ON zd.date = DATE(t.Fecha) - AND zd.Id_Consigna = t.Id_Consigna - AND zd.warehouse_id = t.warehouse_id - AND zd.Id_Agencia = t.Id_Agencia - LEFT JOIN - v_descuadre_porte v ON v.Id_Ticket = t.Id_Ticket - WHERE t.Id_Cliente <> 4712 AND t.Id_Cliente <> 450 - GROUP BY zd.date,Id_Consigna,warehouse_id,zd.Id_Agencia -- HAVING Difer > 0.5 OR Difer < -0.5 jgf 2015-08-18 - ORDER BY v.diferencia; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `agencia_volume` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `agencia_volume`() -BEGIN - DECLARE v_start DATETIME DEFAULT TIMESTAMP(CURDATE()); - DECLARE v_end DATETIME DEFAULT TIMESTAMP(CURDATE(), '23:59:59'); - - - SET v_start = IF(WEEKDAY(CURDATE()), CURDATE(),TIMESTAMPADD(DAY,-1,CURDATE())); - SET v_start = IF(CURDATE() = '2014-05-02', '2014-05-01',v_start); - DROP TEMPORARY TABLE IF EXISTS agenVOL; - CREATE TEMPORARY TABLE agenVOL - ( - Id_Ticket INT PRIMARY KEY - ,Id_Agencia INT - ,Agencia VARCHAR(30) - ,Bultos INT DEFAULT 0 - ,Faltan INT DEFAULT 0 - /*,Prioridad VARCHAR(15) DEFAULT ''*/ - ) - ENGINE=MEMORY; - - -- Insertamos los tickets que ya tienen la linea de portes - - INSERT INTO agenVOL(Id_Agencia, Agencia, Id_Ticket, Bultos) - SELECT a.Id_Agencia, name , Id_Ticket, sum(Cantidad) Bultos - FROM Tickets t - JOIN Agencias a USING(Id_Agencia) - JOIN Movimientos m USING(Id_Ticket) - JOIN agency ag USING(agency_id) - JOIN warehouse_joined wj ON wj.warehouse_id = t.warehouse_id - WHERE Concepte LIKE '%porte%' - AND wj.warehouse_alias_id = 1 -- El 1 equivale a Silla (SillaFV-SillaPCA) - AND Fecha BETWEEN v_start AND v_end - AND Vista = 1 - GROUP BY Id_Ticket; - - -- Insertamos los tickets que ya tienen expediciones, que fallaran si se repite la clave primaria. - - INSERT INTO agenVOL(Id_Agencia, Agencia, Id_Ticket, Bultos) - SELECT a.Id_Agencia, name, ticket_id, COUNT(ticket_id) - FROM expeditions e - JOIN Tickets t ON t.Id_Ticket = e.ticket_id - JOIN Agencias a ON a.Id_Agencia = e.agency_id - JOIN agency ag ON ag.agency_id = a.agency_id - JOIN warehouse_joined wj ON wj.warehouse_id = t.warehouse_id - WHERE t.Fecha BETWEEN v_start AND v_end - AND wj.warehouse_alias_id = 1 -- El 1 equivale a Silla (SillaFV-SillaPCA) - AND Vista = 1 - GROUP BY ticket_id - ON DUPLICATE KEY UPDATE Bultos = Bultos; - - -- Adivinamos el futuro - INSERT INTO agenVOL(Id_Agencia, Agencia, Id_Ticket, Faltan) - SELECT a.Id_Agencia, name, Id_Ticket, 1 as Faltan - FROM Tickets t - JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia - JOIN agency ag ON ag.agency_id = a.agency_id - LEFT JOIN expeditions e ON e.ticket_id = t.Id_Ticket - JOIN warehouse_joined wj ON wj.warehouse_id = t.warehouse_id - WHERE Fecha BETWEEN v_start AND v_end - AND Bultos = 0 AND expeditions_id IS NULL AND EtiquetasEmitidas = 0 - AND wj.warehouse_alias_id = 1 -- JGF 18/12/14 El 1 equivale a Silla (SillaFV-SillaPCA) - AND Vista = 1 - GROUP BY Id_Ticket - ON DUPLICATE KEY UPDATE Faltan = Faltan + 1; - - - -- Matizamos la urgencia para ZELERIS - /* - UPDATE agenVOL a - JOIN Tickets t USING(Id_Ticket) - JOIN Clientes c USING(Id_Cliente) - JOIN Agencias agen ON agen.Id_Agencia = t.Id_Agencia - JOIN agency ag ON ag.agency_id = agen.agency_id - JOIN Agencias_province ap ON ag.agency_id = ap.province_id - JOIN province p ON p.province_id = ap.province_id - SET a.Prioridad = IF(p.name IN ('VALENCIA','MURCIA','MADRID','BARCELONA','GIRONA','ALICANTE','CASTELLON'), 'LENTA','RAPIDA') - WHERE ag.name LIKE 'zeleris';*/ - - SELECT agen.agency_id, name Agencia, COUNT(Id_Ticket) expediciones, SUM(Bultos) Bultos, SUM(Faltan) Faltan/*, Prioridad*/ - FROM agenVOL a - JOIN Agencias agen USING(Id_Agencia) - JOIN agency ag USING(agency_id) - GROUP BY ag.agency_id/*, Prioridad*/; - - DROP TEMPORARY TABLE IF EXISTS agenVOL; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `alfa_invoices` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `alfa_invoices`(IN datFEC DATE) -BEGIN - -DECLARE datSTART DATETIME; -DECLARE vTotal DECIMAL(10,2) DEFAULT 0.00; - -SET @myId = -10000000; -SET @myRef = 'factura'; -SET @myTotal = vTotal; - -SET datSTART = TIMESTAMPADD(DAY, -1 * DAYOFMONTH(datFEC) + 1, datfec); - -IF datFEC < '2017-07-01' THEN - - SELECT Id_Factura `Invoice no`, - date(Fecha) as `Invoice date`, - Id_Cliente `Debtor no`, - `IF` `Vat nr`, - Razonsocial `Name`, - BI7 `Amount excl Vat 6%`, - BI16 `Amount excl Vat 19%`, - IVA7 `Vat 6%`, - IVA16 `Vat 19%`, - Importe `Total inc Vat` - from Facturas - INNER JOIN Clientes USING(Id_Cliente) - where empresa_id = 567 - and Fecha BETWEEN datSTART AND datFEC - order by `Invoice date`, factura_id; - -ELSE - -SELECT * FROM - ( - SELECT io.ref `Invoice no`, - io.issued `Invoice date`, - IF(@myId = io.id, '', clientFk) `Debtor no`, - IF(@myId = io.id, '', c.fi) `Vat nr`, - IF(@myId = io.id, '', c.socialName) `Name`, - taxableBase `Taxable Amount excl VAT`, - CONCAT(CAST(pgc.rate AS DECIMAL(2,0)) ,' %') `VAT Rate`, - CAST(vat AS DECIMAL(10,2)) `VAT Quote`, - CAST(@myTotal + taxableBase + vat AS DECIMAL(10,2)) `Total plus Vat`, - IF(@myId := io.id, NULL, NULL) as ControlField - FROM vn.invoiceOut io - JOIN vn.client c ON c.id = io.clientFk - JOIN vn.invoiceOutTax iot ON iot.invoiceOutFk = io.id - JOIN vn.pgc ON pgc.code = iot.pgcFk - WHERE io.companyFk = 567 - AND io.issued BETWEEN datSTART AND datFEC - ORDER BY io.id, iot.id - ) t1 - ORDER BY `Invoice date` DESC, `Invoice no`; - -END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `article` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `article`() -BEGIN - DROP TEMPORARY TABLE IF EXISTS `article_inventory`; - CREATE TEMPORARY TABLE `article_inventory` - ( - `article_id` INT(11) NOT NULL PRIMARY KEY, - `future` DATETIME - ) - ENGINE = MEMORY; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `articleTagUpdatePriority_kk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `articleTagUpdatePriority_kk`(IN vItem INT) -BEGIN -/* -* DEPRECATED -*/ - -CALL vn.itemTagUpdatePriority(vItem); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `article_available_single` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `article_available_single`(IN v_wh TINYINT, IN v_date DATETIME, IN id_single INT) -BEGIN - - CALL bionic_available_single (v_wh, v_date,id_single,0); - - - SELECT available AS minimo FROM tmp_item - WHERE item_id = id_single; --- ixen totes les linies en lloc d'una sola - DROP TEMPORARY TABLE IF EXISTS tmp_item; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `article_inventory_warehouses` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `article_inventory_warehouses`(vDate DATE) -proc: BEGIN -/** - * Recalcula los inventarios de todos los almacenes. - * - * @param vDate Fecha de los nuevos inventarios - */ - DECLARE vWh INT; - DECLARE vDone BOOL; - DECLARE vEntryId INT; - DECLARE vTravelId INT; - DECLARE vDateTime DATETIME DEFAULT TIMESTAMP(vDate, '00:00:00'); - DECLARE vDeleteDate DATE DEFAULT TIMESTAMPADD(DAY, -2, vDate); - - DECLARE cWarehouses CURSOR FOR - SELECT id FROM warehouse WHERE inventario; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - OPEN cWarehouses; - - l: LOOP - - SET vDone = FALSE; - FETCH cWarehouses INTO vWh; - - IF vDone THEN - LEAVE l; - END IF; - - INSERT INTO travel SET - warehouse_id_out = 13, - warehouse_id = vWh, - shipment = vDateTime, - landing = vDateTime, - agency_id = 53, - ref = 'inventario', - delivered = TRUE, - received = TRUE; - - SELECT LAST_INSERT_ID() INTO vTravelId; - - INSERT INTO Entradas SET - Id_Proveedor = 4, - Fecha = vDateTime, - Confirmada = TRUE, - Pedida = TRUE, - travel_id = vTravelId; - - SELECT LAST_INSERT_ID() INTO vEntryId; - - -- Inserta el visible - - CALL inventario_multiple_inventarios (vWh, vDateTime); - - -- Inserta Last_buy_id - - ALTER TABLE article_inventory - ADD buy_id INT; - - UPDATE article_inventory ai - JOIN - ( - SELECT * FROM ( - SELECT Id_Article, Id_Compra,warehouse_id - FROM Compres c - JOIN Entradas e USING (Id_Entrada) - JOIN travel tr ON tr.id = e.travel_id - WHERE Novincular = FALSE - AND costefijo > 0 AND tarifa2 > 0 - AND NOT Redada - AND landing BETWEEN date_inv() AND vDate - ORDER BY (vWh = warehouse_id) DESC, landing DESC - ) t1 - GROUP BY Id_Article - ) t - ON ai.article_id = t.Id_Article - SET ai.buy_id = t.Id_Compra; - - INSERT INTO Compres ( - Id_Entrada - ,Id_Article - ,Cantidad - ,Costefijo - ,Packing - ,Id_Cubo - ,Tarifa2 - ,Tarifa3 - ,Productor - ) - SELECT - vEntryId - ,AI.article_id - ,IF(AI.visible < 0,0,AI.visible) - ,ifnull(C.Costefijo,0) + ifnull(C.Portefijo,0) + ifnull(C.Comisionfija,0) + ifnull(C.Embalajefijo,0) - ,C.Packing - ,C.Id_Cubo - ,C.Tarifa2 - ,C.Tarifa3 - ,C.Productor - FROM article_inventory AI - LEFT JOIN Compres C ON C.Id_Compra = AI.buy_id; - - DROP TEMPORARY TABLE article_inventory; - END LOOP; - - CLOSE cWarehouses; - - UPDATE tblContadores SET FechaInventario = vDate; - - DELETE e, t - FROM travel t - JOIN Entradas e ON e.travel_id = t.id - WHERE Id_Proveedor = 4 - AND shipment <= vDeleteDate - AND (DAY(shipment) <> 1 OR shipment < TIMESTAMPADD(MONTH, -12, CURDATE())); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `article_minacum` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `article_minacum`(IN v_wh TINYINT, IN v_date_ini DATETIME, IN v_range INT) -BEGIN - -- Cálculo del mínimo acumulado - - DECLARE v_date DATE DEFAULT v_date_ini; - DECLARE v_date_end DATETIME; - - SET v_date_ini = TIMESTAMP(DATE(v_date_ini), '00:00:00'); - SET v_date_end = TIMESTAMP(TIMESTAMPADD(DAY, v_range, v_date_ini),'23:59:59'); - - -- CALL item_travel (v_wh, v_date_ini); - - DROP TEMPORARY TABLE IF EXISTS article_minacum; - CREATE TEMPORARY TABLE article_minacum - ENGINE = MEMORY - SELECT t.article_id, t.warehouse_id, minacum(dat, amount, v_date) AS amount FROM ( - SELECT article_id, DATE(Fecha) AS dat, SUM(amount) AS amount, warehouse_id FROM ( - SELECT Id_Article article_id, Fecha, -Cantidad AS amount, warehouse_id - FROM Movimientos m INNER JOIN Tickets t USING (Id_Ticket) - WHERE Fecha BETWEEN v_date_ini AND v_date_end - AND Cantidad != 0 - AND (@aid IS NULL OR Id_Article = @aid) - AND (v_wh IS NULL OR t.warehouse_id = v_wh) - UNION ALL - SELECT Id_Article, t.landing, Cantidad, warehouse_id - FROM Compres c INNER JOIN Entradas e USING (Id_Entrada) - LEFT JOIN travel t ON e.travel_id = t.id - WHERE t.landing BETWEEN v_date_ini AND v_date_end - AND (v_wh IS NULL OR t.warehouse_id = v_wh) - AND e.Inventario = FALSE - AND Cantidad != 0 - AND (@aid IS NULL OR Id_Article = @aid) - UNION ALL - SELECT Id_Article, t.shipment, -Cantidad, warehouse_id_out - FROM Compres c INNER JOIN Entradas e USING (Id_Entrada) - LEFT JOIN travel t ON e.travel_id = t.id - WHERE t.shipment BETWEEN v_date_ini AND v_date_end - AND (v_wh IS NULL OR t.warehouse_id_out = v_wh) - AND e.Inventario = FALSE - AND Cantidad != 0 - AND (@aid IS NULL OR Id_Article = @aid) - ) t1 - GROUP BY t1.article_id, dat, warehouse_id - ) t - - GROUP BY t.article_id, warehouse_id HAVING amount != 0; - SET @aid = NULL; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `article_multiple_buy` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `article_multiple_buy`(v_date DATETIME, wh INT) -BEGIN - DECLARE v_date_aux DATETIME; - - SELECT TIMESTAMPADD(DAY, -90, CURDATE()) INTO v_date_aux; - - ALTER TABLE article_inventory - ADD buy_id INT; - - DROP TEMPORARY TABLE IF EXISTS tmp; - - CREATE TEMPORARY TABLE tmp - (KEY (Id_Article)) - ENGINE = MEMORY - SELECT * FROM - ( - SELECT Id_Article, Id_Compra - FROM bi.Last_buy_id - ORDER BY (wh = warehouse_id) DESC - ) t - GROUP BY Id_Article; - - UPDATE article_inventory ai - JOIN tmp t ON ai.article_id = t.Id_Article - SET ai.buy_id = t.Id_Compra; - - -- Los valores de hoy - - TRUNCATE TABLE tmp; - - INSERT INTO tmp - SELECT Id_Article, Id_Compra - FROM Compres c - JOIN Entradas e USING (Id_Entrada) - JOIN travel tr ON tr.id = e.travel_id - WHERE Novincular = FALSE - AND tarifa2 > 0 - AND landing BETWEEN CURDATE() AND v_date - ORDER BY (wh = warehouse_id) DESC; - - UPDATE article_inventory ai - INNER JOIN tmp t - ON ai.article_id = t.Id_Article - SET ai.buy_id = t.Id_Compra; - - -- CREATE INDEX idx USING HASH ON article_inventory (buy_id); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `article_multiple_buy_date` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `article_multiple_buy_date`(IN date_ DATETIME, IN wh TINYINT(3)) -BEGIN - - DECLARE datINV DATE; - SELECT FechaInventario INTO datINV FROM tblContadores; - - ALTER TABLE `article_inventory` - ADD `buy_date` datetime NOT NULL; - - UPDATE article_inventory INNER JOIN - ( - - SELECT * FROM - ( - SELECT travel.landing AS bdate, Compres.Id_Article AS article_id - FROM Compres - JOIN Entradas USING(Id_Entrada) - JOIN travel ON travel.id = Entradas.travel_id - - JOIN warehouse W ON W.id = travel.warehouse_id - WHERE travel.landing BETWEEN datINV AND date_ - AND IF(wh = 0, W.comisionantes, wh = travel.warehouse_id) - /*AND Compres.Novincular = FALSE - AND Entradas.Id_Proveedor <> 4 - AND Entradas.Inventario = FALSE*/ - -- jgf 2017/03/06 en la comparativa no trau el dia de caducitat - AND Entradas.Redada = FALSE - ORDER BY article_id, bdate DESC - - ) AS temp - GROUP BY article_id - ) - AS buy ON article_inventory.article_id = buy.article_id - SET article_inventory.buy_date = buy.bdate; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `article_multiple_buy_last` */; -/*!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 = latin1 */ ; -/*!50003 SET character_set_results = latin1 */ ; -/*!50003 SET collation_connection = latin1_swedish_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `article_multiple_buy_last`(IN wh TINYINT, IN date_end DATETIME) -BEGIN - DECLARE v_date DATETIME; - - DROP TEMPORARY TABLE IF EXISTS article_buy_last; - CREATE TEMPORARY TABLE article_buy_last - SELECT * FROM ( - SELECT c.Id_Article AS article_id, c.Id_Compra AS id - FROM Compres c INNER JOIN Entradas e USING(Id_Entrada) - INNER JOIN travel t ON t.id = e.travel_id - WHERE t.landing BETWEEN date_inv() AND date_end - AND c.Novincular = FALSE - AND c.tarifa2 > 0 - ORDER BY t.landing DESC,(wh IN (0,t.warehouse_id)) DESC, (Id_Cubo IS NULL) ,article_id, (e.Id_proveedor = 4) - ) t - GROUP BY article_id; - ALTER TABLE article_buy_last ADD INDEX (article_id); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `article_visible_single` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `article_visible_single`(IN v_wh TINYINT,IN v_article INT) -BEGIN -DECLARE bisible FLOAT; -CALL article_visible_single2(v_wh,v_article,@suma2); - -SET bisible = @suma2; -SELECT bisible AS suma, A.Id_Article, A.Article, A.Medida, A.Tallos, A.Nicho, O.Abreviatura as origen, A.Color, A.Tipo, A.Nicho, - A.Categoria - FROM v_compres A INNER JOIN Origen O ON O.id = A.id_origen WHERE A.Id_Article =v_article AND A.warehouse_id = v_wh ORDER BY landing 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 DROP PROCEDURE IF EXISTS `article_visible_single2` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `article_visible_single2`(IN v_wh TINYINT,IN v_article INT,OUT int_amount INT) -BEGIN - - call item_stock(v_wh,CURDATE(),v_article); - call article_visible(v_wh); - - SELECT SUM(stock) INTO int_amount FROM tmp_item WHERE item_id = v_article ; - SELECT IFNULL(SUM(amount),0) + IFNULL(int_amount,0) INTO int_amount - FROM article_visible - WHERE article_id = v_article; - - DROP TEMPORARY TABLE tmp_item; - DROP TEMPORARY TABLE article_visible; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `availableTraslate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `availableTraslate`(vWarehouseLanding INT, v_date DATE,vWarehouseShipment INT) -proc: BEGIN - DECLARE v_date_ini DATE; - DECLARE v_date_end DATETIME; - DECLARE v_reserve_date DATETIME; - DECLARE v_date_inv DATE; - - IF v_date < CURDATE() - THEN - LEAVE proc; - END IF; - - CALL vn2008.item_stock (vWarehouseLanding, v_date, NULL); - - -- Calcula algunos parámetros necesarios - - SET v_date_ini = TIMESTAMP(v_date, '00:00:00'); - SET v_date_end = TIMESTAMP(TIMESTAMPADD(DAY, 4, v_date), '23:59:59'); - - SELECT FechaInventario INTO v_date_inv FROM vn2008.tblContadores; - - SELECT SUBTIME(NOW(), reserveTime) INTO v_reserve_date - FROM hedera.orderConfig; - - -- Calcula el ultimo dia de vida para cada producto - - DROP TEMPORARY TABLE IF EXISTS item_range; - CREATE TEMPORARY TABLE item_range - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT c.Id_Article item_id, MAX(landing) date_end - FROM vn2008.Compres c - JOIN vn2008.Entradas e ON c.Id_Entrada = e.Id_Entrada - JOIN vn2008.travel t ON t.id = e.travel_id - JOIN vn2008.warehouse w ON w.id = t.warehouse_id - WHERE t.landing BETWEEN v_date_inv AND v_date_ini - AND t.warehouse_id = vWarehouseLanding - AND NOT e.Inventario - AND NOT e.Redada - GROUP BY Id_Article; - - -- Tabla con el ultimo dia de last_buy para cada producto que hace un replace de la anterior - - CALL item_last_buy_(vWarehouseShipment,curdate()); - - DROP TEMPORARY TABLE IF EXISTS item_range_copy; - CREATE TEMPORARY TABLE item_range_copy LIKE item_range; - INSERT INTO item_range_copy - SELECT * FROM item_range; - - INSERT INTO item_range - SELECT t.item_id, tr.landing - FROM t_item_last_buy t - JOIN Compres c ON c.Id_Compra = t.buy_id - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel tr ON tr.id = e.travel_id - LEFT JOIN item_range_copy i ON t.item_id = i.item_id - WHERE t.warehouse_id = vWarehouseShipment - ON DUPLICATE KEY UPDATE item_range.date_end = GREATEST(item_range.date_end,landing); - - DROP TEMPORARY TABLE item_range_copy; - - -- Replica la tabla item_range para poder usarla varias veces en la misma consulta - - DROP TEMPORARY TABLE IF EXISTS item_range_copy1; - CREATE TEMPORARY TABLE item_range_copy1 LIKE item_range; - INSERT INTO item_range_copy1 - SELECT c.item_id, TIMESTAMP(TIMESTAMPADD(DAY, t.life, c.date_end), '23:59:59') date_end FROM item_range c - JOIN vn2008.Articles a ON a.Id_Article = c.item_id - JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - HAVING date_end >= v_date_ini OR date_end IS NULL; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy2; - CREATE TEMPORARY TABLE item_range_copy2 LIKE item_range_copy1; - INSERT INTO item_range_copy2 - SELECT * FROM item_range_copy1; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy3; - CREATE TEMPORARY TABLE item_range_copy3 LIKE item_range_copy1; - INSERT INTO item_range_copy3 - SELECT * FROM item_range_copy1; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy4; - CREATE TEMPORARY TABLE item_range_copy4 LIKE item_range_copy1; - INSERT INTO item_range_copy4 - SELECT * FROM item_range_copy1; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy5; - CREATE TEMPORARY TABLE item_range_copy5 LIKE item_range_copy1; - INSERT INTO item_range_copy5 - SELECT * FROM item_range_copy1; - - -- Calcula el ATP - - DROP TEMPORARY TABLE IF EXISTS availableTraslate; - CREATE TEMPORARY TABLE availableTraslate - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT t.item_id, SUM(stock) available FROM ( - SELECT ti.item_id, stock - FROM vn2008.tmp_item ti - JOIN item_range ir ON ir.item_id = ti.item_id - UNION ALL - SELECT t.item_id, minacum(dt, amount, v_date) AS available FROM ( - SELECT item_id, DATE(dat) dt, SUM(amount) amount FROM ( - SELECT i.item_id, i.dat, i.amount - FROM vn2008.item_out i - JOIN item_range_copy1 ir ON ir.item_id = i.item_id - WHERE i.dat >= v_date_ini - AND (ir.date_end IS NULL OR i.dat <= ir.date_end) - AND i.warehouse_id = vWarehouseLanding - UNION ALL - SELECT m.Id_Article item_id, t.landing dat, m.Cantidad amount - FROM Compres m - JOIN Entradas e ON m.Id_Entrada = e.Id_Entrada - JOIN travel t ON e.travel_id = t.id - JOIN item_range_copy2 ir ON ir.item_id = m.Id_Article - WHERE - e.Inventario = 0 - AND m.Cantidad <> 0 - AND e.redada = 0 - AND t.warehouse_id = vWarehouseLanding - AND t.landing >= v_date_ini - AND (ir.date_end IS NULL OR t.landing <= ir.date_end) - - UNION ALL - SELECT i.item_id, i.dat, i.amount - FROM vn2008.item_entry_out i - JOIN item_range_copy3 ir ON ir.item_id = i.item_id - WHERE i.dat >= v_date_ini - AND (ir.date_end IS NULL OR i.dat <= ir.date_end) - AND i.warehouse_id = vWarehouseLanding - UNION ALL - SELECT r.item_id, r.shipment, -r.amount - FROM hedera.order_row r - JOIN hedera.`order` o ON o.id = r.order_id - JOIN item_range_copy4 ir ON ir.item_id = r.item_id - WHERE r.shipment >= v_date_ini - AND (ir.date_end IS NULL OR r.shipment <= ir.date_end) - AND r.warehouse_id = vWarehouseLanding - AND r.created >= v_reserve_date - AND NOT o.confirmed - ) t - GROUP BY item_id, dt - ) t - GROUP BY t.item_id - ) t GROUP BY t.item_id HAVING available != 0; - - DROP TEMPORARY TABLE - vn2008.tmp_item - ,item_range - ,item_range_copy1 - ,item_range_copy2 - ,item_range_copy3 - ,item_range_copy4 - ,item_range_copy5; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `availableTraslateTesting` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `availableTraslateTesting`(vWarehouseLanding INT, v_date DATE,vWarehouseShipment INT) -proc: BEGIN - DECLARE v_date_ini DATE; - DECLARE v_date_end DATETIME; - DECLARE v_reserve_date DATETIME; - DECLARE v_date_inv DATE; - - IF v_date < CURDATE() - THEN - LEAVE proc; - END IF; - - CALL vn2008.item_stock (vWarehouseLanding, v_date, NULL); - - -- Calcula algunos parámetros necesarios - - SET v_date_ini = TIMESTAMP(v_date, '00:00:00'); - SET v_date_end = TIMESTAMP(TIMESTAMPADD(DAY, 4, v_date), '23:59:59'); - - SELECT FechaInventario INTO v_date_inv FROM vn2008.tblContadores; - - SELECT SUBTIME(NOW(), reserveTime) INTO v_reserve_date - FROM hedera.orderConfig; - - -- Calcula el ultimo dia de vida para cada producto - - DROP TEMPORARY TABLE IF EXISTS item_range; - CREATE TEMPORARY TABLE item_range - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT c.Id_Article item_id, MAX(landing) date_end - FROM vn2008.Compres c - JOIN vn2008.Entradas e ON c.Id_Entrada = e.Id_Entrada - JOIN vn2008.travel t ON t.id = e.travel_id - JOIN vn2008.warehouse w ON w.id = t.warehouse_id - WHERE t.landing BETWEEN v_date_inv AND v_date_ini - AND t.warehouse_id = vWarehouseLanding - AND NOT e.Inventario - AND NOT e.Redada - GROUP BY Id_Article; - - -- Tabla con el ultimo dia de last_buy para cada producto que hace un replace de la anterior - - SELECT vWarehouseShipment; - - CALL item_last_buy_(vWarehouseShipment,v_date); - - SELECT *,'last_buy' FROM t_item_last_buy t ; -- WHERE t.item_id = 41576; - SELECT * FROM item_range t WHERE t.item_id = 41576; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy; - CREATE TEMPORARY TABLE item_range_copy LIKE item_range; - INSERT INTO item_range_copy - SELECT * FROM item_range; - - SELECT 'update' , t.item_id, tr.landing - FROM t_item_last_buy t - JOIN Compres c ON c.Id_Compra = t.buy_id - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel tr ON tr.id = e.travel_id - LEFT JOIN item_range_copy i ON t.item_id = i.item_id - WHERE t.warehouse_id = vWarehouseShipment AND t.item_id = 41576; - - INSERT INTO item_range - SELECT t.item_id, tr.landing - FROM t_item_last_buy t - JOIN Compres c ON c.Id_Compra = t.buy_id - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel tr ON tr.id = e.travel_id - LEFT JOIN item_range_copy i ON t.item_id = i.item_id - WHERE t.warehouse_id = vWarehouseShipment - ON DUPLICATE KEY UPDATE item_range.date_end = GREATEST(item_range.date_end,landing); - - DROP TEMPORARY TABLE item_range_copy; - - -- Replica la tabla item_range para poder usarla varias veces en la misma consulta - - DROP TEMPORARY TABLE IF EXISTS item_range_copy1; - CREATE TEMPORARY TABLE item_range_copy1 LIKE item_range; - INSERT INTO item_range_copy1 - SELECT c.item_id, TIMESTAMP(TIMESTAMPADD(DAY, t.life, c.date_end), '23:59:59') date_end FROM item_range c - JOIN vn2008.Articles a ON a.Id_Article = c.item_id - JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - HAVING date_end >= v_date_ini OR date_end IS NULL; - - select * from item_range_copy1 where item_id = 41576; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy2; - CREATE TEMPORARY TABLE item_range_copy2 LIKE item_range_copy1; - INSERT INTO item_range_copy2 - SELECT * FROM item_range_copy1; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy3; - CREATE TEMPORARY TABLE item_range_copy3 LIKE item_range_copy1; - INSERT INTO item_range_copy3 - SELECT * FROM item_range_copy1; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy4; - CREATE TEMPORARY TABLE item_range_copy4 LIKE item_range_copy1; - INSERT INTO item_range_copy4 - SELECT * FROM item_range_copy1; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy5; - CREATE TEMPORARY TABLE item_range_copy5 LIKE item_range_copy1; - INSERT INTO item_range_copy5 - SELECT * FROM item_range_copy1; - - -- Calcula el ATP - SELECT ti.item_id, stock - FROM vn2008.tmp_item ti - JOIN item_range ir ON ir.item_id = ti.item_id ; - - SELECT i.item_id, i.dat, i.amount - FROM vn2008.item_out i - JOIN item_range_copy1 ir ON ir.item_id = i.item_id - WHERE i.dat >= v_date_ini - AND (ir.date_end IS NULL OR i.dat <= ir.date_end) - AND i.warehouse_id = vWarehouseLanding; - - SELECT m.Id_Article item_id, t.landing dat, m.Cantidad amount - FROM Compres m - JOIN Entradas e ON m.Id_Entrada = e.Id_Entrada - JOIN travel t ON e.travel_id = t.id - JOIN item_range_copy2 ir ON ir.item_id = m.Id_Article - WHERE - e.Inventario = 0 - AND m.Cantidad <> 0 - AND e.redada = 0 - AND t.warehouse_id = vWarehouseLanding - AND t.landing >= v_date_ini - AND (ir.date_end IS NULL OR t.landing <= ir.date_end); - - SELECT i.item_id, i.dat, i.amount - FROM vn2008.item_entry_out i - JOIN item_range_copy3 ir ON ir.item_id = i.item_id - WHERE i.dat >= v_date_ini - AND (ir.date_end IS NULL OR i.dat <= ir.date_end) - AND i.warehouse_id = vWarehouseLanding; - SELECT r.item_id, r.shipment, -r.amount - FROM hedera.order_row r - JOIN hedera.`order` o ON o.id = r.order_id - JOIN item_range_copy4 ir ON ir.item_id = r.item_id - WHERE r.shipment >= v_date_ini - AND (ir.date_end IS NULL OR r.shipment <= ir.date_end) - AND r.warehouse_id = vWarehouseLanding - AND r.created >= v_reserve_date - AND NOT o.confirmed; - - DROP TEMPORARY TABLE IF EXISTS availableTraslate; - CREATE TEMPORARY TABLE availableTraslate - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT t.item_id, SUM(stock) available FROM ( - SELECT ti.item_id, stock - FROM vn2008.tmp_item ti - JOIN item_range ir ON ir.item_id = ti.item_id - UNION ALL - SELECT t.item_id, minacum(dt, amount, v_date) AS available FROM ( - SELECT item_id, DATE(dat) dt, SUM(amount) amount FROM ( - SELECT i.item_id, i.dat, i.amount - FROM vn2008.item_out i - JOIN item_range_copy1 ir ON ir.item_id = i.item_id - WHERE i.dat >= v_date_ini - AND (ir.date_end IS NULL OR i.dat <= ir.date_end) - AND i.warehouse_id = vWarehouseLanding - UNION ALL - SELECT m.Id_Article item_id, t.landing dat, m.Cantidad amount - FROM Compres m - JOIN Entradas e ON m.Id_Entrada = e.Id_Entrada - JOIN travel t ON e.travel_id = t.id - JOIN item_range_copy2 ir ON ir.item_id = m.Id_Article - WHERE - e.Inventario = 0 - AND m.Cantidad <> 0 - AND e.redada = 0 - AND t.warehouse_id = vWarehouseLanding - AND t.landing >= v_date_ini - AND (ir.date_end IS NULL OR t.landing <= ir.date_end) - - UNION ALL - SELECT i.item_id, i.dat, i.amount - FROM vn2008.item_entry_out i - JOIN item_range_copy3 ir ON ir.item_id = i.item_id - WHERE i.dat >= v_date_ini - AND (ir.date_end IS NULL OR i.dat <= ir.date_end) - AND i.warehouse_id = vWarehouseLanding - UNION ALL - SELECT r.item_id, r.shipment, -r.amount - FROM hedera.order_row r - JOIN hedera.`order` o ON o.id = r.order_id - JOIN item_range_copy4 ir ON ir.item_id = r.item_id - WHERE r.shipment >= v_date_ini - AND (ir.date_end IS NULL OR r.shipment <= ir.date_end) - AND r.warehouse_id = vWarehouseLanding - AND r.created >= v_reserve_date - AND NOT o.confirmed - ) t - GROUP BY item_id, dt - ) t - GROUP BY t.item_id - ) t GROUP BY t.item_id HAVING available != 0; - - select * from availableTraslate where item_id = 41576; - - DROP TEMPORARY TABLE - vn2008.tmp_item - ,item_range - ,item_range_copy1 - ,item_range_copy2 - ,item_range_copy3 - ,item_range_copy4 - ,item_range_copy5; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `balance_create` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `balance_create`(IN vStartingMonth INT - , IN vEndingMonth INT - , IN vCompany INT - , IN vConsolidate BOOLEAN - , IN vInterGroupSalesIncluded BOOLEAN) -BEGIN - -DECLARE v_sql TEXT; -DECLARE strTABLE VARCHAR(20) DEFAULT "balance_nest_tree"; -DECLARE intGAP INTEGER DEFAULT 7; -DECLARE intYEARS INTEGER DEFAULT 3; -DECLARE vConsolidatedGroup INTEGER; -DECLARE vStartingDate DATE DEFAULT '2016-01-01'; -DECLARE vStartingYear INT DEFAULT 2016; - - --- Solicitamos la tabla tmp.nest, como base para el balance -CALL nest_tree(strTABLE,intGAP, FALSE); - -DROP TEMPORARY TABLE IF EXISTS tmp.balance; - -CREATE TEMPORARY TABLE tmp.balance -SELECT * FROM tmp.nest; - -DROP TEMPORARY TABLE IF EXISTS tmp.empresas_receptoras; -DROP TEMPORARY TABLE IF EXISTS tmp.empresas_emisoras; - -IF vConsolidate THEN - SELECT empresa_grupo INTO vConsolidatedGroup FROM empresa WHERE id = vCompany; -END IF; - -CREATE TEMPORARY TABLE tmp.empresas_receptoras - SELECT id as empresa_id - FROM vn2008.empresa - WHERE id = vCompany - OR empresa_grupo = vConsolidatedGroup; - - -CREATE TEMPORARY TABLE tmp.empresas_emisoras - SELECT Id_Proveedor as empresa_id - FROM vn2008.Proveedores p; - -IF NOT vInterGroupSalesIncluded THEN - - DELETE ee.* - FROM tmp.empresas_emisoras ee - JOIN vn2008.empresa e on e.id = ee.empresa_id - WHERE e.empresa_grupo = vConsolidatedGroup; - - END IF; - --- Se calculan las facturas que intervienen, para luego poder servir el desglose desde aqui - -DROP TEMPORARY TABLE IF EXISTS tmp.balance_desglose; -CREATE TEMPORARY TABLE tmp.balance_desglose - SELECT er.empresa_id as receptora_id - , ee.empresa_id as emisora_id - , year(IFNULL(r.bookEntried,IFNULL(r.dateBooking, r.Fecha))) as `year` - , month(IFNULL(r.bookEntried,IFNULL(r.dateBooking, r.Fecha))) as `month` - , gastos_id as Id_Gasto - , sum(bi) as importe - FROM recibida r - JOIN recibida_iva ri on ri.recibida_id = r.id - JOIN tmp.empresas_receptoras er on er.empresa_id = r.empresa_id - JOIN tmp.empresas_emisoras ee ON ee.empresa_id = r.proveedor_id - WHERE IFNULL(r.bookEntried,IFNULL(r.dateBooking, r.Fecha)) >= vStartingDate - AND r.contabilizada - GROUP BY Id_Gasto, year, month, emisora_id, receptora_id; -/* -DROP TEMPORARY TABLE IF EXISTS tmp.balance_desglose; -CREATE TEMPORARY TABLE tmp.balance_desglose - SELECT er.empresa_id as receptora_id - , ee.empresa_id as emisora_id - , year(IFNULL(r.dateBooking, r.Fecha)) as `year` - , month(IFNULL(r.dateBooking, r.Fecha)) as `month` - , gastos_id as Id_Gasto - , sum(bi) as importe - FROM recibida r - JOIN recibida_iva ri on ri.recibida_id = r.id - JOIN tmp.empresas_receptoras er on er.empresa_id = r.empresa_id - JOIN tmp.empresas_emisoras ee ON ee.empresa_id = r.proveedor_id - WHERE IFNULL(r.dateBooking, r.Fecha) between vStartingDate and CURDATE() - GROUP BY Id_Gasto, year, month, emisora_id, receptora_id; -*/ -INSERT INTO tmp.balance_desglose(receptora_id - , emisora_id - , year - , month - , Id_Gasto - , importe) - SELECT gr.empresa_id - , gr.empresa_id - , year - , month - , Id_Gasto - , sum(importe) - FROM gastos_resumen gr - JOIN tmp.empresas_receptoras er on gr.empresa_id = er.empresa_id - WHERE year >= vStartingYear - AND month BETWEEN vStartingMonth AND vEndingMonth - GROUP BY Id_Gasto, year, month, gr.empresa_id; - - -DELETE FROM tmp.balance_desglose - WHERE month < vStartingMonth - OR month > vEndingMonth; - - - --- Ahora el balance -SET v_sql = sql_printf ( - ' - ALTER TABLE tmp.balance - ADD COLUMN %t INT(10) NULL , - ADD COLUMN %t INT(10) NULL , - ADD COLUMN %t INT(10) NULL , - ADD COLUMN Id_Gasto VARCHAR(10) NULL, - ADD COLUMN Gasto VARCHAR(45) NULL; - ', - YEAR(CURDATE())-2, - YEAR(CURDATE())-1, - YEAR(CURDATE()) - ); - -CALL util.exec (v_sql); - - --- Añadimos los gastos, para facilitar el formulario - -UPDATE tmp.balance b -JOIN vn2008.balance_nest_tree bnt on bnt.id = b.id -JOIN (SELECT Id_Gasto, Gasto - FROM vn2008.Gastos - GROUP BY Id_Gasto) g ON g.Id_Gasto = bnt.Id_Gasto -SET b.Id_Gasto = g.Id_Gasto - , b.Gasto = g.Gasto; - --- Rellenamos los valores de primer nivel, los que corresponden a los gastos simples - -WHILE intYEARS > 0 DO - - SET intYEARS = intYEARS - 1; - - SET v_sql = sql_printf ( - ' - UPDATE tmp.balance b - JOIN - ( - SELECT Id_Gasto, sum(Importe) as Importe - FROM tmp.balance_desglose - WHERE year = %v - GROUP BY Id_Gasto - ) sub on sub.Id_Gasto = b.Id_Gasto - SET %t = - Importe; - ', - YEAR(CURDATE()) - intYEARS, - YEAR(CURDATE()) - intYEARS - ); - - CALL util.exec (v_sql); - -END WHILE; - --- Añadimos las ventas - - - SET v_sql = sql_printf ( - ' - UPDATE tmp.balance b - JOIN ( - SELECT sum(IF(year = %v, venta, 0)) as y2 - , sum(IF(year = %v, venta, 0)) as y1 - , sum(IF(year = %v, venta, 0)) as y0 - , c.Gasto - - FROM bs.ventas_contables c - join tmp.empresas_receptoras er on er.empresa_id = c.empresa_id - WHERE month BETWEEN %v AND %v - GROUP BY c.Gasto - - ) sub ON sub.Gasto = b.Id_Gasto - SET %t = IFNULL(%t,0) + sub.y2 - , %t = IFNULL(%t,0) + sub.y1 - , %t = IFNULL(%t,0) + sub.y0 - ; - - ', - YEAR(CURDATE()) - 2, - YEAR(CURDATE()) - 1, - YEAR(CURDATE()), - vStartingMonth, - vEndingMonth, - YEAR(CURDATE()) - 2, YEAR(CURDATE()) - 2, - YEAR(CURDATE()) - 1, YEAR(CURDATE()) - 1, - YEAR(CURDATE()), YEAR(CURDATE()) - - ); - - CALL util.exec (v_sql); - --- Ventas intra grupo -IF NOT vInterGroupSalesIncluded THEN - - SELECT lft, rgt - INTO @grupoLft, @grupoRgt - FROM tmp.balance b - WHERE TRIM(b.`name`) = 'Grupo'; - - DELETE - FROM tmp.balance - WHERE lft BETWEEN @grupoLft AND @grupoRgt; - -END IF; - - --- Rellenamos el valor de los padres con la suma de los hijos -DROP TEMPORARY TABLE IF EXISTS tmp.balance_aux; -CREATE TEMPORARY TABLE tmp.balance_aux SELECT * FROM tmp.balance; - -UPDATE tmp.balance b -JOIN -( -select b1.id, b1.name, sum(b2.`2016`) as `2016`, sum(b2.`2017`) as `2017`, sum(b2.`2018`) as `2018` -from tmp.nest b1 -join tmp.balance_aux b2 on b2.lft between b1.lft and b1.rgt -group by b1.id) sub on sub.id = b.id -SET b.`2016` = sub.`2016`, b.`2017` = sub.`2017`, b.`2018` = sub.`2018` -; - - - -SELECT *, concat('',ifnull(Id_Gasto,'')) as newgasto FROM tmp.balance; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `base_ticket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `base_ticket`(IN Id_Ticket INT) -BEGIN - SELECT - red(SUM(Cantidad * Preu * (100 - Descuento) / 100)) AS base - FROm - Movimientos m - INNER JOIN Tickets t USING (Id_Ticket) - WHERE t.Id_Ticket = Id_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 DROP PROCEDURE IF EXISTS `bionic_available_` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_available_`( - vDate DATE, - vAddress INT, - vAgency INT) -BEGIN -/** - * Calcula el disponible para un conjunto de almacenes y fechas - * devueltos por el procedimiento travel_tree() - * - * @table t_bionic_available Tabla con los ids de cache - **/ - DECLARE vAvailableCalc INT; - DECLARE vShipment DATE; - DECLARE vAgencyId INT; - DECLARE vWh INT; - DECLARE vDone BOOL; - DECLARE cTravelTree CURSOR FOR - SELECT warehouse_id, Fecha_envio FROM travel_tree; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Establecemos los almacenes y las fechas que van a entrar al disponible - - SELECT agency_id INTO vAgencyId - FROM Agencias WHERE Id_Agencia = vAgency; - - CALL travel_tree (vDate, vAddress, vAgencyId); - - DROP TEMPORARY TABLE IF EXISTS t_bionic_available; - CREATE TEMPORARY TABLE t_bionic_available( - calc_id INT UNSIGNED, - PRIMARY KEY (calc_id) - ) - ENGINE = MEMORY; - - OPEN cTravelTree; - l: LOOP - SET vDone = FALSE; - FETCH cTravelTree INTO vWh, vShipment; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWh, vShipment); - - INSERT IGNORE INTO t_bionic_available - SET calc_id = vAvailableCalc; - END LOOP; - - CLOSE cTravelTree; - DROP TEMPORARY TABLE travel_tree; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_available_articlelist` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_available_articlelist`(IN strART VARCHAR(50) - , IN minMED DOUBLE - , IN maxMED DOUBLE - , IN minPVP DOUBLE - , IN maxPVP DOUBLE) -BEGIN - -DECLARE intSPACE_POS INT; -DECLARE strSUBTR VARCHAR(50); -DECLARE strFILTER VARCHAR(500); -DECLARE v_sql TEXT; - -DROP TEMPORARY TABLE IF EXISTS articlelist; - -CREATE TEMPORARY table articlelist -(Id_Article INT(11) PRIMARY KEY) -ENGINE = INNODB; - - - --- Arreglos - -SET minMED = IFNULL(minMED,0); -SET minMED = IF(minMED = 0,0.01, minMED); -SET maxMED = IFNULL(maxMED,9990); -SET maxMED = IF(maxMED = 0,9990, maxMED); -SET minPVP = IFNULL(minPVP,0); -SET minPVP = IF(minPVP = 0, 0.01, minPVP); -SET maxPVP = IFNULL(maxPVP,9990); -SET maxPVP = IF(maxPVP = 0, 9990, maxPVP); - --- ARTICLE - -SET strART = TRIM(strART); - -IF ASCII(strART) BETWEEN 48 AND 57 THEN - - INSERT INTO articlelist(Id_Article) VALUES(CAST(strART AS UNSIGNED)); - -ELSE - - SET strFILTER = 'TRUE '; - - WHILE LENGTH(strART) > 0 DO - - SET intSPACE_POS = POSITION(' ' IN strART) ; - - IF intSPACE_POS = 0 THEN - - SET strFILTER = CONCAT(strFILTER, ' AND CONCAT(a.Id_Article,Article,t.Tipo) LIKE "%',strART,'%"'); - SET strART = ''; - - ELSE - - SET strFILTER = CONCAT(strFILTER, ' AND CONCAT(a.Id_Article,Article,t.Tipo) LIKE "%',LEFT(strART,intSPACE_POS - 1),'%"'); - SET strART = TRIM(SUBSTRING(strART, intSPACE_POS)); - - END IF; - - - END WHILE; - - if minpvp = 0.01 and maxpvp = 9990 then - - SET v_sql = sql_printf ( - ' - REPLACE vn2008.articlelist - SELECT a.Id_Article - FROM vn2008.Articles a - LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - WHERE %s - AND Medida BETWEEN %v AND %v; - ' - - ,strFILTER - ,minMED - ,maxMED); - else - - SET v_sql = sql_printf ( - ' - REPLACE vn2008.articlelist - SELECT a.Id_Article - FROM vn2008.Articles a - LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - JOIN ( - SELECT DISTINCT Id_Article - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t using(Id_Ticket) - JOIN vn2008.Clientes c using(Id_Cliente) - WHERE Fecha > CURDATE() - INTERVAL 4 DAY - AND Preu BETWEEN %v AND %v - AND c.invoice <> 0 - ) v on v.Id_Article = a.Id_Article - WHERE %s - AND Medida BETWEEN %v AND %v; - ' - ,minPVP - ,maxPVP - ,strFILTER - ,minMED - ,maxMED); - end if; - - CALL util.exec (v_sql); - -END IF; --- SELECT Id_Article, Article, Medida FROM Articles join articlelist using(Id_Article); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_available_items_` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_available_items_`(v_date DATE, -- fecha de recepcion de mercancia - v_consigna INT, - v_agencia INT) -BEGIN -/** - * Crea una tabla con los identificadores de los articulos disponibles. - * - * @table t_bionic_available_items - **/ - CALL bionic_available_ (v_date, v_consigna, v_agencia); - - DROP TEMPORARY TABLE IF EXISTS t_bionic_available_items; - CREATE TEMPORARY TABLE t_bionic_available_items - (INDEX (Id_Article)) - ENGINE = MEMORY - SELECT a.Id_Article, a.Article - FROM `cache`.available c - JOIN Articles a ON c.item_id = a.Id_Article - JOIN t_bionic_available ba ON c.calc_id = ba.calc_id - WHERE c.available GROUP BY a.Article; - - DROP TEMPORARY TABLE t_bionic_available; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_available_single` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_available_single`(IN v_wh TINYINT, IN v_date DATETIME, IN id_single INT, IN refresh TINYINT) -BEGIN - DECLARE intcalc_id INT; - call cache.available_refresh(intcalc_id,refresh, v_wh,v_date); - - SELECT available AS minimo FROM cache.available WHERE calc_id = intcalc_id AND item_id = id_single ; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_available_types_` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_available_types_`( - v_date DATE, -- fecha de recepcion de mercancia - v_consigna INT, - v_agencia INT) -BEGIN -/** - * Calcula los tipos disponibles para un conjunto de almacenes - * y fechas devueltos por el procedimiento travel_tree() - * - * @table t_bionic_available_types Tabla con los tipos disponibles - **/ - - CALL bionic_available_(v_date, v_consigna, v_agencia); - - DROP TEMPORARY TABLE IF EXISTS t_bionic_available_types; - CREATE TEMPORARY TABLE t_bionic_available_types - (INDEX (tipo_id)) - ENGINE = MEMORY - SELECT a.tipo_id, t.Tipo - FROM `cache`.available c - JOIN Articles a ON c.item_id = a.Id_Article - JOIN Tipos t ON t.tipo_id = a.tipo_id - JOIN t_bionic_available ba ON c.calc_id = ba.calc_id - WHERE c.available > 0 -- JGF 2016-03-23 en el bionic no apareixen negatius, els tipos que no continguen disponible, tampoc els volem mostrar - AND t.Orden != 0 - GROUP BY t.tipo_id; - - DROP TEMPORARY TABLE t_bionic_available; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_available_types_filter` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_available_types_filter`( - v_date DATE, - v_consigna INT, - v_agencia INT, - v_filter TEXT) -BEGIN -/** - * Este procedimiento devuelve una tabla t_bionic_available_types - * que debe de ser borrar por quien la llame, y se conecta con la tabla articlelist - * que tambien hay que eliminar. - * - * @param vDatefecha de recepcion de mercancia - * @table t_bionic_available_types - */ - - DECLARE v_sql TEXT; - DECLARE v_list TEXT; - SET v_list = ''; - - SET v_filter = IFNULL(v_filter,' TRUE'); - - CALL bionic_available_(v_date, v_consigna, v_agencia); - -- Inroducimos los valores en una tabla temporal - DROP TEMPORARY TABLE IF EXISTS t_bionic_available_types; - - CALL check_table_existence('articlelist'); - - IF @table_exists THEN - - SET v_list = 'JOIN vn2008.articlelist AL ON AL.Id_Article = a.Id_Article '; - - END IF; - - SET v_sql = sql_printf ( - ' - CREATE TEMPORARY TABLE t_bionic_available_types - SELECT a.tipo_id, Tipo, reino, count(*) as item_count - FROM `cache`.available c - JOIN vn2008.Articles a ON c.item_id = a.Id_Article - JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - JOIN vn2008.reinos r ON r.id = t.reino_id - JOIN vn2008.t_bionic_available ba ON c.calc_id = ba.calc_id - %s - WHERE c.available > 0 - AND %s - GROUP BY a.tipo_id; - ' - , v_list - , v_filter); - - CALL sql_query (v_sql); - - DROP TEMPORARY TABLE t_bionic_available; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_calc` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc`( - vDate DATE, -- Fecha de recepcion de mercancia - vAddress INT, - vAgency INT) -proc: BEGIN - DECLARE vAvailableCalc INT; - DECLARE vShipment DATE; - DECLARE vAgencyId INT; - DECLARE vCustomer INT; - DECLARE vWh SMALLINT; - DECLARE vDone BOOL; - DECLARE cTravelTree CURSOR FOR - SELECT warehouse_id, Fecha_envio FROM travel_tree; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DROP TEMPORARY TABLE IF EXISTS - tmp.bionic_item, - tmp.bionic_component, - tmp.bionic_lot, - tmp.bionic_price; - - -- Establece los almacenes y las fechas que van a entrar al disponible - - SELECT agency_id INTO vAgencyId FROM Agencias WHERE Id_Agencia = vAgency; - SELECT Id_Cliente INTO vCustomer FROM Consignatarios WHERE Id_Consigna = vAddress; - - CALL travel_tree(vDate, vAddress, vAgencyId); - - -- Crea la tabla temporal que almacenará los lotes - - CREATE TEMPORARY TABLE tmp.bionic_lot LIKE - template_bionic_lot; - - OPEN cTravelTree; - - l: LOOP - SET vDone = FALSE; - FETCH cTravelTree INTO vWh, vShipment; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWh, vShipment); - CALL item_last_buy_ (vWh, vShipment); - - INSERT INTO tmp.bionic_lot (warehouse_id, item_id, available, buy_id) - SELECT - vWh, - i.item_id, - IFNULL(i.available, 0), - ilb.buy_id - FROM `cache`.available i - JOIN tmp.bionic_calc br ON br.item_id = i.item_id - LEFT JOIN Articles a ON a.Id_Article = i.item_id - LEFT JOIN t_item_last_buy ilb ON ilb.item_id = i.item_id - WHERE i.calc_id = vAvailableCalc - AND a.Id_Article != 100 - AND i.available > 0; - - DROP TEMPORARY TABLE t_item_last_buy; - END LOOP; - - CLOSE cTravelTree; - - CALL bionic_calc_component(vAddress, vAgency); - - CREATE TEMPORARY TABLE tmp.bionic_item - ENGINE = MEMORY - SELECT b.item_id, SUM(b.available) available, p.name producer, - a.Article item, a.Medida size, a.Tallos stems, a.Categoria category, - a.Color, a.Foto image, o.Abreviatura origin, bl.min_price price - FROM tmp.bionic_lot b - JOIN Articles a ON b.item_id = a.Id_Article - LEFT JOIN producer p ON p.producer_id = a.producer_id AND p.visible - JOIN Origen o ON o.id = a.id_origen - JOIN ( - SELECT MIN(price) min_price, item_id - FROM tmp.bionic_price - GROUP BY item_id - ) bl ON bl.item_id = b.item_id - GROUP BY b.item_id; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_calc_clon` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc_clon`(IN v_ticket BIGINT) -BEGIN - -/* -Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo -*/ - DECLARE v_shipment DATE; - DECLARE v_customer INT; - DECLARE v_wh SMALLINT; - DECLARE v_agencia INT; - DECLARE v_consigna INT; - DECLARE v_landing DATE; - DECLARE v_agency INT; - - REPLACE order_Tickets(order_id,Id_Ticket) VALUES(48, v_ticket); - - SELECT t.Id_Cliente , t.warehouse_id, date(t.Fecha), t.Id_Consigna, t.Id_Agencia, t.landing, a.agency_id - INTO v_customer, v_wh, v_shipment, v_consigna, v_agencia, v_landing, v_agency - FROM vn2008.Agencias a - JOIN vn2008.Tickets t ON t.Id_Agencia = a.Id_Agencia - WHERE t.Id_Ticket = v_ticket; - - DROP TEMPORARY TABLE IF EXISTS travel_tree; - CREATE TEMPORARY TABLE travel_tree ENGINE = MEMORY - SELECT v_wh warehouse_id, v_shipment Fecha_envio, v_landing Fecha_recepcion; - - CALL item_last_buy_ (v_wh, v_shipment); -- rellena la tabla t_item_last_buy con la ultima compra - - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_lot; - CREATE TEMPORARY TABLE tmp.bionic_lot - SELECT v_wh warehouse_id,NULL available, - m.Id_Article item_id,ilb.buy_id - FROM Movimientos m - LEFT JOIN t_item_last_buy ilb ON ilb.item_id = m.Id_Article - WHERE m.Id_Ticket = v_ticket GROUP BY m.Id_Article; - - CALL bionic_calc_component(v_consigna,v_agencia); - - -- Bionizamos lineas con Preu = 0 - DROP TEMPORARY TABLE IF EXISTS tmp.movement; - CREATE TEMPORARY TABLE tmp.movement - (PRIMARY KEY (Id_Movimiento)) ENGINE = MEMORY - SELECT Id_Movimiento, v_wh warehouse_id FROM Movimientos m - JOIN Tickets t on t.Id_Ticket = m.Id_Ticket WHERE m.Id_Ticket = v_ticket AND Preu = 0; - CALL bionic_movement_update(1); - - -- Bionizamos lineas con Preu > 0 - DROP TEMPORARY TABLE IF EXISTS tmp.movement; - CREATE TEMPORARY TABLE tmp.movement - (PRIMARY KEY (Id_Movimiento)) ENGINE = MEMORY - SELECT Id_Movimiento, v_wh warehouse_id FROM Movimientos m - JOIN Tickets t on t.Id_Ticket = m.Id_Ticket WHERE m.Id_Ticket = v_ticket AND Preu > 0; - CALL bionic_movement_update(6); - - IF v_landing IS NULL THEN - CALL travel_tree_shipment(v_shipment, v_consigna, v_agency,v_wh); - UPDATE Tickets t - JOIN travel_tree_shipment tts ON t.warehouse_id = tts.warehouse_id - SET t.landing = tts.landing - WHERE Id_Ticket = v_ticket; - END IF; - - -- Log - call Ditacio(v_ticket - ,'Bioniza Ticket' - ,'T' - , 20 - , 'proc bionic_calc_clon' - , NULL); - - -- Limpieza - DROP TEMPORARY TABLE t_item_last_buy; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_calc_clonkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc_clonkk`(IN v_ticket BIGINT) -BEGIN - -/* -Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo -*/ - DECLARE v_shipment DATE; - DECLARE v_customer INT; - DECLARE v_wh SMALLINT; - DECLARE v_agencia INT; - DECLARE v_consigna INT; - DECLARE v_landing DATE; - - REPLACE order_Tickets(order_id,Id_Ticket) VALUES(48, v_ticket); - - SELECT Id_Cliente , t.warehouse_id, date(t.Fecha), Id_Consigna , Id_Agencia - INTO v_customer ,v_wh, v_shipment , v_consigna , v_agencia - FROM vn2008.Agencias a - JOIN vn2008.Tickets t using(Id_Agencia) - WHERE Id_Ticket = v_ticket; - - DROP TEMPORARY TABLE IF EXISTS travel_tree; - CREATE TEMPORARY TABLE travel_tree ENGINE = MEMORY - SELECT v_wh warehouse_id, v_shipment Fecha_envio, v_landing Fecha_recepcion; - - CALL item_last_buy_ (v_wh, v_shipment); -- rellena la tabla t_item_last_buy con la ultima compra - - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_lot; - CREATE TEMPORARY TABLE tmp.bionic_lot - SELECT v_wh warehouse_id,NULL available, - m.Id_Article item_id,ilb.buy_id - FROM Movimientos m - LEFT JOIN t_item_last_buy ilb ON ilb.item_id = m.Id_Article - WHERE m.Id_Ticket = v_ticket GROUP BY m.Id_Article; - - CALL bionic_calc_component(v_consigna,v_agencia); - - -- Bionizamos lineas con Preu = 0 - DROP TEMPORARY TABLE IF EXISTS tmp.movement; - CREATE TEMPORARY TABLE tmp.movement - (PRIMARY KEY (Id_Movimiento)) ENGINE = MEMORY - SELECT Id_Movimiento, v_wh warehouse_id FROM Movimientos m - JOIN Tickets t on t.Id_Ticket = m.Id_Ticket WHERE m.Id_Ticket = v_ticket AND Preu = 0; - CALL bionic_movement_update(1); - - -- Bionizamos lineas con Preu > 0 - DROP TEMPORARY TABLE IF EXISTS tmp.movement; - CREATE TEMPORARY TABLE tmp.movement - (PRIMARY KEY (Id_Movimiento)) ENGINE = MEMORY - SELECT Id_Movimiento, v_wh warehouse_id FROM Movimientos m - JOIN Tickets t on t.Id_Ticket = m.Id_Ticket WHERE m.Id_Ticket = v_ticket AND Preu > 0; - CALL bionic_movement_update(6); - - - -- Log - call Ditacio(v_ticket - ,'Bioniza Ticket' - ,'T' - , 20 - , 'proc bionic_calc_clon' - , NULL); - - -- Limpieza - DROP TEMPORARY TABLE t_item_last_buy; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_calc_component` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc_component`( - -- v_date DATE, -- fecha de recepcion de mercancia - v_consigna INT, - v_agencia INT) -proc: BEGIN - - DECLARE v_customer INT; - DECLARE COEFICIENTE_DE_INFLACION_GENERAL INT DEFAULT 1.3; - DECLARE DENSIDAD_MINIMA_PESO_VOLUMETRICO INT DEFAULT 167; - DECLARE VOLUMEN_CAJA_VERDNATURA BIGINT DEFAULT 138000; - -- DECLARE vValorEmbolsado DOUBLE DEFAULT 0.04; - - SELECT Id_Cliente INTO v_customer FROM Consignatarios WHERE Id_Consigna = v_consigna; - SET @rate2 := 0; - SET @rate3 := 0; - - DROP TEMPORARY TABLE IF EXISTS t_bionic_temp; - CREATE TEMPORARY TABLE t_bionic_temp - (PRIMARY KEY (item_id,warehouse_id)) - ENGINE = MEMORY - SELECT - b.item_id, b.warehouse_id,available, - IF((@rate2 := IFNULL(pf.rate_2,c.Tarifa2)) < a.PVP AND a.`Min`, a.PVP, @rate2) * 1.0 rate_2, - IF((@rate3 := IFNULL(pf.rate_3,c.Tarifa3)) < a.PVP AND a.`Min`, a.PVP, @rate3) * 1.0 rate_3, - ifnull(pf.rate_3,0) AS min_price, - IFNULL(pf.Packing,c.Packing) packing, - IFNULL(pf.grouping,c.grouping) grouping, - ABS(IFNULL(pf.caja,c.caja)) box, - b.buy_id, a.tipo_id - FROM tmp.bionic_lot b - JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra - JOIN vn2008.Articles a ON b.item_id = a.Id_Article - JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = t.reino_id - LEFT JOIN vn2008.PreciosEspeciales p ON a.Id_Article = p.Id_Article AND p.Id_Cliente = v_customer - LEFT JOIN ( - SELECT * FROM ( - SELECT p.item_id, p.grouping, p.Packing,p.caja, p.rate_2, p.rate_3, t.warehouse_id - FROM vn2008.price_fixed p - JOIN vn2008.travel_tree t ON t.warehouse_id = p.warehouse_id OR p.warehouse_id = 0 - WHERE t.Fecha_envio BETWEEN p.date_start AND p.date_end ORDER BY p.item_id, p.warehouse_id DESC - ) t - GROUP BY item_id, warehouse_id - ) pf ON pf.item_id = b.item_id AND pf.warehouse_id = b.warehouse_id - -- descartamos articulos con coste menor de 0.01 - WHERE Costefijo + Portefijo + Embalajefijo + Comisionfija > 0.01 AND r.display <> 0; - - -- Creamos la tabla tmp.bionic_component - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component; - CREATE TEMPORARY TABLE tmp.bionic_component LIKE - template_bionic_component; - - -- Componentes del precio, valores absolutos - INSERT INTO tmp.bionic_component ( warehouse_id, item_id, component_id, cost) - SELECT b.warehouse_id, b.item_id, 29, rate_3 - Costefijo - Portefijo - Embalajefijo - Comisionfija - FROM t_bionic_temp b - JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra; - - INSERT INTO tmp.bionic_component ( warehouse_id, item_id, component_id, cost) - SELECT b.warehouse_id, b.item_id, 28, Costefijo + Portefijo + Embalajefijo + Comisionfija - FROM t_bionic_temp b - JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra; - - -- Ahora los valores en funcion de la base - - DROP TEMPORARY TABLE IF EXISTS t_components_base; - - CREATE TEMPORARY TABLE t_components_base - SELECT bc.item_id, ROUND(SUM(cost), 4) AS base, bc.warehouse_id - FROM tmp.bionic_component bc - GROUP BY bc.item_id,warehouse_id; - - -- La ratio se calcula teniendo en cuenta el valor de las reclamaciones y el saldo de greuge - - INSERT INTO tmp.bionic_component - SELECT cb.warehouse_id, item_id, 17, ROUND(base * LEAST(recobro,0.25), 3) - FROM t_components_base cb - JOIN bi.claims_ratio ON Id_Cliente = v_customer - WHERE recobro > 0.009; - - -- PAK 2016-08-31 Componente de maná automático, en función del maná acumulado por el comercial. - - INSERT INTO tmp.bionic_component - SELECT cb.warehouse_id, item_id, 39, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto - FROM t_components_base cb - JOIN Clientes c on c.Id_Cliente = v_customer - JOIN bs.mana_spellers ms ON c.Id_Trabajador = ms.Id_Trabajador - WHERE ms.prices_modifier_activated - HAVING manaAuto <> 0 ; - - -/* - -- Vendedor variable - INSERT INTO tmp.bionic_component - SELECT cb.warehouse_id, item_id, Id_Componente, IFNULL(ROUND(base * tax,4), 0) - FROM t_components_base cb - JOIN bi.tarifa_componentes - WHERE tarifa_componentes_series_id = 2 and IFNULL(tax, 0) > 0; - */ - - --- ******* Inicio Bloque para componentes con tarifa_class diferente de NULL - -- Descuento por ultimas unidades - INSERT INTO tmp.bionic_component - SELECT cb.warehouse_id, b.item_id, Id_Componente, GREATEST(IFNULL(ROUND(base * tax,4), 0), b.min_price - b.rate_3) - FROM t_components_base cb - JOIN bi.tarifa_componentes - JOIN t_bionic_temp b ON b.item_id = cb.item_id AND b.warehouse_id = cb.warehouse_id - LEFT JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id - WHERE Id_Componente = 32 AND tax <> 0 AND b.min_price < b.rate_3 AND PrecioEspecial IS NULL; - - -- Incremento por paquete suelto - INSERT INTO tmp.bionic_component - SELECT b.warehouse_id, b.item_id, 22, rate_2 - rate_3 - FROM t_bionic_temp b - JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra - LEFT JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id - WHERE PrecioEspecial IS NULL; - --- ******* Fin Bloque para componentes con tarifa_class diferente de NULL - - -- Reparto - INSERT INTO tmp.bionic_component - SELECT b.warehouse_id - , b.item_id - , 15 - , COEFICIENTE_DE_INFLACION_GENERAL - * ROUND( - r.cm3 - * IF(a.Vista = 1, (GREATEST(art.density,DENSIDAD_MINIMA_PESO_VOLUMETRICO) / DENSIDAD_MINIMA_PESO_VOLUMETRICO ) , 1) - * IFNULL(az.price - * az.inflacion ,50) - / VOLUMEN_CAJA_VERDNATURA, 4 - ) cost - FROM t_bionic_temp b - JOIN vn2008.Articles art ON art.Id_Article = b.item_id - JOIN vn2008.Agencias a ON a.Id_Agencia = v_agencia - JOIN vn2008.Consignatarios c ON c.Id_Consigna = v_consigna - JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = b.warehouse_id AND ap.province_id = c.province_id - JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = v_agencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = b.warehouse_id - LEFT JOIN bi.rotacion r ON r.warehouse_id = b.warehouse_id AND r.Id_Article = b.item_id - HAVING cost <> 0; - --- Reparto bonificado - INSERT INTO tmp.bionic_component - SELECT b.warehouse_id - , b.item_id - , 41 - , COEFICIENTE_DE_INFLACION_GENERAL - * ROUND( - r.cm3 - * IF(a.Vista = 1, (GREATEST(art.density,DENSIDAD_MINIMA_PESO_VOLUMETRICO) / DENSIDAD_MINIMA_PESO_VOLUMETRICO ) , 1) - * awb.bonus - * az.inflacion - / VOLUMEN_CAJA_VERDNATURA, 4 - ) cost - FROM t_bionic_temp b - JOIN vn2008.Articles art ON art.Id_Article = b.item_id - JOIN vn2008.Agencias a ON a.Id_Agencia = v_agencia - JOIN vn2008.Consignatarios c ON c.Id_Consigna = v_consigna - JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = b.warehouse_id AND ap.province_id = c.province_id - JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = v_agencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = b.warehouse_id - JOIN vn2008.agency_weekday_bonus awb ON awb.warehouse_id = az.warehouse_id AND awb.zona = az.zona AND a.agency_id = awb.agency_id - LEFT JOIN bi.rotacion r ON r.warehouse_id = b.warehouse_id AND r.Id_Article = b.item_id - JOIN vn2008.travel_tree t ON t.warehouse_id = awb.warehouse_id AND weekday(t.Fecha_recepcion) = awb.weekDay - HAVING cost <> 0 - LIMIT 1; - --- PAK 12-05-2015 - -- EMBOLSADO - IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = v_consigna) THEN - - -- IF v_consigna IN (13690, 3402, 5661, 4233) THEN - - INSERT INTO tmp.bionic_component - SELECT b.warehouse_id, b.item_id, 38, ap.packagingValue cost - FROM t_bionic_temp b - JOIN vn.addressForPackaging ap - WHERE ap.addressFk = v_consigna; - - END IF; - - -- JGF 14-08-2015 - -- Modificacion de precio por dia de preparacion del pedido - INSERT INTO tmp.bionic_component - SELECT cb.warehouse_id, cb.item_id, 14, cb.base * (IFNULL(pe.percentage,pp.percentage)/100) - FROM t_components_base cb - JOIN vn2008.travel_tree tt ON tt.warehouse_id = cb.warehouse_id - LEFT JOIN vn2008.preparation_percentage pp ON pp.week_day = weekday(tt.Fecha_envio) AND cb.warehouse_id = IFNULL(pp.warehouse_id,cb.warehouse_id) - LEFT JOIN vn2008.preparation_exception pe ON pe.exception_day = tt.Fecha_envio AND cb.warehouse_id = IFNULL(pe.warehouse_id,cb.warehouse_id) - WHERE IFNULL(pe.percentage,pp.percentage); - - -- Creamos la tabla tmp.bionic_component_copy por que mysql no puede reabrir una tabla temporal - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component_copy; - CREATE TEMPORARY TABLE tmp.bionic_component_copy - SELECT * FROM tmp.bionic_component; - - -- JGF 19-01-2016 - -- Precios especiales - INSERT INTO tmp.bionic_component - SELECT b.warehouse_id, b.item_id, 10, pe.PrecioEspecial - SUM(cost) sum_cost - FROM tmp.bionic_component_copy b - JOIN bi.tarifa_componentes t ON b.component_id = t.Id_Componente - JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id - WHERE t.tarifa_class IS NULL - GROUP BY b.item_id, b.warehouse_id - HAVING ABS(sum_cost) > 0.001; - - -- Lotes - DROP TEMPORARY TABLE IF EXISTS t_component_sum; - CREATE TEMPORARY TABLE t_component_sum - (INDEX (item_id, warehouse_id)) - ENGINE = MEMORY - SELECT SUM(cost) sum_cost, b.item_id, b.warehouse_id, t.tarifa_class - FROM tmp.bionic_component b - JOIN bi.tarifa_componentes t ON b.component_id = t.Id_Componente - GROUP BY b.item_id, b.warehouse_id, t.tarifa_class; - - -- ***** Inicia Modifica t_bionic_rate las diferentes tarifas - -- Tarifa por unidad minima - DROP TEMPORARY TABLE IF EXISTS t_bionic_rate; - CREATE TEMPORARY TABLE t_bionic_rate - ENGINE = MEMORY - SELECT b.warehouse_id, item_id, 1 rate, - IF(box = 1, grouping, 1) grouping, SUM(sum_cost) price - FROM t_bionic_temp b - JOIN t_component_sum cs USING(item_id, warehouse_id) - WHERE IFNULL(cs.tarifa_class,1) = 1 AND box < 2 AND (packing > grouping or box = 0) - GROUP BY warehouse_id, item_id; - - -- Tarifa por caja - INSERT INTO t_bionic_rate (warehouse_id, item_id, rate, grouping, price) - SELECT b.warehouse_id, item_id, 2 rate, packing grouping, - SUM(sum_cost) price - FROM t_bionic_temp b - JOIN t_component_sum cs USING(item_id, warehouse_id) - WHERE available IS NULL OR (IFNULL(cs.tarifa_class,2) = 2 AND packing > 0 AND available >= packing) - GROUP BY warehouse_id, item_id; - - -- Tarifa para toda la cantidad disponible - INSERT INTO t_bionic_rate (warehouse_id, item_id, rate, grouping, price) - SELECT b.warehouse_id, item_id, 3 rate, available grouping, - SUM(sum_cost) price - FROM t_bionic_temp b - JOIN t_component_sum cs USING(item_id, warehouse_id) - WHERE IFNULL(cs.tarifa_class,3) = 3 - GROUP BY warehouse_id, item_id; - - -- ***** Fin Modifica t_bionic_rate las diferentes tarifas - - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_price; - CREATE TEMPORARY TABLE tmp.bionic_price - LIKE template_bionic_price; - - INSERT INTO tmp.bionic_price (warehouse_id, item_id, rate, grouping, price) - SELECT * FROM ( - SELECT * FROM t_bionic_rate ORDER BY price - ) t - GROUP BY item_id, warehouse_id, grouping; - - - DROP TEMPORARY TABLE IF EXISTS tmp.travel_tree; - CREATE TEMPORARY TABLE tmp.travel_tree - ENGINE = MEMORY - SELECT * FROM travel_tree; - - -- Limpieza - - DROP TEMPORARY TABLE travel_tree; - DROP TEMPORARY TABLE t_bionic_temp; - DROP TEMPORARY TABLE t_component_sum; - DROP TEMPORARY TABLE t_components_base; - DROP TEMPORARY TABLE t_bionic_rate; - DROP TEMPORARY TABLE tmp.bionic_component_copy; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_calc_component_beta` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc_component_beta`( - -- v_date DATE, -- fecha de recepcion de mercancia - v_consigna INT, - v_agencia INT) -proc: BEGIN - - DECLARE v_customer INT; - DECLARE COEFICIENTE_DE_INFLACION_GENERAL INT DEFAULT 1.3; - DECLARE DENSIDAD_MINIMA_PESO_VOLUMETRICO INT DEFAULT 167; - DECLARE VOLUMEN_CAJA_VERDNATURA BIGINT DEFAULT 138000; - -- DECLARE vValorEmbolsado DOUBLE DEFAULT 0.04; - - SELECT Id_Cliente INTO v_customer FROM Consignatarios WHERE Id_Consigna = v_consigna; - SET @rate2 := 0; - SET @rate3 := 0; - - DROP TEMPORARY TABLE IF EXISTS t_bionic_temp; - CREATE TEMPORARY TABLE t_bionic_temp - (PRIMARY KEY (item_id,warehouse_id)) - ENGINE = MEMORY - SELECT - b.item_id, b.warehouse_id,available, - IF((@rate2 := IFNULL(pf.rate_2,c.Tarifa2)) < a.PVP AND a.`Min`, a.PVP, @rate2) * 1.0 rate_2, - IF((@rate3 := IFNULL(pf.rate_3,c.Tarifa3)) < a.PVP AND a.`Min`, a.PVP, @rate3) * 1.0 rate_3, - ifnull(pf.rate_3,0) AS min_price, - IFNULL(pf.Packing,c.Packing) packing, - IFNULL(pf.grouping,c.grouping) grouping, - ABS(IFNULL(pf.caja,c.caja)) box, - b.buy_id, a.tipo_id - FROM tmp.bionic_lot b - JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra - JOIN vn2008.Articles a ON b.item_id = a.Id_Article - JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = t.reino_id - LEFT JOIN vn2008.PreciosEspeciales p ON a.Id_Article = p.Id_Article AND p.Id_Cliente = v_customer - LEFT JOIN ( - SELECT * FROM ( - SELECT p.item_id, p.grouping, p.Packing,p.caja, p.rate_2, p.rate_3, t.warehouse_id - FROM vn2008.price_fixed p - JOIN vn2008.travel_tree t ON t.warehouse_id = p.warehouse_id OR p.warehouse_id = 0 - WHERE t.Fecha_envio BETWEEN p.date_start AND p.date_end ORDER BY p.item_id, p.warehouse_id DESC - ) t - GROUP BY item_id, warehouse_id - ) pf ON pf.item_id = b.item_id AND pf.warehouse_id = b.warehouse_id - -- descartamos articulos con coste menor de 0.01 - WHERE Costefijo + Portefijo + Embalajefijo + Comisionfija > 0.01 AND r.display <> 0; - - -- Creamos la tabla tmp.bionic_component - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component; - CREATE TEMPORARY TABLE tmp.bionic_component LIKE - template_bionic_component; - - -- Componentes del precio, valores absolutos - INSERT INTO tmp.bionic_component ( warehouse_id, item_id, component_id, cost) - SELECT b.warehouse_id, b.item_id, 29, rate_3 - Costefijo - Portefijo - Embalajefijo - Comisionfija - FROM t_bionic_temp b - JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra; - - INSERT INTO tmp.bionic_component ( warehouse_id, item_id, component_id, cost) - SELECT b.warehouse_id, b.item_id, 28, Costefijo + Portefijo + Embalajefijo + Comisionfija - FROM t_bionic_temp b - JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra; - - -- Ahora los valores en funcion de la base - - DROP TEMPORARY TABLE IF EXISTS t_components_base; - - CREATE TEMPORARY TABLE t_components_base - SELECT bc.item_id, ROUND(SUM(cost), 4) AS base, bc.warehouse_id - FROM tmp.bionic_component bc - GROUP BY bc.item_id,warehouse_id; - - -- La ratio se calcula teniendo en cuenta el valor de las reclamaciones y el saldo de greuge - - INSERT INTO tmp.bionic_component - SELECT cb.warehouse_id, item_id, 17, ROUND(base * LEAST(recobro,0.25), 3) - FROM t_components_base cb - JOIN bi.claims_ratio ON Id_Cliente = v_customer - WHERE recobro > 0.009; - - -- PAK 2016-08-31 Componente de maná automático, en función del maná acumulado por el comercial. - - INSERT INTO tmp.bionic_component - SELECT cb.warehouse_id, item_id, 39, ROUND(base * prices_modifier_rate, 3) as manaAuto - FROM t_components_base cb - JOIN Clientes c on c.Id_Cliente = v_customer - JOIN bs.mana_spellers ms ON c.Id_Trabajador = ms.Id_Trabajador - WHERE ms.prices_modifier_activated - HAVING manaAuto <> 0 ; - - -/* - -- Vendedor variable - INSERT INTO tmp.bionic_component - SELECT cb.warehouse_id, item_id, Id_Componente, IFNULL(ROUND(base * tax,4), 0) - FROM t_components_base cb - JOIN bi.tarifa_componentes - WHERE tarifa_componentes_series_id = 2 and IFNULL(tax, 0) > 0; - */ - - --- ******* Inicio Bloque para componentes con tarifa_class diferente de NULL - -- Descuento por ultimas unidades - INSERT INTO tmp.bionic_component - SELECT cb.warehouse_id, b.item_id, Id_Componente, GREATEST(IFNULL(ROUND(base * tax,4), 0), b.min_price - b.rate_3) - FROM t_components_base cb - JOIN bi.tarifa_componentes - JOIN t_bionic_temp b ON b.item_id = cb.item_id - LEFT JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id - WHERE Id_Componente = 32 AND tax <> 0 AND b.min_price < b.rate_3 AND PrecioEspecial IS NULL; - - -- Incremento por paquete suelto - INSERT INTO tmp.bionic_component - SELECT b.warehouse_id, b.item_id, 22, rate_2 - rate_3 - FROM t_bionic_temp b - JOIN vn2008.Compres c ON b.buy_id = c.Id_Compra - LEFT JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id - WHERE PrecioEspecial IS NULL; - --- ******* Fin Bloque para componentes con tarifa_class diferente de NULL - - -- Reparto - INSERT INTO tmp.bionic_component - SELECT b.warehouse_id - , b.item_id - , 15 - , COEFICIENTE_DE_INFLACION_GENERAL - * ROUND( - r.cm3 - * IF(a.Vista = 1, (GREATEST(art.density,DENSIDAD_MINIMA_PESO_VOLUMETRICO) / DENSIDAD_MINIMA_PESO_VOLUMETRICO ) , 1) - * az.price - * az.inflacion - / VOLUMEN_CAJA_VERDNATURA, 4 - ) cost - FROM t_bionic_temp b - JOIN vn2008.Articles art ON art.Id_Article = b.item_id - JOIN vn2008.Agencias a ON a.Id_Agencia = v_agencia - JOIN vn2008.Consignatarios c ON c.Id_Consigna = v_consigna - JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = b.warehouse_id AND ap.province_id = c.province_id - JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = v_agencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = b.warehouse_id - LEFT JOIN bi.rotacion r ON r.warehouse_id = b.warehouse_id AND r.Id_Article = b.item_id - HAVING cost <> 0; - --- Reparto bonificado - INSERT INTO tmp.bionic_component - SELECT b.warehouse_id - , b.item_id - , 41 - , COEFICIENTE_DE_INFLACION_GENERAL - * ROUND( - r.cm3 - * IF(a.Vista = 1, (GREATEST(art.density,DENSIDAD_MINIMA_PESO_VOLUMETRICO) / DENSIDAD_MINIMA_PESO_VOLUMETRICO ) , 1) - * awb.bonus - * az.inflacion - / VOLUMEN_CAJA_VERDNATURA, 4 - ) cost - FROM t_bionic_temp b - JOIN vn2008.Articles art ON art.Id_Article = b.item_id - JOIN vn2008.Agencias a ON a.Id_Agencia = v_agencia - JOIN vn2008.Consignatarios c ON c.Id_Consigna = v_consigna - JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = b.warehouse_id AND ap.province_id = c.province_id - JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = v_agencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = b.warehouse_id - JOIN vn2008.agency_weekday_bonus awb ON awb.warehouse_id = az.warehouse_id AND awb.zona = az.zona AND a.agency_id = awb.agency_id - LEFT JOIN bi.rotacion r ON r.warehouse_id = b.warehouse_id AND r.Id_Article = b.item_id - JOIN vn2008.travel_tree t ON t.warehouse_id = awb.warehouse_id AND weekday(t.Fecha_recepcion) = awb.weekDay - HAVING cost <> 0; - --- PAK 12-05-2015 - -- EMBOLSADO - IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = v_consigna) THEN - - -- IF v_consigna IN (13690, 3402, 5661, 4233) THEN - - INSERT INTO tmp.bionic_component - SELECT b.warehouse_id, b.item_id, 38, ap.packagingValue cost - FROM t_bionic_temp b - JOIN vn.addressForPackaging ap - WHERE ap.addressFk = v_consigna; - - END IF; - - -- JGF 14-08-2015 - -- Modificacion de precio por dia de preparacion del pedido - INSERT INTO tmp.bionic_component - SELECT cb.warehouse_id, cb.item_id, 14, cb.base * (IFNULL(pe.percentage,pp.percentage)/100) - FROM t_components_base cb - JOIN vn2008.travel_tree tt ON tt.warehouse_id = cb.warehouse_id - LEFT JOIN vn2008.preparation_percentage pp ON pp.week_day = weekday(tt.Fecha_envio) AND cb.warehouse_id = IFNULL(pp.warehouse_id,cb.warehouse_id) - LEFT JOIN vn2008.preparation_exception pe ON pe.exception_day = tt.Fecha_envio AND cb.warehouse_id = IFNULL(pe.warehouse_id,cb.warehouse_id) - WHERE IFNULL(pe.percentage,pp.percentage); - - -- Creamos la tabla tmp.bionic_component_copy por que mysql no puede reabrir una tabla temporal - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component_copy; - CREATE TEMPORARY TABLE tmp.bionic_component_copy - SELECT * FROM tmp.bionic_component; - - -- JGF 19-01-2016 - -- Precios especiales - INSERT INTO tmp.bionic_component - SELECT b.warehouse_id, b.item_id, 10, pe.PrecioEspecial - SUM(cost) sum_cost - FROM tmp.bionic_component_copy b - JOIN bi.tarifa_componentes t ON b.component_id = t.Id_Componente - JOIN PreciosEspeciales pe ON pe.Id_Cliente = v_customer AND pe.Id_Article = b.item_id - WHERE t.tarifa_class IS NULL - GROUP BY b.item_id, b.warehouse_id - HAVING ABS(sum_cost) > 0.001; - - - - - -- Lotes - DROP TEMPORARY TABLE IF EXISTS t_component_sum; - CREATE TEMPORARY TABLE t_component_sum - (INDEX (item_id, warehouse_id)) - ENGINE = MEMORY - SELECT SUM(cost) sum_cost, b.item_id, b.warehouse_id, t.tarifa_class - FROM tmp.bionic_component b - JOIN bi.tarifa_componentes t ON b.component_id = t.Id_Componente - GROUP BY b.item_id, b.warehouse_id, t.tarifa_class; - - -- ***** Inicia Modifica t_bionic_rate las diferentes tarifas - -- Tarifa por unidad minima - DROP TEMPORARY TABLE IF EXISTS t_bionic_rate; - CREATE TEMPORARY TABLE t_bionic_rate - ENGINE = MEMORY - SELECT b.warehouse_id, item_id, 1 rate, - IF(box = 1, grouping, 1) grouping, SUM(sum_cost) price - FROM t_bionic_temp b - JOIN t_component_sum cs USING(item_id, warehouse_id) - WHERE IFNULL(cs.tarifa_class,1) = 1 AND box < 2 AND (packing > grouping or box = 0) - GROUP BY warehouse_id, item_id; - - -- Tarifa por caja - INSERT INTO t_bionic_rate (warehouse_id, item_id, rate, grouping, price) - SELECT b.warehouse_id, item_id, 2 rate, packing grouping, - SUM(sum_cost) price - FROM t_bionic_temp b - JOIN t_component_sum cs USING(item_id, warehouse_id) - WHERE available IS NULL OR (IFNULL(cs.tarifa_class,2) = 2 AND packing > 0 AND available >= packing) - GROUP BY warehouse_id, item_id; - - -- Tarifa para toda la cantidad disponible - INSERT INTO t_bionic_rate (warehouse_id, item_id, rate, grouping, price) - SELECT b.warehouse_id, item_id, 3 rate, available grouping, - SUM(sum_cost) price - FROM t_bionic_temp b - JOIN t_component_sum cs USING(item_id, warehouse_id) - WHERE IFNULL(cs.tarifa_class,3) = 3 - GROUP BY warehouse_id, item_id; - - -- ***** Fin Modifica t_bionic_rate las diferentes tarifas - - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_price; - CREATE TEMPORARY TABLE tmp.bionic_price - LIKE template_bionic_price; - - INSERT INTO tmp.bionic_price (warehouse_id, item_id, rate, grouping, price) - SELECT * FROM ( - SELECT * FROM t_bionic_rate ORDER BY price - ) t - GROUP BY item_id, warehouse_id, grouping; - - - DROP TEMPORARY TABLE IF EXISTS tmp.travel_tree; - CREATE TEMPORARY TABLE tmp.travel_tree - ENGINE = MEMORY - SELECT * FROM travel_tree; - - -- Limpieza - - DROP TEMPORARY TABLE travel_tree; - DROP TEMPORARY TABLE t_bionic_temp; - DROP TEMPORARY TABLE t_component_sum; - DROP TEMPORARY TABLE t_components_base; - - DROP TEMPORARY TABLE t_bionic_rate; - DROP TEMPORARY TABLE tmp.bionic_component_copy; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_calc_date` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc_date`(v_ticket INT) -proc: BEGIN -/** - * Este procedimiento asigna la fecha de llegada correcta a un ticket. - * - * @param v_ticket Id del ticket - **/ - DECLARE v_shipment DATE; - DECLARE v_agency_id INT; - DECLARE v_wh SMALLINT; - DECLARE v_province INT; - DECLARE v_landing DATE; - - SELECT agency_id, DATE(Fecha), t.warehouse_id, province_id - INTO v_agency_id, v_shipment, v_wh, v_province - FROM Tickets t - JOIN Consignatarios c ON c.Id_Consigna = t.Id_Consigna - JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia - WHERE Id_Ticket = v_ticket; - - SELECT landing INTO v_landing FROM ( - SELECT - @d := TIMESTAMPADD(DAY, subtract_day, v_shipment), - @w := WEEKDAY(@d), - IF(week_day IS NOT NULL, TIMESTAMPADD(DAY, (week_day - @w) + IF(@w > week_day, 7, 0), @d), @d) landing -/* - TIMESTAMPADD(DAY, - IFNULL(IF(WEEKDAY(@vdate) > week_day, 7, 0) + week_day - WEEKDAY(@vdate), - subtract_day) - CAST(subtract_day AS DECIMAL), - @vdate) landing -*/ - FROM agency_hour - WHERE warehouse_id = v_wh - AND (province_id = v_province OR province_id IS NULL) - AND agency_id = v_agency_id - ORDER BY - (province_id IS NOT NULL) * 3 + (week_day IS NOT NULL) DESC, landing - LIMIT 1 - ) t; - - IF v_landing IS NULL THEN - SET v_landing = v_shipment; - END IF; - - UPDATE Tickets SET landing = v_landing WHERE Id_Ticket = v_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 DROP PROCEDURE IF EXISTS `bionic_calc_movement` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc_movement`(IN v_id_mov BIGINT ) -proc: BEGIN - -/* -Este procedimiento bioniza una linea de movimiento -*/ - DECLARE v_shipment DATE; - DECLARE v_customer INT; - DECLARE v_wh SMALLINT; - DECLARE v_agencia INT; - DECLARE v_consigna INT; - DECLARE v_ticket BIGINT; - DECLARE v_id_article BIGINT; - DECLARE v_landing DATE; - DECLARE v_ticket_free BOOLEAN DEFAULT TRUE; - - - SELECT FALSE - INTO v_ticket_free - FROM Tickets t - JOIN Movimientos m ON m.Id_Ticket = t.Id_Ticket - LEFT JOIN vn.ticketState ts on ts.ticket = t.Id_Ticket - WHERE Id_Movimiento = v_id_mov - AND (t.Factura != "" - or - ( - ts.alertLevel > 0 - AND - m.Preu != 0 - ) - ) - LIMIT 1; - - SELECT Id_Ticket, Id_Article INTO v_ticket, v_id_article FROM Movimientos WHERE Id_Movimiento = v_id_mov; - - REPLACE order_Tickets(order_id,Id_Ticket) VALUES(48, v_ticket); - - SELECT Id_Cliente , t.warehouse_id, date(t.Fecha), Id_Consigna , Id_Agencia - INTO v_customer ,v_wh, v_shipment , v_consigna , v_agencia - FROM vn2008.Agencias a - JOIN vn2008.Tickets t using(Id_Agencia) - WHERE Id_Ticket = v_ticket; - - DROP TEMPORARY TABLE IF EXISTS travel_tree; - CREATE TEMPORARY TABLE travel_tree ENGINE = MEMORY - SELECT v_wh warehouse_id, v_shipment Fecha_envio, v_landing Fecha_recepcion; - - CALL item_last_buy_ (v_wh, v_shipment); -- rellena la tabla t_item_last_buy con la ultima compra - DELETE FROM t_item_last_buy WHERE item_id != v_id_article; - - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_lot; - CREATE TEMPORARY TABLE tmp.bionic_lot - SELECT v_wh warehouse_id,NULL available, - m.Id_Article item_id,ilb.buy_id - FROM Movimientos m - LEFT JOIN t_item_last_buy ilb ON ilb.item_id = m.Id_Article - WHERE m.Id_Movimiento = v_id_mov; - - CALL bionic_calc_component(v_consigna,v_agencia); - - DROP TEMPORARY TABLE IF EXISTS tmp.movement; - CREATE TEMPORARY TABLE tmp.movement - (PRIMARY KEY (Id_Movimiento)) ENGINE = MEMORY - SELECT Id_Movimiento,v_wh warehouse_id FROM Movimientos m WHERE m.Id_Movimiento = v_id_mov; - - CALL bionic_movement_update(IF(v_ticket_free,1,6)); -- si el ticket esta facturado, respeta los precios - - -- Log - call Ditacio(v_ticket - ,'Bioniza Linea' - ,'T' - , 20 - , 'proc bionic_calc_movement ' - , v_id_mov); - - -- Limpieza - - DROP TEMPORARY TABLE t_item_last_buy; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_calc_movement_ok` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc_movement_ok`(IN v_ticket BIGINT) -BEGIN - -/* -Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo -*/ - DECLARE v_shipment DATE; - DECLARE v_customer INT; - DECLARE v_wh SMALLINT; - DECLARE v_agencia INT; - DECLARE v_consigna INT; - DECLARE v_landing DATE; - - REPLACE order_Tickets(order_id,Id_Ticket) VALUES(48, v_ticket); - - SELECT Id_Cliente , t.warehouse_id, date(t.Fecha), Id_Consigna , Id_Agencia - INTO v_customer ,v_wh, v_shipment , v_consigna , v_agencia - FROM vn2008.Agencias a - JOIN vn2008.Tickets t using(Id_Agencia) - WHERE Id_Ticket = v_ticket; - - DROP TEMPORARY TABLE IF EXISTS travel_tree; - CREATE TEMPORARY TABLE travel_tree ENGINE = MEMORY - SELECT v_wh warehouse_id, v_shipment Fecha_envio, v_landing Fecha_recepcion; - - CALL item_last_buy_ (v_wh, v_shipment); -- rellena la tabla t_item_last_buy con la ultima compra - - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_lot; - CREATE TEMPORARY TABLE tmp.bionic_lot - SELECT v_wh warehouse_id,NULL available, - m.Id_Article item_id,ilb.buy_id - FROM Movimientos m - LEFT JOIN t_item_last_buy ilb ON ilb.item_id = m.Id_Article - WHERE m.Id_Ticket = v_ticket GROUP BY m.Id_Article; - - CALL bionic_calc_component(v_consigna,v_agencia); - - DROP TEMPORARY TABLE IF EXISTS tmp.movement; - CREATE TEMPORARY TABLE tmp.movement - (PRIMARY KEY (Id_Movimiento)) ENGINE = MEMORY - SELECT Id_Movimiento, v_wh warehouse_id FROM Movimientos m WHERE m.Id_Ticket = v_ticket; - CALL bionic_movement_update(1); - - -- Log - call Ditacio(v_ticket - ,'Bioniza Lineas OK' - ,'T' - , 20 - , 'proc bionic_calc_movement_ok ' - , NULL); - - -- Limpieza - DROP TEMPORARY TABLE t_item_last_buy; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_calc_reverse` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc_reverse`( - vWarehouse INT, - vMargin DECIMAL(10,3), - vRetailedPrice DECIMAL(10,3), - vM3 DECIMAL(10,3), - vConsigna INT, - vAgencia INT) -proc: BEGIN - - DECLARE COEFICIENTE_DE_INFLACION_GENERAL INT DEFAULT 1.3; - DECLARE DENSIDAD_MINIMA_PESO_VOLUMETRICO INT DEFAULT 167; - DECLARE VOLUMEN_CAJA_VERDNATURA BIGINT DEFAULT 138000; - DECLARE vCost DECIMAL(10,4) DEFAULT 0; - DECLARE vCustomer INT; - DECLARE vRecovery DECIMAL(10,4) DEFAULT 0; - DECLARE vMana DECIMAL(10,4) DEFAULT 0; - DECLARE vPort DECIMAL(10,4) DEFAULT 0; - - SELECT Id_Cliente INTO vCustomer FROM Consignatarios WHERE Id_Consigna = vConsigna; - - -- Recobro - SELECT ROUND(LEAST(recobro,0.25), 3) INTO vRecovery - FROM bi.claims_ratio - WHERE Id_Cliente = vCustomer AND recobro > 0.009; - - -- Componente de maná automático, en función del maná acumulado por el comercial. - SELECT ROUND(prices_modifier_rate, 3) INTO vMana - FROM Clientes c - JOIN bs.mana_spellers ms ON c.Id_Trabajador = ms.Id_Trabajador - WHERE ms.prices_modifier_activated AND c.Id_Cliente = vCustomer; - - -- Reparto - SELECT COEFICIENTE_DE_INFLACION_GENERAL - * ROUND( - vM3 - * az.price - * az.inflacion - / VOLUMEN_CAJA_VERDNATURA, 4 - ) INTO vPort - FROM vn2008.Agencias a - JOIN vn2008.Consignatarios c ON c.Id_Consigna = vConsigna AND a.Id_Agencia = vAgencia - JOIN vn2008.Agencias_province ap ON ap.agency_id = a.agency_id AND ap.warehouse_id = vWarehouse AND ap.province_id = c.province_id - JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = vAgencia AND az.zona = ap.zona AND az.Id_Article = 71 AND az.warehouse_id = vWarehouse; - - -- Modificacion de precio por dia de preparacion del pedido - -- No aplicada - - SET vCost = ((vRetailedPrice - vPort) / ( 1 + (vRecovery + vMana))) - vMargin; - - SELECT vCost,vRetailedPrice,vPort,vRecovery,vMana,vMargin,vCustomer; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_calc_ticket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc_ticket`(IN v_ticket BIGINT ) -proc: BEGIN - -/* -Este procedimiento trata de "rebionizar" un ticket, eliminando los componentes existentes e insertandolos de nuevo -*/ - DECLARE v_shipment DATE; - DECLARE v_customer INT; - DECLARE v_wh SMALLINT; - DECLARE v_agencia INT; - DECLARE v_consigna INT; - DECLARE v_landing DATE; - DECLARE v_ticket_free BOOLEAN; - DECLARE v_agency INT; - - CALL bionic_free(); - - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(Factura,"") != "") = FALSE - INTO v_ticket_free - FROM Tickets t LEFT JOIN vn.ticketState ts ON t.Id_Ticket = ts.ticket - WHERE t.Id_Ticket = v_ticket; - - /*SELECT (EtiquetasEmitidas or PedidoImpreso or Firmado or nz(Factura)) = FALSE - INTO v_ticket_free - FROM Tickets - WHERE Id_Ticket = v_ticket;*/ - - REPLACE order_Tickets(order_id, Id_Ticket) VALUES(48, v_ticket); - - SELECT Id_Cliente, t.warehouse_id, date(t.Fecha), Id_Consigna, t.Id_Agencia, landing, a.agency_id - INTO v_customer, v_wh, v_shipment, v_consigna, v_agencia, v_landing, v_agency - FROM vn2008.Tickets t LEFT JOIN vn2008.Agencias a ON t.Id_Agencia = a.Id_Agencia WHERE Id_Ticket = v_ticket; - - DROP TEMPORARY TABLE IF EXISTS travel_tree; - CREATE TEMPORARY TABLE travel_tree ENGINE = MEMORY - SELECT v_wh warehouse_id, v_shipment Fecha_envio, v_landing Fecha_recepcion; - - CALL item_last_buy_ (v_wh, v_shipment); -- rellena la tabla t_item_last_buy con la ultima compra - - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_lot; - CREATE TEMPORARY TABLE tmp.bionic_lot - SELECT v_wh warehouse_id,NULL available, - m.Id_Article item_id,ilb.buy_id - FROM Movimientos m - LEFT JOIN t_item_last_buy ilb ON ilb.item_id = m.Id_Article - WHERE m.Id_Ticket = v_ticket GROUP BY m.Id_Article; - - CALL bionic_calc_component(v_consigna,v_agencia); - - DROP TEMPORARY TABLE IF EXISTS tmp.movement; - CREATE TEMPORARY TABLE tmp.movement - (PRIMARY KEY (Id_Movimiento)) ENGINE = MEMORY - SELECT Id_Movimiento, v_wh warehouse_id - FROM Movimientos m - where m.Id_Ticket = v_ticket; - - CALL bionic_movement_update(IF(v_ticket_free,1,6)); -- si el ticket esta facturado, respeta los precios - - IF v_landing IS NULL THEN - - CALL travel_tree_shipment(v_shipment, v_consigna, v_agency,v_wh); - UPDATE Tickets t - JOIN travel_tree_shipment tts ON t.warehouse_id = tts.warehouse_id - SET t.landing = tts.landing - WHERE Id_Ticket = v_ticket; - - END IF; - -- Limpieza - -- DROP TEMPORARY TABLE t_item_last_buy; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_free` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_free`() -BEGIN - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_lot; - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_item; - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_price; - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_component; - DROP TEMPORARY TABLE IF EXISTS tmp.travel_tree; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_from_item` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_from_item`( - v_date DATE, - v_consigna INT, - v_agencia INT, - v_item INT) -BEGIN - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_calc; - CREATE TEMPORARY TABLE tmp.bionic_calc - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT v_item item_id; - - CALL bionic_calc (v_date, v_consigna, v_agencia); - - DROP TEMPORARY TABLE tmp.bionic_calc; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_from_order` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_from_order`( - v_date DATE, -- fecha de recepcion de mercancia - v_consigna INT, - v_agencia INT, - v_order INT) -BEGIN - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_calc; - CREATE TEMPORARY TABLE tmp.bionic_calc - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT item_id FROM order_row - WHERE order_id = v_order GROUP BY item_id; - - CALL bionic_calc (v_date, v_consigna, v_agencia); - DROP TEMPORARY TABLE tmp.bionic_calc; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_from_ticket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_from_ticket`( - v_date DATE, -- fecha de recepcion de mercancia - v_consigna INT, - v_agencia INT, - v_ticket INT) -BEGIN - DECLARE int_warehouse SMALLINT; - DECLARE v_agency_id INT; - DECLARE v_shipment DATE; - - SELECT warehouse_id INTO int_warehouse FROM Tickets WHERE Id_Ticket = v_ticket; - SELECT agency_id INTO v_agency_id FROM Agencias WHERE Id_Agencia = v_agencia; - - - CALL bionic_free(); - CALL travel_tree(v_date,v_consigna, v_agency_id); - - - SELECT Fecha_envio INTO v_shipment FROM travel_tree WHERE warehouse_id = int_warehouse; - - CALL item_last_buy_ (int_warehouse, v_shipment); - - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_lot; - CREATE TEMPORARY TABLE tmp.bionic_lot - SELECT int_warehouse warehouse_id,NULL available, - m.Id_Article item_id,ilb.buy_id - FROM Movimientos m - LEFT JOIN t_item_last_buy ilb ON ilb.item_id = m.Id_Article - WHERE m.Id_Ticket = v_ticket - AND m.Id_Article != 100 - GROUP BY warehouse_id, item_id; - - DROP TEMPORARY TABLE t_item_last_buy; - - CALL bionic_calc_component ( v_consigna, v_agencia); - - REPLACE INTO tmp.bionic_component (warehouse_id, item_id, component_id, cost) - SELECT t.warehouse_id, m.Id_Article, mc.Id_Componente, mc.Valor - FROM Movimientos_componentes mc - JOIN Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN tarifa_componentes tc ON tc.Id_componente = mc.Id_Componente - WHERE m.Id_Ticket = v_ticket AND tc.is_renewable = FALSE; - - -- para recuperar el shipment en caso de que se necesite - - SET @shipment = v_shipment; - DROP TEMPORARY TABLE tmp.bionic_lot; - - IF IFNULL(v_shipment,CURDATE() - 1) < CURDATE() THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'No se puede realizar el cambio'; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_from_type` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_from_type`( - v_date DATE, -- fecha de recepcion de mercancia - v_consigna INT, - v_agencia INT, - v_type INT) -BEGIN - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_calc; - CREATE TEMPORARY TABLE tmp.bionic_calc - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT Id_Article AS item_id FROM Articles WHERE tipo_id = v_type; - - CALL bionic_calc (v_date, v_consigna, v_agencia); - - DROP TEMPORARY TABLE tmp.bionic_calc; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_make_update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_make_update`( - i_ticket INT - ,i_agencia INT - ,i_consigna INT - ,i_warehouse INT - ,d_shipment DATE - ,d_landing DATE - ,i_option INT) -BEGIN -/** - * Ejecuta los cambios en el ticket, en los movimientos y en los componentes. - */ - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - -- Cambios en el ticket - - START TRANSACTION; - - UPDATE Tickets t - SET - t.Id_Agencia = i_agencia, - t.Id_Consigna = i_consigna, - t.warehouse_id = i_warehouse, - t.landing = d_landing, - t.Fecha = d_shipment - WHERE - t.Id_Ticket = i_ticket; - - -- La opcion 8 es No realizar modificaciones en los precios - - IF i_option <> 8 - THEN - DROP TEMPORARY TABLE IF EXISTS tmp.movement; - CREATE TEMPORARY TABLE tmp.movement - (PRIMARY KEY (Id_Movimiento)) - ENGINE = MEMORY - SELECT Id_Movimiento, i_warehouse warehouse_id - FROM Movimientos m WHERE m.Id_Ticket = i_ticket; - - CALL bionic_movement_update (i_option); - DROP TEMPORARY TABLE tmp.movement; - END IF; - - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_make_updateTest` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_make_updateTest`( - i_ticket INT - ,i_agencia INT - ,i_consigna INT - ,i_warehouse INT - ,d_shipment DATE - ,d_landing DATE - ,i_option INT) -BEGIN -/** - * Ejecuta los cambios en el ticket, en los movimientos y en los componentes. - */ - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - -- Cambios en el ticket - - START TRANSACTION; - - UPDATE Tickets t - SET - t.Id_Agencia = i_agencia, - t.Id_Consigna = i_consigna, - t.warehouse_id = i_warehouse, - t.landing = d_landing, - t.Fecha = d_shipment - WHERE - t.Id_Ticket = i_ticket; - - -- La opcion 8 es No realizar modificaciones en los precios - - IF i_option <> 8 - THEN - DROP TEMPORARY TABLE IF EXISTS tmp.movement; - CREATE TEMPORARY TABLE tmp.movement - (PRIMARY KEY (Id_Movimiento)) - ENGINE = MEMORY - SELECT Id_Movimiento, i_warehouse warehouse_id - FROM Movimientos m WHERE m.Id_Ticket = i_ticket; - - CALL bionic_movement_updateTest(i_option); - DROP TEMPORARY TABLE tmp.movement; - END IF; - - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_movement_update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_movement_update`(i_option INT) -BEGIN -/** - * A partir de la tabla tmp.movement, crea los Movimientos_componentes - * y modifica el campo Preu de la tabla Movimientos - * - * @param i_option integer tipo de actualizacion - * @param table tmp.movement tabla memory con el campo Id_Movimiento, warehouse_id - **/ - DECLARE intComponent INT; - DECLARE bolRENUEVA_COMPONENTES BOOLEAN; - DECLARE bolRESPETA_PRECIOS BOOLEAN; - - CASE i_option - - WHEN 1 THEN -- caso normal - - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = FALSE; - - WHEN 2 THEN - - SET intComponent = 17; -- greuge al client - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = TRUE; - - WHEN 3 THEN - - SET intComponent = 37; -- convertir en maná - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = TRUE; - - WHEN 4 THEN - - SET intComponent = 34; -- greuge contra la cartera del producto - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = TRUE; - - WHEN 5 THEN - - SET intComponent = 35; -- greuge contra la cartera del comprador - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = TRUE; - - WHEN 6 THEN - - SET intComponent = 36; -- descuadre para la empresa - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = TRUE; - - WHEN 7 THEN - -- Insertamos el 80% para el coste - REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento,28, round(((m.Preu * (100 - m.Descuento) /100 ) - SUM(IFNULL(mc.Valor,0))) * 0.8 ,3) - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento - LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente NOT IN (28,29) - GROUP BY m.Id_Movimiento; - - -- Insertamos el 20% para el margen - REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento,29, round(((m.Preu * (100 - m.Descuento) /100 ) - SUM(IFNULL(mc.Valor,0))) * 0.2 ,3) - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento - LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente NOT IN (28,29) - GROUP BY m.Id_Movimiento; - - SET bolRENUEVA_COMPONENTES = FALSE; - SET bolRESPETA_PRECIOS = FALSE; - - WHEN 8 THEN - -- Eliminamos todos los componentes exceptos los propios de la tarifa para no perderla - DELETE mc.* - FROM tmp.movement mo - JOIN Movimientos_componentes mc ON mo.Id_Movimiento = mc.Id_Movimiento; - - -- Insertamos el 100% para el coste Tipo 78 (Genérico) - REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento,28, round(((m.Preu * (100 - m.Descuento) /100 )) ,3) - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento; - - SET bolRENUEVA_COMPONENTES = FALSE; - SET bolRESPETA_PRECIOS = FALSE; - - WHEN 9 THEN -- PAK 2017-02-06 caso especial de artículos cuyo precio se pone a mano, como los portes - - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = TRUE; - - END CASE; - - IF bolRENUEVA_COMPONENTES THEN - - -- Eliminamos todos los componentes exceptos los propios de la tarifa para no perderla - DELETE mc.* - FROM tmp.movement mo - JOIN Movimientos_componentes mc ON mo.Id_Movimiento = mc.Id_Movimiento - JOIN tarifa_componentes tc ON tc.Id_Componente = mc.Id_Componente - WHERE tc.is_renewable = TRUE; - - -- Insertamos los componentes actuales - REPLACE INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento, bc.component_id, bc.cost - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento - JOIN tmp.bionic_component bc ON bc.item_id = m.Id_Article AND bc.warehouse_id = mo.warehouse_id - LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = bc.component_id - LEFT JOIN tarifa_componentes tc ON tc.Id_Componente = bc.component_id - WHERE IF(mc.Id_Componente IS NULL AND tc.is_renewable = FALSE,FALSE,TRUE); - - END IF; - - IF bolRESPETA_PRECIOS THEN - - REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento,intComponent, round((m.Preu * (100 - m.Descuento) /100 ) - SUM(mc.Valor) ,3) dif - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento - LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento - WHERE mc.Id_Componente <> intComponent - GROUP BY m.Id_Movimiento - HAVING dif <> 0; - - ELSE - - -- Cambios en movimientos. - UPDATE Movimientos m - JOIN Articles a on a.Id_Article = m.Id_Article - JOIN Tipos tp on tp.tipo_id = a.tipo_id - JOIN (SELECT SUM(mc.Valor) sum_valor,mc.Id_Movimiento - FROM Movimientos_componentes mc - JOIN tmp.movement m ON m.Id_Movimiento = mc.Id_Movimiento - GROUP BY mc.Id_Movimiento) mc ON mc.Id_Movimiento = m.Id_Movimiento - SET m.Preu = sum_valor - WHERE Tipo != 'Portes'; -- PAK 2017-02-06 - - -- Insertamos descuento, si lo hay - - REPLACE INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento, 21, m.Preu * (100 -m.Descuento) / 100 - sum(Valor) v_valor - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento - JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento - WHERE mc.Id_Componente != 21 - GROUP BY m.Id_Movimiento having round(v_valor,4) <> 0; - - END IF; - - -- Fija el Costfixat - - UPDATE Movimientos m - JOIN (SELECT SUM(mc.Valor) sum_valor,mc.Id_Movimiento - FROM Movimientos_componentes mc - JOIN tmp.movement m ON m.Id_Movimiento = mc.Id_Movimiento - join bi.tarifa_componentes tc using(Id_Componente) - join bi.tarifa_componentes_series tcs on tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id AND tcs.base - GROUP BY mc.Id_Movimiento) mc ON mc.Id_Movimiento = m.Id_Movimiento - SET m.CostFixat = sum_valor, PrecioFijado = 1; - - - -- PAK 2017-02-06 - -- Familia PORTES, un unico componente de porte - - DELETE mc.* - FROM Movimientos_componentes mc - JOIN tmp.movement mo ON mo.Id_Movimiento = mc.Id_Movimiento - JOIN Movimientos m on m.Id_Movimiento = mc.Id_Movimiento - JOIN Articles a ON a.Id_Article = m.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - WHERE Tipo = 'Portes'; - - INSERT INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento, 15, preu -- Reparto - FROM Movimientos m - JOIN tmp.movement mo ON mo.Id_Movimiento = m.Id_Movimiento - JOIN Articles a ON a.Id_Article = m.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - WHERE Tipo = 'Portes' AND preu > 0; - - -- PAK 2017-09-27 - -- Tipos con un unico componente de coste - /* - DELETE mc.* - FROM Movimientos_componentes mc - JOIN tmp.movement mo ON mo.Id_Movimiento = mc.Id_Movimiento - JOIN Movimientos m on m.Id_Movimiento = mc.Id_Movimiento - JOIN Articles a ON a.Id_Article = m.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - WHERE tp.hasComponents = FALSE; - - INSERT INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento, 28, preu -- Coste - FROM Movimientos m - JOIN tmp.movement mo ON mo.Id_Movimiento = m.Id_Movimiento - JOIN Articles a ON a.Id_Article = m.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - WHERE tp.hasComponents = FALSE; -*/ - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_movement_updateTest` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_movement_updateTest`(i_option INT) -BEGIN -/** - * A partir de la tabla tmp.movement, crea los Movimientos_componentes - * y modifica el campo Preu de la tabla Movimientos - * - * @param i_option integer tipo de actualizacion - * @param table tmp.movement tabla memory con el campo Id_Movimiento, warehouse_id - **/ - DECLARE intComponent INT; - DECLARE bolRENUEVA_COMPONENTES BOOLEAN; - DECLARE bolRESPETA_PRECIOS BOOLEAN; - - CASE i_option - - WHEN 1 THEN -- caso normal - - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = FALSE; - - WHEN 2 THEN - - SET intComponent = 17; -- greuge al client - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = TRUE; - - WHEN 3 THEN - - SET intComponent = 37; -- convertir en maná - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = TRUE; - - WHEN 4 THEN - - SET intComponent = 34; -- greuge contra la cartera del producto - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = TRUE; - - WHEN 5 THEN - - SET intComponent = 35; -- greuge contra la cartera del comprador - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = TRUE; - - WHEN 6 THEN - - SET intComponent = 36; -- descuadre para la empresa - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = TRUE; - - WHEN 7 THEN - -- Insertamos el 80% para el coste - REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento,28, round(((m.Preu * (100 - m.Descuento) /100 ) - SUM(IFNULL(mc.Valor,0))) * 0.8 ,3) - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento - LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente NOT IN (28,29) - GROUP BY m.Id_Movimiento; - - -- Insertamos el 20% para el margen - REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento,29, round(((m.Preu * (100 - m.Descuento) /100 ) - SUM(IFNULL(mc.Valor,0))) * 0.2 ,3) - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento - LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente NOT IN (28,29) - GROUP BY m.Id_Movimiento; - - SET bolRENUEVA_COMPONENTES = FALSE; - SET bolRESPETA_PRECIOS = FALSE; - - WHEN 8 THEN - -- Eliminamos todos los componentes exceptos los propios de la tarifa para no perderla - DELETE mc.* - FROM tmp.movement mo - JOIN Movimientos_componentes mc ON mo.Id_Movimiento = mc.Id_Movimiento; - - -- Insertamos el 100% para el coste Tipo 78 (Genérico) - REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento,28, round(((m.Preu * (100 - m.Descuento) /100 )) ,3) - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento; - - SET bolRENUEVA_COMPONENTES = FALSE; - SET bolRESPETA_PRECIOS = FALSE; - - WHEN 9 THEN -- PAK 2017-02-06 caso especial de artículos cuyo precio se pone a mano, como los portes - - SET bolRENUEVA_COMPONENTES = TRUE; - SET bolRESPETA_PRECIOS = TRUE; - - END CASE; - - IF bolRENUEVA_COMPONENTES THEN - - -- Eliminamos todos los componentes exceptos los propios de la tarifa para no perderla - DELETE mc.* - FROM tmp.movement mo - JOIN Movimientos_componentes mc ON mo.Id_Movimiento = mc.Id_Movimiento - JOIN tarifa_componentes tc ON tc.Id_Componente = mc.Id_Componente - WHERE tc.is_renewable = TRUE; - SELECT m.Id_Movimiento, bc.component_id, bc.cost - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento - JOIN tmp.bionic_component bc ON bc.item_id = m.Id_Article AND bc.warehouse_id = mo.warehouse_id - LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = bc.component_id - LEFT JOIN tarifa_componentes tc ON tc.Id_Componente = bc.component_id - WHERE IF(mc.Id_Componente IS NULL AND tc.is_renewable = FALSE,FALSE,TRUE); - -- Insertamos los componentes actuales - REPLACE INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento, bc.component_id, bc.cost - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento - JOIN tmp.bionic_component bc ON bc.item_id = m.Id_Article AND bc.warehouse_id = mo.warehouse_id - LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = bc.component_id - LEFT JOIN tarifa_componentes tc ON tc.Id_Componente = bc.component_id - WHERE IF(mc.Id_Componente IS NULL AND tc.is_renewable = FALSE,FALSE,TRUE); - - END IF; - - IF bolRESPETA_PRECIOS THEN - - REPLACE INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento,intComponent, round((m.Preu * (100 - m.Descuento) /100 ) - SUM(mc.Valor) ,3) dif - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento - LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento - WHERE mc.Id_Componente <> intComponent - GROUP BY m.Id_Movimiento - HAVING dif <> 0; - - SELECT m.Id_Movimiento,intComponent, round((m.Preu * (100 - m.Descuento) /100 ) - SUM(mc.Valor) ,3) dif - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento - LEFT JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento - WHERE mc.Id_Componente <> intComponent - GROUP BY m.Id_Movimiento - HAVING dif <> 0; - ELSE - - -- Cambios en movimientos. - UPDATE Movimientos m - JOIN Articles a on a.Id_Article = m.Id_Article - JOIN Tipos tp on tp.tipo_id = a.tipo_id - JOIN (SELECT SUM(mc.Valor) sum_valor,mc.Id_Movimiento - FROM Movimientos_componentes mc - JOIN tmp.movement m ON m.Id_Movimiento = mc.Id_Movimiento - GROUP BY mc.Id_Movimiento) mc ON mc.Id_Movimiento = m.Id_Movimiento - SET m.Preu = sum_valor - WHERE Tipo != 'Portes'; -- PAK 2017-02-06 - - SELECT SUM(mc.Valor) sum_valor,mc.Id_Movimiento - FROM Movimientos_componentes mc - JOIN tmp.movement m ON m.Id_Movimiento = mc.Id_Movimiento - GROUP BY mc.Id_Movimiento; - - -- Insertamos descuento, si lo hay - - REPLACE INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento, 21, m.Preu * (100 -m.Descuento) / 100 - sum(Valor) v_valor - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento - JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento - WHERE mc.Id_Componente != 21 - GROUP BY m.Id_Movimiento having round(v_valor,4) <> 0; - SELECT m.Id_Movimiento, 21, m.Preu * (100 -m.Descuento) / 100 - sum(Valor) v_valor - FROM Movimientos m - JOIN tmp.movement mo ON m.Id_Movimiento = mo.Id_Movimiento - JOIN Movimientos_componentes mc ON mc.Id_Movimiento = m.Id_Movimiento - WHERE mc.Id_Componente != 21 - GROUP BY m.Id_Movimiento having round(v_valor,4) <> 0; - END IF; - - -- Fija el Costfixat - - UPDATE Movimientos m - JOIN (SELECT SUM(mc.Valor) sum_valor,mc.Id_Movimiento - FROM Movimientos_componentes mc - JOIN tmp.movement m ON m.Id_Movimiento = mc.Id_Movimiento - join bi.tarifa_componentes tc using(Id_Componente) - join bi.tarifa_componentes_series tcs on tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id AND tcs.base - GROUP BY mc.Id_Movimiento) mc ON mc.Id_Movimiento = m.Id_Movimiento - SET m.CostFixat = sum_valor, PrecioFijado = 1; - - - -- PAK 2017-02-06 - -- Familia PORTES, un unico componente de porte - - DELETE mc.* - FROM Movimientos_componentes mc - JOIN tmp.movement mo ON mo.Id_Movimiento = mc.Id_Movimiento - JOIN Movimientos m on m.Id_Movimiento = mc.Id_Movimiento - JOIN Articles a ON a.Id_Article = m.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - WHERE Tipo = 'Portes'; - - INSERT INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento, 15, preu -- Reparto - FROM Movimientos m - JOIN tmp.movement mo ON mo.Id_Movimiento = m.Id_Movimiento - JOIN Articles a ON a.Id_Article = m.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - WHERE Tipo = 'Portes' AND preu > 0; - - -- PAK 2017-09-27 - -- Tipos con un unico componente de coste - /* - DELETE mc.* - FROM Movimientos_componentes mc - JOIN tmp.movement mo ON mo.Id_Movimiento = mc.Id_Movimiento - JOIN Movimientos m on m.Id_Movimiento = mc.Id_Movimiento - JOIN Articles a ON a.Id_Article = m.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - WHERE tp.hasComponents = FALSE; - - INSERT INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento, 28, preu -- Coste - FROM Movimientos m - JOIN tmp.movement mo ON mo.Id_Movimiento = m.Id_Movimiento - JOIN Articles a ON a.Id_Article = m.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - WHERE tp.hasComponents = FALSE; -*/ - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_movement_update_mode` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_movement_update_mode`(IN idMOV BIGINT, IN i_MODE INT) -BEGIN - - DROP TEMPORARY TABLE IF EXISTS tmp.movement; - CREATE TEMPORARY TABLE tmp.movement - (PRIMARY KEY (Id_Movimiento)) ENGINE = MEMORY - SELECT Id_Movimiento, warehouse_id - FROM Movimientos m - JOIN Tickets t using(Id_Ticket) - WHERE m.Id_Movimiento = idMOV; - - CALL bionic_movement_update(i_MODE); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_movimiento_precio_update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_movimiento_precio_update`(IN i_mov INT) -BEGIN - -DECLARE d_compo_precio DOUBLE; -DECLARE d_mov_precio DOUBLE; - -SELECT SUM(Valor) INTO d_compo_precio -FROM bi.movimientos_componentes -WHERE Id_Movimiento = i_mov; - -SELECT Preu INTO d_mov_precio -FROM Movimientos -WHERE Id_Movimiento = i_mov; - -IF d_mov_precio <> d_compo_precio -AND d_compo_precio IS NOT NULL -AND d_mov_precio IS NOT NULL -THEN - - INSERT INTO bi.movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - VALUES (i_mov, 21, d_mov_precio - d_compo_precio) - ON DUPLICATE KEY UPDATE Valor = Valor + d_mov_precio - d_compo_precio ; - -END IF; - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_tickets_range_bionizar` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_tickets_range_bionizar`(IN datSTART DATE, IN datEND DATE) -BEGIN -DECLARE done BIT DEFAULT 0; -DECLARE datEND_Midnight DATETIME DEFAULT vn2008.dayend(datEND); -DECLARE v_ticket BIGINT; -DECLARE rs CURSOR FOR -SELECT DISTINCT t.Id_Ticket -FROM -( - -- Movimientos que no coincide la suma de los componentes con el precio -select t.Id_Ticket, IFNULL(sum(Valor),0) - (Preu * (100 - m.Descuento)/100) as Diferencia, NULL as Nothing - from vn2008.Tickets t - join vn2008.Movimientos m on t.Id_Ticket = m.Id_Ticket - join vn2008.Articles a using(Id_Article) - left join vn2008.Movimientos_componentes mc using(Id_Movimiento) - join vn2008.Tipos tp on a.tipo_id = tp.tipo_id - where t.Fecha between datSTART and datEND_Midnight - and not tp.confeccion - and m.Cantidad > 0 - and tp.reino_id != 6 - group by Id_Movimiento - having ABS(Diferencia) > 1 OR (Diferencia IS NULL) - -UNION ALL - -- Movimientos sin componente de coste - SELECT DISTINCT t.Id_Ticket, NULL, NULL - FROM Tickets t - JOIN Movimientos m ON t.Id_Ticket = m.Id_Ticket - JOIN Articles a ON a.Id_Article = m.Id_Article - LEFT JOIN - ( - SELECT DISTINCT t.Id_Ticket, 0 - FROM Tickets t - JOIN Movimientos m on m.Id_Ticket = t.Id_Ticket - JOIN Articles a on a.Id_Article = m.Id_Article - JOIN Tipos tp on a.tipo_id = tp.tipo_id - JOIN Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento - JOIN tarifa_componentes tc on tc.Id_Componente = mc.Id_Componente - WHERE (tarifa_componentes_series_id = 1 OR tp.reino_id = 6) - AND t.Fecha between datSTART and datEND_Midnight - ) sub on sub.Id_Ticket = t.Id_Ticket - WHERE sub.Id_Ticket IS NULL - AND t.Fecha between datSTART and datEND_Midnight - AND a.tipo_id != 84 -- Portes - AND a.tipo_id != 78 -- Genericos - AND t.Id_Cliente NOT IN (200,400) - AND t.warehouse_id != 13 -- Inventario - -UNION ALL - -- Movimientos sin porte en tickets con agencia que SI que deberia de llevar - SELECT m.Id_Ticket, count(Id_Movimiento) as Lineas_totales, Lineas_conPorte - FROM Movimientos m - JOIN Articles a on a.Id_Article = m.Id_Article - JOIN Tipos tp on tp.tipo_id = a.tipo_id - JOIN Tickets t on m.Id_Ticket = t.Id_Ticket - JOIN v_expeditions_shipping_charge v on v.Id_ticket = t.Id_Ticket - LEFT JOIN - ( - SELECT m.Id_Ticket, count(Id_Componente) Lineas_conPorte - FROM Movimientos_componentes mc - JOIN Movimientos m using(Id_Movimiento) - JOIN Tickets t using(Id_Ticket) - WHERE Id_Componente = 15 - AND Fecha between datSTART and datEND_Midnight - GROUP BY m.Id_Ticket - ) sub on sub.Id_Ticket = t.Id_Ticket - WHERE t.Fecha between datSTART and datEND_Midnight - AND Preu != 0 - AND tp.reino_id != 6 - AND shipping_charge > 1 - GROUP BY m.Id_Ticket - HAVING Lineas_totales > IFNULL(Lineas_conPorte,0) - - - -) sub -JOIN Tickets t ON t.Id_Ticket = sub.Id_Ticket -JOIN warehouse w ON w.id = t.warehouse_id -WHERE w.inventario; - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - - - - -OPEN rs; - -FETCH rs INTO v_ticket ; - -WHILE NOT done DO - - CALL bionic_calc_ticket(v_ticket); - - call Ditacio(v_ticket - ,'Bioniza Ticket' - ,'T' - , 20 - , 'proc bionic_tickets_range_bionizar' - , NULL); - - FETCH rs INTO v_ticket ; - -END WHILE; - - -CLOSE rs; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bonus_comparados` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bonus_comparados`() -BEGIN - -SELECT CodigoTrabajador as Comercial - , T.Fecha - , bs.Id_Ticket - , T.Alias - , bs.Id_Article - , A.Article - , A.Medida - ,A.Categoria - , O.Abreviatura - , bs.amount - , bs.bonus - , amount * bonus * IF(bonus_buenos.bonus_sales_id IS NULL,0,1) as saldo -FROM bonus_sales bs -JOIN Articles A USING(Id_Article) -JOIN Trabajadores USING(Id_Trabajador) -JOIN Tickets T USING(Id_Ticket) -JOIN Clientes C USING(Id_Cliente) -JOIN Origen O ON O.id = A.id_origen -JOIN Permisos P ON bs.Id_Trabajador = P.Id_Trabajador -LEFT JOIN ( - select b.bonus_sales_id - from bonus_sales b - left join Movimientos M using(Id_Ticket, Id_Article) - join Tickets T on T.Id_Ticket = b.Id_Ticket - where Fecha >= '2012-12-01' - and Cantidad > amount / 2 - ) bonus_buenos USING(bonus_sales_id) - -WHERE T.Fecha > '2012-12-01' AND invoice AND Id_Grupo = 6; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_label` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_label`(IN entry_id_ INT, IN groupby TINYINT(1)) -BEGIN - - DECLARE done INT DEFAULT 0; - DECLARE label INT; - DECLARE id INT; - DECLARE recordset CURSOR FOR SELECT Compres.Etiquetas, Compres.Id_Compra FROM Compres INNER JOIN - (SELECT e.Id_entrada FROM Entradas e INNER JOIN ( - SELECT Id_Entrada,Inventario,Id_proveedor,travel_id,Id_Agencia FROM Entradas e1 INNER JOIN travel t ON e1.travel_id = t.id WHERE Id_Entrada = entry_id_) y - ON y.Inventario = e.Inventario AND e.travel_id = y.travel_id AND e.Id_proveedor = y.Id_proveedor AND y.Id_Agencia = e.Id_Agencia - WHERE (0 OR e.Id_Entrada = entry_id_)) entry_label - ON Compres.Id_Entrada = entry_label.Id_entrada - INNER JOIN Articles ON Compres.Id_Article = Articles.Id_Article WHERE Articles.Imprimir <> FALSE; - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - - DROP TEMPORARY TABLE IF EXISTS `buy_label_source`; - - CREATE TEMPORARY TABLE `buy_label_source` - ( - `buy_id` INT(11) NOT NULL - ) - - ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - OPEN recordset; - - REPEAT - - FETCH recordset INTO label, id; - WHILE label > 0 DO - - SET label = label - 1; - INSERT INTO buy_label_source (buy_id) VALUES (id); - - END WHILE; - - UNTIL done END REPEAT; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_label_bunch` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_label_bunch`(IN entry_id_ INT, IN groupby TINYINT(1),IN single TINYINT(1), IN idCOM BIGINT) -BEGIN - DECLARE done INT DEFAULT 0; - DECLARE date_ DATE; - DECLARE provider_id INT; - DECLARE agency_id INT; - DECLARE i_wh INT; - DECLARE label INT; - DECLARE id INT; - DECLARE recordset CURSOR FOR - SELECT ROUND(C.Cantidad / IF(C.caja = FALSE, 1,C.Grouping) + 0.49), C.Id_Compra - FROM Compres C - INNER JOIN entry_label ON C.Id_Entrada = entry_label.entry_id - INNER JOIN Articles A ON C.Id_Article = A.Id_Article - WHERE (A.Imprimir <> FALSE AND idCOM = 0 AND C.Novincular = FALSE) - OR idCOM = C.Id_Compra; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - SET idCOM = IFNULL(idCOM, 0); - - DROP TEMPORARY TABLE IF EXISTS `entry_label`; - CREATE TEMPORARY TABLE `entry_label` - (`entry_id` INT(11) NOT NULL) - ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - - IF groupby <> FALSE THEN - - SELECT Id_Proveedor, DATE(landing), travel.agency_id, warehouse_id - INTO provider_id, date_, agency_id, i_wh - FROM Entradas - INNER JOIN travel ON travel.id = Entradas.travel_id - WHERE Id_Entrada = entry_id_; - - INSERT INTO entry_label (entry_id) - SELECT Entradas.Id_Entrada - FROM Entradas - INNER JOIN travel ON travel.id = Entradas.travel_id - WHERE Entradas.Inventario = FALSE - AND Entradas.Id_Proveedor = provider_id - AND warehouse_id = i_wh - AND DATE(landing) = date_ - AND travel.agency_id= agency_id; - - ELSE - - INSERT INTO entry_label (entry_id) VALUES (entry_id_); - SELECT landing - INTO date_ FROM - Entradas e - JOIN travel t ON t.id = e.travel_id - JOIN Compres c ON c.Id_Entrada = e.Id_Entrada - WHERE (entry_id_ = e.Id_Entrada - OR c.Id_Compra = idCOM) - LIMIT 1; - - END IF; - - DROP TEMPORARY TABLE IF EXISTS `buy_label_source`; - - CREATE TEMPORARY TABLE `buy_label_source` - (`buy_id` INT(11) NOT NULL) - ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - - OPEN recordset; - FETCH recordset INTO label, id; - REPEAT - REPEAT - SET label = label - 1; - INSERT INTO buy_label_source (buy_id) VALUES (id); - UNTIL label <= 0 OR single END REPEAT; - - INSERT INTO buy_label_source (buy_id) VALUES (0); - FETCH recordset INTO label, id; - UNTIL done END REPEAT; - - SELECT - C.Id_Article, - @a:=IF(A.min - AND IFNULL(rate_3, C.Tarifa3) < A.PVP, - A.PVP, - IFNULL(rate_3, C.Tarifa3)) Tarifa2, - ROUND(IF(C.caja = FALSE, @a, @a * C.Grouping), - 2) AS Bunch, - ROUND(@a / A.Tallos, 2) AS PPT, - A.Article, - A.Medida, - A.Color, - A.Categoria, - Abreviatura AS Origen, - p.name Productor, - A.Tallos, - C.grouping, - E.Notas_Eva, - P.Proveedor, - C.Packing - FROM - buy_label_source bls - LEFT JOIN - Compres C ON C.Id_Compra = bls.buy_id - LEFT JOIN - Entradas E ON E.Id_Entrada = C.Id_Entrada - LEFT JOIN - Articles A ON A.Id_Article = C.Id_Article - LEFT JOIN - Proveedores P ON P.Id_Proveedor = E.Id_Proveedor - LEFT JOIN - Origen o ON A.id_origen = o.id - LEFT JOIN - producer p ON p.producer_id = A.producer_id - LEFT JOIN - (SELECT - item_id, rate_3 - FROM - price_fixed - WHERE - IFNULL(date_, CURDATE()) BETWEEN date_start AND date_end - AND rate_3 - AND warehouse_id IN (0 , i_wh) - GROUP BY item_id) pf ON pf.item_id = A.Id_Article; - - DROP TEMPORARY TABLE `entry_label`; - DROP TEMPORARY TABLE `buy_label_source`; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_label_bunchkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_label_bunchkk`(IN entry_id_ INT, IN groupby TINYINT(1),IN single TINYINT(1), IN idCOM BIGINT) -BEGIN - DECLARE done INT DEFAULT 0; - DECLARE date_ DATE; - DECLARE provider_id INT; - DECLARE agency_id INT; - DECLARE i_wh INT; - DECLARE label INT; - DECLARE id INT; - DECLARE recordset CURSOR FOR - SELECT ROUND(C.Cantidad / IF(C.caja = FALSE, 1,C.Grouping) + 0.49), C.Id_Compra - FROM Compres C - INNER JOIN entry_label ON C.Id_Entrada = entry_label.entry_id - INNER JOIN Articles A ON C.Id_Article = A.Id_Article - WHERE (A.Imprimir <> FALSE AND idCOM = 0 AND C.Novincular = FALSE) - OR idCOM = C.Id_Compra; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - SET idCOM = IFNULL(idCOM, 0); - - DROP TEMPORARY TABLE IF EXISTS `entry_label`; - CREATE TEMPORARY TABLE `entry_label` - ( - `entry_id` INT(11) NOT NULL - ) - ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - - IF groupby <> FALSE THEN - - SELECT Id_Proveedor, DATE(landing), travel.agency_id, warehouse_id INTO provider_id, date_, agency_id, i_wh - FROM Entradas - INNER JOIN travel ON travel.id = Entradas.travel_id - - WHERE Id_Entrada = entry_id_; - - INSERT INTO entry_label (entry_id) SELECT Entradas.Id_Entrada FROM Entradas - - INNER JOIN travel ON travel.id = Entradas.travel_id - - WHERE Entradas.Inventario = FALSE AND Entradas.Id_Proveedor = provider_id - - AND warehouse_id = i_wh AND DATE(landing) = date_ AND travel.agency_id= agency_id; - - ELSE - - INSERT INTO entry_label (entry_id) VALUES (entry_id_); - SELECT landing INTO date_ FROM Entradas e - JOIN travel t ON t.id = e.travel_id - JOIN Compres c ON c.Id_Entrada = e.Id_Entrada - WHERE (entry_id_ = e.Id_Entrada OR c.Id_Compra = idCOM) LIMIT 1; - - END IF; - - - DROP TEMPORARY TABLE IF EXISTS `buy_label_source`; - - CREATE TEMPORARY TABLE `buy_label_source` - ( - `buy_id` INT(11) NOT NULL - ) - ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - - OPEN recordset; - FETCH recordset INTO label, id; - REPEAT - REPEAT - - SET label = label - 1; - INSERT INTO buy_label_source (buy_id) VALUES (id); - UNTIL label <= 0 OR single END REPEAT; - - INSERT INTO buy_label_source (buy_id) VALUES (0); - FETCH recordset INTO label, id; - UNTIL done END REPEAT; - - SELECT C.Id_Article,@a := IF(A.min AND IFNULL(rate_3,C.Tarifa3) < A.PVP, A.PVP, IFNULL(rate_3,C.Tarifa3)) Tarifa2, - ROUND(IF(C.caja = FALSE, @a,@a * C.Grouping),2) AS Bunch, - ROUND(@a / A.Tallos,2) AS PPT, - A.Article, A.Medida, A.Color, A.Categoria, Abreviatura as Origen, C.Productor, - A.Tallos, C.grouping, E.Notas_Eva,P.Proveedor,C.Packing - FROM buy_label_source bls - LEFT JOIN Compres C ON C.Id_Compra = bls.buy_id - LEFT JOIN Entradas E ON E.Id_Entrada = C.Id_Entrada - LEFT JOIN Articles A ON A.Id_Article = C.Id_Article - LEFT JOIN Proveedores P ON P.Id_Proveedor = E.Id_Proveedor - LEFT JOIN Origen o ON A.id_origen = o.id - LEFT JOIN ( - SELECT item_id, rate_3 FROM price_fixed - WHERE IFNULL(date_,CURDATE()) BETWEEN date_start AND date_end AND rate_3 - AND warehouse_id IN (0,i_wh) - GROUP BY item_id - ) pf ON pf.item_id = A.Id_Article; - -- JGF 02/02/15 canvie CURDATE() per IFNULL(date_,CURDATE()) - - DROP TEMPORARY TABLE `entry_label`; - DROP TEMPORARY TABLE `buy_label_source`; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_scan` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_scan`(v_barcode VARCHAR(255), v_labels INT) -BEGIN -/** - * Marca una compra de subasta como escaneada. - * - * @param v_barcode Código de compra de una etiqueta de subasta - * @param v_labels Cantidad escaneada - **/ - DECLARE v_edi INT; - DECLARE v_buy INT; - DECLARE v_item INT; - DECLARE v_do_photo BOOL; - - -- Aun no se sabe como obtener el número de serie de transacción de - -- las compras realizadas a través de un reloj, por lo que se establece - -- siempre a '01' - - IF SUBSTR(v_barcode, 3, 2) != '99' THEN - SET v_barcode = CONCAT(LEFT(v_barcode, 12), '010'); - END IF; - - SELECT e.id, c.Id_Compra, c.Id_Article, a.do_photo - INTO v_edi, v_buy, v_item, v_do_photo - FROM buy_edi e - JOIN Compres c ON c.buy_edi_id = e.id - JOIN Articles a ON a.Id_Article = c.Id_Article - WHERE e.barcode = v_barcode - AND e.entry_year = YEAR(CURDATE()) - ORDER BY c.Id_Compra - LIMIT 1; - - UPDATE buy_edi SET scanned = TRUE WHERE id = v_edi; - - UPDATE Compres - SET Vida = Vida + IF(v_labels != -1, v_labels, Etiquetas) - WHERE Id_Compra = v_buy; - - IF v_do_photo THEN - UPDATE Articles SET do_photo = FALSE WHERE Id_Article = v_item; - END IF; - - SELECT v_buy buy, v_do_photo do_photo; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_split` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_split`(v_buy INT, v_fv_entry INT, v_pca_entry INT) -BEGIN - DECLARE v_item INT; - DECLARE v_packing INT; - DECLARE v_remaining INT; - DECLARE v_labels INT; - DECLARE v_remainder INT; - DECLARE v_is_buy INT; - DECLARE v_id INT; - DECLARE v_amount INT; - DECLARE v_done BOOL DEFAULT FALSE; - - DECLARE cur CURSOR FOR - SELECT TRUE, c.Id_Compra, c.Cantidad - IFNULL((c.Vida * c.Packing), 0) - FROM Compres c - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel t ON t.id = e.travel_id - WHERE c.Id_Article = v_item - AND t.shipment = CURDATE() AND t.warehouse_id_out IN (7, 40) - AND t.warehouse_id NOT IN (44, 1) - AND NOT e.redada AND NOT e.Inventario - AND IFNULL(c.Vida, 0) < c.Etiquetas - LOCK IN SHARE MODE - UNION ALL - SELECT FALSE, m.Id_Movimiento, m.Cantidad - IFNULL(l.stem, 0) - FROM Movimientos m - JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket - LEFT JOIN movement_label l ON l.Id_Movimiento = m.Id_Movimiento - WHERE m.Id_Article = v_item - AND t.Fecha = CURDATE() AND t.warehouse_id IN (7, 40) - AND NOT t.Etiquetasemitidas - AND IFNULL(l.stem, 0) < m.Cantidad - LOCK IN SHARE MODE; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET v_done = TRUE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - -- Obtiene los datos de la compra - - SELECT Id_Article, Packing, Cantidad - INTO v_item, v_packing, v_remaining - FROM Compres WHERE Id_Compra = v_buy; - - -- Crea splits de los tickets - - DROP TEMPORARY TABLE IF EXISTS tmp.split; - CREATE TEMPORARY TABLE tmp.split - ( - is_buy BOOL, - id INT, - labels INT, - remainder INT - ) - ENGINE = MEMORY; - - OPEN cur; - - l: LOOP - SET v_done = FALSE; - FETCH cur INTO v_is_buy, v_id, v_amount; - - IF v_done OR v_remaining = 0 THEN - LEAVE l; - END IF; - - SET v_amount = LEAST(v_amount, v_remaining); - SET v_remaining = v_remaining - v_amount; - SET v_labels = v_amount DIV v_packing; - - INSERT INTO tmp.split - VALUES (v_is_buy, v_id, v_labels, v_amount % v_packing); - - IF v_is_buy - THEN - UPDATE Compres - SET Vida = Vida + v_labels - WHERE Id_Compra = v_id; - ELSE - INSERT INTO movement_label - SET - Id_Movimiento = v_id, - stem = v_amount, - label = v_labels - ON DUPLICATE KEY UPDATE - stem = stem + VALUES(stem), - label = label + VALUES(label); - END IF; - END LOOP; - - CLOSE cur; - - -- Crea los movimientos de almacén a silla - - CALL buy_transfer (v_buy, v_fv_entry, v_pca_entry); - - UPDATE Compres SET dispatched = Vida * Packing - WHERE Id_Compra = v_buy; - - -- Devuelve los splits creados - - DROP TEMPORARY TABLE IF EXISTS tmp.aux; - CREATE TEMPORARY TABLE tmp.aux - ENGINE = MEMORY - SELECT s.labels, s.remainder, w.`name` destination, - a.Id_Article, a.Article, a.Medida - FROM tmp.split s - JOIN Compres c ON c.Id_Compra = s.id - JOIN Articles a ON a.Id_Article = c.Id_Article - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel t ON t.id = e.travel_id - JOIN warehouse w ON t.warehouse_id = w.id - WHERE s.is_buy; - - INSERT INTO tmp.aux - SELECT s.labels, s.remainder, o.Consignatario, - a.Id_Article, a.Article, a.Medida - FROM tmp.split s - JOIN Movimientos m ON m.Id_Movimiento = s.id - JOIN Articles a ON a.Id_Article = m.Id_Article - JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN Consignatarios o ON o.Id_Consigna = t.Id_Consigna - WHERE NOT s.is_buy; - - SELECT * FROM tmp.aux; - - -- Limpia y confirma cambios - - DROP TEMPORARY TABLE - tmp.split, - tmp.aux; - - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_tarifas`(v_buy INT) -BEGIN - DECLARE v_entry INT; - DECLARE v_wh INT; - - SELECT Id_Entrada, warehouse_id - INTO v_entry, v_wh - FROM Compres - JOIN Entradas USING(Id_Entrada) - JOIN travel ON travel.id = travel_id - WHERE v_buy = Id_Compra; - - CALL buy_tarifas_table (v_entry); - - UPDATE Compres C - LEFT JOIN Cubos CB USING(Id_Cubo) - JOIN Articles A USING(Id_Article) - JOIN Tipos TP USING(tipo_id) - JOIN Entradas E USING(Id_Entrada) - JOIN travel TR ON TR.id = E.travel_id - JOIN Agencias AG ON TR.agency_id = AG.Id_Agencia - LEFT JOIN recibida_entrada re ON E.Id_Entrada = re.Id_Entrada - LEFT JOIN awb_recibida ar ON re.awb_recibida = ar.recibida_id - LEFT JOIN v_awb_volumen va ON va.awb_id = ar.awb_id - JOIN tblTARIFAS TC - SET C.Portefijo = @PF:= - IF (va.importe, - ROUND((va.importe * A.density * CM3_2(C.Id_Cubo, C.Id_Article) / 1000) / (va.Vol_Total * 167 * C.Packing ),3), - ROUND(IFNULL(((AG.m3 * cm3_2(C.Id_Cubo, C.Id_Article)) / 1000000) / C.Packing,0),3) - ), - C.Comisionfija = @CF:= ROUND(IFNULL(E.comision * C.Costefijo / 100,0),3), - C.Embalajefijo = @EF:= ROUND((CB.costeRetorno + IF(CB.Retornable != 0, 0, CB.Valor)) / C.packing,3), - C.Tarifa3 = @t3:= IF(TC.t3 = 0, C.Costefijo,ROUND((C.Costefijo + @CF + @EF + @PF) / ((100 - TC.t3 - TP.promo ) /100) ,2)), -- He añadido que el coste sea igual a tarifa3 si t3 = 0 - C.Tarifa2 = @t2:= ROUND(@t3 * (1 + ( (TC.t2 - TC.t3)/100) ),2), - C.Tarifa2 = IF(@t2 <= @t3, @t3 , @t2) - WHERE C.Id_Compra = v_buy; - - IF v_wh = 42 -- Canarias - THEN - UPDATE Compres - SET Tarifa2 = Tarifa3 - WHERE Id_Compra = v_buy; - END IF; - - CALL vn2008.buy_tarifas_priceBuilder_Buy(v_buy); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_awb` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_tarifas_awb`(IN strAWB varchar(18)) -BEGIN - -DECLARE datINV DATE; -DECLARE wh_id INT; -DECLARE idENTRADA INT; - -DECLARE done BOOL DEFAULT FALSE; -DECLARE entryFk INT; - -DECLARE rs CURSOR FOR - SELECT e.Id_Entrada - FROM Entradas e - JOIN recibida_entrada re on e.Id_Entrada = re.Id_Entrada - JOIN awb_recibida ar ON re.awb_recibida = ar.recibida_id - JOIN v_awb_volumen va ON va.awb_id = ar.awb_id - WHERE va.codigo = strAWB ; - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - -SELECT warehouse_id, E.Id_Entrada INTO wh_id, idENTRADA -FROM Entradas E -JOIN travel ON travel.id = travel_id -JOIN recibida_entrada re on E.Id_Entrada = re.Id_Entrada -JOIN awb_recibida ar ON re.awb_recibida = ar.recibida_id -JOIN awb ON awb.id = ar.awb_id -WHERE awb.codigo = strAWB -LIMIT 1; - - - CALL buy_tarifas_table(idENTRADA); - - UPDATE Compres C - LEFT JOIN Cubos CB USING(Id_Cubo) - JOIN Articles A USING(Id_Article) - JOIN Entradas E USING(Id_Entrada) - JOIN recibida_entrada re on E.Id_Entrada = re.Id_Entrada - JOIN awb_recibida ar ON re.awb_recibida = ar.recibida_id - JOIN v_awb_volumen va ON va.awb_id = ar.awb_id - JOIN Tipos TP USING(tipo_id) - JOIN travel TR ON TR.id = E.travel_id - JOIN Agencias AG ON TR.agency_id = AG.Id_Agencia - JOIN tblTARIFAS TC - - SET C.Portefijo = @PF:= round((va.importe * A.density * CM3_2(C.Id_Cubo, C.Id_Article) / 1000) / (va.Vol_Total * 167 * C.Packing ),3), - - C.Comisionfija = @CF:= ROUND(IFNULL(E.comision * C.Costefijo / 100,0),3), - - C.Embalajefijo = @EF:= ROUND((CB.costeRetorno + IF(CB.Retornable != 0, 0, CB.Valor)) / C.Packing,3), - - C.Tarifa3 = @t3:= IF(TC.t3 = 0, C.Costefijo,ROUND((C.Costefijo + @CF + @EF + @PF) / ((100 - TC.t3 - TP.promo ) /100) ,2)), -- He añadido que el coste sea igual a tarifa3 si t3 = 0 - - C.Tarifa2 = @t2:= round(@t3 * (1 + ( (TC.t2 - TC.t3)/100) ),2), - - C.Tarifa2 = @t2:= IF(@t2 <= @t3, @t3 , @t2) - - - WHERE va.codigo = strAWB ; - - -OPEN rs; - - FETCH rs INTO entryFk; - - WHILE NOT done DO - - CALL vn2008.buy_tarifas_priceBuilder_Entry(entryFk); - - FETCH rs INTO entryFk; - - END WHILE; - - -CLOSE rs; - - - -CASE wh_id - - WHEN 41 THEN -- Canarias - - UPDATE Compres - SET Tarifa2 = Tarifa3 - WHERE Id_Entrada = idENTRADA; - - - ELSE - - BEGIN - END; - -END CASE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_awb_bucle` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_tarifas_awb_bucle`() -BEGIN - -DECLARE strAWB VARCHAR(25); -DECLARE done INT DEFAULT FALSE; -DECLARE rs CURSOR FOR -SELECT codigo -FROM awb -WHERE MYSQL_TIME > '2015-06-30' AND importe > 0 ; -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - -OPEN rs; - -FETCH rs INTO strAWB; --- drop temporary table if exists killme; --- create temporary table killme select strAWB, now() as fecha, 0; - -WHILE NOT done DO - - insert into killme select strAWB, MYSQL_TIME, importe from awb where codigo = strAWB; - call buy_tarifas_awb(strAWB); - FETCH rs INTO strAWB; - select * from killme order by fecha desc; -END WHILE; - - - -drop temporary table killme; - - -CLOSE rs; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_entry` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_tarifas_entry`(IN idENTRADA INT(11)) -BEGIN - - DECLARE datINV DATE; - DECLARE wh_id INT; - DECLARE m3i INTEGER; - - - SELECT warehouse_id INTO wh_id - FROM Entradas - JOIN travel ON travel.id = travel_id - WHERE Id_Entrada = idENTRADA; - - CALL buy_tarifas_table(idENTRADA); - - SELECT AG.m3 * sum( etiquetas * IFNULL(((AG.m3 * cm3_2(C.Id_Cubo, C.Id_Article)) / 1000000) ,0) ) / - sum(etiquetas * IFNULL(((AG.m3 * ( A.density / 167 ) * cm3_2(C.Id_Cubo, C.Id_Article)) / 1000000) ,0)) INTO m3i - FROM Compres C - JOIN Articles A USING(Id_Article) - JOIN Entradas E USING(Id_Entrada) - JOIN Tipos TP USING(tipo_id) - JOIN travel TR ON TR.id = E.travel_id - JOIN Agencias AG ON TR.agency_id = AG.Id_Agencia - WHERE E.Id_Entrada = idENTRADA; - - - - UPDATE Compres C - LEFT JOIN Cubos CB USING(Id_Cubo) - JOIN Articles A USING(Id_Article) - JOIN Entradas E USING(Id_Entrada) - LEFT JOIN recibida_entrada re on E.Id_Entrada = re.Id_Entrada - LEFT JOIN awb_recibida ar ON re.awb_recibida = ar.recibida_id - LEFT JOIN v_awb_volumen va ON va.awb_id = ar.awb_id - JOIN Tipos TP USING(tipo_id) - JOIN travel TR ON TR.id = E.travel_id - JOIN Agencias AG ON TR.agency_id = AG.Id_Agencia - JOIN tblTARIFAS TC - - SET C.Portefijo = @PF:= - IF (va.importe, - - round((va.importe * A.density * CM3_2(C.Id_Cubo, C.Id_Article) / 1000) / (va.Vol_Total * 167 * C.Packing ),3), - - ROUND(IFNULL(((AG.m3 * @cm3:= cm3_2(C.Id_Cubo, C.Id_Article)) / 1000000) / C.Packing,0),3) - ), - - C.Comisionfija = @CF:= ROUND(IFNULL(E.comision * C.Costefijo / 100,0),3), - - C.Embalajefijo = @EF:= IF(CB.Retornable != 0, 0, ROUND(IFNULL( CB.Valor / C.Packing ,0),3)), - - C.Tarifa3 = @t3:= IF(TC.t3 = 0, C.Costefijo,ROUND((C.Costefijo + @CF + @EF + @PF) / ((100 - TC.t3 - TP.promo ) /100) ,2)), -- He añadido que el coste sea igual a tarifa3 si t3 = 0 - - C.Tarifa2 = @t2:= round(@t3 * (1 + ( (TC.t2 - TC.t3)/100)),2), - - C.Tarifa2 = @t2:= IF(@t2 <= @t3, @t3 , @t2) - - WHERE C.Id_Entrada = idENTRADA ; - - - CASE wh_id - - WHEN 41 THEN -- Canarias - - UPDATE Compres - SET Tarifa2 = Tarifa3 - WHERE Id_Entrada = idENTRADA; - ELSE - - BEGIN - END; - - END CASE; - - -- priceBuilder - call buy_tarifas_priceBuilder_Entry(idENTRADA); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_lot` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_tarifas_lot`(IN idCOMPRA INT(11)) -BEGIN - -DECLARE intWHIN INTEGER(3); -DECLARE intDAYS INTEGER(3); -DECLARE dbM3 DOUBLE; -DECLARE done INT DEFAULT 0; -DECLARE datFEC DATE; -DECLARE wh INTEGER(3); -DECLARE idART INTEGER(11); -DECLARE dbCOST DOUBLE; -DECLARE m3value DOUBLE; -DECLARE intLIFE INTEGER; -DECLARE intPACK INTEGER; -DECLARE intPromo DOUBLE; -DECLARE whlc CURSOR FOR SELECT whin, days, m3 FROM warehouse_lc WHERE whout = @wh:= wh UNION ALL SELECT @wh, 0, 0 ; -DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1; - -SELECT - Id_Article, - warehouse_id, - landing, - nz(Costefijo) + nz(Embalajefijo) + nz(Portefijo) + nz(Comisionfija), - life, - C.Packing, - (cm3_2(C.Id_Cubo, C.Id_Article) / 1000000) / C.Packing, - promo -INTO idART , wh , datFEC , dbCOST , intLIFE, intPACK, m3value, intPromo FROM - Compres C - JOIN - Articles A USING (Id_Article) - JOIN - Tipos TP USING (tipo_id) - JOIN - Entradas E USING (Id_Entrada) - JOIN - travel tr ON tr.id = E.travel_id -WHERE - Id_Compra = idCOMPRA; - - - -OPEN whlc; - -FETCH whlc INTO intWHIN, intDAYS, dbM3; - -WHILE NOT done DO - -SELECT idART , wh , datFEC , dbCOST , intLIFE, intPACK, m3value, intWHIN, intDAYS, dbM3, done, dbCOST + (m3value * dbM3); - - INSERT INTO price_fixed(item_id, - rate_3, - rate_2, - date_start, - date_end, - warehouse_id) - - SELECT idART, - round( (dbCOST + (m3value * dbM3)) / ((100 - t3 - intPromo )/100) , 2), - @tf2 := round((dbCOST + (m3value * dbM3)) / ((100 - t2 - intPromo)/100) ,2), - TIMESTAMPADD(DAY, intDAYS, datFEC), - TIMESTAMPADD(DAY, intLIFE, datFEC), - intWHIN - FROM tarifas - WHERE warehouse_id = intWHIN AND fecha <= TIMESTAMPADD(DAY, intDAYS, datFEC) - ORDER BY fecha DESC - LIMIT 1; - -FETCH whlc INTO intWHIN, intDAYS, dbM3; - - END WHILE; - -CALL buy_tarifas_priceBuilder_Buy(idCOMPRA); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_priceBuilder` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_tarifas_priceBuilder`(entryFk INT) -BEGIN - -UPDATE vn.buy b - JOIN - ( - SELECT i.id, i.name, i.size, pb.price, difTags.numTags , count(DISTINCT pbt.tagFk) matchedTags - FROM vn.item i - JOIN vn.buy b ON b.itemFk = i.id - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.itemTag it ON it.itemFk = i.id - JOIN vn.priceBuilder pb ON pb.itemTypeFk = i.typeFk - JOIN vn.priceBuilderWarehouse pbw ON pbw.priceBuilderFk = pb.id AND pbw.warehouseFk = tr.warehouseInFk - LEFT JOIN vn.priceBuilderTag pbt ON pbt.priceBuilderFk = pb.id AND pbt.tagFk = it.tagFk AND pbt.value = it.value - JOIN vn.priceBuilderDistinctTags difTags ON difTags.priceBuilderFk = pb.id - WHERE b.entryFk = entryFk - AND tr.landed BETWEEN pb.started AND pb.finished - GROUP BY i.id - HAVING matchedTags = numTags - ) sub ON sub.id = b.itemFk - SET b.price2 = sub.price, b.price3 = sub.price * 0.95 - WHERE b.entryFk = entryFk; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_priceBuilder_Buy` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_tarifas_priceBuilder_Buy`(buyFk INT) -BEGIN - -UPDATE vn.buy b - JOIN - ( - SELECT i.id, i.name, i.size, pb.price, difTags.numTags , count(DISTINCT pbt.tagFk) matchedTags - FROM vn.item i - JOIN vn.buy b ON b.itemFk = i.id - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.itemTag it ON it.itemFk = i.id - JOIN vn.priceBuilder pb ON pb.itemTypeFk = i.typeFk - JOIN vn.priceBuilderWarehouse pbw ON pbw.priceBuilderFk = pb.id AND pbw.warehouseFk = tr.warehouseInFk - LEFT JOIN vn.priceBuilderTag pbt ON pbt.priceBuilderFk = pb.id AND pbt.tagFk = it.tagFk AND pbt.value = it.value - JOIN vn.priceBuilderDistinctTags difTags ON difTags.priceBuilderFk = pb.id - WHERE b.id = buyFk - AND tr.landed BETWEEN pb.started AND pb.finished - GROUP BY i.id - HAVING matchedTags = numTags - ) sub ON sub.id = b.itemFk - SET b.price2 = sub.price, b.price3 = sub.price * 0.95 - WHERE b.id = buyFk; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_priceBuilder_Entry` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_tarifas_priceBuilder_Entry`(entryFk INT) -BEGIN - -UPDATE vn.buy b - JOIN - ( - SELECT i.id, i.name, i.size, pb.price, difTags.numTags , count(DISTINCT pbt.tagFk) matchedTags - FROM vn.item i - JOIN vn.buy b ON b.itemFk = i.id - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.itemTag it ON it.itemFk = i.id - JOIN vn.priceBuilder pb ON pb.itemTypeFk = i.typeFk - JOIN vn.priceBuilderWarehouse pbw ON pbw.priceBuilderFk = pb.id AND pbw.warehouseFk = tr.warehouseInFk - LEFT JOIN vn.priceBuilderTag pbt ON pbt.priceBuilderFk = pb.id AND pbt.tagFk = it.tagFk AND pbt.value = it.value - JOIN vn.priceBuilderDistinctTags difTags ON difTags.priceBuilderFk = pb.id - WHERE b.entryFk = entryFk - AND tr.landed BETWEEN pb.started AND pb.finished - GROUP BY i.id - HAVING matchedTags = numTags - ) sub ON sub.id = b.itemFk - SET b.price2 = sub.price, b.price3 = sub.price * 0.95 - WHERE b.entryFk = entryFk; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_recalcular_almacen` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_tarifas_recalcular_almacen`(IN wh_id INT, IN datFEC DATE) -BEGIN - -DECLARE done INT DEFAULT 0; -DECLARE idE INT; - -DECLARE cur1 CURSOR FOR -SELECT Id_Entrada -FROM Entradas -JOIN travel ON travel.id = travel_id -WHERE landing >= datFEC AND wh_id IN (0,warehouse_id); - -DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1; - -OPEN cur1; - -REPEAT - - FETCH cur1 INTO idE; - - IF NOT done THEN - - Call buy_tarifas_entry(idE); - - - - END IF; - - -UNTIL done END REPEAT; - - CLOSE cur1; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_T3` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_tarifas_T3`(IN idCOMPRA INT(11)) -BEGIN - - DECLARE idENTRADA BIGINT; - DECLARE wh_id INT; - - SELECT Id_Entrada, warehouse_id INTO idENTRADA, wh_id - FROM Compres - JOIN Entradas using(Id_Entrada) - JOIN travel ON travel.id = travel_id - WHERE idCOMPRA = Id_Compra; - - CALL buy_tarifas_table(idENTRADA); - - UPDATE Compres C - JOIN tblTARIFAS TC - - SET - C.Tarifa3 = @t3:= C.Tarifa3, - - C.Tarifa2 = @t2:= round(@t3 * (1 + ( (TC.t2 - TC.t3)/100) ),2), - - C.Tarifa2 = @t2:= IF(@t2 <= @t3, @t3 + 0.01, @t2) - - WHERE C.Id_Compra = idCOMPRA; - - IF wh_id = 41 THEN -- Canarias - - UPDATE Compres - SET Tarifa2 = Tarifa3 - WHERE Id_Compra = idCOMPRA; - - END IF; - - CALL buy_tarifas_priceBuilder_Buy(idCOMPRA); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_T3_pf` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_tarifas_T3_pf`(IN idPRICE INT, IN t3 DOUBLE) -BEGIN - -DECLARE idENTRADA BIGINT; -DECLARE idCOMPRA BIGINT; -DECLARE datFEC DATE; -DECLARE wh INT; -DECLARE idART BIGINT; - -SELECT date_start, warehouse_id, item_id INTO datFEC, wh, idART -FROM price_fixed WHERE price_fixed_id = idPRICE; - -SELECT C.Id_Entrada, Id_Compra INTO idENTRADA, idCOMPRA -FROM Compres C -JOIN Entradas E using(Id_Entrada) -JOIN travel TR on TR.id = E.travel_id -WHERE Id_Article = idART -AND wh IN (0, warehouse_id) -AND Novincular = FALSE -AND NOT Redada -AND landing <= datFEC -ORDER BY landing DESC -LIMIT 1; - -CALL buy_tarifas_table(idENTRADA); - -SELECT - - @t2:= round(t3 * (1 + ( (TC.t2 - TC.t3)/100) ),2) as rate_2b, - - @t2:= IF(@t2 <= t3, t3 + 0.01, @t2) as rate_2 - -FROM price_fixed PF - JOIN Compres C ON C.Id_Compra = idCOMPRA AND price_fixed_id = idPRICE - JOIN tblTARIFAS TC; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_tarifas_table` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_tarifas_table`(v_entry INT) -BEGIN - DECLARE v_date DATE; - DECLARE v_wh INT; - - -- Obtiene fecha de llegada y almacén entrante - - SELECT landing, warehouse_id INTO v_date , v_wh - FROM travel TR - JOIN Entradas E ON TR.id = E.travel_id - WHERE Id_Entrada = v_entry; - - -- Prepara una tabla con las tarifas aplicables en funcion de la fecha y el almacén - - DROP TEMPORARY TABLE IF EXISTS tblTARIFAS; - CREATE TEMPORARY TABLE tblTARIFAS - ENGINE = MEMORY - SELECT * FROM - ( - SELECT * FROM - ( - SELECT t0, t1, t2, t3 - FROM tarifas - WHERE fecha <= v_date - AND warehouse_id = v_wh - ORDER BY fecha DESC - - ) sub - UNION ALL - SELECT t0, t1, t2, t3 - FROM tblContadores - ) sub2 - LIMIT 1; - - -- pak 22/09/2015 - - UPDATE bi.rotacion r - JOIN Compres c ON c.Id_Article = r.Id_Article - SET cm3 = vn2008.cm3_unidad(c.Id_Compra) - WHERE Id_Entrada = v_entry - AND r.warehouse_id = v_wh; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `buy_transfer` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_transfer`(v_buy INT, v_fv_entry INT, v_pca_entry INT) -proc: BEGIN -/** - * Traslada la cantidad restante de una compra de Holanda - * al almacén de Silla. - **/ - DECLARE v_wh INT; - DECLARE v_entry INT; - DECLARE v_fv INT; - DECLARE v_amount INT; - DECLARE v_item INT; - DECLARE v_holland_wh INT DEFAULT 7; - - -- Comprueba que es mercancía que llega al almacén de Holanda - - SELECT t.warehouse_id, tp.FV INTO v_wh, v_fv - FROM Compres c - JOIN Entradas e ON c.Id_Entrada = e.Id_Entrada - JOIN travel t ON t.id = e.travel_id - JOIN Articles a ON a.Id_Article = c.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - WHERE c.Id_Compra = v_buy; - - IF v_wh != v_holland_wh THEN - LEAVE proc; - END IF; - - -- Calcula a que almacén de Silla debe transladar la mercancía - - SET v_entry = IF(v_fv, v_fv_entry, v_pca_entry); - SET v_entry = IFNULL(v_entry, IFNULL(v_pca_entry, v_fv_entry)); - - IF v_entry IS NULL THEN - LEAVE proc; - END IF; - - -- Calcula la cantidad a trasladar - - SELECT Id_Article INTO v_item - FROM Compres WHERE Id_Compra = v_buy; - - SELECT IFNULL(SUM(amount), 0) INTO v_amount - FROM ( - SELECT SUM(c.Cantidad) amount - FROM Compres c - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel t ON t.id = e.travel_id - WHERE c.Id_Article = v_item - AND t.landing = CURDATE() - AND t.warehouse_id = v_holland_wh - UNION ALL - SELECT -SUM(c.Cantidad) - FROM Compres c - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel t ON t.id = e.travel_id - WHERE c.Id_Article = v_item - AND t.shipment = CURDATE() - AND t.warehouse_id_out = v_holland_wh - UNION ALL - SELECT -SUM(Cantidad) - FROM Movimientos m - JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket - WHERE m.Id_Article = v_item - AND t.Fecha = CURDATE() - AND t.warehouse_id = v_holland_wh - ) t; - - IF v_amount <= 0 THEN - LEAVE proc; - END IF; - - -- Crea la nueva línea de compra con el translado - - INSERT INTO Compres ( - Id_Article, Etiquetas, Cantidad, Id_Entrada, - Id_Cubo, Packing, grouping, caja, Costefijo, Portefijo, - Embalajefijo, Comisionfija, novincular, buy_edi_id) - SELECT - c.Id_Article, - v_amount DIV c.Packing, - v_amount, - v_entry, - c.Id_Cubo, - c.Packing, - c.grouping, - c.caja, - @cost := IFNULL(c.Costefijo, 0) + IFNULL(c.Comisionfija, 0) + IFNULL(c.Portefijo, 0), - @porte := ROUND((@cm3:= cm3_2(c.Id_Cubo, c.Id_Article)) * a.m3 / 1000000 / c.Packing, 3), - c.EmbalajeFijo, - @comision := ROUND(c.Costefijo * e.comision / 100, 3), - c.novincular, - c.buy_edi_id - FROM Compres c - JOIN Cubos cu ON cu.Id_Cubo = c.Id_Cubo - JOIN Entradas e ON e.Id_Entrada = v_entry - JOIN travel t ON t.id = e.travel_id - JOIN Agencias a ON t.agency_id = a.Id_Agencia - WHERE c.Id_Compra = v_buy; - - CALL buy_tarifas (LAST_INSERT_ID()); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `cacheReset` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `cacheReset`(vCacheName VARCHAR(10), vParams VARCHAR(15)) -BEGIN - - UPDATE cache.cache_calc - SET expires = NOW() - WHERE cacheName = vCacheName collate utf8_unicode_ci - AND params = vParams collate utf8_unicode_ci; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Cajas_Saldo_Detalle` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Cajas_Saldo_Detalle`() -BEGIN - - Select Proveedores.Id_Proveedor, Proveedor, Fecha, round(Importe) as Importe - from Proveedores - join - ( - select Fecha, sub.Id_Proveedor, sum(Importe) as Importe - from - - ( - - select round(sum(Importe),2) as Importe, TIMESTAMPADD(DAY,-1,CURDATE()) as Fecha, Id_Proveedor - from pago - join Proveedores using(Id_Proveedor) - where Fecha >= '2011-01-01' - and Id_Proveedor NOT IN (select id from empresa) - group by Id_Proveedor - - union all - - select IFNULL(-1 * round(sum(rv.Cantidad / if(Id_Moneda = 2,rate,1)),2),0) AS Vto, TIMESTAMPADD(DAY,-1,CURDATE()), proveedor_id - from recibida_vencimiento rv - join recibida r on r.id = rv.recibida_id - join reference_rate rr on rr.`date` = rv.fecha - join Proveedores P on P.Id_Proveedor = r.proveedor_id - join Paises PS on PS.Id = P.pais_id - where rv.fecha between '2011-01-01' and CURDATE()-1 - and Id_Proveedor NOT IN (select id from empresa) - group by proveedor_id - - union all - - select -1 * round(rv.Cantidad / if(Id_Moneda = 2,currate(),1),2) AS Vto, rv.fecha, proveedor_id - from recibida_vencimiento rv - join recibida r on r.id = rv.recibida_id - join Proveedores P on P.Id_Proveedor = r.proveedor_id - join Paises PS on PS.Id = P.pais_id - where rv.fecha >= CURDATE() - and Id_Proveedor NOT IN (select id from empresa) - - union all - - select @remesas:= @pago:= @saldo:= 0.0000, curdate(), @prov:= 0) sub - group by Fecha,Id_Proveedor - ) sub2 using(Id_Proveedor) - having Importe < -100 - ; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `CalculoRemesas` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `CalculoRemesas`(IN vFechaRemesa DATE) -BEGIN - - DROP TEMPORARY TABLE IF EXISTS TMP_REMESAS; - CREATE TEMPORARY TABLE TMP_REMESAS SELECT - CONCAT(p.NIF,REPEAT('0', 12-LENGTH(p.NIF))) as CIF1, - cli.Id_Cliente, - cli.Cliente, - cli.`IF` as NIF, - c.PaymentDate as Vencimiento, - 0 ImporteFac, - cast(c.Recibo as decimal(10,2)) as ImporteRec, - 0 as ImporteActual, - c.company_id empresa_id, - cli.RazonSocial, - cast(c.Recibo as decimal(10,2)) as ImporteTotal, - cast(c.Recibo as decimal(10,2)) as Saldo, - p.Proveedor as Empresa, - e.abbreviation as EMP, - cli.cuenta, - iban AS Iban, - CONVERT(SUBSTRING(iban,5,4),UNSIGNED INT) AS nrbe , - sepavnl as SEPA, - corevnl as RecibidoCORE - - FROM Clientes cli - JOIN - (SELECT risk.company_id, - c.Id_Cliente, - sum(risk.amount) as Recibo, - IF((c.Vencimiento + graceDays) mod 30.001 <= day(vFechaRemesa) - ,TIMESTAMPADD(DAY, (c.Vencimiento + graceDays) MOD 30.001, LAST_DAY(TIMESTAMPADD(MONTH,-1,vFechaRemesa))) - ,TIMESTAMPADD(DAY, (c.Vencimiento + graceDays) MOD 30.001, LAST_DAY(TIMESTAMPADD(MONTH,-2,vFechaRemesa))) - ) as PaymentDate - FROM Clientes c - JOIN pay_met pm on pm.id = pay_met_id - JOIN - ( - SELECT company_id, customer_id, amount - FROM Clientes c - JOIN bi.customer_risk cr ON cr.customer_id = c.Id_Cliente - WHERE pay_met_id = 4 - - UNION ALL - - SELECT empresa_id, Id_Cliente, - Importe - FROM Facturas f - JOIN Clientes c using(Id_Cliente) - JOIN pay_met pm on pm.id = pay_met_id - WHERE f.Vencimiento > vFechaRemesa - AND pay_met_id = 4 AND deudaviva - AND Importe > 0 - - ) risk ON c.Id_Cliente = risk.customer_id - GROUP BY risk.company_id, Id_Cliente - HAVING Recibo > 10 - ) c on c.Id_Cliente = cli.Id_Cliente - JOIN Proveedores p on p.Id_Proveedor = c.company_id - JOIN empresa e on e.id = c.company_id; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `CalculoRemesaskk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `CalculoRemesaskk`(IN vFechaRemesa DATE) -BEGIN - - -DROP TEMPORARY TABLE IF EXISTS TMP_REMESAS; -CREATE TEMPORARY TABLE TMP_REMESAS SELECT - CONCAT(p.NIF,REPEAT('0', 12-LENGTH(p.NIF))) as CIF1, - cli.Id_Cliente, - cli.Cliente, - cli.`IF` as NIF , - cli.CC, - c.PaymentDate as Vencimiento, - 0 ImporteFac, - cast(c.Recibo as decimal(10,2)) as ImporteRec, - 0 as ImporteActual, - c.empresa_id, - cli.RazonSocial, - cast(c.Recibo as decimal(10,2)) as ImporteTotal, - cast(c.Recibo as decimal(10,2)) as Saldo, - p.Proveedor as Empresa, - e.abbreviation as EMP, - cli.cuenta, - CONCAT(cc_to_iban(CC),CC) AS Iban, - CONVERT(left(CC,4),UNSIGNED INT) AS nrbe , - IF(c.empresa_id=442,sepavnl,sepafth) as SEPA, - IF(c.empresa_id=442,corevnl,corefth) as RecibidoCORE - - FROM Clientes cli - JOIN - (SELECT empresa_id, - c.Id_Cliente, - sum(Importe) as Recibo, - IF((c.Vencimiento + graceDays) mod 30.001 <= day(vFechaRemesa) - ,TIMESTAMPADD(DAY, (c.Vencimiento + graceDays) MOD 30.001, LAST_DAY(TIMESTAMPADD(MONTH,-1,vFechaRemesa))) - ,TIMESTAMPADD(DAY, (c.Vencimiento + graceDays) MOD 30.001, LAST_DAY(TIMESTAMPADD(MONTH,-2,vFechaRemesa))) - ) as PaymentDate - FROM Clientes c - JOIN pay_met pm on pm.id = pay_met_id - JOIN - ( - SELECT empresa_id, Id_Cliente, Importe - FROM Facturas f - JOIN Clientes c using(Id_Cliente) - JOIN pay_met pm on pm.id = pay_met_id - WHERE IF(Importe > 0,paymentday(Fecha,c.Vencimiento + graceDays), Fecha) <= vFechaRemesa - AND pay_met_id = 4 AND deudaviva - - UNION ALL - - SELECT empresa_id, Id_Cliente, - Entregado - FROM Recibos r - JOIN Clientes c using(Id_Cliente) - JOIN pay_met pm on pm.id = pay_met_id - WHERE pay_met_id = 4 AND deudaviva - - ) sub using(Id_Cliente) - GROUP BY empresa_id, Id_Cliente - HAVING Recibo > 10 - ) c on c.Id_Cliente = cli.Id_Cliente - JOIN Proveedores p on p.Id_Proveedor = c.empresa_id - JOIN empresa e on e.id = c.empresa_id; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `calling` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `calling`() -BEGIN - DROP TEMPORARY TABLE IF EXISTS Agenda, Agenda2; - - - CREATE TEMPORARY TABLE IF NOT EXISTS Agenda (Telefono varchar(15) PRIMARY KEY, Cliente VARCHAR(45)); - -CREATE TEMPORARY TABLE IF NOT EXISTS Agenda2 LIKE Agenda; - -REPLACE Agenda(Telefono, Cliente) - SELECT Telefono, Nombre from v_Agenda2; - - -REPLACE Agenda(Telefono, Cliente) - SELECT DISTINCT src, clid FROM cdr WHERE src < 6000 AND clid NOT LIKE '%device%' - AND calldate > TIMESTAMPADD(DAY, -7,CURDATE()) ; - - - -INSERT INTO Agenda2(Telefono, Cliente) - SELECT Telefono, Cliente FROM Agenda; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `camiones` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `camiones`(vWarehouse INT, vDate DATE) -BEGIN - SELECT Temperatura - ,ROUND(SUM(Etiquetas * volume)) AS cm3 - ,ROUND(SUM(IF(scanned, Etiquetas, 0) * volume)) AS cm3s - ,ROUND(SUM(Vida * volume)) AS cm3e - FROM ( - SELECT t.Temperatura, c.Etiquetas, b.scanned, c.Vida, - IF(cu.Volumen > 0, cu.Volumen, cu.x * cu.y * IF(cu.z > 0, cu.z, a.Medida + 10)) volume - FROM Compres c - LEFT JOIN buy_edi b ON b.id = c.buy_edi_id - JOIN Articles a ON a.Id_Article = c.Id_Article - JOIN Tipos t ON t.tipo_id = a.tipo_id - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel tr ON tr.id = e.travel_id - JOIN Cubos cu ON cu.Id_Cubo = c.Id_Cubo - WHERE tr.warehouse_id = vWarehouse - AND tr.landing = vDate - ) sub - GROUP BY Temperatura; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Campaigns_Generator` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Campaigns_Generator`(IN datFEC DATE, IN intDAYS INT, IN intIMP INT) -BEGIN -DELETE FROM Campaigns; - -INSERT INTO Campaigns(Id_Cliente, Notas) -SELECT T.Id_Cliente, CONCAT('Consumo año anterior: ',FORMAT(SUM(M.Cantidad * M.Preu * (100 - M.Descuento) / 100), 0), ' € ') as Total -FROM Movimientos M -INNER JOIN Tickets T ON T.Id_Ticket = M.Id_Ticket -WHERE Date(T.Fecha) BETWEEN ADDDATE(datFEC,-1 * intDAYS) AND datFEC -GROUP BY T.Id_Cliente; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Campaigns_GeneratorKK` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Campaigns_GeneratorKK`(IN datFEC DATE, IN intDAYS INT, IN intIMP INT) -BEGIN -DELETE FROM Campaigns; - -INSERT INTO Campaigns(Id_Cliente, Notas) -SELECT T.Id_Cliente, CONCAT('Consumo año anterior: ',FORMAT(SUM(M.Cantidad * M.Preu * (100 - M.Descuento) / 100), 0), ' € ') as Total -FROM Movimientos M -INNER JOIN Tickets T ON T.Id_Ticket = M.Id_Ticket -WHERE Date(T.Fecha) BETWEEN ADDDATE(datFEC,-1 * intDAYS) AND datFEC -GROUP BY T.Id_Cliente; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Canariaskk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Canariaskk`(IN datFEC DATE, IN idWH INT , IN idEMP INT) -BEGIN - -DECLARE idTICKET DOUBLE; - - -CALL ticket_new_complet(4712, datFEC, idWH , 20, idEMP, NULL, NULL,NULL, idTICKET); - - -INSERT INTO Movimientos (Id_Ticket, Id_Article, Concepte, Cantidad, Preu, PrecioFijado) -SELECT idTICKET, 95, CONCAT(Codintrastat, ' : ', IF(Abreviatura = 'XYZ', 'NAC', Abreviatura), ' : ' , Nombotanic), sum(Cantidad), Preu, TRUE -FROM Articles INNER JOIN Movimientos ON Articles.Id_Article = Movimientos.Id_Article - INNER JOIN Tickets ON Movimientos.Id_Ticket = Tickets.Id_Ticket - INNER JOIN Consignatarios ON Tickets.Id_Consigna = Consignatarios.Id_Consigna - INNER JOIN province ON Consignatarios.province_id = province.province_id - INNER JOIN Origen ON Articles.id_origen = Origen.id -WHERE date(Tickets.Fecha) = datFEC AND province.name IN ('SANTA CRUZ DE TENERIFE','LAS PALMAS DE GRAN CANARIA') -GROUP BY Nombotanic, Preu; - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `check_table_existence` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `check_table_existence`(IN table_name CHAR(64)) -BEGIN - DECLARE CONTINUE HANDLER FOR SQLSTATE '42S02' SET @err = 1; - SET @err = 0; - SET @table_name = table_name; - SET @sqlString = CONCAT('SELECT NULL FROM ',@table_name); - PREPARE stmt1 FROM @sqlString; - IF (@err = 1) THEN - SET @table_exists = 0; - ELSE - SET @table_exists = 1; - DEALLOCATE PREPARE stmt1; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clean` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clean`(IN v_full TINYINT(1)) -BEGIN - DECLARE v_date DATETIME; - DECLARE v_date18 DATETIME; - DECLARE v_date8 DATE; - DECLARE v_date6 DATE; - DECLARE v_date3Month DATE; - DECLARE vDate2000 DATE; - DECLARE vRangeDeleteTicket INT; - DECLARE strtable varchar(15) DEFAULT NULL; - DECLARE done BIT DEFAULT 0; - - SET v_date = TIMESTAMPADD(MONTH, -2, CURDATE()); - SET v_date18 = TIMESTAMPADD(MONTH, -18,CURDATE()); - SET v_date3Month = TIMESTAMPADD(MONTH, -3, CURDATE()); - SET v_date8 = TIMESTAMPADD(DAY, -8,CURDATE()); - SET v_date6 = TIMESTAMPADD(DAY, -6,CURDATE()); - SET vRangeDeleteTicket = 60; - INSERT INTO vn2008.daily_task_log(consulta) VALUES('clean START'); - - DELETE FROM cdr WHERE calldate < v_date; - DELETE FROM Monitoring WHERE ODBC_TIME < v_date; - DELETE FROM Conteo WHERE Fecha < v_date; - DELETE FROM XDiario WHERE FECHA < v_date3Month OR FECHA IS NULL; - DELETE FROM mail WHERE DATE_ODBC < v_date; - - -- DELETE FROM Cajas WHERE CajaFecha < v_date18; - - DELETE rr FROM Recibos_recorded rr JOIN Recibos r ON rr.Id_Recibos = r.Id WHERE r.Fechacobro < v_date; - - SELECT MAX(idTickets_dits) - INTO @id - FROM Tickets_dits - WHERE ODBC_DATE < v_date; - DELETE FROM Tickets_dits WHERE idTickets_dits <= @id; - - -- DELETE FROM Tickets_dits WHERE ODBC_DATE < v_date; - DELETE FROM expeditions WHERE odbc_date < v_date18; - DELETE FROM expeditions_deleted WHERE odbc_date < v_date18; - DELETE FROM Entradas_dits WHERE ODBC_DATE < v_date18; - DELETE FROM log_articles WHERE ODBC_DATE < v_date; - DELETE FROM sms WHERE DATE_ODBC < v_date18; - DELETE FROM Movimientos_mark WHERE odbc_date < v_date; - DELETE FROM Splits WHERE Fecha < v_date18; - DELETE ts FROM Tickets_stack ts JOIN Tickets t ON ts.Id_Ticket = t.Id_Ticket WHERE t.Fecha < v_date; - DELETE tobs FROM ticket_observation tobs JOIN Tickets t ON tobs.Id_Ticket = t.Id_Ticket WHERE t.Fecha < v_date; - DELETE tobs FROM movement_label tobs JOIN Movimientos m ON tobs.Id_Movimiento = m.Id_Movimiento - JOIN Tickets t ON m.Id_Ticket = t.Id_Ticket WHERE t.Fecha < v_date; - DELETE FROM chat WHERE odbc_date < v_date; - DELETE FROM Extractos WHERE Fecha < v_date; - DELETE FROM Remesas WHERE `Fecha Remesa` < v_date18; - DELETE FROM sharingcart where datEND < v_date; - DELETE FROM sharingclient where datEND < v_date; - DELETE FROM Stockcontrol WHERE Datestart < v_date18; - DELETE FROM bi.comparativa_clientes WHERE Fecha < v_date18; - DELETE FROM reference_rate WHERE date < v_date18; - DELETE tt.* FROM Tickets_turno tt LEFT JOIN Movimientos m using(Id_Ticket) WHERE m.Id_Article IS NULL; - - SELECT MAX(inter_id) - INTO @id - FROM vncontrol.inter - WHERE odbc_date < v_date18; - DELETE FROM vncontrol.inter WHERE inter_id <= @id; - - -- DELETE FROM vncontrol.inter WHERE odbc_date < v_date18; - DELETE FROM Entradas_dits WHERE ODBC_DATE < v_date; - DELETE FROM cyc_declaration WHERE Fecha < v_date18; - DELETE FROM vn.message WHERE sendDate < v_date; - DELETE FROM travel_reserve WHERE odbc_date < v_date; - -- DELETE FROM syslog.systemevents WHERE odbc_date < v_date8; - DELETE FROM daily_task_log WHERE odbc_date < v_date; - -- DELETE FROM bi.Greuge_Evolution WHERE Fecha < v_date AND weekday(Fecha) != 1; - DELETE mc FROM Movimientos_checked mc JOIN Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento WHERE m.odbc_date < v_date; - DELETE FROM cache.departure_limit WHERE Fecha < TIMESTAMPADD(MONTH,-1,CURDATE()); - DELETE cm - FROM Compres_mark cm - JOIN Compres c ON c.Id_Compra = cm.Id_Compra - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel t ON t.id = e.travel_id - WHERE t.landing <= v_date; - DELETE co - FROM Compres_ok co JOIN Compres c ON c.Id_Compra = co.Id_Compra - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel t ON t.id = e.travel_id - WHERE t.landing <= v_date; - - DELETE FROM vn2008.scan WHERE odbc_date < v_date6 AND id <> 1; - - SET vDate2000 = TIMESTAMPADD(YEAR, 2000 - YEAR(CURDATE()), CURDATE()); - - IF v_full - THEN - DELETE FROM Tickets - WHERE Fecha NOT IN ('2000-01-01','2000-01-02') - AND YEAR(Fecha) = 2000 - AND ABS(DATEDIFF(Fecha,vDate2000)) > vRangeDeleteTicket; - - DELETE e.* FROM Entradas e - LEFT JOIN recibida_entrada re ON e.Id_Entrada = re.Id_Entrada - WHERE travel_id IS NULL - AND re.Id_Entrada IS NULL; - END IF; - - -- Tickets Nulos PAK 11/10/2016 - - UPDATE vn2008.Tickets - SET empresa_id = 965 - WHERE Id_Cliente = 31 - AND empresa_id != 965; - - -- Equipos duplicados - - DELETE w.* - FROM vn2008.workerTeam w - JOIN (SELECT id, team, user, COUNT(*) - 1 as duplicated - FROM vn.workerTeam - GROUP BY team,user - HAVING duplicated - ) d ON d.team = w.team AND d.user = w.user AND d.id != w.id; - - INSERT INTO vn2008.daily_task_log(consulta) VALUES('clean END'); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clean_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clean_launcher`() -BEGIN - - call vn2008.clean(TRUE); - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Clientes_Calidad` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Clientes_Calidad`() -BEGIN - - DECLARE intMONTH INTEGER; - DECLARE intYEAR INTEGER; - - SET intYEAR = YEAR(Curdate()); - SET intMONTH = MONTH(curdate())-1; - - IF intMONTH = 0 THEN - - SET intYEAR = intYEAR -1; - SET intMONTH = 12; - - END IF; - - UPDATE Clientes - SET - Calidad = 0; - - TRUNCATE bi.calidad_detalle; - - INSERT INTO bi.calidad_detalle(Id_Cliente,calidad_parametros_id,valor) - SELECT Id_Cliente, calidad_parametros_id, 0 - FROM bi.calidad_parametros - JOIN Clientes; - - -- Valoramos del 0 al 5 su consumo - - REPLACE INTO bi.calidad_detalle(Id_Cliente,calidad_parametros_id,valor) - SELECT Id_Cliente, 1, IF(Consumo > 5, 5, Consumo) - FROM ( - SELECT Id_Cliente, round(sum(importe)/1000) as Consumo - from bs.ventas v - join vn2008.time t on t.date = v.fecha - where year =intYEAR and month = intMONTH - group by Id_Cliente) sub; - - - -- Incrementamos dos puntos a los de giro bancario, y restamos uno a los de pago contado/contrareembolso - - REPLACE INTO bi.calidad_detalle(Id_Cliente,calidad_parametros_id,valor) - SELECT Id_Cliente, 3, CASE pay_met_id WHEN 4 -- giro - THEN 2 - - WHEN 1 -- contado - THEN -1 - - WHEN 5 -- tarjeta - - THEN 1 - - WHEN 7 -- tarjeta - - THEN 1 - - WHEN 6 -- contrareembolso - THEN -1 - - ELSE 0 END - FROM Clientes; - - /* Incrementamos a los que tengan reclamaciones 0%, 2 puntos - 1%, 1 punto - 2% 0 puntos - 3% -3 puntos - 4% - 6 puntos - 5% - 9 puntos - */ - - REPLACE INTO bi.calidad_detalle(Id_Cliente,calidad_parametros_id,valor) - SELECT Id_Cliente, 2, CASE nz(Ratio) - WHEN 0 THEN 2 - WHEN 0.01 THEN 1 - WHEN 0.02 THEN 0 - WHEN 0.03 THEN -3 - WHEN 0.04 THEN -6 - ELSE -9 - END - FROM bi.claims_ratio ; - - -- Ahora les ponemos un punto a los que compran por la web mas del 50% de sus pedidos - - REPLACE INTO bi.calidad_detalle(Id_Cliente,calidad_parametros_id,valor) - SELECT Id_Cliente, 4, Webs - FROM - ( SELECT Id_Cliente, sum(sub.Id_Trabajador = 4) / count(sub.Id_Trabajador) as Webs - FROM Tickets - JOIN - (SELECT Id_Ticket, Id_Trabajador - FROM Tickets_dits - WHERE idaccion_dits = 84 - AND ODBC_DATE >= TIMESTAMPADD(DAY,-30,CURDATE())) sub USING(Id_Ticket) - WHERE Fecha > '2001-01-01' AND Id_Agencia <> 23 -- ni tickets borrados, ni abonos cuentan - GROUP BY Id_Cliente - HAVING Webs > 0.5) sub2; - - - -- Marcamos con un 11 a los clientes recien nacidos, para protegerlos - - REPLACE INTO bi.calidad_detalle(Id_Cliente,calidad_parametros_id,valor) - SELECT Id_Cliente, 5, 11 - FROM - (SELECT Id_Cliente, MIN(Fecha) as Inicio - FROM Tickets - WHERE Fecha > '2001-01-01' - GROUP BY Id_Cliente - HAVING Inicio >= TIMESTAMPADD(DAY,-30,CURDATE())) sub ; - - -- Ahora actualizamos la tabla Clientes - - UPDATE Clientes - JOIN - (SELECT - Id_Cliente, SUM(valor) AS valoracion - FROM - bi.calidad_detalle - GROUP BY Id_Cliente) sub USING (Id_Cliente) - SET - calidad = IF(valoracion > 11, 11, valoracion); - - IF DAY(CURDATE()) = 1 THEN - -- Y de paso, desactivamos a los que hace tiempo que no compran.alter - -- JGF Sólo desctivamos a los clientes que no han comprado en los dos ultimos meses - UPDATE account.user u - SET - active = 0 - WHERE - u.role = 2 - AND id NOT IN (SELECT DISTINCT - c.Id_Cliente - FROM - Clientes c LEFT JOIN Tickets t ON t.Id_Cliente = c.Id_Cliente - WHERE - Created > TIMESTAMPADD(MONTH, - 2, CURDATE()) OR - Fecha > TIMESTAMPADD(MONTH, - 2, CURDATE())); - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Clientes_Calidad_detalle` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Clientes_Calidad_detalle`(IN IdC INT) -BEGIN - - -SELECT descripcion Concepto, valor Puntos -FROM bi.calidad_parametros -JOIN bi.calidad_detalle using(calidad_parametros_id) -WHERE Id_Cliente = idC; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clientes_saldos` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clientes_saldos`() -BEGIN - - - -DROP TEMPORARY TABLE IF EXISTS clientes_pendientes; - -CREATE TEMPORARY TABLE clientes_pendientes -( Id_Cliente INT NOT NULL -, empresa_id INT NOT NULL -, saldo double NOT NULL -, PRIMARY KEY(Id_Cliente, empresa_id)); - -INSERT INTO clientes_pendientes -SELECT Id_Cliente, empresa_id, sum(importe) as saldo - FROM - ( - SELECT - Id_Cliente, - empresa_id, - - Entregado as importe - - FROM - Recibos - JOIN - Clientes USING(Id_Cliente) - JOIN - pay_met p on p.id = pay_met_id - WHERE - deudaviva - - - UNION ALL - - - SELECT - Id_Cliente, - empresa_id, - Importe - - FROM - Facturas - JOIN - Clientes USING(Id_Cliente) - JOIN - pay_met p on p.id = pay_met_id - WHERE - deudaviva - - - ) sub - GROUP BY empresa_id, Id_Cliente - having saldo > 0; - - - - DROP TEMPORARY TABLE IF EXISTS cobros_pendientes; - - CREATE TEMPORARY TABLE cobros_pendientes - (Id_Cliente INT - ,fecha DATE - ,empresa_id INT NOT NULL - ,saldo DOUBLE - ,PRIMARY KEY(Id_Cliente, empresa_id)); - - - - INSERT INTO cobros_pendientes(Id_Cliente - , fecha - , empresa_id - , saldo) - - - - SELECT cp.Id_Cliente, - CASE (vencimiento > 30) - - WHEN TRUE THEN - - timestampadd(DAY,vencimiento,maxFecha) - - ELSE - - timestampadd( - DAY - ,vencimiento - day(maxFecha) - ,timestampadd(MONTH,1,maxFecha) - ) - - END as fecha, - cp.empresa_id, - cp.saldo - FROM clientes_pendientes cp - JOIN Clientes USING(Id_Cliente) - JOIN ( SELECT - max(Fecha) as maxFecha, - Id_Cliente, - empresa_id - FROM - Facturas - GROUP BY - Id_Cliente, - empresa_id - ) mf on mf.Id_Cliente = cp.Id_Cliente - AND mf.empresa_id = cp.empresa_id; - - - SELECT * FROM cobros_pendientes; - - DROP TEMPORARY TABLE cobros_pendientes; - DROP TEMPORARY TABLE clientes_pendientes; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clientManaGrouped` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clientManaGrouped`(vClient INT) -BEGIN - - SELECT 'Tickets' as Grupo, CAST(sum(s.quantity * Valor) AS DECIMAL(10,2)) as Mana - FROM vn.ticket t - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.sale s on s.ticketFk = t.id - JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = s.id - WHERE Id_Componente IN (37, 39) - AND t.shipped >= '2016-01-01' - AND t.clientFk = vClient - - UNION ALL - - SELECT 'Recibos' as Grupo, - sum(Entregado) as Mana - FROM vn2008.Recibos r - JOIN vn2008.Clientes c using(Id_Cliente) - WHERE r.Id_Banco = 66 - AND r.Fechacobro >= '2016-01-01' - AND c.Id_Cliente = vClient - - UNION ALL - - SELECT 'Greuges' as Grupo, sum(g.Importe) as Mana - FROM vn2008.Greuges g - JOIN vn2008.Clientes c using(Id_Cliente) - WHERE g.Greuges_type_id = 3 -- Maná - AND g.Fecha > '2016-01-01' - AND c.Id_Cliente = vClient; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clonWeeklyTickets` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clonWeeklyTickets`(IN vWeek INT) -BEGIN - DECLARE done BIT DEFAULT 0; - DECLARE vLanding DATE; - DECLARE vShipment DATE; - DECLARE vWarehouse INT; - DECLARE vTicket INT; - DECLARE vWeekDay INT; - DECLARE vClient INT; - DECLARE vEmpresa INT; - DECLARE vConsignatario INT; - DECLARE vAgencia INT; - DECLARE vNewTicket INT; - DECLARE vYear INT; - - DECLARE rsTicket CURSOR FOR - SELECT tt.Id_Ticket, weekDay, Id_Cliente, warehouse_id, empresa_id, Id_Consigna, Id_Agencia - FROM Tickets_turno tt - JOIN Tickets t ON tt.Id_Ticket = t.Id_Ticket; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - - SET done = 0; - SET vYear = YEAR(CURDATE()) + IF(vWeek < WEEK(CURDATE()),1, 0); - - OPEN rsTicket; - - FETCH rsTicket INTO vTicket, vWeekDay, vClient, vWarehouse, vEmpresa, vConsignatario, vAgencia; - - WHILE NOT done DO - - SELECT date INTO vShipment - FROM time - WHERE year = vYear AND week = vWeek - AND WEEKDAY(date) = vWeekDay; - - -- busca si el ticket ya ha sido clonado - IF (select count(*) FROM Tickets t JOIN ticket_observation tob ON t.Id_Ticket = tob.Id_Ticket - WHERE Id_Consigna = vConsignatario AND Fecha = vShipment AND tob.text LIKE CONCAT('%',vTicket,'%')) = 0 - THEN - - IF (SELECT COUNT(*) FROM Agencias WHERE Id_Agencia = vAgencia AND Agencia LIKE '%turno%') THEN - SET vAgencia = NULL; - END IF; - - CALL vn.ticketCreate(vClient, vShipment, vWarehouse, vEmpresa, vConsignatario, vAgencia, NULL, vLanding, vNewTicket); - - INSERT INTO Movimientos (Id_Ticket, Id_Article, Concepte, Cantidad, Preu, Descuento, CostFixat, PrecioFijado) - SELECT vNewTicket, Id_Article, Concepte, Cantidad, Preu, Descuento, CostFixat, PrecioFijado - FROM Movimientos WHERE Id_Ticket = vTicket; - - INSERT INTO Ordenes (orden,datorden,datticket,codvendedor,codcomprador,cantidad,preciomax,preu,id_article,id_cliente,comentario, - ok, total,datcompra,ko,id_movimiento) - SELECT o.orden,o.datorden,vShipment,o.codvendedor,o.codcomprador,o.cantidad,o.preciomax,o.preu,o.id_article,o.id_cliente,o.comentario, - o.ok, o.total,o.datcompra,o.ko,m2.Id_Movimiento - FROM Movimientos m JOIN Ordenes o ON o.Id_Movimiento = m.Id_Movimiento - JOIN Movimientos m2 ON m.Concepte = m2.Concepte AND m.Cantidad = m2.Cantidad AND m.Id_Article = m2.Id_Article - WHERE m.Id_Ticket = vTicket AND m2.Id_Ticket = vNewTicket; - - INSERT INTO ticket_observation(Id_Ticket,observation_type_id,text) VALUES(vNewTicket,4,CONCAT('turno desde ticket: ',vTicket)) - ON DUPLICATE KEY UPDATE text = CONCAT(ticket_observation.text,VALUES(text),' '); - - CALL bionic_calc_clon(vNewTicket); - END IF; - FETCH rsTicket INTO vTicket, vWeekDay, vClient, vWarehouse, vEmpresa, vConsignatario, vAgencia; - - END WHILE; - - CLOSE rsTicket; - - DROP TEMPORARY TABLE IF EXISTS travel_tree_shipment; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `cobro` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `cobro`(IN datFEC DATE - , IN idCLI INT - , IN dblIMPORTE DOUBLE - , IN idCAJA INT - , IN idPAYMET INT - , IN strCONCEPTO VARCHAR(40) - , IN idEMP INT - , IN idWH INT - , IN idTRABAJADOR INT) -BEGIN - - DECLARE bolCASH BOOLEAN; - DECLARE cuenta_banco BIGINT; - DECLARE cuenta_cliente BIGINT; - DECLARE max_asien INT; - - -- XDIARIO - -- No se asientan los cobros directamente, salvo en el caso de las cajas de CASH - SELECT (cash = 1) INTO bolCASH FROM Bancos WHERE Bancos.Id_Banco = idCAJA; - - IF bolCASH THEN - - SELECT Cuenta INTO cuenta_banco FROM Bancos WHERE Id_Banco = idCAJA; - SELECT Cuenta INTO cuenta_cliente FROM Clientes WHERE Id_Cliente = idCLI; - SELECT MAX(asien)+1 INTO max_asien FROM XDiario; - - INSERT INTO XDiario (ASIEN,FECHA,SUBCTA,CONTRA,CONCEPTO,EURODEBE,EUROHABER,empresa_id) - SELECT max_asien,datFEC,SUBCTA,CONTRA,strCONCEPTO,EURODEBE,EUROHABER,idEMP FROM - ( - SELECT cuenta_banco SUBCTA, cuenta_cliente CONTRA, 0 EURODEBE, dblIMPORTE EUROHABER - UNION ALL - SELECT cuenta_cliente SUBCTA, cuenta_banco CONTRA, dblIMPORTE EURODEBE, 0 EUROHABER - ) gf; - - - END IF; - - - -- CAJERA - - INSERT INTO Cajas(Id_Trabajador - , Id_Banco - , Entrada - , Concepto - , Cajafecha - , Serie - , Partida - , Numero - ,empresa_id - ,warehouse_id) - - VALUES ( idTRABAJADOR - , idCAJA - , dblIMPORTE - , strCONCEPTO - , datFEC - , 'A' - , TRUE - , idCLI - , idEMP - , idWH ); - - - - -- RECIBO - INSERT INTO Recibos(Entregado - ,Fechacobro - ,Id_Trabajador - ,Id_Banco - ,Id_Cliente - ,Id_Factura - ,empresa_id) - - VALUES ( dblIMPORTE - , datFEC - , idTRABAJADOR - , idCAJA - , idCLI - , strCONCEPTO - , idEMP); - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `colas_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `colas_launcher`() -BEGIN - - INSERT INTO vn2008.Colas(Id_Informe,Id_Trabajador) VALUES (11,57); - INSERT INTO vn2008.Colas(Id_Informe) VALUES (16); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `comercial_caducado` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `comercial_caducado`() -BEGIN - --- Este procedimiento le pasa los clientes al jefe de ventas cuando llevan dos meses inactivos - -IF day(CURDATE()) = 5 then -- solo se ejecuta los dias 5 de cada mes - - Update Clientes - join - ( - Select c.Id_Cliente - from Clientes c - join jerarquia j on j.worker_id = c.Id_Trabajador -- este filtro es para que solo toque los de los comerciales - - join - ( - select Id_Cliente, sum(Importe) as Saldo - from - ( - select Id_Cliente, Importe from Facturas - union all - select Id_Cliente, - Entregado from Recibos - ) sub - group by Id_Cliente - ) sindeuda on sindeuda.Id_Cliente = c.Id_Cliente - - left join - ( - select distinct Id_Cliente - from Facturas - where Fecha BETWEEN CURDATE() - INTERVAL 12 MONTH AND CURDATE() - ) f on f.Id_Cliente = c.Id_Cliente - - left join - ( - select distinct Id_Cliente - from Tickets - where Fecha between CURDATE() - INTERVAL 2 DAY AND CURDATE() + INTERVAL 200 DAY - - ) tic_vivos on tic_vivos.Id_Cliente = c.Id_Cliente - - where c.Created < CURDATE() - INTERVAL 2 MONTH -- este filtro respeta a los recien nacidos.... - and j.boss_id = 87 -- sólo afecta a los comerciales de Alfredo - and f.Id_Cliente is null -- comprueba que no tenga facturas en los dos ultimos meses - and sindeuda.Saldo < 10 -- sólo cambia a los clientes con deuda escasa o nula - and tic_vivos.Id_Cliente is null -- si tiene tickets vivos, lo respeta - - - ) sub using(Id_Cliente) - - set Id_Trabajador = 87 ;-- Alfredo Giner; - -end if; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `comparativa_clientes` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `comparativa_clientes`(IN v_date DATE,IN i_vendedor INT, IN i_comprador INT, IN i_tipo INT, IN i_wh INT, IN days INT) -BEGIN - -DECLARE date_cyear_ini DATETIME; -DECLARE date_cyear_end DATETIME; -DECLARE date_lyear_ini DATETIME; -DECLARE date_lyear_end DATETIME; -DECLARE week_count TINYINT DEFAULT 7; - - -SET date_cyear_ini = TIMESTAMP(DATE(TIMESTAMPADD(DAY, -22 - WEEKDAY(v_date), v_date)), '00:00:00'); -SET date_cyear_end = TIMESTAMP(DATE(TIMESTAMPADD(DAY, (7 * week_count) -1, date_cyear_ini)), '23:59:59'); -SET date_lyear_ini = TIMESTAMPADD(DAY,-364,date_cyear_ini); -SET date_lyear_end = TIMESTAMPADD(DAY,-364,date_cyear_end); - - CALL article (); - - INSERT INTO article_inventory (article_id) - SELECT Id_Article - FROM Articles a - JOIN Tipos t ON t.tipo_id = a.tipo_id - LEFT JOIN reinos r ON r.id = t.reino_id - WHERE (i_tipo = 0 OR a.tipo_id = i_tipo) - AND r.display <> 0; - - IF v_date < CURDATE() - THEN - ALTER TABLE `article_inventory` - ADD `buy_id` INT NOT NULL DEFAULT 0, - ADD `buy_date` DATE DEFAULT '2000-01-01', - ADD `life` INT DEFAULT 0, - ADD `sd` INT DEFAULT 0, - ADD `avalaible` INT DEFAULT 0, - ADD `visible` INT DEFAULT 0; - - ELSE - CALL inventario_multiple_2 (v_date, i_wh, days); - CALL article_multiple_buy (v_date, i_wh); - CALL article_multiple_buy_date (v_date, i_wh); - END IF; - - - -DROP TEMPORARY TABLE IF EXISTS clientcom; -CREATE TEMPORARY TABLE clientcom -SELECT vnperiod(Fecha) as period - ,Id_Article - , Cantidad - , Preu - , CS.Id_Cliente - FROM vn2008.Movimientos M - JOIN vn2008.Tickets T USING (Id_Ticket) - JOIN vn2008.Consignatarios CS USING(Id_Consigna) - JOIN vn2008.Clientes C ON C.Id_Cliente = CS.Id_Cliente - JOIN vn2008.Articles a USING (Id_Article) - LEFT JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id - WHERE (T.Fecha BETWEEN date_cyear_ini AND date_cyear_end or T.Fecha BETWEEN date_lyear_ini AND date_lyear_end) - AND T.Id_Cliente NOT IN(400,200) - AND i_vendedor IN (0, C.Id_Trabajador ) - AND i_comprador IN (0, tp.Id_Trabajador) - AND i_tipo IN (0,tp.tipo_id) - AND r.display <> 0 AND T.warehouse_id NOT IN (0,13) - ORDER BY period; - -DROP TEMPORARY TABLE IF EXISTS clientcom_periods; -CREATE TEMPORARY TABLE clientcom_periods -SELECT period, @order:= @order + 1 as period_order -FROM ( -SELECT DISTINCT period, @order:=0 -FROM clientcom -ORDER BY period) sub; - -SELECT cc.Id_Article - , cc.Id_Cliente - ,CAST(SUM(IF(period_order = 1, cc.Cantidad, 0)) AS SIGNED) AS lweek1 - ,CAST(SUM(IF(period_order = 2, cc.Cantidad, 0)) AS SIGNED) AS lweek2 - ,CAST(SUM(IF(period_order = 3, cc.Cantidad, 0)) AS SIGNED) AS lweek3 - ,CAST(SUM(IF(period_order = 4, cc.Cantidad, 0)) AS SIGNED) AS lweek4 - ,CAST(SUM(IF(period_order = 5, cc.Cantidad, 0)) AS SIGNED) AS lweek5 - ,CAST(SUM(IF(period_order = 6, cc.Cantidad, 0)) AS SIGNED) AS lweek6 - ,CAST(SUM(IF(period_order = 7, cc.Cantidad, 0)) AS SIGNED) AS lweek7 - ,CAST(SUM(IF(period_order = 7+1, cc.Cantidad, 0)) AS SIGNED) AS cweek1 - ,CAST(SUM(IF(period_order = 7+2, cc.Cantidad, 0)) AS SIGNED) AS cweek2 - ,CAST(SUM(IF(period_order = 7+3, cc.Cantidad, 0)) AS SIGNED) AS cweek3 - ,CAST(SUM(IF(period_order = 7+4, cc.Cantidad, 0)) AS SIGNED) AS cweek4 - ,CAST(SUM(IF(period_order = 7+5, cc.Cantidad, 0)) AS SIGNED) AS cweek5 - ,CAST(SUM(IF(period_order = 7+6, cc.Cantidad, 0)) AS SIGNED) AS cweek6 - ,CAST(SUM(IF(period_order = 7+7, cc.Cantidad, 0)) AS SIGNED) AS cweek7 - - ,CAST(SUM(IF(period_order = 1, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice1 - ,CAST(SUM(IF(period_order = 2, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice2 - ,CAST(SUM(IF(period_order = 3, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice3 - ,CAST(SUM(IF(period_order = 4, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice4 - ,CAST(SUM(IF(period_order = 5, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice5 - ,CAST(SUM(IF(period_order = 6, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice6 - ,CAST(SUM(IF(period_order = 7, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice7 - ,CAST(SUM(IF(period_order = 7+1, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice1 - ,CAST(SUM(IF(period_order = 7+2, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice2 - ,CAST(SUM(IF(period_order = 7+3, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice3 - ,CAST(SUM(IF(period_order = 7+4, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice4 - ,CAST(SUM(IF(period_order = 7+5, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice5 - ,CAST(SUM(IF(period_order = 7+6, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice6 - ,CAST(SUM(IF(period_order = 7+7, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice7 - - ,A.Article - ,A.Medida - ,A.Color - ,A.tipo_id - ,C.Cliente - ,T1.CodigoTrabajador as Comercial - ,O.Abreviatura as Origen - ,TT.ball as Tinta - ,r.reino as Reino - ,TP.Id_Tipo - ,JF.CodigoTrabajador as Equipo - ,T2.CodigoTrabajador as Comprador - ,TT.orden as Orden_Color - -,i.buy_id -, i.life -, CAST(IFNULL(i.sd,0) AS SIGNED) as sd -,CAST(i.avalaible AS SIGNED) avalaible -, CAST(i.visible AS SIGNED) visible -, i.buy_date -,P.Proveedor - -FROM clientcom cc -JOIN clientcom_periods ccp using(period) --- La parte del inventario -LEFT JOIN article_inventory i ON i.article_id = cc.Id_Article -LEFT JOIN Compres CM ON i.buy_id = CM.Id_Compra -LEFT JOIN Entradas E USING(Id_Entrada) -LEFT JOIN Proveedores P ON P.Id_Proveedor = E.Id_Proveedor --- Ahora la parte de los vendedores -JOIN Clientes C ON C.Id_Cliente = cc.Id_Cliente -JOIN Trabajadores T1 ON C.Id_Trabajador = T1.Id_Trabajador -LEFT JOIN jerarquia J ON J.worker_id = T1.Id_Trabajador -JOIN Trabajadores JF ON JF.Id_Trabajador = J.boss_id --- JOIN Trabajadores JF ON T1.Id_Trabajador = JF.boss JGF propuesta para sustituir por las dos lineas superiores - --- Ahora la parte de los compradores -JOIN Articles A ON A.Id_Article = cc.Id_Article -JOIN Origen O ON O.id = A.id_origen -JOIN Tintas TT ON TT.Id_Tinta = A.Color -JOIN Tipos TP ON TP.tipo_id = A.tipo_id -JOIN reinos r ON r.id = TP.reino_id -JOIN Trabajadores T2 ON T2.Id_Trabajador = TP.Id_Trabajador - -GROUP BY Id_Article,Id_Cliente; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `comparativa_clienteskk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `comparativa_clienteskk`(IN v_date DATE,IN i_vendedor INT, IN i_comprador INT, IN i_tipo INT, IN i_wh INT, IN days INT) -BEGIN - -DECLARE date_cyear_ini DATETIME; -DECLARE date_cyear_end DATETIME; -DECLARE date_lyear_ini DATETIME; -DECLARE date_lyear_end DATETIME; -DECLARE week_count TINYINT DEFAULT 7; - - -SET date_cyear_ini = TIMESTAMP(DATE(TIMESTAMPADD(DAY, -22 - WEEKDAY(v_date), v_date)), '00:00:00'); -SET date_cyear_end = TIMESTAMP(DATE(TIMESTAMPADD(DAY, (7 * week_count) -1, date_cyear_ini)), '23:59:59'); -SET date_lyear_ini = TIMESTAMPADD(DAY,-364,date_cyear_ini); -SET date_lyear_end = TIMESTAMPADD(DAY,-364,date_cyear_end); - - CALL article (); - - INSERT INTO article_inventory (article_id) - SELECT Id_Article FROM Articles a - JOIN Tipos t using(tipo_id) - WHERE i_tipo = 0 OR a.tipo_id = i_tipo - AND reino_id <> 6; - - IF v_date < CURDATE() - THEN - ALTER TABLE `article_inventory` - ADD `buy_id` INT NOT NULL DEFAULT 0, - ADD `buy_date` DATE DEFAULT '2000-01-01', - ADD `life` INT DEFAULT 0, - ADD `sd` INT DEFAULT 0, - ADD `avalaible` INT DEFAULT 0, - ADD `visible` INT DEFAULT 0; - - ELSE - CALL inventario_multiple_2 (v_date, i_wh, days); - CALL article_multiple_buy (v_date, i_wh); - CALL article_multiple_buy_date (v_date, i_wh); - END IF; - - - -DROP TEMPORARY TABLE IF EXISTS clientcom; -CREATE TEMPORARY TABLE clientcom -SELECT vnperiod(Fecha) as period - ,Id_Article - , Cantidad - , Preu - , CS.Id_Cliente - FROM vn2008.Movimientos M - JOIN vn2008.Tickets T USING (Id_Ticket) - JOIN vn2008.Consignatarios CS USING(Id_Consigna) - JOIN vn2008.Clientes C ON C.Id_Cliente = CS.Id_Cliente - JOIN vn2008.Articles A USING (Id_Article) - LEFT JOIN vn2008.Tipos USING(tipo_id) - WHERE (T.Fecha BETWEEN date_cyear_ini AND date_cyear_end or T.Fecha BETWEEN date_lyear_ini AND date_lyear_end) - AND T.Id_Cliente NOT IN(400,200) - AND i_vendedor IN (0, C.Id_Trabajador ) - AND i_comprador IN (0, Tipos.Id_Trabajador) - AND i_tipo IN (0,Tipos.tipo_id) - AND reino_id <> 6 AND T.warehouse_id NOT IN (0,13) - ORDER BY period; - -DROP TEMPORARY TABLE IF EXISTS clientcom_periods; -CREATE TEMPORARY TABLE clientcom_periods -SELECT period, @order:= @order + 1 as period_order -FROM ( -SELECT DISTINCT period, @order:=0 -FROM clientcom -ORDER BY period) sub; - -SELECT cc.Id_Article - , cc.Id_Cliente - ,CAST(SUM(IF(period_order = 1, cc.Cantidad, 0)) AS SIGNED) AS lweek1 - ,CAST(SUM(IF(period_order = 2, cc.Cantidad, 0)) AS SIGNED) AS lweek2 - ,CAST(SUM(IF(period_order = 3, cc.Cantidad, 0)) AS SIGNED) AS lweek3 - ,CAST(SUM(IF(period_order = 4, cc.Cantidad, 0)) AS SIGNED) AS lweek4 - ,CAST(SUM(IF(period_order = 5, cc.Cantidad, 0)) AS SIGNED) AS lweek5 - ,CAST(SUM(IF(period_order = 6, cc.Cantidad, 0)) AS SIGNED) AS lweek6 - ,CAST(SUM(IF(period_order = 7, cc.Cantidad, 0)) AS SIGNED) AS lweek7 - ,CAST(SUM(IF(period_order = 7+1, cc.Cantidad, 0)) AS SIGNED) AS cweek1 - ,CAST(SUM(IF(period_order = 7+2, cc.Cantidad, 0)) AS SIGNED) AS cweek2 - ,CAST(SUM(IF(period_order = 7+3, cc.Cantidad, 0)) AS SIGNED) AS cweek3 - ,CAST(SUM(IF(period_order = 7+4, cc.Cantidad, 0)) AS SIGNED) AS cweek4 - ,CAST(SUM(IF(period_order = 7+5, cc.Cantidad, 0)) AS SIGNED) AS cweek5 - ,CAST(SUM(IF(period_order = 7+6, cc.Cantidad, 0)) AS SIGNED) AS cweek6 - ,CAST(SUM(IF(period_order = 7+7, cc.Cantidad, 0)) AS SIGNED) AS cweek7 - - ,CAST(SUM(IF(period_order = 1, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice1 - ,CAST(SUM(IF(period_order = 2, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice2 - ,CAST(SUM(IF(period_order = 3, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice3 - ,CAST(SUM(IF(period_order = 4, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice4 - ,CAST(SUM(IF(period_order = 5, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice5 - ,CAST(SUM(IF(period_order = 6, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice6 - ,CAST(SUM(IF(period_order = 7, cc.Cantidad* Preu, 0)) AS SIGNED) AS lprice7 - ,CAST(SUM(IF(period_order = 7+1, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice1 - ,CAST(SUM(IF(period_order = 7+2, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice2 - ,CAST(SUM(IF(period_order = 7+3, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice3 - ,CAST(SUM(IF(period_order = 7+4, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice4 - ,CAST(SUM(IF(period_order = 7+5, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice5 - ,CAST(SUM(IF(period_order = 7+6, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice6 - ,CAST(SUM(IF(period_order = 7+7, cc.Cantidad* Preu, 0)) AS SIGNED) AS cprice7 - - ,A.Article - ,A.Medida - ,A.Color - ,A.tipo_id - ,C.Cliente - ,T1.CodigoTrabajador as Comercial - ,O.Abreviatura as Origen - ,TT.ball as Tinta - ,r.reino as Reino - ,TP.Id_Tipo - ,JF.CodigoTrabajador as Equipo - ,T2.CodigoTrabajador as Comprador - ,TT.orden as Orden_Color - -,i.buy_id -, i.life -, CAST(IFNULL(i.sd,0) AS SIGNED) as sd -,CAST(i.avalaible AS SIGNED) avalaible -, CAST(i.visible AS SIGNED) visible -, i.buy_date -,P.Proveedor - -FROM clientcom cc -JOIN clientcom_periods ccp using(period) --- La parte del inventario -LEFT JOIN article_inventory i ON i.article_id = cc.Id_Article -LEFT JOIN Compres CM ON i.buy_id = CM.Id_Compra -LEFT JOIN Entradas E USING(Id_Entrada) -LEFT JOIN Proveedores P ON P.Id_Proveedor = E.Id_Proveedor --- Ahora la parte de los vendedores -JOIN Clientes C ON C.Id_Cliente = cc.Id_Cliente -JOIN Trabajadores T1 ON C.Id_Trabajador = T1.Id_Trabajador -LEFT JOIN jerarquia J ON J.worker_id = T1.Id_Trabajador -JOIN Trabajadores JF ON JF.Id_Trabajador = J.boss_id --- JOIN Trabajadores JF ON T1.Id_Trabajador = JF.boss JGF propuesta para sustituir por las dos lineas superiores - --- Ahora la parte de los compradores -JOIN Articles A ON A.Id_Article = cc.Id_Article -JOIN Origen O ON O.id = A.id_origen -JOIN Tintas TT ON TT.Id_Tinta = A.Color -JOIN Tipos TP ON TP.tipo_id = A.tipo_id -JOIN reinos r ON r.id = TP.reino_id -JOIN Trabajadores T2 ON T2.Id_Trabajador = TP.Id_Trabajador - -GROUP BY Id_Article,Id_Cliente; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `comparativa_clientes_tickets` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `comparativa_clientes_tickets`(IN i_week INT - , IN i_year INT - , IN i_vendedor INT - , IN i_comprador INT - , IN i_article INT - , IN i_cliente INT - , IN i_tipo INT - , IN i_reino INT - , IN i_equipo INT - , IN v_color varchar(3)) -BEGIN - -DECLARE datSTART DATETIME; -DECLARE datEND DATETIME; - -SELECT min(date), TIMESTAMP(max(date),'23:59:59') INTO datSTART, datEND FROM time WHERE i_week = week AND i_year = year; - - - -SELECT T.Id_Ticket, Fecha, Alias, Id_Article, Concepte, Cantidad, Preu, M.Descuento, Cantidad * Preu * (100-M.Descuento)/100 as Importe, w.name as almacen -FROM Movimientos M -JOIN Tickets T using(Id_Ticket) -JOIN warehouse w on w.id = T.warehouse_id -JOIN Consignatarios CS using(Id_Consigna) -JOIN Clientes C ON C.Id_Cliente = CS.Id_Cliente -JOIN Trabajadores TR ON TR.Id_Trabajador = C.Id_Trabajador -JOIN jerarquia J ON J.worker_id = TR.Id_Trabajador -JOIN Articles A using(Id_Article) -JOIN Tipos TP using(tipo_id) -WHERE T.Fecha BETWEEN datSTART AND datEND -AND i_vendedor IN (0, C.Id_Trabajador) -AND i_comprador IN (0, TP.Id_Trabajador) -AND i_cliente IN (0, CS.Id_Cliente) -AND i_tipo IN (0, A.tipo_id) -AND i_article IN (0,A.Id_Article) -AND i_reino IN (0,TP.reino_id) -AND i_equipo IN(0,J.boss_id) -AND v_color IN ("",A.color); - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `comparative` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `comparative`( - v_date DATETIME - ,days TINYINT - ,i_wh TINYINT - ,i_tipo INT - ,i_filtro INT -) -BEGIN - DECLARE wstart INT; - DECLARE wend INT; - DECLARE cyear INT; - DECLARE date_cyear_ini DATETIME; - DECLARE date_cyear_end DATETIME; - DECLARE week_count TINYINT DEFAULT 7; - DECLARE date_lyear_ini DATETIME; - DECLARE date_lyear_end DATETIME; - DECLARE corrector INT; - DECLARE w1, w2, w3, w4, w5, w6, w7 INT; - DECLARE y1, y2, y3, y4, y5, y6, y7 INT; - DECLARE wperiod INT;-- DECLARE ws, ys INT; -- PAK 11/01/2016 - DECLARE i INT DEFAULT 0; - DECLARE lastCOMP BIGINT; -- Almacena el ultimo valor del Periodo - DECLARE strFILTRO VARCHAR(255) DEFAULT 'TRUE'; - - IF i_filtro THEN - SELECT `sql` INTO strFILTRO FROM filtros WHERE id = i_filtro; - END IF; - - SET corrector = 1; - - IF days < 0 OR days > 30 THEN - SET days = 15; - END IF; - - IF i_wh = NULL THEN - SET i_wh = 0; - END IF; - -- JGF 2015-04-16 cambio -21 por -22 para que la semana cuente de domingo a sabado - SET date_cyear_ini = TIMESTAMP(DATE(TIMESTAMPADD(DAY, -22 - WEEKDAY(v_date), v_date)), '00:00:00'); - SET date_cyear_end = TIMESTAMP(DATE(TIMESTAMPADD(DAY, (7 * week_count) -1, date_cyear_ini)), '23:59:59'); - -- Eliminamos el calculo del inventario para fechas en el pasado - - DROP TEMPORARY TABLE IF EXISTS `article_inventory`; - CREATE TEMPORARY TABLE `article_inventory` - ( - `article_id` INT(11) NOT NULL PRIMARY KEY, - `future` DATETIME - ) - ENGINE = MEMORY; - - INSERT INTO article_inventory (article_id) - SELECT Id_Article FROM Articles a - JOIN Tipos t ON a.tipo_id = t.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = t.reino_id - WHERE (i_tipo = 0 OR a.tipo_id = i_tipo) - AND r.display <> 0; - - IF v_date < CURDATE() - THEN - ALTER TABLE `article_inventory` - ADD `buy_id` INT NOT NULL DEFAULT 0, - ADD `buy_date` DATE DEFAULT '2000-01-01', - ADD `life` INT DEFAULT 0, - ADD `sd` INT DEFAULT 0, - ADD `avalaible` INT DEFAULT 0, - ADD `visible` INT DEFAULT 0; - - ELSE - - CALL inventario_multiple_2 (v_date, i_wh, days); - - CALL article_multiple_buy (v_date, i_wh); - - CALL article_multiple_buy_date (v_date, i_wh); - - - END IF; - - - DROP TEMPORARY TABLE IF EXISTS wtable; - - CREATE TEMPORARY TABLE wtable ( - cy INT(6), - ly INT(6) - ); - - REPEAT - SET i = i + 1; - SET wperiod = vnperiod(TIMESTAMPADD(DAY, 7*(i - 1), date_cyear_ini)); -- PAK 11/01/2016 - INSERT INTO wtable(cy, ly) VALUES(wperiod, wperiod - 100); -- VALUES( ys * 100 + ws, (ys -1) * 100 + ws); -- PAK 11/01/2016 - - UNTIL i = 7 END REPEAT; - - - SELECT cy, ly INTO w1, y1 FROM wtable limit 1; - SELECT cy, ly INTO w2, y2 FROM wtable WHERE cy > w1 limit 1; - SELECT cy, ly INTO w3, y3 FROM wtable WHERE cy > w2 limit 1; - SELECT cy, ly INTO w4, y4 FROM wtable WHERE cy > w3 limit 1; - - SELECT cy, ly INTO w5, y5 FROM wtable WHERE cy > w4 limit 1; - SELECT cy, ly INTO w6, y6 FROM wtable WHERE cy > w5 limit 1; - SELECT cy, ly INTO w7, y7 FROM wtable WHERE cy > w6 limit 1; - DROP TEMPORARY TABLE wtable; - - SET cyear = YEAR(date_cyear_ini); - - -- Genera una tabla con los datos del año pasado. - - DROP TEMPORARY TABLE IF EXISTS last_year; - CREATE TEMPORARY TABLE last_year - (KEY (Id_Article)) - ENGINE = MEMORY - SELECT Id_Article - - ,CAST(SUM(IF(Periodo = y1, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek1 - ,CAST(SUM(IF(Periodo = y2, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek2 - ,CAST(SUM(IF(Periodo = y3, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek3 - ,CAST(SUM(IF(Periodo = y4, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek4 - ,CAST(SUM(IF(Periodo = y5, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek5 - ,CAST(SUM(IF(Periodo = y6, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek6 - ,CAST(SUM(IF(Periodo = y7, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek7 - - ,CAST(SUM(IF(Periodo = y1, price, 0)) AS DECIMAL(10,0)) AS lprice1 - ,CAST(SUM(IF(Periodo = y2, price, 0)) AS DECIMAL(10,0)) AS lprice2 - ,CAST(SUM(IF(Periodo = y3, price, 0)) AS DECIMAL(10,0)) AS lprice3 - ,CAST(SUM(IF(Periodo = y4, price, 0)) AS DECIMAL(10,0)) AS lprice4 - ,CAST(SUM(IF(Periodo = y5, price, 0)) AS DECIMAL(10,0)) AS lprice5 - ,CAST(SUM(IF(Periodo = y6, price, 0)) AS DECIMAL(10,0)) AS lprice6 - ,CAST(SUM(IF(Periodo = y7, price, 0)) AS DECIMAL(10,0)) AS lprice7 - - FROM Comparativa - JOIN warehouse W on W.id = warehouse_id - WHERE (Periodo BETWEEN y1 and y7) - AND IF(i_wh = 0, W.is_comparative, i_wh = warehouse_id) - GROUP BY Id_Article; - - -- Genera una tabla con los datos de este año. - - DROP TEMPORARY TABLE IF EXISTS cur_year; - CREATE TEMPORARY TABLE cur_year - (KEY (Id_Article)) - ENGINE = MEMORY - SELECT Id_Article - - ,CAST(SUM(IF(week = w1, Total, 0)) AS DECIMAL(10,0)) AS cweek1 - ,CAST(SUM(IF(week = w2, Total, 0)) AS DECIMAL(10,0)) AS cweek2 - ,CAST(SUM(IF(week = w3, Total, 0)) AS DECIMAL(10,0)) AS cweek3 - ,CAST(SUM(IF(week = w4, Total, 0)) AS DECIMAL(10,0)) AS cweek4 - ,CAST(SUM(IF(week = w5, Total, 0)) AS DECIMAL(10,0)) AS cweek5 - ,CAST(SUM(IF(week = w6, Total, 0)) AS DECIMAL(10,0)) AS cweek6 - ,CAST(SUM(IF(week = w7, Total, 0)) AS DECIMAL(10,0)) AS cweek7 - - ,CAST(SUM(IF(week = w1, price, 0)) AS DECIMAL(10,0)) AS cprice1 - ,CAST(SUM(IF(week = w2, price, 0)) AS DECIMAL(10,0)) AS cprice2 - ,CAST(SUM(IF(week = w3, price, 0)) AS DECIMAL(10,0)) AS cprice3 - ,CAST(SUM(IF(week = w4, price, 0)) AS DECIMAL(10,0)) AS cprice4 - ,CAST(SUM(IF(week = w5, price, 0)) AS DECIMAL(10,0)) AS cprice5 - ,CAST(SUM(IF(week = w6, price, 0)) AS DECIMAL(10,0)) AS cprice6 - ,CAST(SUM(IF(week = w7, price, 0)) AS DECIMAL(10,0)) AS cprice7 - - FROM ( - SELECT A.Id_Article - ,CTS.period week - ,SUM(Cantidad) AS Total - ,TRUNCATE(SUM(Cantidad * IF(T.Fecha >= '2015-10-01',M.CostFixat,Preu * (100 - Descuento) / 100)),0) AS price - FROM Movimientos M - LEFT JOIN Tickets T ON T.Id_Ticket = M.Id_Ticket - INNER JOIN `time` CTS ON CTS.`date` = DATE(T.Fecha) - INNER JOIN Articles A USING (Id_Article) - INNER JOIN Tipos tp ON tp.tipo_id = A.tipo_id - LEFT JOIN reinos r ON r.id = tp.reino_id - JOIN warehouse W ON W.id = T.warehouse_id - WHERE Fecha BETWEEN date_cyear_ini AND date_cyear_end - AND T.Id_Cliente NOT IN(400,200) - AND IF(i_wh = 0, W.is_comparative, i_wh = T.warehouse_id) - AND r.display <> 0 - - GROUP BY A.Id_Article, week - ) t - GROUP BY Id_Article; - -- Genera la tabla con la comparativa. - - DROP TEMPORARY TABLE IF EXISTS remcom; - - SET strFILTRO = REPLACE(strFILTRO, 'Id_Article','A.Id_Article'); - SET strFILTRO = REPLACE(strFILTRO, 'tipo_id','tp.tipo_id'); - -- select * from article_inventory; - - DROP TEMPORARY TABLE IF EXISTS tmp.comparative; - - CALL util.exec (sql_printf - ( - 'CREATE TEMPORARY TABLE tmp.comparative ENGINE = MEMORY - SELECT - an.nicho, p.name Productor, C.Packing, C.Costefijo - ,A.Color, Id_Tipo as Tipo,A.tipo_id, o.Abreviatura as Origen, A.Categoria - ,A.Tallos, A.Medida, A.Article, TR.CodigoTrabajador - - ,cweek1, cweek2, cweek3, cweek4, cweek5, cweek6, cweek7 - ,lweek1, lweek2, lweek3, lweek4, lweek5, lweek6, lweek7 - - ,cprice1, cprice2, cprice3, cprice4, cprice5, cprice6, cprice7 - ,lprice1, lprice2, lprice3, lprice4, lprice5, lprice6, lprice7 - - ,A.Id_Article, i.buy_id , tp.life , CAST(IFNULL(i.sd,0) AS SIGNED) as sd - ,CAST(i.avalaible AS SIGNED) avalaible, CAST(i.visible AS SIGNED) visible, i.buy_date - ,E.Id_Proveedor AS provider_id - ,A.offer, A.bargain, A.comments, A.relevancy, A.description itemDescription - ,IF(cy.Id_Article IS NULL AND i.visible = 0 AND i.avalaible = 0 AND IFNULL(i.sd, 0) = 0, FALSE, TRUE) AS filtret - ,(IFNULL(it.itemFk,0) != 0) isTagged - FROM vn2008.article_inventory i - JOIN vn2008.Articles A ON A.Id_Article = i.article_id - LEFT JOIN vn.itemTagged it ON it.itemFk = i.article_id - LEFT JOIN vn2008.Articles_nicho an ON A.Id_Article = an.Id_Article AND an.warehouse_id = %s - LEFT JOIN vn2008.producer p ON p.producer_id = A.producer_id - LEFT JOIN vn2008.Tipos tp ON A.tipo_id = tp.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id - LEFT JOIN vn2008.Trabajadores TR ON TR.Id_Trabajador = tp.Id_Trabajador - - LEFT JOIN vn2008.Compres C ON i.buy_id = C.Id_Compra - LEFT JOIN vn2008.Entradas E USING(Id_Entrada) - LEFT JOIN vn2008.Origen o ON o.id = A.id_origen - LEFT JOIN vn2008.last_year ly ON ly.Id_Article = A.Id_Article - LEFT JOIN vn2008.cur_year cy ON cy.Id_Article = A.Id_Article AND (i.avalaible <> 0 OR i.visible <> 0 OR cweek1 OR cweek2 OR cweek3 OR cweek4 - OR cweek5 OR cweek6 OR cweek7 OR lweek1 OR lweek2 OR lweek3 OR lweek4 OR lweek5 - OR lweek6 OR lweek7) - WHERE r.display <> 0 AND %s ' - - ,i_wh,strFILTRO - )); - - -- Destruye las tablas temporales creadas. - - DROP TEMPORARY TABLE last_year; - DROP TEMPORARY TABLE cur_year; - DROP TEMPORARY TABLE article_inventory; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `comparativeTestkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `comparativeTestkk`( - v_date DATETIME - ,days TINYINT - ,i_wh TINYINT - ,i_tipo INT - ,i_filtro INT -) -BEGIN - DECLARE wstart INT; - DECLARE wend INT; - DECLARE cyear INT; - DECLARE date_cyear_ini DATETIME; - DECLARE date_cyear_end DATETIME; - DECLARE week_count TINYINT DEFAULT 7; - DECLARE date_lyear_ini DATETIME; - DECLARE date_lyear_end DATETIME; - DECLARE corrector INT; - DECLARE w1, w2, w3, w4, w5, w6, w7 INT; - DECLARE y1, y2, y3, y4, y5, y6, y7 INT; - DECLARE wperiod INT;-- DECLARE ws, ys INT; -- PAK 11/01/2016 - DECLARE i INT DEFAULT 0; - DECLARE lastCOMP BIGINT; -- Almacena el ultimo valor del Periodo - DECLARE strFILTRO VARCHAR(255) DEFAULT 'TRUE'; - - IF i_filtro THEN - SELECT `sql` INTO strFILTRO FROM filtros WHERE id = i_filtro; - END IF; - - SET corrector = 1; - - IF days < 0 OR days > 30 THEN - SET days = 15; - END IF; - - IF i_wh = NULL THEN - SET i_wh = 0; - END IF; - -- JGF 2015-04-16 cambio -21 por -22 para que la semana cuente de domingo a sabado - SET date_cyear_ini = TIMESTAMP(DATE(TIMESTAMPADD(DAY, -22 - WEEKDAY(v_date), v_date)), '00:00:00'); - SET date_cyear_end = TIMESTAMP(DATE(TIMESTAMPADD(DAY, (7 * week_count) -1, date_cyear_ini)), '23:59:59'); - -- Eliminamos el calculo del inventario para fechas en el pasado - - CALL article (); - - INSERT INTO article_inventory (article_id) - SELECT Id_Article FROM Articles a - JOIN Tipos t ON a.tipo_id = t.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = t.reino_id - WHERE (i_tipo = 0 OR a.tipo_id = i_tipo) - AND r.display <> 0; - - IF v_date < CURDATE() - THEN - ALTER TABLE `article_inventory` - ADD `buy_id` INT NOT NULL DEFAULT 0, - ADD `buy_date` DATE DEFAULT '2000-01-01', - ADD `life` INT DEFAULT 0, - ADD `sd` INT DEFAULT 0, - ADD `avalaible` INT DEFAULT 0, - ADD `visible` INT DEFAULT 0; - - ELSE - - CALL inventario_multiple_2 (v_date, i_wh, days); - - CALL article_multiple_buy (v_date, i_wh); - - CALL article_multiple_buy_date (v_date, i_wh); - - - END IF; - - - DROP TEMPORARY TABLE IF EXISTS wtable; - - CREATE TEMPORARY TABLE wtable ( - cy INT(6), - ly INT(6) - ); - - REPEAT - SET i = i + 1; - SET wperiod = vnperiod(TIMESTAMPADD(DAY, 7*(i - 1), date_cyear_ini)); -- PAK 11/01/2016 - INSERT INTO wtable(cy, ly) VALUES(wperiod, wperiod - 100); -- VALUES( ys * 100 + ws, (ys -1) * 100 + ws); -- PAK 11/01/2016 - - UNTIL i = 7 END REPEAT; - - - SELECT cy, ly INTO w1, y1 FROM wtable limit 1; - SELECT cy, ly INTO w2, y2 FROM wtable WHERE cy > w1 limit 1; - SELECT cy, ly INTO w3, y3 FROM wtable WHERE cy > w2 limit 1; - SELECT cy, ly INTO w4, y4 FROM wtable WHERE cy > w3 limit 1; - - SELECT cy, ly INTO w5, y5 FROM wtable WHERE cy > w4 limit 1; - SELECT cy, ly INTO w6, y6 FROM wtable WHERE cy > w5 limit 1; - SELECT cy, ly INTO w7, y7 FROM wtable WHERE cy > w6 limit 1; - DROP TEMPORARY TABLE wtable; - - SET cyear = YEAR(date_cyear_ini); - - -- Genera una tabla con los datos del año pasado. - - DROP TEMPORARY TABLE IF EXISTS last_year; - CREATE TEMPORARY TABLE last_year - (KEY (Id_Article)) - ENGINE = MEMORY - SELECT Id_Article - - ,CAST(SUM(IF(Periodo = y1, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek1 - ,CAST(SUM(IF(Periodo = y2, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek2 - ,CAST(SUM(IF(Periodo = y3, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek3 - ,CAST(SUM(IF(Periodo = y4, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek4 - ,CAST(SUM(IF(Periodo = y5, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek5 - ,CAST(SUM(IF(Periodo = y6, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek6 - ,CAST(SUM(IF(Periodo = y7, Cantidad, 0)) AS DECIMAL(10,0)) AS lweek7 - - ,CAST(SUM(IF(Periodo = y1, price, 0)) AS DECIMAL(10,0)) AS lprice1 - ,CAST(SUM(IF(Periodo = y2, price, 0)) AS DECIMAL(10,0)) AS lprice2 - ,CAST(SUM(IF(Periodo = y3, price, 0)) AS DECIMAL(10,0)) AS lprice3 - ,CAST(SUM(IF(Periodo = y4, price, 0)) AS DECIMAL(10,0)) AS lprice4 - ,CAST(SUM(IF(Periodo = y5, price, 0)) AS DECIMAL(10,0)) AS lprice5 - ,CAST(SUM(IF(Periodo = y6, price, 0)) AS DECIMAL(10,0)) AS lprice6 - ,CAST(SUM(IF(Periodo = y7, price, 0)) AS DECIMAL(10,0)) AS lprice7 - - FROM Comparativa - JOIN warehouse W on W.id = warehouse_id - WHERE (Periodo BETWEEN y1 and y7) - AND IF(i_wh = 0, W.is_comparative, i_wh = warehouse_id) - GROUP BY Id_Article; - - -- Genera una tabla con los datos de este año. - - DROP TEMPORARY TABLE IF EXISTS cur_year; - CREATE TEMPORARY TABLE cur_year - (KEY (Id_Article)) - ENGINE = MEMORY - SELECT Id_Article - - ,CAST(SUM(IF(week = w1, Total, 0)) AS DECIMAL(10,0)) AS cweek1 - ,CAST(SUM(IF(week = w2, Total, 0)) AS DECIMAL(10,0)) AS cweek2 - ,CAST(SUM(IF(week = w3, Total, 0)) AS DECIMAL(10,0)) AS cweek3 - ,CAST(SUM(IF(week = w4, Total, 0)) AS DECIMAL(10,0)) AS cweek4 - ,CAST(SUM(IF(week = w5, Total, 0)) AS DECIMAL(10,0)) AS cweek5 - ,CAST(SUM(IF(week = w6, Total, 0)) AS DECIMAL(10,0)) AS cweek6 - ,CAST(SUM(IF(week = w7, Total, 0)) AS DECIMAL(10,0)) AS cweek7 - - ,CAST(SUM(IF(week = w1, price, 0)) AS DECIMAL(10,0)) AS cprice1 - ,CAST(SUM(IF(week = w2, price, 0)) AS DECIMAL(10,0)) AS cprice2 - ,CAST(SUM(IF(week = w3, price, 0)) AS DECIMAL(10,0)) AS cprice3 - ,CAST(SUM(IF(week = w4, price, 0)) AS DECIMAL(10,0)) AS cprice4 - ,CAST(SUM(IF(week = w5, price, 0)) AS DECIMAL(10,0)) AS cprice5 - ,CAST(SUM(IF(week = w6, price, 0)) AS DECIMAL(10,0)) AS cprice6 - ,CAST(SUM(IF(week = w7, price, 0)) AS DECIMAL(10,0)) AS cprice7 - - FROM ( - SELECT A.Id_Article - ,CTS.period week - ,SUM(Cantidad) AS Total - ,TRUNCATE(SUM(Cantidad * IF(T.Fecha >= '2015-10-01',M.CostFixat,Preu * (100 - Descuento) / 100)),0) AS price - FROM Movimientos M - LEFT JOIN Tickets T ON T.Id_Ticket = M.Id_Ticket - INNER JOIN `time` CTS ON CTS.`date` = DATE(T.Fecha) - INNER JOIN Articles A USING (Id_Article) - INNER JOIN Tipos tp ON tp.tipo_id = A.tipo_id - LEFT JOIN reinos r ON r.id = tp.reino_id - JOIN warehouse W ON W.id = T.warehouse_id - WHERE Fecha BETWEEN date_cyear_ini AND date_cyear_end - AND T.Id_Cliente NOT IN(400,200) - AND IF(i_wh = 0, W.is_comparative, i_wh = T.warehouse_id) - AND r.display <> 0 - - GROUP BY A.Id_Article, week - ) t - GROUP BY Id_Article; - -- Genera la tabla con la comparativa. - - DROP TEMPORARY TABLE IF EXISTS remcom; - - SET strFILTRO = REPLACE(strFILTRO, 'Id_Article','A.Id_Article'); - SET strFILTRO = REPLACE(strFILTRO, 'tipo_id','tp.tipo_id'); - -- select * from article_inventory; - CALL util.exec (sql_printf - ( - 'SELECT - an.nicho, p.name Productor, C.Packing, C.Costefijo - ,A.Color, Id_Tipo as Tipo,A.tipo_id, o.Abreviatura as Origen, A.Categoria - ,A.Tallos, A.Medida, A.Article, TR.CodigoTrabajador - - ,cweek1, cweek2, cweek3, cweek4, cweek5, cweek6, cweek7 - ,lweek1, lweek2, lweek3, lweek4, lweek5, lweek6, lweek7 - - ,cprice1, cprice2, cprice3, cprice4, cprice5, cprice6, cprice7 - ,lprice1, lprice2, lprice3, lprice4, lprice5, lprice6, lprice7 - - ,A.Id_Article, i.buy_id , tp.life , CAST(IFNULL(i.sd,0) AS SIGNED) as sd - ,CAST(i.avalaible AS SIGNED) avalaible, CAST(i.visible AS SIGNED) visible, i.buy_date - ,E.Id_Proveedor AS provider_id, t.Orden, t.Tinta - ,A.offer, A.bargain, A.comments, A.relevancy, A.description itemDescription - ,IF(cy.Id_Article IS NULL AND i.visible = 0 AND i.avalaible = 0 AND IFNULL(i.sd, 0) = 0, FALSE, TRUE) AS filtret - ,(IFNULL(it.itemFk,0) != 0) isTagged - FROM vn2008.article_inventory i - JOIN vn2008.Articles A ON A.Id_Article = i.article_id - LEFT JOIN vn.itemTagged it ON it.itemFk = i.article_id - LEFT JOIN vn2008.Articles_nicho an ON A.Id_Article = an.Id_Article AND an.warehouse_id = %s - LEFT JOIN vn2008.producer p ON p.producer_id = A.producer_id - LEFT JOIN vn2008.Tipos tp ON A.tipo_id = tp.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id - LEFT JOIN vn2008.Trabajadores TR ON TR.Id_Trabajador = tp.Id_Trabajador - LEFT JOIN vn2008.Tintas t ON t.Id_Tinta = A.color - LEFT JOIN vn2008.Compres C ON i.buy_id = C.Id_Compra - LEFT JOIN vn2008.Entradas E USING(Id_Entrada) - LEFT JOIN vn2008.Origen o ON o.id = A.id_origen - LEFT JOIN vn2008.last_year ly ON ly.Id_Article = A.Id_Article - LEFT JOIN vn2008.cur_year cy ON cy.Id_Article = A.Id_Article AND (i.avalaible <> 0 OR i.visible <> 0 OR cweek1 OR cweek2 OR cweek3 OR cweek4 - OR cweek5 OR cweek6 OR cweek7 OR lweek1 OR lweek2 OR lweek3 OR lweek4 OR lweek5 - OR lweek6 OR lweek7) - WHERE r.display <> 0 AND %s ' - - ,i_wh,strFILTRO - )); - - -- Destruye las tablas temporales creadas. - - DROP TEMPORARY TABLE last_year; - DROP TEMPORARY TABLE cur_year; - DROP TEMPORARY TABLE article_inventory; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `compresFromTicket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compresFromTicket`(IN vTicketId BIGINT, IN vEntryId BIGINT) -BEGIN - - DECLARE vShipmentWarehouse INT; - DECLARE vShipmentDate INT; - - SELECT warehouse_id_out, shipment - INTO vShipmentWarehouse, vShipmentDate - FROM travel tr - JOIN Entradas e ON e.travel_id = tr.id - WHERE Id_Entrada = vEntryId; - - CALL item_last_buy_(vShipmentWarehouse,vShipmentDate); - - INSERT INTO Compres(Id_Article,Cantidad, Id_Entrada, Id_Cubo, Packing, grouping, caja, Costefijo, Etiquetas) - SELECT m.Id_Article, - m.Cantidad, - vEntryId, - c.Id_Cubo, - c.Packing, - IF(c.grouping,c.grouping,1), - c.caja, - buyingAbsoluteCost(c.Id_Compra) Costefijo, - ifnull(floor(m.Cantidad / c.Packing),1) Etiquetas - FROM - Movimientos m - JOIN Articles a ON m.Id_Article = a.Id_Article - LEFT JOIN t_item_last_buy b ON m.Id_Article = b.item_id AND b.warehouse_id = vShipmentWarehouse - LEFT JOIN Compres c ON c.Id_Compra = b.buy_id - WHERE m.Id_Ticket = vTicketId; - - CALL buy_tarifas_entry(vEntryId); - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `CompresTriggerBeforeDelete` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `CompresTriggerBeforeDelete`(oldId INT, oldEntrada INT) -BEGIN - - DECLARE hasToRecalculate BOOLEAN; - DECLARE newWarehouse INT; - - SELECT Id_Compra INTO hasToRecalculate FROM vn.lastBuy lb - WHERE lb.id = oldId LIMIT 1; - - IF hasToRecalculate THEN - SELECT warehouse_id INTO newWarehouse FROM travel t - JOIN Entradas e ON t.id = e.travel_id - WHERE e.Id_Entrada = oldEntrada; - - CALL vn.lastBuyRefresh(newWarehouse); - END IF; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `compresTriggerBeforeInsert` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compresTriggerBeforeInsert`(newNoVincular INT, newEntrada INT, newCompra INT, newItem INT) -BEGIN - DECLARE newWarehouse INTEGER; - - IF newNoVincular = FALSE THEN - - UPDATE travel t - JOIN vn.lastBuy lb ON newItem = lb.item AND t.warehouse_id = lb.warehouse - JOIN Entradas e ON e.travel_id = t.id - SET lb.id = newCompra - WHERE e.Id_Entrada = newEntrada AND t.landing > lb.landing AND t.landing <= CURDATE(); - - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `compresTriggerBeforeUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compresTriggerBeforeUpdate`(vOldEntrada INT, vNewEntrada INT, oldItem INT, - newItem INT, newNoVincular BOOLEAN, newCompra INT) -BEGIN - DECLARE newWarehouse INTEGER; - DECLARE hasToRecalculate BOOLEAN; - - IF newNoVincular = FALSE THEN - IF oldItem <> newItem OR vOldEntrada <> vNewEntrada THEN - SELECT Id_Compra INTO hasToRecalculate FROM travel t - JOIN Entradas e ON e.travel_id = t.id - JOIN vn.lastBuy lb ON lb.id = newCompra - WHERE e.Id_Entrada = vOldEntrada LIMIT 1; - - IF hasToRecalculate THEN - SELECT warehouse_id INTO newWarehouse FROM travel t - JOIN Entradas e ON t.id = e.travel_id - WHERE e.Id_Entrada = vOldEntrada; - CALL vn.lastBuyRefresh(newWarehouse); - END IF; - END IF; - IF vOldEntrada <> vNewEntrada THEN - - UPDATE Entradas oldEntrada - JOIN travel oldTravel ON oldEntrada.travel_id = oldtravel.id - JOIN Entradas newEntrada ON newEntrada.Id_Entrada = vNewEntrada - JOIN travel newTravel ON newTravel.id = newEntrada.travel_id - JOIN vn.lastBuy lb ON newItem = lb.item AND newTravel.warehouse_id = lb.warehouse - SET lb.id = newCompra - WHERE oldEntrada.Id_Entrada = vOldEntrada AND oldTravel.warehouse_id <> newTravel.warehouse_id - AND newTravel.landing > lb.landing AND newTravel.landing <= CURDATE(); - END IF; - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `confection_control_source` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `confection_control_source`(vScopeDays TINYINT) -BEGIN - - DECLARE vMidnight DATETIME DEFAULT TIMESTAMP(CURDATE(),'23:59:59'); - DECLARE vEndingDate DATETIME DEFAULT TIMESTAMPADD(DAY,vScopeDays,vMidnight); - DECLARE maxAlertLevel INT DEFAULT 2; - - DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; - - CREATE TEMPORARY TABLE tmp.production_buffer - ENGINE = MEMORY - SELECT - date(t.Fecha) as Fecha, - hour(t.Fecha) as Hora, - hour(t.Fecha) as Departure, - t.Id_Ticket, - m.Id_Movimiento, - m.Cantidad, - m.Concepte, - ABS(m.Reservado) Reservado, - i.Categoria, - t.Alias as Cliente, - wh.name as Almacen, - t.warehouse_id, - cs.province_id, - a.agency_id, - ct.description as Taller, - stock.visible, - stock.available - FROM vn2008.Tickets t - JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia - JOIN vn2008.warehouse wh ON wh.id = t.warehouse_id - JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles i ON i.Id_Article = m.Id_Article - JOIN vn2008.Tipos tp ON tp.tipo_id = i.tipo_id - JOIN vn.confectionType ct ON ct.id = tp.confeccion - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket - LEFT JOIN - ( - SELECT item_id, sum(visible) visible, sum(available) available - FROM - ( - SELECT a.item_id, 0 as visible, a.available - FROM cache.cache_calc cc - LEFT JOIN cache.available a ON a.calc_id = cc.id - WHERE cc.cache_id IN (2,8) - AND cc.params IN (concat("1/", CURDATE()),concat("44/", CURDATE())) - - UNION ALL - - SELECT v.item_id, v.visible, 0 as available - FROM cache.cache_calc cc - LEFT JOIN cache.visible v ON v.calc_id = cc.id - where cc.cache_id IN (2,8) and cc.params IN ("1","44") - ) sub - GROUP BY item_id - ) stock ON stock.item_id = m.Id_Article - WHERE tp.confeccion - AND tls.alertLevel < maxAlertLevel - AND wh.hasConfectionTeam - AND t.Fecha BETWEEN CURDATE() AND vEndingDate - AND m.Cantidad > 0; - - -- Hora limite de preparación - - CALL production_buffer_set_priority; - - -- Entradas - - INSERT INTO tmp.production_buffer( - Fecha, - Id_Ticket, - Cantidad, - Concepte, - Categoria, - Cliente, - Almacen, - Taller - ) - SELECT - tr.shipment AS Fecha, - e.Id_Entrada AS Id_Ticket, - c.Cantidad, - a.Article, - a.Categoria, - whi.name as Cliente, - who.name as Almacen, - ct.description as Taller - FROM vn2008.Compres c - JOIN vn2008.Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN vn2008.travel tr ON tr.id = e.travel_id - JOIN vn2008.warehouse whi ON whi.id = tr.warehouse_id - JOIN vn2008.warehouse who ON who.id = tr.warehouse_id_out - JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article - JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id - JOIN vn.confectionType ct ON ct.id = tp.confeccion - WHERE who.hasConfectionTeam - AND tp.confeccion - AND tr.shipment BETWEEN CURDATE() AND vEndingDate; - - - SELECT * FROM tmp.production_buffer; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `createBouquet` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `createBouquet`( - vName VARCHAR(50), - vType int, - vSize int, - vColour VARCHAR(5), - OUT vItem INT(11) - -) -BEGIN - DECLARE vDate DATE; - DECLARE vCodintrastat INT(11); - - -- COMPROBAMOS SI EXISTE UN ARTÍCULO IGUAL. - SELECT - Id_Article - INTO vItem FROM - Articles - WHERE - (Id_Article BETWEEN 161000 AND 169000) - AND Article LIKE CONCAT('%', vName) - AND tipo_id = vType - AND Medida = vSize - AND Color = vColour - LIMIT 1; - - -- SI NO EXISTE CREAMOS UNO NUEVO - IF vItem IS NULL THEN - - - -- OBTENER EL ID ENTRE 161000 Y 169000 DEL SIGUIENTE ARTÍCULO - SELECT (IF(MAX(Id_Article) IS NULL, 161000, (MAX(Id_Article) + 1))) INTO vItem FROM Articles WHERE Id_Article BETWEEN 161000 AND 169000; - - -- INSERTAR EL ARTÍCULO - INSERT INTO Articles(Id_Article, Article, tipo_id, Medida, color, id_origen) - VALUES ( - vItem, - vName, - vType, - vSize, - vColour, - 1 - ); - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `createWorker` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `createWorker`( - vName VARCHAR(50), - vCognames VARCHAR(50), - vDNI VARCHAR(9), - vAddress TEXT, - vPostalCode VARCHAR(5), - vTown VARCHAR(25), - vProvince SMALLINT(5), - vCompany SMALLINT(5), - vPhone VARCHAR(11), - vMail VARCHAR(80) CHARSET utf8, - vDniExpiration DATETIME, - vEmployeeBoss INT -) -BEGIN - DECLARE vClient INT; - DECLARE vUser INT; - DECLARE vWorker INT; - DECLARE vWorkerCode VARCHAR(8); - DECLARE vPassword VARCHAR(50); - DECLARE vUsername VARCHAR(50) CHARSET utf8; - DECLARE vOficial INT DEFAULT 1; - DECLARE vDiscount INT DEFAULT 3; - DECLARE vPayMethodFk INT DEFAULT 4; - DECLARE vDueDay INT DEFAULT 5; - DECLARE vDefaultCredit DECIMAL(10, 2) DEFAULT 300.00; - DECLARE vIsTaxDataChecked TINYINT(1) DEFAULT 1; - DECLARE vHasCoreVnl TINYINT(1) DEFAULT 1; - DECLARE vMandateType INT DEFAULT 2; - - -############################################################################## -#### GENERAR CLIENTE -############################################################################## - - -- Comprobar si existe un cliente con el mismo DNI. - SELECT Id_cliente INTO vClient FROM vn2008.Clientes WHERE `if` = vDNI; - - -- Si no existe el cliente creamos uno nuevo. - IF vClient IS NULL THEN - - SELECT (MAX(Id_Cliente) + 1) INTO vClient FROM Clientes WHERE Id_Cliente < 999999; - - INSERT INTO Clientes ( - Id_Cliente, - Cliente, - Domicilio, - `IF`, - Telefono, - province_id, - Poblacion, - CodPostal, - RazonSocial, - Contacto, - Oficial, - Descuento, - Codpos, - pay_met_id, - Vencimiento, - credito, - contabilizado, - coreVnl) - SELECT - vClient, - Concat('TR ', vName, ' ', vCognames), - vAddress, - vDNI, - vPhone, - vProvince, - vTown, - vPostalCode, - CONCAT(vCognames, ' ', vName), - vName, - vOficial, - vDiscount, - vPostalCode, - vPayMethodFk, - vDueDay, - vDefaultCredit, - vIsTaxDataChecked, - vHasCoreVnl; - - INSERT INTO mandato (Id_Cliente, empresa_id, idmandato_tipo) - VALUES (vClient, vCompany, vMandateType); - END IF; - - -############################################################################## -#### GENERAR USUARIO -############################################################################## - - SET vUsername = LCASE(CONCAT(REPLACE(vName, ' ', ''), LEFT(vCognames, 1), MID(vCognames, (LOCATE(' ', vCognames) + 1), 1))); - - -- Generar nombre de usuario hasta que haya uno disponible. - WHILE (SELECT COUNT(*) FROM account.user WHERE `name`= vUsername) DO - SET vUsername = CONCAT(vUsername, (FLOOR(RAND() * 100))); - END WHILE; - - SET vPassword = CONCAT(IF(INSTR(vCognames,' ') = 0, vCognames, LEFT(vCognames, INSTR(vCognames,' ') - 1)), '.' , vClient); - - -- Comprobamos si existe un usuario con el mismo ID de cliente. - IF NOT (SELECT COUNT(*) FROM account.user where id = vClient) THEN - - -- Alta del usuario. - INSERT INTO account.user (id, role, `name`, `password`, active) VALUES (vClient, 1, LCASE(vUsername), MD5(LCASE(vPassword)), 1); - SET vUser = vClient; - INSERT INTO account.account SET id = vClient; - ELSE - - -- Alta del usuario. - INSERT INTO account.user (role, `name`, `password`, active) VALUES (1, LCASE(vUsername), MD5(LCASE(vPassword)), 1); - SET vUser = LAST_INSERT_ID(); - INSERT INTO account.account SET id = vUser; - END IF; - -############################################################################## -#### GENERAR TRABAJADOR -############################################################################## - - SET vWorkerCode = CONCAT(LEFT(vName, 1), LEFT(vCognames, 1), MID(vCognames, (LOCATE(' ', vCognames) + 1), 1)); - - -- Generar código de trabajador hasta que haya uno disponible. - IF (SELECT COUNT(*) FROM Trabajadores WHERE CodigoTrabajador = vWorkerCode) THEN - SET vWorkerCode = "001"; - END IF; - - -- Comprobamos si ya existe un trabajador con el mismo DNI. - IF NOT (SELECT COUNT(*) FROM Trabajadores WHERE dni = vDNI) THEN - - -- Alta en la tabla trabajadores. - INSERT INTO Trabajadores (CodigoTrabajador, Nombre, Apellidos, `Password`, dni, empresa_id, user_id, boss, DniExpiration) - VALUES (vWorkerCode, vName, vCognames, LCASE(vPassword), vDNI, vCompany, vUser, vEmployeeBoss, VDniExpiration); - - SET vWorker = LAST_INSERT_ID(); - ELSE - UPDATE Trabajadores SET user_id = vUser WHERE dni = vDNI; - END IF; - -############################################################################## -#### REENVIO EMAIL -############################################################################## - - IF vMail IS NOT NULL AND NOT (SELECT COUNT(*) FROM account.mailForward WHERE forwardTo = vMail) THEN - INSERT INTO account.mailForward (account, forwardTo) VALUES (vUser, vMail); - UPDATE Trabajadores SET email = CONCAT(vUsername, '@verdnatura.es') WHERE user_id = vUser; - END IF; - - -- Devolver información generada - SELECT vUser, vWorker, vPassword, vUsername; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `credit_update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `credit_update`() -BEGIN - -DECLARE dblDiferencia DOUBLE DEFAULT 10.0; -DECLARE dblImporteRec,auxdblImporteRec DOUBLE DEFAULT 0.0; -DECLARE dblImporteFac,auxdblImporteFac DOUBLE DEFAULT 0.0; -DECLARE intIdRecibo,auxintIdRecibo INT (11) DEFAULT 0; -DECLARE intId_Cliente,auxintId_Cliente,intId_ClienteRec,auxintId_ClienteRec INT DEFAULT 0; -DECLARE bitFin,bitFinRecord,bitFinRecord1 BIT DEFAULT 0; -DECLARE datFechaVencimiento DATE DEFAULT CURDATE(); -DECLARE intEmpresa_id INT DEFAULT 0; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `customerDebtEvolution` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `customerDebtEvolution`(IN vCustomer INT) -BEGIN - -SELECT * FROM -( - SELECT day, date, @s:= round(IFNULL(Euros,0) + @s,2) as Saldo, Euros, Credito, 0 as Cero - FROM - ( - SELECT day, date, IFNULL(Euros,0) as Euros, Credito - FROM time - JOIN (SELECT @s:= 0, - Credito as Credito FROM Clientes WHERE Id_Cliente = vCustomer) c - LEFT JOIN - (SELECT Euros, date(Fecha) as Fecha FROM - ( - SELECT Fechacobro as Fecha, Entregado as Euros - FROM Recibos - WHERE Id_Cliente = vCustomer - AND Fechacobro >= '2017-01-01' - UNION ALL - SELECT paymentday(f.Fecha,c.Vencimiento), - Importe - FROM Facturas f - JOIN Clientes c ON f.Id_Cliente = c.Id_Cliente - WHERE f.Id_Cliente = vCustomer - AND Fecha >= '2017-01-01' - UNION ALL - SELECT '2016-12-31', Debt - FROM bi.customerDebtInventory - WHERE Id_Cliente = vCustomer - UNION ALL - SELECT Fecha, - SUM(Cantidad * Preu * (100 - Descuento ) * 1.10 / 100) - FROM Tickets t - JOIN Movimientos m on m.Id_Ticket = t.Id_Ticket - WHERE Id_Cliente = vCustomer - AND Factura IS NULL - AND Fecha >= '2017-01-01' - GROUP BY Fecha - ) sub2 - ORDER BY Fecha - )sub ON time.date = sub.Fecha - WHERE time.date BETWEEN '2016-12-31' AND CURDATE() - ORDER BY date - ) sub3 -)sub4 -; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `cycDueDateClassification` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `cycDueDateClassification`(vCompany INT,vDate DATE) -BEGIN - - SELECT Fecha, Clasificacion, CAST(SUM(Importe) AS DECIMAL(10,2)) as Importe, empresa_id - FROM - ( - SELECT CASE - WHEN C.Vencimiento <= 30 THEN '0-30 dias' - WHEN C.Vencimiento BETWEEN 31 AND 60 THEN '31-60 dias' - WHEN C.Vencimiento BETWEEN 61 AND 90 THEN '61-90 dias' - ELSE '> 90 dias' - END AS Clasificacion, - F.Importe, - C.Fecha, - F.empresa_id - - FROM cyc_declaration C - JOIN Facturas F USING(factura_id) - WHERE C.Riesgo > 0 AND C.Fecha = vDate AND F.empresa_id = vCompany - - ) cyc - GROUP BY Fecha, Clasificacion, empresa_id; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `cycGeneralClassification` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `cycGeneralClassification`(vCompany INT,vDate DATE) -BEGIN - SELECT Fecha, Clasificacion, CAST(SUM(Importe) AS DECIMAL(10,2)) as Importe, empresa_id - FROM - ( - SELECT CASE IFNULL(C.Riesgo,-1) - WHEN 0 THEN 'No aseguradas' - WHEN -1 THEN 'Clasificacion nada' - ELSE 'Asegurados' - END AS Clasificacion, - F.Importe, - C.Fecha, - F.empresa_id - - FROM cyc_declaration C - JOIN Facturas F ON F.factura_id = C.factura_id - WHERE C.Fecha = vDate AND F.empresa_id = vCompany - - ) cyc - GROUP BY Fecha, Clasificacion, empresa_id; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `cycNoInsurancedClassification` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `cycNoInsurancedClassification`(vCompany INT,vDate DATE) -BEGIN - -SELECT 'ORG. PUBLICOS' AS Tipo, C.Fecha, CAST(SUM(F.Importe) AS DECIMAL(10,2)) as Importe, F.empresa_id - - FROM cyc_declaration C - INNER JOIN Facturas F USING(factura_id) - JOIN Clientes CL USING(Id_Cliente) - WHERE C.Riesgo IS NULL - AND LEFT(CL.`IF`,1) = 'G' - AND C.Fecha = vDate AND F.empresa_id = vCompany - -GROUP BY Fecha, F.empresa_id - -UNION ALL - -SELECT 'VINCULADAS' , C.Fecha, CAST(SUM(F.Importe) AS DECIMAL(10,2)) as Importe, F.empresa_id - - FROM cyc_declaration C - INNER JOIN Facturas F USING(factura_id) - WHERE C.Riesgo IS NULL - AND F.Id_Cliente IN(2066, 2067) - AND C.Fecha = vDate AND F.empresa_id = vCompany - -GROUP BY Fecha, F.empresa_id - -UNION ALL - -SELECT 'CONTADO', C.Fecha, CAST(SUM(F.Importe) AS DECIMAL(10,2)) as Importe, F.empresa_id - - FROM cyc_declaration C - INNER JOIN Facturas F USING(factura_id) - JOIN Clientes CL USING(Id_Cliente) - WHERE C.Riesgo IS NULL - AND pay_met_id = 1 - AND LEFT(CL.`IF`,1) <> 'G' - AND F.Id_Cliente NOT IN(2066, 2067) - AND C.Fecha = vDate AND F.empresa_id = vCompany - -GROUP BY Fecha, F.empresa_id - -UNION ALL - -SELECT 'OTROS', C.Fecha, CAST(SUM(F.Importe) AS DECIMAL(10,2)) as Importe, F.empresa_id - - FROM cyc_declaration C - INNER JOIN Facturas F USING(factura_id) - JOIN Clientes CL USING(Id_Cliente) - WHERE C.Riesgo IS NULL - AND pay_met_id <> 1 - AND LEFT(CL.`IF`,1) <> 'G' - AND F.Id_Cliente NOT IN(2066, 2067) - AND C.Fecha = vDate AND F.empresa_id = vCompany - -GROUP BY Fecha, F.empresa_id - - -; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `cyc_mensual` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `cyc_mensual`(IN datFEC DATE) -BEGIN - -REPLACE cyc_declaration(factura_id, Riesgo, Fecha, Vencimiento) -SELECT F.factura_id, R.Riesgo, @fecha, IFNULL(C.Vencimiento,0) -FROM Facturas F -INNER JOIN Clientes C ON F.Id_Cliente = C.Id_Cliente -INNER JOIN empresa E ON E.id = F.empresa_id -LEFT JOIN - ( SELECT * - FROM ( - SELECT Id_Cliente, Riesgo - FROM cyc - WHERE Fecha <= @fecha:= TIMESTAMPADD(DAY, -1 * DAY(datFEC), datFEC) - ORDER BY Fecha DESC - ) sub - GROUP BY Id_Cliente - ) R ON F.Id_Cliente = R.Id_Cliente -WHERE E.cyc -AND periodo(Fecha) = periodo(@fecha) -; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `cyc_report2kk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `cyc_report2kk`() -BEGIN - -SELECT Fecha, Clasificacion, CAST(SUM(Importe) AS DECIMAL(10,2)) as Importe, empresa_id -FROM -( - SELECT CASE - WHEN C.Vencimiento <= 30 THEN '0-30 dias' - WHEN C.Vencimiento BETWEEN 31 AND 60 THEN '31-60 dias' - WHEN C.Vencimiento BETWEEN 61 AND 90 THEN '61-90 dias' - ELSE '> 90 dias' - END AS Clasificacion, - F.Importe, - C.Fecha, - F.empresa_id - - FROM cyc_declaration C - INNER JOIN Facturas F USING(factura_id) - WHERE C.Riesgo > 0 - -) cyc -GROUP BY Fecha, Clasificacion, empresa_id; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `cyc_reportkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `cyc_reportkk`() -BEGIN - -SELECT Fecha, Clasificacion, CAST(SUM(Importe) AS DECIMAL(10,2)) as Importe, empresa_id -FROM -( - SELECT CASE IFNULL(C.Riesgo,-1) - WHEN 0 THEN 'No aseguradas' - WHEN -1 THEN 'Sin clasificar' - ELSE 'Asegurados' - END AS Clasificacion, - F.Importe, - C.Fecha, - F.empresa_id - - FROM cyc_declaration C - INNER JOIN Facturas F USING(factura_id) - -) cyc -GROUP BY Fecha, Clasificacion, empresa_id; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `defaulterRanking` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `defaulterRanking`() -BEGIN - -SELECT - c.Id_Cliente, - hasChanged, - Cliente, - amount as Deuda, - CodigoTrabajador, - CyC, - Apuntador, - Fecha_obs, - last_obs, - defaulterSince -from - bi.defaulters d - join - ( - SELECT customer_id Id_Cliente,SUM(amount) AS Saldo - FROM bi.customerRiskOverdue - GROUP BY customer_id - ) saldos ON saldos.Id_Cliente = d.client - join - Clientes c on c.Id_Cliente = d.client - join - Trabajadores t USING (Id_Trabajador) -left join -( -SELECT Id_Cliente, last_obs, CodigoTrabajador as Apuntador, Fecha as Fecha_obs -FROM -( -SELECT Id_Cliente, `text` as last_obs, CodigoTrabajador, client_observation.odbc_date as Fecha -FROM client_observation -JOIN Trabajadores using(Id_Trabajador) -order by client_observation.odbc_date desc -) sub GROUP BY Id_Cliente -) obs on obs.Id_Cliente = d.client -WHERE -date = CURDATE() -and amount > 0 -and not (Saldo > amount AND amount < 0) -and CodigoTrabajador not in ('CYC','BUD','EJE') -ORDER BY amount DESC; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `desglose_volume` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `desglose_volume`(IN agency_id INT) -BEGIN - DECLARE v_start DATETIME DEFAULT TIMESTAMP(CURDATE()); - DECLARE v_end DATETIME DEFAULT TIMESTAMP(CURDATE(), '23:59:59'); - - SET v_start = IF(WEEKDAY(CURDATE()), CURDATE(),TIMESTAMPADD(DAY,-1,CURDATE())); - SET v_start = IF(CURDATE() = '2014-05-02', '2014-05-01',v_start); - - DROP TEMPORARY TABLE IF EXISTS zeleVOL; - CREATE TEMPORARY TABLE zeleVOL - ( - Id_Ticket INT PRIMARY KEY - ,Provincia VARCHAR(30) - ,Bultos INT DEFAULT 0 - ,Faltan INT DEFAULT 0 - ); - - -- Insertamos los tickets que ya tienen la linea de portes - - INSERT INTO zeleVOL(Provincia, Id_Ticket, Bultos) - SELECT p.name, t.Id_Ticket, sum(m.Cantidad) - FROM Tickets t - JOIN Consignatarios c USING(Id_Consigna) - JOIN province p ON c.province_id = p.province_id - JOIN Movimientos m USING(Id_Ticket) - JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia - JOIN warehouse_joined wj ON wj.warehouse_id = t.warehouse_id - WHERE m.Id_Article = 71 - AND wj.warehouse_alias_id = 1 -- El 1 equivale a Silla (SillaFV-SillaPCA) - AND t.Fecha BETWEEN v_start AND v_end - AND a.agency_id = agency_id - GROUP BY p.name, Id_Ticket; - - -- Insertamos los tickets que ya tienen expediciones, que fallaran si se repite la clave primaria. - - INSERT INTO zeleVOL(Provincia, Id_Ticket, Bultos) SELECT p.name, e.ticket_id, COUNT(e.ticket_id) - FROM expeditions e - JOIN Tickets t ON ticket_id = Id_Ticket - JOIN Consignatarios c USING(Id_Consigna) - JOIN province p ON c.province_id = p.province_id - JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia - JOIN warehouse_joined wj ON wj.warehouse_id = t.warehouse_id - WHERE e.odbc_date BETWEEN v_start AND v_end - AND wj.warehouse_alias_id = 1 -- El 1 equivale a Silla (SillaFV-SillaPCA) - AND a.agency_id = agency_id - GROUP BY p.name, ticket_id - ON DUPLICATE KEY UPDATE Bultos = Bultos; - - -- Por encajar - - INSERT INTO zeleVOL(Provincia, Id_Ticket, Faltan) - SELECT province, Id_Ticket, COUNT(Id_Ticket) as Faltan - FROM - ( - SELECT p.name AS province, Id_Ticket, COUNT(Id_Movimiento) l, SUM(Cantidad) c - FROM Movimientos m - JOIN Tickets t USING(Id_Ticket) - JOIN Consignatarios c USING(Id_Consigna) - JOIN province p ON c.province_id = p.province_id - JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN expeditions e ON t.Id_Ticket = e.ticket_id - JOIN warehouse_joined wj ON wj.warehouse_id = t.warehouse_id - WHERE Fecha BETWEEN v_start AND v_end - AND wj.warehouse_alias_id = 1 -- El 1 equivale a Silla (SillaFV-SillaPCA) - AND a.agency_id = agency_id - AND (Bultos = 0 AND expeditions_id IS NULL AND EtiquetasEmitidas = 0) - GROUP BY p.name, Id_Ticket - ) sub GROUP BY province - ON DUPLICATE KEY UPDATE Faltan = Faltan; - -- Mostramos el resultado - - SELECT Provincia, COUNT(Id_Ticket) expediciones, SUM(Bultos) Bultos, SUM(Faltan) Prevision - FROM zeleVOL - GROUP BY Provincia; - - DROP TEMPORARY TABLE IF EXISTS zeleVOL; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `dif_porte` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `dif_porte`(IN datFEC DATE) -BEGIN - -/* Calcula los greuges de porte que no coinciden con lo esperado -/ -/ -/ -*/ - - -drop temporary table if exists tmp.bionic_porte; -create temporary table tmp.bionic_porte -select Id_Ticket, sum(Valor * Cantidad) as bionic -from vn2008.Movimientos m -join vn2008.Movimientos_componentes mc using(Id_Movimiento) -where Id_Componente = 15 -group by Id_Ticket; - -ALTER TABLE tmp.bionic_porte -ADD KEY bp_Id_Ticket_ix (Id_Ticket); - - -drop temporary table if exists tmp.shipping_porte; -create temporary table tmp.shipping_porte -select Id_Ticket, shipping_charge from vn2008.v_expeditions_shipping_charge where Fecha >= datFEC; - -ALTER TABLE tmp.shipping_porte -ADD KEY sp_Id_Ticket_ix (Id_Ticket); - - -drop temporary table if exists tmp.greuge_porte; -create temporary table tmp.greuge_porte -select Id as Id_Greuge, cast(right(Comentario,7) as decimal(10,0)) Id_Ticket, Importe -FROM vn2008.Greuges -where Comentario like 'dif_porte%'; -ALTER TABLE tmp.greuge_porte -ADD KEY Id_Ticket_ix (Id_Ticket); -select * from tmp.greuge_porte; - - - -SELECT Id_Ticket,shipping_charge as Teorico, bionic as Practico, Importe as Greuge, shipping_charge - bionic - Importe as dif -FROM tmp.shipping_porte -join tmp.greuge_porte using(Id_Ticket) -join tmp.bionic_porte using(Id_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 DROP PROCEDURE IF EXISTS `Ditacio` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Ditacio`(IN intId INT,IN straccion varchar(100),IN strtabla CHAR(1),IN intIdTrabajador INT, -IN straccion_old VARCHAR(100),IN straccion_new VARCHAR(100)) -proc_label:BEGIN - - DECLARE intlengthaccion TINYINT; - DECLARE strtabla_dits VARCHAR(35); - - SELECT CASE - WHEN strtabla='A' THEN 'Articles_dits' - WHEN strtabla='I' THEN 'Inventario_dits' - WHEN strtabla='E' THEN 'Entradas_dits' - WHEN strtabla='T' THEN 'Tickets_dits' - WHEN strtabla='C' THEN 'Clientes_dits' - WHEN strtabla='V' THEN 'travel_dits' - WHEN strtabla='R' THEN 'Rutas_dits' - WHEN strtabla='G' THEN 'Agencias_dits' - WHEN strtabla='S' THEN 'salarioDits' - ELSE NULL - END - INTO strtabla_dits; - - IF (strtabla_dits IS NULL) - THEN LEAVE proc_label; - END IF; - - SET @intIdTrabajador = intIdTrabajador; - SET @intId = intId; - SET @strvalue_old = straccion_old; - SET @strvalue_new = straccion_new; - SET @intidaccion = NULL; - - SELECT idaccion_dits - INTO @intidaccion - FROM accion_dits - WHERE accion=left(straccion,CHAR_LENGTH(accion)) - ORDER BY CHAR_LENGTH(accion) DESC - LIMIT 1; - - IF @intidaccion IS null THEN -- idaccion genèric per a evitar errors en cas de no existir - SET @intidaccion = 103; - END IF; - - SET @SQL=CONCAT('INSERT INTO ',strtabla_dits,' (idaccion_dits,Id_Trabajador,Id_Ticket,value_old,value_new) - VALUES (?,?,?,?,?)'); - - PREPARE stmt1 FROM @SQL; - EXECUTE stmt1 USING @intidaccion,@intIdTrabajador,@intId,@strvalue_old,@strvalue_new; - DEALLOCATE PREPARE stmt1; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `emailYesterdayPurchasesByConsigna` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `emailYesterdayPurchasesByConsigna`(IN v_Date DATE, IN v_Client_Id INT) -BEGIN - - -DECLARE MyIdTicket BIGINT; -DECLARE MyAlias VARCHAR(50); -DECLARE MyDomicilio VARCHAR(255); -DECLARE MyPoblacion VARCHAR(25); -DECLARE MyImporte DOUBLE; -DECLARE MyMailTo VARCHAR(250); -DECLARE MyMailReplyTo VARCHAR(250); -DECLARE done INT DEFAULT FALSE; -DECLARE emptyList INT DEFAULT 0; -DECLARE txt TEXT; - -DECLARE rs CURSOR FOR -SELECT t.Id_Ticket, Alias, cast(amount as decimal(10,2)) Importe, Domicilio, POBLACION -FROM Tickets t -JOIN Consignatarios cs on t.Id_Consigna = cs.Id_Consigna -JOIN v_ticket_amount v on v.Id_Ticket = t.Id_Ticket -WHERE t.Fecha BETWEEN v_Date AND dayend(v_Date) -AND t.Id_Cliente = v_Client_Id; - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - -SET v_Date = IFNULL(v_Date, util.yesterday()); - -OPEN rs; - -FETCH rs INTO MyIdTicket, MyAlias, MyImporte, MyDomicilio, MyPoblacion; - -SET emptyList = done; - -SET txt = CONCAT('

    ', - '

    Relación de envíos.

    ', - '

    Dia: ', v_Date, '

    '); - -WHILE NOT done DO - - SET txt = CONCAT(txt, '

    ', - ' - - - - - - -
    - Ticket ', MyIdTicket,' ', MyImporte, ' €
    ' - , ' ', MyAlias, '
    ' - , ' ', MyDomicilio, '(', MyPoblacion, ')'); - -FETCH rs INTO MyIdTicket, MyAlias, MyImporte, MyDomicilio, MyPoblacion; - -END WHILE; - - -SET txt = CONCAT(txt, - '', - '', - '
    ', - '

    Puede acceder al detalle de los albaranes haciendo click sobre el número de Ticket', - '

    Muchas gracias por su confianza

    ', - '

    '); - --- Envío del email -IF emptyList = 0 THEN - - SELECT CONCAT(`e-mail`,',pako@verdnatura.es') INTO MyMailTo - FROM Clientes - WHERE Id_Cliente = v_Client_Id AND `e-mail`>''; - - IF v_Client_Id = 7818 THEN -- LOEWE - - SET MyMailTo = 'isabel@elisabethblumen.com,emunozca@loewe.es,pako@verdnatura.es'; - - END IF; - - INSERT INTO mail(`to`, reply_to, subject, text) - VALUES (IFNULL(MyMailTo,'pako.natek@gmail.com'),'pako@verdnatura.es','Resumen de pedidos preparados',txt); - -END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `emailYesterdayPurchasesLauncher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `emailYesterdayPurchasesLauncher`() -BEGIN - -DECLARE done INT DEFAULT 0; -DECLARE vMyClientId INT; - -DECLARE rs CURSOR FOR -SELECT Id_Cliente -FROM Clientes -WHERE EYPBC != 0; - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - -OPEN rs; - -FETCH rs INTO vMyClientId; - -WHILE NOT done DO - - CALL emailYesterdayPurchasesByConsigna(util.yesterday(), vMyClientId); - - FETCH rs INTO vMyClientId; - -END WHILE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `embalajes_stocks` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `embalajes_stocks`(IN idPEOPLE INT, IN bolCLIENT BOOLEAN) -BEGIN - -if bolCLIENT then - - select m.Id_Article, Article, - cast(sum(m.Cantidad) as decimal) as Saldo - from Movimientos m - join Articles a on m.Id_Article = a.Id_Article - join Tipos tp on tp.tipo_id = a.tipo_id - join Tickets t using(Id_Ticket) - join Consignatarios cs using(Id_Consigna) - where cs.Id_Cliente = idPEOPLE - and Tipo = 'Contenedores' - and t.Fecha > '2010-01-01' - group by m.Id_Article; - -else - -select Id_Article, Article, sum(Cantidad) as Saldo -from -(select Id_Article, Cantidad -from Compres c -join Articles a using(Id_Article) -join Tipos tp using(tipo_id) -join Entradas e using(Id_Entrada) -join travel tr on tr.id = travel_id -where Id_Proveedor = idPEOPLE -and landing >= '2010-01-01' -and reino_id = 6 - -union all - -select Id_Article, - Cantidad -from Movimientos m -join Articles a using(Id_Article) -join Tipos tp using(tipo_id) -join Tickets t using(Id_Ticket) -join Consignatarios cs using(Id_Consigna) -join proveedores_clientes pc on pc.Id_Cliente = cs.Id_Cliente -where Id_Proveedor = idPEOPLE -and reino_id = 6 -and t.Fecha > '2010-01-01') mov - -join Articles a using(Id_Article) -group by Id_Article; - -end if; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `embalajes_stocks_detalle` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `embalajes_stocks_detalle`(IN idPEOPLE INT, IN idARTICLE INT, IN bolCLIENT BOOLEAN) -BEGIN - - -if bolCLIENT then - - select m.Id_Article - , Article - , IF(Cantidad < 0, - Cantidad, NULL) as Entrada - , IF(Cantidad < 0, NULL, Cantidad) as Salida - , 'T' as Tabla - , t.Id_Ticket as Registro - , t.Fecha - , w.name as Almacen - , cast(Preu as Decimal(5,2)) Precio - , c.Cliente as Proveedor - , abbreviation as Empresa - from Movimientos m - join Articles a using(Id_Article) - join Tickets t using(Id_Ticket) - join empresa e on e.id = t.empresa_id - join warehouse w on w.id = t.warehouse_id - join Consignatarios cs using(Id_Consigna) - join Clientes c on c.Id_Cliente = cs.Id_Cliente - where cs.Id_Cliente = idPEOPLE - and m.Id_Article = idARTICLE - and t.Fecha > '2010-01-01'; - -else - -select Id_Article, Tabla, Registro, Fecha, Article -, w.name as Almacen, Entrada, Salida, Proveedor, cast(Precio as Decimal(5,2)) Precio - -from - -(select Id_Article - , IF(Cantidad > 0, Cantidad, NULL) as Entrada - , IF(Cantidad > 0, NULL,- Cantidad) as Salida - , 'E' as Tabla - , Id_Entrada as Registro - , landing as Fecha - , tr.warehouse_id - , Costefijo as Precio -from Compres c -join Entradas e using(Id_Entrada) -join travel tr on tr.id = travel_id -where Id_Proveedor = idPEOPLE -and Id_Article = idARTICLE -and landing >= '2010-01-01' - -union all - -select Id_Article - , IF(Cantidad < 0, - Cantidad, NULL) as Entrada - , IF(Cantidad < 0, NULL, Cantidad) as Salida - , 'T' - , Id_Ticket - , Fecha - , t.warehouse_id - , Preu -from Movimientos m -join Tickets t using(Id_Ticket) -join Consignatarios cs using(Id_Consigna) -join proveedores_clientes pc on pc.Id_Cliente = cs.Id_Cliente -where Id_Proveedor = idPEOPLE -and Id_Article = idARTICLE -and t.Fecha > '2010-01-01') mov - -join Articles a using(Id_Article) -join Proveedores p on Id_Proveedor = idPEOPLE -join warehouse w on w.id = mov.warehouse_id -; - -end if; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `entradaCambioUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `entradaCambioUpdate`(IN vIdEntrada INT) -BEGIN - - DECLARE vMoneda INT; - - SELECT Id_Moneda INTO vMoneda FROM Entradas WHERE Id_Entrada = vIdEntrada; - - UPDATE Entradas - SET comision = getComision(vIdEntrada, vMoneda) - WHERE Id_Entrada = vIdEntrada; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `EntradasTriggerBeforeDelete` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `EntradasTriggerBeforeDelete`(oldTravel INT, oldId INT) -BEGIN - - DECLARE hasToRecalculate BOOLEAN; - DECLARE newWarehouse INT; - - SELECT Id_Compra INTO hasToRecalculate FROM Compres c - JOIN vn.lastBuy lb ON lb.id = c.Id_Compra - WHERE c.Id_Entrada = newId LIMIT 1; - IF hasToRecalculate THEN - SELECT warehouse_id INTO newWarehouse FROM travel WHERE id = oldTravel; - CALL vn.lastBuyRefresh(newWarehouse); - END IF; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `EntradasTriggerBeforeUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `EntradasTriggerBeforeUpdate`(oldTravel INT, newTravel INT, oldRedada BOOLEAN, - newRedada BOOLEAN, newId INT) -BEGIN - DECLARE newWarehouse INTEGER; - DECLARE hasToRecalculate BOOLEAN; - - IF oldRedada <> newRedada OR newTravel IS NULL THEN - - SELECT Id_Compra INTO hasToRecalculate FROM Compres c - JOIN vn.lastBuy lb ON lb.id = c.Id_Compra - WHERE c.Id_Entrada = newId LIMIT 1; - IF hasToRecalculate THEN - SELECT warehouse_id INTO newWarehouse FROM travel WHERE id = newtravel; - CALL vn.lastBuyRefresh(newWarehouse); - END IF; - END IF; - - IF newTravel <> oldTravel AND newTravel IS NOT NULL THEN - UPDATE travel t - JOIN Compres c ON c.Id_Entrada = newId - JOIN vn.lastBuy lb ON c.Id_Article = lb.item AND t.warehouse_id = lb.warehouse - SET lb.id = c.Id_Compra - WHERE t.id = newTravel AND t.landing BETWEEN date_inv() AND util.yesterday() - AND t.landing > lb.landing; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Entradas_Restar` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Entradas_Restar`(IN Id_Minuendo INT, IN Id_Sustraendo INT) -BEGIN - -UPDATE Compres c -JOIN -( - SELECT Id_Article, Cantidad - FROM Compres - WHERE Id_Entrada = Id_Sustraendo -) sub using(Id_Article) -SET c.Cantidad = c.Cantidad - sub.Cantidad -WHERE Id_Entrada = Id_Minuendo; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `entryComisionUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `entryComisionUpdate`(IN vIdEntrada INT) -BEGIN - - UPDATE Entradas - SET comision = getComision(vIdEntrada) - WHERE Id_Entrada = vIdEntrada; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `entryFromOrder` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `entryFromOrder`(IN vShipmentWarehouse INTEGER, IN vLandingWarehouse INTEGER, IN vItem INTEGER, - IN vAmount INTEGER,IN vVolume INTEGER,vCost DECIMAL(10,2), IN vRetailedPrice DECIMAL(10,2), vInOutDate DATE) -BEGIN - - DECLARE vTravel INT; - DECLARE vEntry INT; - DECLARE vBucket VARCHAR(10); - - -- seleccionamos travel - SELECT id, Id_Entrada INTO vTravel, vEntry - FROM travel t LEFT JOIN Entradas e ON t.id = e.travel_id - WHERE t.landing = vInOutDate AND t.shipment = vInOutDate AND t.warehouse_id_out = vShipmentWarehouse - AND t.warehouse_id = vLandingWarehouse AND agency_id = 15 - LIMIT 1; - - -- creamos el travel si es necesario - IF NOT IFNULL(vTravel,0) THEN - INSERT INTO travel (shipment, landing, warehouse_id, warehouse_id_out, agency_id) - VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse, 15); - SELECT LAST_INSERT_ID() INTO vTravel; - END IF; - -- creamos la Entrada si es necesario - IF NOT IFNULL(vEntry,0) THEN - INSERT INTO Entradas (Id_Proveedor, travel_id) - VALUES (13, vTravel); -- proveedor 'MOVIMIENTO ALMACEN' - SELECT LAST_INSERT_ID() INTO vEntry; - END IF; - - -- creamos el cubo si es necesario - SELECT Id_Cubo INTO vBucket FROM Cubos WHERE Volumen = vVolume LIMIT 1; - - IF NOT IFNULL(vBucket,'') > '' THEN - INSERT INTO Cubos (Id_Cubo, Volumen) - VALUES (CONCAT('dm',vVolume/1000), vVolume); - SELECT LAST_INSERT_ID() INTO vBucket; - END IF; - - INSERT INTO Compres(Id_Article,Cantidad, Id_Entrada, Id_Cubo, Packing, grouping, caja, Costefijo, Portefijo, Embalajefijo, - Comisionfija, Tarifa2, Tarifa3) - VALUES(vItem, - vAmount, - vEntry, - vBucket, - 1, - 1, - 0, - vCost, - 0, - 0, - 0, - vRetailedPrice, - vRetailedPrice); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `entryFromTicket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `entryFromTicket`(IN vTicket INTEGER, IN vLandingWarehouse INTEGER) -BEGIN - - DECLARE vShipmentWarehouse INT; - DECLARE vLandingDate DATE; - DECLARE vShipmentDate DATE; - DECLARE vTravel INT; - DECLARE vEntry INT; - - SELECT warehouse_id, Fecha, Fecha INTO vShipmentWarehouse, vShipmentDate, vLandingDate FROM Tickets WHERE Id_Ticket = vTicket; - - -- seleccionamos travel - SELECT id, Id_Entrada INTO vTravel, vEntry - FROM travel t LEFT JOIN Entradas e ON t.id = e.travel_id - WHERE t.landing = vLandingDate AND t.shipment = vShipmentDate AND t.warehouse_id_out = vShipmentWarehouse AND t.warehouse_id = vLandingWarehouse - AND agency_id = 15 - LIMIT 1; - - -- creamos el travel si es necesario - IF vTravel IS NULL THEN - select vLandingDate; - INSERT INTO travel (shipment, landing, warehouse_id, warehouse_id_out, agency_id) - VALUES (vShipmentDate, vLandingDate, vLandingWarehouse, vShipmentWarehouse, 15); - SELECT LAST_INSERT_ID() INTO vTravel; - END IF; - - -- creamos la Entrada si es necesario - IF vEntry IS NULL THEN - INSERT INTO Entradas (Id_Proveedor, travel_id) - VALUES (13, vTravel); -- proveedor 'MOVIMIENTO ALMACEN' - SELECT LAST_INSERT_ID() INTO vEntry; - END IF; - - CALL item_last_buy_(vShipmentWarehouse,vShipmentDate); - - INSERT INTO Compres(Id_Article,Cantidad, Id_Entrada, Id_Cubo, Packing, grouping, caja, Costefijo, Portefijo, Embalajefijo, - Comisionfija, Tarifa2, Tarifa3) - SELECT m.Id_Article, - m.Cantidad, - vEntry, - c.Id_Cubo, - c.Packing, - IF(c.grouping,c.grouping,1), - c.caja, - Costefijo, - c.Portefijo, - c.Embalajefijo, - c.Comisionfija, - m.Preu Tarifa2, - m.Preu Tarifa3 - FROM - Movimientos m - JOIN Articles a ON m.Id_Article = a.Id_Article - LEFT JOIN t_item_last_buy b ON m.Id_Article = b.item_id AND b.warehouse_id = vShipmentWarehouse - LEFT JOIN Compres c ON c.Id_Compra = b.buy_id - WHERE m.Id_Ticket = vTicket; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `entryUpdateComision` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `entryUpdateComision`(IN vIdEntrada INT) -BEGIN - - UPDATE Entradas - SET comision = getComision(vIdEntrada, Id_Moneda) - WHERE Id_Entrada = vIdEntrada; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `entryWithItem` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `entryWithItem`(IN vShipmentWarehouse INTEGER, IN vLandingWarehouse INTEGER, - IN vItem INTEGER, IN vAmount INTEGER,IN vVolume INTEGER, IN vGrossMargin DECIMAL(10,2), vInOutDate DATE) -BEGIN - - DECLARE vLandingWarehouse INT; - DECLARE vLandingDate DATE; - DECLARE vShipmentDate DATE; - DECLARE vTravel INT; - DECLARE vEntry INT; - DECLARE vBucket VARCHAR(10); - - -- seleccionamos travel - SELECT id, Id_Entrada INTO vTravel, vEntry - FROM travel t LEFT JOIN Entradas e ON t.id = e.travel_id - WHERE t.landing = vInOutDate AND t.shipment = vInOutDate AND t.warehouse_id_out = vShipmentWarehouse - AND t.warehouse_id = vLandingWarehouse AND agency_id = 15 - LIMIT 1; - - -- creamos el travel si es necesario - IF NOT vTravel THEN - INSERT INTO travel (shipment, landing, warehouse_id, warehouse_id_out, agency_id) - VALUES (vShipmentDate, vLandingDate, vLandingWarehouse, vLandingWarehouse, 15); - SELECT LAST_INSERT_ID() INTO vTravel; - END IF; - - -- creamos la Entrada si es necesario - IF NOT vEntry THEN - INSERT INTO Entradas (Id_Proveedor, travel_id) - VALUES (13, vTravel); -- proveedor 'MOVIMIENTO ALMACEN' - SELECT LAST_INSERT_ID() INTO vEntry; - END IF; - - -- creamos el cubo si es necesario - SELECT Id_Cubo INTO vBucket FROM Cubos WHERE Volumen = vVolume LIMIT 1; - IF vBucket IS NULL THEN - INSERT INTO Cubos (Id_Cubo, Volumen) - VALUES (CONCAT('dm',vVolume/1000), vVolume); - SELECT LAST_INSERT_ID() INTO vBucket; - END IF; - - INSERT INTO Compres(Id_Article,Cantidad, Id_Entrada, Id_Cubo, Packing, grouping, caja, Costefijo, Portefijo, Embalajefijo, - Comisionfija, Tarifa2, Tarifa3) - SELECT vItem, - vAmount, - vEntry, - vBucket, - 1 Packing, - 1 grouping, - 0 caja, - SUM(m.Preu), - 0 Portefijo, - 0 Embalajefijo, - 0 Comisionfija, - SUM(m.Preu) + vGrossMargin Tarifa2, - SUM(m.Preu) + vGrossMargin Tarifa3 - FROM - Movimientos m - WHERE m.Id_Ticket = vTicket; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `envios_masivos` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `envios_masivos`(IN idTICKET INT, IN IdCONSIGNA_DESDE INT, IN IdCONSIGNA_HASTA INT) -BEGIN - --- Se trata de clonar el ticket semilla para todos los consignatarios del rango, con los movimientos que contenga - --- Insertamos los tickets - -INSERT INTO Tickets(Id_Consigna, Id_Cliente, warehouse_id, Fecha, Alias, Tipo, Id_Trabajador, empresa_id, Id_Agencia) -SELECT c.Id_Consigna, t.Id_Cliente, t.warehouse_id, t.Fecha, c.Consignatario, t.Tipo, t.Id_Trabajador, t.empresa_id, t.Id_Agencia -FROM Tickets t -JOIN Consignatarios c -WHERE Id_Ticket = idTICKET -AND c.Id_Consigna BETWEEN IdCONSIGNA_DESDE AND IdCONSIGNA_HASTA; - - --- Insertamos los movimientos - -INSERT INTO Movimientos(Id_Article, Concepte, Cantidad, Preu, PrecioFijado, Id_Ticket) -SELECT Id_Article, Concepte, Cantidad, Preu, TRUE , t.Id_Ticket -FROM Tickets t -JOIN Movimientos m -WHERE m.Id_Ticket = idTICKET -AND t.Id_Consigna BETWEEN IdCONSIGNA_DESDE AND IdCONSIGNA_HASTA; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `etiqueta_sambori` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `etiqueta_sambori`(IN lngEXPEDITION BIGINT, IN intMODE INT, IN intH INT, IN intFILAS INT) -BEGIN - -DECLARE intCOLUMNAS INT; -DECLARE intBULTOS INT; -DECLARE intDESCARGAS INT; -DECLARE intRUTA INT; -DECLARE intPOSICIONES INT; - - - -SELECT Id_Ruta INTO intRUTA -FROM Tickets t -JOIN expeditions e on e.ticket_id = t.Id_Ticket -WHERE e.expeditions_id = lngEXPEDITION; - - -SELECT sum(Bultos) , count(*) , CEIL(SUM(CEIL(Bultos / intH)) / intFILAS), SUM(CEIL(Bultos / intH)) - INTO intBULTOS,intDESCARGAS, intCOLUMNAS, intPOSICIONES -from -( -SELECT Id_Consigna, sum(Bultos) Bultos -FROM Tickets -WHERE Id_Ruta = intRUTA -group by Id_Consigna -) sub; - - - - -IF intMODE <> 2 THEN - - SELECT - CONCAT( IF(posicion_min MOD intFILAS = 0, intFILAS, posicion_min MOD intFILAS) - , MID(' BCDEFG',CEIL(posicion_min /intFILAS),1) - , IF(posicion_min = posicion_max,'',' - ') - , IF(posicion_min = posicion_max,'',IF(posicion_max MOD intFILAS = 0, intFILAS, posicion_max MOD intFILAS)) - , IF(posicion_min = posicion_max,'',MID(' BCDEFG',CEIL(posicion_max /intFILAS),1)) - - ) sambori, - t.Prioridad, - t.Id_Consigna, - CONCAT(e.counter, ' / ', t.Bultos) count_bultos, - e.expeditions_id, - zone, - Matricula Vehiculo, - trab.CodigoTrabajador Chofer, - Rutas.Id_Ruta, - RIGHT(Rutas.Id_Ruta, 2) Id_RutaSTR, - t.Bultos TotalBultos, - RIGHT(e.expeditions_id,3) expeditions_IDSTR - FROM - expeditions e - JOIN - Tickets t ON e.ticket_id = t.Id_Ticket - JOIN - ( - select Prioridad, cast(@s - 1 as decimal(3,0)) as posicion_max, @s:= cast(@s - ubicaciones as decimal(3,0)) as posicion_min - from - ( - select t.Prioridad, sum(t.Bultos) as bultos, CEIL(sum(t.bultos) / intH) as ubicaciones, @s := intPOSICIONES + 1 - from Tickets t - where Id_Ruta = intRUTA - group by Prioridad) sub - - ) posiciones on posiciones.Prioridad = t.Prioridad - - JOIN - Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna - JOIN - province p USING (province_id) - JOIN - Rutas ON t.Id_Ruta = Rutas.Id_Ruta - left JOIN - Vehiculos veh USING (Id_vehiculo) - left JOIN - Trabajadores trab ON Rutas.Id_Trabajador = trab.Id_Trabajador - WHERE - expeditions_id = lngEXPEDITION; -ELSE - - - SELECT - CEIL((SUM(IF(t.Prioridad > t1.Prioridad, - t1.Bultos, - 0)) + e.Counter) / CEIL(SUM(t1.Bultos) / 13)) sambori, - t.Prioridad, - t.Id_Consigna, - CONCAT(e.counter, ' / ', t.Bultos) count_bultos, - e.expeditions_id, - zone, - Matricula Vehiculo, - trab.CodigoTrabajador Chofer, - Rutas.Id_Ruta, - RIGHT(Rutas.Id_Ruta, 2) Id_RutaSTR, - t.Bultos TotalBultos, - RIGHT(e.expeditions_id,3) expeditions_IDSTR - FROM - expeditions e - JOIN - Tickets t ON e.ticket_id = t.Id_Ticket - JOIN - Tickets t1 ON t.Id_Ruta = t1.Id_Ruta - JOIN - Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna - JOIN - province p USING (province_id) - JOIN - Rutas ON t1.Id_Ruta = Rutas.Id_Ruta - LEFT JOIN - Vehiculos veh USING (Id_vehiculo) - LEFT JOIN - Trabajadores trab ON Rutas.Id_Trabajador = trab.Id_Trabajador - WHERE - expeditions_id = lngEXPEDITION; -END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `etiqueta_sambori_2` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `etiqueta_sambori_2`(IN lngEXPEDITION BIGINT, IN intMODE INT, IN intH INT, IN intFILAS INT) -BEGIN - -DECLARE intCOLUMNAS INT; -DECLARE intBULTOS INT; -DECLARE intDESCARGAS INT; -DECLARE intRUTA INT; -DECLARE intPOSICIONES INT; - - - -SELECT Id_Ruta INTO intRUTA -FROM Tickets t -JOIN expeditions e on e.ticket_id = t.Id_Ticket -WHERE e.expeditions_id = lngEXPEDITION; - - -SELECT sum(Bultos) , count(*) , CEIL(SUM(CEIL(Bultos / intH)) / intFILAS), SUM(CEIL(Bultos / intH)) - INTO intBULTOS,intDESCARGAS, intCOLUMNAS, intPOSICIONES -from -( -SELECT Id_Consigna, sum(Bultos) Bultos -FROM Tickets -WHERE Id_Ruta = intRUTA -group by Id_Consigna -) sub; - - - - -IF intMODE <> 2 THEN - - SELECT - CONCAT( IF(posicion_min MOD intFILAS = 0, intFILAS, posicion_min MOD intFILAS) - , MID(' BCDEFG',CEIL(posicion_min /intFILAS),1) - , IF(posicion_min = posicion_max,'',' - ') - , IF(posicion_min = posicion_max,'',IF(posicion_max MOD intFILAS = 0, intFILAS, posicion_max MOD intFILAS)) - , IF(posicion_min = posicion_max,'',MID(' BCDEFG',CEIL(posicion_max /intFILAS),1)) - - ) sambori, - t.Prioridad, - t.Id_Consigna, - CONCAT(e.counter, ' / ', t.Bultos) count_bultos, - e.expeditions_id, - zone, - Matricula Vehiculo, - trab.CodigoTrabajador Chofer, - Rutas.Id_Ruta, - RIGHT(Rutas.Id_Ruta, 2) Id_RutaSTR - FROM - expeditions e - JOIN - Tickets t ON e.ticket_id = t.Id_Ticket - JOIN - ( - select Prioridad, cast(@s - 1 as decimal(3,0)) as posicion_max, @s:= cast(@s - ubicaciones as decimal(3,0)) as posicion_min - from - ( - select t.Prioridad, sum(t.Bultos) as bultos, CEIL(sum(t.bultos) / intH) as ubicaciones, @s := intPOSICIONES + 1 - from Tickets t - where Id_Ruta = intRUTA - group by Prioridad) sub - - ) posiciones on posiciones.Prioridad = t.Prioridad - - JOIN - Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna - JOIN - province p USING (province_id) - JOIN - Rutas ON t.Id_Ruta = Rutas.Id_Ruta - left JOIN - Vehiculos veh USING (Id_vehiculo) - left JOIN - Trabajadores trab ON Rutas.Id_Trabajador = trab.Id_Trabajador - WHERE - expeditions_id = lngEXPEDITION; -ELSE - - - SELECT - CEIL((SUM(IF(t.Prioridad > t1.Prioridad, - t1.Bultos, - 0)) + e.Counter) / CEIL(SUM(t1.Bultos) / 13)) sambori, - t.Prioridad, - t.Id_Consigna, - CONCAT(e.counter, ' / ', t.Bultos) count_bultos, - e.expeditions_id, - zone, - Matricula Vehiculo, - trab.CodigoTrabajador Chofer, - Rutas.Id_Ruta, - RIGHT(Rutas.Id_Ruta, 2) Id_RutaSTR - FROM - expeditions e - JOIN - Tickets t ON e.ticket_id = t.Id_Ticket - JOIN - Tickets t1 ON t.Id_Ruta = t1.Id_Ruta - JOIN - Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna - JOIN - province p USING (province_id) - JOIN - Rutas ON t1.Id_Ruta = Rutas.Id_Ruta - LEFT JOIN - Vehiculos veh USING (Id_vehiculo) - LEFT JOIN - Trabajadores trab ON Rutas.Id_Trabajador = trab.Id_Trabajador - WHERE - expeditions_id = lngEXPEDITION; -END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `eti_list` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `eti_list`(IN wh_in INT) -BEGIN - -SELECT warehouse.name AS Alm_Origen - , travel.shipment - , travel.shipment_hour AS ETD - , warehouse_1.name AS Alm_Destino - , travel.landing - ,travel.landing_hour AS ETA - , awb.codigo AS awb - , Entradas.Id_Entrada - , Sum(Compres.Etiquetas) AS bultos - , Agencias.Agencia - , producer.name AS producer - , Proveedores.Proveedor - , Sum(Compres.Vida) AS Impresas - , producer.producer_id - , IFNULL((Entradas.Confirmada AND length(Entradas.Notas) > 0),0) as Ready_to_print - FROM Compres - INNER JOIN Entradas ON Entradas.Id_Entrada = Compres.Id_Entrada - INNER JOIN travel ON Entradas.travel_id = travel.id - INNER JOIN warehouse AS warehouse_1 ON warehouse_1.id = travel.warehouse_id - INNER JOIN warehouse ON warehouse.id = travel.warehouse_id_out - INNER JOIN Agencias ON Agencias.Id_Agencia = travel.agency_id - LEFT JOIN recibida_entrada ON Entradas.Id_Entrada = recibida_entrada.Id_Entrada - LEFT JOIN awb_recibida ON recibida_entrada.awb_recibida = awb_recibida.recibida_id - LEFT JOIN awb ON awb_recibida.awb_id = awb.id - INNER JOIN Articles ON Compres.Id_Article = Articles.Id_Article - LEFT JOIN producer ON Articles.producer_id = producer.producer_id - INNER JOIN Proveedores ON Entradas.Id_Proveedor = Proveedores.Id_Proveedor - - - WHERE wh_in IN (travel.warehouse_id_out, travel.warehouse_id) - AND travel.landing Between TIMESTAMPADD(DAY,-7,CURDATE()) and TIMESTAMPADD(DAY,14,CURDATE()) - GROUP BY warehouse.name, travel.shipment, travel.shipment_hour - , warehouse_1.name, travel.landing, travel.landing_hour - , awb.codigo, Entradas.Id_Entrada, Agencias.Agencia - , producer.name, Proveedores.Proveedor - ORDER BY travel.landing DESC; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `eti_to_print` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `eti_to_print`(IN idENTRADA INT, IN idPRODUCER INT) -BEGIN - -select Vida as Impresas - ,Etiquetas as bultos - ,Packing - ,Id_Article - ,CONCAT(Article,' ',Medida,' ', Categoria) as Articat - ,p.name as marca - ,Proveedor - ,Id_Entrada - ,Id_Compra -from Compres c -join Entradas e using(Id_Entrada) -join Proveedores using(Id_Proveedor) -join travel tr on tr.id = e.travel_id -join Articles a using(Id_Article) -left join producer p using(producer_id) -where Id_Entrada = idENTRADA - and idPRODUCER in (0,a.producer_id) ; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `f10_no_vincular` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `f10_no_vincular`(lngEntrada INTEGER) - DETERMINISTIC -BEGIN - DECLARE datFecha DATE DEFAULT CURDATE(); - --- Modifica el NoVincular si hay dos entradas con el mismo Packing y el mismo Id_Articulo - DROP TEMPORARY TABLE IF EXISTS f10_no_vincular_; - CREATE TEMPORARY TABLE IF NOT EXISTS f10_no_vincular_ - SELECT c.Id_Entrada,c.Id_Compra,c.Id_Article, c.Novincular, c.Packing, be.pri - FROM Compres c - JOIN buy_edi be ON c.buy_edi_id = be.id AND be.fec = datFecha - LEFT JOIN Entradas_kop ek ON ek.Id_Entrada = c.Id_Entrada - WHERE - ((ek.Id_Entrada IS NOT NULL AND ek.sub IS NULL) - OR (c.Id_Entrada = 9200 AND be.ok <> FALSE) - OR c.Id_Entrada = lngEntrada) AND Id_Article <> 90; - - -- Modifica el NoVincular si hay dos entradas con el mismo Packing y el mismo Id_Articulo - DROP TEMPORARY TABLE IF EXISTS f10_mismo_Packing; - CREATE TEMPORARY TABLE IF NOT EXISTS f10_mismo_Packing - SELECT * FROM ( - SELECT * FROM f10_no_vincular_ - ORDER BY pri DESC) t - GROUP BY Id_Article,Packing - HAVING count(Id_Compra) > 1 AND BIT_OR(Id_Entrada = 9200); - - UPDATE Compres c - JOIN buy_edi be ON c.buy_edi_id = be.id AND be.fec = datFecha - JOIN f10_mismo_Packing f ON f.Id_Article = c.Id_Article AND c.Packing = f.Packing - LEFT JOIN Entradas_kop ek ON ek.Id_Entrada = f.Id_Entrada - SET c.Novincular = IF(c.Id_Compra = f.Id_Compra,0,1) - WHERE - ((ek.Id_Entrada IS NOT NULL AND ek.sub IS NULL) - OR (c.Id_Entrada = 9200 AND be.ok <> FALSE) - OR c.Id_Entrada = lngEntrada); - --- Modifica el Id_Articulo si hay dos entradas con packing y el mismo Id_Articulo - DROP TEMPORARY TABLE IF EXISTS f10_mismo_Articulo; - CREATE TEMPORARY TABLE IF NOT EXISTS f10_mismo_Articulo - SELECT Id_Article FROM ( - SELECT * FROM ( - SELECT * FROM f10_no_vincular_ - ORDER BY Id_Entrada = 9200 DESC) t - GROUP BY Id_Article,Packing ) t - GROUP BY Id_Article HAVING COUNT(*) > 1 AND BIT_OR(Id_Entrada = 9200); - SELECT 4; - UPDATE Compres c - JOIN buy_edi be ON c.buy_edi_id = be.id AND be.fec = datFecha - JOIN f10_mismo_Articulo f ON f.Id_Article = c.Id_Article - LEFT JOIN Entradas_kop ek ON ek.Id_Entrada = c.Id_Entrada - SET c.Id_Article = 90 - WHERE c.Id_Entrada = 9200 AND be.ok <> FALSE; - - DROP TEMPORARY TABLE IF EXISTS f10_no_vincular_; - DROP TEMPORARY TABLE IF EXISTS f10_mismo_Packing; - DROP TEMPORARY TABLE IF EXISTS f10_mismo_Articulo; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `F5` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `F5`(IN idT BIGINT) -BEGIN -SELECT C.calidad, - LEFT(Article, 4) as Subtipo, - barcode, - 'ASEGURADO' AS asegurado, -/*CASE A.tipo_id -WHEN 75 THEN IF(M.Id_Article IN (120,2388,20100,16,10,130,104851,1,56,238,104850,104849,2),'RAMAJE',R.Reino) -WHEN 68 THEN IF(M.Id_Article IN (11539,10,14),'RAMAJE',R.Reino) -WHEN 69 THEN IF(M.Id_Article IN (41),'RAMAJE',R.Reino) -WHEN 72 THEN IF(M.Id_Article IN (238),'RAMAJE',R.Reino) -WHEN 2 THEN 'CYMBIDIUMS & ANTHURIUMS' -WHEN 122 THEN 'CYMBIDIUMS & ANTHURIUMS' -WHEN 12 THEN 'CYMBIDIUMS & ANTHURIUMS' -WHEN 13 THEN 'CYMBIDIUMS & ANTHURIUMS' -WHEN 14 THEN 'CYMBIDIUMS & ANTHURIUMS' -WHEN 15 THEN 'CYMBIDIUMS & ANTHURIUMS' -WHEN 71 THEN IF(LEFT(Article,2) = 'HC','Flor',R.Reino) -WHEN 19 THEN IF(LEFT(Article,3) IN ('HEL','GIN'),'CYMBIDIUMS & ANTHURIUMS',R.Reino) -WHEN 70 THEN IF(Article like '%red beauty%' or Article like '%clarinervium%','CYMBIDIUMS & ANTHURIUMS',R.Reino) -WHEN 86 THEN 'Flor' -ELSE R.Reino -END as*/ Reino, - /* -CASE A.tipo_id -WHEN 75 THEN IF(M.Id_Article IN (120,2388,20100,16,10,130,104851,1,56,238,104850,104849,2),-1,R.orden) -WHEN 68 THEN IF(M.Id_Article IN (11539,10,14),-1,R.orden) -WHEN 69 THEN IF(M.Id_Article IN (41),-1,R.orden) -WHEN 72 THEN IF(M.Id_Article IN (238),-1,R.orden) -WHEN 2 THEN 0 -WHEN 122 THEN 0 -WHEN 12 THEN 0 -WHEN 13 THEN 0 -WHEN 14 THEN 0 -WHEN 15 THEN 0 -WHEN 71 THEN IF(LEFT(Article,2) = 'HC',1,R.orden) -WHEN 19 THEN IF(LEFT(Article,3) IN ('HEL','GIN'),0,R.orden) -WHEN 70 THEN IF(Article like '%red beauty%' or Article like '%clarinervium%',0,R.orden) -WHEN 86 THEN 1 -ELSE R.orden -END as*/ R.orden, - CS.Consignatario, - T.Id_Cliente, - T.Id_Trabajador, - T.Id_Ticket, - T.Fecha, - M.Id_Article, - M.Cantidad, - M.quantity, - M.Cantidad / IF(nz(Gro.Grouping) = 0,1,nz(Gro.Grouping)) as Paquetes, - M.Concepte, - A.Medida, - A.Color, - A.Categoria, - O.Abreviatura as Origen, - T.Localizacion, - CT.CodigoTrabajador as Vendedor, - T.Bultos, - T.Observaciones, - Ag.Agencia Tipo, - TR.CodigoTrabajador, - /*0 Seguro,*/ - M.OK, - M.Reservado, - A.Tallos, - Gro.Grouping, - IF(`transaction`,right(concat('000000' ,M.Id_Article),6),M.Id_Movimiento) Id_Movimiento, - an.Nicho, - 'PEDIDO ASEGURADO' AS MSG, - T.Id_Ruta, - RT.Id_Vehiculo, - observation_type_id, - group_concat(IF(observation_type_id = 1,text,'') SEPARATOR '') 'sacador', - group_concat(IF(observation_type_id = 2,text,'') SEPARATOR '') 'encajador', - A.Foto, - M.Id_Movimiento movement_id, - lpad(ifnull(cooler_path_detail_id, an.Nicho),5,'0') as path, - M.Descuento,M.Preu, mm.valor as Preparado, mm.original_quantity - , p.`name` producer, T.warehouse_id, CS.POBLACION -- JGF 2016-02-16 -FROM - - Tickets T - LEFT JOIN Movimientos M USING(Id_Ticket) - LEFT JOIN Articles A on A.Id_Article = M.Id_Article - LEFT JOIN Articles_nicho an ON A.Id_Article = an.Id_Article AND an.warehouse_id = T.warehouse_id - LEFT JOIN producer p on p.producer_id = A.producer_id -- JGF 2016-02-16 - LEFT JOIN cooler_path_detail c on left(an.Nicho,3) = pasillo - LEFT JOIN Origen O ON A.id_origen = O.id - LEFT JOIN Clientes C USING(Id_Cliente) - LEFT JOIN Trabajadores CT ON C.Id_Trabajador = CT.Id_Trabajador - LEFT JOIN Trabajadores TR ON TR.Id_Trabajador = T.Id_Trabajador - INNER JOIN Consignatarios CS ON T.Id_Consigna = CS.Id_Consigna - INNER JOIN Agencias Ag ON Ag.Id_Agencia = T.Id_Agencia - LEFT JOIN ( - SELECT Id_Article, code as barcode - FROM barcodes - GROUP BY Id_Article - ) BC ON BC.Id_Article = A.Id_Article - LEFT JOIN Tipos TP USING(tipo_id) - LEFT JOIN reinos R ON TP.reino_id = R.id - LEFT JOIN Rutas RT USING(Id_Ruta) - LEFT JOIN ticket_observation tobs ON T.Id_Ticket = tobs.Id_ticket - AND (tobs.observation_type_id = 1 or tobs.observation_type_id = 2) - - LEFT JOIN ( - SELECT Id_Article, Grouping - FROM ( - SELECT landing, Id_Article, CASE caja - WHEN 0 THEN 1 - WHEN 2 THEN Packing - ELSE Grouping - END as Grouping - FROM Compres C - JOIN Entradas E USING(Id_Entrada) - JOIN travel TR ON TR.id = travel_id - WHERE warehouse_id = (SELECT warehouse_id FROM Tickets WHERE Id_Ticket = idT) - AND landing between (SELECT FechaInventario FROM tblContadores LIMIT 1) AND (SELECT date(Fecha) FROM Tickets WHERE Id_Ticket = idT) - ORDER BY landing DESC - ) GR1 - GROUP BY Id_Article - - ) Gro ON Gro.Id_Article = M.Id_Article - LEFT JOIN Movimientos_mark mm ON mm.Id_Movimiento = M.Id_Movimiento - - WHERE T.Id_Ticket = idT group by M.Id_Movimiento; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `F5_entrada` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `F5_entrada`(IN idE BIGINT) -BEGIN - - -SELECT - NULL AS Sacador, - NULL AS Encajador, - v.Cantidad / v.Packing AS Paquetes, - v.Packing AS Grouping, - barcode, - 'ASEGURADO' AS asegurado, - reino, - r.orden, - Alias AS Consignatario, - v.Id_Proveedor AS Id_Cliente, - v.Pedida, - v.Confirmada, - NULL AS vendedor, - 10 AS Calidad, - LPAD(IFNULL(cooler_path_detail_id, an.Nicho), - 5, - '0') AS path, - TB.Id_Trabajador, - v.Id_Entrada AS Id_Ticket, - landing AS Fecha, - v.Id_Article, - v.Cantidad, - v.article AS Concepte, - v.Medida, - v.Color, - v.Categoria, - Abreviatura AS Origen, - NULL AS Localizacion, - 0 AS Bultos, - w.`name` AS Tipo, - CodigoTrabajador, - 0 AS OK, - 0 AS Reservado, - v.Tallos, - v.Id_Compra AS Id_Movimiento, - an.Nicho, - 'PEDIDO ASEGURADO' AS MSG, - 0 AS Seguro, - 0 AS Id_Ruta, - 0 AS Id_Vehiculo, - a.Foto, - pr.name as producer -FROM - v_compres v - LEFT JOIN - Articles_nicho an ON v.Id_Article = an.Id_Article AND an.warehouse_id = v.warehouse_id_out - JOIN - warehouse w ON w.id = v.warehouse_id - LEFT JOIN - Tipos USING (tipo_id) - LEFT JOIN - reinos r ON r.id = Tipos.reino_id - LEFT JOIN - Trabajadores TB ON TB.Id_Trabajador = v.Id_Trabajador - LEFT JOIN - Proveedores p ON p.Id_Proveedor = v.Id_Proveedor - LEFT JOIN - (SELECT - Id_Article, code AS barcode - FROM - barcodes - GROUP BY Id_Article) BC ON BC.Id_Article = v.Id_Article - LEFT JOIN - Articles a ON a.Id_Article = v.Id_Article - LEFT JOIN - producer pr on pr.producer_id = a.producer_id - LEFT JOIN - cooler_path_detail c ON LEFT(v.Nicho, 3) = pasillo - LEFT JOIN - Origen o ON o.id = v.Id_origen -WHERE - v.Id_Entrada = idE - AND v.tipo_id IS NOT NULL - AND v.reino_id <> 8 - ; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `F5_entradakk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `F5_entradakk`(IN idE BIGINT) -BEGIN - - -SELECT - NULL AS Sacador, - NULL AS Encajador, - v.Cantidad / v.Packing AS Paquetes, - v.Packing AS Grouping, - barcode, - 'ASEGURADO' AS asegurado, - reino, - r.orden, - Alias AS Consignatario, - v.Id_Proveedor AS Id_Cliente, - v.Pedida, - v.Confirmada, - NULL AS vendedor, - 10 AS Calidad, - LPAD(IFNULL(cooler_path_detail_id, an.Nicho), - 5, - '0') AS path, - TB.Id_Trabajador, - v.Id_Entrada AS Id_Ticket, - landing AS Fecha, - v.Id_Article, - v.Cantidad, - v.article AS Concepte, - v.Medida, - v.Color, - v.Categoria, - Abreviatura AS Origen, - NULL AS Localizacion, - 0 AS Bultos, - w.`name` AS Tipo, - CodigoTrabajador, - 0 AS OK, - 0 AS Reservado, - v.Tallos, - v.Id_Compra AS Id_Movimiento, - an.Nicho, - 'PEDIDO ASEGURADO' AS MSG, - 0 AS Seguro, - 0 AS Id_Ruta, - 0 AS Id_Vehiculo, - a.Foto, - pr.name as producer -FROM - v_compres v - LEFT JOIN - Articles_nicho an ON v.Id_Article = an.Id_Article AND an.warehouse_id = v.warehouse_id_out - JOIN - warehouse w ON w.id = v.warehouse_id - LEFT JOIN - Tipos USING (tipo_id) - LEFT JOIN - reinos r ON r.id = Tipos.reino_id - LEFT JOIN - Trabajadores TB ON TB.Id_Trabajador = v.Id_Trabajador - LEFT JOIN - Proveedores p ON p.Id_Proveedor = v.Id_Proveedor - LEFT JOIN - (SELECT - Id_Article, code AS barcode - FROM - barcodes - GROUP BY Id_Article) BC ON BC.Id_Article = v.Id_Article - LEFT JOIN - Articles a ON a.Id_Article = v.Id_Article - LEFT JOIN - producer pr on pr.producer_id = a.producer_id - LEFT JOIN - cooler_path_detail c ON LEFT(v.Nicho, 3) = pasillo - LEFT JOIN - Origen o ON o.id = v.Id_origen -WHERE - v.Id_Entrada = idE - AND v.tipo_id IS NOT NULL - AND v.tipo_id <> 77 - ; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Facturas_Saltos` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Facturas_Saltos`(IN datSTART DATE , IN datEND DATE) -BEGIN - - -DECLARE strSER1 VARCHAR(2); -DECLARE strSER2 VARCHAR(2); -DECLARE intEMP1 INT; -DECLARE intEMP2 INT; -DECLARE v_done BOOLEAN DEFAULT FALSE; -DECLARE strFAC1 VARCHAR(11); -DECLARE strFAC2 VARCHAR(11); - - -DECLARE rs CURSOR FOR - SELECT Id_Factura, empresa_id, Serie - FROM Facturas - WHERE Fecha BETWEEN datSTART AND datEND - ORDER BY empresa_id, Serie, Id_Factura; - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_done = TRUE; - -OPEN rs; - -DROP TEMPORARY TABLE IF EXISTS Facturas_Saltarinas; - -CREATE TEMPORARY TABLE Facturas_Saltarinas -(Factura_Inicial VARCHAR(11), - Factura_Final VARCHAR(11), - Empresa VARCHAR(3), - Serie VARCHAR(1)); - -FETCH rs INTO strFAC1, intEMP1, strSER1; - -IF NOT v_done THEN - - FETCH rs INTO strFAC2, intEMP2, strSER2; - -END IF; - -WHILE NOT v_done DO - - IF strSER1 = strSER2 AND intEMP1 = intEMP2 AND right(strFAC2,5) - right(strFAC1,5) > 1 then - - INSERT INTO Facturas_Saltarinas(Factura_Inicial, Factura_Final, Empresa, Serie) - SELECT strFAC1, strFAC2, abbreviation, strSER1 - FROM empresa - WHERE id = intEMP1; - - END IF; - - SET strFAC1 = strFAC2; - SET intEMP1 = intEMP2; - SET STRSER1 = strSER2; - - FETCH rs INTO strFAC2, intEMP2, strSER2; - -END WHILE; - -SELECT * FROM Facturas_Saltarinas; - -CLOSE rs; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Factura_vuelve` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Factura_vuelve`(IN strFactura VARCHAR(10), IN intCLI INT ) -BEGIN - -DECLARE dblIMPORTE DOUBLE; -DECLARE datFEC DATE; -DECLARE intEMP INT; -DECLARE intCLI_OLD INT; - -/*Este procedure no funcionara correctament perque el strFactura ha de fer referencia al factura_id*/ -SELECT Importe, Fecha, empresa_id, Id_Cliente -INTO dblIMPORTE, datFEC, intEMP, intCLI_OLD -FROM Facturas WHERE Id_Factura = strFactura; - --- Cambia la empresa de la factura - -UPDATE Facturas SET empresa_id = 965, Id_Cliente = intCLI WHERE Id_Factura = strFactura; - --- Cambia la empresa de los tickets - -UPDATE Tickets SET empresa_id = 965, Id_Cliente = intCLI WHERE Factura = strFactura; - - --- Descuenta la cantidad del cliente antiguo - -INSERT INTO Recibos(Id_Factura - ,Entregado - ,Fechacobro - ,Id_Trabajador - ,Id_Banco - ,Id_Cliente - ,empresa_id) - -VALUES (strFactura - ,-1 * dblIMPORTE - ,datFEC - ,2 - ,430 - ,intCLI_OLD - ,intEMP); - --- Carga el cobro en la cuenta del nuevo cliente - -INSERT INTO Recibos(Id_Factura - ,Entregado - ,Fechacobro - ,Id_Trabajador - ,Id_Banco - ,Id_Cliente - ,empresa_id) - -VALUES (strFactura - ,dblIMPORTE - ,datFEC - ,2 - ,430 - ,intCLI - ,965); - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `fv_to_pcakk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `fv_to_pcakk`() -BEGIN - -DECLARE idT INT; - -DECLARE idC INT; -DECLARE newFEC DATE; -DECLARE idEMP INT; -DECLARE idCON INT; -DECLARE intTIPO INT; -DECLARE newTICKET INT; -DECLARE newLANDING DATE; - -SELECT DISTINCT Id_Ticket INTO idT -FROM Movimientos m -JOIN Tickets t using(Id_Ticket) -JOIN Articles a using(Id_Article) -WHERE tipo_id = 19 AND Article like 'HEL %' -AND Fecha between '2015-10-22' and '2015-10-31' -AND warehouse_id =1 LIMIT 1; - -WHILE idT IS NOT NULL DO - - SELECT Id_Cliente,Fecha,empresa_id,Id_Consigna,Id_Agencia , landing - INTO idC , newFEC, idEMP , idCON , intTIPO , newLANDING - FROM Tickets - WHERE Id_Ticket = idT; - - CALL `ticket_new_complet`(idC ,newFEC, 44, 20, idEMP , idCON , intTIPO , NULL , newTICKET); - - UPDATE Movimientos - JOIN Articles a using(Id_Article) - SET Id_Ticket = newTICKET - WHERE tipo_id = 19 AND Article like 'HEL %' - AND Id_Ticket = idT; - - INSERT INTO order_Tickets (Id_Ticket, order_id) - SELECT newTICKET, order_id - FROM order_Tickets - WHERE Id_Ticket = idT; - - UPDATE Tickets - SET landing = newLANDING - WHERE Id_Ticket = newTICKET; - -SET idT = NULL; - -SELECT DISTINCT Id_Ticket INTO idT -FROM Movimientos m -JOIN Tickets t using(Id_Ticket) -JOIN Articles a using(Id_Article) -WHERE tipo_id = 19 AND Article like 'HEL %' -AND Fecha between '2015-10-22' and '2015-10-31' -AND warehouse_id =1 LIMIT 1; - -END WHILE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `gescartera_Estados` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `gescartera_Estados`(IN intAno INT,IN intMes INT,IN intDiasPerdidos INT) -BEGIN -DECLARE intCLI,intCLI2 INT DEFAULT 0; -DECLARE datFEC,datFEC2,auxdatFEC DATE DEFAULT '2001-01-01'; -DECLARE lngTIC, lngTIC2 BIGINT DEFAULT 0; -DECLARE intDiferencia INT DEFAULT 0; # Variable donde se colocará la diferencia de días entre dos fechas. -DECLARE done,EsPerdido bit DEFAULT 0; -DECLARE intEstado TINYINT(2) DEFAULT 0; -DECLARE intNuevo INT DEFAULT 1; -DECLARE intPerdido INT DEFAULT 2; -DECLARE intRecuperado INT DEFAULT 3; - - -# Añado una fecha de fin para que no tenga en cuenta los tickets del futuro. (and Fecha<=current_date()) -/* -DECLARE cursor1 CURSOR FOR SELECT Id_Ticket,ti.Id_Cliente,date_format(Fecha,'%Y-%m-%d') AS FormatoFecha -FROM vn2008.Tickets ti -WHERE DATE_FORMAT(Fecha,'%Y-%m-%d')>CAST(CONCAT(YEAR(CURDATE())-2,'-','01-01')AS DATE) -AND DATE_FORMAT(Fecha,'%Y-%m-%d')<=LAST_DAY(CAST(CONCAT(intAno, '-' , intMes,'-',01) AS DATE)) -ORDER BY ti.Id_Cliente,Fecha; -*/ -DECLARE cursor1 CURSOR FOR SELECT Id_Ticket,fac.Id_Cliente,date_format(Fecha,'%Y-%m-%d') AS FormatoFecha -FROM Facturas fac -JOIN (SELECT Id_Ticket,Id_Cliente,Factura from Tickets ti where Factura is not null order by Fecha DESC,Id_Ticket DESC) sub1 -on fac.Id_Factura=sub1.Factura -WHERE DATE_FORMAT(Fecha,'%Y-%m-%d')>CAST(CONCAT(YEAR(CURDATE())-2,'-','01-01')AS DATE) -AND DATE_FORMAT(Fecha,'%Y-%m-%d')<=LAST_DAY(CAST(CONCAT(intAno, '-' , intMes,'-',01) AS DATE)) -group by Id_Cliente,Fecha -order by sub1.Id_Cliente,FormatoFecha; - -DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1; -DECLARE CONTINUE HANDLER FOR 1146 -BEGIN - -DROP TEMPORARY TABLE IF EXISTS GC; - -CREATE TEMPORARY TABLE GC (Id_Ticket BIGINT,Fecha DATE,Id_Cliente int,Estado SMALLINT) ENGINE=MEMORY; - -OPEN cursor1; - FETCH cursor1 INTO lngtIC,intCLI,datFEC; - # el primero registro es un cliente nuevo. - INSERT INTO GC(Id_Ticket, Fecha, Id_Cliente, Estado) VALUES(lngtIC,datFEC, intCLI,intNuevo); - SET auxdatFEC=datFEC; - - WHILE NOT DONE DO - FETCH cursor1 INTO lngtIC2,intCLI2,datFEC2; - CASE - WHEN DONE THEN SET intDiferencia=DATEDIFF(CURRENT_DATE,datFEC2); - WHEN intCLI=intCLI2 THEN - SET intDiferencia=DATEDIFF(datFEC2,datFEC); - IF ((intEstado=2)) THEN -- es recuperado despues de haberse perdido - INSERT INTO GC(Id_Ticket, Fecha, Id_Cliente, Estado) VALUES (lngtIC2,datFEC2, intCLI,intRecuperado); # RECUPERADO - SET intEstado=1; - SET auxdatFEC=datFEC2; - ELSE - IF (intDiferencia >= intDiasPerdidos) THEN - -- IF (DATE_FORMAT(datFEC2,'%Y-%m')<>DATE_FORMAT(DATE_ADD(datFEC,INTERVAL intDiasPerdidos DAY),'%Y-%m')) AND (intEstado<2) THEN - INSERT INTO GC(Id_Ticket, Fecha, Id_Cliente, Estado) VALUES (0,DATE_ADD(auxdatFEC,INTERVAL intDiasPerdidos DAY), intCLI,intPerdido); - INSERT INTO GC(Id_Ticket, Fecha, Id_Cliente, Estado) VALUES (lngtIC2,datFEC2, intCLI,intRecuperado); # RECUPERADO - SET intEstado=1,auxdatFEC=datFEC2; - -- ELSE - -- INSERT INTO GC(Id_Ticket, Fecha, Id_Cliente, Estado) VALUES (lngtIC2,datFEC2, intCLI,intPerdido); # PERDIDO - -- SET intEstado=2; # Lo marcamos como perdido - -- END IF; - - END IF; - END IF; - WHEN intCLI<>intCLI2 THEN - SET intEstado=0; - SET intDiferencia=DATEDIFF(CURRENT_DATE,datFEC); - INSERT INTO GC(Id_Ticket, Fecha, Id_Cliente, Estado) VALUES(lngtIC2,datFEC2, intCLI2,intNuevo); # NUEVO - SET auxdatFEC=datFEC2; - END CASE; - SET datFEC=datFEC2; - SET intCLI=intCLI2; - SET lngTIC = lngTIC2,auxdatFEC=datFEC2; - - END WHILE; - - CLOSE cursor1; - - - # inserto los registros de clientes sin ticket (Estado 4) - INSERT GC - SELECT 0,'2000-01-01',Id_Cliente,4 - FROM vn2008.Clientes - WHERE Id_Cliente NOT IN - (select distinct Id_Cliente - FROM vn2008.Tickets order by id_cliente); - - SELECT Id_Ticket, Fecha, Id_Cliente, CASE ESTADO - WHEN 1 THEN 'NUEVO' - WHEN 2 THEN 'PERDIDO' - WHEN 3 THEN 'RECUPERADO' - ELSE 'SIN TICKET' END AS Estado,CodigoTrabajador - FROM GC - INNER JOIN vn2008.Clientes cli USING (Id_Cliente) - INNER JOIN vn2008.Trabajadores trab USING (Id_Trabajador); - -END; - - IF EXISTS (SELECT * FROM GC LIMIT 1) THEN - - SELECT Id_Ticket, Fecha, Id_Cliente, CASE ESTADO - WHEN 1 THEN 'NUEVO' - WHEN 2 THEN 'PERDIDO' - WHEN 3 THEN 'RECUPERADO' - ELSE 'SIN TICKET' END AS Estado,CodigoTrabajador - FROM GC - INNER JOIN vn2008.Clientes cli USING (Id_Cliente) - INNER JOIN vn2008.Trabajadores trab USING (Id_Trabajador); - - END IF; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `get_barcodes_ticket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `get_barcodes_ticket`(IN idT BIGINT) -BEGIN - - drop temporary TABLE IF EXISTS articles_ticket; - CREATE TEMPORARY TABLE IF NOT EXISTS articles_ticket - (PRIMARY KEY (Id_Article)) - ENGINE = MEMORY - select distinct Id_Article from Movimientos where Id_Ticket = idT; - - drop temporary TABLE IF EXISTS articles_ticket2; - CREATE TEMPORARY TABLE IF NOT EXISTS articles_ticket2 - (PRIMARY KEY (Id_Article)) - ENGINE = MEMORY - select * from articles_ticket; - - drop temporary TABLE IF EXISTS articles_buys; - CREATE TEMPORARY TABLE IF NOT EXISTS articles_buys AS - select Id_Compra, a.Id_Article from v_compres c JOIN articles_ticket a ON a.Id_Article = c.Id_Article - where landing >= DATE_SUB(CURDATE(), INTERVAL 14 DAY); - - SELECT distinct - code, a.Id_Article - FROM - barcodes b - inner join - articles_ticket a ON a.Id_Article = b.Id_Article - union - SELECT - Id_Compra as code, a.Id_Article - FROM - articles_buys c - inner join - articles_ticket2 a ON a.Id_Article = c.Id_Article; - - drop temporary TABLE IF EXISTS articles_ticket; - drop temporary TABLE IF EXISTS articles_ticket2; - drop temporary TABLE IF EXISTS articles_buys; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `historico` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `historico`(IN idART INT, IN wh INT, IN v_virtual INT) -BEGIN -DECLARE datFEC DATETIME; - -SELECT Fechainventario INTO datFEC FROM tblContadores; -SET @a = 0; -SELECT DATE(Fecha) AS Fecha, - Entrada, - Salida, - OK, - Alias, - Referencia, - id, - @a := @a + IFNULL(Entrada,0) - IFNULL(Salida,0) as acumulado, - F5, - v_virtual, - Calidad,CodigoTrabajador -FROM - - ( SELECT TR.landing as Fecha, - C.Cantidad as Entrada, - NULL as Salida, - (TR.received != FALSE) as OK, - P.Proveedor as Alias, - E.Referencia as Referencia, - E.Id_Entrada as id, - TR.delivered as F5, - 0 as Calidad, tra.CodigoTrabajador - FROM Compres C - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON TR.id = E.travel_id - JOIN Proveedores P USING (Id_Proveedor) - LEFT JOIN Articles a ON a.Id_Article = C.Id_Article - LEFT JOIN Tipos ti ON ti.Id_Tipo = a.tipo_id - LEFT JOIN Trabajadores tra ON tra.Id_Trabajador = ti.Id_Trabajador - WHERE TR.landing >= datFEC - AND wh IN (TR.warehouse_id , 0) - AND C.Id_Article = idART - AND E.Inventario = 0 - - UNION ALL - - SELECT TR.shipment as Fecha, - NULL as Entrada, - C.Cantidad as Salida, - TR.delivered as OK, - P.Proveedor as Alias, - E.Referencia as Referencia, - E.Id_Entrada as id, - TR.delivered as F5, - 0 as Calidad, tra.CodigoTrabajador - - FROM Compres C - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON TR.id = E.travel_id - JOIN warehouse ON warehouse.id = TR.warehouse_id_out - JOIN Proveedores P USING (Id_Proveedor) - LEFT JOIN Articles a ON a.Id_Article = C.Id_Article - LEFT JOIN Tipos ti ON ti.Id_Tipo = a.tipo_id - LEFT JOIN Trabajadores tra ON tra.Id_Trabajador = ti.Id_Trabajador - WHERE TR.shipment >= datFEC - AND wh IN (TR.warehouse_id_out,0) - AND Id_Proveedor <> 4 - AND C.Id_Article = idART - AND E.Inventario = 0 - AND fuente = 0 - - UNION ALL - - SELECT T.Fecha as Fecha, - NULL as Entrada, - M.Cantidad as Salida, - (IFNULL(ts.alertLevel,0) > 1 OR ok ) as OK, - T.Alias as Alias, - T.Localizacion as Referencia, - T.Id_Ticket as id, - FALSE EtiquetasEmitidas, - C.Calidad, tr.CodigoTrabajador - - FROM Movimientos M - JOIN Tickets T USING (Id_Ticket) - LEFT JOIN vn.ticketState ts ON ts.ticket = T.Id_Ticket - JOIN Clientes C ON C.Id_Cliente = T.Id_Cliente - LEFT JOIN Trabajadores tr ON tr.Id_Trabajador = C.Id_Trabajador - WHERE T.Fecha >= datFEC - AND M.Id_Article = idART - AND wh IN (T.warehouse_id , 0) - - ) AS Historico -ORDER BY Fecha, OK DESC, Entrada DESC; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `historicokk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `historicokk`(IN idART INT, IN wh INT, IN v_virtual INT) -BEGIN -DECLARE datFEC DATETIME; - -SELECT Fechainventario INTO datFEC FROM tblContadores; -SET @a = 0; -SELECT DATE(Fecha) AS Fecha, - Entrada, - Salida, - OK, - Alias, - Referencia, - id, - @a := @a + IFNULL(Entrada,0) - IFNULL(Salida,0) as acumulado, - F5, - v_virtual, - Calidad,CodigoTrabajador -FROM - - ( SELECT TR.landing as Fecha, - C.Cantidad as Entrada, - NULL as Salida, - (TR.received != FALSE) as OK, - P.Proveedor as Alias, - E.Referencia as Referencia, - E.Id_Entrada as id, - TR.delivered as F5, - 0 as Calidad, tra.CodigoTrabajador - FROM Compres C - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON TR.id = E.travel_id - JOIN Proveedores P USING (Id_Proveedor) - LEFT JOIN Articles a ON a.Id_Article = C.Id_Article - LEFT JOIN Tipos ti ON ti.Id_Tipo = a.tipo_id - LEFT JOIN Trabajadores tra ON tra.Id_Trabajador = ti.Id_Trabajador - WHERE TR.landing >= datFEC - AND wh IN (TR.warehouse_id , 0) - AND C.Id_Article = idART - AND E.Inventario = 0 - - UNION ALL - - SELECT TR.shipment as Fecha, - NULL as Entrada, - C.Cantidad as Salida, - TR.delivered as OK, - P.Proveedor as Alias, - E.Referencia as Referencia, - E.Id_Entrada as id, - TR.delivered as F5, - 0 as Calidad, tra.CodigoTrabajador - - FROM Compres C - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON TR.id = E.travel_id - JOIN warehouse ON warehouse.id = TR.warehouse_id_out - JOIN Proveedores P USING (Id_Proveedor) - LEFT JOIN Articles a ON a.Id_Article = C.Id_Article - LEFT JOIN Tipos ti ON ti.Id_Tipo = a.tipo_id - LEFT JOIN Trabajadores tra ON tra.Id_Trabajador = ti.Id_Trabajador - WHERE TR.shipment >= datFEC - AND wh IN (TR.warehouse_id_out,0) - AND Id_Proveedor <> 4 - AND C.Id_Article = idART - AND E.Inventario = 0 - AND fuente = 0 - - UNION ALL - - SELECT T.Fecha as Fecha, - NULL as Entrada, - M.Cantidad as Salida, - (IFNULL(ts.alertLevel,0) > 0) as OK, - T.Alias as Alias, - T.Localizacion as Referencia, - T.Id_Ticket as id, - T.PedidoImpreso EtiquetasEmitidas, - C.Calidad, tr.CodigoTrabajador - - FROM Movimientos M - JOIN Tickets T USING (Id_Ticket) - LEFT JOIN vn.ticketState ts ON ts.ticket = T.Id_Ticket - JOIN Clientes C ON C.Id_Cliente = T.Id_Cliente - LEFT JOIN Trabajadores tr ON tr.Id_Trabajador = C.Id_Trabajador - WHERE T.Fecha >= datFEC - AND M.Id_Article = idART - AND wh IN (T.warehouse_id , 0) - - ) AS Historico -ORDER BY Fecha, OK DESC, Entrada DESC; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `historicoprecio` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `historicoprecio`( id_art INT, id_wh INT,id_datestart DATE,id_dateend DATE) -BEGIN - - - SET @@max_sp_recursion_depth = 100 ; - DROP TEMPORARY TABLE IF EXISTS historicoprecio; - - CREATE TEMPORARY TABLE historicoprecio - ( - date_start DATE, - rate_0 DOUBLE, - rate_1 DOUBLE, - rate_2 DOUBLE, - rate_3 DOUBLE, - PRIMARY KEY (date_start) - ) - ENGINE = MEMORY; - - - CALL historicoprecio2 (id_art,id_wh,id_datestart,id_dateend); - - - SET @a:= @b:= @c:= @d:= @e:= @f := @g:= @h:=0.0; - SELECT * FROM - (SELECT d.`date` landing,if(rate_0 IS NULL,@a,@a:=rate_0) Costefijo,if(rate_1 IS NULL,@b,@b:=rate_1) rate_1, - if(rate_2 IS NULL,@c,@c:=rate_2) rate_2,if(rate_3 IS NULL,@d,@d:=rate_3) rate_3,'PF' tipo FROM `time` d - LEFT JOIN historicoprecio hp ON d.`date` = hp.date_start WHERE d.`date` BETWEEN id_datestart AND id_dateend - UNION ALL - SELECT DISTINCT d.`date` ,if(Costefijo IS NULL,@e,@e:=Costefijo) Costefijo,if(Tarifa1 IS NULL,@f,@f:=Tarifa1), - if(Tarifa2 IS NULL,@g,@g:=Tarifa2),if(Tarifa3 IS NULL,@h,@h:=Tarifa3),'C' - FROM `time` d - LEFT JOIN travel t ON t.landing = d.`date` - LEFT JOIN Entradas e ON e.travel_id = t.id - LEFT JOIN Compres c ON c.Id_Entrada = e.Id_Entrada AND id_wh IN (0,warehouse_id) AND c.Id_Article = id_art AND NoVincular = FALSE - WHERE d.`date` BETWEEN id_datestart AND id_dateend - ) - t ORDER BY landing DESC; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `historicoprecio2` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `historicoprecio2`( id_art INT, id_wh INT,id_datestart DATE,id_dateend DATE) -BEGIN - DECLARE done BIT DEFAULT 0; - DECLARE datini,datfin,datiniaux,datfinaux DATE; - DECLARE dblrate0,dblrate0aux,dblrate1,dblrate1aux,dblrate2,dblrate2aux,dblrate3,dblrate3aux DOUBLE DEFAULT 0; - DECLARE boolBeforeStart TINYINT DEFAULT 1; - -- selecciona el primer bloque apartir de la mínima fecha que esta dentro del rango y la fecha de finalizar es posterior - SET datiniaux = NULL; - SET datfinaux = NULL; - -- guarda en dblrate0aux el valor del valor del periode, a lo millor falla si no trau cap linea - SELECT IFNULL(rate_0,0), IFNULL(rate_1,0), IFNULL(rate_2,0), IFNULL(rate_3,0) - INTO dblrate0aux,dblrate1aux,dblrate2aux,dblrate3aux FROM price_fixed - WHERE date_start = id_datestart AND warehouse_id IN (0,id_wh) AND item_id = id_art; - - REPEAT - - SET datini = NULL; - SET datfin = NULL; - SET dblrate0 = NULL; - SET dblrate1 = NULL; - SET dblrate2 = NULL; - SET dblrate3 = NULL; - SELECT date_start,date_end,rate_0,rate_1,rate_2,rate_3 INTO datini,datfin,dblrate0,dblrate1,dblrate2,dblrate3 FROM price_fixed - WHERE item_id = id_art AND warehouse_id IN (0,id_wh) AND date_end < id_dateend - AND date_end >= IFNULL(datfinaux,id_datestart) AND date_start = (SELECT MIN(date_start) FROM price_fixed - WHERE date_start >= IFNULL(datiniaux,TIMESTAMPADD(DAY,1,id_datestart)) AND item_id = id_art AND warehouse_id IN (0,id_wh) ) - ORDER BY date_start LIMIT 1; - - IF datini IS NOT NULL THEN - -- Inserta un registre(dia -1) - IF boolBeforeStart THEN - INSERT INTO historicoprecio(date_start,rate_0,rate_1,rate_2,rate_3) - VALUES(TIMESTAMPADD(DAY,-1,datini),dblrate0aux,dblrate1aux,dblrate2aux,dblrate3aux); - SET boolBeforeStart = TRUE; - END IF; - -- reiniciem els valors de les variables - SET datiniaux = NULL; - SET datfinaux = NULL; - -- seleccionem el dia fins al qual dura el periode eliminant els dies que queden solapats - SELECT MIN(date_start) INTO datfinaux FROM price_fixed WHERE date_start > datini AND date_start < datfin AND date_end >= datfin - AND warehouse_id IN (0,id_wh) AND item_id = id_art; - - -- cridada recursiva per al periode(retallat si cal) inclós - CALL historicoprecio2 (id_art,id_wh,datini,IFNULL(datfinaux,datfin)); - -- anyadeix el valor que ha d'agafar el dia seguent d'acabar el periode actual. - IF datfinaux IS NULL THEN - INSERT INTO historicoprecio(date_start,rate_0,rate_1,rate_2,rate_3) - VALUES(TIMESTAMPADD(DAY,1,datfin),dblrate0aux,dblrate1aux,dblrate2aux,dblrate3aux), - (datfin,dblrate0,dblrate1,dblrate2,dblrate3); - ELSE - INSERT INTO historicoprecio(date_start,rate_0,rate_1,rate_2,rate_3) - VALUES(TIMESTAMPADD(DAY,-1,datfinaux),dblrate0,dblrate1,dblrate2,dblrate3); - SET boolBeforeStart = FALSE; - END IF; - SET datiniaux=TIMESTAMPADD(DAY,1,datini); - SET datfinaux=datfin; - - END IF; - UNTIL datini IS NULL END REPEAT; - -- inserta linea caso base - INSERT INTO historicoprecio(date_start,rate_0,rate_1,rate_2,rate_3) VALUES(id_datestart,dblrate0aux,dblrate1aux,dblrate2aux,dblrate3aux) - ON DUPLICATE KEY UPDATE rate_0 = dblrate0,rate_1 = dblrate1,rate_2 = dblrate2,rate_3 = dblrate3; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `historico_absoluto` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `historico_absoluto`(IN idART INT, IN wh INT, IN datfecha DATETIME) -BEGIN - -DECLARE inv_calculado INT; -DECLARE inv INT; -DECLARE today DATETIME; -DECLARE fecha_inv DATETIME; -SET today = curdate(); - - DROP TEMPORARY TABLE IF EXISTS historico_pasado; - CREATE TEMPORARY TABLE historico_pasado - SELECT * - FROM ( - SELECT TR.landing as Fecha, - C.Cantidad as Entrada, - NULL as Salida, - (TR.received != FALSE) as OK, - P.Proveedor as Alias, - E.Referencia as Referencia, - E.Id_Entrada as id, - TR.delivered as F5, 0 as Calidad - FROM Compres C -- mirar perque no entra en received - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN Proveedores P USING (Id_Proveedor) - WHERE TR.landing >= '2001-01-01' - AND Id_proveedor <> 4 - AND wh IN (TR.warehouse_id , 0) - AND C.Id_Article = idART - AND E.Inventario = 0 - - UNION ALL - - SELECT TR.shipment as Fecha, - NULL as Entrada, - C.Cantidad as Salida, - TR.delivered as OK, - P.Proveedor as Alias, - E.Referencia as Referencia, - E.Id_Entrada as id, - TR.delivered as F5, 0 as Calidad - FROM Compres C - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN Proveedores P USING (Id_Proveedor) - - WHERE TR.shipment >= '2001-01-01' - AND wh = TR.warehouse_id_out - AND Id_Proveedor <> 4 - AND C.Id_Article = idART - AND E.Inventario = 0 - - UNION ALL - - SELECT T.Fecha as Fecha, - NULL as Entrada, - M.Cantidad as Salida, - (M.OK <> 0 OR T.Etiquetasemitidas <> 0 OR T.Factura IS NOT NULL) as OK, - T.Alias as Alias, - T.Factura as Referencia, - T.Id_Ticket,T.PedidoImpreso, - C.Calidad - FROM Movimientos M - INNER JOIN Tickets T USING (Id_Ticket) - JOIN Clientes C ON C.Id_Cliente = T.Id_Cliente - WHERE T.Fecha >= '2001-01-01' - AND M.Id_Article = idART - AND wh IN (T.warehouse_id , 0) - ) as t1 ORDER BY Fecha, Entrada DESC, OK DESC; - - SELECT sum(Entrada) - sum(Salida) INTO inv_calculado - FROM historico_pasado - WHERE Fecha < datfecha; - - -- WHERE historico_pasado.Fecha < fecha_inv ; - - -SELECT p1.*, NULL as v_virtual FROM( - SELECT datfecha as Fecha,inv_calculado as Entrada, NULL as Salida,1 as OK, - 'Inventario calculado' as Alias, '' as Referencia, 0 as id, 1 as F5, 0 as Calidad - UNION ALL - SELECT * FROM historico_pasado WHERE Fecha >= datfecha - )as p1; - - -DROP TEMPORARY TABLE historico_pasado; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `historico_joined` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `historico_joined`(IN idART INT, IN wh_joined INT, IN v_virtual INT) -BEGIN -DECLARE datFEC DATETIME; - -SELECT Fechainventario INTO datFEC FROM tblContadores; -SET @a = 0; -SELECT DATE(Fecha) AS Fecha, - Entrada, - Salida, - OK, - Alias, - Referencia, - id, - @a := @a + IFNULL(Entrada,0) - IFNULL(Salida,0) as acumulado, - F5, - v_virtual, - Calidad,CodigoTrabajador -FROM - - ( SELECT TR.landing as Fecha, - C.Cantidad as Entrada, - NULL as Salida, - (TR.received != FALSE) as OK, - P.Proveedor as Alias, - E.Referencia as Referencia, - E.Id_Entrada as id, - TR.delivered as F5, - 0 as Calidad, tra.CodigoTrabajador - FROM Compres C - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON TR.id = E.travel_id - JOIN Proveedores P USING (Id_Proveedor) - LEFT JOIN Articles a ON a.Id_Article = C.Id_Article - LEFT JOIN Tipos ti ON ti.Id_Tipo = a.tipo_id - LEFT JOIN Trabajadores tra ON tra.Id_Trabajador = ti.Id_Trabajador - LEFT JOIN warehouse_joined wj ON wj.warehouse_id = TR.warehouse_id - WHERE TR.landing >= datFEC - AND wh_joined IN (wj.warehouse_alias_id , 0) - AND C.Id_Article = idART - AND E.Inventario = 0 - - UNION ALL - - SELECT TR.shipment as Fecha, - NULL as Entrada, - C.Cantidad as Salida, - TR.delivered as OK, - P.Proveedor as Alias, - E.Referencia as Referencia, - E.Id_Entrada as id, - TR.delivered as F5, - 0 as Calidad, tra.CodigoTrabajador - - FROM Compres C - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON TR.id = E.travel_id - JOIN Proveedores P USING (Id_Proveedor) - LEFT JOIN Articles a ON a.Id_Article = C.Id_Article - LEFT JOIN Tipos ti ON ti.Id_Tipo = a.tipo_id - LEFT JOIN Trabajadores tra ON tra.Id_Trabajador = ti.Id_Trabajador - LEFT JOIN warehouse_joined wj ON wj.warehouse_id = TR.warehouse_id_out - WHERE TR.shipment >= datFEC - AND wh_joined IN (wj.warehouse_alias_id,0) - AND Id_Proveedor <> 4 - AND C.Id_Article = idART - AND E.Inventario = 0 - - UNION ALL - - SELECT T.Fecha as Fecha, - NULL as Entrada, - M.Cantidad as Salida, - (M.OK <> 0 OR T.Etiquetasemitidas <> 0 OR T.Factura IS NOT NULL) as OK, - T.Alias as Alias, - T.Localizacion as Referencia, - T.Id_Ticket as id, - T.PedidoImpreso EtiquetasEmitidas, - C.Calidad, tr.CodigoTrabajador - - FROM Movimientos M - JOIN Tickets T USING (Id_Ticket) - JOIN Clientes C ON C.Id_Cliente = T.Id_Cliente - LEFT JOIN Trabajadores tr ON tr.Id_Trabajador = C.Id_Trabajador - LEFT JOIN warehouse_joined wj ON wj.warehouse_id = T.warehouse_id - WHERE T.Fecha >= datFEC - AND M.Id_Article = idART - AND wh_joined IN (wj.warehouse_alias_id , 0) - - ) AS Historico -ORDER BY Fecha, Entrada DESC, OK DESC; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `historico_multiple` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `historico_multiple`(IN idART INT) -BEGIN - -DECLARE datFEC DATETIME; - -SELECT Fechainventario INTO datFEC FROM tblContadores; - -SET @a = 0; - -DROP TEMPORARY TABLE IF EXISTS hm1; - -CREATE TEMPORARY TABLE hm1 -SELECT DATE(Fecha) as Fecha, - Entrada, - Salida, - OK, - Referencia, - Historia.id, - - wh, - - `name` as wh_name - -FROM - - ( SELECT TR.landing as Fecha, - C.Cantidad as Entrada, - NULL as Salida, - - IF(warehouse_id = 44, 1, warehouse_id) as wh, - (TR.received != FALSE) as OK, - E.Referencia as Referencia, - E.Id_Entrada as id - - - - FROM Compres C - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - WHERE TR.landing >= datFEC - AND C.Id_Article = idART - AND E.Redada = 0 - - AND C.Cantidad <> 0 - - UNION ALL - - SELECT TR.shipment as Fecha, - NULL as Entrada, - C.Cantidad as Salida, - - - IF(warehouse_id_out = 44, 1, warehouse_id_out) as wh, - TR.delivered as OK, - - E.Referencia as Referencia, - E.Id_Entrada as id - - FROM Compres C - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - WHERE TR.shipment >= datFEC - AND C.Id_Article = idART - - AND E.Redada = 0 - - AND C.Cantidad <> 0 - - UNION ALL - - SELECT T.Fecha as Fecha, - NULL as Entrada, - M.Cantidad as Salida, - IF(warehouse_id = 44, 1, warehouse_id) as wh, - - (M.OK <> 0 OR T.Etiquetasemitidas <> 0 OR T.Factura IS NOT NULL) as OK, - T.Factura as Referencia, - T.Id_Ticket as id - - FROM Movimientos M - INNER JOIN Tickets T USING (Id_Ticket) - WHERE T.Fecha >= datFEC - AND M.Id_Article = idART - - ) AS Historia - - INNER JOIN warehouse ON warehouse.id = Historia.wh -ORDER BY Fecha, Entrada DESC, OK DESC; - - -DROP TEMPORARY TABLE IF EXISTS hm2; -DROP TEMPORARY TABLE IF EXISTS hm3; -DROP TEMPORARY TABLE IF EXISTS hm4; -DROP TEMPORARY TABLE IF EXISTS hm5; -DROP TEMPORARY TABLE IF EXISTS hm6; -DROP TEMPORARY TABLE IF EXISTS hm7; -DROP TEMPORARY TABLE IF EXISTS hm8; -CREATE TEMPORARY TABLE hm2 SELECT * FROM hm1 WHERE wh = 19; -CREATE TEMPORARY TABLE hm3 SELECT * FROM hm1 WHERE wh = 7; -CREATE TEMPORARY TABLE hm4 SELECT * FROM hm1 WHERE wh = 1 or wh = 44; -CREATE TEMPORARY TABLE hm5 SELECT * FROM hm1 WHERE wh = 5; -CREATE TEMPORARY TABLE hm6 SELECT * FROM hm1 WHERE wh = 17; -CREATE TEMPORARY TABLE hm7 SELECT * FROM hm1 WHERE wh = 37; -CREATE TEMPORARY TABLE hm8 SELECT * FROM hm1 WHERE wh = 55; - -SELECT * FROM - -( - -SELECT Fecha, Entrada as BOGEntrada, Salida as BOGSalida, OK as BOGOK, Referencia as BOGReferencia, id as BOGid, - - NULL AS VNHEntrada, NULL AS VNHSalida, NULL AS VNHOK, NULL AS VNHReferencia, NULL AS VNHid, - - NULL AS SILEntrada, NULL AS SILSalida, NULL AS SILOK, NULL AS SILReferencia, NULL AS SILid, - - NULL AS MADEntrada, NULL AS MADSalida, NULL AS MADOK, NULL AS MADReferencia, NULL AS MADid, - - NULL AS MCFEntrada, NULL AS MCFSalida, NULL AS MCFOK, NULL AS MCFReferencia, NULL AS MCFid, - - NULL AS VILEntrada, NULL AS VILSalida, NULL AS VILOK, NULL AS VILReferencia, NULL AS VILid, - - NULL AS BAREntrada, NULL AS BARSalida, NULL AS BAROK, NULL AS BARReferencia, NULL AS BARid - -FROM hm2 - - -UNION ALL - -SELECT Fecha - , NULL, NULL, NULL, NULL, NULL - ,Entrada, Salida, OK, Referencia, id - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL -FROM hm3 - - - -UNION ALL - -SELECT Fecha - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , Entrada, Salida, OK, Referencia, id - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL -FROM hm4 - -UNION ALL - -SELECT Fecha - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , Entrada, Salida, OK, Referencia, id - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL -FROM hm5 - -UNION ALL - -SELECT Fecha - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , Entrada, Salida, OK, Referencia, id - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL -FROM hm6 - -UNION ALL - -SELECT Fecha - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , Entrada, Salida, OK, Referencia, id - , NULL, NULL, NULL, NULL, NULL - - -FROM hm7 - -UNION ALL - -SELECT Fecha - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , NULL, NULL, NULL, NULL, NULL - , Entrada, Salida, OK, Referencia, id - -FROM hm8 - -) sub - -ORDER BY Fecha, BOGEntrada IS NULL, VNHEntrada IS NULL, SILEntrada IS NULL, MADEntrada IS NULL, MCFEntrada IS NULL, VILEntrada IS NULL, BAREntrada IS NULL; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ImporteSantos` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ImporteSantos`(IN dat_from date,IN dat_to date) -BEGIN - -select codigotrabajador,Id_Cliente,Cliente,cast(sum(ImporteAnt) as decimal(10,0)) ImporteAnt,cast(sum(ImporteActual) as decimal(10,0)) ImporteActual -from ( - select codigotrabajador,cli.Id_Cliente Id_Cliente,Cliente,sum(amount) ImporteAnt,0 ImporteActual - from bi.ticket ti - inner join Clientes cli on ti.Id_Cliente=cli.Id_Cliente - inner join vn2008.Trabajadores on cli.Id_Trabajador=Trabajadores.Id_Trabajador - where (date between date_add(dat_from,interval -1 year) and date_add(dat_to,interval -1 year)) - -- and cli.invoice - group by CodigoTrabajador,ti.Id_Cliente - - union all -select CodigoTrabajador,cli.Id_Cliente,Cliente,0 ImporteAnt, - IFNULL(round(sum(cantidad * Costfixat),2),2) ImporteActual - from Tickets ti - inner join Movimientos m using (Id_Ticket) - INNER JOIN vn2008.Articles a USING(Id_Article) - INNER JOIN Tipos tp ON tp.tipo_id = a.tipo_id - LEFT JOIN reinos r ON r.id = tp.reino_id - INNER JOIN vn2008.Consignatarios c USING(Id_Consigna) - inner join Clientes cli on c.Id_Cliente=cli.Id_cliente - inner join vn2008.Trabajadores on cli.Id_Trabajador=Trabajadores.Id_Trabajador - inner join vn2008.Permisos perm on cli.Id_Trabajador=perm.Id_Trabajador - inner join vn2008.Grupos grup on perm.Id_Grupo=grup.Id - where ti.Fecha between dat_from and DAYEND(dat_to) - -- and cli.invoice - AND r.display <> 0 - and (grup.Id in (6) or cli.Id_Trabajador in (20)) - group by CodigoTrabajador,c.Id_Cliente,year(Fecha) -)sub1 -group by CodigoTrabajador,Id_Cliente -having (ImporteAnt<>0 or ImporteActual<>0) -order by CodigoTrabajador,Id_Cliente; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `InsertarEspionaje` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `InsertarEspionaje`(intIdTrabajador INT(11),intIdEquipo int) -BEGIN - -DECLARE intNReg TINYINT DEFAULT 0; - -SELECT Count(*) AS NReg -INTO intNReg -FROM Espionajes -WHERE Fecha=Current_date -AND Id_Trabajador=intIdTrabajador; - -IF (intNReg=0) THEN - INSERT INTO Espionajes (Id_Trabajador,Fecha,HoraEntrada,Id_Equipo) - VALUES (intIdTrabajador,CURRENT_DATE,CURRENT_TIME,intIdEquipo); -ELSE - UPDATE Espionajes - SET HoraSalida=CURRENT_TIME - WHERE Id_Trabajador=intIdTrabajador - AND Fecha=curdate(); -END IF; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `insert_producer_plantpassport` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `insert_producer_plantpassport`(IN idCompra INT) -BEGIN - DECLARE last_insert INTEGER; - - INSERT IGNORE INTO producer (`name`) - SELECT es.company_name - FROM vn2008.Compres c - JOIN vn2008.buy_edi be ON be.id = c.buy_edi_id - JOIN edi.supplier es ON es.supplier_id = be.pro - WHERE c.Id_Compra = idCompra; - - -- SELECT LAST_INSERT_ID() INTO last_insert; - - /* - IF last_insert > 0 THEN - UPDATE Articles a JOIN Compres c - ON a.Id_Article = c.Id_Article SET a.producer_id = last_insert WHERE c.Id_Compra = idCompra; - END IF;*/ -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `inventario_margen` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `inventario_margen`(IN d_START DATETIME, IN d_END DATETIME, IN i_tipo INT, IN i_filtro INT, IN i_wh INT) -BEGIN - - DECLARE d_INV DATETIME; - DECLARE bolREVERSE BOOLEAN DEFAULT 0; - DECLARE d_FEC2 DATETIME; - DECLARE d_FEC DATETIME; - DECLARE i_SECTOR INT DEFAULT 0; - DECLARE strFILTRO VARCHAR(255) DEFAULT 'TRUE'; - DECLARE dblPORTE_m3 DOUBLE DEFAULT 45; - DECLARE intCASE INTEGER; - DECLARE ID_CLIENTE_COMPLEMENTOS INT DEFAULT 1927; - DECLARE ID_REINO_OTROS INT DEFAULT 6; - DECLARE ID_PROVEEDOR_INVENTARIO INT DEFAULT 4; - DECLARE ID_TRABAJADOR_MARIBEL INT DEFAULT 133; - - IF i_filtro THEN - SELECT `sql` INTO strFILTRO FROM filtros WHERE id = i_filtro; - END IF; - - - --- PREVIO: Crear una tabla para filtrar los articulos que interesan - - DROP TEMPORARY TABLE IF EXISTS article_selection; - - SET strFILTRO = REPLACE(strFILTRO, 'Id_Article','A.Id_Article'); - - CALL util.exec (sql_printf( - 'CREATE TEMPORARY TABLE vn2008.article_selection - ENGINE = MEMORY - SELECT A.Id_Article - FROM vn2008.Articles A - LEFT JOIN vn2008.Tipos t USING(tipo_id) - LEFT JOIN vn2008.Trabajadores TR ON TR.Id_Trabajador = t.Id_Trabajador - LEFT JOIN vn2008.Tintas tn ON A.color = tn.Id_Tinta - LEFT JOIN vn2008.Origen o ON o.id = A.id_origen - WHERE %s AND %s AND reino_id != %v' - ,IF(i_tipo, CONCAT('tipo_id = ', i_tipo), 'TRUE') - ,strFILTRO - ,ID_REINO_OTROS - )); - - -ALTER TABLE article_selection ADD PRIMARY KEY(Id_Article); - - --- PRIMER PASO: Cálculo del inventario inicial, valorado - --- Averiguamos la fecha del inventario inmediatemente anterior a la fecha de inicio - - SELECT landing INTO d_INV - FROM travel TR - INNER JOIN Entradas E ON E.travel_id = TR.id - WHERE landing <= d_START - AND E.Id_Proveedor = ID_PROVEEDOR_INVENTARIO - AND i_wh IN (0,TR.warehouse_id) - ORDER BY landing DESC - LIMIT 1; - - IF d_INV is null THEN - - SELECT landing INTO d_INV - FROM travel TR - INNER JOIN Entradas E ON E.travel_id = TR.id - WHERE landing > d_START - AND E.Id_Proveedor = ID_PROVEEDOR_INVENTARIO - AND i_wh IN (0,TR.warehouse_id) - ORDER BY landing ASC - LIMIT 1; - - END IF; - - --- Ubicamos la fecha de inventario segun su posición relativa a la de inicio y a la de fin - -IF d_INV <= d_START THEN - - SET intCASE = 1; - -ELSE - - IF d_INV > d_END THEN - - SET intCASE = 3; - - ELSE - - SET intCASE = 2; - - END IF; - -END IF; - -DROP TEMPORARY TABLE IF EXISTS inv; - --- Preparamos la tabla temporal que va a almacenar el valor y cantidad de productos - -CREATE TEMPORARY TABLE inv - (w_id SMALLINT, - Id_Article BIGINT, - Unidades INT, - Valor DOUBLE, - Sector INT DEFAULT 0 ) ENGINE = MEMORY; - - -ALTER TABLE inv ADD PRIMARY KEY USING HASH (w_id, Id_Article, Sector); - -/************************** SECTOR INICIAL: 0 *****************************/ - -CASE intCASE - - WHEN 1 THEN - - SET d_FEC = TIMESTAMP(d_INV,'00:00:00'); - SET d_FEC2 = TIMESTAMP(TIMESTAMPADD(DAY,-1,d_START) ,'23:59:59'); - SET bolREVERSE = FALSE; - - ELSE - - SET d_FEC = TIMESTAMP(d_START,'00:00:00'); - SET d_FEC2 = TIMESTAMP(TIMESTAMPADD(DAY,-1,d_INV) ,'23:59:59'); - SET bolREVERSE = TRUE; - - -END CASE; - - --- Inicializamos el inventario - - - INSERT INTO inv(w_id, Id_Article, Unidades,Valor) - SELECT TR.warehouse_id, C.Id_Article, sum(C.Cantidad), ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0) - FROM Compres C - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos TP USING(tipo_id) - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN warehouse w ON w.id = warehouse_id - JOIN article_selection USING(Id_Article) - WHERE landing = d_INV - AND w.comisionantes - AND i_wh IN (0,TR.warehouse_id) - AND E.Id_Proveedor = ID_PROVEEDOR_INVENTARIO - AND reino_id != ID_REINO_OTROS - AND TR.warehouse_id != TR.warehouse_id_out - GROUP BY TR.warehouse_id, C.Id_Article; - --- Se insertan las compras que llegan entre la fecha del inventario y la fecha inicial - - INSERT INTO inv(w_id, Id_Article, Unidades, Valor) - SELECT TR.warehouse_id, C.Id_Article, C.Cantidad * IF(bolREVERSE,-1,1), ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0) - FROM Compres C - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos TP USING(tipo_id) - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN warehouse w ON w.id = warehouse_id - JOIN article_selection USING(Id_Article) - WHERE landing BETWEEN d_FEC AND d_FEC2 - AND i_wh IN (0,TR.warehouse_id) - AND w.comisionantes - AND NOT redada - AND reino_id != ID_REINO_OTROS - AND E.Id_Proveedor != ID_PROVEEDOR_INVENTARIO - AND TR.warehouse_id != TR.warehouse_id_out - ORDER BY landing DESC - ON DUPLICATE KEY UPDATE inv.Unidades = inv.Unidades + (C.Cantidad * IF(bolREVERSE,-1,1)) - , Valor = IF(Costefijo > 0,ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0),Valor); - --- Se sacan las que salen - - INSERT INTO inv(w_id, Id_Article, Unidades) - SELECT TR.warehouse_id_out, C.Id_Article, C.Cantidad * IF(bolREVERSE,1,-1) - FROM Compres C - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos TP USING(tipo_id) - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN warehouse w ON w.id = warehouse_id_out - JOIN article_selection USING(Id_Article) - WHERE shipment BETWEEN d_FEC AND d_FEC2 - AND i_wh IN (0,TR.warehouse_id_out) - AND w.comisionantes - AND NOT redada - AND reino_id != ID_REINO_OTROS - AND E.Id_Proveedor != ID_PROVEEDOR_INVENTARIO - AND TR.warehouse_id != TR.warehouse_id_out - ON DUPLICATE KEY UPDATE inv.Unidades = inv.Unidades + (C.Cantidad * IF(bolREVERSE,1,-1)); - --- Ahora las ventas - - INSERT INTO inv(w_id, Id_Article, Unidades) - SELECT w.id, M.Id_Article, M.Cantidad * IF(bolREVERSE,1,-1) - FROM Movimientos M - INNER JOIN Tickets T USING (Id_Ticket) - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos TP USING(tipo_id) - INNER JOIN warehouse w ON w.id = T.warehouse_id - INNER JOIN article_selection USING(Id_Article) - WHERE T.Fecha BETWEEN d_FEC AND d_FEC2 - AND i_wh IN (0,T.warehouse_id) - AND w.comisionantes - AND reino_id != ID_REINO_OTROS - ON DUPLICATE KEY UPDATE inv.Unidades = inv.Unidades + (M.Cantidad * IF(bolREVERSE,1,-1)); - - -UPDATE inv SET Valor = inv.Unidades * Valor; - - -/************************** SECTOR ENTRADAS: 1 *****************************/ - -SET i_SECTOR = 1; - - - SET d_FEC = TIMESTAMP(d_START,'00:00:00'); - SET d_FEC2 = TIMESTAMP(d_END ,'23:59:59'); - - - --- Ahora vamos a incrementar en unidades y valor el producto recibido en el rango de fechas del procedimiento - - INSERT INTO inv(Sector, w_id, Id_Article, Unidades, Valor) - SELECT i_SECTOR, TR.warehouse_id, C.Id_Article, sum(C.Cantidad ) - , sum(C.Cantidad * (nz(Costefijo)+nz(Embalajefijo)+nz(Portefijo)+nz(Comisionfija)) ) - FROM Compres C - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos TP USING(tipo_id) - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN warehouse w ON w.id = warehouse_id - JOIN article_selection USING(Id_Article) - WHERE landing BETWEEN d_FEC AND d_FEC2 - AND i_wh IN (0,TR.warehouse_id) - AND w.comisionantes - AND NOT redada - AND E.Id_Proveedor != ID_PROVEEDOR_INVENTARIO - AND reino_id != ID_REINO_OTROS - AND TR.warehouse_id != TR.warehouse_id_out - GROUP BY TR.warehouse_id, C.Id_Article; - - - - -/************************** SECTOR SALIDAS: 2 *****************************/ - -SET i_SECTOR = 2; - --- Ahora vamos a restar en unidades y valor el producto que sale de los almacenes en el rango de fechas del procedimiento - - INSERT INTO inv(Sector, w_id, Id_Article, Unidades, Valor) - SELECT i_SECTOR, TR.warehouse_id_out, C.Id_Article, sum( -1 * C.Cantidad ) - , sum( -1 * C.Cantidad * (nz(Costefijo) + nz(Embalajefijo) )) - FROM Compres C - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos TP USING(tipo_id) - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN warehouse w ON w.id = warehouse_id_out - JOIN article_selection USING(Id_Article) - WHERE shipment BETWEEN d_FEC AND d_FEC2 - AND i_wh IN (0,TR.warehouse_id_out) - AND w.comisionantes - AND NOT redada - AND E.Id_Proveedor != ID_PROVEEDOR_INVENTARIO - AND reino_id != ID_REINO_OTROS - AND TR.warehouse_id != TR.warehouse_id_out - GROUP BY TR.warehouse_id_out, C.Id_Article ; - - - -/******************** SECTOR VENTAS: 3 **************************************/ - -SET i_SECTOR = 3; - - -DROP TEMPORARY TABLE IF EXISTS Cub; - CREATE TEMPORARY TABLE Cub - SELECT * FROM (SELECT * FROM bi.last_Id_Cubo order by Id_Compra desc) sub group by Id_Article, warehouse_id; - - ALTER TABLE Cub ADD PRIMARY KEY USING HASH (Id_Article, warehouse_id); - - - - -IF d_START >= '2015-10-01' THEN - - INSERT INTO inv(Sector, w_id, Id_Article, Unidades, Valor) - - - SELECT i_SECTOR - , w.id - , M.Id_Article - , sum(-1 * M.Cantidad ) as Unidades - , sum(-1 * IF(T.Id_Cliente IN (200,400),0,1) * IFNULL(bsv.importe,0)) as Valor - FROM Movimientos M - LEFT JOIN bs.ventas bsv on bsv.Id_Movimiento = M.Id_Movimiento - INNER JOIN Tickets T USING (Id_Ticket) - INNER JOIN Articles A ON A.Id_Article = M.Id_Article - INNER JOIN Tipos TP on TP.tipo_id = A.tipo_id - INNER JOIN warehouse w ON w.id = T.warehouse_id - JOIN article_selection `AS` ON `AS`.Id_Article = M.Id_Article - WHERE T.Fecha BETWEEN d_FEC AND d_FEC2 - AND i_wh IN (0,T.warehouse_id) - AND w.comisionantes - AND reino_id != ID_REINO_OTROS - /* - AND ( - T.Id_Cliente != ID_CLIENTE_COMPLEMENTOS - OR - TP.Id_Trabajador != ID_TRABAJADOR_MARIBEL - ) - */ - GROUP BY T.warehouse_id, Id_Article; - - - - -ELSE - - - - INSERT INTO inv(Sector, w_id, Id_Article, Unidades, Valor) - - - SELECT i_SECTOR, w.id, M.Id_Article, sum(-1 * M.Cantidad ) - , - - sum( -1 - * M.Cantidad - * IF(CS.Id_Cliente IN (200,400),0,1) - * IF( - T.Fecha >= '2015-10-01' - , M.CostFixat - , ( - ( M.Preu - * (100 - M.Descuento) - / 100 - ) - - IF(C.Descuento = 1 and T.Bultos > 0 and Fecha > '2013-07-01', - IFNULL( dblPORTE_m3 * (cm3_2(CB.Id_Cubo, CB.Id_Article) / 1000000) / CB.Packing ,0 ) - ,0) - ) - ) - - ) as Preu - - FROM Movimientos M - INNER JOIN Tickets T USING (Id_Ticket) - LEFT JOIN Cub CB ON CB.Id_Article = M.Id_Article AND T.warehouse_id = CB.warehouse_id - INNER JOIN Consignatarios CS USING(Id_Consigna) - INNER JOIN Clientes C ON C.Id_Cliente = CS.Id_Cliente - INNER JOIN Articles A ON A.Id_Article = M.Id_Article - INNER JOIN Tipos TP USING(tipo_id) - INNER JOIN warehouse w ON w.id = T.warehouse_id - JOIN article_selection `AS` ON `AS`.Id_Article = M.Id_Article - WHERE T.Fecha BETWEEN d_FEC AND d_FEC2 - AND i_wh IN (0,T.warehouse_id) - AND w.comisionantes - AND reino_id != ID_REINO_OTROS - /* - AND ( - T.Id_Cliente != ID_CLIENTE_COMPLEMENTOS - OR - TP.Id_Trabajador != ID_TRABAJADOR_MARIBEL - ) - */ - GROUP BY T.warehouse_id, Id_Article; - - -END IF; - - -- Ventas del año anterior - - DROP TEMPORARY TABLE IF EXISTS Ventas_Lastyear; - - CREATE TEMPORARY TABLE Ventas_Lastyear - SELECT CodigoTrabajador, TP.Id_Tipo, - - sum(M.Cantidad - * IF(CS.Id_Cliente IN (200,400),0,1) - * IF( - T.Fecha >= '2015-10-01' - , M.CostFixat - , ( - ( M.Preu - * (100 - M.Descuento) - / 100 - ) - - IF(C.Descuento = 1 and T.Bultos > 0 and Fecha > '2013-07-01', - IFNULL( dblPORTE_m3 * (cm3_2(CB.Id_Cubo, CB.Id_Article) / 1000000) / CB.Packing ,0 ) - ,0) - ) - ) - - ) as Importe - FROM Movimientos M - INNER JOIN Tickets T USING (Id_Ticket) - LEFT JOIN Cub CB ON CB.Id_Article = M.Id_Article AND T.warehouse_id = CB.warehouse_id - INNER JOIN Consignatarios CS USING(Id_Consigna) - INNER JOIN Clientes C ON C.Id_Cliente = CS.Id_Cliente - INNER JOIN Articles A ON A.Id_Article = M.Id_Article - INNER JOIN Tipos TP USING(tipo_id) - INNER JOIN Trabajadores TR ON TP.Id_Trabajador = TR.Id_Trabajador - INNER JOIN warehouse w ON w.id = T.warehouse_id - JOIN article_selection `AS` ON `AS`.Id_Article = M.Id_Article - WHERE T.Fecha BETWEEN TIMESTAMPADD(YEAR,-1,d_FEC) AND TIMESTAMPADD(YEAR,-1,d_FEC2) - AND i_wh IN (0,T.warehouse_id) - AND w.comisionantes - AND reino_id != ID_REINO_OTROS - /* - AND ( - T.Id_Cliente != ID_CLIENTE_COMPLEMENTOS - OR - TP.Id_Trabajador != ID_TRABAJADOR_MARIBEL - ) - */ - GROUP BY CodigoTrabajador, Id_Tipo; - - - - - - -/******************** SECTOR FINAL: 4 **************************************/ - -SET i_SECTOR = 4; - - -CASE intCASE - - - WHEN 3 THEN - - SET d_FEC = TIMESTAMP(TIMESTAMPADD(DAY,1,d_END),'00:00:00'); - SET d_FEC2 = TIMESTAMP(TIMESTAMPADD(DAY,-1,d_INV),'23:59:59'); - SET bolREVERSE = TRUE; - - ELSE - - SET d_FEC = TIMESTAMP(d_INV,'00:00:00'); - SET d_FEC2 = TIMESTAMP(d_END ,'23:59:59'); - SET bolREVERSE = FALSE; - - -END CASE; - --- Ahora repetimos el proceso de inventario, para contabilizar el stock remanente. - --- Inicializamos el inventario - - - INSERT INTO inv(Sector, w_id, Id_Article, Unidades, Valor) - SELECT i_SECTOR, TR.warehouse_id, C.Id_Article, sum(C.Cantidad), nz(Costefijo) + nz(Portefijo) + nz(Embalajefijo) + nz(Comisionfija) - FROM Compres C - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos TP USING(tipo_id) - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN warehouse w ON w.id = warehouse_id - JOIN article_selection USING(Id_Article) - WHERE landing = d_INV - AND i_wh IN (0,TR.warehouse_id) - AND E.Id_Proveedor = ID_PROVEEDOR_INVENTARIO - AND reino_id != ID_REINO_OTROS - AND w.comisionantes - AND TR.warehouse_id != TR.warehouse_id_out - GROUP BY TR.warehouse_id, C.Id_Article; - - - - - - --- Se insertan las compras que llegan entre la fecha del inventario y la fecha inicial - - INSERT INTO inv(Sector, w_id, Id_Article, Unidades, Valor) - SELECT i_SECTOR, TR.warehouse_id, C.Id_Article, C.Cantidad * IF(bolREVERSE,-1,1), nz(Costefijo) + nz(Portefijo) + nz(Embalajefijo) + nz(Comisionfija) - FROM Compres C - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos TP USING(tipo_id) - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN warehouse w ON w.id = warehouse_id - JOIN article_selection USING(Id_Article) - WHERE landing BETWEEN d_FEC AND d_FEC2 - AND i_wh IN (0,TR.warehouse_id) - AND NOT redada - AND w.comisionantes - AND E.Id_Proveedor != 4 - AND reino_id != ID_REINO_OTROS - AND TR.warehouse_id != TR.warehouse_id_out - ORDER BY landing DESC - ON DUPLICATE KEY UPDATE inv.Unidades = inv.Unidades + (C.Cantidad * IF(bolREVERSE,-1,1)) - , Valor = IF( nz(Costefijo) > 0,nz(Costefijo) + nz(Portefijo) + nz(Embalajefijo) + nz(Comisionfija),Valor); - --- Se sacan las que salen - - INSERT INTO inv(Sector, w_id, Id_Article, Unidades) - SELECT i_SECTOR, TR.warehouse_id_out, C.Id_Article, C.Cantidad * IF(bolREVERSE,1,-1) - FROM Compres C - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos TP USING(tipo_id) - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN warehouse w ON w.id = warehouse_id_out - JOIN article_selection USING(Id_Article) - WHERE shipment BETWEEN d_FEC AND d_FEC2 - AND i_wh IN (0,TR.warehouse_id_out) - AND NOT redada - AND w.comisionantes - AND E.Id_Proveedor != 4 - AND reino_id != ID_REINO_OTROS - - ON DUPLICATE KEY UPDATE inv.Unidades = inv.Unidades + (C.Cantidad * IF(bolREVERSE,1,-1)); - - --- Ahora las ventas - - INSERT INTO inv(Sector, w_id, Id_Article, Unidades) - SELECT i_SECTOR, w.id, M.Id_Article, M.Cantidad * IF(bolREVERSE,1,-1) - FROM Movimientos M - INNER JOIN Tickets T USING (Id_Ticket) - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos TP USING(tipo_id) - INNER JOIN warehouse w ON w.id = T.warehouse_id - JOIN article_selection USING(Id_Article) - WHERE T.Fecha BETWEEN d_FEC AND d_FEC2 - AND i_wh IN (0,T.warehouse_id) - AND w.comisionantes - AND reino_id != ID_REINO_OTROS - ON DUPLICATE KEY UPDATE inv.Unidades = inv.Unidades + (M.Cantidad * IF(bolREVERSE,1,-1)); - --- Valoramos el inventario final - - -UPDATE inv SET Valor = inv.Unidades * Valor WHERE Sector =4; - - --- Resultado - -DROP TEMPORARY TABLE IF EXISTS Margen_Desglose; - -CREATE TEMPORARY TABLE Margen_Desglose - -SELECT CASE Sector - WHEN 0 THEN 'Inventario Inicial' - WHEN 1 THEN 'Entradas' - WHEN 2 THEN 'Salidas' - WHEN 3 THEN 'Ventas' - WHEN 4 THEN 'Inventario Final' END AS Seccion - , w.name as Almacen, r.reino as Reino, Id_Article, Article, Medida, Unidades,Id_Tipo, round(Valor,0) as Valor , round(Valor/Unidades,3) as Precio, Sector -FROM inv -JOIN Articles USING(Id_Article) -JOIN Tipos TP USING(tipo_id) -JOIN warehouse w ON w.id = w_id -JOIN reinos r ON r.id = TP.reino_id -WHERE Unidades != 0 -ORDER BY Almacen, Sector -; - - - - - -DROP TEMPORARY TABLE IF EXISTS Margen_Bruto; - -CREATE TEMPORARY TABLE Margen_Bruto - -SELECT Unidades_Vendidas, Coste, Venta,1 - round(coste / venta,2) as Margen -FROM ( -SELECT w.name as Almacen, r.reino as Reino, Id_Article, Article, Medida, sum(IF(Sector = 3, -1,0) * Unidades) as Unidades_Vendidas - , @coste:= round(sum( IF(Sector != 3, Valor * IF(Sector = 4,-1,1), 0) ) ,0) as Coste - , @venta:= round(sum( IF(Sector = 3, - Valor, 0 ) ),0) as Venta -FROM inv -JOIN Articles USING(Id_Article) -JOIN Tipos TP USING(tipo_id) -JOIN warehouse w ON w.id = w_id -JOIN reinos r ON r.id = TP.reino_id -WHERE Unidades != 0 - -) sub; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `inventario_multiple` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `inventario_multiple`(IN wh TINYINT(2), IN date_ticket DATETIME) -BEGIN --- DEPRECATED USAR cache.available_refresh - DECLARE date_order DATETIME; - DECLARE date_end DATETIME DEFAULT CURDATE(); - DECLARE date_aux DATE; - DECLARE date_start DATETIME; - DECLARE date_yesterday DATETIME; - DECLARE date_tomorrow DATETIME; - DECLARE strWH VARCHAR(2); - - SET strWH = IF(wh,wh,'%'); - SET date_end = TIMESTAMPADD(DAY, 7, date_ticket); - - CALL article (); - - ALTER TABLE `article_inventory` - ADD `available` FLOAT(7,2) NOT NULL, - ADD `inventory` FLOAT(7,2) NOT NULL, - ADD `visible` FLOAT(7,2) NOT NULL; - - -- JGF 2015-02-19 Falla, el valor @camp es cero y falla Campanya - /* - SELECT - IF(@camp := DATEDIFF(campaign, date_ticket) BETWEEN 0 AND campaign_life, - TIMESTAMPADD(DAY, -campaign_life, campaign), - FechaInventario), - IF(@camp BETWEEN 0 AND campaign_life, - TIMESTAMP(campaign, '23:59:59'), - TIMESTAMP(TIMESTAMPADD(DAY, 15, date_ticket),'23:59:59')) - INTO date_start, date_end - FROM tblContadores;*/ - - SELECT - FechaInventario,TIMESTAMP(TIMESTAMPADD(DAY, 15, date_ticket),'23:59:59') - INTO date_start, date_end - FROM tblContadores; - - - SET date_order = TIMESTAMP(DATE(date_ticket), '00:00:00'); - SET date_tomorrow = TIMESTAMPADD(DAY, 1, date_order); - --- Inventario hasta dia antes del ticket - CALL item_stock(wh,date_ticket,NULL); - - INSERT INTO article_inventory (article_id,inventory,visible,available) - SELECT item_id, stock, visible, available - FROM tmp_item; - - DROP TEMPORARY TABLE IF EXISTS tmp_item; - --- Inventario ventas durante el dia del ticket - INSERT INTO article_inventory(article_id,visible) - - SELECT Id_Article, SUM(amount) AS Subtotal - - FROM ( - - SELECT Id_Article, -Cantidad AS amount - - FROM Movimientos M INNER JOIN Tickets T USING (Id_Ticket) - - WHERE Fecha >= date_order - - AND Fecha < date_tomorrow - - AND (M.OK != FALSE - - OR T.Etiquetasemitidas != FALSE - - OR T.Factura IS NOT NULL) - - AND T.warehouse_id = wh - - UNION ALL - - SELECT Id_Article, Cantidad - - FROM Compres C INNER JOIN Entradas E USING (Id_Entrada) - - LEFT JOIN travel TR ON E.travel_id = TR.id - - WHERE TR.landing >= date_order - - AND TR.landing < date_tomorrow - - AND TR.received != FALSE - - AND TR.warehouse_id = wh - - AND E.Inventario = FALSE - - AND E.Redada = FALSE - - UNION ALL - - SELECT Id_Article, -Cantidad - - FROM Compres C INNER JOIN Entradas E USING (Id_Entrada) - - LEFT JOIN travel TR ON E.travel_id = TR.id - - WHERE TR.shipment >= date_order - - AND TR.shipment < date_tomorrow - - AND TR.delivered != FALSE - - AND TR.warehouse_id_out = wh - - AND E.Inventario = FALSE - - AND E.Redada = FALSE - - ) AS T1 - - GROUP BY Id_Article - - ON DUPLICATE KEY UPDATE - - visible = inventory + VALUES(visible); - - - -- Disponible en el futuro - CALL item_travel (wh, date_order); - - SET date_aux = DATE(date_order); - - INSERT INTO article_inventory(article_id,available) - - SELECT Tic3.Id_Article, minacum(dat, amount, date_aux) AS sd - - FROM ( - - SELECT Tic2.Id_Article, DATE(Fecha) AS dat, SUM(amount) AS amount - - FROM ( - - SELECT Id_Article, Fecha, -Cantidad AS amount - - FROM Movimientos M - - INNER JOIN Tickets T USING (Id_Ticket) - - WHERE Fecha BETWEEN date_order AND date_end - - AND T.warehouse_id = wh - - UNION ALL - - SELECT Id_Article, TR.landing, Cantidad - - FROM Compres C INNER JOIN Entradas E USING (Id_Entrada) - - LEFT JOIN travel TR ON E.travel_id = TR.id - - WHERE TR.landing BETWEEN date_order AND date_end - - AND TR.warehouse_id = wh - - AND E.Inventario = FALSE - - AND E.Redada = FALSE - - UNION ALL - - SELECT Id_Article, TR.shipment, -Cantidad - - FROM Compres C INNER JOIN Entradas E USING (Id_Entrada) - - LEFT JOIN travel TR ON E.travel_id = TR.id - - WHERE TR.shipment BETWEEN date_order AND date_end - - AND TR.warehouse_id_out = wh - - AND E.Inventario = FALSE - - AND E.Redada = FALSE - - ) AS Tic2 - - GROUP BY Tic2.Id_Article, dat - - ) Tic3 - - LEFT JOIN Articles A ON Tic3.Id_Article = A.Id_Article - - LEFT JOIN Origen O ON O.id = A.id_origen - - LEFT JOIN item_travel t ON t.wh = O.warehouse_id - - WHERE dat < IFNULL(t.landing, date_end) - - GROUP BY Tic3.Id_Article - - ON DUPLICATE KEY UPDATE - - available = IFNULL(inventory,0) + VALUES(available); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `inventario_multiple_2` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `inventario_multiple_2`( - date_ticket DATETIME - ,wh TINYINT - ,days_max TINYINT -) -proc: BEGIN - DECLARE date_end DATETIME DEFAULT CURDATE(); - DECLARE date_start DATETIME; - DECLARE date_top DATETIME; - DECLARE date_tomorrow DATETIME; - - SET date_ticket = DATE(date_ticket); -- PAK - - ALTER TABLE `article_inventory` - ADD `avalaible` INT NOT NULL, - ADD `sd` INT NOT NULL, - ADD `rest` INT NOT NULL, - ADD `expected` INT NOT NULL, - ADD `inventory` INT NOT NULL, - ADD `visible` INT NOT NULL, - ADD `life` TINYINT NOT NULL DEFAULT '0'; - - IF date_ticket < CURDATE() - THEN - LEAVE proc; - END IF; - - SELECT FechaInventario INTO date_start FROM tblContadores; - - SET date_end = TIMESTAMP(TIMESTAMPADD(DAY, IF(days_max >= 0, days_max,15), date_ticket),'23:59:59'); - SET date_tomorrow = TIMESTAMPADD(DAY, 1,date_ticket); - SET date_top = TIMESTAMPADD(DAY, 1,date_end); - - -- Calculo del inventario dia D a las 24:00 zulu - - UPDATE article_inventory AI INNER JOIN - - ( - - SELECT Id_Article, SUM(amount) as Subtotal FROM - - ( - - SELECT Id_Article, -Cantidad AS amount - - FROM Movimientos M - JOIN Tickets T USING (Id_Ticket) - JOIN warehouse W ON W.id = T.warehouse_id - WHERE DATE(Fecha) BETWEEN date_start AND date_ticket - AND IF(wh = 0, W.is_comparative, wh =T.warehouse_id) - - UNION ALL - - SELECT Id_Article, Cantidad - FROM Compres C INNER JOIN Entradas E USING (Id_Entrada) - LEFT JOIN travel TR ON E.travel_id = TR.id - JOIN warehouse W ON W.id = TR.warehouse_id -- PAK - WHERE TR.landing BETWEEN date_start AND date_ticket - AND IF(wh = 0, W.is_comparative, wh =TR.warehouse_id) - AND E.Inventario = 0 - AND E.Redada = 0 - - UNION ALL - - SELECT Id_Article, -Cantidad - FROM Compres C - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON E.travel_id = TR.id - JOIN warehouse W ON W.id = TR.warehouse_id_out - WHERE TR.shipment BETWEEN date_start AND date_ticket - AND IF(wh = 0, W.is_comparative, wh =TR.warehouse_id_out) - AND E.Inventario = 0 - AND E.Redada = 0 - - ) AS T1 - - GROUP BY Id_Article - - ) AS T2 - - ON AI.article_id = T2.Id_Article - - SET AI.inventory = T2.Subtotal, - - AI.visible = T2.Subtotal, - - AI.avalaible = T2.Subtotal, - - AI.sd = T2.Subtotal; - - -- Calculo del visible - - UPDATE article_inventory AI INNER JOIN - ( - SELECT Id_Article, SUM(amount) as Subtotal FROM - ( - SELECT Id_Article, Cantidad AS amount - FROM Movimientos M - JOIN Tickets T USING (Id_Ticket) - JOIN warehouse W ON W.id = T.warehouse_id -- PAK - WHERE Fecha >= date_ticket AND Fecha < date_tomorrow -- PAK - AND (M.OK = 0 AND T.Etiquetasemitidas = 0 AND T.Factura IS NULL) - AND IF(wh = 0, W.is_comparative, wh =T.warehouse_id) - - UNION ALL - - SELECT Id_Article, -Cantidad - FROM Compres C - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON E.travel_id = TR.id - JOIN warehouse W ON W.id = TR.warehouse_id -- PAK - WHERE TR.landing = date_ticket - AND TR.received = 0 - AND E.Inventario = 0 - AND E.Redada = 0 - AND IF(wh = 0, W.is_comparative, wh =TR.warehouse_id) - - UNION ALL - - SELECT Id_Article, Cantidad - FROM Compres C INNER JOIN Entradas E USING (Id_Entrada) - LEFT JOIN travel TR ON E.travel_id = TR.id - INNER JOIN warehouse W ON W.id = TR.warehouse_id_out - WHERE TR.shipment = date_ticket - AND TR.delivered = 0 - AND E.Inventario = 0 - AND E.Redada = 0 - AND IF(wh = 0, W.is_comparative, wh =TR.warehouse_id_out) - - ) AS T1 - - GROUP BY Id_Article - - ) AS T2 - - ON AI.article_id = T2.Id_Article - - SET AI.visible = AI.visible + T2.Subtotal; - - -- Calculo del disponible - - CALL item_travel (wh, date_ticket); - - UPDATE article_inventory AI INNER JOIN - ( - SELECT Tic3.Id_Article, SUM(amount) AS sd, minacum(Fecha, amount, date_ticket) as smd FROM - ( - - SELECT Tic2.Id_Article, Fecha, SUM(amount) AS amount FROM - ( - SELECT Id_Article, DATE(Fecha) as Fecha, -Cantidad AS amount - FROM Movimientos M - JOIN Tickets T USING (Id_Ticket) - JOIN warehouse W ON W.id = T.warehouse_id - WHERE Fecha BETWEEN date_tomorrow AND date_end - AND IF(wh = 0, W.is_comparative, wh =T.warehouse_id) - - UNION ALL - - SELECT Id_Article, landing as Fecha, Cantidad - FROM Compres C - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON E.travel_id = TR.id - JOIN warehouse W ON W.id = TR.warehouse_id -- PAK - WHERE TR.landing BETWEEN date_tomorrow AND date_end - AND IF(wh = 0, W.is_comparative, wh =TR.warehouse_id) - AND E.Inventario = 0 - AND E.Redada = 0 - - UNION ALL - - SELECT Id_Article, shipment as Fecha, -Cantidad - FROM Compres C - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON E.travel_id = TR.id - JOIN warehouse W ON W.id = TR.warehouse_id_out - WHERE TR.shipment BETWEEN date_tomorrow AND date_end - AND IF(wh = 0, W.is_comparative, wh =TR.warehouse_id_out) - AND E.Inventario = 0 - AND E.Redada = 0 - - ) AS Tic2 - - GROUP BY Tic2.Id_Article, Fecha - ) Tic3 - - LEFT JOIN Articles A ON Tic3.Id_Article = A.Id_Article - LEFT JOIN Origen O ON O.id = A.id_origen - LEFT JOIN item_travel t ON t.wh = O.warehouse_id - - WHERE Fecha < IF(days_max < 0 AND t.landing IS NOT NULL, - t.landing, - date_top) - - GROUP BY Tic3.Id_Article - - - ) AS Tic5 - - ON Tic5.Id_Article = AI.article_id - SET AI.avalaible = IF(Tic5.smd > 0, AI.avalaible, AI.avalaible + Tic5.smd), - AI.sd = AI.inventory + Tic5.sd; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `inventario_multiple_inventarios` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `inventario_multiple_inventarios`(wh SMALLINT, date_ticket DATETIME) -BEGIN - DECLARE date_order DATETIME; - DECLARE date_end DATETIME DEFAULT CURDATE(); - DECLARE date_start DATETIME; - - CALL article (); - - ALTER TABLE article_inventory - ADD visible FLOAT(7,2) NOT NULL; - - -- Campaña - - SELECT - IF(@camp := DATEDIFF(campaign, date_ticket) BETWEEN 0 AND campaign_life , - TIMESTAMPADD(DAY, -campaign_life, campaign) , - FechaInventario), - IF(@camp BETWEEN 0 AND campaign_life, - TIMESTAMP(campaign, '23:59:59'), - TIMESTAMP(TIMESTAMPADD(DAY, 15, date_ticket),'23:59:59')) - INTO date_start, date_end - FROM tblContadores; - - SET date_order = TIMESTAMP(DATE(date_ticket), '00:00:00'); - - INSERT INTO article_inventory (article_id, visible) - SELECT Id_Article, SUM(amount) - FROM ( - SELECT Id_Article, -Cantidad AS amount - FROM Movimientos M INNER JOIN Tickets T USING (Id_Ticket) - WHERE Fecha >= date_start - AND Fecha < date_order - AND T.warehouse_id = wh - UNION ALL - SELECT Id_Article, Cantidad - FROM Compres C INNER JOIN Entradas E USING (Id_Entrada) - LEFT JOIN travel TR ON E.travel_id = TR.id - WHERE TR.landing >= date_start - AND TR.landing < date_order - AND TR.warehouse_id = wh - AND E.Inventario = FALSE - UNION ALL - SELECT Id_Article, -Cantidad - FROM Compres C INNER JOIN Entradas E USING (Id_Entrada) - LEFT JOIN travel TR ON E.travel_id = TR.id - WHERE TR.shipment >= date_start - AND TR.shipment < date_order - AND TR.warehouse_id_out = wh - AND E.Inventario = FALSE - ) AS T1 - GROUP BY Id_Article; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `inventario_multiple_joined` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `inventario_multiple_joined`( - date_ticket DATETIME - ,wh_joined TINYINT - ,days_max TINYINT -) -proc: BEGIN - DECLARE date_end DATETIME DEFAULT CURDATE(); - DECLARE date_start DATETIME; - DECLARE date_top DATETIME; - DECLARE date_tomorrow DATETIME; - DECLARE i_avalaible INTEGER; - DECLARE wh INTEGER; - - SET date_ticket = DATE(date_ticket); -- PAK - - ALTER TABLE `article_inventory` - ADD `avalaible` INT NOT NULL, - ADD `sd` INT NOT NULL, - ADD `rest` INT NOT NULL, - ADD `expected` INT NOT NULL, - ADD `inventory` INT NOT NULL, - ADD `visible` INT NOT NULL, - ADD `life` TINYINT NOT NULL DEFAULT '0'; - - IF date_ticket < CURDATE() - THEN - LEAVE proc; - END IF; - - SELECT FechaInventario INTO date_start FROM tblContadores; - - SET date_end = TIMESTAMP(TIMESTAMPADD(DAY, IF(days_max >= 0, days_max,15), date_ticket),'23:59:59'); - SET date_tomorrow = TIMESTAMPADD(DAY, 1,date_ticket); - SET date_top = TIMESTAMPADD(DAY, 1,date_end); - - -- Calculo del inventario dia D a las 24:00 zulu - - UPDATE article_inventory AI INNER JOIN - - ( - - SELECT Id_Article, SUM(amount) as Subtotal FROM - - ( - - SELECT Id_Article, -Cantidad AS amount - - FROM Movimientos M - - JOIN Tickets T USING (Id_Ticket) - JOIN warehouse_joined wj ON T.warehouse_id = wj.warehouse_id -- JGF 15/12/14 - WHERE DATE(Fecha) BETWEEN date_start AND date_ticket - AND wh_joined IN (wj.warehouse_alias_id, 0) - UNION ALL - - SELECT Id_Article, Cantidad - - FROM Compres C INNER JOIN Entradas E USING (Id_Entrada) - - LEFT JOIN travel TR ON E.travel_id = TR.id - JOIN warehouse_joined wj ON TR.warehouse_id = wj.warehouse_id -- JGF 15/12/14 - WHERE TR.landing BETWEEN date_start AND date_ticket - AND wh_joined IN (wj.warehouse_alias_id, 0) - - AND E.Inventario = 0 - AND E.Redada = 0 - - UNION ALL - - SELECT Id_Article, -Cantidad - FROM Compres C - - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON E.travel_id = TR.id - JOIN warehouse_joined wj ON TR.warehouse_id_out = wj.warehouse_id -- JGF 15/12/14 - WHERE TR.shipment BETWEEN date_start AND date_ticket - AND wh_joined IN (wj.warehouse_alias_id,0) - AND E.Inventario = 0 - AND E.Redada = 0 - ) AS T1 - - GROUP BY Id_Article - - ) AS T2 - - ON AI.article_id = T2.Id_Article - - SET AI.inventory = T2.Subtotal, - - AI.visible = T2.Subtotal, - - AI.avalaible = T2.Subtotal, - - AI.sd = T2.Subtotal; - - SELECT avalaible INTO i_avalaible FROM article_inventory WHERE article_id = 21012; - - -- Calculo del visible - - UPDATE article_inventory AI INNER JOIN - ( - SELECT Id_Article, SUM(amount) as Subtotal FROM - ( - SELECT Id_Article, Cantidad AS amount - FROM Movimientos M - - JOIN Tickets T USING (Id_Ticket) - JOIN warehouse_joined wj ON T.warehouse_id = wj.warehouse_id -- JGF 15/12/14 - WHERE Fecha >= date_ticket AND Fecha < date_tomorrow -- PAK - AND (M.OK = 0 AND T.Etiquetasemitidas = 0 AND T.Factura IS NULL) - AND wh_joined IN (wj.warehouse_alias_id, 0) - UNION ALL - SELECT Id_Article, -Cantidad - FROM Compres C - - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON E.travel_id = TR.id - - JOIN warehouse_joined wj ON TR.warehouse_id = wj.warehouse_id -- JGF 15/12/14 - WHERE TR.landing = date_ticket - - AND TR.received = 0 - AND E.Inventario = 0 - AND E.Redada = 0 - AND wh_joined IN (wj.warehouse_alias_id, 0) - - UNION ALL - - SELECT Id_Article, Cantidad - FROM Compres C INNER JOIN Entradas E USING (Id_Entrada) - LEFT JOIN travel TR ON E.travel_id = TR.id - JOIN warehouse_joined wj ON TR.warehouse_id_out = wj.warehouse_id -- JGF 15/12/14 - WHERE TR.shipment = date_ticket - AND TR.delivered = 0 - AND E.Inventario = 0 - AND E.Redada = 0 - AND wh_joined IN (wj.warehouse_alias_id,0) - ) AS T1 - - GROUP BY Id_Article - - ) AS T2 - - ON AI.article_id = T2.Id_Article - - SET AI.visible = AI.visible + T2.Subtotal; - - -- Calculo del disponible - SELECT IF(COUNT(warehouse_id),0,warehouse_id) INTO wh FROM warehouse_joined WHERE warehouse_alias_id = wh_joined; - - CALL item_travel (wh, date_ticket); - - UPDATE article_inventory AI INNER JOIN - ( - SELECT Tic3.Id_Article, SUM(amount) AS sd, minacum(Fecha, amount, date_ticket) as smd FROM - ( - - SELECT Tic2.Id_Article, Fecha, SUM(amount) AS amount FROM - ( - SELECT Id_Article, DATE(Fecha) as Fecha, -Cantidad AS amount - FROM Movimientos M - - JOIN Tickets T USING (Id_Ticket) - - JOIN warehouse_joined wj ON T.warehouse_id = wj.warehouse_id -- JGF 15/12/14 - WHERE Fecha BETWEEN date_tomorrow AND date_end - AND wh_joined IN (wj.warehouse_alias_id, 0) - - UNION ALL - SELECT Id_Article, landing as Fecha, Cantidad - FROM Compres C - - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON E.travel_id = TR.id - - JOIN warehouse_joined wj ON TR.warehouse_id = wj.warehouse_id -- JGF 15/12/14 - WHERE TR.landing BETWEEN date_tomorrow AND date_end - AND wh_joined IN (wj.warehouse_alias_id, 0) - - AND E.Inventario = 0 - AND E.Redada = 0 - UNION ALL - SELECT Id_Article, shipment as Fecha, -Cantidad - FROM Compres C - - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON E.travel_id = TR.id - JOIN warehouse_joined wj ON TR.warehouse_id_out = wj.warehouse_id -- JGF 15/12/14 - WHERE TR.shipment BETWEEN date_tomorrow AND date_end - AND wh_joined IN (wj.warehouse_alias_id,0) - AND E.Inventario = 0 - AND E.Redada = 0 - ) AS Tic2 - - GROUP BY Tic2.Id_Article, Fecha - ) Tic3 - - LEFT JOIN Articles A ON Tic3.Id_Article = A.Id_Article - LEFT JOIN Origen O ON O.id = A.id_origen - LEFT JOIN item_travel t ON t.wh = O.warehouse_id - - WHERE Fecha < IF(days_max < 0 AND t.landing IS NOT NULL, - t.landing, - date_top) - - GROUP BY Tic3.Id_Article - - - ) AS Tic5 - - ON Tic5.Id_Article = AI.article_id - SET AI.avalaible = IF(Tic5.smd > 0, AI.avalaible, AI.avalaible + Tic5.smd), - AI.sd = AI.inventory + Tic5.sd; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `inventario_multiple_reservas` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `inventario_multiple_reservas`(date_ticket DATETIME, wh INT, days_max INT) -BEGIN - DECLARE date_end DATETIME DEFAULT CURDATE(); - DECLARE date_start DATETIME; - DECLARE i_avalaible INTEGER; - - SET date_ticket = DATE(date_ticket); - - CALL article (); - - INSERT INTO article_inventory (article_id) - SELECT a.Id_Article - FROM Articles a - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - LEFT JOIN reinos r ON r.id = tp.reino_id - WHERE r.display <> 0; - - ALTER TABLE `article_inventory` - ADD `avalaible` INT(11) NOT NULL, - ADD `sd` INT(11) NOT NULL, - ADD `rest` INT(11) NOT NULL, - ADD `expected` INT(11) NOT NULL, - ADD `inventory` INT(11) NOT NULL, - ADD `visible` INT(11) NOT NULL, - ADD `life` TINYINT(1) NOT NULL DEFAULT '0'; - - SELECT FechaInventario INTO date_start FROM tblContadores; - - SET date_end = TIMESTAMP(TIMESTAMPADD(DAY, -1, date_ticket),'23:59:59'); - - -- Utilizo el valor clave 4848 para days_max para aprovechar el procedimiento para el frmCamiones de eti - - IF days_max = 4848 THEN - set date_ticket = date_end; - END IF; - - -- Calculo del inventario dia D a las 24:00 - - UPDATE article_inventory AI INNER JOIN - ( - SELECT Id_Article, SUM(amount) as Subtotal FROM ( - SELECT Id_Article, -Cantidad AS amount - FROM Movimientos M - JOIN Tickets T USING (Id_Ticket) - JOIN warehouse W ON W.id = T.warehouse_id - WHERE Fecha BETWEEN date_start AND date_end - AND wh IN (T.warehouse_id, 0) - AND NOT W.fuente - UNION ALL - SELECT Id_Article, Cantidad - FROM Compres C - JOIN Entradas E USING (Id_Entrada) - LEFT JOIN travel TR ON E.travel_id = TR.id - JOIN warehouse W ON W.id = TR.warehouse_id - WHERE TR.landing BETWEEN date_start AND date_ticket - AND wh IN (TR.warehouse_id, 0) - AND NOT W.fuente - AND E.Inventario = 0 - AND E.Redada = 0 - UNION ALL - SELECT Id_Article, -Cantidad - FROM Compres C - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON E.travel_id = TR.id - JOIN warehouse W ON W.id = TR.warehouse_id_out - WHERE TR.shipment BETWEEN date_start AND date_end - AND wh IN (TR.warehouse_id_out,0) - AND NOT W.fuente - AND E.Inventario = 0 - AND E.Redada = 0 - ) AS T1 - GROUP BY Id_Article - ) AS T2 - ON AI.article_id = T2.Id_Article - SET AI.inventory = T2.Subtotal, - AI.visible = T2.Subtotal, - AI.avalaible = T2.Subtotal, - AI.sd = T2.Subtotal; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `inventario_valorado` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `inventario_valorado`(IN d_FEC DATE, IN bol_DESGLOSE BOOLEAN) -BEGIN - - DECLARE d_INV DATE; - DECLARE bolREVERSE BOOLEAN DEFAULT 0; - DECLARE d_INV2 DATE; - - SELECT landing INTO d_INV - FROM travel TR - INNER JOIN Entradas E ON E.travel_id = TR.id - WHERE landing <= d_FEC - AND E.Id_Proveedor = 4 - ORDER BY landing DESC - LIMIT 1; - - SET bolREVERSE = IF (d_INV is null, 1, 0); - - - IF bolREVERSE THEN - - SELECT landing INTO d_INV2 - FROM travel TR - INNER JOIN Entradas E ON E.travel_id = TR.id - WHERE landing >= d_FEC - AND E.Id_Proveedor = 4 - ORDER BY landing ASC - LIMIT 1; - - SET d_INV = TIMESTAMPADD(DAY,1,d_FEC); - SET d_FEC = d_INV2; - - - - END IF; - - DROP TEMPORARY TABLE IF EXISTS inv; - - CREATE TEMPORARY TABLE inv - (w_id SMALLINT, - Id_Article BIGINT, - cantidad INT, - coste DOUBLE DEFAULT 0, - total DOUBLE DEFAULT 0) ENGINE = MEMORY; - - - ALTER TABLE inv ADD PRIMARY KEY USING HASH (w_id, Id_Article); - - - - IF bolREVERSE = 1 THEN - - INSERT INTO inv(w_id, Id_Article, cantidad) - SELECT TR.warehouse_id, C.Id_Article, SUM(C.Cantidad) - FROM Compres C - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN Tipos t USING(tipo_id) - INNER JOIN warehouse w ON w.id = warehouse_id - WHERE landing = d_FEC - AND E.Id_Proveedor = 4 - AND NOT w.fuente - AND t.inventory - AND reino_id NOT IN (7) - GROUP BY TR.warehouse_id, C.Id_Article; - - END IF; - - INSERT INTO inv(w_id, Id_Article, cantidad) - SELECT TR.warehouse_id, C.Id_Article, C.Cantidad * IF(bolREVERSE,-1,1) - FROM Compres C - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN Tipos t USING(tipo_id) - INNER JOIN warehouse w ON w.id = TR.warehouse_id - WHERE landing BETWEEN d_INV AND TIMESTAMPADD(DAY, IF(bolREVERSE,-1,0) ,d_FEC) - AND NOT redada - AND NOT w.fuente - AND reino_id NOT IN (7) - AND t.inventory - ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (C.Cantidad * IF(bolREVERSE,-1,1)); - - INSERT INTO inv(w_id, Id_Article, cantidad) - SELECT TR.warehouse_id_out, C.Id_Article, C.Cantidad * IF(bolREVERSE,1,-1) - FROM Compres C - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN Tipos t USING(tipo_id) - INNER JOIN warehouse w ON w.id = warehouse_id_out - WHERE shipment BETWEEN d_INV AND TIMESTAMPADD(DAY, IF(bolREVERSE,-1,0) ,d_FEC) - AND NOT redada - AND NOT w.fuente - AND reino_id NOT IN (7) - AND t.inventory - ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (C.Cantidad * IF(bolREVERSE,1,-1)); - - INSERT INTO inv(w_id, Id_Article, cantidad) - SELECT w.id, M.Id_Article, M.Cantidad * IF(bolREVERSE,1,-1) - FROM Movimientos M - INNER JOIN Tickets T USING (Id_Ticket) - INNER JOIN Clientes C USING(Id_Cliente) - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos t USING(tipo_id) - INNER JOIN warehouse w ON w.id = warehouse_id - WHERE T.Fecha BETWEEN d_INV AND TIMESTAMPADD(DAY, -1 ,d_FEC) - AND NOT w.fuente - AND reino_id NOT IN (7) - AND t.inventory - ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + M.Cantidad * IF(bolREVERSE,1,-1); - - - INSERT INTO inv(w_id, Id_Article, cantidad) - SELECT w.id, M.Id_Article, M.Cantidad * IF(bolREVERSE,0,-1) - FROM Movimientos M - INNER JOIN Tickets T USING (Id_Ticket) - INNER JOIN Clientes C USING(Id_Cliente) - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos t USING(tipo_id) - INNER JOIN warehouse w ON w.id = warehouse_id - WHERE date(T.Fecha) = d_FEC - AND (d_FEC <> CURDATE() or (M.OK <> 0 or T.Etiquetasemitidas <> 0 )) - AND NOT w.fuente - AND reino_id NOT IN (7) - AND t.inventory - ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + M.Cantidad * IF(bolREVERSE,0,-1); - - CALL item_last_buy_(NULL,d_FEC); - - UPDATE inv - JOIN t_item_last_buy lb ON w_id = lb.warehouse_id AND inv.Id_Article = lb.item_id - JOIN Compres C ON C.Id_Compra = lb.buy_id - SET total = inv.cantidad * (ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0)), - coste = ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0) - WHERE inv.cantidad <> 0; - - DELETE FROM inv WHERE Cantidad IS NULL or Cantidad = 0; - - IF bol_DESGLOSE THEN - - SELECT inv.w_id, a.Id_Article, a.Article, a.Medida, inv.Cantidad, tp.Id_Tipo, - tp.reino_id, inv.coste, cast(inv.total as decimal(10,2)) total, an.nicho - FROM inv - JOIN warehouse w on w.id = w_id - JOIN Articles a ON a.Id_Article = inv.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - JOIN Articles_nicho an ON an.Id_Article = a.Id_Article AND an.warehouse_id = w.id - where w.valuatedInventory - and inv.total > 0 - order by inv.total desc; - - ELSE - - SELECT w.name as Almacen, r.reino as Reino, cast(total as decimal) as Euros - FROM inv - JOIN warehouse w ON w.id = w_id - JOIN Articles A USING(Id_Article) - JOIN Tipos t USING(tipo_id) - JOIN reinos r ON r.id = t.reino_id - where w.valuatedInventory; - - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `inventory_refresh` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `inventory_refresh`() -BEGIN -/** - * Recalcula los inventarios de todos los almacenes. - */ - INSERT INTO daily_task_log - SET consulta = 'inventory_refresh-begin'; - - CALL article_inventory_warehouses (TIMESTAMPADD(DAY, -10, CURDATE())); - - INSERT INTO daily_task_log - SET consulta = 'inventory_refresh-end'; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoice_newkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoice_newkk`( - customer_id INT, - serie VARCHAR(10), - date_ini DATE, - date_end DATE, - date_invoice DATETIME, - ticket_id INT, - empresa_act INT, - Id_Trabajador INT -) -BEGIN - DECLARE invoice_id VARCHAR(30) DEFAULT NULL; - DECLARE date_vec DATE DEFAULT date_invoice; - DECLARE day_vec INT; - DECLARE bi_r DOUBLE DEFAULT 0; - DECLARE bi_g DOUBLE DEFAULT 0; - DECLARE bi_n DOUBLE DEFAULT 0; - DECLARE iva_r DOUBLE DEFAULT 0; - DECLARE iva_g DOUBLE DEFAULT 0; - DECLARE re_r DOUBLE DEFAULT 0; - DECLARE re_g DOUBLE DEFAULT 0; - DECLARE dblImporte DOUBLE DEFAULT 0; - DECLARE intpais_id TINYINT DEFAULT 1; - DECLARE intFac INTEGER; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - SELECT TIMESTAMP (date_ini, '00:00:00') into date_ini; - - SET date_invoice = IFNULL(date_invoice,CURDATE()); - - IF date_invoice >= '2015-12-01' AND empresa_act = 791 AND serie <> 'A' THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT ='ERROR_FTH_NO_EXISTE'; - END IF; - - DROP TEMPORARY TABLE IF EXISTS `iva_base`; - CREATE TEMPORARY TABLE `iva_base` - ( - `id` VARCHAR(3) NOT NULL, - `base` DOUBLE NOT NULL DEFAULT 0, - PRIMARY KEY (`id`) - ) - ENGINE = MEMORY; - - DROP TEMPORARY TABLE IF EXISTS `ticket_invoice`; - CREATE TEMPORARY TABLE `ticket_invoice` - ( - `ticket_id` INT NOT NULL, - PRIMARY KEY (`ticket_id`) - ) - ENGINE = MEMORY; - - START TRANSACTION; - - SELECT pais_id INTO intpais_id FROM Proveedores WHERE Id_Proveedor = empresa_act; - - IF ticket_id = 0 THEN - - INSERT INTO ticket_invoice (ticket_id) SELECT Id_Ticket FROM Tickets WHERE (Fecha BETWEEN date_ini - AND DAYEND(date_end)) AND Id_Cliente = customer_id AND Factura IS NULL AND empresa_id = empresa_act ; - - ELSE - - INSERT INTO ticket_invoice (ticket_id) SELECT Id_Ticket FROM Tickets WHERE Id_Ticket = ticket_id - AND Factura IS NULL ; - - END IF; --- Elimina tickets sense moviments - UPDATE Tickets INNER JOIN (SELECT COUNT(Movimientos.Id_Movimiento) AS num, ticket_invoice.ticket_id AS ticket_id - FROM ticket_invoice LEFT JOIN Movimientos ON ticket_invoice.ticket_id = Movimientos.Id_Ticket - GROUP BY ticket_invoice.ticket_id HAVING num = 0) counter - ON Tickets.Id_Ticket = counter.ticket_id SET Tickets.Fecha = '1999-01-01 00:00:00'; - - -- Eliminem els tickets que no han de ser facturats - DELETE ticket_invoice.* FROM ticket_invoice INNER JOIN Tickets ON ticket_invoice.ticket_id = Tickets.Id_Ticket - INNER JOIN Clientes ON Tickets.Id_Cliente = Clientes.Id_cliente WHERE YEAR(Tickets.Fecha) < 2001 AND invoice; - - IF (SELECT COUNT(*) FROM ticket_invoice) > 0 THEN - - INSERT INTO iva_base (id) SELECT tipoiva FROM tblIVA; - - UPDATE iva_base - INNER JOIN - (SELECT tipo, SUM(base) base - FROM - (SELECT t.tipo, red(m.Cantidad * m.Preu * (100 - Descuento) / 100) AS base - FROM - Movimientos m - INNER JOIN ticket_invoice ti ON m.Id_Ticket = ti.ticket_id - INNER JOIN (SELECT t.tipo, Id_Article - FROM - (SELECT - date, iva_codigo_id, ic.tipo, iva_group_id - FROM - iva_group_codigo gi - INNER JOIN iva_codigo ic ON gi.iva_codigo_id = ic.id - INNER JOIN iva_tipo itp ON itp.id = ic.iva_tipo_id - WHERE - date <= date_invoice - AND Id_Pais = intpais_id - ORDER BY date DESC) t - INNER JOIN Articles USING (iva_group_id) - GROUP BY Id_Article) t USING (Id_Article)) sub - GROUP BY tipo) iva_movement ON iva_base.id = iva_movement.tipo - SET - iva_base.base = iva_movement.base; - - IF (serie = 'H' OR serie = 'V' OR serie = 'E' OR serie = 'X') then - SELECT SUM(base) into dblImporte from iva_base; - ELSE - - SET bi_r = (SELECT base FROM iva_base WHERE id = 'R'); - - SET bi_g = (SELECT base FROM iva_base WHERE id = 'G'); - SET bi_n = (SELECT base FROM iva_base WHERE id = '0'); - SET iva_r = red(bi_r * (SELECT iva FROM iva_codigo INNER JOIN iva_tipo it ON it.id = iva_tipo_id - WHERE tipo = 'R' AND Id_Pais = intpais_id AND Fecha <= date_invoice and iva ORDER BY fecha DESC, recargo DESC LIMIT 1) / 100 ); - SET iva_g = red(bi_g * (SELECT iva FROM iva_codigo INNER JOIN iva_tipo it ON it.id = iva_tipo_id - WHERE tipo = 'G' AND Id_Pais = intpais_id AND Fecha <= date_invoice and iva ORDER BY fecha DESC, recargo DESC LIMIT 1) / 100 ); - IF (SELECT IF(RE = 0, FALSE, TRUE) FROM Clientes WHERE Clientes.Id_cliente = customer_id) THEN - - SET re_r = red(bi_r * (SELECT recargo FROM iva_codigo INNER JOIN iva_tipo it ON it.id = iva_tipo_id - WHERE tipo = 'R' AND Id_Pais = intpais_id AND Fecha <= date_invoice and iva ORDER BY fecha DESC, recargo DESC LIMIT 1) / 100 ); - SET re_g = red(bi_g * (SELECT recargo FROM iva_codigo INNER JOIN iva_tipo it ON it.id = iva_tipo_id - WHERE tipo = 'G' AND Id_Pais = intpais_id AND Fecha <= date_invoice and iva ORDER BY fecha DESC, recargo DESC LIMIT 1) / 100 ); - END IF; - SET dblImporte = bi_r + bi_g + bi_n + iva_r + iva_g + re_r + re_g ; - END IF; - - END IF; - - IF dblImporte <> 0 THEN - - SELECT Vencimiento INTO day_vec FROM Clientes WHERE Id_cliente = customer_id; - SET date_vec = TIMESTAMPADD(DAY, day_vec, date_vec); - - -- el trigger añade el siguiente Id_Factura correspondiente a la serie - INSERT INTO Facturas - ( - Id_Factura, - Serie, - Fecha, - Id_Cliente, - BI7, - BI16, - IVA7, - IVA16, - RE1, - RE4, - Importe, - Vencimiento, - empresa_id - ) - VALUES - ( - 1, - serie, - date_invoice, - customer_id, - bi_r, - bi_g, - iva_r, - iva_g, - re_r, - re_g, - dblImporte, - date_vec, - empresa_act - ); - - SET intFac = LAST_INSERT_ID(); - - SELECT Id_Factura INTO invoice_id FROM Facturas - WHERE factura_id = intFac; - - UPDATE Tickets INNER JOIN ticket_invoice ON Tickets.Id_Ticket = ticket_invoice.ticket_id - SET Factura = invoice_id, Etiquetasemitidas = TRUE; - - DROP TEMPORARY TABLE IF EXISTS tmp.updateInter; - CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY - SELECT s.id,ti.ticket_id,Id_Trabajador - FROM ticket_invoice ti - JOIN vn.ticketState ts ON ti.ticket_id = ts.ticket - JOIN state s - WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = vn.getAlert3State(ti.ticket_id); - - INSERT INTO vncontrol.inter(state_id,Id_Ticket,Id_Trabajador) - SELECT * FROM tmp.updateInter; - - INSERT INTO Tickets_dits (idaccion_dits,Id_Trabajador,Id_Ticket,value_old,value_new) - SELECT 111/*Factura serie*/,Id_Trabajador,ti.ticket_id,NULL,serie FROM ticket_invoice ti; - END IF; - - DROP TEMPORARY TABLE `iva_base`; - DROP TEMPORARY TABLE `ticket_invoice`; - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemTagArrangedUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `itemTagArrangedUpdate`(IN vItem BIGINT) -BEGIN -/** - * DEPRECATED - **/ - CALL vn.itemTagArrangedUpdate(vItem); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemTagArrangedUpdate_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `itemTagArrangedUpdate_launcher`() -BEGIN - - call vn2008.itemTagArrangedUpdate(0); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemTagUpdatePriority` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `itemTagUpdatePriority`(IN vItem INT) -BEGIN -/* -* DEPRECATED -*/ - -CALL vn.itemTagUpdatePriority(vItem); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_buffer_tarifa_traveltreekk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_buffer_tarifa_traveltreekk`(v_date DATE, v_consigna INT, v_agencia INT, i_order INT, v_wh SMALLINT) -BEGIN - -- v_date fecha de recepcion de mercancia - - DECLARE done TINYINT DEFAULT 0; - DECLARE v_shipment DATE; - DECLARE v_agency_id INT; - - DECLARE cur1 CURSOR FOR - SELECT warehouse_id, Fecha_envio - FROM travel_tree; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - - -- establecemos los almacenes y las fechas que van a entrar al dispo_multi - - SELECT agency_id INTO v_agency_id FROM Agencias WHERE Id_Agencia = v_agencia; - - -- Si pasamos un almacen significa que estamos recalculando el dispo y el precio para un ticket existente - - IF v_wh = 0 - THEN - CALL travel_tree(v_date,v_consigna, v_agency_id); - ELSE - DROP TEMPORARY TABLE IF EXISTS travel_tree; - - CREATE TEMPORARY TABLE travel_tree ( - warehouse_id SMALLINT NOT NULL, - Fecha_envio DATE NOT NULL, - Fecha_recepcion DATE NOT NULL, - PRIMARY KEY ( warehouse_id) - ) ENGINE = MEMORY; - - INSERT INTO travel_tree - SELECT v_wh, v_date, v_date; - END IF; - - -- Ejecutamos item_buffer_tarifa para cada registro del cursos, y almacenaremos los valores acumulados, para el buffer y para los componentes - - OPEN cur1; - FETCH cur1 INTO v_wh, v_shipment; - - DROP TEMPORARY TABLE IF EXISTS buffer_multi; - CREATE TEMPORARY TABLE buffer_multi ( - warehouse_id tinyint(4) NOT NULL , - Id_Article int(11) NOT NULL , - visible double DEFAULT NULL, - available double DEFAULT NULL, - future date DEFAULT NULL, - buy_inc int(11) DEFAULT NULL, - buy_last date DEFAULT NULL, - buy_id int(11) DEFAULT NULL, - `fixed` tinyint(4) DEFAULT '0', - rate_0 double DEFAULT NULL, - rate_1 double DEFAULT NULL, - rate_2 double DEFAULT NULL, - rate_3 double DEFAULT NULL, - Packing int(8) DEFAULT 1, - Grouping int(8) DEFAULT 1, - Productor VARCHAR(45) DEFAULT NULL, - caja tinyint(4) DEFAULT '0', - Origen VARCHAR(3) NOT NULL DEFAULT '---', - mark tinyint(4) DEFAULT '0', - `comment` VARCHAR(100), - foto VARCHAR(50), - Id_Tipo smallint(5), - Article VARCHAR(50), - PRIMARY KEY (Id_Article, warehouse_id) - ) ENGINE = MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ; - - WHILE NOT done - DO - CALL item_buffer_tarifa(v_wh, v_shipment, v_consigna, FALSE, v_agencia); - - -- eliminaremos PCA de Silla FV y viceversa - - INSERT INTO buffer_multi(warehouse_id, Id_Article, visible, available, future, buy_inc, buy_last, buy_id, `fixed`, rate_0, rate_1, rate_2, rate_3, Packing, Grouping, Productor, caja, Origen, mark, `comment`, foto, Id_Tipo, Article) - SELECT v_wh, id, visible, available, future, buy_inc, buy_last, buy_id, `fixed`, rate_0, rate_1, rate_2, rate_3, Packing, Grouping, Productor, bb.caja, Origen, mark, `comment`, A.Foto, A.tipo_id, A.Article - FROM bionic_buffer bb - JOIN Articles A ON A.Id_Article = bb.id - JOIN Tipos TP ON TP.tipo_id = A.tipo_id - WHERE NOT (v_wh = 44 AND TP.reino_id IN (1,5)) - AND NOT (v_wh = 1 AND TP.reino_id NOT IN (1,5)); - - INSERT INTO order_components(order_id, warehouse_id, Id_Article, Valor, Id_Componente) - SELECT i_order, v_wh, bb.Id_Article, Valor, Id_Componente - FROM components bb - JOIN Articles A ON A.Id_Article = bb.Id_Article - JOIN Tipos TP ON TP.tipo_id = A.tipo_id - WHERE NOT (v_wh = 44 AND TP.reino_id IN (1,5)) - AND NOT (v_wh = 1 AND TP.reino_id NOT IN (1,5)); - - DROP TEMPORARY TABLE bionic_buffer; - DROP TEMPORARY TABLE components; - - FETCH cur1 INTO v_wh, v_shipment; - END WHILE; - - CLOSE cur1; - - DROP TEMPORARY TABLE IF EXISTS buffer_multi_lotes; - - CREATE TEMPORARY TABLE buffer_multi_lotes - ENGINE = MEMORY - SELECT buy_last as landing, warehouse_id, Id_Article, FLOOR(available/IF(caja = 1,Grouping,1)) AS Items, - IF(caja = 1,Grouping,1) AS Grouping, rate_1 AS Precio, 1 AS tarifa_class - FROM buffer_multi - WHERE caja < 2 - AND (Packing > Grouping or caja = 0); - - INSERT INTO buffer_multi_lotes - SELECT buy_last, warehouse_id, Id_Article, FLOOR(available/Packing) AS items, Packing AS Grouping, rate_2 AS Precio,2 AS tarifa_class - FROM buffer_multi - WHERE Packing > 0 - AND available > Packing; - - INSERT INTO buffer_multi_lotes - SELECT buy_last, warehouse_id, Id_Article, 1 AS items, available AS Grouping, rate_3 AS Precio,3 AS tarifa_class - FROM buffer_multi; - - DROP TEMPORARY TABLE travel_tree; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_buffer_tarifa_traveltree_dupkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_buffer_tarifa_traveltree_dupkk`( - v_date DATE, -- fecha de recepcion de mercancia - v_consigna INT, - v_agencia INT, - i_order INT, - v_wh TINYINT) -BEGIN - DECLARE v_shipment DATE; - DECLARE v_agency_id INT; - DECLARE done BOOL DEFAULT FALSE; - DECLARE cur CURSOR FOR - SELECT warehouse_id, Fecha_envio FROM travel_tree; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - CALL cache.order_clean (i_order); - - -- Establecemos los almacenes y las fechas que van a entrar al dispo_multi - - SELECT agency_id INTO v_agency_id FROM Agencias WHERE Id_Agencia = v_agencia; - - -- Si pasamos un almacen significa que estamos recalculando el dispo y el precio para un ticket existente - - DROP TEMPORARY TABLE IF EXISTS travel_tree; - - IF v_wh = 0 - THEN - CALL vn2008.travel_tree(v_date,v_consigna, v_agency_id); - ELSE - CREATE TEMPORARY TABLE travel_tree - (PRIMARY KEY (warehouse_id)) - ENGINE=MEMORY - SELECT v_wh warehouse_id, v_date Fecha_envio; - END IF; - - -- Ejecutamos item_buffer_tarifa para cada registro del cursos, y almacenaremos los valores acumulados, para el buffer y para los componentes - - OPEN cur; - FETCH cur INTO v_wh, v_shipment; - - WHILE NOT done - DO - CALL item_buffer_tarifa_dup (v_wh, v_shipment, v_consigna, FALSE, v_agencia); - - -- Eliminaremos PCA de Silla FV y viceversa - - INSERT INTO cache.order_stock ( - order_id, warehouse_id, Id_Article, visible, available, future, buy_inc, buy_last, buy_id, `fixed`, rate_0, rate_1, rate_2, rate_3, Packing, Grouping, Productor, caja, Origen, mark, `comment`, foto, Id_Tipo, Article - ) - SELECT i_order, v_wh, id, visible, available, future, buy_inc, buy_last, buy_id, `fixed`, rate_0, rate_1, rate_2, rate_3, Packing, Grouping, Productor, bb.caja, Origen, mark, `comment`, A.Foto, A.tipo_id, A.Article - FROM bionic_buffer bb - JOIN Articles A on A.Id_Article = bb.id - JOIN Tipos TP on TP.tipo_id = A.tipo_id - WHERE NOT (v_wh = 44 AND TP.reino_id IN (1,5)) - AND NOT (v_wh = 1 AND TP.reino_id NOT IN (1,5)); - - INSERT INTO cache.order_component ( - order_id, warehouse_id, item_id, cost, component_id - ) - SELECT i_order, v_wh, bb.Id_Article, Valor, Id_Componente - FROM components bb - JOIN Articles A on A.Id_Article = bb.Id_Article - JOIN Tipos TP on TP.tipo_id = A.tipo_id - WHERE NOT (v_wh = 44 AND TP.reino_id IN (1,5)) - AND NOT (v_wh = 1 AND TP.reino_id NOT IN (1,5)); - - FETCH cur INTO v_wh, v_shipment; - END WHILE; - - CLOSE cur; - - INSERT INTO cache.order_stock_lot ( - order_id, - landing, - warehouse_id, - item_id, - items, - grouping, - price, - rate_class - ) - SELECT order_id, buy_last, warehouse_id, Id_Article, FLOOR(available / IF(caja = 1, Grouping, 1)), IF(caja = 1, Grouping, 1), rate_1, 1 - FROM cache.order_stock - WHERE caja < 2 - AND (Packing > Grouping or caja = 0) - UNION ALL - SELECT order_id, buy_last, warehouse_id, Id_Article, FLOOR(available/Packing), Packing, rate_2, 2 - FROM cache.order_stock - WHERE Packing > 0 - AND available > Packing - UNION ALL - SELECT order_id, buy_last, warehouse_id, Id_Article, 1, available, rate_3, 3 - FROM cache.order_stock; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_buy` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_buy`(IN v_wh TINYINT, IN v_date DATETIME) -BEGIN - DECLARE date_inv DATE; - ALTER TABLE item - ADD buy_id INT UNSIGNED; - - IF v_date < (SELECT date_inv()) THEN - SELECT MIN(landing) INTO date_inv FROM travel t INNER JOIN Entradas e ON e.travel_id = t.id - WHERE warehouse_id_out = 13 AND landing <= v_date; - ELSE - SET date_inv = date_inv(); - END IF; - UPDATE item i INNER JOIN ( - SELECT * FROM ( - SELECT c.Id_Article item_id, c.Id_Compra id - FROM Compres c INNER JOIN Entradas e USING(Id_Entrada) - INNER JOIN travel t ON t.id = e.travel_id - WHERE t.landing BETWEEN date_inv AND v_date - AND c.Novincular = FALSE - AND c.Tarifa2 >= 0 - ORDER BY v_wh = t.warehouse_id DESC, t.landing DESC - ) t - GROUP BY item_id - ) t - ON i.id = t.item_id - SET i.buy_id = t.id; - - CREATE INDEX buy USING HASH ON item (buy_id); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_buy_price` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_buy_price`(IN v_customer INT,IN date_ DATE,IN v_wh TINYINT) -BEGIN - ALTER TABLE item - ADD price DOUBLE, - ADD discount INT; - - - -- Lo primero, el precio normal, la ultima entrada para ese almacen - - UPDATE item i - JOIN Compres b ON i.buy_id = b.Id_Compra - JOIN Clientes c ON c.Id_cliente = v_customer - SET i.price = CASE c.Descuento - - WHEN 0 THEN b.PVP - WHEN 1 THEN b.Tarifa1 - WHEN 2 THEN b.Tarifa2 - WHEN 3 THEN b.Tarifa3 - ELSE IF(c.Descuento BETWEEN 4 AND 100, b.Tarifa2, round(b.Tarifa3 * (200 - c.Descuento) / 100 ,2) ) - END, - i.discount = IF(c.Descuento BETWEEN 4 AND 100, c.Descuento, 0); - - -- Precios fijados - - UPDATE item i - INNER JOIN Clientes c ON c.Id_cliente = v_customer - JOIN v_price_fixed_group fp ON i.id = fp.item_id - SET i.price = CASE c.Descuento - WHEN 0 THEN fp.rate_0 - WHEN 1 THEN fp.rate_1 - WHEN 2 THEN fp.rate_2 - WHEN 3 THEN fp.rate_3 - ELSE fp.rate_3 - END, - i.discount = 0 - WHERE fp.warehouse_id IN (0,v_wh) - AND date_ BETWEEN fp.date_start AND fp.date_end; - - -- Precios especiales - - UPDATE item i - JOIN Clientes c ON c.Id_cliente = v_customer - JOIN PreciosEspeciales p ON i.id = p.Id_Article AND p.Id_Cliente = v_customer - SET i.price = p.PrecioEspecial, - i.discount = 0; - - -- Precio mínimo - - UPDATE item i - JOIN Articles a ON a.Id_Article = i.id - JOIN Clientes c ON c.Id_cliente = v_customer - SET i.price = IF(a.`Min` AND i.price < a.PVP, a.PVP,i.price); - --- pak 14/9/14 provisional - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_cache_cleaner` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_cache_cleaner`() -BEGIN - DECLARE v_lifetime INT DEFAULT 80; - DECLARE v_expired DATETIME DEFAULT TIMESTAMPADD(SECOND, -v_lifetime, NOW()); - - IF (SELECT MAX(id) FROM`cache`) < 32000 - THEN - UPDATE `cache` SET age = age + 1 WHERE stamp < v_expired ORDER BY age DESC; - - DELETE FROM `cache` WHERE stamp < TIMESTAMPADD(SECOND, -40, v_expired); - - IF ROW_COUNT() > 0 - THEN - DELETE a - FROM cache_a a - LEFT JOIN `cache` c ON c.id = a.cache_id - WHERE c.id IS NULL; - END IF; - ELSE - TRUNCATE TABLE `cache`; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_catalog` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_catalog`( - v_wh INT - ,v_date DATE - ,v_customer INT -) -BEGIN - DECLARE v_cache SMALLINT; - - CALL item_cache (v_cache, 'a', v_wh, v_date); - - DROP TEMPORARY TABLE IF EXISTS item_catalog; - - CREATE TEMPORARY TABLE item_catalog - (KEY (item_id)) - ENGINE = MEMORY - SELECT - b.item_id - ,b.available - ,b.fixed - ,IFNULL(p.PrecioEspecial,( - CASE c.Descuento - WHEN 0 THEN b.rate_0 - WHEN 1 THEN b.rate_1 - WHEN 2 THEN b.rate_2 - WHEN 3 THEN b.rate_3 - ELSE NULL - END - )) AS price - ,be.S1 s1 - ,be.S2 s2 - ,0 discount - ,CASE co.caja WHEN 0 THEN 1 WHEN 2 THEN co.packing ELSE co.grouping END AS grouping - FROM cache_a b - JOIN Clientes c - ON c.Id_cliente = v_customer - JOIN Articles a - ON a.Id_Article = b.item_id - JOIN Tipos t - ON t.tipo_id = a.tipo_id - JOIN reinos r - ON r.id = t.reino_id - JOIN Compres co - ON co.Id_Compra = b.buy_id - LEFT JOIN buy_edi be - ON be.id = co.buy_edi_id - LEFT JOIN PreciosEspeciales p - ON p.Id_Cliente = v_customer AND b.item_id = p.Id_Article - WHERE b.available > 0 AND b.cache_id = v_cache; - -- ON be.compra_id = co.compra_id - -- Cliente Te gustan las flores - - IF NOT v_customer = 3064 - THEN - DELETE c - FROM item_catalog c - JOIN Articles ON item_id = Id_Article - WHERE tipo_id = 105; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_express` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_express`(IN intWH INT, IN datFEC DATE) -BEGIN - -DECLARE datINV DATE; - - - -SELECT FechaInventario INTO datINV FROM tblContadores LIMIT 1; - - -SELECT sub1.Id_Article, Visible, Tarifa2 -FROM -(SELECT Id_Article, SUM(Cantidad) as Visible -FROM Compres C -JOIN Entradas E USING(Id_Entrada) -JOIN travel T ON T.id = E.travel_id -WHERE shipment >= datINV -AND landing <= datFEC -AND Redada = 0 -AND warehouse_id = intWH -GROUP BY Id_Article) sub1 -JOIN -( -SELECT * FROM -( -SELECT Id_Article, Tarifa2 -FROM Compres C -JOIN Entradas E USING(Id_Entrada) -JOIN travel T ON T.id = E.travel_id -WHERE shipment >= datINV -AND landing <= datFEC -AND Redada = 0 -AND Novincular = 0 -AND warehouse_id = intWH -ORDER BY landing DESC) sub -GROUP BY Id_Article) sub2 USING(Id_Article); - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_last_buy_` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_last_buy_`(v_wh SMALLINT, v_date DATE) -BEGIN - -- Ultima compra hasta hoy - - CALL cache.last_buy_refresh (FALSE); - - - DROP TEMPORARY TABLE IF EXISTS t_item_last_buy; - CREATE TEMPORARY TABLE t_item_last_buy - (PRIMARY KEY (item_id,warehouse_id)) - ENGINE = MEMORY - SELECT item_id, buy_id, warehouse_id - FROM cache.last_buy - WHERE v_wh = warehouse_id OR v_wh IS NULL; - - - -- Ultima compra hasta @v_date - - - -- CALL item_last_buy_from_interval (v_wh, CURDATE(), TIMESTAMPADD(DAY, 1, v_date)); JGF 2016-06-08 fallo: cogia un dia mas de lo solicitado - CALL item_last_buy_from_interval (v_wh, CURDATE(), v_date); - - REPLACE INTO t_item_last_buy - SELECT item_id, buy_id, warehouse_id - FROM tmp.item_last_buy_from_interval - WHERE v_wh = warehouse_id OR v_wh IS NULL; - - - DROP TEMPORARY TABLE tmp.item_last_buy_from_interval; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_last_buy_from_interval` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_last_buy_from_interval`(v_wh SMALLINT, v_date_ini DATE, v_date_end DATE) -BEGIN -/** - * Obtiene la ultima compra a partir de un intervalo - * de fechas dado. - * - * @param v_wh Id de almacen %NULL para todos los almacenes - * @param v_date_ini Fecha inicial - * @param v_date_end Fecha final - * @table tmp.item_last_buy_from_interval - **/ - IF v_date_end IS NULL - THEN - SET v_date_end = v_date_ini; - END IF; - - - IF v_date_end < v_date_ini THEN - SET v_date_ini = TIMESTAMPADD(MONTH,-1,v_date_end); - END IF; - - DROP TEMPORARY TABLE IF EXISTS tmp.item_last_buy_from_interval; - CREATE TEMPORARY TABLE tmp.item_last_buy_from_interval - ENGINE = MEMORY - SELECT c.Id_Article item_id, t.warehouse_id, multimax(t.landing, c.Id_Compra) buy_id, MAX(t.landing) landing - FROM Compres c - JOIN Entradas e USING (Id_Entrada) - JOIN travel t ON t.id = e.travel_id - WHERE t.landing BETWEEN v_date_ini AND v_date_end - AND (v_wh IS NULL OR t.warehouse_id = v_wh) - AND c.Tarifa2 > 0 - AND NOT c.Novincular - GROUP BY item_id, warehouse_id; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_new` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_new`() -BEGIN - CREATE TEMPORARY TABLE item - ( - item_id INT UNSIGNED NOT NULL, - UNIQUE KEY USING HASH (item_id) - ) - ENGINE = MEMORY; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_stock` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_stock`(v_wh SMALLINT, v_date DATETIME, v_item INT) -BEGIN -/** - * Calcula el stock del v_wh desde FechaInventario hasta v_date - **/ - - DECLARE n TINYINT; - DECLARE v_diff TIME; - DECLARE v_inv DATETIME; - DECLARE v_camp DATETIME; - DECLARE v_curdate DATETIME DEFAULT CURDATE(); - - SET v_date = TIMESTAMP(DATE(v_date), '00:00:00'); - - SELECT FechaInventario, TIMESTAMPADD(DAY, -campaign_life, campaign) - INTO v_inv, v_camp FROM tblContadores LIMIT 1; - - DROP TEMPORARY TABLE IF EXISTS tmp_item; - CREATE TEMPORARY TABLE tmp_item - (UNIQUE INDEX i USING HASH (item_id)) - ENGINE = MEMORY - SELECT item_id, SUM(amount) stock, SUM(amount) visible, SUM(amount) available FROM ( - SELECT item_id, amount FROM item_out - WHERE dat >= v_curdate AND dat < v_date - AND warehouse_id = v_wh - AND (v_item IS NULL OR item_id = v_item) - UNION ALL - SELECT item_id, amount FROM item_entry_in - WHERE dat >= v_curdate AND dat < v_date - AND warehouse_id = v_wh - AND (v_item IS NULL OR item_id = v_item) - UNION ALL - SELECT item_id, amount FROM item_entry_out - WHERE dat >= v_curdate AND dat < v_date - AND warehouse_id = v_wh - AND (v_item IS NULL OR item_id = v_item) - ) t - GROUP BY item_id HAVING stock != 0; - - CALL `cache`.stock_refresh (FALSE); - - INSERT INTO tmp_item (item_id,stock,visible,available) - SELECT item_id,amount,amount,amount FROM `cache`.stock - WHERE warehouse_id = v_wh AND (v_item IS NULL OR v_item = item_id) - ON DUPLICATE KEY UPDATE - stock = stock + VALUES(stock), - visible = visible + VALUES(visible), - available = available + VALUES(available); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_stock_avail` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_stock_avail`(IN v_wh TINYINT, IN v_date DATETIME, IN id_single INT,IN direccion TINYINT) -BEGIN - DECLARE done INT DEFAULT 0; - DECLARE expr,expr1,expr2,expr3,expr4,expr5 TEXT; - DECLARE query TEXT; - DECLARE _son,_self TEXT; - DECLARE _auxshipment, _auxlanding,fut DATE; - -- Selecciona tots els travels cap als fill ens els próxims 15 dies - DECLARE cur1 CURSOR FOR - SELECT shipment,landing FROM travel WHERE warehouse_id_out = v_wh AND shipment BETWEEN TIMESTAMPADD(day,1,v_date) - AND TIMESTAMPADD(day,15,v_date) AND warehouse_id = (SELECT son FROM warehouse_tree_bidi WHERE father = v_wh - LIMIT 1) - ORDER BY shipment; - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - -- selecciona els primers travels que arrivaran després de la v_date de cada warehouse - - CALL item_travel (v_wh, v_date); - - SET expr = sql_printf ('dat BETWEEN DATE(%v) AND DATE(%v)' - ,TIMESTAMP(v_date, '00:00:00') - ,TIMESTAMP(TIMESTAMPADD(DAY, 15, v_date), '23:59:59') - /*,v_wh*/ - ); - - - IF id_single IS NOT NULL THEN - SET expr = sql_printf('%s AND item_id = %v' - ,expr - ,id_single - ); - END IF; - - SET expr1 = sql_printf ('%s AND warehouse_id = %v ' - ,expr - ,v_wh - ); - SET expr2 = ''; - SET _self = CONCAT(v_wh, 'virtual'); - - -- crea una taula amb el nom del warehousevirtual - CALL sql_query (sql_printf('CREATE TEMPORARY TABLE IF NOT EXISTS vn2008.%t - ( - item_id INT(11), - dat DATE, - amount DOUBLE(8,2), - PRIMARY KEY(item_id,dat) - ) - ENGINE = MEMORY;',_self)); - -- si esta mirant els pares li añadeix el virtual que pot arrivar a conseguir - IF direccion >= 0 THEN - SET expr2 = sql_printf (' UNION ALL - SELECT item_id, dat, amount - FROM vn2008.%t WHERE %s' - ,_self - ,expr - ); - END IF; - - ALTER TABLE tmp_item ADD future DATE; - - /*jgf afegeix AND Reservado != 0 */ - -- calcula el mínim disponible fins a la próxima arrivada de mercancia -SET query = sql_printf ( - 'INSERT INTO tmp_item (item_id,available, future) - SELECT item_id, SUM(amount) AS available,landing as future FROM ( - SELECT t.item_id, minacum(dt, amount, %v) amount,w.landing FROM ( - SELECT item_id, DATE(dat) dt, SUM(amount) amount FROM ( - SELECT item_id, dat, amount - FROM item_out WHERE %s - UNION ALL - SELECT item_id, dat, amount - FROM item_entry_in WHERE %s - UNION ALL - SELECT item_id, dat, amount - FROM item_entry_out WHERE %s - %s - ) t - GROUP BY item_id, dt - ) t - LEFT JOIN Articles a ON a.Id_Article = t.item_id - LEFT JOIN Origen o ON o.id = a.id_origen - LEFT JOIN item_travel w ON w.wh = o.warehouse_id - WHERE IFNULL(dt < w.landing OR Id_Article > 170000, TRUE) - GROUP BY t.item_id - ) t - GROUP BY t.item_id HAVING available != 0 - ON DUPLICATE KEY UPDATE - available = IFNULL(available,0) + VALUES(available)' - , DATE(v_date) + 0, expr1, expr1, expr1, expr2 - ); - -- JGF 22/10/14 - WHERE IFNULL(dt <= w.landing OR Id_Article > 170000, TRUE) - -- JGF 2015-03-31 ANTES WHERE IFNULL(dt <= w.landing OR Id_Article > 170000, TRUE) - CALL sql_query (query); - -- si el v_wh es pare - IF (direccion > 0) THEN - - -- crea una taula TEMPORAL per al fill - SELECT CONCAT(son,'virtual') A INTO _son FROM warehouse_tree_bidi WHERE father = v_wh LIMIT 1; - CALL sql_query (sql_printf('CREATE TEMPORARY TABLE IF NOT EXISTS vn2008.%t - ( - item_id INT(11), - dat DATE, - amount DOUBLE(8,2), - PRIMARY KEY(item_id,dat) - ) - ENGINE = MEMORY;',_son)); - IF (direccion >= 2) THEN - CALL sql_query (query); - SET query = sql_printf ( -- REPLACE en lugar de INSERT INTO PAK 20/11/14 - 'REPLACE vn2008.%t (item_id,dat,amount) - SELECT item_id,landing,available FROM tmp_item,travel - WHERE shipment = DATE(%v) AND warehouse_id_out = %v AND available > 0 - AND warehouse_id = (SELECT son FROM warehouse_tree_bidi WHERE father = %v - LIMIT 1) GROUP BY warehouse_id - ',_son,v_date,v_wh,v_wh); - - CALL sql_query (query); - - TRUNCATE TABLE tmp_item; - END IF; - OPEN cur1; - FETCH cur1 INTO _auxshipment,_auxlanding; - WHILE !done DO - SET expr4 = sql_printf ('dat BETWEEN %v AND %v' - ,TIMESTAMP(DATE(_auxshipment), '00:00:00') - ,TIMESTAMP(TIMESTAMPADD(DAY, 15, v_date), '23:59:59') - ); - IF id_single IS NOT NULL THEN - SET expr4 = sql_printf('%s AND item_id = %v' - ,expr4 - ,id_single - ); - END IF; - - SET expr5 = sql_printf ('%s AND warehouse_id = %v' - ,expr4 - ,v_wh - ); - -- afegir entrades menys eixides desde l'ultim dia.. - SET query = sql_printf ( - 'INSERT INTO vn2008.%t (item_id,dat,amount) - SELECT item_id, %v, SUM(amount) AS available FROM ( - SELECT t.item_id, minacum(dt, amount, %v) amount FROM ( - SELECT item_id, DATE(dat) dt, SUM(amount) amount FROM ( - SELECT item_id, dat, amount - FROM item_out WHERE %s - UNION ALL - SELECT item_id, dat, amount - FROM item_entry_in WHERE %s - UNION ALL - SELECT item_id, dat, amount - FROM item_entry_out WHERE %s - UNION ALL - SELECT item_id, dat, amount - FROM %t WHERE %s - ) t - GROUP BY item_id, dt - ) t - LEFT JOIN Articles a ON a.Id_Article = t.item_id - LEFT JOIN Origen o ON o.id = a.id_origen - LEFT JOIN item_travel w ON w.wh = o.warehouse_id - WHERE IFNULL(dt < w.landing OR Id_Article > 170000, TRUE) - GROUP BY t.item_id - ) t GROUP BY t.item_id HAVING available > 0 - ON DUPLICATE KEY UPDATE - amount = IFNULL(amount,0) + VALUES(amount) - ',_son,DATE(_auxlanding)+0,DATE(_auxshipment)+0,expr5, expr5, expr5,_self,expr4); - -- JGF 07/07/14 - WHERE IFNULL(dt < w.landing , TRUE) - CALL sql_query (query); - FETCH cur1 INTO _auxshipment,_auxlanding; - END WHILE; - - CLOSE cur1; - END IF; - CALL sql_query (sql_printf('DROP TEMPORARY TABLE IF EXISTS %t;',_self)); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_stock_avail_new` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_stock_avail_new`(IN v_wh TINYINT, IN v_date DATETIME, IN id_single INT,IN direccion TINYINT) -BEGIN - DECLARE done INT DEFAULT 0; - DECLARE expr,expr1,expr2,expr3,expr4,expr5 TEXT; - DECLARE query TEXT; - DECLARE _son,_self TEXT; - DECLARE _auxshipment, _auxlanding,fut DATE; - - -- Selecciona tots els viajes cap als fill ens els próxims 15 dies - - DECLARE cur1 CURSOR FOR - SELECT shipment,landing FROM travel - WHERE warehouse_id_out = v_wh - AND shipment BETWEEN TIMESTAMPADD(day,1,v_date) - AND TIMESTAMPADD(day,15,v_date) - AND warehouse_id = (SELECT son FROM warehouse_tree_bidi WHERE father = v_wh LIMIT 1) - ORDER BY shipment; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - - -- Selecciona els primers viajes que arrivaran després de la v_date de cada almacen - - CALL item_travel (v_wh, v_date); - - SET expr = sql_printf ('dat BETWEEN DATE(%v) AND DATE(%v)' - ,TIMESTAMP(v_date, '00:00:00') - ,TIMESTAMP(TIMESTAMPADD(DAY, 15, v_date), '23:59:59') - ); - - IF id_single IS NOT NULL - THEN - SET expr = sql_printf('%s AND item_id = %v' - ,expr - ,id_single - ); - END IF; - - SET expr1 = sql_printf ('%s AND warehouse_id = %v ' - ,expr - ,v_wh - ); - SET expr2 = ''; - SET _self = CONCAT(v_wh, 'virtual'); - - -- Crea una taula amb el nom del almacen virtual - - CALL sql_query (sql_printf('CREATE TEMPORARY TABLE IF NOT EXISTS vn2008.%t - ( - item_id INT(11), - dat DATE, - amount DOUBLE(8,2), - PRIMARY KEY(item_id,dat) - ) - ENGINE = MEMORY',_self)); - - -- Si esta mirant els pares li añadeix el virtual que pot arrivar a conseguir - - IF direccion >= 0 - THEN - SET expr2 = sql_printf (' UNION ALL - SELECT item_id, dat, amount - FROM vn2008.%t WHERE %s' - ,_self - ,expr - ); - END IF; - - ALTER TABLE tmp_item ADD future DATE; - - -- Calcula el mínim disponible fins a la próxima arrivada de mercancia - - SET query = sql_printf ( - 'INSERT INTO tmp_item (item_id, available, future) - SELECT item_id, SUM(amount) AS available,landing as future FROM ( - SELECT t.item_id, minacum(dt, amount, %v) amount,w.landing FROM ( - SELECT item_id, DATE(dat) dt, SUM(amount) amount FROM ( - SELECT item_id, dat, amount - FROM item_out WHERE %s - UNION ALL - SELECT item_id, dat, amount - FROM item_entry_in WHERE %s - UNION ALL - SELECT item_id, dat, amount - FROM item_entry_out WHERE %s - %s - ) t - GROUP BY item_id, dt - ) t - LEFT JOIN Articles a ON a.Id_Article = t.item_id - LEFT JOIN Origen o ON o.id = a.id_origen - LEFT JOIN item_travel w ON w.wh = o.warehouse_id - WHERE IFNULL(dt <= w.landing OR Id_Article > 170000, TRUE) - GROUP BY t.item_id - ) t - GROUP BY t.item_id HAVING available != 0 - ON DUPLICATE KEY UPDATE - available = IFNULL(available,0) + VALUES(available)' - ,DATE(v_date)+0 - ,expr1 - ,expr1 - ,expr1 - ,expr2 - ); - CALL sql_query (query); - - -- Si es el almacen padre - - IF (direccion > 0) - THEN - -- Crea una tabla temporar pare el hijo - SELECT CONCAT(son,'virtual') A INTO _son FROM warehouse_tree_bidi WHERE father = v_wh LIMIT 1; - - CALL sql_query (sql_printf( - 'CREATE TEMPORARY TABLE IF NOT EXISTS vn2008.%t - ( - item_id INT(11), - dat DATE, - amount DOUBLE(8,2), - PRIMARY KEY(item_id,dat) - ) - ENGINE = MEMORY;', - _son - )); - - IF (direccion >= 2) - THEN - CALL sql_query (query); - CALL sql_query (sql_printf ( - 'REPLACE vn2008.%t (item_id,dat,amount) - SELECT item_id, landing, available FROM tmp_item, travel - WHERE shipment = DATE(%v) AND warehouse_id_out = %v AND available > 0 - AND warehouse_id = (SELECT son FROM warehouse_tree_bidi WHERE father = %v LIMIT 1) - GROUP BY warehouse_id' - ,_son - ,v_date - ,v_wh - ,v_wh - )); - TRUNCATE TABLE tmp_item; - END IF; - - OPEN cur1; - FETCH cur1 INTO _auxshipment,_auxlanding; - - WHILE !done - DO - SET expr4 = sql_printf ('dat BETWEEN %v AND %v' - ,TIMESTAMP(DATE(_auxshipment), '00:00:00') - ,TIMESTAMP(TIMESTAMPADD(DAY, 15, v_date), '23:59:59') - ); - - IF id_single IS NOT NULL - THEN - SET expr4 = sql_printf('%s AND item_id = %v' - ,expr4 - ,id_single - ); - END IF; - - SET expr5 = sql_printf ('%s AND warehouse_id = %v' - ,expr4 - ,v_wh - ); - - -- Afegir entrades menys eixides desde l'ultim dia - - CALL sql_query (sql_printf ( - 'INSERT INTO vn2008.%t (item_id,dat,amount) - SELECT item_id, %v, SUM(amount) AS available FROM ( - SELECT t.item_id, minacum(dt, amount, %v) amount FROM ( - SELECT item_id, DATE(dat) dt, SUM(amount) amount FROM ( - SELECT item_id, dat, amount - FROM item_out WHERE %s - UNION ALL - SELECT item_id, dat, amount - FROM item_entry_in WHERE %s - UNION ALL - SELECT item_id, dat, amount - FROM item_entry_out WHERE %s - UNION ALL - SELECT item_id, dat, amount - FROM %t WHERE %s - ) t - GROUP BY item_id, dt - ) t - LEFT JOIN Articles a ON a.Id_Article = t.item_id - LEFT JOIN Origen o ON o.id = a.id_origen - LEFT JOIN item_travel w ON w.wh = o.warehouse_id - WHERE IFNULL(dt < w.landing OR Id_Article > 170000, TRUE) - GROUP BY t.item_id - ) t GROUP BY t.item_id HAVING available > 0 - ON DUPLICATE KEY UPDATE - amount = IFNULL(amount,0) + VALUES(amount)' - ,_son - ,DATE(_auxlanding)+0 - ,DATE(_auxshipment)+0 - ,expr5 - ,expr5 - ,expr5 - ,_self - ,expr4 - )); - - FETCH cur1 INTO _auxshipment,_auxlanding; - END WHILE; - - CLOSE cur1; - END IF; - - CALL sql_query (sql_printf('DROP TEMPORARY TABLE IF EXISTS %t', _self)); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_stock_visible` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_stock_visible`(v_wh SMALLINT, v_item INT) -BEGIN - DECLARE v_curdate DATETIME DEFAULT TIMESTAMP(CURDATE(), '00:00:00'); - DECLARE v_tomorrow DATETIME DEFAULT TIMESTAMPADD(HOUR, 24, CURDATE()); - - INSERT INTO tmp_item (item_id, visible) - SELECT item_id, SUM(amount) amount FROM ( - SELECT item_id, amount FROM item_out - WHERE dat >= v_curdate - AND warehouse_id = v_wh - AND (alertLevel > 1 - OR - ok != FALSE - /* AND (((ok != FALSE OR ready != FALSE OR invoice IS NOT NULL) - AND dat < v_tomorrow) - */ - OR Reservado != FALSE ) - UNION ALL - SELECT item_id, amount FROM item_entry_in - WHERE received != FALSE - AND dat >= v_curdate AND dat < v_tomorrow - AND warehouse_id = v_wh - AND (v_item IS NULL OR item_id = v_item) - UNION ALL - SELECT item_id, amount FROM item_entry_out - WHERE delivered != FALSE - AND dat >= v_curdate AND dat < v_tomorrow - AND warehouse_id = v_wh - AND (v_item IS NULL OR item_id = v_item) - ) t - GROUP BY item_id - ON DUPLICATE KEY UPDATE - visible = IFNULL(stock,0) + VALUES(visible); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_travel` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_travel`(v_wh TINYINT, v_date DATETIME) -BEGIN - DECLARE v_travel INT; - DECLARE v_wh_out INT; - DECLARE v_shipment DATETIME; - DECLARE v_campaign DATETIME; - DECLARE v_date_start DATETIME; - - DROP TEMPORARY TABLE IF EXISTS travel_top; - DROP TEMPORARY TABLE IF EXISTS item_travel; - - -- Crea una taula buida travel_top - - CREATE TEMPORARY TABLE travel_top - (PRIMARY KEY (wh_in,wh_out,landing,shipment)) -- 28/1/15 JGF & PAK cuelgue dia 26 - ENGINE = MEMORY - SELECT 0 id, v_wh wh_in, v_wh wh_out, FALSE ok, v_date landing, v_date shipment; - - REPEAT - SET v_travel = NULL; - - -- Va seleccionant registres un a un - - SELECT id, wh_out, shipment, landing - INTO v_travel, v_wh_out, v_shipment, v_date_start - FROM travel_top WHERE ok = FALSE LIMIT 1; - - -- Marca el registre per a saber que esta revistat - - UPDATE travel_top SET ok = TRUE WHERE id = v_travel; - - -- Concatena travels - - - INSERT IGNORE INTO travel_top - SELECT id, v_wh, warehouse_id_out, FALSE, IF(v_travel, v_date_start, landing), shipment - FROM travel - WHERE warehouse_id = v_wh_out - -- Canvia Javi 08/04/13 error que pasaba a les 06:00 del mati - -- AND IF(v_travel, landing <= v_shipment, landing > v_shipment) - AND IF(v_travel, landing <= v_shipment, landing >= v_shipment) - AND shipment >= CURDATE() - AND delivered = FALSE; - - UNTIL v_travel IS NULL - END REPEAT;/* - select max_count; - SELECT * FROM travel_top;*/ - - DELETE FROM travel_top WHERE id = 0; -/* - SELECT TIMESTAMPADD(DAY, -campaign_life, campaign), campaign - INTO v_date_start, v_campaign FROM tblContadores;*/ - - -- Agafa el travel que arriva primer per a cada warehouse - - CREATE TEMPORARY TABLE item_travel - (KEY (wh)) - ENGINE = MEMORY - SELECT * FROM ( - SELECT wh_out wh,/* IF( - v_date BETWEEN v_date_start AND v_campaign - AND landing BETWEEN v_date_start AND v_campaign - ,TIMESTAMPADD(DAY, 1, v_campaign) - ,landing - ) */landing - FROM travel_top - WHERE wh_out <> v_wh - ORDER BY landing - ) t - GROUP BY wh; --- SELECT * FROM item_travel; - DROP TEMPORARY TABLE travel_top; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_travel_fixed` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_travel_fixed`(v_wh TINYINT, v_date DATETIME) -BEGIN - DECLARE v_travel INT; - DECLARE v_wh_out INT; - DECLARE v_shipment DATETIME; - DECLARE v_campaign DATETIME; - DECLARE v_date_start DATETIME; - - DROP TEMPORARY TABLE IF EXISTS travel_top; - DROP TEMPORARY TABLE IF EXISTS item_travel_fixed; - - CREATE TEMPORARY TABLE travel_top - (KEY (id)) - ENGINE = MEMORY - SELECT 0 id, v_wh wh_out, v_date shipment; - - REPEAT - SET v_travel = NULL; - - SELECT t.id, wh_out, shipment - INTO v_travel, v_wh_out, v_shipment - FROM travel_top t - JOIN warehouse w ON w.id = wh_out AND fuente = 0 - LIMIT 1; - - INSERT INTO travel_top - SELECT t.id, warehouse_id_out, shipment/*, FALSE*/ - FROM travel t - WHERE warehouse_id = v_wh_out - AND landing <= v_shipment - AND shipment >= CURDATE() - AND NOT delivered; - - DELETE t - FROM travel_top t - JOIN warehouse w ON w.id = wh_out - WHERE t.id = v_travel AND fuente = 0; - UNTIL v_travel IS NULL - END REPEAT; - - - SELECT TIMESTAMPADD(DAY, -campaign_life, campaign), campaign - INTO v_date_start, v_campaign FROM tblContadores; - - CREATE TEMPORARY TABLE item_travel_fixed - (KEY (wh)) - ENGINE = MEMORY - SELECT * FROM - ( - SELECT wh_out wh - FROM travel_top - WHERE wh_out <> v_wh - ) t - GROUP BY wh; - - DROP TEMPORARY TABLE travel_top; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_travel_select` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_travel_select`(v_wh TINYINT, v_date DATETIME) -BEGIN - DECLARE v_travel INT; - DECLARE v_wh_out INT; - DECLARE v_shipment DATETIME; - DECLARE v_campaign DATETIME; - DECLARE v_date_start DATETIME; - - DROP TEMPORARY TABLE IF EXISTS travel_top; - DROP TEMPORARY TABLE IF EXISTS item_travel; - - -- Crea una taula buida travel_top - - CREATE TEMPORARY TABLE travel_top - (PRIMARY KEY (id)) - ENGINE = MEMORY - SELECT 0 id, v_wh wh_in, v_wh wh_out, FALSE ok, v_date landing, v_date shipment; - - REPEAT - SET v_travel = NULL; - - -- Va seleccionant registres un a un - - SELECT id, wh_out, shipment, landing - INTO v_travel, v_wh_out, v_shipment, v_date_start - FROM travel_top WHERE ok = FALSE LIMIT 1; - - -- Marca el registre per a saber que esta revistat - - UPDATE travel_top SET ok = TRUE WHERE id = v_travel; - - -- Concatena travels cap al pasat - - INSERT IGNORE INTO travel_top - SELECT id, v_wh, warehouse_id_out, FALSE, IF(v_travel, v_date_start, landing), shipment - FROM travel - WHERE warehouse_id = v_wh_out - AND IF(v_travel, landing <= v_shipment, landing > v_shipment) - AND shipment >= CURDATE() - AND delivered = FALSE; - - UNTIL v_travel IS NULL - END REPEAT; - - DELETE FROM travel_top WHERE id = 0; - - SELECT TIMESTAMPADD(DAY, -campaign_life, campaign), campaign - INTO v_date_start, v_campaign FROM tblContadores; - - -- Agafa el travel que arriva primer per a cada warehouse - - CREATE TEMPORARY TABLE item_travel - (KEY (wh)) - ENGINE = MEMORY - SELECT * FROM ( - SELECT wh_out wh, IF( - v_date BETWEEN v_date_start AND v_campaign - AND landing BETWEEN v_date_start AND v_campaign - ,TIMESTAMPADD(DAY, 1, v_campaign) - ,landing - ) landing - FROM travel_top - WHERE wh_out <> v_wh - ORDER BY landing - ) t - GROUP BY wh; - - SELECT * FROM item_travel; - DROP TEMPORARY TABLE travel_top; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_travel_testing` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_travel_testing`(v_wh TINYINT, v_date DATETIME) -BEGIN - DECLARE v_travel INT; - DECLARE v_wh_out INT; - DECLARE v_shipment DATETIME; - DECLARE v_campaign DATETIME; - DECLARE v_date_start DATETIME; - - - - DROP TEMPORARY TABLE IF EXISTS travel_top; - DROP TEMPORARY TABLE IF EXISTS item_travel; - - -- Crea una taula buida travel_top - - drop temporary table if exists travels_list; - create temporary table travels_list - (id integer, shipment date, landing date, warehouse_id int, warehouse_id_out int); - - CREATE TEMPORARY TABLE travel_top - -- (PRIMARY KEY (wh_in,wh_out,landing,shipment) ) - ENGINE = MEMORY - SELECT 0 RODA, 0 ORDRE, 0 son_id, 0 id, v_wh wh_in, v_wh wh_out, FALSE ok, v_date landing, v_date shipment; - - SET @rodaeta:= 0; - - REPEAT - SET v_travel = -1; - - - -- Va seleccionant registres un a un - - SELECT id, wh_out, shipment, landing - INTO v_travel, v_wh_out, v_shipment, v_date_start - FROM travel_top WHERE ok = FALSE - LIMIT 1; - - -- Marca el registre per a saber que esta revistat - - UPDATE travel_top SET ok = TRUE WHERE id = v_travel; - - -- Concatena travels - SET @ordre := 0; - - INSERT INTO travel_top - SELECT -7 , @ordre:= @ordre + 1 , v_travel ,id, v_wh, warehouse_id_out, FALSE, IF(v_travel>0, v_date_start, landing), shipment - FROM travel - WHERE warehouse_id = v_wh_out - AND IF(v_travel>0, landing <= v_shipment, landing >= v_shipment) - AND shipment >= '2005-01-26' and shipment < '2005-02-28' - AND delivered = FALSE; - - IF (SELECT Count(*) FROM travel_top WHERE RODA = -7) THEN - SET @rodaeta:= @rodaeta + 1; - update travel_top set RODA = @rodaeta where RODA = -7; - end if; - - INSERT INTO travels_list - SELECT id, shipment, landing, warehouse_id, warehouse_id_out - FROM travel - WHERE warehouse_id = v_wh_out - AND IF(v_travel>0, landing <= v_shipment, landing >= v_shipment) - AND shipment >= '2005-01-26' and shipment < '2005-02-28' - AND delivered = FALSE; - - -UNTIL v_travel = -1 END REPEAT; - - - - /* - select max_count; - SELECT * FROM travel_top;*/ - - /*DELETE FROM travel_top WHERE id = 0;*/ -/* - SELECT TIMESTAMPADD(DAY, -campaign_life, campaign), campaign - INTO v_date_start, v_campaign FROM tblContadores;*/ - - -- Agafa el travel que arriva primer per a cada warehouse - - CREATE TEMPORARY TABLE item_travel - (KEY (wh)) - ENGINE = MEMORY - SELECT * FROM ( - SELECT wh_out wh,/* IF( - v_date BETWEEN v_date_start AND v_campaign - AND landing BETWEEN v_date_start AND v_campaign - ,TIMESTAMPADD(DAY, 1, v_campaign) - ,landing - ) */landing - FROM travel_top - WHERE wh_out <> v_wh - ORDER BY landing - ) t - GROUP BY wh; - -SELECT * FROM item_travel; -SELECT * FROM travel_top order by RODA, ORDRE; - - DROP TEMPORARY TABLE travel_top; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ListaTicketsEncajados` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ListaTicketsEncajados`(IN intId_Trabajador int) -BEGIN - -SELECT Agencia,Consignatario, ti.Id_Ticket, ts.worker Id_Trabajador,IFNULL(ncajas,0) AS ncajas, -IFNULL(nbultos,0) AS nbultos,IFNULL(notros,0) AS notros,code AS Estado -FROM Tickets ti -INNER JOIN Consignatarios ON ti.Id_Consigna = Consignatarios.Id_consigna -INNER JOIN Agencias ON ti.Id_Agencia = Agencias.Id_Agencia -LEFT JOIN (select Ticket_Id,count(*) as ncajas from expeditions where Id_Article=94 group by ticket_id) sub1 on ti.Id_Ticket=sub1.Ticket_Id -LEFT JOIN (select Ticket_Id,count(*) as nbultos from expeditions where Id_Article is null group by ticket_id) sub2 on ti.Id_Ticket=sub2.Ticket_Id -LEFT JOIN (select Ticket_Id,count(*) as notros from expeditions where Id_Article >0 group by ticket_id) sub3 on ti.Id_Ticket=sub3.Ticket_Id -INNER JOIN vn.ticketState ts ON ti.Id_ticket = ts.ticket -WHERE ti.Fecha=curdate() and -ts.worker=intId_Trabajador -group by ti.Id_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 DROP PROCEDURE IF EXISTS `malpagantes` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `malpagantes`() -BEGIN - -set @cliente := 0; -set @saldo := 0; - -Select Id_Cliente, Cliente from -Clientes -join -(select distinct Id_Cliente -from Facturas -where Fecha > '2015-01-01') cli using(Id_Cliente) -left join -( -select distinct Id_Cliente -from -( -select Fecha - , @saldo := IF(@cliente = Id_Cliente, @saldo + Importe, Importe) Saldo - , @cliente := Id_Cliente as Id_Cliente -from -( -select Id_Cliente, Fecha, Importe from - -( -select Id_Cliente, -1 * Importe Importe, Fecha -from Facturas -union all -select Id_Cliente, Entregado, Fechacobro -from Recibos -) sub -order by Id_Cliente, Fecha -) sub2 -) sub3 -where Saldo > -1 -and Fecha > '2015-01-01' - -) sub4 using(Id_Cliente) -where sub4.Id_Cliente is null; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `manaEraser` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `manaEraser`(vTicket INT) -BEGIN - - DECLARE vComponentOld INT; - DECLARE vComponentNew INT; - - SELECT Id_Componente - INTO vComponentOld - FROM tarifa_componentes - WHERE Componente = 'maná'; - - SELECT Id_Componente - INTO vComponentNew - FROM tarifa_componentes - WHERE Componente = 'rebaja manual'; - - UPDATE Movimientos_componentes mc - JOIN Movimientos m using(Id_Movimiento) - SET mc.Id_Componente = vComponentNew - WHERE mc.Id_Componente = vComponentOld - AND m.Id_Ticket = vTicket; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `manaRequery` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `manaRequery`(worker INTEGER) -BEGIN - - DECLARE workerIsExcluded BOOLEAN; - DECLARE MyFechaDesde DATE; - - SELECT COUNT(*) INTO workerIsExcluded - FROM bs.mana_spellers_excluded - WHERE Id_Trabajador = worker; - - IF NOT workerIsExcluded THEN - - SELECT max(dated) INTO MyFechaDesde - FROM bs.manaCustomer; - - REPLACE bs.mana_spellers (Id_Trabajador, used) - SELECT worker, sum(mana) FROM - ( - SELECT Cantidad * Valor as mana - FROM vn2008.Tickets t - JOIN Consignatarios cs using(Id_Consigna) - JOIN Clientes c on c.Id_Cliente = cs.Id_Cliente - JOIN Movimientos m using(Id_Ticket) - JOIN Movimientos_componentes mc using(Id_Movimiento) - WHERE c.Id_Trabajador = worker AND Id_Componente IN (39, 37) -- maná auto y maná - AND Fecha > MyFechaDesde - - UNION ALL - - SELECT - Entregado - FROM Recibos r - JOIN Clientes c using(Id_Cliente) - WHERE c.Id_Trabajador = worker AND Id_Banco = 66 - AND Fechacobro > MyFechaDesde - - UNION ALL - - SELECT g.Importe - FROM Greuges g - JOIN Clientes c using(Id_Cliente) - WHERE c.Id_Trabajador = worker AND Greuges_type_id = 3 -- Maná - AND Fecha > MyFechaDesde - - UNION ALL - - SELECT mana - FROM bs.manaCustomer mc - JOIN vn2008.Clientes c ON c.Id_Cliente = mc.Id_Cliente - WHERE c.Id_Trabajador = worker AND dated = MyFechaDesde - ) sub; - - END IF; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `mana_list` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `mana_list`(IN str VARCHAR(3)) -BEGIN - -DECLARE idT INT; - -IF ASCII(str) between 48 and 57 THEN -- el chr(48) es el 0 y el chr(57) es el 9. De ese modo se comprueba si es un numero o un carácter de texto - - SET idT = cast(str as signed); - -ELSE - - SELECT Id_Trabajador INTO idT - FROM Trabajadores - WHERE CodigoTrabajador = str; - -END IF; - - -SELECT * FROM -( -SELECT Id_Ticket - , Alias - , t.Fecha as FechaTicket - , m.odbc_date as FechaAccion - , Id_Article - , CONCAT(IF(Id_Componente = 39, 'Auto: ',''),Concepte) Concepte - , Cantidad - , round(Valor,2) as Valor - , round(Cantidad * Valor,2) as MANA - FROM Movimientos_componentes mc - JOIN Movimientos m using(Id_Movimiento) - JOIN Tickets t using(Id_Ticket) - JOIN Consignatarios cs using(Id_Consigna) - JOIN Clientes c on c.Id_Cliente = cs.Id_Cliente - WHERE c.Id_Trabajador = idT - AND Id_Componente IN (39, 37) - and t.Fecha > TIMESTAMPADD(WEEK,-1,CURDATE()) - - UNION ALL - -SELECT NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL - - UNION ALL - -SELECT c.Id_Cliente, Cliente, r.FechaCobro, r.odbc_date, NULL, 'cobro', NULL, NULL, - Entregado - FROM Recibos r - JOIN Clientes c using(Id_Cliente) - WHERE Id_Banco = 66 -- Caja de maná - AND c.Id_Trabajador = idT - - UNION ALL - -SELECT NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL - - UNION ALL - -SELECT c.Id_Cliente, Cliente, g.Fecha, g.odbc_date, NULL, Comentario, NULL, NULL, g.Importe - FROM Greuges g - JOIN Clientes c using(Id_Cliente) - WHERE Greuges_type_id = 3 -- Maná - AND c.Id_Trabajador = idT - ) t1 -ORDER BY FechaAccion DESC; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `mana_requery` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `mana_requery`() -BEGIN - -DECLARE MyFechaDesde DATE; - -SELECT max(dated) INTO MyFechaDesde -FROM bs.manaCustomer; - - -UPDATE bs.mana_spellers - -LEFT JOIN - -( - - SELECT Id_Trabajador, sum(mana) as mana FROM - - ( - SELECT c.Id_Trabajador, Cantidad * Valor as mana - FROM Tickets t - JOIN Consignatarios cs using(Id_Consigna) - JOIN Clientes c on c.Id_Cliente = cs.Id_Cliente - JOIN Movimientos m using(Id_Ticket) - JOIN Movimientos_componentes mc using(Id_Movimiento) - WHERE Id_Componente IN (39, 37) -- maná auto y maná - AND Fecha > MyFechaDesde - - UNION ALL - - SELECT c.Id_Trabajador, - Entregado - FROM Recibos r - JOIN Clientes c using(Id_Cliente) - WHERE Id_Banco = 66 - AND Fechacobro > MyFechaDesde - - UNION ALL - - SELECT c.Id_Trabajador, g.Importe - FROM Greuges g - JOIN Clientes c using(Id_Cliente) - WHERE Greuges_type_id = 3 -- Maná - AND Fecha > MyFechaDesde - - UNION ALL - - SELECT c.Id_Trabajador, mana - FROM bs.manaCustomer mc - JOIN vn2008.Clientes c ON c.Id_Cliente = mc.Id_Cliente - WHERE dated = MyFechaDesde - ) sub - - GROUP BY Id_Trabajador - -) m using(Id_Trabajador) - -SET used = IFNULL(m.mana,0); - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `massiveTicket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `massiveTicket`( - IN dateFrom DATE, IN dateTo DATE, IN customerId INT, OUT newTicketId INT) -BEGIN -/** - * Genera un nuevo ticket con los movimientos correspondientes a los parámetros - * - * @param dateFrom Fecha mínima para los tickets - * @param dateTo Fecha máxima para los tickets - * @param customerId Cliente - * - * @return newTicketId Nuevo numero de ticket - **/ - - DECLARE inventoryWarehouse INT DEFAULT 13; - DECLARE defaultCompany INT DEFAULT 442; - DECLARE defaultWorker INT DEFAULT 20; - - CALL vn.ticketCreate ( customerId - , CURDATE() - , inventoryWarehouse - , defaultCompany - , NULL - , NULL - , NULL - , CURDATE() - , newTicketId); - - INSERT INTO Movimientos( Id_Ticket - , Id_Article - , Concepte - , Preu - , Descuento - , Cantidad) - - SELECT newTicketId - , Id_Article - , Concepte - , Preu - , Descuento - , Cantidad - FROM Movimientos m - JOIN Tickets t ON m.Id_Ticket = t.Id_Ticket - WHERE Id_Cliente = customerId - AND t.Fecha BETWEEN dateFROM AND DAYEND(dateTO); - - SELECT newTicketId; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `mensaje` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `mensaje`(IN idREM INT, IN idDES INT, IN strMSG LONGTEXT) -BEGIN - -/*DECLARE lngLASTID BIGINT;*/ - --- Caso sencillo - -INSERT INTO Mensajes(Mensaje, Fecha, Remitente, Destinatario) -VALUES(strMSG, NOW(), idREM, idDES); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `monitoring_calls` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `monitoring_calls`(IN datFEC DATE) -BEGIN - -SELECT Id_Trabajador, AVG(billsec) as Duracion, days.Fecha, Hora, SUM(Recibidas) as Entrantes, SUM(Emitidas) as Salientes -FROM -( -SELECT Id_Trabajador, billsec, 1 as Recibidas, NULL as Emitidas, date(calldate) as Fecha, hour(calldate) as Hora -FROM Trabajadores T -INNER JOIN cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%') -LEFT JOIN v_phonebook A ON A.Telefono = C.src -WHERE calldate >= datFEC -UNION ALL -SELECT Id_Trabajador, billsec, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate) -FROM Trabajadores T -INNER JOIN cdr C ON C.src = T.extension -LEFT JOIN v_phonebook A ON A.Telefono = C.dst -WHERE calldate >= datFEC -) llamadas -INNER JOIN Permisos USING(Id_Trabajador) -INNER JOIN -( -SELECT DISTINCT Fecha FROM Tickets WHERE Fecha >= datFEC -) days USING(Fecha) -WHERE Id_Grupo = 6 -GROUP BY Id_Trabajador, Fecha, Hora; - -/* -SELECT Id_Trabajador, SUM(dur_in) dur_in, SUM(dur_out) dur_out, llamadas.Fecha,YEAR(llamadas.Fecha) `year`, -MONTH(llamadas.Fecha) `month`,WEEK(llamadas.Fecha,7) `week`, Hora, SUM(Recibidas) as Entrantes, SUM(Emitidas) as Salientes -FROM -( -SELECT Id_Trabajador, billsec dur_in, NULL dur_out, 1 as Recibidas, NULL as Emitidas, date(calldate) as Fecha, hour(calldate) as Hora -FROM Trabajadores T -INNER JOIN cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%') -WHERE calldate >= CURDATE() -UNION ALL -SELECT Id_Trabajador,NULL dur_in, billsec dur_out, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate) -FROM Trabajadores T -INNER JOIN cdr C ON C.src = T.extension -WHERE calldate >= CURDATE() -) llamadas -INNER JOIN Permisos USING(Id_Trabajador) -WHERE Id_Grupo = 6 -GROUP BY Id_Trabajador, Fecha, Hora; -*/ -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Movimiento_rechazo` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Movimiento_rechazo`(IN idMOV BIGINT) -BEGIN - - DECLARE idC INT; - DECLARE newFEC DATE; - DECLARE intWarehouse INT; - DECLARE intEmpresa INT; - DECLARE IdConsignatario INT; - DECLARE intIdAgencia INT; - DECLARE Id_NEWTICKET BIGINT; - DECLARE Id_NEWMOVIMIENTO BIGINT; - DECLARE datLanding DATE; - DECLARE v_start DATETIME; - DECLARE v_end DATETIME; - DECLARE intTicketActual INT; - DECLARE SYSTEM_WORKER INT DEFAULT 20; - - SELECT Id_Cliente - , Fecha - , warehouse_id - , empresa_id - , Id_Consigna - , Id_Agencia - , Landing - , Id_Ticket - - INTO idC - , newFEC - , intWarehouse - , intEmpresa - , IdConsignatario - , intIdAgencia - , datLanding - , intTicketActual - - FROM Tickets t - JOIN Movimientos m using(Id_Ticket) - WHERE Id_Movimiento = idMOV; - - -- Busca un ticket existente que coincida con los parametros del nuevo pedido - - SET v_start = TIMESTAMP(newFEC); - SET v_end = TIMESTAMP(newFEC, '23:59:59'); - - SELECT Id_Ticket INTO Id_NEWTICKET - FROM vn2008.Tickets t - WHERE IdConsignatario = t.Id_Consigna - AND intWarehouse = t.warehouse_id - AND intIdAgencia = t.Id_Agencia - AND datLanding <=> t.Landing - AND t.Fecha BETWEEN v_start AND v_end -- uso BETWEEN para aprovechar el indice - AND t.Factura IS NULL - AND t.Localizacion = 'RECHAZO' - AND t.PedidoImpreso = 0 - AND t.Etiquetasemitidas = 0 - AND vn2008.is_bionic(t.Id_Ticket) - AND t.Id_Cliente <> 1118 - AND t.Id_Ticket <> intTicketActual - LIMIT 1; - - IF Id_NEWTICKET IS NULL - THEN - CALL vn.ticketCreate(idC - , newFEC - , intWarehouse - , intEmpresa - , IdConsignatario - , intIdAgencia - , NULL - ,datLanding - , Id_NEWTICKET); - - CALL bionic_calc_ticket(Id_NEWTICKET); - END IF; - - INSERT INTO vncontrol.inter(Id_Ticket, Id_Trabajador, state_id) - SELECT Id_NEWTICKET, SYSTEM_WORKER, s.id - FROM vn2008.state s - WHERE s.code = 'FIXING'; - - INSERT INTO Movimientos(Id_Ticket, Id_Article, Concepte, Cantidad, Preu, Descuento) - SELECT Id_NEWTICKET, Id_Article, Concepte, Cantidad, Preu, Descuento - FROM Movimientos - WHERE Id_Movimiento = idMOV; - - SELECT LAST_INSERT_ID() INTO Id_NEWMOVIMIENTO; - - INSERT INTO Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT Id_NEWMOVIMIENTO, Id_Componente, Valor - FROM Movimientos_componentes - WHERE Id_Movimiento = idMOV; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `msg` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `msg`(IN memTXT VARCHAR(255), IN idREM INTEGER, idDES INTEGER) -BEGIN - DECLARE last_ID INTEGER; - DECLARE codDES CHAR(3); - - SELECT CodigoTrabajador INTO codDES FROM Trabajadores WHERE Id_Trabajador = idDES; - - INSERT INTO Mensajes(Mensaje,Fecha,Remitente,Destinatario) - VALUES(memTXT, NOW(),idREM, idDES); - SELECT LAST_INSERT_ID() INTO last_ID; - - - INSERT INTO Incidencias(Incidencia,Id_Trabajador,Destino,Fecha,Fecha_Mod) - VALUES (CONCAT('@@ ',last_ID),idREM,codDES,NOW(),NOW()); - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nest_brother_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nest_brother_add`( - vTable VARCHAR(45) - ,vNewBrother VARCHAR(45) - ,vOldBrotherId INT -) -BEGIN - DECLARE vMyRight INT; - DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA(); - - DROP TEMPORARY TABLE IF EXISTS aux; - CREATE TEMPORARY TABLE aux - SELECT 0 as rgt; - - CALL util.exec (sql_printf ( - 'UPDATE vn2008.aux SET rgt = (SELECT rgt FROM %t.%t WHERE id = %v)' - ,vSchema - ,vTable - ,vOldBrotherId - )); - - SELECT rgt INTO vMyRight FROM aux; - - DROP TEMPORARY TABLE aux; - - CALL util.exec (sql_printf ( - 'UPDATE %t.%t SET rgt = rgt + 2 WHERE rgt > %v ORDER BY rgt DESC' - ,vSchema - ,vTable - ,vMyRight - )); - - CALL util.exec (sql_printf ( - 'UPDATE %t.%t SET lft = lft + 2 WHERE lft > %v ORDER BY lft DESC' - ,vSchema - ,vTable - ,vMyRight - )); - - CALL util.exec (sql_printf ( - 'INSERT INTO %t.%t (name, lft, rgt) VALUES(%v, %v + 1, %v + 2)' - ,vSchema - ,vTable - ,vNewBrother - ,vMyRight - ,vMyRight - )); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nest_child_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nest_child_add`( - vTable VARCHAR(45) - ,vChild VARCHAR(45) - ,vFatherId INT -) -BEGIN - DECLARE vMyLeft INT; - DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA(); - - DROP TEMPORARY TABLE IF EXISTS aux; - CREATE TEMPORARY TABLE aux - SELECT 0 as lft; - - CALL util.exec (sql_printf ( - 'UPDATE vn2008.aux SET lft = (SELECT lft FROM %t.%t WHERE id = %v)' - ,vSchema - ,vTable - ,vFatherId - )); - - SELECT lft INTO vMyLeft FROM aux; - - DROP TEMPORARY TABLE aux; - - CALL util.exec (sql_printf ( - 'UPDATE %t.%t SET rgt = rgt + 2 WHERE rgt > %v ORDER BY rgt DESC' - ,vSchema - ,vTable - ,vMyLeft - )); - - CALL util.exec (sql_printf ( - 'UPDATE %t.%t SET lft = lft + 2 WHERE lft > %v ORDER BY lft DESC' - ,vSchema - ,vTable - ,vMyLeft - )); - - CALL util.exec (sql_printf ( - 'INSERT INTO %t.%t(name, lft, rgt) VALUES(%v, %v + 1, %v + 2)' - ,vSchema - ,vTable - ,vChild - ,vMyLeft - ,vMyLeft - )); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nest_delete` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nest_delete`( - vTable VARCHAR(45) - ,vNodeId INT -) -BEGIN - DECLARE vMyRight INT; - DECLARE vMyLeft INT; - DECLARE vMyWidth INT; - DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA(); - - DROP TEMPORARY TABLE IF EXISTS aux; - CREATE TEMPORARY TABLE aux - SELECT 0 AS rgt, 0 AS lft, 0 AS wdt; - - CALL util.exec (sql_printf ( - 'UPDATE vn2008.aux a JOIN %t.%t t SET a.rgt = t.rgt, a.lft = t.lft, a.wdt = t.rgt - t.lft + 1 WHERE t.id = %v' - ,vSchema - ,vTable - ,vNodeId - )); - - SELECT rgt, lft, wdt INTO vMyRight, vMyLeft, vMyWidth FROM aux; - - DROP TEMPORARY TABLE aux; - - CALL util.exec (sql_printf ( - 'DELETE FROM %t.%t WHERE lft BETWEEN %v AND %v' - ,vSchema - ,vTable - ,vMyLeft - ,vMyRight - )); - - CALL util.exec (sql_printf ( - 'UPDATE %t.%t SET rgt = rgt - %v WHERE rgt > %v ORDER BY rgt' - ,vSchema - ,vTable - ,vMyWidth - ,vMyRight - )); - - CALL util.exec (sql_printf ( - 'UPDATE %t.%t SET lft = lft - %v WHERE lft > %v ORDER BY lft' - ,vSchema - ,vTable - ,vMyWidth - ,vMyRight - )); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nest_leaves` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nest_leaves`( - vTable VARCHAR(20) - ,vLinesTable VARCHAR(40) - ,vNestId VARCHAR(40) - ,vGap INT - ,vShouldShow BOOL -) -BEGIN - DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA(); - - DROP TEMPORARY TABLE IF EXISTS tmp.nest; - - -- Se llama al procedimiento que genera el arbol - - CALL nest_tree(vTable, vGap, FALSE); - - -- Se añade un campo para el conteo de hojas - - ALTER TABLE tmp.nest - ADD leaves INT, - ADD time DATETIME; - - -- Añadimos la hora - - CALL util.exec (sql_printf ( - 'UPDATE tmp.nest n - JOIN %t.%t s using(id) - SET n.time = s.odbc_date' - ,vSchema - ,vTable - )); - - -- Actualizamos el campo leaves para los nodos que tienen asociados - - CALL util.exec (sql_printf ( - 'update tmp.nest n - join - ( - select %t as id, count(*) as leaves - from %t.%t - group by %t - ) s using(id) - set n.leaves = s.leaves' - ,vNestId - ,vSchema - ,vLinesTable - ,vNestId - )); - - -- Actualizamos todos los nodos con la suma de las hojas de los hijos - - drop temporary table if exists tmp.nest2; - - create temporary table tmp.nest2 - select * from tmp.nest; - - drop temporary table if exists tmp.nest3; - - create temporary table tmp.nest3 - select * from tmp.nest; - - update tmp.nest - join - ( - select n.id, sum(n2.leaves) leaves - from tmp.nest3 n - join tmp.nest2 n2 on n2.lft between n.lft and n.rgt - group by n.id - ) sub on sub.id = nest.id - set nest.leaves = ifnull(sub.leaves,0); - - drop temporary table tmp.nest2; - - IF vShouldShow THEN - SELECT * FROM tmp.nest; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nest_move` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nest_move`( - strTABLE VARCHAR(45) - ,idNODE INT - ,idFATHER INT -) -BEGIN - DECLARE myRight INT; - DECLARE myLeft INT; - DECLARE myWidth INT; - DECLARE fatherRight INT; - DECLARE fatherLeft INT; - DECLARE gap INT; - DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA(); - - DROP TEMPORARY TABLE IF EXISTS aux; - CREATE TEMPORARY TABLE aux - SELECT 0 as rgt, 0 as lft, 0 as wdt, 0 as frg, 0 as flf; - - -- Averiguamos el ancho de la rama - - CALL util.exec (sql_printf ( - 'UPDATE vn2008.aux a JOIN %t.%t t SET a.wdt = t.rgt - t.lft +1 - WHERE t.id = %v' - ,vSchema - ,strTABLE - ,idNODE - )); - - -- Averiguamos la posicion del nuevo padre - - CALL util.exec (sql_printf ( - 'UPDATE vn2008.aux a JOIN %t.%t t SET a.frg = t.rgt, a.flf = t.lft WHERE t.id = %v' - ,vSchema - ,strTABLE - ,idFATHER - )); - - SELECT wdt, frg, flf INTO myWidth, fatherRight, fatherLeft FROM aux; - - -- 1º Incrementamos los valores de todos los nodos a la derecha del punto de inserción (fatherRight) , para hacer sitio - - CALL util.exec (sql_printf ( - 'UPDATE %t.%t SET rgt = rgt + %v WHERE rgt >= %v ORDER BY rgt DESC' - ,vSchema - ,strTABLE - ,myWidth - ,fatherRight - )); - - CALL util.exec (sql_printf ( - 'UPDATE %t.%t SET lft = lft + %v WHERE lft >= %v ORDER BY lft DESC' - ,vSchema - ,strTABLE - ,myWidth - ,fatherRight - )); - - -- Es preciso recalcular los valores del nodo en el caso de que estuviera a la derecha del nuevo padre - - CALL util.exec (sql_printf ( - 'UPDATE vn2008.aux a JOIN %t.%t t SET a.rgt = t.rgt, a.lft = t.lft WHERE t.id = %v' - ,vSchema - ,strTABLE - ,idNODE - )); - - SELECT lft, rgt, frg - lft INTO myLeft, myRight, gap FROM aux; - - -- 2º Incrementamos el valor de todos los nodos a trasladar hasta alcanzar su nueva posicion - - CALL util.exec (sql_printf ( - 'UPDATE %t.%t SET lft = lft + %v WHERE lft BETWEEN %v AND %v ORDER BY lft DESC' - ,vSchema - ,strTABLE - ,gap - ,myLeft - ,myRight - )); - - CALL util.exec (sql_printf ( - 'UPDATE %t.%t SET rgt = rgt + %v WHERE rgt BETWEEN %v AND %v ORDER BY rgt DESC' - ,vSchema - ,strTABLE - ,gap - ,myLeft - ,myRight - )); - - -- 3º Restaremos a todos los nodos resultantes, a la derecha de la posicion arrancada el ancho de la rama escindida - - CALL util.exec (sql_printf ( - 'UPDATE %t.%t SET lft = lft - %v WHERE lft > %v ORDER BY lft' - ,vSchema - ,strTABLE - ,myWidth - ,myLeft - )); - - CALL util.exec (sql_printf ( - 'UPDATE %t.%t SET rgt = rgt - %v WHERE rgt > %v ORDER BY rgt' - ,vSchema - ,strTABLE - ,myWidth - ,myRight - )); - - DROP TEMPORARY TABLE aux; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nest_query` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nest_query`(strTABLE VARCHAR(45)) -BEGIN - DECLARE v_max_depth INT; - DECLARE v_current_depth INT; - DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA(); - - DROP TEMPORARY TABLE IF EXISTS tmp.nest_depth; - DROP TEMPORARY TABLE IF EXISTS tmp.nest_depth_aux; - - -- Calculamos el nivel de profundidad para cada item - - CALL util.exec (sql_printf ( - 'CREATE TEMPORARY TABLE tmp.nest_depth - SELECT node.id node_id, COUNT(parent.id) - 1 as depth - FROM %t.%t AS node, - %t.%t AS parent - WHERE node.lft BETWEEN parent.lft AND parent.rgt - GROUP BY node.id - ORDER BY node.lft' - ,vSchema - ,strTABLE - ,vSchema - ,strTABLE - )); - - SELECT max(depth) FROM tmp.nest_depth INTO v_max_depth; - SET v_current_depth = 2; - - CREATE TEMPORARY TABLE tmp.nest_depth_aux - SELECT * FROM tmp.nest_depth; - - -- Vamos a hacer consultas anidadas para obtener una consulta de dos entradas - - DROP TEMPORARY TABLE IF EXISTS tmp.nest; - DROP TEMPORARY TABLE IF EXISTS tmp.nest_aux; - - -- Primera tabla, con el nivel 0 - CALL util.exec (sql_printf ( - 'CREATE TEMPORARY TABLE tmp.nest - SELECT child.id nest_id - ,child.lft - ,child.rgt - ,parent.id as ID0 - ,parent.name as PARENT0 - ,child.id as ID1 - ,child.name as PARENT1 - FROM %t.%t AS parent - JOIN tmp.nest_depth nd ON nd.node_id = parent.id AND nd.depth = 0, - %t.%t AS child - JOIN tmp.nest_depth_aux ndc ON ndc.node_id = child.id AND ndc.depth = 1 - WHERE child.lft BETWEEN parent.lft + 1 AND parent.rgt - ORDER BY parent.lft' - ,vSchema - ,strTABLE - ,vSchema - ,strTABLE - )); - - CREATE TEMPORARY TABLE tmp.nest_aux - SELECT * FROM tmp.nest; - - WHILE v_current_depth <= v_max_depth - DO - DROP TEMPORARY TABLE IF EXISTS tmp.nest; - - CALL util.exec (sql_printf ( - 'CREATE TEMPORARY TABLE tmp.nest - SELECT parent.* - ,child.id as %v - ,child.name as %v - ,child.id as ID - FROM tmp.nest_aux AS parent - LEFT JOIN %t.%t AS child ON child.lft BETWEEN parent.lft + 1 AND parent.rgt - LEFT JOIN tmp.nest_depth_aux ndc ON ndc.node_id = child.id - WHERE IFNULL(ndc.depth,%v) = %v - ORDER BY parent.lft' - ,CONCAT('ID',v_current_depth) - ,CONCAT('PARENT',v_current_depth) - ,vSchema - ,strTABLE - ,v_current_depth - ,v_current_depth - )); - - -- Actualizamos lft y rgt - - CALL util.exec (sql_printf ( - 'UPDATE tmp.nest - JOIN %t.%t AS child ON child.id = nest.ID - SET nest.lft = child.lft, nest.rgt = child.rgt, nest_id = nest.ID' - ,vSchema - ,strTABLE - )); - - ALTER TABLE tmp.nest DROP COLUMN ID; - - DROP TEMPORARY TABLE IF EXISTS tmp.nest_aux; - CREATE TEMPORARY TABLE tmp.nest_aux - SELECT * FROM tmp.nest; - - SET v_current_depth = v_current_depth + 1; - END WHILE; - - -- Eliminamos los campos duplicados - SET v_current_depth = 0; - - WHILE v_current_depth <= v_max_depth - DO - SET @id = 0; - - CALL util.exec (sql_printf ( - 'UPDATE tmp.nest_aux - SET %t = IF(@id = %t, NULL, %t), - ID0 = IF(@id := %t, ID0, ID0), - %t = IF(length(%t), %t,NULL)' - ,CONCAT('PARENT',v_current_depth) - ,CONCAT('ID',v_current_depth) - ,CONCAT('PARENT',v_current_depth) - ,CONCAT('ID',v_current_depth) - ,CONCAT('ID',v_current_depth) - ,CONCAT('PARENT',v_current_depth) - ,CONCAT('ID',v_current_depth) - )); - - SET v_current_depth = v_current_depth + 1; - END WHILE; - - SELECT * FROM tmp.nest_aux; - - -- Limpieza - - DROP TEMPORARY TABLE IF EXISTS - tmp.nest_aux, - tmp.nest, - tmp.nest_depth_aux, - tmp.nest_depth; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nest_sons_list` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nest_sons_list`( - vId INT - ,vTable VARCHAR(45) - ,vShouldShow BOOLEAN -) -BEGIN -/** - * Devuelve un recordset con los ID de todos los nodos que - * cuelgan del nodo que se pasa como parámetro - */ - DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA(); - - DROP TEMPORARY TABLE IF EXISTS tmp.nest_sons; - CALL util.exec (sql_printf ( - 'CREATE TEMPORARY TABLE tmp.nest_sons - SELECT DISTINCT node.id node_id - FROM %t.%t AS node - JOIN %t.%t AS parent ON node.lft between parent.lft and parent.rgt - WHERE parent.id = %v - ORDER BY node.lft' - ,vSchema - ,vTable - ,vSchema - ,vTable - ,vId - )); - - IF vShouldShow THEN - SELECT * FROM tmp.nest_sons; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nest_tree` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nest_tree`( - vTable VARCHAR(20) - ,vGap INT - ,vShouldShow BOOL -) -BEGIN - DECLARE vSchema VARCHAR(255) DEFAULT SCHEMA(); - - DROP TEMPORARY TABLE IF EXISTS tmp.nest; - CALL util.exec (sql_printf ( - 'CREATE TEMPORARY TABLE tmp.nest - SELECT node.id - ,CONCAT( REPEAT(REPEAT(" ",%v), COUNT(parent.id) - 1), node.name) AS name - ,node.lft - ,node.rgt - ,COUNT(parent.id) - 1 as depth - ,cast((node.rgt - node.lft - 1) / 2 as DECIMAL) as sons - FROM %t.%t AS node, - %t.%t AS parent - WHERE node.lft BETWEEN parent.lft AND parent.rgt - GROUP BY node.id - ORDER BY node.lft' - ,vGap - ,vSchema - ,vTable - ,vSchema - ,vTable - )); - - IF vShouldShow THEN - SELECT * FROM tmp.nest; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `newItem` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `newItem`(IN vTicket INTEGER, IN vVolume INTEGER, IN vQuantity INTEGER) -BEGIN - - DECLARE vLandingWarehouse INT; - DECLARE vLandingDate DATE; - DECLARE vShipmentDate DATE; - DECLARE vTravel INT; - DECLARE vEntry INT; - - SELECT warehouse_id, Fecha, landing INTO vLandingWarehouse, vShipmentDate, vLandingDate FROM Tickets WHERE Id_Ticket = vTicket; - - -- seleccionamos travel - SELECT id, Id_Entrada INTO vTravel, vEntry - FROM travel t LEFT JOIN Entradas e ON t.id = e.travel_id - WHERE t.landing = vLandingDate AND t.shipment = vShipmentDate AND t.warehouse_id_out = vLandingWarehouse AND t.warehouse_id = vWarehouse - AND t.delivered = FALSE ; -- agency ?? - - -- creamos el travel si es necesario - IF NOT vTravel THEN - INSERT INTO travel (shipment, landing, warehouse_id, warehouse_id_out, agency_id) - VALUES (vShipmentDate, vLandingDate, vLandingWarehouse, vShipmentWarehouse, a); - SELECT LAST_INSERT_ID() INTO vTravel; - END IF; - - -- creamos la Entrada si es necesario - IF NOT vEntry THEN - INSERT INTO Entradas (Id_Proveedor, travel_id) - VALUES (13, vTravel); -- proveedor 'MOVIMIENTO ALMACEN' - SELECT LAST_INSERT_ID() INTO vEntry; - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `niching` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `niching`(IN i_ini INT, IN i_end INT -, IN i_bal INT, IN i_col INT ) -BEGIN - -DECLARE i INT(5); -DECLARE j INT(5); - -DROP TEMPORARY TABLE IF EXISTS labels; - -CREATE TEMPORARY TABLE `labels` - (`label` VARCHAR(15) NULL) -ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - -WHILE i_ini <= i_end DO - - SET i = i_bal; - - WHILE i > 0 DO - - - - SET j = i_col; - IF j = 0 THEN - INSERT INTO labels(label) - VALUES (CONCAT(i_ini,IF(i=0,' ',char(64 + i)))); - ELSE - - WHILE j > 0 DO - - INSERT INTO labels(label) - VALUES (CONCAT(i_ini,char(64 + i), j)); - - SET j = j - 1; - - END WHILE; - END IF; - SET i = i - 1; - - END WHILE; - -SET i_ini = i_ini + 1; - -END WHILE; - -SELECT CONCAT('*',label,'*') as label, label as id FROM labels; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nightly_tasks` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nightly_tasks`() -BEGIN - -DECLARE AUX INT; - -DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; - SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('jgallego@verdnatura.es', 'error nightly tasks' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('pako@verdnatura.es', 'error nightly tasks' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - -END; - - INSERT INTO vn2008.daily_task_log(consulta) VALUES('arranca el event vn2008.nightly_tasks'); - - - SELECT SLEEP(1) INTO AUX; - CALL vn2008.emailYesterdayPurchasesLauncher(); - INSERT INTO vn2008.daily_task_log(consulta) VALUES('emailYesterdayPurchasesLauncher END'); - - SELECT SLEEP(1) INTO AUX; - CALL vn2008.inventory_refresh(); - INSERT INTO vn2008.daily_task_log(consulta) VALUES('inventory refresh END'); - - SELECT SLEEP(1) INTO AUX; - CALL bi.last_buy_id_add; - INSERT INTO vn2008.daily_task_log(consulta) VALUES('last buy id END'); - - /* JGF 2016-09-06 Quitado a peticion de AGS - SELECT SLEEP(1) INTO AUX; - CALL vn2008.comercial_caducado; - INSERT INTO vn2008.daily_task_log(consulta) VALUES('Comercial Caducado END'); - */ - SELECT SLEEP(1) INTO AUX; - CALL bi.defaulting(curdate()); - INSERT INTO vn2008.daily_task_log(consulta) VALUES('defaulting END'); - - INSERT INTO vn2008.Colas(Id_Informe,Id_Trabajador) VALUES (11,57); - - -- Desactivacion de usuarios con contrato terminado - INSERT INTO vn2008.Colas(Id_Informe) VALUES (16); - - SELECT SLEEP(1) INTO AUX; - CALL `bi`.`Ultima_Accion`; - INSERT INTO vn2008.daily_task_log(consulta) VALUES('ultima accion END'); - - SELECT SLEEP(1) INTO AUX; - CALL `bi`.`facturacion_media_anual_update`(); - INSERT INTO vn2008.daily_task_log(consulta) VALUES('facturacion media anual END'); - - SELECT SLEEP(1) INTO AUX; - CALL vn2008.Clientes_calidad; - INSERT INTO vn2008.daily_task_log(consulta) VALUES('clientes calidad END'); - - SELECT SLEEP(1) INTO AUX; - CALL bi.rotacion_update; - INSERT INTO vn2008.daily_task_log(consulta) VALUES('rotation update END'); - - SELECT SLEEP(1) INTO AUX; - CALL bi.rutas_m3_add; - INSERT INTO vn2008.daily_task_log(consulta) VALUES('rutas_m3 END'); - - SELECT SLEEP(1) INTO AUX; - CALL vn2008.tarjetas_credito_0; - INSERT INTO vn2008.daily_task_log(consulta) VALUES('tarjetas credito 0 END'); - - SELECT SLEEP(1) INTO AUX; - CALL bi.comparativa_add(); - INSERT INTO vn2008.daily_task_log(consulta) VALUES('comparativa add END'); - - SELECT SLEEP(1) INTO AUX; - call vn2008.recobro_credito(); -- PAK 12/01/2016 - INSERT INTO vn2008.daily_task_log(consulta) VALUES('recobro_credito END'); - - SELECT SLEEP(1) INTO AUX; - CALL vn2008.accumulatorsReadingDateUpdate(); - INSERT INTO vn2008.daily_task_log(consulta) VALUES('accumulatorsReadingDateUpdate END'); - - SELECT SLEEP(1) INTO AUX; - call vn2008.itemTagArrangedUpdate(0); - INSERT INTO vn2008.daily_task_log(consulta) VALUES('itemTagFormatUpdate END'); - - SELECT SLEEP(1) INTO AUX; - CALL vn.itemTagUpdatePriority(0); - INSERT INTO vn2008.daily_task_log(consulta) VALUES('articleTagUpdatePriority END'); - - /* - CALL vn.invoiceOutAgainDateRange(util.yesterday(),util.yesterday()); - INSERT INTO vn2008.daily_task_log(consulta) VALUES('invoiceOutAgainDateRange END'); - */ - - /* jgf posar quan estiga arreglat - SELECT SLEEP(1) INTO AUX; - CALL bi.primer_pedido_add; - INSERT INTO vn2008.daily_task_log(consulta) VALUES('primer_pedido_add END'); -*/ - SELECT SLEEP(1) INTO AUX; - INSERT INTO vn2008.daily_task_log(consulta) VALUES('finalitza el event vn2008.nightly_tasks'); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `notify_passport` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `notify_passport`(IN idA INT, IN idEti SMALLINT, IN idPacking SMALLINT, IN idCompra INT) -BEGIN - INSERT INTO vn2008.mail(`subject`,`text`,`to`) - SELECT 'Solicitar pasaporte', - CONCAT('Etiquetas: ',ifnull(idEti,0),', Packing: ',ifnull(idPacking,0),', Nombre: ',ifnull(a.Article,0),', buy_edi: ',ifnull(be.id,0),', Nombre botánico: ', - IFNULL(g.latin_genus_name,''),' ',IFNULL(s.latin_species_name,''),' , Productor: ',IFNULL(es.company_name,IFNULL(p.`name`,''))) - ,'ekt@verdnatura.es' - FROM vn2008.Articles a - LEFT JOIN vn2008.Articles_botanical ab ON ab.Id_Article = a.Id_Article - LEFT JOIN edi.genus g ON g.genus_id = ab.genus_id - LEFT JOIN edi.specie s ON IFNULL(s.specie_id,ab.specie_id) = ab.specie_id - LEFT JOIN vn2008.producer p ON p.producer_id = a.producer_id - LEFT JOIN vn2008.Compres c ON c.Id_Compra = idCompra - LEFT JOIN vn2008.buy_edi be ON c.buy_edi_id = be.id - LEFT JOIN edi.supplier es ON es.supplier_id = be.pro - WHERE a.Id_Article = idA; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `pay` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `pay`(IN datFEC DATE - , IN idPROV INT - , IN dblIMPORTE DOUBLE - , IN idMONEDA INT - , IN dblDIVISA DOUBLE - , IN idCAJA INT - , IN idPAYMET INT - , IN dblGASTOS DOUBLE - , IN strCONCEPTO VARCHAR(40) - , IN idEMP INT) -BEGIN - - --- Registro en la tabla Cajas -INSERT INTO Cajas ( Concepto - , Serie - , Numero - , Salida - , Cajafecha - , Partida - , Id_Banco - , Id_Trabajador - ,empresa_id - ,conciliado) - -SELECT CONCAT('n/pago a ', Proveedor) - , 'R' - , idPROV - , dblIMPORTE - , datFEC - , 1 - , idCAJA - , 20 - , idEMP - , 1 -FROM Proveedores -WHERE Id_Proveedor = idPROV; - - --- Registro en la tabla pago -INSERT INTO pago(fecha - , id_proveedor - , importe - , id_moneda - , divisa - , id_banco - , pay_met_id - , g_bancarios - , concepte - , empresa_id) - - VALUES(datFEC - , idPROV - , dblIMPORTE - , idMONEDA - , IF(dblDIVISA = 0, NULL, dblDIVISA) - , idCAJA - , idPAYMET - , dblGASTOS - , strCONCEPTO - , idEMP); - -SELECT LAST_INSERT_ID() as pago_id; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `percentil` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `percentil`() -BEGIN - -DECLARE max_range INT; - -DROP TEMPORARY TABLE IF EXISTS previa; - -CREATE TEMPORARY TABLE previa -SELECT @posicion:= @posicion +1 as Posicion, Id_Cliente, Total FROM ( -SELECT Id_Cliente, Total FROM ( -SELECT Id_Cliente, SUM(Importe) as Total -FROM Facturas -INNER JOIN Clientes USING(Id_Cliente) -INNER JOIN (SELECT @posicion := 0) sub_pos -WHERE invoice -AND YEAR(Fecha) = YEAR(CURDATE()) -GROUP BY Id_Cliente) sub -ORDER BY Total -) sub2; - -SELECT COUNT(*) INTO max_range FROM previa; - -UPDATE Clientes SET percentil = 0; - -UPDATE Clientes INNER JOIN previa USING(Id_Cliente) -SET Clientes.percentil = ROUND(Posicion *100 / max_range,0); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `portekk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `portekk`(IN intId_Ticket INT,IN intbultos INT, IN intId_Article INT) -BEGIN - - -- Deprecated!! Usar la funcion porte en lugar de este procedure - DECLARE intId_Agencia INT; - DECLARE int_agency_id SMALLINT; - DECLARE int_province_id SMALLINT; - DECLARE bolCOD71 TINYINT(1); - DECLARE intPorte DOUBLE DEFAULT -1; - DECLARE dayofweek TINYINT(1) default 0; - DECLARE suplemento DOUBLE DEFAULT 9.41; - DECLARE strCodPostal VARCHAR(5); - DECLARE intWarehouse_id SMALLINT; - DECLARE dbldescuento DOUBLE DEFAULT 0; - DECLARE intVista TINYINT(1); - DECLARE dblvolumen DOUBLE; - DECLARE intPROVINCIA INT; - - SET @porte := 0; - SELECT c.province_id, a.agency_id, t.Id_Agencia, cod71, Porte,c.CODPOSTAL,t.warehouse_id,c.province_id,cli.Descuento,IFNULL(ag.Vista,a.Vista), por_volumen - INTO intPROVINCIA, int_agency_id,intId_Agencia, bolCOD71,intPorte,strCodPostal,intWarehouse_id,int_province_id,dbldescuento,intVista,dblvolumen - FROM Tickets t - JOIN Consignatarios c USING(Id_Consigna) - JOIN Agencias a ON t.Id_Agencia = a.Id_Agencia - JOIN agency agn ON agn.agency_id = a.agency_id - JOIN Clientes cli on c.Id_Cliente=cli.Id_Cliente - LEFT JOIN agency_warehouse ag ON ag.agency_id = a.agency_id - WHERE Id_Ticket = intId_Ticket limit 1; --- Fusionar con lo de arriba -/*SELECT IFNULL(MAX(counter),0) +1 INTO intcounter FROM expeditions e - INNER JOIN Tickets t1 ON e.ticket_id = t1.Id_Ticket - INNER JOIN Tickets t2 ON t2.Id_Consigna = t1.Id_Consigna AND DATE(t2.Fecha) = DATE(t1.Fecha) - WHERE t2.Id_Ticket = NEW.ticket_id AND t1.Etiquetasemitidas = FALSE AND t1.empresa_id = t2.empresa_id;*/ - - - IF (intPorte >= 0 or dbldescuento BETWEEN 0 AND 1 ) THEN - IF intPorte or base_ticket(intId_Ticket) < 50 THEN - SELECT IFNULL(intPorte,10)/intbultos price;/*en el cas dels tarifa 1 els cobren 10€ de ports*/ - ELSE - SELECT 0 price; - END IF; - ELSE - IF NOT dblvolumen THEN - IF bolCOD71 THEN - IF intVista = 2 AND intbultos BETWEEN 1 AND 2 THEN - SELECT IF(price * intbultos < 10 AND porte_minimo, 10 / intbultos, price) price FROM Agencias_zonas az - WHERE zona = 1 AND Id_Agencia = intId_Agencia AND az.warehouse_id = intWarehouse_id; - ELSE - IF intId_Agencia = 47 THEN -- Si es viaxpress - SELECT price price FROM Agencias_zonas az INNER JOIN viaxpress USING(zona) - WHERE Id_Agencia = 47 AND codigo_postal = strCodPostal AND az.warehouse_id = intWarehouse_id; - ELSE - CALL util.exec (sql_printf (' - SELECT price FROM vn2008.Agencias_zonas az - WHERE Id_Agencia = %v AND %v = Id_Article AND az.warehouse_id = %v - AND zona = (SELECT zona FROM vn2008.Agencias_province - WHERE warehouse_id = %v AND agency_id = %v and province_id = %v)' - ,intId_Agencia,intId_Article,intWarehouse_id,intWarehouse_id,int_agency_id,int_province_id)); - END IF; - END IF; - ELSE - SELECT 0 price; - END IF; - ELSE -- Si es una agency con la columna por_volumen <> 0 calcula el porte por Volumen - - CALL ticket_volumen(intId_Ticket); - SELECT MAX(Porte_total)/intbultos price FROM ticket_volumen; - DROP TEMPORARY TABLE IF EXISTS ticket_volumen; - END IF; - END IF; - - - SET @porte = price; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `PortesDesdeTicketkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `PortesDesdeTicketkk`( intTicket INTEGER) -BEGIN - -- DEPRECATED! con el bionic esto ya no se usa - DECLARE done BIT DEFAULT 0; - DECLARE v_date_ini,v_date_end DATE; - -- JGF 21/08/14 A partir de un intTicket se calcula lo que se ha cobrado en concepto de portes - -- restando la tarifa dos en esa fecha al valor del ticket - DROP TEMPORARY TABLE IF EXISTS portes; - IF (SELECT Descuento FROM Clientes c JOIN Tickets t ON t.Id_Cliente = c.Id_Cliente WHERE t.Id_Ticket = intTicket) BETWEEN 0 AND 1 THEN - SELECT TIMESTAMPADD(MONTH,-12,Fecha),Fecha INTO v_date_ini,v_date_end FROM Tickets WHERE Id_Ticket = intTicket LIMIT 1; - - - CREATE TEMPORARY TABLE portes (KEY (Id_Article)) ENGINE = MEMORY - SELECT Id_Article,round(SUM(Preu * (1 - (Descuento / 100)) * Cantidad)/ SUM(Cantidad),2) price, round(SUM(Preu * (1 - (Descuento / 100)) * Cantidad),2) importe, - round((SUM(Preu * (1 - (Descuento / 100)) * Cantidad) / SUM(Cantidad) - Tarifa2) * SUM(Cantidad),2) diferencia,Tarifa2, - v_date_end Fecha,SUM(Cantidad) Cantidad - FROM - (SELECT * FROM ( - SELECT m.Id_Article, Tarifa2,m.Preu,m.Descuento,m.Cantidad,t.Fecha,t.warehouse_id,Id_Movimiento - FROM Compres c - JOIN Movimientos m ON m.Id_Article = c.Id_Article - JOIN Articles a ON a.Id_Article = c.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - JOIN Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel tr ON tr.id = e.travel_id - WHERE t.Id_Ticket = intTicket AND Novincular = FALSE AND Tarifa2 > 0 - AND t.warehouse_id = tr.warehouse_id AND tr.landing BETWEEN v_date_ini AND v_date_end - AND reino_id <> 6 ORDER BY tr.landing DESC) t - GROUP BY t.Id_Movimiento) t - GROUP BY Id_Article, warehouse_id - UNION all - SELECT Id_Article,Preu * (1 - (Descuento / 100)) ,Preu * (1 - (Descuento / 100)) * Cantidad , - Preu * (1 - (Descuento / 100)) * Cantidad ,0 ,v_date_end, Cantidad FROM Movimientos - WHERE Id_Ticket= intTicket AND Id_Article = 71; - - UPDATE portes p JOIN price_fixed pf ON p.Id_Article = pf.item_id AND Fecha BETWEEN date_start AND date_end AND pf.rate_2 - SET diferencia = (price - rate_2) * Cantidad,Tarifa2 = rate_2; - ELSE - CREATE TEMPORARY TABLE portes (KEY (Id_Article)) ENGINE = MEMORY - SELECT Id_Article,Preu * (1 - (Descuento / 100)) price,Preu * (1 - (Descuento / 100)) * Cantidad importe, - Preu * (1 - (Descuento / 100)) * Cantidad diferencia,0 Tarifa2, Cantidad FROM Movimientos - WHERE Id_Ticket= intTicket AND Id_Article = 71; - END IF; - -- SELECT * FROM vn2008.portes; - - -- SELECT NULL, NULL, NULL, sum(diferencia) as Porte, NULL FROM portes p; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `precio` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `precio`( IN id_cli INT, id_art INT, id_wh INT ) -BEGIN -DECLARE tarifa,descompte, packin,groupin,caj,minimo, id_compra INT DEFAULT 0; -DECLARE importe_min, importe,bonus FLOAT DEFAULT NULL; - -SELECT PrecioEspecial INTO importe FROM PreciosEspeciales WHERE Id_Cliente = id_cli AND Id_Article = id_art; - -IF importe IS NULL THEN - SELECT `Min`, PVP INTO minimo, importe_min FROM `Articles` WHERE Id_Article = id_art; - SELECT Descuento - INTO tarifa - FROM Clientes - WHERE Id_Cliente = id_cli; - - SELECT CASE - WHEN tarifa =0 THEN IF(minimo AND IFNULL(fp.rate_0,C.PVP) < importe_min, importe_min, IFNULL(fp.rate_0,C.PVP)) - WHEN tarifa =1 THEN IF(minimo AND IFNULL(fp.rate_1,C.Tarifa1) < importe_min, importe_min, IFNULL(fp.rate_1,C.Tarifa1)) - WHEN tarifa =2 THEN IF(minimo AND IFNULL(fp.rate_2,C.Tarifa2) < importe_min, importe_min, IFNULL(fp.rate_2,C.Tarifa2)) - WHEN tarifa =3 THEN IF(minimo AND IFNULL(fp.rate_3,C.Tarifa3) < importe_min, importe_min, IFNULL(fp.rate_3,C.Tarifa3)) - WHEN tarifa BETWEEN 4 AND 100 THEN Tarifa1 - WHEN tarifa >100 THEN IF(minimo AND IFNULL(fp.rate_3,C.Tarifa3) * ( ( 200 - tarifa ) /100 ) < importe_min, importe_min,IFNULL(fp.rate_3,C.Tarifa3) * ( ( 200 - tarifa ) /100 )) - END, IFNULL(fp.Packing,C.Packing) Packing, C.Id_Compra,IFNULL(fp.grouping,C.grouping) grouping,IFNULL(fp.caja,C.caja) caja,fp.bonus INTO importe, packin, id_compra,groupin,caj,bonus - FROM Compres C - INNER JOIN Entradas E ON E.Id_Entrada = C.Id_Entrada - INNER JOIN travel T ON T.id = E.travel_id - LEFT JOIN price_fixed fp ON fp.item_id = id_art AND CURDATE() BETWEEN fp.date_start AND fp.date_end AND fp.warehouse_id IN (0,id_wh) - WHERE Id_Article = id_art - AND C.Novincular = FALSE - AND T.landing BETWEEN date_inv() AND CURDATE( ) - AND T.warehouse_id = id_wh - ORDER BY T.landing DESC - LIMIT 1; - - IF tarifa BETWEEN 4 AND 100 THEN SET descompte = tarifa; -END IF; - -IF minimo <> FALSE THEN - IF importe < importe_min THEN - SET importe = importe_min; -END IF; - -END IF; - -END IF; -SELECT importe, descompte, tarifa, packin, id_compra,groupin,caj,bonus -FROM DUAL; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `preOrdenarRuta` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `preOrdenarRuta`(IN vRutaId INT) -BEGIN - -UPDATE Tickets mt -JOIN ( - SELECT tt.Id_Consigna, round(ifnull(avg(t.Prioridad),0),0) as Prioridad - from Tickets t - JOIN Tickets tt on tt.Id_Consigna = t.Id_Consigna - where t.Fecha > TIMESTAMPADD(YEAR,-1,CURDATE()) - AND tt.Id_Ruta = vRutaId - GROUP BY Id_Consigna - ) sub ON sub.Id_Consigna = mt.Id_Consigna - SET mt.Prioridad = sub.Prioridad - WHERE mt.Id_Ruta = vRutaId; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `prepare_client_list` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `prepare_client_list`() -BEGIN - DROP TEMPORARY TABLE IF EXISTS tmp.client_list; - CREATE TEMPORARY TABLE tmp.client_list - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT DISTINCT Id_Cliente - FROM tmp.ticket_list; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `prepare_ticket_list` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `prepare_ticket_list`(vStartingDate DATETIME, vEndingDate DATETIME) -BEGIN - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - ENGINE = MEMORY - SELECT t.Id_Ticket, c.Id_Cliente - FROM Tickets t - LEFT JOIN vn.ticketState ts ON ts.ticket = t.Id_Ticket - JOIN Clientes c ON c.Id_Cliente = t.Id_Cliente - JOIN clientes_tipo ct ON ct.clientes_tipo_id = c.clientes_tipo_id - WHERE ct.code IN ('normal','handMaking') - AND ( - Fecha BETWEEN util.today() AND vEndingDate - OR ( - ts.alertLevel < 3 - AND t.Fecha >= vStartingDate - AND t.Fecha < util.today() - ) - ); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `price_detail` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `price_detail`(IN idART INT, IN datLanding DATE) -BEGIN - CALL item_last_buy_(NULL,datLanding); - - SELECT 'Ultimas compras',NULL as Entrada, NULL as Almacen, NULL as Tarifa3, NULL as Tarifa2 - UNION ALL - SELECT NULL, Id_Entrada, w.name, Tarifa3, Tarifa2 - FROM Compres c - JOIN t_item_last_buy b ON c.Id_Compra = b.buy_id - JOIN warehouse w on w.id = b.warehouse_id - WHERE b.item_id = idART - UNION all - SELECT 'Precios fijados',NULL, NULL as Almacen, NULL as Tarifa3, NULL as Tarifa2 - UNION ALL - SELECT NULL, CONCAT('de ', date_start, ' a ',date_end) , w.name, rate_3,rate_2 - FROM price_fixed - JOIN warehouse w on w.id = warehouse_id - WHERE item_id = idART - AND datLanding BETWEEN date_start AND date_end; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `proc_end` */; -/*!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 = latin1 */ ; -/*!50003 SET character_set_results = latin1 */ ; -/*!50003 SET collation_connection = latin1_swedish_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `proc_end`() -BEGIN - -UPDATE stat SET `end` = NOW() -WHERE id = (SELECT id FROM lastid); - -DROP TEMPORARY TABLE IF EXISTS lastid; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `proc_start` */; -/*!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 = latin1 */ ; -/*!50003 SET character_set_results = latin1 */ ; -/*!50003 SET collation_connection = latin1_swedish_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `proc_start`(IN v_proc_id INT) -BEGIN - -INSERT INTO stat(proc_id) VALUES(v_proc_id); - - -DROP TEMPORARY TABLE IF EXISTS lastid; -CREATE TEMPORARY TABLE lastid -SELECT last_insert_id() id; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `productionState` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`z-developer`@`%` PROCEDURE `productionState`(vWarehouse INT , vDate DATE) -BEGIN - - -SELECT IF(a.Vista= 2, z.alias, a.Agencia) Agencia, t.Id_Ruta, count(*) Pedidos -FROM Tickets t -JOIN Consignatarios CS on CS.Id_Consigna = t.Id_Consigna -JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN Agencias_province ap on ap.province_id = CS.province_id AND ap.warehouse_id = t.warehouse_id AND ap.agency_id = a.agency_id - LEFT JOIN Tickets_state tls on tls.Id_Ticket = t.Id_Ticket - LEFT JOIN zoneNickname z ON z.warehouse_id = ap.warehouse_id and z.agency_id = ap.agency_id AND z.zona = ap.zona - LEFT JOIN vncontrol.inter vni ON vni.inter_id = tls.inter_id - LEFT JOIN state s ON s.id = vni.state_id -WHERE Fecha BETWEEN vDate AND util.dayend(vDate) -AND s.alert_level = 1 -AND t.warehouse_id = vWarehouse -GROUP BY Agencia, Id_Ruta; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `production_buffer_problems` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `production_buffer_problems`() -BEGIN -/** - * Necesita la tabla tmp.ticket_list - */ - DECLARE vToday DATETIME; - DECLARE vTomorrowMidnight DATETIME ; - DECLARE vWarehouse INT; - DECLARE vDate DATE; - DECLARE vAvailableCache INT; - DECLARE vVisibleCache INT; - DECLARE vDone BOOL; - - DECLARE vCursor CURSOR FOR - SELECT DISTINCT warehouse_id, DATE(Fecha) - FROM tmp.ticket_list tt - JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket - AND DATE(t.Fecha) BETWEEN CURDATE() AND TIMESTAMPADD(DAY,1.9,CURDATE()); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DROP TEMPORARY TABLE IF EXISTS tmp.buffer_problems; - CREATE TEMPORARY TABLE tmp.buffer_problems ( - Id_Ticket INT(11), - problem VARCHAR(50), - INDEX (Id_Ticket) - ) - ENGINE = MEMORY; - - SET vToday = CURDATE(); - SET vTomorrowMidnight = TIMESTAMP(TIMESTAMPADD(DAY, 1, CURDATE()), '23:59:59'); - - OPEN vCursor; - - l: LOOP - SET vDone = FALSE; - FETCH vCursor INTO vWarehouse, vDate; - - IF vDone THEN - LEAVE l; - END IF; - - CALL cache.visible_refresh (vVisibleCache, FALSE, vWarehouse); - CALL cache.available_refresh (vAvailableCache, FALSE, vWarehouse, vDate); - - -- El disponible es menor que 0 - - INSERT INTO tmp.buffer_problems(Id_Ticket, problem) - SELECT tt.Id_Ticket, Article - FROM tmp.ticket_list tt - JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket - LEFT JOIN vn2008.Movimientos M ON M.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles A ON A.Id_Article = M.Id_Article - JOIN vn2008.Tipos tp on tp.tipo_id = A.tipo_id - LEFT JOIN cache.visible v ON A.Id_Article = v.item_id AND v.calc_id = vVisibleCache - LEFT JOIN cache.available av ON av.item_id = A.Id_Article AND av.calc_id = vAvailableCache - WHERE date(t.Fecha) = vDate - AND reino_id NOT IN (8,6) - AND M.Cantidad > IFNULL(v.visible,0) - AND M.Cantidad > 0 - AND IFNULL(av.available,0) < 0 - AND M.OK = FALSE - AND NOT generic - AND vWarehouse = t.warehouse_id; - - -- El disponible es mayor que cero y la cantidad supera el visible, estando aun sin preparar - INSERT INTO tmp.buffer_problems(Id_Ticket, problem) - SELECT tt.Id_Ticket, CONCAT('RETRASO (', A.Id_Article, ') ', Article) - FROM tmp.ticket_list tt - JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket - LEFT JOIN vn2008.Movimientos M ON M.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles A ON A.Id_Article = M.Id_Article - JOIN vn2008.Tipos tp on tp.tipo_id = A.tipo_id - LEFT JOIN cache.visible v ON A.Id_Article = v.item_id AND v.calc_id = vVisibleCache - LEFT JOIN ( - SELECT Id_Article FROM Articles_nicho - WHERE DATE(modificationDate) = CURDATE() AND warehouse_id = vWarehouse - ) nicho ON nicho.Id_Article = A.Id_Article - LEFT JOIN cache.available av ON av.item_id = A.Id_Article AND av.calc_id = vAvailableCache - WHERE IFNULL(av.available,0) >= 0 - AND M.Cantidad > IFNULL(v.visible,0) - AND M.OK = FALSE - AND M.Reservado = FALSE - AND reino_id NOT IN (8,6) - AND date(t.Fecha) = vDate - AND NOT generic - AND CURDATE() = vDate - AND t.warehouse_id = vWarehouse - AND nicho.Id_Article IS NULL; - END LOOP; - - CLOSE vCursor; - - -- Código 100 - - INSERT INTO tmp.buffer_problems(Id_Ticket, problem) - SELECT DISTINCT tt.Id_Ticket, 'COD 100' - FROM tmp.ticket_list tt - JOIN Movimientos m on m.Id_Ticket = tt.Id_Ticket - WHERE Id_Article = 100; - - -- Congelado - - INSERT INTO tmp.buffer_problems(Id_Ticket, problem) - SELECT DISTINCT tt.Id_Ticket, 'CONGELADO' - FROM tmp.ticket_list tt - JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket - JOIN Clientes c on c.Id_Cliente = t.Id_Cliente - WHERE c.Congelado; - - -- Datos del cliente sin confirmar - - INSERT INTO tmp.buffer_problems(Id_Ticket, problem) - SELECT DISTINCT tt.Id_Ticket, 'FICHA INCOMPLETA' - FROM tmp.ticket_list tt - JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket - JOIN Clientes c on c.Id_Cliente = t.Id_Cliente - WHERE c.contabilizado = FALSE; - - -- Riesgo - - CALL risk_vs_client_list(CURDATE()); - - INSERT INTO tmp.buffer_problems(Id_Ticket, problem) - SELECT DISTINCT tt.Id_Ticket, 'RIESGO' - FROM tmp.ticket_list tt - JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket - JOIN Agencias a on t.Id_Agencia = a.Id_Agencia - JOIN tmp.risk r on r.Id_Cliente = t.Id_Cliente - JOIN Clientes c on c.Id_Cliente = t.Id_Cliente - WHERE r.risk > c.Credito + 10 - AND (Vista != 3 OR t.Id_Agencia = 687); -- para que las recogidas se preparen, salvo las de Madrid - /* - -- Saldo vencido - INSERT INTO tmp.buffer_problems(Id_Ticket, problem) - SELECT DISTINCT tt.Id_Ticket, 'SALDO VENCIDO' - FROM tmp.ticket_list tt - JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket - JOIN Agencias a on t.Id_Agencia = a.Id_Agencia - JOIN bi.defaulters d ON d.client = t.Id_Cliente - WHERE d.amount > 200 AND d.date = CURDATE() - AND Vista != 3; -- para que las recogidas se preparen - */ -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `production_buffer_problemsOptimizado` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `production_buffer_problemsOptimizado`() -BEGIN -/* - * Necesita la tabla tmp.ticket_list - * - */ - DECLARE vWarehouse INT; - DECLARE vDate DATE; - DECLARE vAvailableCache INT; - DECLARE vVisibleCache INT; - DECLARE vDone INT DEFAULT 0; - - DECLARE vCursor CURSOR FOR - SELECT DISTINCT warehouse_id, date(Fecha) - FROM tmp.ticket_list tt - JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket - AND DATE(t.Fecha) BETWEEN CURDATE() AND TIMESTAMPADD(DAY,1.9,CURDATE()); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.buffer_problems; - CREATE TEMPORARY TABLE tmp.buffer_problems ( - Id_Ticket INT(11), - problem VARCHAR(50), - INDEX (Id_Ticket) - ) - ENGINE = MEMORY; - - - -- CONGELADO - INSERT INTO tmp.buffer_problems(Id_Ticket, problem) - SELECT DISTINCT tt.Id_Ticket, 'CONGELADO' - FROM tmp.ticket_list tt - JOIN Clientes c on c.Id_Cliente = tt.Id_Cliente - WHERE c.Congelado; - - -- eliminamos tickets con problemas para no volverlos a mirar - DROP TEMPORARY TABLE IF EXISTS tmp.ticketListFiltered; - - CREATE TEMPORARY TABLE tmp.ticketListFiltered - (PRIMARY KEY (Id_Ticket)) - ENGINE = MEMORY - SELECT tt.Id_Ticket, c.Id_Cliente - FROM tmp.ticket_list tt - JOIN Clientes c on c.Id_Cliente = tt.Id_Cliente - WHERE c.Congelado = 0; - - -- RIESGO - CALL risk_vs_client_list(CURDATE()); - - - INSERT INTO tmp.buffer_problems(Id_Ticket, problem) - SELECT DISTINCT tt.Id_Ticket, 'RIESGO' - FROM tmp.ticketListFiltered tt - JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket - JOIN Agencias a on t.Id_Agencia = a.Id_Agencia - JOIN tmp.risk r on r.Id_Cliente = t.Id_Cliente - JOIN Clientes c on c.Id_Cliente = t.Id_Cliente - WHERE r.risk > c.Credito + 10 - AND Vista != 3; -- para que las recogidas se preparen - - -- eliminamos tickets con problemas para no volverlos a mirar - DELETE tlf FROM tmp.ticketListFiltered tlf - JOIN tmp.buffer_problems bf ON tlf.Id_Ticket = bf.Id_Ticket; - - -- CODIGO 100 - INSERT INTO tmp.buffer_problems(Id_Ticket, problem) - SELECT DISTINCT tt.Id_Ticket, 'COD 100' - FROM tmp.ticket_list tt - JOIN Movimientos m on m.Id_Ticket = tt.Id_Ticket - WHERE Id_Article = 100; - - -- eliminamos tickets con problemas para no volverlos a mirar - DELETE tlf FROM tmp.ticketListFiltered tlf - JOIN tmp.buffer_problems bf ON tlf.Id_Ticket = bf.Id_Ticket; - - OPEN vCursor; - - WHILE NOT vDone - DO - FETCH vCursor INTO vWarehouse, vDate ; - - CALL cache.visible_refresh(vVisibleCache,FALSE,vWarehouse); - CALL cache.available_refresh(vAvailableCache,FALSE,vWarehouse,vDate); - - -- El disponible es menor que 0 - INSERT INTO tmp.buffer_problems(Id_Ticket, problem) - SELECT tt.Id_Ticket, Article - -- CONCAT(IF( M.Cantidad < IFNULL(v.visible,0) , 'NO HAY ','FALTARÁ ' ), Article) - FROM tmp.ticket_list tt - JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket - LEFT JOIN vn2008.Movimientos M ON M.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles A ON A.Id_Article = M.Id_Article - JOIN vn2008.Tipos tp on tp.tipo_id = A.tipo_id - LEFT JOIN cache.visible v ON A.Id_Article = v.item_id AND v.calc_id = vVisibleCache - LEFT JOIN cache.available av ON av.item_id = A.Id_Article AND av.calc_id = vAvailableCache - WHERE date(t.Fecha) = vDate - AND reino_id != 6 - AND M.Cantidad > IFNULL(v.visible,0) - AND IFNULL(av.available,0) < 0 - AND M.OK = FALSE - AND NOT generic - AND vWarehouse = t.warehouse_id; - - -- eliminamos tickets con problemas para no volverlos a mirar - DELETE tlf FROM tmp.ticketListFiltered tlf - JOIN tmp.buffer_problems bf ON tlf.Id_Ticket = bf.Id_Ticket; - - -- Amarillo: El disponible es mayor que cero y la cantidad supera el visible, estando aun sin preparar - INSERT INTO tmp.buffer_problems(Id_Ticket, problem) - SELECT tt.Id_Ticket, CONCAT('RETRASO ', Article) - FROM tmp.ticket_list tt - JOIN Tickets t on t.Id_Ticket = tt.Id_Ticket - LEFT JOIN vn2008.Movimientos M ON M.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles A ON A.Id_Article = M.Id_Article - JOIN vn2008.Tipos tp on tp.tipo_id = A.tipo_id - LEFT JOIN cache.visible v ON A.Id_Article = v.item_id AND v.calc_id = vVisibleCache - LEFT JOIN cache.available av ON av.item_id = A.Id_Article AND av.calc_id = vAvailableCache - WHERE IFNULL(av.available,0) >= 0 - AND M.Cantidad > IFNULL(v.visible,0) - AND M.OK = FALSE - AND M.Reservado = FALSE - AND reino_id != 6 - AND date(t.Fecha) = vDate - AND NOT generic - AND CURDATE() = vDate - AND t.warehouse_id = vWarehouse; - END WHILE; - - CLOSE vCursor; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `production_buffer_set_priority` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `production_buffer_set_priority`() -BEGIN - -DECLARE currentDayOfWeek INT; - -SET currentDayOfWeek = weekday(curdate()); - --- Sin provincia ni dia de envio -UPDATE tmp.production_buffer pb -LEFT JOIN -( - SELECT agency_id - , warehouse_id - , max_hour - FROM agency_hour ah - WHERE subtract_day < 225 - AND week_day is null - AND province_id is null - -) t on t.agency_id = pb.agency_id - and t.warehouse_id = pb.warehouse_id - -SET pb.Hora = IF(pb.Hora is null or pb.Hora = 0 or pb.Hora = 24,IFNULL(t.max_hour,24), pb.Hora) - ,pb.Departure =IFNULL(t.max_hour,0); - - --- Agencias sin provincia, machacan lo anterior si coinciden -UPDATE tmp.production_buffer pb -JOIN -( - SELECT agency_id - , warehouse_id - , shipmentDay(week_day, subtract_day) as shipmentDay - , max_hour - FROM agency_hour ah - WHERE subtract_day < 225 - AND agency_id is not null - AND week_day is not null - AND max_hour is not null - AND province_id is null - HAVING shipmentDay = currentDayOfWeek - -) t on t.agency_id = pb.agency_id - and t.warehouse_id = pb.warehouse_id - -SET pb.Hora = IF(pb.Hora is null or pb.Hora = 0 or pb.Hora = 24,t.max_hour, pb.Hora) -,pb.Departure = t.max_hour -; - - --- Agencias con provincia, se ejecuta para machacar lo anterior, si procede. -UPDATE tmp.production_buffer pb -JOIN -( - SELECT agency_id - , warehouse_id - , shipmentDay(week_day, subtract_day) as shipmentDay - , max_hour - , province_id - FROM agency_hour ah - WHERE subtract_day < 225 - AND agency_id is not null - AND week_day is not null - AND max_hour is not null - AND province_id is not null - HAVING shipmentDay = currentDayOfWeek - -) t on t.agency_id = pb.agency_id - and t.warehouse_id = pb.warehouse_id - and t.province_id = pb.province_id - -SET pb.Hora = IF(pb.Hora is null or pb.Hora = 0 or pb.Hora = 24,t.max_hour, pb.Hora) -,pb.Departure = t.max_hour -; - --- Pedidos del dia anterior son prioritarios -/* -UPDATE tmp.production_buffer pb -JOIN Tickets t ON t.Id_Ticket = pb.ticket -SET pb.Hora = 1 -WHERE t.Fecha < CURDATE(); -*/ -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `production_control_source` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `production_control_source`(vWarehouseId INT, vScopeDays TINYINT) -BEGIN - DECLARE vMidnight DATETIME DEFAULT TIMESTAMP(CURDATE(),'23:59:59'); - DECLARE vEndingDate DATETIME DEFAULT TIMESTAMPADD(DAY,vScopeDays,vMidnight); - DECLARE SAFE_ALERT_LEVEL INT DEFAULT 3; - DECLARE vLoadingDelay DECIMAL(5) DEFAULT 2; - - CALL prepare_ticket_list(TIMESTAMPADD(DAY,0,CURDATE()-1), vEndingDate); - CALL prepare_client_list; - CALL production_buffer_problems; - - DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; - CREATE TEMPORARY TABLE tmp.production_buffer - (PRIMARY KEY(Id_Ticket)) - ENGINE = MEMORY - SELECT t.Id_Ticket - , t.Id_Cliente - , t.warehouse_id - , t.Alias - , t.Bultos - , HOUR(t.Fecha) as Hora - , HOUR(t.Fecha) + vLoadingDelay as Departure - , MINUTE(t.Fecha) as minuto - , t.Id_Ruta - , IF(a.Vista = 2,ap.zona,0) as zona - , CS.Consignatario - , CS.CODPOSTAL - , CS.POBLACION - , p.name PROVINCIA - , IF(a.Vista= 2, CONCAT(LEFT(z.alias,16),' ',IFNULL(RIGHT(t.Id_Ruta,3),'')), a.Agencia) Agencia - , a.agency_id - , 0 AS `lines` - , CAST( 0 AS DECIMAL(5,2)) AS m3 - , 0 AS problems - , " " as problem - , IFNULL(tls.state,2) AS state - , w.Codigotrabajador - , DATE(t.Fecha) AS Fecha - , Averiguar_ComercialCliente_IdTicket(t.Id_Ticket) AS Comercial - , p.province_id - , tls.productionOrder as state_order - , ifnull(tls.alertLevel,0) alert_level - , t.boxed as palletized - FROM tmp.ticket_list tt - JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket - JOIN Consignatarios CS on CS.Id_Consigna = t.Id_Consigna - LEFT JOIN province p on p.province_id = CS.province_id - JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN Agencias_province ap on ap.province_id = CS.province_id AND ap.warehouse_id = t.warehouse_id AND ap.agency_id = a.agency_id - LEFT JOIN vn.ticketState tls on tls.ticket = tt.Id_Ticket - LEFT JOIN Trabajadores w on w.Id_Trabajador = tls.worker - LEFT JOIN zoneNickname z ON z.warehouse_id = ap.warehouse_id and z.agency_id = ap.agency_id AND z.zona = ap.zona - WHERE t.warehouse_id = vWarehouseId - AND a.Vista IN (1,2,3); - - - -- Líneas y volumen por ticket - - UPDATE tmp.production_buffer pb - JOIN ( - SELECT m.Id_Ticket, COUNT(Id_Movimiento) as `lines`, cast( sum( m.Cantidad * r.cm3 / 1000000 ) as decimal(10,2)) as m3 - FROM tmp.ticket_list tt - JOIN Movimientos m on tt.Id_Ticket = m.Id_Ticket - JOIN bi.rotacion r on m.Id_Article = r.Id_Article - WHERE r.warehouse_id = vWarehouseId - GROUP BY m.Id_Ticket - ) m on m.Id_Ticket = pb.Id_Ticket - SET pb.`lines` = m.`lines`, - pb.m3 = m.m3; - - DELETE FROM tmp.production_buffer - WHERE `lines`= 0; - - -- Cajas - - ALTER TABLE tmp.production_buffer - ADD Cajas DOUBLE DEFAULT NULL; - - UPDATE tmp.production_buffer pb - JOIN ( - SELECT t.Id_Ticket, sum(floor(m.Cantidad / c.Packing) * bultoCubico) as Cajas - FROM tmp.ticket_list tt - JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket - JOIN Movimientos m on m.Id_Ticket = t.Id_Ticket - JOIN cache.last_buy lb on lb.warehouse_id = t.warehouse_id AND lb.item_id = m.Id_Article - JOIN Compres c on c.Id_Compra = lb.buy_id - JOIN Cubos cb on cb.Id_Cubo = c.Id_Cubo - WHERE m.Cantidad > c.Packing - GROUP BY t.Id_Ticket - HAVING Cajas >= 1 - ) sub ON sub.Id_Ticket = pb.Id_Ticket - SET pb.Cajas = sub.Cajas; - - -- Artificial, Seco y Preservado: Reino 4 - - ALTER TABLE tmp.production_buffer - ADD lineasArtificial INT DEFAULT NULL; - - UPDATE tmp.production_buffer pb - JOIN ( - SELECT tt.Id_Ticket, COUNT(m.Id_Movimiento) as Lineas - FROM tmp.ticket_list tt - JOIN Movimientos m ON m.Id_Ticket = tt.Id_Ticket - JOIN Articles a ON a.Id_Article = m.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - JOIN reinos r ON r.id = tp.reino_id - WHERE reino = 'Artificial' - GROUP BY tt.Id_Ticket - HAVING Lineas >= 1 - ) sub ON sub.Id_Ticket = pb.Id_Ticket - SET pb.lineasArtificial = sub.Lineas; - - - -- Problemas por ticket - - UPDATE tmp.production_buffer pb - JOIN ( - SELECT Id_Ticket, COUNT(Id_Ticket) as problems, GROUP_CONCAT(problem) problem - FROM tmp.buffer_problems - GROUP BY Id_Ticket - ) p on p.Id_Ticket = pb.Id_Ticket - SET pb.problems = p.problems, - pb.problem = p.problem; - - -- Hora limite de preparación - - CALL production_buffer_set_priority; - - -- Entradas - - INSERT INTO tmp.production_buffer( - Fecha - , Id_Ticket - , Agencia - , Id_Cliente - , Consignatario - , state - , CodigoTrabajador - , m3 - , `lines` - ) - SELECT DISTINCT c.shipment AS Fecha - , c.Id_Entrada AS Id_Ticket - , warehouse.name - , c.Id_Proveedor - , c.ref AS Consignatario - , IF(BIT_OR(controlado.Id_Compra),6,IF(BIT_OR(preparado.Id_Compra),5,3)) AS state - , c.Id_Trabajador AS CodigoTrabajador - , round(sum(cm3) / 1000000,2) AS m3 - , count(c.Id_Compra) as `lines` - FROM v_compres c - INNER JOIN warehouse ON c.warehouse_id = warehouse.id - LEFT JOIN Compres_ok preparado ON c.Id_Compra = preparado.Id_Compra AND preparado.valor = 1 - LEFT JOIN Compres_ok controlado ON c.Id_Compra = controlado.Id_Compra AND controlado.valor = 2 - WHERE warehouse_id_out = vWarehouseId AND IFNULL(c.Confirmada,FALSE) = FALSE - AND c.shipment >= CURDATE() - GROUP BY Id_Entrada; - - -- Refresca la caché para el cierre dinámico de agencias - - CALL cache.departure_timing(vWarehouseId); - - -- Tickets de recogida - - REPLACE tmp.production_buffer( - Fecha - , Id_Ticket - , Agencia - , Id_Cliente - , Consignatario - , state - , CodigoTrabajador - , alert_level - , warehouse_id - ) - SELECT - DATE(t.Fecha) AS Fecha - , t.Id_Ticket - , a.Agencia - , t.Id_Cliente - , CS.Consignatario - , s.id as state - , w.Codigotrabajador - , ifnull(tls.alertLevel,0) alert_level - , vWarehouseId - FROM vn2008.Tickets t - JOIN vn2008.Consignatarios CS on CS.Id_Consigna = t.Id_Consigna - JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN vn2008.warehouse_pickup wp ON wp.agency_id = a.Id_Agencia - LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket - LEFT JOIN vn.state s ON s.id = tls.state - LEFT JOIN vn2008.Trabajadores w on w.Id_Trabajador = tls.worker - WHERE t.Fecha between TIMESTAMPADD(WEEK,-1,CURDATE()) AND dayend(TIMESTAMPADD(DAY,-1,CURDATE())) - AND wp.warehouse_id = vWarehouseId; - - -- DROP TEMPORARY TABLE tmp.ticket_list; - -- DROP TEMPORARY TABLE IF EXISTS tmp.risk; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `production_control_source_Beta` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `production_control_source_Beta`(vWarehouseId INT, vScopeDays TINYINT) -BEGIN - DECLARE vMidnight DATETIME DEFAULT TIMESTAMP(CURDATE(),'23:59:59'); - DECLARE vEndingDate DATETIME DEFAULT TIMESTAMPADD(DAY,vScopeDays,vMidnight); - DECLARE SAFE_ALERT_LEVEL INT DEFAULT 3; - DECLARE vLoadingDelay DECIMAL(5) DEFAULT 2; - - CALL prepare_ticket_list(TIMESTAMPADD(DAY,0,CURDATE()-1), vEndingDate); - CALL prepare_client_list; - CALL production_buffer_problems; - - IF vWarehouseId = 0 THEN - - DELETE tt.* - FROM tmp.ticket_list tt - JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket - WHERE t.warehouse_id NOT IN (1,44); - - ELSE - - DELETE tt.* - FROM tmp.ticket_list tt - JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket - WHERE t.warehouse_id != vWarehouseId; - - END IF; - - /* - DROP TEMPORARY TABLE IF EXISTS tmp.selectedWarehouses; - - IF vWarehouseId = 0 THEN - - CREATE TEMPORARY TABLE tmp.selectedWarehouses - (PRIMARY KEY(id)) - ENGINE = MEMORY - SELECT id - FROM warehouse - WHERE id = vWarehouseId; - - ELSE - - CREATE TEMPORARY TABLE tmp.selectedWarehouses - (PRIMARY KEY(id)) - ENGINE = MEMORY - SELECT id - FROM warehouse - WHERE id IN (1,44); -- Silla FV y Silla PCA - - END IF; - */ - - - DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; - CREATE TEMPORARY TABLE tmp.production_buffer - (PRIMARY KEY(Id_Ticket)) - ENGINE = MEMORY - SELECT t.Id_Ticket - , t.Id_Cliente - , t.warehouse_id - , t.Alias - , t.Bultos - , HOUR(t.Fecha) as Hora - , HOUR(t.Fecha) + vLoadingDelay as Departure - , MINUTE(t.Fecha) as minuto - , t.Id_Ruta - , IF(a.Vista = 2,ap.zona,0) as zona - , CS.Consignatario - , CS.CODPOSTAL - , CS.POBLACION - , p.name PROVINCIA - , IF(a.Vista= 2, CONCAT(LEFT(z.alias,16),' ',IFNULL(RIGHT(t.Id_Ruta,3),'')), a.Agencia) Agencia - , a.agency_id - , 0 AS `lines` - , CAST( 0 AS DECIMAL(5,2)) AS m3 - , 0 AS problems - , " " as problem - , IFNULL(tls.state,2) AS state - , w.Codigotrabajador - , DATE(t.Fecha) AS Fecha - , Averiguar_ComercialCliente_IdTicket(t.Id_Ticket) AS Comercial - , p.province_id - , tls.productionOrder as state_order - , ifnull(tls.alertLevel,0) alert_level - , t.boxed as palletized - FROM tmp.ticket_list tt - JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket - JOIN Consignatarios CS on CS.Id_Consigna = t.Id_Consigna - LEFT JOIN province p on p.province_id = CS.province_id - JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN Agencias_province ap on ap.province_id = CS.province_id AND ap.warehouse_id = t.warehouse_id AND ap.agency_id = a.agency_id - LEFT JOIN vn.ticketState tls on tls.ticket = tt.Id_Ticket - LEFT JOIN Trabajadores w on w.Id_Trabajador = tls.worker - LEFT JOIN zoneNickname z ON z.warehouse_id = ap.warehouse_id and z.agency_id = ap.agency_id AND z.zona = ap.zona - AND a.Vista IN (1,2,3); - - - -- Líneas y volumen por ticket - - UPDATE tmp.production_buffer pb - JOIN ( - SELECT m.Id_Ticket, COUNT(Id_Movimiento) as `lines`, cast( sum( m.Cantidad * r.cm3 / 1000000 ) as decimal(10,2)) as m3 - FROM tmp.ticket_list tt - JOIN Tickets t ON t.Id_Ticket = tt.Id_Ticket - JOIN Movimientos m on tt.Id_Ticket = m.Id_Ticket - JOIN bi.rotacion r on m.Id_Article = r.Id_Article AND r.warehouse_id = t.warehouse_id - GROUP BY m.Id_Ticket - ) m on m.Id_Ticket = pb.Id_Ticket - SET pb.`lines` = m.`lines`, - pb.m3 = m.m3; - - DELETE FROM tmp.production_buffer - WHERE `lines`= 0; - - -- Cajas - - ALTER TABLE tmp.production_buffer - ADD Cajas DOUBLE DEFAULT NULL; - - UPDATE tmp.production_buffer pb - JOIN ( - SELECT t.Id_Ticket, sum(floor(m.Cantidad / c.Packing) * bultoCubico) as Cajas - FROM tmp.ticket_list tt - JOIN Tickets t on tt.Id_Ticket = t.Id_Ticket - JOIN Movimientos m on m.Id_Ticket = t.Id_Ticket - JOIN cache.last_buy lb on lb.warehouse_id = t.warehouse_id AND lb.item_id = m.Id_Article - JOIN Compres c on c.Id_Compra = lb.buy_id - JOIN Cubos cb on cb.Id_Cubo = c.Id_Cubo - WHERE m.Cantidad > c.Packing - GROUP BY t.Id_Ticket - HAVING Cajas >= 1 - ) sub ON sub.Id_Ticket = pb.Id_Ticket - SET pb.Cajas = sub.Cajas; - - -- Artificial, Seco y Preservado: Reino 4 - - ALTER TABLE tmp.production_buffer - ADD lineasArtificial INT DEFAULT NULL; - - UPDATE tmp.production_buffer pb - JOIN ( - SELECT tt.Id_Ticket, COUNT(m.Id_Movimiento) as Lineas - FROM tmp.ticket_list tt - JOIN Movimientos m ON m.Id_Ticket = tt.Id_Ticket - JOIN Articles a ON a.Id_Article = m.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - JOIN reinos r ON r.id = tp.reino_id - WHERE reino = 'Artificial' - GROUP BY tt.Id_Ticket - HAVING Lineas >= 1 - ) sub ON sub.Id_Ticket = pb.Id_Ticket - SET pb.lineasArtificial = sub.Lineas; - - - -- Problemas por ticket - - UPDATE tmp.production_buffer pb - JOIN ( - SELECT Id_Ticket, COUNT(Id_Ticket) as problems, GROUP_CONCAT(problem) problem - FROM tmp.buffer_problems - GROUP BY Id_Ticket - ) p on p.Id_Ticket = pb.Id_Ticket - SET pb.problems = p.problems, - pb.problem = p.problem; - - -- Hora limite de preparación - - CALL production_buffer_set_priority; - - -- Entradas - - INSERT INTO tmp.production_buffer( - Fecha - , Id_Ticket - , Agencia - , Id_Cliente - , Consignatario - , state - , CodigoTrabajador - , m3 - , `lines` - ) - SELECT DISTINCT c.shipment AS Fecha - , c.Id_Entrada AS Id_Ticket - , warehouse.name - , c.Id_Proveedor - , c.ref AS Consignatario - , IF(BIT_OR(controlado.Id_Compra),6,IF(BIT_OR(preparado.Id_Compra),5,3)) AS state - , c.Id_Trabajador AS CodigoTrabajador - , round(sum(cm3) / 1000000,2) AS m3 - , count(c.Id_Compra) as `lines` - FROM v_compres c - INNER JOIN warehouse ON c.warehouse_id = warehouse.id - LEFT JOIN Compres_ok preparado ON c.Id_Compra = preparado.Id_Compra AND preparado.valor = 1 - LEFT JOIN Compres_ok controlado ON c.Id_Compra = controlado.Id_Compra AND controlado.valor = 2 - WHERE (warehouse_id_out = CASE vWarehouseId WHEN 0 THEN 1 ELSE vWarehouseId END - OR - warehouse_id_out = CASE vWarehouseId WHEN 0 THEN 44 ELSE vWarehouseId END) - AND IFNULL(c.Confirmada,FALSE) = FALSE - AND c.shipment >= CURDATE() - GROUP BY Id_Entrada; - - -- Refresca la caché para el cierre dinámico de agencias - - CALL cache.departure_timing; - - -- Tickets de recogida - - REPLACE tmp.production_buffer( - Fecha - , Id_Ticket - , Agencia - , Id_Cliente - , Consignatario - , state - , CodigoTrabajador - , alert_level - , warehouse_id - ) - SELECT - DATE(t.Fecha) AS Fecha - , t.Id_Ticket - , a.Agencia - , t.Id_Cliente - , CS.Consignatario - , s.id as state - , w.Codigotrabajador - , ifnull(tls.alertLevel,0) alert_level - , t.warehouse_id - FROM vn2008.Tickets t - JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Consignatarios CS on CS.Id_Consigna = t.Id_Consigna - JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN vn2008.warehouse_pickup wp ON wp.agency_id = a.Id_Agencia - LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket - LEFT JOIN vn.state s ON s.id = tls.state - LEFT JOIN vn2008.Trabajadores w on w.Id_Trabajador = tls.worker - WHERE t.Fecha between TIMESTAMPADD(WEEK,-1,CURDATE()) AND dayend(TIMESTAMPADD(DAY,-1,CURDATE())) - ; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `proveedores_saldo` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `proveedores_saldo`(IN datFEC DATE) -BEGIN - -SET datFEC = IF(datfec < CURDATE(), CURDATE(), datfec); - -SELECT P.Id_Proveedor - , P.Proveedor - , P.empresa_id - , P.pay_met_id - , P.cuenta - , RED(IFNULL(sub_tot.Saldo,0) + IFNULL(sub_fut.Saldo,0) + IFNULL(sub_hoy.Saldo,0)) Total - , RED(IFNULL(sub_hoy.Saldo,0) + IFNULL(sub_fut.Saldo,0)) Inmediato - , RED(IFNULL(sub_hoy.Saldo,0)) Vencido -FROM -(SELECT Id_Proveedor, Proveedor, id as empresa_id, pay_met_id, P.cuenta FROM Proveedores P INNER JOIN empresa) P - -LEFT JOIN -( -SELECT Id_Proveedor, empresa_id, SUM(Sald) as Saldo -FROM -( -SELECT RV.Fecha, SUM(-1* ROUND(IFNULL(cantidad,0) / IF(p.cuenta LIKE '___4______',rr.rate,1),2)) as Sald, proveedor_id as Id_Proveedor, empresa_id -FROM recibida_vencimiento RV -INNER JOIN recibida R ON RV.recibida_id = R.id -INNER JOIN Proveedores p ON p.Id_Proveedor = R.proveedor_id -INNER JOIN reference_rate rr ON rr.date=R.fecha -WHERE RV.fecha > datFEC - AND R.contabilizada -GROUP BY proveedor_id, empresa_id -UNION ALL -SELECT fecha, red(SUM(IFNULL(importe,0))), id_proveedor, empresa_id -FROM pago -WHERE fecha > datFEC -GROUP BY id_proveedor, empresa_id -) sub -GROUP BY Id_Proveedor, empresa_id -) sub_tot USING(Id_Proveedor, empresa_id) - --- Saldo inmediato - -LEFT JOIN -( -SELECT Id_Proveedor, empresa_id, SUM(Sald) as Saldo -FROM -( -SELECT RV.Fecha, SUM(-1* ROUND(IFNULL(cantidad,0)/ IF(p.cuenta LIKE '___4______',rr.rate,1),2)) as Sald, proveedor_id as Id_Proveedor, empresa_id -FROM recibida_vencimiento RV -INNER JOIN recibida R ON RV.recibida_id = R.id -INNER JOIN Proveedores p ON p.Id_Proveedor = R.proveedor_id -INNER JOIN reference_rate rr ON rr.date = R.fecha -WHERE RV.fecha BETWEEN CURDATE() AND datFEC -AND R.contabilizada -GROUP BY proveedor_id, empresa_id -UNION ALL -SELECT fecha, ROUND(SUM(IFNULL(importe,0)),2), id_proveedor, empresa_id -FROM pago -WHERE fecha BETWEEN CURDATE() AND datFEC -GROUP BY id_proveedor, empresa_id -) sub3 -GROUP BY Id_Proveedor, empresa_id -) sub_fut USING(Id_Proveedor, empresa_id) - - - -LEFT JOIN -( -SELECT Id_Proveedor, empresa_id, SUM(Sald) as Saldo -FROM -( -SELECT RV.Fecha, SUM(-1* ROUND(IFNULL(cantidad,0)/ IF(p.cuenta LIKE '___4______',rr.rate,1),2)) as Sald, proveedor_id as Id_Proveedor, empresa_id -FROM recibida_vencimiento RV -INNER JOIN recibida R ON RV.recibida_id = R.id -INNER JOIN Proveedores p ON p.Id_Proveedor = R.proveedor_id -INNER JOIN reference_rate rr ON rr.date = R.fecha -WHERE RV.fecha > '2014-12-31' AND RV.fecha < CURDATE() -AND R.contabilizada -GROUP BY proveedor_id, empresa_id -UNION ALL -SELECT fecha, red(SUM(IFNULL(importe,0))), id_proveedor, empresa_id -FROM pago -WHERE fecha > '2014-12-31' AND fecha < CURDATE() -GROUP BY id_proveedor, empresa_id -) sub5 -GROUP BY Id_Proveedor, empresa_id -) sub_hoy USING(Id_Proveedor, empresa_id) -WHERE abs(sub_tot.Saldo) >0.2 - OR ABS(sub_fut.Saldo) >0.2 - OR ABS(sub_hoy.Saldo) >0.2 -; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `proveedores_saldos` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `proveedores_saldos`() -BEGIN - - DECLARE startingDate DATETIME DEFAULT TIMESTAMPADD(MONTH,-3,CURDATE()); - - DROP TEMPORARY TABLE IF EXISTS saldos_iniciales; - - CREATE TEMPORARY TABLE saldos_iniciales - - (proveedor_id INT NOT NULL - , empresa_id INT NOT NULL - , saldo_inicial double NOT NULL - , saldo_final DOUBLE NOT NULL - , moneda_id INT NOT NULL - , PRIMARY KEY(proveedor_id, empresa_id, moneda_id)) - ENGINE = MEMORY; - - -- Calcula el saldo inicial y final de cada proveedor - INSERT INTO saldos_iniciales - SELECT id_proveedor, empresa_id, sum(importe * isBeforeStarting) as saldo_inicial,sum(importe) saldo_final, moneda_id - FROM ( - SELECT - p.id_proveedor, - p.empresa_id, - if(p.id_moneda = 1, p.importe, p.divisa) as importe, - if( p.fecha < startingDate,1,0) isBeforeStarting, - p.id_moneda moneda_id - FROM pago p - WHERE p.fecha > '2014-12-31' - AND p.empresa_id = 442 - AND p.id_proveedor <> 567 - - UNION ALL - - SELECT - r.proveedor_id, - r.empresa_id, - - if(r.moneda_id = 1, rv.cantidad, rv.divisa) AS Total, - if(rv.fecha < startingDate,1,0) isBeforeStarting, - r.moneda_id - FROM - recibida r - INNER JOIN recibida_vencimiento rv ON r.id = rv.recibida_id - WHERE r.fecha > '2014-12-31' - AND r.contabilizada AND r.empresa_id = 442 - AND r.proveedor_id <> 567 - ) sub - GROUP BY empresa_id, id_proveedor, moneda_id; - - DROP TEMPORARY TABLE IF EXISTS vencimientos_pendientes; - - CREATE TEMPORARY TABLE vencimientos_pendientes - (vencimiento_id INT, id INT auto_increment - ,fecha DATE - ,proveedor_id INT NOT NULL - ,empresa_id INT NOT NULL - ,importe DECIMAL(10,2) NOT NULL - ,moneda_id INT NOT NULL - ,pendiente DECIMAL(10,2) DEFAULT 0 - ,saldo DECIMAL(10,2) DEFAULT 0 - ,saldoFinal DECIMAL(10,2) DEFAULT 0 - ,isPago BOOLEAN - ,conciliado BOOLEAN - ,PRIMARY KEY(id), - INDEX(proveedor_id,empresa_id,moneda_id)) - ENGINE = MEMORY; - - INSERT INTO vencimientos_pendientes(vencimiento_id - , fecha - , proveedor_id - , empresa_id - , importe - , moneda_id - , isPago - , conciliado) - SELECT p.id, - p.fecha, - p.id_proveedor, - p.empresa_id, - if(p.id_moneda = 1, p.importe, p.divisa) as importe, - p.id_moneda, - TRUE isPago, - p.conciliado - FROM pago p - WHERE p.fecha >= startingDate AND p.empresa_id = 442 - AND p.id_proveedor <> 567 - UNION ALL - SELECT rv.id - , rv.fecha - , r.proveedor_id - , r.empresa_id - , -if(r.moneda_id = 1, rv.cantidad, rv.divisa) as importe - , r.moneda_id - , FALSE - , TRUE - FROM recibida r - LEFT JOIN saldos_iniciales si ON r.empresa_id = si.empresa_id AND r.proveedor_id = si.proveedor_id AND r.moneda_id = si.moneda_id - INNER JOIN recibida_vencimiento rv ON r.id = rv.recibida_id - WHERE rv.fecha >= startingDate AND IFNULL(saldo_final,TRUE) <> 0 - and r.contabilizada AND r.empresa_id = 442 - AND r.proveedor_id <> 567 - ORDER BY id_proveedor, empresa_id, id_moneda, fecha, isPago DESC,id; - - -- Ahora, calculamos el importe pendiente para cada recibo en orden descendente - SET @saldo:= 0.0; - SET @prov := 0.0; - SET @emp := 0.0; - set @moneda := 0.0; - SET @pendiente := 0.0; - SET @day := CURDATE(); - - UPDATE vencimientos_pendientes vp LEFT JOIN saldos_iniciales si ON - vp.empresa_id = si.empresa_id AND vp.proveedor_id = si.proveedor_id AND vp.moneda_id = si.moneda_id - SET vp.saldo = @saldo:= (IF(@emp <> vp.empresa_id OR @prov <> vp.proveedor_id OR @moneda <> vp.moneda_id, IFNULL(si.saldo_inicial,0),@saldo) + vp.importe) -- si hay cambio de empresa o proveedor o moneda, el saldo se reinicia - , vp.pendiente = @pendiente:= IF(@emp <> vp.empresa_id OR @prov <> vp.proveedor_id OR @moneda <> vp.moneda_id OR @day <> vp.fecha, vp.importe * (NOT isPago) , @pendiente + vp.importe) - , vp.empresa_id = @emp:= vp.empresa_id - , vp.proveedor_id = @prov:= vp.proveedor_id - , vp.moneda_id = @moneda:= vp.moneda_id - , vp.fecha = @day:= vp.fecha - , vp.saldo = @saldo - , vp.pendiente = @pendiente; - - CREATE TEMPORARY TABLE rowsToDelete - ENGINE = MEMORY - SELECT fecha,proveedor_id,empresa_id,moneda_id - FROM vencimientos_pendientes - WHERE saldo < 0.5 AND saldo > -0.5; - - DELETE vp.* FROM vencimientos_pendientes vp JOIN rowsToDelete rd - ON vp.fecha <= rd.fecha AND vp.proveedor_id = rd.proveedor_id AND vp.empresa_id = rd.empresa_id AND vp.moneda_id = rd.moneda_id - WHERE isPago = FALSE; - - SELECT vp.vencimiento_id - , vp.fecha - , vp.proveedor_id - , vp.empresa_id - , vp.moneda_id - , vp.importe - , vp.pendiente - , vp.saldo - , p.pay_met_id - , vp.isPago - , vp.conciliado - , vp.saldoFinal - FROM vencimientos_pendientes vp - LEFT JOIN Proveedores p ON p.Id_Proveedor = vp.proveedor_id; - - DROP TEMPORARY TABLE vencimientos_pendientes; - DROP TEMPORARY TABLE saldos_iniciales; - DROP TEMPORARY TABLE rowsToDelete; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `proveedores_saldoskk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `proveedores_saldoskk`() -BEGIN - - - -DROP TEMPORARY TABLE IF EXISTS proveedores_pendientes; - -CREATE TEMPORARY TABLE proveedores_pendientes -( proveedor_id INT NOT NULL -, empresa_id INT NOT NULL -, saldo double NOT NULL -, moneda_id INT NOT NULL -, PRIMARY KEY(proveedor_id, empresa_id, moneda_id)); - -INSERT INTO proveedores_pendientes -SELECT id_proveedor, empresa_id, sum(importe) as saldo, id_moneda as moneda_id - FROM - ( - SELECT - p.id_proveedor, - p.empresa_id, - - if(p.id_moneda = 1, p.importe, p.divisa) as importe, - p.id_moneda - - FROM - pago p - - WHERE - - p.fecha > '2014-12-31' - - UNION ALL - - SELECT - r.proveedor_id, - r.empresa_id, - if(r.moneda_id = 1, rv.cantidad, rv.divisa) AS Total, - r.moneda_id - - FROM - recibida r - INNER JOIN recibida_vencimiento rv ON r.id = rv.recibida_id - WHERE r.fecha > '2014-12-31' AND r.contabilizada - ) sub - GROUP BY empresa_id, id_proveedor, moneda_id - having saldo > 0; - - - - DROP TEMPORARY TABLE IF EXISTS vencimientos_pendientes_aux; - - CREATE TEMPORARY TABLE vencimientos_pendientes_aux - (vencimiento_id INT, id INT auto_increment - ,fecha DATE - ,proveedor_id INT NOT NULL - ,empresa_id INT NOT NULL - ,importe double NOT NULL - ,moneda_id INT NOT NULL - ,pendiente DOUBLE DEFAULT 0 - ,PRIMARY KEY(id)); - - SET @imp:= 0; - - INSERT INTO vencimientos_pendientes_aux(vencimiento_id - , fecha - , proveedor_id - , empresa_id - , importe - , moneda_id - , pendiente) - - - - SELECT rv.id - , rv.fecha - , r.proveedor_id - , r.empresa_id - , @imp:= if(r.moneda_id = 1, rv.cantidad, rv.divisa) as importe - , r.moneda_id - , pp.saldo - FROM recibida r - INNER JOIN recibida_vencimiento rv ON r.id = rv.recibida_id - JOIN proveedores_pendientes pp ON pp.proveedor_id = r.proveedor_id AND pp.empresa_id = r.empresa_id AND pp.moneda_id = r.moneda_id - WHERE r.fecha > '2010-12-31' - and rv.fecha > TIMESTAMPADD(MONTH,-3,CURDATE()) - and r.contabilizada; - - - DROP TEMPORARY TABLE IF EXISTS vencimientos_pendientes; - - CREATE TEMPORARY TABLE vencimientos_pendientes - (vencimiento_id INT, id INT , id2 INT auto_increment - ,fecha DATE - ,proveedor_id INT NOT NULL - ,empresa_id INT NOT NULL - ,importe double NOT NULL - ,moneda_id INT NOT NULL - ,pendiente DOUBLE DEFAULT 0 - ,saldo DOUBLE - ,PRIMARY KEY(id2)); - - - - INSERT INTO vencimientos_pendientes(vencimiento_id - , id - , fecha - , proveedor_id - , empresa_id - , importe - , moneda_id - , pendiente - , saldo) - - - - SELECT vencimiento_id, id, fecha, proveedor_id, empresa_id, importe, moneda_id, 0, pp.saldo - FROM vencimientos_pendientes_aux vp - JOIN proveedores_pendientes pp USING(proveedor_id, empresa_id, moneda_id) - ORDER BY proveedor_id, empresa_id, moneda_id, fecha DESC, importe; - - DROP TEMPORARY TABLE vencimientos_pendientes_aux; - - - -- Ahora, al fin, calculamos el importe pendiente para cada recibo en orden descendente - - -- Cogemos los valores del primer registro como semilla - SELECT proveedor_id, empresa_id, saldo, moneda_id, 0 - INTO @prov, @emp, @saldo, @moneda, @pend - FROM vencimientos_pendientes WHERE id2 = 1; - - - UPDATE vencimientos_pendientes - SET saldo = @saldo:= IF(@emp <> empresa_id OR @prov <>proveedor_id OR @moneda <> moneda_id,saldo,@saldo) -- si hay cambio de empresa o proveedor o moneda, el saldo se reinicia - , pendiente = @pend:= IF(saldo >= importe AND saldo > 0, importe, saldo) - , saldo = @saldo:= @saldo - @pend - , empresa_id = @emp:= empresa_id - , proveedor_id = @prov:= proveedor_id - , moneda_id = @moneda:= moneda_id; - - SELECT vp.vencimiento_id - , vp.fecha - , vp.proveedor_id - , vp.empresa_id - , vp.moneda_id - , vp.importe - , vp.pendiente - , pp.saldo - FROM vencimientos_pendientes vp - JOIN proveedores_pendientes pp USING(proveedor_id, empresa_id, moneda_id) - WHERE pendiente > 0; - - DROP TEMPORARY TABLE vencimientos_pendientes; - DROP TEMPORARY TABLE proveedores_pendientes; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `prueba_miguel` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `prueba_miguel`() -BEGIN -select 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 DROP PROCEDURE IF EXISTS `quadre_clientes` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `quadre_clientes`(IN datFEC DATETIME) -BEGIN - - - DECLARE datSTART DATE; - SET datFEC = TIMESTAMP(datFEC,'23:59:59'); - SELECT FIRSTDAYOFYEAR(datFEC) INTO datSTART; - - SELECT P2.Alias, C.Id_Cliente, C.Cuenta, Gestion, Contaplus, Gestion - Contaplus as Diferencia, empresa_id, Cliente - - FROM Clientes C - - JOIN pay_met pm ON pm.id = C.pay_met_id - - JOIN - - ( - - SELECT empresa_id, Id_Cliente, round(sum(Gestion),2) as Gestion, round(sum(Contaplus),2) as Contaplus - - FROM - - ( - SELECT empresa_id, Id_Cliente, Gestion, 0 as Contaplus - - FROM - - ( - SELECT empresa_id, Id_Cliente, -1 * Importe as Gestion - FROM Facturas - WHERE Fecha BETWEEN datSTART AND datFEC - UNION ALL - SELECT empresa_id, Id_Cliente, Entregado - FROM Recibos - WHERE Fechacobro BETWEEN datSTART AND datFEC - ) G - - WHERE empresa_id <> 965 - - UNION ALL - - SELECT empresa_id, Id_Cliente, 0, round(nz(Eurohaber) - nz(Eurodebe),2) as Contaplus - - FROM bi.XDiario_ALL XD - - JOIN Clientes C ON C.Cuenta = XD.SUBCTA - - WHERE Fecha BETWEEN datSTART AND datFEC - - ) sub1 - - GROUP BY empresa_id, Id_Cliente - - ) sub2 USING(Id_Cliente) - - JOIN Proveedores P2 ON P2.Id_Proveedor = sub2.empresa_id - - WHERE pm.deudaviva -- Cliente de perdidas no vale la pena revisarlo - - HAVING ABS(Diferencia) > 0.05 - - ORDER BY Cliente; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `quadre_clientes_detalle` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `quadre_clientes_detalle`(IN idC INT, IN idE INT, IN datFEC DATETIME) -BEGIN - -DECLARE datSTART DATE; - -SET datSTART = FIRSTDAYOFYEAR(datFEC); -SET datFEC = TIMESTAMP(datFEC,'23:59:59'); - --- Creamos una tabla para almacenar las facturas del cliente, junto con el numero de veces que se repite. -DROP TEMPORARY TABLE IF EXISTS qFACTURAS; - -CREATE TEMPORARY TABLE qFACTURAS -(Fecha DATETIME, - TPVcount INT, - Factura DECIMAL(10,2) SIGNED, - Recibo DECIMAL(10,2) SIGNED, - CPcount INT, - Debe DECIMAL(10,2) SIGNED, - Haber DECIMAL(10,2) SIGNED, - Control INT DEFAULT 0, - PRIMARY KEY(Fecha, TPVcount, Factura, Recibo, CPcount, Debe, Haber)) - ENGINE = InnoDB -; - --- Insertamos las facturas y los recibos de gestion. -INSERT INTO qFACTURAS - - SELECT Fecha, COUNT(*) as TPVcount, round(Importe,2) as Factura, 0 as Recibo, COUNT(*)as CPcount,round(Importe,2) as Debe, 0 as Haber, 1 as Control - FROM Facturas - WHERE Id_Cliente = idC AND empresa_id = idE AND Fecha BETWEEN datSTART AND datFEC - GROUP BY Fecha, round(Importe,2) - UNION ALL - SELECT Fechacobro as Fecha, COUNT(*) as TPVcount, 0 as Factura, round(Entregado,2) as Recibo,COUNT(*) as CPCount, 0 as Debe, round(Entregado,2) as Haber, 3 as Control - FROM Recibos - WHERE Id_Cliente = idC AND empresa_id = idE AND Fechacobro BETWEEN datSTART AND datFEC - GROUP BY Fechacobro, round(Entregado,2); - --- Insertamos los asientos de contabilidad, marcando con control = -1 las repetidas. -INSERT INTO qFACTURAS - SELECT * - FROM ( - SELECT Fecha, COUNT(*) as TPVcount, round(Eurodebe,2) as Factura, round(Eurohaber,2) as Recibo, COUNT(*) as CPcount, round(Eurodebe,2) as Debe, round(Eurohaber,2) as Haber, 2 as Control - FROM bi.XDiario_ALL XD - JOIN Clientes C ON C.Cuenta = XD.SUBCTA - WHERE Id_Cliente = idC AND empresa_id = idE AND Fecha BETWEEN datSTART AND datFEC - AND (Eurodebe <> 0 OR Eurohaber <>0) - GROUP BY Fecha, round(Eurodebe,2), round(Eurohaber,2) - ) sub - - ON DUPLICATE KEY UPDATE Control = -1; - - - --- Eliminamos las repetidas --- DELETE FROM qFACTURAS WHERE Control = -1; - --- Arreglamos las buenas -UPDATE qFACTURAS SET TPVcount = 0, Factura = 0, Recibo = 0 WHERE Control = 2; -UPDATE qFACTURAS SET CPcount = 0, Debe = 0, Haber = 0 WHERE Control IN (1,3); - --- Mostramos el resultado -SELECT *, @saldo := @saldo + TPVcount * (Factura + Recibo) - CPCount * ( Debe + Haber ) as Saldo -FROM qFACTURAS -JOIN (SELECT @saldo := 0) truqui ; -DROP TEMPORARY TABLE IF EXISTS qFACTURAS; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `quadre_proveedores` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `quadre_proveedores`(IN datFEC DATETIME) -BEGIN - - DECLARE datSTART DATE; - SET datFEC = TIMESTAMP(datFEC,'23:59:59'); - - SELECT FIRSTDAYOFYEAR(datFEC) INTO datSTART; - - SELECT P2.Alias, P.Id_Proveedor, P.Cuenta, Gestion, Contaplus, Gestion - Contaplus as Diferencia, empresa_id, P.Proveedor - - FROM Proveedores P - - JOIN - - ( - - SELECT empresa_id, Id_Proveedor, round(sum(Gestion),2) as Gestion, round(sum(Contaplus),2) as Contaplus - - FROM - - ( - SELECT empresa_id, proveedor_id as Id_Proveedor, Gestion, 0 as Contaplus - - FROM - - ( - SELECT empresa_id, proveedor_id, -1 * sum(cantidad) as Gestion - FROM recibida_vencimiento rv - INNER JOIN recibida r ON r.id = rv.recibida_id - WHERE IFNULL(r.bookEntried,r.fecha) BETWEEN datSTART AND datFEC - AND r.contabilizada - GROUP BY r.id - - UNION ALL - - SELECT empresa_id, id_proveedor, importe - FROM pago - WHERE Fecha BETWEEN datSTART AND datFEC - AND conciliado - AND pay_met_id <> 18 -- Saldos iniciales - ) G - - UNION ALL - - SELECT empresa_id, Id_Proveedor, 0, round(nz(Eurodebe) - nz(Eurohaber),2) as Contaplus - - FROM bi.XDiario_ALL XD - - JOIN Proveedores P ON P.cuenta = XD.SUBCTA - - WHERE Fecha BETWEEN datSTART AND datFEC - - - ) sub1 - - - GROUP BY empresa_id, Id_Proveedor - - ) sub2 USING(Id_Proveedor) - - JOIN Proveedores P2 ON P2.Id_Proveedor = sub2.empresa_id - - HAVING ABS(Diferencia) > 0.05 - - ORDER BY P.Proveedor; - - - - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `quadre_proveedores_detalle` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `quadre_proveedores_detalle`(IN idP INT, IN idE INT, IN datFEC DATETIME) -BEGIN - -DECLARE datSTART DATE; -SET datFEC = TIMESTAMP(datFEC,'23:59:59'); - -SET datSTART = FIRSTDAYOFYEAR(datFEC); - --- Creamos una tabla para almacenar las facturas del proveedor, junto con el numero de veces que se repite. -DROP TEMPORARY TABLE IF EXISTS qFACTURAS; - -CREATE TEMPORARY TABLE qFACTURAS -(Fecha DATE, - TPVcount INT, - Factura DECIMAL(10,2) SIGNED, - Recibo DECIMAL(10,2) SIGNED, - CPcount INT, - Debe DECIMAL(10,2) SIGNED, - Haber DECIMAL(10,2) SIGNED, - Control INT DEFAULT 0, - PRIMARY KEY(Fecha, TPVcount, Factura, Recibo, CPcount, Debe, Haber)) - ENGINE = InnoDB -; - --- Insertamos las facturas y los pagos de gestion. -INSERT INTO qFACTURAS - - SELECT Fecha, COUNT(*) as TPVcount, round(Importe,2) as Factura - , 0 as Recibo, COUNT(*)as CPcount,round(Importe,2) as Debe, 0 as Haber, 1 as Control - FROM (SELECT IFNULL(r.dateBooking,r.Fecha) as Fecha, sum(rv.cantidad) as Importe - FROM recibida_vencimiento rv - JOIN recibida r ON r.id = rv.recibida_id - WHERE proveedor_id = idP - AND empresa_id = idE - AND IFNULL(r.dateBooking,r.Fecha) BETWEEN datSTART AND datFEC - AND (r.contabilizada OR r.dateBooking) - GROUP BY r.id) F - GROUP BY Fecha, round(Importe,2) - UNION ALL - SELECT Fecha, COUNT(*) as TPVcount, 0 as Factura, round(importe,2) as Recibo,COUNT(*) as CPCount, 0 as Debe, round(importe,2) as Haber, 3 as Control - FROM pago - WHERE Id_Proveedor = idP AND empresa_id = idE AND Fecha BETWEEN datSTART AND datFEC - AND conciliado - GROUP BY Fecha, round(importe,2); - --- Insertamos los asientos de contabilidad, marcando con control = -1 las repetidas -INSERT INTO qFACTURAS - SELECT * - FROM ( - SELECT Fecha, COUNT(*) as TPVcount, round(Eurohaber,2) as Factura, round(Eurodebe,2) as Recibo, COUNT(*) as CPcount, round(Eurohaber,2) as Debe, round(Eurodebe,2) as Haber, 2 as Control - FROM bi.XDiario_ALL XD - JOIN Proveedores P ON P.cuenta = XD.SUBCTA - WHERE Id_Proveedor = idP AND empresa_id = idE AND Fecha BETWEEN datSTART AND datFEC - AND (Eurodebe <> 0 OR Eurohaber <>0) - GROUP BY Fecha, round(Eurohaber,2), round(Eurodebe,2) - ) sub - - ON DUPLICATE KEY UPDATE Control = -1; - - - --- Eliminamos las repetidas -DELETE FROM qFACTURAS WHERE Control = -1; - --- Arreglamos las buenas -UPDATE qFACTURAS SET TPVcount = 0, Factura = 0, Recibo = 0 WHERE Control = 2; -UPDATE qFACTURAS SET CPcount = 0, Debe = 0, Haber = 0 WHERE Control IN (1,3); - --- Mostramos el resultado -SELECT *, @saldo := @saldo + TPVcount * (Factura + Recibo) - CPcount * (Debe + Haber) as Saldo -FROM qFACTURAS -JOIN (SELECT @saldo := 0) truqui ; - -DROP TEMPORARY TABLE IF EXISTS qFACTURAS; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `quadre_proveedores_test` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `quadre_proveedores_test`(IN datFEC DATETIME) -BEGIN - - DECLARE datSTART DATE; - SET datFEC = TIMESTAMP(datFEC,'23:59:59'); - - SELECT FIRSTDAYOFYEAR(datFEC) INTO datSTART; - - SELECT P2.Alias, P.Id_Proveedor, P.Cuenta, Gestion, Contaplus, Gestion - Contaplus as Diferencia, empresa_id, P.Proveedor - - FROM Proveedores P - - JOIN - - ( - - SELECT empresa_id, Id_Proveedor, round(sum(Gestion),2) as Gestion, round(sum(Contaplus),2) as Contaplus - - FROM - - ( - SELECT empresa_id, proveedor_id as Id_Proveedor, Gestion, 0 as Contaplus - - FROM - - ( - SELECT empresa_id, proveedor_id, -1 * sum(cantidad) as Gestion - FROM recibida_vencimiento rv - INNER JOIN recibida r ON r.id = rv.recibida_id - WHERE r.Fecha BETWEEN datSTART AND datFEC - AND r.contabilizada - GROUP BY r.id - - UNION ALL - - SELECT empresa_id, id_proveedor, importe - FROM pago - WHERE Fecha BETWEEN datSTART AND datFEC - AND conciliado - AND pay_met_id <> 18 -- Saldos iniciales - ) G - - UNION ALL - - SELECT empresa_id, Id_Proveedor, 0, round(nz(Eurodebe) - nz(Eurohaber),2) as Contaplus - - FROM bi.XDiario_ALL XD - - JOIN Proveedores P ON P.cuenta = XD.SUBCTA - - WHERE Fecha BETWEEN datSTART AND datFEC - - - ) sub1 - - - GROUP BY empresa_id, Id_Proveedor - - ) sub2 USING(Id_Proveedor) - - JOIN Proveedores P2 ON P2.Id_Proveedor = sub2.empresa_id - - HAVING ABS(Diferencia) > 0.05 - - ORDER BY P.Proveedor; - - - - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `radar` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `radar`(IN today DATETIME, IN worker INTEGER, IN scopeDays SMALLINT) -BEGIN - - DECLARE todayMidnight DATE DEFAULT TIMESTAMP(today,'23:59:59'); - DECLARE yesterday DATETIME; - DECLARE maxDate DATETIME; - DECLARE datBUF DATETIME; - DECLARE warehouse INTEGER; - DECLARE done BIT DEFAULT 0; - DECLARE visible_calc INTEGER; - DECLARE available_calc INTEGER; - DECLARE dateStart DATE; - - SET dateStart = TIMESTAMPADD(MONTH, -2, CURDATE()); - SELECT TIMESTAMPADD(DAY, -1, today) INTO yesterday; - -- lo quitamos despues de campañaA - SELECT TIMESTAMP(TIMESTAMPADD(DAY, scopeDays, yesterday),'23:59:59') INTO maxDate; - -- SELECT TIMESTAMP(TIMESTAMPADD(DAY, 14, yesterday),'23:59:59') INTO maxDate; - -- Creamos una tabla con los Comerciales de los que se mostraran los tickets - CALL subordinate(worker,TRUE); - - -- Se genera una tabla con los tickets representados - DROP TEMPORARY TABLE IF EXISTS ticketRange; - CREATE TEMPORARY TABLE ticketRange - SELECT T.Id_Ticket, T.Id_Cliente, C.Id_Trabajador - FROM Tickets T - LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket - INNER JOIN Clientes C on C.Id_Cliente = T.Id_Cliente - INNER JOIN subordinate s1 ON C.Id_Trabajador = s1.Id_Trabajador - WHERE Fecha >= yesterday - AND Fecha <= maxDate AND T.Factura Is NULL - AND IFNULL(tls.alertLevel,0) < 3 - - UNION DISTINCT - - SELECT Id_Ticket, s.Id_Cliente, s.Id_Trabajador - FROM sharingclient s - INNER JOIN Tickets T USING(Id_Cliente) - LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket - INNER JOIN subordinate s2 ON s.Id_Trabajador = s2.Id_Trabajador - WHERE maxDate >= datSTART - AND datEND >= yesterday - AND date(Fecha) >= IF(yesterday > datSTART, yesterday, datSTART) - AND date(Fecha) <= IF(datEND > maxDate, maxDate, datEND) - AND IFNULL(tls.alertLevel,0) < 3 - - UNION DISTINCT - - SELECT Id_Ticket, C.Id_Cliente, s.Id_Suplente - FROM Clientes C - INNER JOIN Tickets T USING(Id_Cliente) - LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket - INNER JOIN sharingcart s ON s.Id_Trabajador = C.Id_Trabajador - INNER JOIN subordinate su on su.Id_Trabajador=Id_Suplente - WHERE maxDate >= datSTART - AND datEND >= yesterday - AND date(Fecha) >= IF(yesterday > datSTART, yesterday, datSTART) - AND date(Fecha) <= IF(datEND > maxDate, maxDate, datEND) - AND IFNULL(tls.alertLevel,0) < 3 - - UNION DISTINCT - - SELECT Id_Ticket, C.Id_Cliente, C.Id_Trabajador - FROM Clientes C - INNER JOIN Tickets T USING(Id_Cliente) - LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket - INNER JOIN workerTeamCollegues w ON w.collegueId = C.Id_Trabajador - WHERE Fecha >= yesterday - AND Fecha <= maxDate AND T.Factura Is NULL - AND IFNULL(tls.alertLevel,0) < 3 - AND w.workerId = worker; - - IF (SELECT COUNT(*) FROM ticketRange) THEN - - -- Generamos varias auxiliares (ya podian los de mysql haber solucionado esto) - - DROP TEMPORARY TABLE IF EXISTS tmp.client_list; - CREATE TEMPORARY TABLE tmp.client_list - (INDEX (Id_Cliente)) - ENGINE = MEMORY - SELECT DISTINCT Id_Cliente FROM ticketRange; - - DROP TEMPORARY TABLE IF EXISTS cr5; - CREATE TEMPORARY TABLE cr5 - (INDEX (Id_Cliente)) - ENGINE = MEMORY - SELECT Id_Cliente FROM tmp.client_list; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - ENGINE = MEMORY - SELECT t.Id_Ticket ticketFk FROM Tickets t - STRAIGHT_JOIN tmp.client_list c ON t.Id_Cliente = c.Id_Cliente - WHERE Fecha BETWEEN dateStart AND maxDate - AND Factura IS NULL; - - CALL vn.ticketGetTotal(); - - -- Generamos otra tabla temporal con los Tickets_iva - - DROP TEMPORARY TABLE IF EXISTS tt3; - CREATE TEMPORARY TABLE tt3 - ENGINE = MEMORY - SELECT t.ticketFk, tt.total, tr.* - FROM tmp.ticket t - LEFT JOIN tmp.ticketTotal tt ON t.ticketFk = tt.ticketFk - JOIN ticketRange tr ON tr.Id_Ticket = t.ticketFk; - - -- Generamos la lista de tickets y sus datos - - DROP TEMPORARY TABLE IF EXISTS Radartest; - - CREATE TEMPORARY TABLE Radartest - - SELECT IF(C.Id_Trabajador = worker, 1, 0) as Propio, - Credito, - CAST(Riesgo AS DECIMAL (10,2)) Riesgo, - -- Greuge, - T.Id_Ticket, - T.warehouse_id as wh, - T.Fecha, - T.Alias, - -- T.Vista, - REPEAT(' ',50) as problem, - T.Agencia Tipo, - -- C.Id_Trabajador, - T.workerId AS Id_Trabajador, - T.Solucion, - T.Localizacion, - IFNULL(state,'LIBRE') as Estado, - alertLevel, - alertCode, - Date(T.Fecha) as Fecha_Simple, - CAST(T.Importe AS DECIMAL (10,2)) Importe, - C.Descuento, - C.calidad, - C.Id_Cliente, - p.`name` provincia - FROM Clientes C - INNER JOIN - - ( - - SELECT T.* , A.Vista, A.Agencia, s.`name` as state, alertLevel, s.`code` AS alertCode, tt3.Id_Trabajador AS workerId, - - tt3.total as Importe, - - 0 AS inacabable - - -- (-1 < ifnull(order_id,-1)) as isbionic - - FROM Tickets T - LEFT JOIN vn.ticketState ts on ts.ticket = T.Id_Ticket - LEFT JOIN vn2008.state s on s.id = ts.state - - INNER JOIN tt3 ON tt3.ticketFk = T.Id_Ticket - - -- LEFT JOIN (SELECT DISTINCT 1 as order_id, Id_Ticket FROM order_Tickets) o on o.Id_Ticket = T.Id_Ticket - - INNER JOIN Agencias A ON A.Id_Agencia = T.Id_Agencia - - -- WHERE T.Etiquetasemitidas = FALSE - GROUP BY T.Id_Ticket - - ) AS T ON T.Id_Cliente = C.Id_Cliente - - LEFT JOIN Consignatarios co ON co.Id_Consigna = T.Id_Consigna - LEFT JOIN province p ON p.province_id = co.province_id - - LEFT JOIN - - ( - - SELECT TOTAL.Id_Cliente, ROUND(SUM(amount),2) as Riesgo FROM - - (SELECT cl.Id_Cliente, amount FROM bi.customer_risk cr - INNER JOIN tmp.client_list cl ON cr.customer_id = cl.Id_Cliente - - UNION ALL - - SELECT t.Id_Cliente, tt.total FROM tmp.ticketTotal tt - INNER JOIN Tickets t ON t.Id_Ticket = tt.ticketFk - INNER JOIN cr5 C ON C.Id_Cliente = t.Id_Cliente - WHERE t.Fecha BETWEEN dateStart AND maxDate - AND t.Factura is null - - ) as TOTAL GROUP BY TOTAL.Id_Cliente - - ) AS Peligros ON Peligros.Id_Cliente = C.Id_Cliente - ; - -- Actualizamos el Riesgo con los tickets futuros - set @cliente:= 0; - SET @riesgo := 0; - - UPDATE Radartest SET Riesgo = - IF(@cliente <> @cliente:= Id_Cliente , - Importe + @riesgo:= - Riesgo + Importe , - Importe + @riesgo:= @riesgo + Importe) - order by Id_Cliente, Fecha_Simple DESC; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - - CREATE TEMPORARY TABLE tmp.ticket_list - SELECT Id_Ticket, Id_Cliente FROM Radartest; - - CALL prepare_client_list(); - CALL production_buffer_problems; - - UPDATE Radartest r - JOIN ( - SELECT Id_Ticket, GROUP_CONCAT(problem) problem - FROM tmp.buffer_problems - GROUP BY Id_Ticket - ) p on p.Id_Ticket = r.Id_Ticket - SET r.problem = p.problem; - - - - SELECT R.*, Riesgo + Credito as Risk , CodigoTrabajador - FROM Radartest R - INNER JOIN vn2008.Trabajadores trab on R.Id_Trabajador=trab.Id_Trabajador; - - END IF; - - DROP TEMPORARY TABLE IF EXISTS ticketRange; - DROP TABLE IF EXISTS subordinate; - DROP TEMPORARY TABLE IF EXISTS tmp.client_list; - DROP TEMPORARY TABLE IF EXISTS cr5; - DROP TEMPORARY TABLE IF EXISTS 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 DROP PROCEDURE IF EXISTS `radarTest` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `radarTest`(IN today DATETIME, IN worker INTEGER, IN scopeDays SMALLINT) -BEGIN - - DECLARE todayMidnight DATE DEFAULT TIMESTAMP(today,'23:59:59'); - DECLARE yesterday DATETIME; - DECLARE maxDate DATETIME; - DECLARE datBUF DATETIME; - DECLARE warehouse INTEGER; - DECLARE done BIT DEFAULT 0; - DECLARE visible_calc INTEGER; - DECLARE available_calc INTEGER; - DECLARE dateStart DATE; - - SET dateStart = TIMESTAMPADD(MONTH, -2, CURDATE()); - SELECT TIMESTAMPADD(DAY, -1, today) INTO yesterday; - -- lo quitamos despues de campañaA - SELECT TIMESTAMP(TIMESTAMPADD(DAY, scopeDays, yesterday),'23:59:59') INTO maxDate; - -- SELECT TIMESTAMP(TIMESTAMPADD(DAY, 14, yesterday),'23:59:59') INTO maxDate; - -- Creamos una tabla con los Comerciales de los que se mostraran los tickets - CALL subordinate(worker,TRUE); - - -- Se genera una tabla con los tickets representados - DROP TEMPORARY TABLE IF EXISTS ticketRange; - CREATE TEMPORARY TABLE ticketRange - SELECT T.Id_Ticket, T.Id_Cliente, C.Id_Trabajador - FROM Tickets T - LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket - INNER JOIN Clientes C on C.Id_Cliente = T.Id_Cliente - INNER JOIN subordinate s1 ON C.Id_Trabajador = s1.Id_Trabajador - WHERE Fecha >= yesterday - AND Fecha <= maxDate AND T.Factura Is NULL - AND IFNULL(tls.alertLevel,0) < 3 - - UNION DISTINCT - - SELECT Id_Ticket, s.Id_Cliente, s.Id_Trabajador - FROM sharingclient s - INNER JOIN Tickets T USING(Id_Cliente) - LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket - INNER JOIN subordinate s2 ON s.Id_Trabajador = s2.Id_Trabajador - WHERE maxDate >= datSTART - AND datEND >= yesterday - AND date(Fecha) >= IF(yesterday > datSTART, yesterday, datSTART) - AND date(Fecha) <= IF(datEND > maxDate, maxDate, datEND) - AND IFNULL(tls.alertLevel,0) < 3 - - UNION DISTINCT - - SELECT Id_Ticket, C.Id_Cliente, s.Id_Suplente - FROM Clientes C - INNER JOIN Tickets T USING(Id_Cliente) - LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket - INNER JOIN sharingcart s ON s.Id_Trabajador = C.Id_Trabajador - INNER JOIN subordinate su on su.Id_Trabajador=Id_Suplente - WHERE maxDate >= datSTART - AND datEND >= yesterday - AND date(Fecha) >= IF(yesterday > datSTART, yesterday, datSTART) - AND date(Fecha) <= IF(datEND > maxDate, maxDate, datEND) - AND IFNULL(tls.alertLevel,0) < 3 - - UNION DISTINCT - - SELECT Id_Ticket, C.Id_Cliente, C.Id_Trabajador - FROM Clientes C - INNER JOIN Tickets T USING(Id_Cliente) - LEFT JOIN vn.ticketState tls on tls.ticket = T.Id_Ticket - INNER JOIN workerTeamCollegues w ON w.collegueId = C.Id_Trabajador - WHERE Fecha >= yesterday - AND Fecha <= maxDate AND T.Factura Is NULL - AND IFNULL(tls.alertLevel,0) < 3 - AND w.workerId = worker; - - IF (SELECT COUNT(*) FROM ticketRange) THEN - - -- Generamos varias auxiliares (ya podian los de mysql haber solucionado esto) - - DROP TEMPORARY TABLE IF EXISTS tmp.client_list; - CREATE TEMPORARY TABLE tmp.client_list - (INDEX (Id_Cliente)) - ENGINE = MEMORY - SELECT DISTINCT Id_Cliente FROM ticketRange; - - DROP TEMPORARY TABLE IF EXISTS cr5; - CREATE TEMPORARY TABLE cr5 - (INDEX (Id_Cliente)) - ENGINE = MEMORY - SELECT Id_Cliente FROM tmp.client_list; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - ENGINE = MEMORY - SELECT t.Id_Ticket ticketFk FROM Tickets t - STRAIGHT_JOIN tmp.client_list c ON t.Id_Cliente = c.Id_Cliente - WHERE Fecha BETWEEN dateStart AND maxDate - AND Factura IS NULL; - - CALL vn.ticketGetTotal(); - - -- Generamos otra tabla temporal con los Tickets_iva - - DROP TEMPORARY TABLE IF EXISTS tt3; - CREATE TEMPORARY TABLE tt3 - ENGINE = MEMORY - SELECT t.ticketFk, tt.total, tr.* - FROM tmp.ticket t - LEFT JOIN tmp.ticketTotal tt ON t.ticketFk = tt.ticketFk - JOIN ticketRange tr ON tr.Id_Ticket = t.ticketFk; - - -- Generamos la lista de tickets y sus datos - - DROP TEMPORARY TABLE IF EXISTS Radartest; - - CREATE TEMPORARY TABLE Radartest - - SELECT IF(C.Id_Trabajador = worker, 1, 0) as Propio, - Credito, - CAST(Riesgo AS DECIMAL (10,2)) Riesgo, - -- Greuge, - T.Id_Ticket, - T.warehouse_id as wh, - T.Fecha, - T.Alias, - -- T.Vista, - REPEAT(' ',50) as problem, - T.Agencia Tipo, - -- C.Id_Trabajador, - T.workerId AS Id_Trabajador, - T.Solucion, - T.Localizacion, - IFNULL(state,'LIBRE') as Estado, - alertLevel, - alertCode, - Date(T.Fecha) as Fecha_Simple, - CAST(T.Importe AS DECIMAL (10,2)) Importe, - C.Descuento, - C.calidad, - C.Id_Cliente, - p.`name` provincia - FROM Clientes C - INNER JOIN - - ( - - SELECT T.* , A.Vista, A.Agencia, s.`name` as state, alertLevel, s.`code` AS alertCode, tt3.Id_Trabajador AS workerId, - - tt3.total as Importe, - - 0 AS inacabable - - -- (-1 < ifnull(order_id,-1)) as isbionic - - FROM Tickets T - LEFT JOIN vn.ticketState ts on ts.ticket = T.Id_Ticket - LEFT JOIN vn2008.state s on s.id = ts.state - - INNER JOIN tt3 ON tt3.ticketFk = T.Id_Ticket - - -- LEFT JOIN (SELECT DISTINCT 1 as order_id, Id_Ticket FROM order_Tickets) o on o.Id_Ticket = T.Id_Ticket - - INNER JOIN Agencias A ON A.Id_Agencia = T.Id_Agencia - - -- WHERE T.Etiquetasemitidas = FALSE - GROUP BY T.Id_Ticket - - ) AS T ON T.Id_Cliente = C.Id_Cliente - - LEFT JOIN Consignatarios co ON co.Id_Consigna = T.Id_Consigna - LEFT JOIN province p ON p.province_id = co.province_id - - LEFT JOIN - - ( - - SELECT TOTAL.Id_Cliente, ROUND(SUM(amount),2) as Riesgo FROM - - (SELECT cl.Id_Cliente, amount FROM bi.customer_risk cr - INNER JOIN tmp.client_list cl ON cr.customer_id = cl.Id_Cliente - - UNION ALL - - SELECT t.Id_Cliente, tt.total FROM tmp.ticketTotal tt - INNER JOIN Tickets t ON t.Id_Ticket = tt.ticketFk - INNER JOIN cr5 C ON C.Id_Cliente = t.Id_Cliente - WHERE t.Fecha BETWEEN dateStart AND maxDate - AND t.Factura is null - - ) as TOTAL GROUP BY TOTAL.Id_Cliente - - ) AS Peligros ON Peligros.Id_Cliente = C.Id_Cliente - ORDER BY C.Id_Cliente; - -- Actualizamos el Riesgo con los tickets futuros - set @cliente:= 0; - SET @riesgo := 0; - - SELECT * FROM Radartest; - - UPDATE Radartest SET Riesgo = - IF(@cliente <> @cliente:= Id_Cliente , - Importe + @riesgo:= - Riesgo + Importe , - Importe + @riesgo = @riesgo + Importe), - Propio = @riesgo - order by Id_Cliente, Fecha_Simple DESC; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - - CREATE TEMPORARY TABLE tmp.ticket_list - SELECT Id_Ticket, Id_Cliente FROM Radartest; - select * from Radartest; - CALL prepare_client_list(); - CALL production_buffer_problems; - - - UPDATE Radartest r - JOIN ( - SELECT Id_Ticket, GROUP_CONCAT(problem) problem - FROM tmp.buffer_problems - GROUP BY Id_Ticket - ) p on p.Id_Ticket = r.Id_Ticket - SET r.problem = p.problem; - - - - SELECT R.*, Riesgo + Credito as Risk , CodigoTrabajador - FROM Radartest R - INNER JOIN vn2008.Trabajadores trab on R.Id_Trabajador=trab.Id_Trabajador; - - END IF; - - DROP TEMPORARY TABLE IF EXISTS ticketRange; - DROP TABLE IF EXISTS subordinate; - DROP TEMPORARY TABLE IF EXISTS tmp.client_list; - DROP TEMPORARY TABLE IF EXISTS cr5; - DROP TEMPORARY TABLE IF EXISTS 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 DROP PROCEDURE IF EXISTS `radar_lostcalls` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `radar_lostcalls`() -BEGIN - -SELECT Averiguar_ComercialCliente(C.Id_Cliente, calldate) as Comercial, C.Cliente AS Cliente, A2.Telefono -, A.Nombre as Destino, t3.* FROM - -( SELECT * FROM - (SELECT * FROM - ( SELECT dstchannel, disposition, calldate,src,dst,1 as missed, TIMESTAMPADD(SECOND,duration,calldate) as hangupdate, - TIMESTAMPADD(SECOND, (-billsec),TIMESTAMPADD(SECOND,duration,calldate) ) as answerdate, - duration, billsec FROM - (SELECT * FROM - (SELECT * FROM cdr WHERE calldate > timestampadd(day, -4,curdate()) ORDER BY calldate DESC ) t - GROUP BY src - ) cdr_sub - WHERE (dstchannel = '' or disposition <> 'ANSWERED' or lastapp = 'Playback') AND dstchannel <> 'killed' - AND src > 6000 - AND calldate > TIMESTAMPADD(DAY,-4,CURDATE()) - UNION ALL - SELECT dstchannel, disposition, calldate,dst, 0,0,calldate,calldate,0,0 - FROM cdr - WHERE dst > 6000 - AND calldate > TIMESTAMPADD(WEEK,-4,CURDATE()) - ) t - ORDER BY calldate DESC - ) t2 GROUP BY src - HAVING missed - ORDER BY calldate DESC -) t3 - -LEFT JOIN v_Agenda2 A2 ON CAST(A2.Telefono AS SIGNED) = t3.src -LEFT JOIN v_Agenda2 A ON CAST(A.Telefono AS SIGNED) = t3.dst -LEFT JOIN Clientes C ON C.Id_Cliente = A2.Id AND A2.Tipo = 'C' -; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `radar_negativos` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `radar_negativos`(IN v_force BOOLEAN, IN intRANGE INT) -BEGIN - -/** - * Calcula una tabla con el máximo negativo visible para cada producto y almacen - * - * @param v_force Fuerza el recalculo del stock - * @param intRANGE Numero de dias a considerar -**/ - - CALL `cache`.stock_refresh(v_force); - SET @aid = NULL; - call article_minacum(NULL,CURDATE(),intRANGE); - - SELECT a.Id_Article, a.Article, sub.warehouse_id, p.`name` producer, a.Medida, a.Categoria - , w.name as Almacen, sum(IFNULL(amount,0)) as Negativo - FROM (SELECT item_id, warehouse_id, amount - FROM cache.stock - WHERE amount > 0 - UNION ALL - SELECT article_id, warehouse_id, amount - FROM article_minacum - ) sub - JOIN warehouse w on w.id = warehouse_id - JOIN Articles a on a.Id_Article = item_id - LEFT JOIN producer p on p.producer_id = a.producer_id - JOIN Tipos t on t.tipo_id = a.tipo_id - JOIN reinos r on r.id = t.reino_id - WHERE w.tpv - AND t.tipo_id NOT IN (61,101,100,99, 180, 7, 21) - AND r.display <> 0 - AND a.Id_Article NOT IN (95,98) - GROUP BY item_id, warehouse_id - HAVING negativo < 0; - - DROP TEMPORARY TABLE IF EXISTS article_minacum; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `raidUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `raidUpdate`() -BEGIN - UPDATE travel - SET shipment = CURDATE(), - landing = TIMESTAMPADD(DAY, 1, CURDATE()) - WHERE id = 12505; - - UPDATE Entradas e - JOIN Entradas_Auto ea USING (Id_Entrada) - JOIN travel t ON t.id = e.travel_id - JOIN ( - SELECT * - FROM ( - SELECT id, landing, warehouse_id, warehouse_id_out - FROM travel - JOIN ( - SELECT warehouse_id, warehouse_id_out - FROM Entradas_Auto ea - JOIN Entradas e USING(Id_Entrada) - JOIN travel t ON t.id = e.travel_id - GROUP BY warehouse_id, warehouse_id_out - ) t USING (warehouse_id, warehouse_id_out) - WHERE shipment > CURDATE() AND delivered = FALSE - ORDER BY landing - ) t - GROUP BY warehouse_id, warehouse_id_out - ) t USING (warehouse_id, warehouse_id_out) - SET e.travel_id = t.id; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `rateView` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `rateView`() -BEGIN - - SELECT - t.year as año, - t.month as mes, - pagos.dolares, - pagos.cambioPractico, - CAST(sum(divisa) / sum(bi) as DECIMAL(5,4)) as cambioTeorico, - pagos.cambioOficial - FROM recibida r - JOIN time t ON t.date = r.fecha - JOIN recibida_iva ri ON r.id = ri.recibida_id - JOIN - ( - SELECT - t.year as Año, - t.month as Mes, - cast(sum(divisa) as DECIMAL(10,2)) as dolares, - cast(sum(divisa) / sum(importe) as DECIMAL(5,4)) as cambioPractico, - cast(rr.rate * 0.998 as DECIMAL(5,4)) as cambioOficial - FROM pago p - JOIN time t ON t.date = p.fecha - JOIN reference_rate rr ON rr.date = p.fecha AND moneda_id = 2 - WHERE divisa - AND fecha >= '2015-01-11' - GROUP BY t.year, t.month - ) pagos ON t.year = pagos.Año AND t.month = pagos.Mes - WHERE moneda_id = 2 - AND fecha >= '2015-01-01' - AND divisa - AND bi - GROUP BY t.year, t.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 DROP PROCEDURE IF EXISTS `recalculator` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `recalculator`(vTicketId INT) -BEGIN - DECLARE vWh INT; - DECLARE vDate DATE; - DECLARE vCustomerId INT; - DECLARE vServiFac INT; - - SELECT warehouse_id, Fecha, Id_Cliente, IFNULL(Factura, 0) != 0 OR Etiquetasemitidas != 0 - INTO vWh, vDate, vCustomerId, vServiFac - FROM Tickets - WHERE Id_Ticket = vTicketId; - - IF NOT vServiFac - THEN - DROP TEMPORARY TABLE IF EXISTS item; - - CREATE TEMPORARY TABLE item - (INDEX (id)) - ENGINE = MEMORY - SELECT Id_Article id, Id_Movimiento - FROM Movimientos - WHERE Preciofijado = FALSE - AND Id_Ticket = vTicketId - AND (Id_Article < 82 OR Id_Article > 100); - - CALL item_buy (vWh, vDate); - CALL item_buy_price (vCustomerId, vDate, vWh); - - UPDATE Movimientos - JOIN item USING (Id_Movimiento) - SET Preu = price, - Descuento = discount; - - SELECT * FROM item; - - DROP TEMPORARY TABLE item; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `recalculator_plus` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `recalculator_plus`(vTicketId INT) -BEGIN - CALL recalculator (vTicketId); - - CREATE TEMPORARY TABLE movement - ENGINE = MEMORY - SELECT Id_Movimiento, Id_Article, Preu, Descuento, Cantidad, ABS(Preciofijado) AS PrecioFijado - FROM Movimientos - WHERE Id_Ticket = vTicketId - AND Reservado = FALSE - AND Id_Article NOT BETWEEN 85 AND 100 - AND Id_Movimiento NOT IN - ( - SELECT Id_Movimiento FROM Movimientos - WHERE Id_Ticket = vTicketId - AND Reservado = FALSE - AND Id_Article NOT BETWEEN 71 AND 100 - GROUP BY Id_Article, Preu, Descuento, ABS(PrecioFijado) - HAVING COUNT(*) = 1 - UNION ALL - SELECT Id_Movimiento FROM movement_label - ) FOR UPDATE; - - CREATE TEMPORARY TABLE movement_u - ENGINE = MEMORY - SELECT Id_Movimiento, Id_Article, Preu, Descuento, PrecioFijado, SUM(Cantidad) amount - FROM movement - GROUP BY Id_Article, Preu, Descuento, PrecioFijado; - - UPDATE Movimientos - JOIN movement_u u USING(Id_Movimiento) - JOIN Tickets T ON T.Id_Ticket = vTicketId - SET Cantidad = amount; - - DELETE movement FROM movement JOIN movement_u USING (Id_Movimiento); - DELETE Movimientos FROM Movimientos JOIN movement USING (Id_Movimiento); - - DROP TEMPORARY TABLE movement; - DROP TEMPORARY TABLE movement_u; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `recibidaIvaDivisaUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `recibidaIvaDivisaUpdate`(IN vRecibidaId INT) -BEGIN - -/* Actualiza el valor de la divisa en función del cambio oficial para el dia de expedicion -*/ - UPDATE recibida_iva - SET bi = NULL - WHERE recibida_id = vRecibidaId - AND divisa IS NOT NULL; - - UPDATE recibida_iva ri - JOIN recibida r ON r.id = ri.recibida_id - JOIN reference_rate rr ON rr.date = r.fecha AND r.moneda_id = rr.moneda_id - SET ri.bi = ri.divisa / rr.rate - WHERE r.id = vRecibidaId; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `recibidaIvaInsert` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `recibidaIvaInsert`(IN vId INT) -BEGIN - - INSERT INTO recibida_iva(recibida_id, iva_id, bi,gastos_id,divisa) - SELECT r.id, - CASE - WHEN p.cuenta LIKE '___4______' THEN 71 - WHEN p.cuenta LIKE '___1______' THEN 36 - WHEN p.cuenta LIKE '___3______' THEN 63 - END, - SUM(Costefijo * Cantidad) / IFNULL(rr.rate,1), - 6003000000, - IF(r.moneda_id = 1,NULL,SUM(Costefijo * Cantidad )) - FROM recibida r - JOIN recibida_entrada re ON r.id = re.recibida_id - JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada - JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor - JOIN Compres c ON c.Id_Entrada = e.Id_Entrada - JOIN reference_rate rr ON rr.moneda_id = r.moneda_id AND rr.date = r.fecha - LEFT JOIN recibida_iva ri ON re.recibida_id=ri.recibida_id - WHERE re.awb_recibida =vId AND ri.bi IS NULL - GROUP BY e.Id_Entrada, re.awb_recibida; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `recibida_select` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `recibida_select`(IN recibida INT) -BEGIN - DECLARE cta_proveed VARCHAR(10); - DECLARE cta_proveeda VARCHAR(10); - DECLARE v_num_recibida INT; - DECLARE dblRefRate,dblRefMin,dblRef DOUBLE; - - DECLARE NEW_id,NEW_empresa_id,NEW_proveedor_id INT; - DECLARE NEW_serie VARCHAR(1); - DECLARE NEW_fecha DATE; - DECLARE NEW_num_recibida VARCHAR(10); - DECLARE NEW_sref VARCHAR(20); - - SELECT id,empresa_id,proveedor_id,serie,fecha,num_recibida,sref - INTO NEW_id,NEW_empresa_id,NEW_proveedor_id, NEW_serie,NEW_fecha,NEW_num_recibida, NEW_sref - FROM recibida WHERE id = recibida; - - - SELECT rate INTO dblRefRate FROM reference_rate WHERE date = (SELECT MAX(date) FROM reference_rate - WHERE date <= (SELECT t.shipment FROM - recibida_entrada re - INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada - LEFT JOIN travel t ON t.id = e.travel_id - WHERE re.awb_recibida = recibida GROUP BY re.awb_recibida)); - - SELECT rate INTO dblRefMin FROM reference_min WHERE date=(SELECT MAX(date) FROM reference_min - WHERE date<=(SELECT t.shipment FROM - recibida_entrada re - INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada - LEFT JOIN travel t ON t.id = e.travel_id - WHERE re.awb_recibida = NEW_id GROUP BY re.awb_recibida)); - - -- IF dblRefMin < dblRefRate THEN - -- SET dblRef = dblRefRate; - -- ELSE - -- SET dblRef =dblRefMin; - -- END IF; - SELECT IFNULL(MAX(r.num_recibida) + 1,1) INTO v_num_recibida FROM recibida r - WHERE r.serie LIKE NEW_serie - AND YEAR(r.fecha) = YEAR(NEW_fecha) - AND r.empresa_id = NEW_empresa_id GROUP BY r.empresa_id; - - SET NEW_num_recibida = IFNULL(v_num_recibida,1); - SELECT REPLACE(cuenta,' ','') INTO cta_proveed FROM Proveedores WHERE Id_Proveedor=NEW_proveedor_id; - - -SELECT a,NEW_fecha,subcta,contra,concepto,eurodebe,eurohaber,baseeuro,NEW_serie,NEW_sref,iva, - (SELECT CONCAT(NEW_serie,'/', LPAD(v_num_recibida,5,'0'))),l340,LRECT349,TIPOOPE,AUXILIAR,NEW_empresa_id - FROM - - (SELECT MAX(ASIEN) + 1 as a FROM XDiario) t - - INNER JOIN - - ( - - SELECT *,NEW_serie FROM - - (SELECT CONCAT('s/fra',RIGHT(sref,8),':',LEFT(Proveedor, 10)) concepto FROM Proveedores - - INNER JOIN recibida ON Id_Proveedor = proveedor_id WHERE id = NEW_id) t4 - - INNER JOIN( - -- Linea del proveedor/acreedor - SELECT subcta,'' contra,eurodebe,ROUND(SUM(eurohaber) + 0.0001,2) eurohaber,baseeuro,0 iva, l340,LRECT349,TIPOOPE,'' AUXILIAR - - FROM ( - - SELECT cta_proveed subcta, - - NULL eurodebe, ROUND((1+(iva/100)*(r.serie = 'R'))*SUM(bi),2) eurohaber, NULL baseeuro,ri.recibida_id, 0 l340,0 LRECT349,' ' TIPOOPE - - FROM recibida r - - INNER JOIN recibida_iva ri ON ri.recibida_id = r.id INNER JOIN iva_codigo ic ON ri.iva_id = ic.id - - INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id - INNER JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id - - WHERE r.id = NEW_id GROUP BY iva) t - - GROUP BY recibida_id - - UNION ALL - -- Linea de iva - SELECT ic.codigo,cta_proveed contra, - - ROUND(iva/100*SUM(ri.bi) + 0.0001,2) eurodebe, NULL eurohaber, - - ROUND(SUM(ri.bi),2) baseeuro,iva, 1 l340,(NOT ((p.pais_id <> p2.pais_id) AND pa.CEE < 2)) LRECT349,TIPOOPE, - IF(pa2.CEE < 2 AND ri2.gastos_id IS NULL,'','*') AUXILIAR -- JGF 30-01-2014 IF(NOT ((p.pais_id <> p2.pais_id) AND pa.CEE < 2),'*','') -- ANTES '' AUXILIAR JGF < 30-01-2014 --- AND ri.gastos_id LIKE '4751______' - FROM recibida r - - INNER JOIN recibida_iva ri ON ri.recibida_id = r.id - - LEFT JOIN recibida_iva ri2 ON ri2.recibida_id = r.id AND ri2.gastos_id LIKE '4751______' - - INNER JOIN iva_codigo ic ON ri.iva_id = ic.id - - INNER JOIN iva_tipo it ON ic.iva_tipo_id = it.id - - INNER JOIN Gastos g ON ri.gastos_id = g.Id_Gasto AND g.iva_tipo_id = ic.iva_tipo_id - - INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id - - INNER JOIN Paises pa ON p.pais_id = pa.Id - - INNER JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id - - INNER JOIN Paises pa2 ON p2.pais_id = pa2.Id - WHERE r.id = NEW_id AND g.conbase AND link GROUP BY iva - - UNION ALL - -- Linea iva inversor sujeto pasivo - SELECT ic2.codigo,cta_proveed contra, - - NULL eurodebe, ROUND(ic2.iva/100*SUM(bi) + 0.0001,2) eurohaber, - - ROUND(SUM(bi),2) baseeuro,ic2.iva, 1 l340,0 LRECT349,TIPOOPE,'*' AUXILIAR - - FROM recibida r - - INNER JOIN recibida_iva ri ON ri.recibida_id = r.id - - INNER JOIN iva_codigo ic ON ri.iva_id = ic.id - - INNER JOIN iva_codigo ic2 ON ic2.link = ic.link AND ic.id <> ic2.id - - INNER JOIN iva_tipo it ON ic.iva_tipo_id = it.id - - WHERE r.id = NEW_id AND ic2.link GROUP BY ic2.iva - - UNION ALL - -- Linea de Gastos - SELECT if(gastos_id LIKE '4751______',LPAD(RIGHT(cta_proveed ,4),10,gastos_id),gastos_id),cta_proveed , - - if(gastos_id LIKE '4751______',NULL,ABS(ROUND(SUM(bi),2))) , - - if(gastos_id LIKE '4751______',ABS(ROUND(SUM(bi),2)),NULL) , - - NULL ,0, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR - - FROM recibida r - - INNER JOIN recibida_iva ri ON ri.recibida_id = r.id - - INNER JOIN Proveedores p ON p.Id_Proveedor=r.proveedor_id - - WHERE r.id = NEW_id AND gastos_id <> 5660000002 GROUP BY gastos_id - - ) t2 - - UNION ALL - - - -- Extracomunitarias gasto contra proveedor/acreedor - SELECT CONCAT('COMPRA s/fra ',sref,':',LEFT(p.Proveedor, 10)) concepto ,gastos_id,cuenta, - - ROUND(SUM(bi)/IF(r.serie='W',dblRefRate,1)* (re.percentage / 100),2),NULL ,IF( @a:=@a+1 ,NULL,NULL) ,0, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR,r.serie - - FROM recibida_entrada re - - INNER JOIN recibida_iva ri ON re.recibida_id = ri.recibida_id - - INNER JOIN recibida r ON r.id = ri.recibida_id - - INNER JOIN Proveedores p ON p.Id_Proveedor = r.proveedor_id - - INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada - - LEFT JOIN travel t ON t.id = e.travel_id - - INNER JOIN (SELECT @a:=0,@cont:=1,@total:=0,@base:=2) t1 - - WHERE re.awb_recibida = NEW_id AND re.percentage GROUP BY r.id - -UNION ALL - - -- Extracomunitarias proveedor contra gasto - SELECT CONCAT('COMPRA s/fra ',sref,':',LEFT(p.Proveedor, 10)) concepto ,p.cuenta subcta,gastos_id, - - NULL eurodebe, ROUND((1+(iva/100)*(r.serie = 'R'))*SUM(bi)/IF(r.serie='W',dblRefRate,1)* (re.percentage / 100),2) eurohaber, - - NULL baseeuro,0 iva, 0 l340,0 LRECT349,' ' TIPOOPE,'' AUXILIAR,r.serie - -- antes sols iva - FROM recibida_entrada re - - INNER JOIN recibida_iva ri ON re.recibida_id = ri.recibida_id - - INNER JOIN recibida r ON r.id = ri.recibida_id - - INNER JOIN iva_codigo ic ON ri.iva_id = ic.id - - INNER JOIN Proveedores p ON Id_Proveedor = r.proveedor_id - - INNER JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id - - WHERE re.awb_recibida = NEW_id AND re.percentage GROUP BY r.id - -UNION ALL - - -- Linea de iva adquisicion - SELECT CONCAT('ADQUI. INTRA FRA ',sref),ic.codigo,p.cuenta contra, - - ROUND(iva/100*SUM(ri.importe) + 0.0001,2) eurodebe, NULL eurohaber, - - ROUND(SUM(ri.importe),2) baseeuro,iva, 1 l340,1 LRECT349,TIPOOPE,'' AUXILIAR,r.serie - - FROM awb_recibida ar - - JOIN awb a ON ar.awb_id = a.id - - JOIN iva_codigo ic ON a.iva_id = ic.id - - JOIN iva_tipo it ON ic.iva_tipo_id = it.id - - JOIN Proveedores p ON a.transitario_id = p.Id_Proveedor - - JOIN recibida_intrastat ri ON ri.recibida_id = ar.recibida_id - - JOIN recibida r ON r.id = ri.recibida_id - - JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id - - WHERE ar.recibida_id = NEW_id AND (p.pais_id <> p2.pais_id) - GROUP BY iva - - UNION ALL - - -- Linea de iva adquisicion - SELECT CONCAT('ADQUI. INTRA FRA ',sref),ic2.codigo,p.cuenta contra, - - NULL eurodebe, ROUND(ic2.iva/100*SUM(ri.importe) + 0.0001,2) eurohaber, - - ROUND(SUM(ri.importe),2) baseeuro,ic2.iva, 1 l340,0 LRECT349, TIPOOPE,'' AUXILIAR,r.serie - - FROM awb_recibida ar - - JOIN awb a ON ar.awb_id = a.id - - JOIN iva_codigo ic ON a.iva_id = ic.id - - JOIN iva_codigo ic2 ON ic2.link = ic.link AND ic.id <> ic2.id - - JOIN iva_tipo it ON ic.iva_tipo_id = it.id - - JOIN Proveedores p ON a.transitario_id = p.Id_Proveedor - - JOIN recibida_intrastat ri ON ri.recibida_id = ar.recibida_id - - JOIN recibida r ON r.id = ar.recibida_id - - JOIN Proveedores p1 ON p1.Id_Proveedor = r.proveedor_id - - JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id - - WHERE ar.recibida_id = NEW_id AND (p.pais_id <> p2.pais_id) GROUP BY ic2.iva - - UNION ALL - -- Linea iva importacion - SELECT concepto,subcta,Cuenta, - IF (NOT ((ppais_id <> p2pais_id) AND CEE < 2), - (IF(@cont<@a, - eurodebe, - ROUND(bi-@total,2) - )) - ,NULL)eurodebe,eurohaber,baseeuro,iva, - IF(@total:=@total+eurodebe ,0,0) l340,0 LRECT349, - IF(@cont:=@cont+1,'','') TIPOOPE,'*' AUXILIAR,serie FROM ( - - SELECT CONCAT('COMPRA FRA ',p.Proveedor) concepto,ic.codigo subcta,p.Cuenta,ic.iva, - red(sum(costefijo * Cantidad / sub1.costetotal * sub2.importe)*0.21) eurodebe,NULL eurohaber, - ROUND(sum(costefijo * Cantidad / sub1.costetotal * sub2.importe),2) baseeuro,ri.bi,r.serie,pa.CEE,p.pais_id ppais_id,p2.pais_id p2pais_id - - FROM awb_recibida ar - - JOIN recibida_entrada re ON ar.recibida_id = re.awb_recibida - - JOIN Compres c ON c.Id_Entrada = re.Id_Entrada - - INNER JOIN Articles a ON a.Id_Article = c.Id_Article - - INNER JOIN ( - - SELECT a.Codintrastat, sum(c.costefijo * c.Cantidad) as costetotal - - FROM Compres c - - JOIN Articles a ON a.Id_Article = c.Id_Article - - JOIN recibida_entrada re ON re.Id_Entrada = c.Id_Entrada - - JOIN awb_recibida ar ON ar.recibida_id = re.awb_recibida - - JOIN awb aw ON ar.awb_id = aw.id - - WHERE ar.recibida_id = NEW_id AND re.percentage - - GROUP BY a.Codintrastat - - ) sub1 USING(Codintrastat) - - INNER JOIN ( - - SELECT Codintrastat,ri.importe - - FROM recibida_intrastat ri - - WHERE ri.recibida_id = NEW_id - - ) sub2 USING(Codintrastat) - - -- JOIN recibida_intrastat ri ON ar.awb_recibida = ri.recibida_id and ri.Codintrastat = sub1.Codintrastat - - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - - JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor - - JOIN Paises pa ON p.pais_id = pa.Id - - JOIN recibida_iva ri ON ri.recibida_id = re.awb_recibida - - JOIN recibida_iva ri2 ON ri2.recibida_id = re.recibida_id - - JOIN iva_codigo ic ON ic.id = ri2.iva_id - - JOIN recibida r ON r.id = re.recibida_id - - JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id - - WHERE re.awb_recibida = NEW_id AND re.percentage AND IF(cta_proveed like '___0______',ri.gastos_id = 5660000002,TRUE) - -- canvie el cta_proveed like '___1______' per cero cuidao en les van de put - - GROUP BY p.Id_Proveedor - - - -- antes GROUP BY a.Codintrastat,Id_Entrada - -) t3)t4; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `recibida_select2` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `recibida_select2`(IN recibida INT) -BEGIN - DECLARE cta_proveed VARCHAR(10); - DECLARE cta_proveeda VARCHAR(10); - DECLARE v_num_recibida INT; - DECLARE dblRefRate,dblRefMin,dblRef DOUBLE; - - DECLARE NEW_id,NEW_empresa_id,NEW_proveedor_id INT; - DECLARE NEW_serie VARCHAR(1); - DECLARE NEW_fecha DATE; - DECLARE NEW_num_recibida VARCHAR(10); - DECLARE NEW_sref VARCHAR(20); - - SELECT id,empresa_id,proveedor_id,serie,fecha,num_recibida,sref - INTO NEW_id,NEW_empresa_id,NEW_proveedor_id, NEW_serie,NEW_fecha,NEW_num_recibida, NEW_sref - FROM recibida WHERE id = recibida; - - - SELECT rate INTO dblRefRate FROM reference_rate WHERE date = (SELECT MAX(date) FROM reference_rate - WHERE date <= (SELECT t.shipment FROM - recibida_entrada re - INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada - LEFT JOIN travel t ON t.id = e.travel_id - WHERE re.awb_recibida = recibida GROUP BY re.awb_recibida)); - - SELECT rate INTO dblRefMin FROM reference_min WHERE date=(SELECT MAX(date) FROM reference_min - WHERE date<=(SELECT t.shipment FROM - recibida_entrada re - INNER JOIN Entradas e ON e.Id_Entrada = re.Id_Entrada - LEFT JOIN travel t ON t.id = e.travel_id - WHERE re.awb_recibida = NEW_id GROUP BY re.awb_recibida)); - - -- IF dblRefMin < dblRefRate THEN - -- SET dblRef = dblRefRate; - -- ELSE - -- SET dblRef =dblRefMin; - -- END IF; - SELECT IFNULL(MAX(r.num_recibida) + 1,1) INTO v_num_recibida FROM recibida r - WHERE r.serie LIKE NEW_serie - AND YEAR(r.fecha) = YEAR(NEW_fecha) - AND r.empresa_id = NEW_empresa_id GROUP BY r.empresa_id; - - SET NEW_num_recibida = IFNULL(v_num_recibida,1); - - - SELECT REPLACE(cuenta,' ','') INTO cta_proveed FROM Proveedores WHERE Id_Proveedor=NEW_proveedor_id; - - -SELECT CONCAT('COMPRA FRA ',p.Proveedor) concepto,ic.codigo subcta,p.Cuenta,ic.iva, - red(sum(costefijo * Cantidad / sub1.costetotal * sub2.importe)*0.21) eurodebe,NULL eurohaber, - ROUND(sum(costefijo * Cantidad / sub1.costetotal * sub2.importe),2) baseeuro,ri.bi,r.serie,pa.CEE,p.pais_id ppais_id,p2.pais_id p2pais_id - - FROM awb_recibida ar - - left JOIN recibida_entrada re ON ar.recibida_id = re.awb_recibida - - left JOIN Compres c ON c.Id_Entrada = re.Id_Entrada - - left JOIN Articles a ON a.Id_Article = c.Id_Article - - left JOIN ( - - SELECT a.Codintrastat, sum(c.costefijo * c.Cantidad) as costetotal - - FROM Compres c - - left JOIN Articles a ON a.Id_Article = c.Id_Article - - left JOIN recibida_entrada re ON re.Id_Entrada = c.Id_Entrada - - left JOIN awb_recibida ar ON ar.recibida_id = re.awb_recibida - - left JOIN awb aw ON ar.awb_id = aw.id - - WHERE ar.recibida_id = NEW_id AND re.percentage/*JGF 27/08/14*/ - - GROUP BY a.Codintrastat - - ) sub1 USING(Codintrastat) - - left JOIN ( - - SELECT Codintrastat,ri.importe - - FROM recibida_intrastat ri - - WHERE ri.recibida_id = NEW_id - - ) sub2 USING(Codintrastat) - - -- JOIN recibida_intrastat ri ON ar.awb_recibida = ri.recibida_id and ri.Codintrastat = sub1.Codintrastat - - left JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - - left JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor - - left JOIN Paises pa ON p.pais_id = pa.Id - - left JOIN recibida_iva ri ON ri.recibida_id = re.awb_recibida - - left JOIN recibida_iva ri2 ON ri2.recibida_id = re.recibida_id - - left JOIN iva_codigo ic ON ic.id = ri2.iva_id - - left JOIN recibida r ON r.id = re.recibida_id - - left JOIN Proveedores p2 ON p2.Id_Proveedor = r.empresa_id - - WHERE re.awb_recibida = NEW_id AND re.percentage/*JGF 27/08/14*/ AND IF(cta_proveed like '___0______',ri.gastos_id = 5660000002,TRUE) - -- canvie el cta_proveed like '___1______' per cero cuidao en les van de put - GROUP BY p.Id_Proveedor; - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `recobro_credito` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `recobro_credito`() -BEGIN - -INSERT INTO vn2008.daily_task_log(consulta) VALUES('recobro_credito'); - -DROP TEMPORARY TABLE IF EXISTS clientes_credit; -CREATE TEMPORARY TABLE clientes_credit -SELECT Id_Cliente, if (Credito > Recobro ,Credito - Recobro,0) as newCredit -from -( -SELECT r.Id_Cliente, r.amount as Recobro, timestampadd(DAY, period, UltimaFecha) as Deadline, sub2.amount as Credito -FROM vn2008.recovery r -join - ( - select Id_Cliente, amount , odbc_date as UltimaFecha - from - ( - select * from credit - order by odbc_date desc - ) sub - group by Id_Cliente - ) sub2 using(Id_Cliente) - -where dend is null or dend >= curdate() -group by Id_Cliente -having Deadline <= curdate() -) sub3 -where Credito > 0; - -UPDATE Clientes -JOIN -clientes_credit using(Id_Cliente) -SET Clientes.Credito = newCredit; - -/* -Lo hace el trigger JGF 2017/10/18 -INSERT INTO credit(Id_Cliente, amount, Id_Trabajador) -SELECT Id_Cliente, newCredit, 20 -FROM clientes_credit; -*/ -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `reinvoice` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `reinvoice`(Id_Factura VARCHAR(15)) -BEGIN - DECLARE date_invoice DATE; - DECLARE customer_id INTEGER; - DECLARE serie CHAR(1); - DECLARE bi DOUBLE; - DECLARE bi_diff DOUBLE; - DECLARE base_max DOUBLE; - DECLARE day_vec INT; - DECLARE bi_r DOUBLE DEFAULT 0; - DECLARE bi_g DOUBLE DEFAULT 0; - DECLARE bi_n DOUBLE DEFAULT 0; - DECLARE iva_r DOUBLE DEFAULT 0; - DECLARE iva_g DOUBLE DEFAULT 0; - DECLARE re_r DOUBLE DEFAULT 0; - DECLARE re_g DOUBLE DEFAULT 0; - DECLARE dblImporte DOUBLE DEFAULT 0; - DECLARE intpais_id TINYINT DEFAULT 1; - DECLARE intFac INTEGER; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - DROP TEMPORARY TABLE IF EXISTS `iva_base`; - CREATE TEMPORARY TABLE `iva_base` - ( - `id` VARCHAR(3) NOT NULL, - `base` DOUBLE NOT NULL DEFAULT 0, - PRIMARY KEY (`id`) - ) - ENGINE = MEMORY; - - DROP TEMPORARY TABLE IF EXISTS `ticket_invoice`; - CREATE TEMPORARY TABLE `ticket_invoice` - ( - `ticket_id` INT NOT NULL, - PRIMARY KEY (`ticket_id`) - ) - ENGINE = MEMORY; - - START TRANSACTION; - - SELECT pais_id,Fecha,f.Id_Factura,Id_Cliente INTO intpais_id,date_invoice,Id_Factura,customer_id FROM Proveedores p - JOIN Facturas f ON p.Id_Proveedor = f.empresa_id - WHERE f.Id_Factura = Id_Factura; - - INSERT INTO ticket_invoice (ticket_id) SELECT Id_Ticket FROM Tickets t - WHERE Factura = Id_Factura; - - -- Eliminem els tickets que no han de ser facturats - - IF (SELECT COUNT(*) FROM ticket_invoice) > 0 - THEN - INSERT INTO iva_base (id) SELECT tipoiva FROM tblIVA; - - UPDATE iva_base - INNER JOIN - (SELECT tipo, SUM(base) base - FROM - (SELECT t.tipo, red(m.Cantidad * m.Preu * (100 - Descuento) / 100) AS base - FROM - Movimientos m - INNER JOIN ticket_invoice ti ON m.Id_Ticket = ti.ticket_id - INNER JOIN (SELECT t.tipo, Id_Article - FROM - (SELECT - date, iva_codigo_id, ic.tipo, iva_group_id - FROM - iva_group_codigo gi - INNER JOIN iva_codigo ic ON gi.iva_codigo_id = ic.id - INNER JOIN iva_tipo itp ON itp.id = ic.iva_tipo_id - WHERE - date <= date_invoice - AND Id_Pais = intpais_id - ORDER BY date DESC) t - INNER JOIN Articles USING (iva_group_id) - GROUP BY Id_Article) t USING (Id_Article)) sub - GROUP BY tipo) iva_movement ON iva_base.id = iva_movement.tipo - SET - iva_base.base = iva_movement.base; - - IF (serie = 'H' OR serie = 'V' OR serie = 'E' OR serie = 'X') THEN - SELECT SUM(base) into dblImporte from iva_base; - ELSE - - SET bi_r = (SELECT base FROM iva_base WHERE id = 'R'); - - SET bi_g = (SELECT base FROM iva_base WHERE id = 'G'); - SET bi_n = (SELECT base FROM iva_base WHERE id = '0'); - SET iva_r = red(bi_r * (SELECT iva FROM iva_codigo INNER JOIN iva_tipo it ON it.id = iva_tipo_id - WHERE tipo = 'R' AND Id_Pais = intpais_id AND Fecha <= date_invoice and iva ORDER BY fecha DESC, recargo DESC LIMIT 1) / 100 ); - SET iva_g = red(bi_g * (SELECT iva FROM iva_codigo INNER JOIN iva_tipo it ON it.id = iva_tipo_id - WHERE tipo = 'G' AND Id_Pais = intpais_id AND Fecha <= date_invoice and iva ORDER BY fecha DESC, recargo DESC LIMIT 1) / 100 ); - - IF (SELECT IF(RE = 0, FALSE, TRUE) FROM Clientes WHERE Clientes.Id_cliente = customer_id) - THEN - SET re_r = red(bi_r * (SELECT recargo FROM iva_codigo INNER JOIN iva_tipo it ON it.id = iva_tipo_id - WHERE tipo = 'R' AND Id_Pais = intpais_id AND Fecha <= date_invoice and iva ORDER BY fecha DESC, recargo DESC LIMIT 1) / 100 ); - SET re_g = red(bi_g * (SELECT recargo FROM iva_codigo INNER JOIN iva_tipo it ON it.id = iva_tipo_id - WHERE tipo = 'G' AND Id_Pais = intpais_id AND Fecha <= date_invoice and iva ORDER BY fecha DESC, recargo DESC LIMIT 1) / 100 ); - END IF; - - SET dblImporte = bi_r + bi_g + bi_n + iva_r + iva_g + re_r + re_g ; - END IF; - END IF; - - IF (SELECT SUM(base) FROM iva_base) != 0 - THEN - UPDATE Facturas - SET - BI7 = bi_r, - BI16 = bi_g, - IVA7 = iva_r, - IVA16 = iva_g, - RE1 = re_r, - RE4 = re_g, - Importe = dblImporte - WHERE Facturas.Id_Factura = Id_Factura; - END IF; - - DROP TEMPORARY TABLE `iva_base`; - DROP TEMPORARY TABLE `ticket_invoice`; - - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `resumen_produccion` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `resumen_produccion`(IN datSTART DATE, IN datEND DATE) -BEGIN - -DECLARE datENDFIN DATETIME; -DECLARE datSTART_LY DATETIME; -DECLARE datEND_LY DATETIME; - -SET datENDFIN = DAYEND(datEND); -SET datSTART_LY = TIMESTAMPADD(YEAR,-1,datSTART); -SET datSTART_LY = TIMESTAMPADD(DAY,-1,datSTART_LY); - -SET datEND_LY = TIMESTAMPADD(YEAR,-1,datEND); -SET datEND_LY = TIMESTAMPADD(DAY,-1,datEND_LY); - -DROP TEMPORARY TABLE IF EXISTS tblRESUMEN; - -CREATE TEMPORARY TABLE tblRESUMEN - (Agencia VARCHAR(30), - Vista INT(2), - Dia DATE, - Tickets INT(4), - unidades INT(11), - m3 INT(6), - bultos INT(6), - linea INT(11), - almacen VARCHAR(25), - importe DOUBLE, - año INT -); - -INSERT INTO tblRESUMEN - -select Agencia, Vista, Dia, count(Id_Ticket) as Tickets, sum(unidades) as unidades, sum(Volumen) / 1000000 as m3 - , sum(Bul1) as bultos, sum(lineas) as linea, almacen, SUM(importe) as importe, año -from -( -select Agencia, Vista, date(Fecha) as Dia, sum(Cantidad) as unidades , sum(Cantidad * cm3) as Volumen - ,sum(IF (M.Id_Article IN (71,68,83,79, 85,89,91,92,93), Cantidad, 0)) as Bul1 - , Id_Ticket, count(*) as lineas, IFNULL(T.Bultos,0) as Bul2, w.name as almacen, SUM(Cantidad * Preu * (100 - M.Descuento) / 100) importe, year(T.Fecha) as año - from Movimientos M - inner join Tickets T USING(Id_Ticket) - join warehouse w on T.warehouse_id = w.id - join bi.rotacion r on r.Id_Article = M.Id_Article and r.warehouse_id = T.warehouse_id - inner join Clientes C USING(Id_Cliente) - inner join Articles A on A.Id_Article = M.Id_Article - inner join Tipos TP USING(tipo_id) - join reinos re on re.id = TP.reino_id - inner join Agencias USING(Id_Agencia) - where (Fecha BETWEEN datSTART AND datENDFIN or Fecha BETWEEN datSTART_LY AND datEND_LY) - and re.display <> 0 - and (invoice or Id_Cliente = 31) and C.Id_Cliente NOT IN (2066,2067,2068) - group by Id_Ticket) sub - -group by Agencia, Vista, Dia, almacen, año -; - -SET lc_time_names = 'es_ES'; - -SELECT *, - CASE Vista - WHEN 1 THEN 'Agencias' - WHEN 2 THEN 'Rutas' - WHEN 3 THEN 'Mercado' - ELSE 'Otras' - END as Sector - ,dayname(Dia) as Nombre_Dia - , week - , year - - - FROM tblRESUMEN - JOIN time t on t.date = Dia; - -DROP TEMPORARY TABLE IF EXISTS tblRESUMEN; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `riskkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `riskkk`(v_date DATE, v_customer INT) -BEGIN -/** - * Calcula el riesgo para uno o todos los clientes activos. - * - * @deprecated usar vn.clientGetDebt - * @param v_date Fecha maxima de los registros - * @param v_customer Cliente a mostrar su riesgo, %NULL para todos - * @return table tmp.risk - */ - DECLARE v_date_start DATETIME DEFAULT TIMESTAMPADD(MONTH, -33, CURDATE()); - DECLARE v_date_end DATETIME; - - SET v_date = IFNULL(v_date, CURDATE()); - SET v_date_end = TIMESTAMP(v_date, '23:59:59'); - - DROP TEMPORARY TABLE IF EXISTS ticket_tmp; - CREATE TEMPORARY TABLE ticket_tmp - ENGINE = MEMORY - SELECT Id_Ticket ticket_id FROM Tickets t - WHERE (v_customer IS NULL OR Id_Cliente = v_customer) - AND t.Factura IS NULL - AND t.Fecha BETWEEN v_date_start AND v_date_end; - - CALL ticket_total(); - - DROP TEMPORARY TABLE IF EXISTS tmp.risk; - CREATE TEMPORARY TABLE tmp.risk - ENGINE = MEMORY - SELECT Id_Cliente, SUM(amount) risk - FROM Clientes c - JOIN ( - SELECT customer_id, SUM(amount) amount - FROM bi.customer_risk - WHERE (v_customer IS NULL OR customer_id = v_customer) - GROUP BY customer_id - UNION ALL - SELECT Id_Cliente, SUM(Entregado) - FROM Recibos - WHERE (v_customer IS NULL OR Id_Cliente = v_customer) - AND Fechacobro > v_date_end - GROUP BY Id_Cliente - UNION ALL - SELECT t.Id_Cliente, SUM(total) - FROM ticket_total tt - JOIN Tickets t ON tt.ticket_id = t.Id_Ticket - GROUP BY t.Id_Cliente - UNION ALL - SELECT t.clientFk customer_id, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)) - FROM hedera.tpvTransaction t - WHERE (v_customer IS NULL OR t.clientFk = v_customer) - AND t.receiptFk IS NULL - AND t.status = 'ok' - GROUP BY t.clientFk - ) t ON c.Id_Cliente = t.customer_id - WHERE c.activo != FALSE - GROUP BY c.Id_Cliente; - - DROP TEMPORARY TABLE - ticket_total, - ticket_tmp; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `risk_vs_client_list` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `risk_vs_client_list`(maxRiskDate DATE) -BEGIN -/** - * Calcula el riesgo para los clientes activos de la tabla temporal tmp.client_list - * - * @deprecated usar vn.clientGetDebt - * @param maxRiskDate Fecha maxima de los registros - * @return table tmp.risk - */ - DECLARE startingDate DATETIME DEFAULT TIMESTAMPADD(DAY, - DAYOFMONTH(CURDATE()) - 30, CURDATE()); - DECLARE endingDate DATETIME; - DECLARE MAX_RISK_ALLOWED INT DEFAULT 200; - - SET maxRiskDate = IFNULL(maxRiskDate, CURDATE()); - SET endingDate = TIMESTAMP(maxRiskDate, '23:59:59'); - - DROP TEMPORARY TABLE IF EXISTS tmp.client_list_2; - CREATE TEMPORARY TABLE tmp.client_list_2 - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT * - FROM tmp.client_list; - - DROP TEMPORARY TABLE IF EXISTS tmp.client_list_3; - CREATE TEMPORARY TABLE tmp.client_list_3 - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT * - FROM tmp.client_list; - - DROP TEMPORARY TABLE IF EXISTS tmp.tickets_sin_facturar; - CREATE TEMPORARY TABLE tmp.tickets_sin_facturar - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT t.Id_Cliente, floor(IF(cl.isVies, 1, 1.1) * sum(Cantidad * Preu * (100 - Descuento) / 100)) as total - FROM Movimientos m - JOIN Tickets t on m.Id_Ticket = t.Id_Ticket - JOIN tmp.client_list c on c.Id_Cliente = t.Id_Cliente - JOIN vn.client cl ON cl.id = t.Id_Cliente - WHERE Factura IS NULL - AND Fecha BETWEEN startingDate AND endingDate - GROUP BY t.Id_Cliente; - - DROP TEMPORARY TABLE IF EXISTS tmp.risk; - CREATE TEMPORARY TABLE tmp.risk - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT Id_Cliente, SUM(amount) risk, sum(saldo) saldo - FROM Clientes c - JOIN ( - SELECT customer_id, SUM(amount) amount,SUM(amount) saldo - FROM bi.customer_risk - JOIN tmp.client_list on Id_Cliente = customer_id - GROUP BY customer_id - UNION ALL - SELECT Id_Cliente, SUM(Entregado),SUM(Entregado) - FROM Recibos - JOIN tmp.client_list_2 using(Id_Cliente) - WHERE Fechacobro > endingDate - GROUP BY Id_Cliente - UNION ALL - SELECT Id_Cliente, total,0 - FROM tmp.tickets_sin_facturar - UNION ALL - SELECT t.clientFk, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)), CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)) - FROM hedera.tpvTransaction t - JOIN tmp.client_list_3 on Id_Cliente = t.clientFk - WHERE t.receiptFk IS NULL - AND t.status = 'ok' - GROUP BY t.clientFk - ) t ON c.Id_Cliente = t.customer_id - WHERE c.activo != FALSE - GROUP BY c.Id_Cliente; - - DELETE r.* - FROM tmp.risk r - JOIN vn2008.Clientes c on c.Id_Cliente = r.Id_Cliente - JOIN vn2008.pay_met pm on pm.id = c.pay_met_id - WHERE IFNULL(r.saldo,0) < 10 - AND r.risk <= MAX_RISK_ALLOWED - AND pm.`name` = 'TARJETA'; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Rutas_Graph` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Rutas_Graph`() -BEGIN - -DECLARE datSTART DATE DEFAULT TIMESTAMPADD(DAY,-3,CURDATE()); -DECLARE datEND DATE; - -SET datEND = vn2008.dayend(timestampadd(day,3,CURDATE())); - -CALL item_last_buy_(NULL,datSTART); - -Select cast(sum(Cantidad * vn2008.cm3_unidad(buy_id)) / 1000000 as DECIMAL(5,1)) as m3, Agencia, w.name as Almacen, date(R.Fecha) as Fecha_Ruta - from vn2008.Rutas R - JOIN vn2008.Agencias a on a.Id_Agencia = R.Id_Agencia - join vn2008.Tickets t using(Id_Ruta) - JOIN vn2008.warehouse w on w.id = t.warehouse_id - join vn2008.Movimientos m using(Id_Ticket) - JOIN cache.last_buy b ON m.Id_Article = b.item_id AND t.warehouse_id = b.warehouse_id - where R.Fecha between datSTART and datEND - group by Agencia, Almacen, Fecha_Ruta - -UNION ALL -Select cast(sum(Cantidad * vn2008.cm3_unidad(buy_id)) / 1000000 as decimal(5,1)) as m3 ,Agencia, w.name as Almacen, timestampadd(day,1,t.Fecha) Fecha - from vn2008.Tickets t - join warehouse w on w.id = warehouse_id - join Agencias a using(Id_Agencia) - join vn2008.Movimientos m using(Id_Ticket) - JOIN cache.last_buy b ON m.Id_Article = b.item_id AND t.warehouse_id = b.warehouse_id - LEFT JOIN warehouse_pickup wp ON wp.agency_id = t.Id_Agencia and wp.warehouse_id = t.warehouse_id - JOIN warehouse_pickup is_rec ON is_rec.agency_id = t.Id_Agencia - where t.Fecha between TIMESTAMPADD(DAY,-1,datSTART) and TIMESTAMPADD(DAY,-1,datEND) - AND wp.agency_id IS NULL - group by Agencia, Almacen, Fecha - -- JGF 2016-05-05 -UNION ALL - Select cast(sum(Cantidad * vn2008.cm3_unidad(Id_Compra)) / 1000000 as decimal(5,1)) as m3 ,a.Agencia, w.name as Almacen, - timestampadd(day,1,t.shipment) Fecha - from Compres c JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel t ON t.id = e.travel_id - JOIN Agencias a on a.Id_Agencia = t.agency_id - JOIN warehouse w on w.id = t.warehouse_id_out - JOIN warehouse_pickup wp ON wp.warehouse_id = t.warehouse_id_out - where t.shipment between TIMESTAMPADD(DAY,-1,datSTART) and TIMESTAMPADD(DAY,-1,datEND) - group by a.Agencia, Almacen, Fecha; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Rutas_monitor_update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Rutas_monitor_update`(vDate DATE) -BEGIN - -DECLARE vDateEND DATETIME; - -SET vDateEND = util.dayend(vDate); -SET vDate = TIMESTAMPADD(DAY,-1,vDate); - -INSERT IGNORE INTO Rutas_monitor(Id_Ruta) - SELECT DISTINCT Id_Ruta - FROM Tickets - WHERE Fecha BETWEEN vDate AND vDateEND - AND Id_Ruta; - -UPDATE Rutas_monitor rm -JOIN Rutas r ON r.Id_Ruta = rm.Id_Ruta -JOIN Agencias a ON a.Id_Agencia = r.Id_Agencia -SET rm.`name` = a.Agencia, rm.fecha = r.Fecha, - rm.pedidosLibres = 0, - rm.pedidosProduccion = 0, - rm.pedidosEncajados = 0, - rm.Fecha = r.Fecha; -/* -UPDATE Rutas_monitor rm -JOIN ( - SELECT Id_Ruta, max(landing) as landing - FROM Tickets t - WHERE t.Fecha BETWEEN vDate AND vDateEND - GROUP BY Id_Ruta - ) t ON t.Id_Ruta = rm.Id_Ruta -SET rm.Fecha = t.landing; -*/ -UPDATE Rutas_monitor rm -JOIN -( SELECT Id_Ruta, count(*) AS pedidosLibres - FROM Tickets t - JOIN Tickets_state ts ON t.Id_Ticket = ts.Id_Ticket - JOIN vncontrol.inter i ON i.inter_id = ts.inter_id - JOIN state s ON i.state_id = s.id AND s.alert_level = 0 - WHERE t.Fecha BETWEEN vDate AND vDateEND - AND Id_Ruta - GROUP BY Id_Ruta -) t ON t.Id_Ruta = rm.Id_Ruta -SET rm.pedidosLibres = t.pedidosLibres; - -UPDATE Rutas_monitor rm -JOIN -( SELECT Id_Ruta, count(*) AS pedidosProduccion - FROM Tickets t - JOIN Tickets_state ts ON t.Id_Ticket = ts.Id_Ticket - JOIN vncontrol.inter i ON i.inter_id = ts.inter_id - JOIN state s ON i.state_id = s.id AND s.alert_level = 1 - WHERE t.Fecha BETWEEN vDate AND vDateEND - AND Id_Ruta - GROUP BY Id_Ruta -) t ON t.Id_Ruta = rm.Id_Ruta -SET rm.pedidosProduccion = t.pedidosProduccion; - -UPDATE Rutas_monitor rm -JOIN -( SELECT Id_Ruta, count(*) AS pedidosEncajados - FROM Tickets t - JOIN Tickets_state ts ON t.Id_Ticket = ts.Id_Ticket - JOIN vncontrol.inter i ON i.inter_id = ts.inter_id - JOIN state s ON i.state_id = s.id AND s.alert_level >= 2 - WHERE t.Fecha BETWEEN vDate AND vDateEND - AND Id_Ruta - GROUP BY Id_Ruta -) t ON t.Id_Ruta = rm.Id_Ruta -SET rm.pedidosEncajados = t.pedidosEncajados; - -UPDATE Rutas_monitor rm -JOIN -( SELECT Id_Ruta, count(*) AS bultos - FROM Tickets t - JOIN expeditions e ON e.ticket_id = t.Id_Ticket - WHERE t.Fecha BETWEEN vDate AND vDateEND - AND Id_Ruta - GROUP BY Id_Ruta -) t ON t.Id_Ruta = rm.Id_Ruta -SET rm.bultos = t.bultos; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `saldos_bancos` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `saldos_bancos`() -BEGIN - -declare datEND DATE; - -SET datEND = CURDATE() + INTERVAL 2 MONTH; - -drop table if exists bi.saldos_bancos; - - -create table bi.saldos_bancos - - select Semana, Mes, Año, Entrada - , Salida - , @saldo := IF(@banco = Id_Banco and @emp = empresa_id, @saldo,0) + ifnull(Entrada,0)-ifnull(Salida,0) as Saldo - , @banco := Id_Banco as Id_Banco - , @emp := empresa_id as empresa_id - , 'NUL' as Empresa - - from - ( - select * from - ( - select t.week as Semana, t.year as Año, t.month as Mes, b.Id_Banco, sum(Entrada) as Entrada, sum(Salida) as Salida, @banco := 0, @saldo := 0, @emp := 0, e.id as empresa_id - from time t - join Bancos b on b.entity_id = 1 - join empresa e on e.id IN (791,442) - left join - ( - Select Id_Banco, Entrada, Salida, Cajafecha,empresa_id - from Cajas - where Cajafecha >= '2015-01-01' - and Serie = 'MB' - union all - Select Id_Banco, NULL, importe, greatest(fecha,TIMESTAMPADD(DAY,1,CURDATE())),empresa_id - from pago - where conciliado = FALSE /*fecha between CURDATE() and datEND*/ - union all - Select Id_Banco, Entregado, NULL, greatest(Fechacobro,TIMESTAMPADD(DAY,1,CURDATE())),empresa_id - from Recibos - where Fechacobro between CURDATE() and datEND - union all - Select IFNULL(Id_Banco,9999), Importe, NULL, Fecha,empresa_id - from Saldos_Prevision - where Fecha between CURDATE() and datEND - ) sub2 on t.date = sub2.Cajafecha and b.Id_Banco = sub2.Id_Banco and e.id = sub2.empresa_id - - where t.date between '2015-01-01' and datEND - and b.cash != 1 - group by b.Id_Banco, e.id, t.year, t.week - ) sub3 - order by Id_Banco, empresa_id, Año, Mes, Semana - ) sub -; - -update bi.saldos_bancos s -join empresa e on e.id = s.empresa_id -set s.Empresa = abbreviation; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `saldos_bancos_pordia` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `saldos_bancos_pordia`() -BEGIN - -declare datEND DATE; - -SET datEND = CURDATE() + INTERVAL 2 MONTH; - -drop table if exists bi.saldos_bancos_pordia; - - -create table bi.saldos_bancos_pordia - - select Fecha, Entrada - , Salida - , @saldo := IF(@banco = Id_Banco and @emp = empresa_id, @saldo,0) + ifnull(Entrada,0)-ifnull(Salida,0) as Saldo - , @banco := Id_Banco as Id_Banco - , @emp := empresa_id as empresa_id - , 'NUL' as Empresa - , Año, Mes, Dia - - from - ( - select * from - ( - select t.day as Dia, t.month as Mes,t.year as Año, t.date as Fecha, b.Id_Banco, sum(Entrada) as Entrada, sum(Salida) as Salida, @banco := 0, @saldo := 0, @emp := 0, e.id as empresa_id - from time t - join Bancos b on b.entity_id = 1 - join empresa e on e.id IN (791,442) - left join - ( - Select Id_Banco, Entrada, Salida, Cajafecha,empresa_id - from Cajas - where Cajafecha >= '2015-01-01' - and Serie = 'MB' - union all - Select Id_Banco, NULL, importe, greatest(fecha,TIMESTAMPADD(DAY,1,CURDATE())),empresa_id - from pago - where conciliado = FALSE /*fecha between CURDATE() and datEND*/ - union all - Select Id_Banco, Entregado, NULL, greatest(Fechacobro,TIMESTAMPADD(DAY,1,CURDATE())),empresa_id - from Recibos - where conciliado = FALSE -- Fechacobro between CURDATE() and datEND - union all - Select IFNULL(Id_Banco,9999), Importe, NULL, Fecha,empresa_id - from Saldos_Prevision - where Fecha between CURDATE() and datEND - ) sub2 on t.date = sub2.Cajafecha and b.Id_Banco = sub2.Id_Banco and e.id = sub2.empresa_id - - where t.date between '2015-01-01' and datEND - and b.cash != 1 - group by b.Id_Banco, e.id, t.date - ) sub3 - order by Id_Banco, empresa_id, Fecha - ) sub -; - -update bi.saldos_bancos_pordia s -join empresa e on e.id = s.empresa_id -set s.Empresa = abbreviation; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `scan_rutas_view` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `scan_rutas_view`() -BEGIN - - -/* muestra las rutas agrupadas de los ultimos tres dias, así como una lista de los tickets sin enrutar, agrpados por agencia y fecha*/ - -select Fecha, Id_Ruta, Matricula, sub.m3, CodigoTrabajador, Agencia, Bultos, w.name as Almacen -from -( -select r.Fecha, Id_Ruta, r.Id_Trabajador, r.Id_Agencia, Id_Vehiculo, sum(m3) m3, sum(Bultos) Bultos, warehouse_id -from Rutas r -join Tickets t using(Id_Ruta) -where r.Fecha >= timestampadd(day,-3,curdate()) -group by Id_Ruta, warehouse_id - -union all - -select ifnull(landing,Fecha), dayofmonth(Fecha) * 100000 + Id_Agencia ruta , count(*) as m3, Id_Agencia, null, null, sum(Bultos), warehouse_id -from Tickets -where Id_Ruta is null -and Fecha between timestampadd(day,-3,curdate()) and dayend(curdate()) -group by ruta, warehouse_id -) sub -left join Vehiculos using(Id_Vehiculo) -left join Agencias using(Id_Agencia) -left join Trabajadores using(Id_Trabajador) -left join warehouse w on w.id = sub.warehouse_id; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `sendTicket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `sendTicket`(vDate DATE) -BEGIN - IF vDate IS NULL THEN - SET vDate = AYER(); - END IF; - - INSERT INTO mail (`to`, `reply_to`, subject,text) - SELECT IFNULL(c.`e-mail`,CONCAT(u.name,'@verdnatura.es')), - CONCAT(u.name,'@verdnatura.es'), - CONCAT('Albaran ',Id_Ticket), -CONCAT('Estimado cliente: - -Aquí tiene el enlace a su albarán. - -https://www.verdnatura.es/#!form=ecomerce/ticket&ticket=',Id_Ticket, -' - -Estamos en periodo de pruebas para este nuevo método. En el caso de que tenga problemas para acceder a su albarán, responda a este correo explicando los detalles. - -Estamos trabajando para mejorar el acceso a sus documentos.Le agradecemos su colaboración. - -Reciba un muy cordial saludo, - -',tr.nombre, ' ', tr.apellidos,' -',u.name,'@verdnatura.es - -Dpto. Comercial') - FROM Tickets t - JOIN Clientes c USING(Id_Cliente) - JOIN Trabajadores tr ON tr.Id_Trabajador = c.Id_Trabajador - JOIN account.user u ON tr.user_id = u.id - WHERE vDate = DATE(t.Fecha); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `splitAnthuriums2016` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `splitAnthuriums2016`() -BEGIN - -DECLARE vStartingDate DATETIME DEFAULT '2016-10-18'; -DECLARE vEndingDate DATETIME DEFAULT '2016-10-31 23:59:00'; -DECLARE vMyTicket INT; -DECLARE vNewTicket INT; -DECLARE SILLA_PCA INT DEFAULT 44; -DECLARE done INT DEFAULT 0; - -DECLARE rs CURSOR FOR -SELECT DISTINCT Id_Ticket -FROM Movimientos m -JOIN Tickets t using(Id_Ticket) -JOIN Articles a using(Id_Article) -JOIN Tipos tp using(tipo_id) -WHERE t.Fecha between vStartingDate and vEndingDate -AND warehouse_id = 1 -AND - ( - Id_Tipo = 'ANT' - OR - ( Id_Article = 100 - AND - Concepte LIKE 'ANT%') - ); - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - -OPEN rs; - -FETCH rs INTO vMyTicket; - - - -WHILE NOT done DO - - - INSERT INTO Tickets(Id_Cliente - , warehouse_id - , Fecha - , Alias - , Id_Consigna - , Id_Trabajador - , Id_Ruta - , empresa_id - , Id_Agencia - , landing) - SELECT Id_Cliente - , SILLA_PCA as warehouse_id - , Fecha - , Alias - , Id_Consigna - , Id_Trabajador - , Id_Ruta - , empresa_id - , Id_Agencia - , landing - FROM Tickets - WHERE Id_Ticket = vMyTicket; - - SELECT LAST_INSERT_ID() INTO vNewTicket; - - -- SELECT vMyTicket, vNewTicket; SET done = 1; - UPDATE Movimientos m - JOIN Articles a using(Id_Article) - JOIN Tipos tp using(tipo_id) - SET Id_Ticket = vNewTicket - WHERE Id_Ticket = vMyTicket - AND ( - Id_Tipo = 'ANT' - OR - ( m.Id_Article = 100 - AND - Concepte LIKE 'ANT%') - ); - - FETCH rs INTO vMyTicket; - -END WHILE; - -CLOSE rs; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `splitHeliconias2016` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `splitHeliconias2016`() -BEGIN - -DECLARE vStartingDate DATETIME DEFAULT '2016-10-18'; -DECLARE vEndingDate DATETIME DEFAULT '2016-10-31 23:59:00'; -DECLARE vMyTicket INT; -DECLARE vNewTicket INT; -DECLARE SILLA_PCA INT DEFAULT 44; -DECLARE done INT DEFAULT 0; - -DECLARE rs CURSOR FOR -SELECT DISTINCT Id_Ticket -FROM Movimientos m -JOIN Compres c ON Id_Entrada IN (100461, 100929) AND c.Id_Article = m.Id_Article -JOIN Tickets t using(Id_Ticket) -WHERE t.Fecha between vStartingDate and vEndingDate -AND warehouse_id = 1; - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - -OPEN rs; - -FETCH rs INTO vMyTicket; - - - -WHILE NOT done DO - - - INSERT INTO Tickets(Id_Cliente - , warehouse_id - , Fecha - , Alias - , Id_Consigna - , Id_Trabajador - , Id_Ruta - , empresa_id - , Id_Agencia - , landing) - SELECT Id_Cliente - , SILLA_PCA as warehouse_id - , Fecha - , Alias - , Id_Consigna - , Id_Trabajador - , Id_Ruta - , empresa_id - , Id_Agencia - , landing - FROM Tickets - WHERE Id_Ticket = vMyTicket; - - SELECT LAST_INSERT_ID() INTO vNewTicket; - - -- SELECT vMyTicket, vNewTicket; SET done = 1; - UPDATE Movimientos m - JOIN Compres c ON Id_Entrada IN (100461, 100929) AND c.Id_Article = m.Id_Article - SET Id_Ticket = vNewTicket - WHERE Id_Ticket = vMyTicket - ; - - FETCH rs INTO vMyTicket; - -END WHILE; - -CLOSE rs; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `splitOrquideas2016` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `splitOrquideas2016`() -BEGIN - -DECLARE vStartingDate DATETIME DEFAULT '2016-10-18'; -DECLARE vEndingDate DATETIME DEFAULT '2016-10-31 23:59:00'; -DECLARE vMyTicket INT; -DECLARE vNewTicket INT; -DECLARE SILLA_PCA INT DEFAULT 44; -DECLARE done INT DEFAULT 0; - -DECLARE rs CURSOR FOR -SELECT DISTINCT Id_Ticket -FROM Movimientos m -JOIN Tickets t using(Id_Ticket) -JOIN Articles a using(Id_Article) -JOIN Tipos tp using(tipo_id) -WHERE t.Fecha between vStartingDate and vEndingDate -AND warehouse_id = 1 -AND - ( - Id_Tipo = 'CYM' - OR - Id_Tipo = 'ORQ' - OR - ( Id_Article = 100 - AND - Concepte LIKE 'CYM%') - ); - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - -OPEN rs; - -FETCH rs INTO vMyTicket; - - - -WHILE NOT done DO - - - INSERT INTO Tickets(Id_Cliente - , warehouse_id - , Fecha - , Alias - , Id_Consigna - , Id_Trabajador - , Id_Ruta - , empresa_id - , Id_Agencia - , landing) - SELECT Id_Cliente - , SILLA_PCA as warehouse_id - , Fecha - , Alias - , Id_Consigna - , Id_Trabajador - , Id_Ruta - , empresa_id - , Id_Agencia - , landing - FROM Tickets - WHERE Id_Ticket = vMyTicket; - - SELECT LAST_INSERT_ID() INTO vNewTicket; - - -- SELECT vMyTicket, vNewTicket; SET done = 1; - UPDATE Movimientos m - JOIN Articles a using(Id_Article) - JOIN Tipos tp using(tipo_id) - SET Id_Ticket = vNewTicket - WHERE Id_Ticket = vMyTicket - AND ( - Id_Tipo = 'CYM' - OR - Id_Tipo = 'ORQ' - OR - ( Id_Article = 100 - AND - Concepte LIKE 'CYM%') - ); - - FETCH rs INTO vMyTicket; - -END WHILE; - -CLOSE rs; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `splitRamos2016` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `splitRamos2016`() -BEGIN - -DECLARE vStartingDate DATETIME DEFAULT '2016-10-21'; -DECLARE vEndingDate DATETIME DEFAULT '2016-10-31 23:59:00'; -DECLARE vMyTicket INT; -DECLARE vNewTicket INT; -DECLARE SILLA_PCA INT DEFAULT 44; -DECLARE done INT DEFAULT 0; -DECLARE vLinesNotToChange INT; - -DECLARE rs CURSOR FOR -SELECT DISTINCT Id_Ticket - FROM Movimientos m - JOIN - ( - SELECT DISTINCT Id_Article - FROM Compres c - JOIN Entradas e on c.Id_Entrada = e.Id_Entrada - JOIN travel tr on tr.id = travel_id - WHERE landing between vStartingDate and vEndingDate - AND warehouse_id = 44 - AND Id_Proveedor = 850 - ) c on c.Id_Article = m.Id_Article - JOIN Tickets t using(Id_Ticket) - WHERE t.Fecha between vStartingDate and vEndingDate - AND warehouse_id = 1 - ; - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - -OPEN rs; - -FETCH rs INTO vMyTicket; - - - -WHILE NOT done DO - - SELECT COUNT(*) - INTO vLinesNotToChange - FROM Movimientos m - LEFT JOIN - ( - SELECT DISTINCT Id_Article - FROM Compres c - JOIN Entradas e on c.Id_Entrada = e.Id_Entrada - JOIN travel tr on tr.id = travel_id - WHERE landing between vStartingDate and vEndingDate - AND warehouse_id = 44 - AND Id_Proveedor = 850 - ) c on c.Id_Article = m.Id_Article - WHERE Id_Ticket = vMyTicket - AND c.Id_Article IS NULL; - - IF vLinesNotToChange THEN - - INSERT INTO Tickets(Id_Cliente - , warehouse_id - , Fecha - , Alias - , Id_Consigna - , Id_Trabajador - , Id_Ruta - , empresa_id - , Id_Agencia - , landing) - SELECT Id_Cliente - , SILLA_PCA as warehouse_id - , Fecha - , Alias - , Id_Consigna - , Id_Trabajador - , Id_Ruta - , empresa_id - , Id_Agencia - , landing - FROM Tickets - WHERE Id_Ticket = vMyTicket; - - SELECT LAST_INSERT_ID() INTO vNewTicket; - - -- SELECT vMyTicket, vNewTicket; SET done = 1; - UPDATE Movimientos m - JOIN - ( - SELECT DISTINCT Id_Article - FROM Compres c - JOIN Entradas e on c.Id_Entrada = e.Id_Entrada - JOIN travel tr on tr.id = travel_id - WHERE landing between vStartingDate and vEndingDate - AND warehouse_id = 44 - AND Id_Proveedor = 850 - ) c on c.Id_Article = m.Id_Article - SET Id_Ticket = vNewTicket - WHERE Id_Ticket = vMyTicket; - - ELSE - - UPDATE Tickets - SET warehouse_id = 44 - WHERE Id_Ticket = vMyTicket; - - END IF; - - - FETCH rs INTO vMyTicket; - -END WHILE; - -CLOSE rs; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `sql_query` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `sql_query`(IN v_sql TEXT) -BEGIN - SET @v_sql = v_sql; - - PREPARE stmt FROM @v_sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `subordinate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `subordinate`( IN idWORKER INTEGER,IN CasoBase BOOL) -BEGIN - DECLARE auxWorker INT; - DECLARE vCompanyId INT; - - SELECT empresa_id - INTO vCompanyId - FROM Trabajadores - WHERE Id_Trabajador = idWORKER; - - IF vCompanyId = 1381 THEN -- ORNAMENTALES - - DROP TABLE IF EXISTS subordinate; - CREATE TABLE subordinate - (INDEX (Id_Trabajador)) ENGINE = MEMORY - SELECT Id_Trabajador,TRUE visited,0 boss - FROM Trabajadores - WHERE empresa_id = vCompanyId; - - ELSE - - - /* PAK 23/05/2016 - - Guardia de domingos - - Los domingos viene Fran a hacer de comercial y necesita ver todos los radares - - - - IF dayofweek(curdate()) = 1 and idWORKER = 43 then -- Domingo y Fran Natek - - DROP TABLE IF EXISTS subordinate; - - CREATE TABLE subordinate - (INDEX (Id_Trabajador)) ENGINE = MEMORY - SELECT Id_Trabajador,TRUE visited,0 boss - FROM Trabajadores; - - - else - */ - - IF CasoBase THEN - SET @@max_sp_recursion_depth = 5 ; - DROP TABLE IF EXISTS subordinate; - CREATE TABLE subordinate - (INDEX (Id_Trabajador)) ENGINE = MEMORY - SELECT idWORKER Id_Trabajador,TRUE visited,0 boss; - END IF; - - INSERT INTO subordinate - SELECT Id_Trabajador,0,idWORKER FROM Trabajadores WHERE boss = idWORKER; - IF (SELECT COUNT(*) FROM subordinate WHERE visited = 0 AND idWORKER = boss LIMIT 1) > 0 THEN - SELECT Id_Trabajador into auxWorker FROM subordinate WHERE visited = 0 AND idWORKER = boss LIMIT 1; - REPEAT - CALL subordinate(auxWorker,FALSE); - UPDATE subordinate SET visited = TRUE WHERE Id_Trabajador = auxWorker; - SET auxWorker = 0; - SELECT Id_Trabajador into auxWorker FROM subordinate WHERE visited = 0 AND idWORKER = boss LIMIT 1; - UNTIL auxWorker = 0 - END REPEAT; - END IF; - - /* - end if; - */ - - END IF; - - IF idWorker = 2 THEN - INSERT INTO subordinate(Id_Trabajador,visited,boss) VALUES (2,TRUE,2); - -- INSERT INTO subordinate(Id_Trabajador,visited,boss) VALUES (43,TRUE,2); - END IF; - - /* - IF CasoBase THEN - SELECT * FROM subordinate; - END IF;*/ - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `subordinate2` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `subordinate2`( IN idWORKER INTEGER,IN CasoBase BOOL) -BEGIN - DECLARE auxWorker INT; - DECLARE vCompanyId INT; - - SELECT empresa_id - INTO vCompanyId - FROM Trabajadores - WHERE Id_Trabajador = idWORKER; - - IF vCompanyId = 1381 THEN -- ORNAMENTALES - - DROP TABLE IF EXISTS subordinate; - CREATE TABLE subordinate - (INDEX (Id_Trabajador)) ENGINE = MEMORY - SELECT Id_Trabajador,TRUE visited,0 boss - FROM Trabajadores - WHERE empresa_id = vCompanyId; - - ELSE - - - /* PAK 23/05/2016 - - Guardia de domingos - - Los domingos viene Fran a hacer de comercial y necesita ver todos los radares - - - - IF dayofweek(curdate()) = 1 and idWORKER = 43 then -- Domingo y Fran Natek - - DROP TABLE IF EXISTS subordinate; - - CREATE TABLE subordinate - (INDEX (Id_Trabajador)) ENGINE = MEMORY - SELECT Id_Trabajador,TRUE visited,0 boss - FROM Trabajadores; - - - else - */ - - IF CasoBase THEN - SET @@max_sp_recursion_depth = 5 ; - DROP TABLE IF EXISTS subordinate; - CREATE TABLE subordinate - (INDEX (Id_Trabajador)) ENGINE = MEMORY - SELECT idWORKER Id_Trabajador,TRUE visited,0 boss; - END IF; - - INSERT INTO subordinate - SELECT Id_Trabajador,0,idWORKER FROM Trabajadores WHERE boss = idWORKER; - IF (SELECT COUNT(*) FROM subordinate WHERE visited = 0 AND idWORKER = boss LIMIT 1) > 0 THEN - SELECT Id_Trabajador into auxWorker FROM subordinate WHERE visited = 0 AND idWORKER = boss LIMIT 1; - REPEAT - CALL subordinate(auxWorker,FALSE); - UPDATE subordinate SET visited = TRUE WHERE Id_Trabajador = auxWorker; - SET auxWorker = 0; - SELECT Id_Trabajador into auxWorker FROM subordinate WHERE visited = 0 AND idWORKER = boss LIMIT 1; - UNTIL auxWorker = 0 - END REPEAT; - END IF; - - /* - end if; - */ - - END IF; - - IF idWorker = 2 THEN - INSERT INTO subordinate(Id_Trabajador) VALUES (2); - END IF; - - /* - IF CasoBase THEN - SELECT * FROM subordinate; - END IF;*/ - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `suppliersDebt` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `suppliersDebt`() -BEGIN - - SELECT abbreviation as Empresa, Proveedor, Euros, empresa_id, proveedor_id - FROM - ( - SELECT empresa_id, proveedor_id, cast(sum(Euros) AS DECIMAL(10,2)) as Euros - FROM - ( - SELECT empresa_id, proveedor_id, -1 * cantidad as Euros - FROM recibida_vencimiento rv - INNER JOIN recibida r ON r.id = rv.recibida_id - WHERE r.fecha > '2014-12-31' - - UNION ALL - - SELECT empresa_id, id_proveedor, importe - FROM pago - WHERE fecha > '2014-12-31' - ) sub - GROUP BY empresa_id, proveedor_id - ) sub2 - JOIN Proveedores p ON p.Id_Proveedor = sub2.proveedor_id - JOIN empresa e ON e.id = sub2.empresa_id - ; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `supplierStatement` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `supplierStatement`(vSupplierFk INT, vCurrencyFk INT, vCompanyFk INT, vOrderBy VARCHAR(15)) -BEGIN - SET @saldo_eur:= 0; - SET @saldo_div:= 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.supplierStatement; - - CREATE TEMPORARY TABLE tmp.supplierStatement ENGINE = MEMORY - SELECT - *, - @saldo_eur:= round(@saldo_eur + IFNULL(Pago_Euros, 0) - IFNULL(Fac_Euros, 0) ,2 ) AS saldo_eur, - @saldo_div:= round(@saldo_div + IFNULL(Pago_Divisas, 0) - IFNULL(Fac_Divisas, 0) ,2 ) AS saldo_div - FROM - (SELECT * FROM - (SELECT - NULL as banco_id, - r.empresa_id, - r.serie, - r.id, - CASE - WHEN vOrderBy = 'issued' THEN r.fecha - WHEN vOrderBy = 'bookEntried' THEN r.bookEntried - WHEN vOrderBy = 'booked' THEN r.dateBooking - WHEN vOrderBy = 'dueDate' THEN rv.fecha - END AS fecha, - CONCAT('S/Fra ', r.sref) sref, - if(r.moneda_id > 1,round(sum(divisa) / sum(cantidad),3),NULL) val_cambio, - CAST(sum(cantidad) as DECIMAL(10,2)) as Fac_Euros, - CAST(sum(divisa) as DECIMAL(10,2)) as Fac_Divisas, - NULL AS Pago_Euros, - NULL AS Pago_Divisas, - r.moneda_id, - r.contabilizada, - Moneda, - NULL as pago_sdc_id - FROM - recibida r - JOIN recibida_vencimiento rv on rv.recibida_id = r.id - JOIN Monedas m on m.Id_Moneda = r.moneda_id - WHERE - r.fecha > '2014-12-31' - AND r.proveedor_id = vSupplierFk - AND vCurrencyFk IN (r.moneda_id, 0) - AND vCompanyFk IN (r.empresa_id,0) - GROUP BY rv.id - - UNION ALL SELECT - p.id_banco, - p.empresa_id, - NULL, - p.id, - Fecha, - CONCAT(IFNULL(name, ''), IF(pre.concepto <> '', CONCAT(' : ', pre.concepto), '')), - if(p.id_moneda > 1, p.divisa / importe, NULL) tip_cambio, - NULL, - NULL, - p.importe, - p.divisa, - p.id_moneda, - IFNULL(conciliado, 0), - Moneda, - pago_sdc_id - FROM - pago p - LEFT JOIN Monedas ON Monedas.Id_Moneda = p.id_moneda - LEFT JOIN Bancos ON p.id_banco = Bancos.Id_banco - LEFT JOIN pay_met pm ON p.pay_met_id = pm.id - LEFT JOIN Pagares pre ON pre.pago_id = p.id - WHERE - Fecha > '2014-12-31' - AND p.Id_Proveedor = vSupplierFk - AND vCurrencyFk IN (p.id_moneda,0) - AND vCompanyFk IN (p.empresa_id,0) - ) AS SUB - ORDER BY fecha, IF(vOrderBy = 'dueDate', id, NULL)) t; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `tarjetas_credito_0` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `tarjetas_credito_0`() -BEGIN - - DECLARE MyMaxID INT; - - SELECT MAX(id) FROM credit INTO MyMaxID; - - UPDATE Clientes - SET Credito = 0 - WHERE pay_met_id = 5 -- TARJETA - ; - - UPDATE credit - SET Id_Trabajador = 20 - WHERE id > MyMaxID; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `tickets_in_a_week` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `tickets_in_a_week`(IN intWEEK INT(2), IN intYEAR INT(4), IN idART INT(11), IN intWH INT(2)) -BEGIN - DECLARE period INT(6) DEFAULT intYEAR * 100 + intWEEK; - DECLARE datINI DATE; - DECLARE datFIN DATE; - - -- Seleccionamos la fecha minima/maxima del periodo que vamos a consultar - SELECT MIN(`date`) INTO datINI FROM vn2008.`time` t WHERE t.period = period; - SELECT TIMESTAMP(MAX(`date`),'23:59:59') INTO datFIN FROM vn2008.`time` t WHERE t.period = period; - - SELECT T.Fecha, - T.Id_Ticket, - M.Cantidad, - M.Id_Article, - T.Alias, - M.PrecioFijado, - M.Preu, - M.Id_Movimiento, - T.warehouse_id, - W.name, - ticket_state(Factura, PedidoImpreso, Etiquetasemitidas, blocked) as Estado, - M.Descuento - FROM Movimientos M - INNER JOIN Tickets T using(Id_Ticket) - LEFT JOIN warehouse W ON W.id = T.warehouse_id - WHERE M.Id_Article = idART AND T.Fecha BETWEEN datINI and datFIN - AND IF(intWH = 0, W.comisionantes, intWH =T.warehouse_id) - ORDER BY T.Fecha, T.Id_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 DROP PROCEDURE IF EXISTS `tickets_in_a_week_by_type` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `tickets_in_a_week_by_type`(IN intWEEK INT(2), IN intYEAR INT(4), IN idART INT(11), IN intWH INT(2)) -BEGIN - - DECLARE intTIPO INT; - DECLARE period INT(6) DEFAULT intYEAR * 100 + intWEEK; - DECLARE datINI DATE; - DECLARE datFIN DATE; - - SELECT tipo_id INTO intTIPO FROM Articles WHERE Id_Article = idART; - - -- Seleccionamos la fecha minima/maxima del periodo que vamos a consultar - SELECT MIN(`date`) INTO datINI FROM vn2008.`time` t WHERE t.period = period; - SELECT TIMESTAMP(MAX(`date`),'23:59:59') INTO datFIN FROM vn2008.`time` t WHERE t.period = period; - - SELECT T.Fecha, - T.Id_Ticket, - M.Cantidad, - M.Id_Article, - T.Alias, - M.PrecioFijado, - M.Preu, - M.Id_Movimiento, - T.warehouse_id, - W.name, - ticket_state(Factura, PedidoImpreso, Etiquetasemitidas, blocked) as Estado, - M.Descuento - FROM Movimientos M - JOIN Articles A using(Id_Article) - INNER JOIN Tickets T ON M.Id_Ticket = T.Id_Ticket - LEFT JOIN warehouse W ON W.id = T.warehouse_id - WHERE A.tipo_id = intTIPO - AND T.Fecha between datINI and datFIN - AND IF(intWH = 0, W.comisionantes, intWH =T.warehouse_id) - ORDER BY T.Fecha, T.Id_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 DROP PROCEDURE IF EXISTS `tickets_week_joined` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `tickets_week_joined`(IN intWEEK INT(2), IN intYEAR INT(4), IN idART INT(11), IN intWhJoined INT(2)) -BEGIN - - - DECLARE datSTART date; - DECLARE datEND date; - - - SET datSTART = TIMESTAMPADD(YEAR,intYEAR,'0000-01-01'); - SET datSTART = TIMESTAMPADD(WEEK, intWEEK-1,datSTART); - SET datSTART = TIMESTAMPADD(DAY,-1 * WEEKDAY(datSTART),datSTART); - - - --- Año 2014 -/* -IF datSTART = '2013-12-31' THEN - - SET datSTART = '2013-12-30' ; - -END IF; -*/ - - - SET datEND = TIMESTAMPADD(DAY,7,datSTART); - - - - SELECT T.Fecha, - T.Id_Ticket, - M.Cantidad, - M.Id_Article, - T.Alias, - M.PrecioFijado, - M.Preu, - M.Id_Movimiento, - T.warehouse_id, - wa.alias `name`, - ticket_state(Factura, PedidoImpreso, Etiquetasemitidas, blocked) as Estado, - M.Descuento - FROM Movimientos M - JOIN Tickets T ON M.Id_Ticket = T.Id_Ticket - JOIN warehouse_joined wj ON wj.warehouse_id = T.warehouse_id - JOIN warehouse_alias wa ON wa.warehouse_alias_id = wj.warehouse_alias_id - WHERE M.Id_Article = idART - AND T.Fecha between datSTART and datEND - AND intWhJoined IN (0,wj.warehouse_alias_id) - ORDER BY T.Fecha, T.Id_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 DROP PROCEDURE IF EXISTS `tickets_week_type_joined` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `tickets_week_type_joined`(IN intWEEK INT(2), IN intYEAR INT(4), IN idART INT(11), IN intWhJoined INT(2)) -BEGIN - - DECLARE intTIPO INT; - DECLARE datSTART date; - DECLARE datEND date; - - SELECT tipo_id INTO intTIPO FROM Articles WHERE Id_Article = idART; - - SET datSTART = TIMESTAMPADD(YEAR,intYEAR,'0000-01-01'); - SET datSTART = TIMESTAMPADD(WEEK, intWEEK-1,datSTART); - SET datSTART = TIMESTAMPADD(DAY,-1 * WEEKDAY(datSTART),datSTART); - - SET datEND = TIMESTAMPADD(DAY,7,datSTART); - - - - SELECT T.Fecha, - T.Id_Ticket, - M.Cantidad, - M.Id_Article, - T.Alias, - M.PrecioFijado, - M.Preu, - M.Id_Movimiento, - T.warehouse_id, - wa.alias `name`, - ticket_state(Factura, PedidoImpreso, Etiquetasemitidas, blocked) as Estado, - M.Descuento - FROM Movimientos M - JOIN Articles A using(Id_Article) - INNER JOIN Tickets T ON M.Id_Ticket = T.Id_Ticket - JOIN warehouse_joined wj ON wj.warehouse_id = T.warehouse_id - JOIN warehouse_alias wa ON wa.warehouse_alias_id = wj.warehouse_alias_id - WHERE A.tipo_id = intTIPO - AND T.Fecha between datSTART and datEND - AND intWhJoined IN (0,wj.warehouse_alias_id) - ORDER BY T.Fecha, T.Id_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 DROP PROCEDURE IF EXISTS `ticket_canarias` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_canarias`(IN v_entrada BIGINT, IN v_ticket BIGINT) -BEGIN - - -set @w := 1; -set @tr := 0; -set @e := v_entrada; -set @t := v_ticket; - -select id, IF(warehouse_id_out = 13, @w, warehouse_id_out) into @tr, @w from travel join Entradas on id = travel_id where Id_Entrada = @e; - -update travel tr join Entradas e on tr.id = e.travel_id set warehouse_id_out = 13 where Id_Entrada = @e and warehouse_id_out <> 13; - -update Tickets set warehouse_id = @w where Id_Ticket = @t; - -REPLACE order_Tickets(order_id, Id_Ticket) VALUES(48,@t); - -delete mc.* from Movimientos_componentes mc join Movimientos m using(Id_Movimiento) where Id_Ticket = @t; - -insert into Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) -select Id_Movimiento, 28, nz(Costefijo) -from Movimientos m -join Compres c on Id_Entrada = @e and c.Id_Article = m.Id_Article -where Id_Ticket = @t -on DUPLICATE KEY UPDATE Valor = nz(Costefijo) ; - -insert into Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) -select Id_Movimiento, 29, Preu - nz(Costefijo) -from Movimientos m -join Compres c on Id_Entrada = @e and c.Id_Article = m.Id_Article -where Id_Ticket = @t -on DUPLICATE KEY UPDATE Valor = Preu - nz(Costefijo) ; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_componentes` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentes`(IN idTICKET BIGINT) -BEGIN - -SET @a:=0; - -SELECT IF(@a = Id_Movimiento, NULL, Concepte) as Concepte - ,IF(@a = Id_Movimiento, NULL, Cantidad) as Cantidad - ,IF(@a = Id_Movimiento, NULL, Id_Article) as Id_Article - , @a:= Id_Movimiento as IdM - , Id_Article as IdA - , Componente - , Valor - , Importe - , base - , margen -FROM -( -SELECT m.Id_Movimiento - , m.Concepte - , tc.Componente - , m.Cantidad - , mc.Valor - , round(m.Cantidad * mc.Valor,3) as Importe - , Id_Article - , base - , margen -FROM vn2008.Movimientos m -JOIN vn2008.Movimientos_componentes mc using(Id_Movimiento) -INNER JOIN bi.tarifa_componentes tc ON mc.Id_Componente = tc.Id_Componente -INNER JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) -WHERE m.Id_Ticket = idTICKET -ORDER BY Id_Movimiento -) sub; - - - - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Ticket_from_Entry` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Ticket_from_Entry`(IN IdEntrada INT(11), IN IdCliente INT(6), IN IdEmpresa INT(4), IN buying_quote DOUBLE, IN Ratio DOUBLE) -BEGIN - - DECLARE idTICKET INT(11); - - INSERT INTO Tickets(Id_Cliente, warehouse_id, Fecha, Alias, Id_Agencia, Id_Consigna, Id_Trabajador, empresa_id, Etiquetasemitidas, Localizacion) - SELECT IdCliente, 13, shipment, Consignatario, TR.agency_id, Id_Consigna, 20, IdEmpresa, TRUE, IdEntrada - FROM Entradas E - JOIN travel TR ON TR.id = E.travel_id - JOIN (SELECT Consignatario, Id_Consigna FROM Consignatarios WHERE Id_Cliente = IdCliente AND Predeterminada LIMIT 1) Consigna - WHERE Id_Entrada = IdEntrada; - -- JOIN Agencias AG ON AG.Id_Agencia = TR.agency_id - - SELECT LAST_INSERT_ID() INTO idTICKET; - - INSERT INTO Movimientos(Id_Ticket, Id_Article, Concepte, Cantidad, Preu, PrecioFijado) - SELECT idTICKET, Id_Article, Article, round(Cantidad * IF(Cantidad > round(1+ (1/buying_quote),0),buying_quote,1), 0), ROUND(Costefijo * Ratio,2), TRUE - FROM Compres c - JOIN Articles a using(Id_Article) - JOIN Tipos t on t.tipo_id = a.tipo_id - JOIN reinos r on r.id = t.reino_id - WHERE Id_Entrada = idEntrada - AND r.display <> 0 - AND Cantidad * buying_quote > 1; - - SELECT idTICKET; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Ticket_from_Entry_cursor` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Ticket_from_Entry_cursor`(IN IdEmpresa INt(4), IN IdCliente INT(5), IN buying_quote DOUBLE, IN Ratio DOUBLE) -BEGIN - -DECLARE done BIT DEFAULT 0; -DECLARE IdEntrada INT(10); - --- Declaro el cursor para las entradas -DECLARE cursor_entradas CURSOR FOR -SELECT Id_Entrada -FROM Entradas E -JOIN travel TR ON TR.id = E.travel_id -WHERE shipment BETWEEN '2013-04-01' AND '2013-04-30' -AND warehouse_id = 17 -and warehouse_id_out = 1; - - - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - -OPEN cursor_entradas; - -REPEAT - - FETCH cursor_entradas INTO IdEntrada; - - CALL Ticket_from_Entry(IdEntrada, IdCliente, IdEmpresa, buying_quote, Ratio); - - -UNTIL done END REPEAT; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_iva` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_iva`(vBillingDate DATE) - READS SQL DATA -BEGIN -/** - * Calcula la base imponible, el IVA y el recargo de equivalencia para - * un conjunto de tickets. - * - * @deprecated Use procedure vn.ticketGetTax() instead - * - * @table ticket_tmp(ticket_id) Tabla con el listado de tickets - * @param billing_date Fecha de facturación - * @treturn ticket_iva - */ - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT ticket_id ticketFk FROM ticket_tmp; - - CALL vn.ticketGetTax (vBillingDate); - - CREATE TEMPORARY TABLE ticket_iva - (INDEX (ticket_id)) - ENGINE = MEMORY - SELECT ticketFk ticket_id, type tipo, taxBase bi, tax iva, equalizationTax re - FROM tmp.ticketTax; - - DROP TEMPORARY TABLE - tmp.ticketTax, - 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 DROP PROCEDURE IF EXISTS `ticket_locatorbetaKk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_locatorbetaKk`(IN date_ DATETIME,IN wh_ INT, IN days TINYINT) -BEGIN - DECLARE DATEFEC DATE DEFAULT CURDATE(); - DECLARE v_date_start DATETIME DEFAULT TIMESTAMPADD(MONTH, -2, CURDATE()); - DECLARE v_date_end DATETIME DEFAULT TIMESTAMP(DATEFEC,'23:59:59'); - DECLARE v_date_future DATETIME DEFAULT TIMESTAMPADD(DAY,days,v_date_end); - - DROP TEMPORARY TABLE IF EXISTS `Locator`; - --- usar ticket_total crear ticket_tmp(ticket_id) - DROP TEMPORARY TABLE IF EXISTS ticket_tmp; - CREATE TEMPORARY TABLE `ticket_tmp` - ENGINE = MEMORY - SELECT Id_Ticket ticket_id FROM Tickets t - WHERE t.Factura IS NULL - AND t.Fecha BETWEEN v_date_start AND v_date_future; - - CALL ticket_total(); - /* - DROP TEMPORARY TABLE IF EXISTS ticket_total2; - CREATE TEMPORARY TABLE `ticket_total2` - ENGINE = MEMORY - SELECT t.* FROM ticket_total t - LEFT JOIN Tickets t1 ON t1.Id_Ticket = t.ticket_id - LEFT JOIN Tickets_state ts ON ts.Id_Ticket = t1.Id_Ticket - LEFT JOIN vncontrol.inter i ON ts.inter_id = i.inter_id - LEFT JOIN state s ON s.id = i.state_id - LEFT JOIN expeditions e ON e.ticket_id = t.ticket_id - LEFT JOIN Agencias a ON a.Id_Agencia = t1.Id_Agencia - LEFT JOIN agency ag ON ag.agency_id = a.agency_id - LEFT JOIN agency_warehouse aw ON aw.agency_id = a.agency_id AND aw.warehouse_id = wh_ - -- para pte recogida - LEFT JOIN warehouse w_out on w_out.id = t1.warehouse_id - LEFT JOIN warehouse w ON w.id = wh_ - LEFT JOIN warehouse_pickup wp on wp.agency_id = t1.Id_Agencia and wp.warehouse_id = wh_ - - WHERE t1.Fecha BETWEEN TIMESTAMPADD(DAY,-5,DATE(date_)) AND TIMESTAMPADD(DAY,days,DATE(date_)) - AND IFNULL(aw.Vista,a.Vista) > 0 - AND ((t1.Anotadoencaja = FALSE - AND t1.Etiquetasemitidas = FALSE - AND e.ticket_id IS NULL - AND t1.warehouse_id = wh_ - AND IFNULL(s.order,0) < 2) - OR (ts.state_name = 'Pte Recogida' - AND wp.warehouse_id IS NOT NULL)); - */ - SELECT t.* FROM ticket_total t - LEFT JOIN Tickets t1 ON t1.Id_Ticket = t.ticket_id - LEFT JOIN Tickets_state ts ON ts.Id_Ticket = t1.Id_Ticket - LEFT JOIN vncontrol.inter i ON ts.inter_id = i.inter_id - LEFT JOIN state s ON s.id = i.state_id - LEFT JOIN expeditions e ON e.ticket_id = t.ticket_id - LEFT JOIN Agencias a ON a.Id_Agencia = t1.Id_Agencia - LEFT JOIN agency ag ON ag.agency_id = a.agency_id - LEFT JOIN agency_warehouse aw ON aw.agency_id = a.agency_id AND aw.warehouse_id = wh_ - -- para pte recogida - LEFT JOIN warehouse w_out on w_out.id = t1.warehouse_id - LEFT JOIN warehouse w ON w.id = wh_ - LEFT JOIN warehouse_pickup wp on wp.agency_id = t1.Id_Agencia and wp.warehouse_id = wh_ - - WHERE t1.Fecha BETWEEN TIMESTAMPADD(DAY,-5,DATE(date_)) AND TIMESTAMPADD(DAY,days,DATE(date_)) - AND IFNULL(aw.Vista,a.Vista) > 0 - AND ((t1.Anotadoencaja = FALSE - AND t1.Etiquetasemitidas = FALSE - AND e.ticket_id IS NULL)); - /* AND t1.warehouse_id = wh_ - AND IFNULL(s.order,0) < 2) - OR (ts.state_name = 'Pte Recogida' - AND wp.warehouse_id IS NOT NULL))*/ - /* - DROP TEMPORARY TABLE IF EXISTS tmp.risk; - CREATE TEMPORARY TABLE tmp.risk - SELECT Id_Cliente, SUM(amount) risk - FROM Clientes c - JOIN ( - SELECT customer_id, SUM(amount) amount - FROM bi.customer_risk - GROUP BY customer_id - UNION ALL - SELECT Id_Cliente, SUM(Entregado) - FROM Recibos - WHERE Fechacobro > v_date_end - GROUP BY Id_Cliente - UNION ALL - SELECT t.Id_Cliente, SUM(total) - FROM ticket_total tt - JOIN Tickets t ON tt.ticket_id = t.Id_Ticket - WHERE t.Fecha <= v_date_end - GROUP BY t.Id_Cliente - UNION ALL - SELECT t.clientFk, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)) - FROM hedera.tpvTransaction t - WHERE t.receiptFk IS NULL - AND t.status = 'ok' - GROUP BY t.clientFk - ) t ON c.Id_Cliente = t.customer_id - WHERE c.activo != FALSE - GROUP BY c.Id_Cliente; - - CREATE TEMPORARY TABLE `Locator` - ENGINE = MEMORY - SELECT Congelado, Credito, risk Riesgo, Greuge, T.*,IFNULL(state_name,'libre') AS Estado, - Codigotrabajador, DATE(T.Fecha) AS Fecha_Simple, Averiguar_ComercialCliente_IdTicket(T.Id_Ticket) AS Comercial,C.calidad,UCASE(LEFT(w_out.`name`,5)) w_out - FROM Clientes C - INNER JOIN - ( - SELECT - t.Id_Ticket, t.Id_Cliente, t.warehouse_id, t.Fecha, t.Alias, - NULL Notas, t.Factura, t.factura_id, t.Anotadoencaja, t.Id_Consigna, t.Id_Trabajador, - t.Observaciones, t.Firmado, t.Etiquetasemitidas, t.PedidoImpreso, t.Bultos, t.Localizacion, - t.Hora, t.odbc_date, t.blocked, t.Solucion, t.Id_Ruta, t.Prioridad, t.priority, - t.empresa_id, t.Id_Agencia, - CS.Consignatario, IFNULL(aw.Vista,a.Vista) Vista,a.Agencia, DATEFEC AS Hora_MAX , - SUM(IF(Movimientos.OK = 0, 1, 0)) AS `lines`, - tt.total AS Importe, - IF(reino_id IN (5, 1), 0,tt.total) AS Plantas, - 0 AS inacabable, - CS.CODPOSTAL, CS.POBLACION, p.name PROVINCIA, a.Vista VistaTicket,p.zone - - FROM Tickets t - JOIN ticket_total2 tt ON tt.ticket_id = t.Id_Ticket - INNER JOIN Consignatarios CS USING(Id_Consigna) - LEFT JOIN province p USING(province_id) - LEFT JOIN Movimientos USING(Id_Ticket) - LEFT JOIN Articles on Movimientos.Id_Article = Articles.Id_Article - LEFT JOIN Tipos using(tipo_id) - LEFT JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN agency ag ON ag.agency_id = a.agency_id - LEFT JOIN agency_warehouse aw ON aw.agency_id = a.agency_id AND aw.warehouse_id = wh_ - - GROUP BY t.Id_Ticket - ) T USING(Id_Cliente) - LEFT JOIN Tickets_state ts ON ts.Id_Ticket = T.Id_Ticket - LEFT JOIN Trabajadores Tb ON Tb.Id_Trabajador = T.Id_Trabajador - LEFT JOIN tmp.risk as Peligros USING(Id_Cliente) - JOIN warehouse w_out on w_out.id = T.warehouse_id - LEFT JOIN - ( - SELECT Id_Cliente, SUM(Importe) AS Greuge FROM Greuges - GROUP BY Id_Cliente - ) AS Agravios USING(Id_Cliente); - - - ALTER TABLE `Locator` ADD PRIMARY KEY(Id_Ticket); - - UPDATE `Locator` JOIN - ( - SELECT d.Id_Ticket from Tickets_dits d - JOIN Tickets t using(Id_Ticket) - LEFT JOIN Agencias a using(Id_Agencia) - LEFT JOIN expeditions e on e.ticket_id = d.Id_Ticket - WHERE Fecha BETWEEN CURDATE() AND TIMESTAMP(curdate(),'23:59:59') - AND idaccion_dits = 18 AND ticket_id is null - AND t.warehouse_id = 1 - AND NOT Etiquetasemitidas - AND d.ODBC_DATE < TIMESTAMPADD(HOUR,-2, now()) - AND Vista in (1,2)) sub using(Id_Ticket) - SET Observaciones = CONCAT('F5 PERDIDO ',IFNULL(Observaciones,'')); - - - -- ENTRADAS - INSERT INTO `Locator`(Fecha_Simple, Id_Ticket, Agencia, Id_Cliente, Alias, PedidoImpreso, CodigoTrabajador, Fecha, Estado, Consignatario, Vista, PROVINCIA,Riesgo) - SELECT DISTINCT v_compres.shipment AS Fecha_Simple, v_compres.Id_Entrada AS Id_Ticket, warehouse.name, v_compres.Id_Proveedor, - v_compres.ref AS Alias, v_compres.Pedida AS PedidoImpreso, v_compres.Id_Trabajador AS CodigoTrabajador, v_compres.shipment AS Fecha, 0 AS problem, v_compres.ref AS Consignatario, 1, 'TRASLADO',0 - FROM v_compres - INNER JOIN warehouse ON v_compres.warehouse_id = warehouse.id - WHERE warehouse_id_out = wh_ AND v_compres.Confirmada = False - AND v_compres.shipment >= date_; - - - -*/ - DROP TEMPORARY TABLE IF EXISTS ticket_tmp; - DROP TEMPORARY TABLE IF EXISTS ticket_total; - DROP TEMPORARY TABLE IF EXISTS ticket_total2; - DROP TEMPORARY TABLE IF EXISTS tmp.risk; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_locatorkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_locatorkk`(date_ DATETIME, IN wh_ INT, IN days TINYINT) -BEGIN - DECLARE DATEFEC DATE DEFAULT CURDATE(); - DECLARE v_date_start DATETIME DEFAULT TIMESTAMPADD(MONTH, -2, CURDATE()); - DECLARE v_date_end DATETIME DEFAULT TIMESTAMP(DATEFEC,'23:59:59'); - DECLARE v_date_future DATETIME DEFAULT TIMESTAMPADD(DAY,days,v_date_end); - - DROP TEMPORARY TABLE IF EXISTS `Locator`; - --- usar ticket_total crear ticket_tmp(ticket_id) - DROP TEMPORARY TABLE IF EXISTS ticket_tmp; - CREATE TEMPORARY TABLE `ticket_tmp` - ENGINE = MEMORY - SELECT Id_Ticket ticket_id FROM Tickets t - WHERE t.Factura IS NULL - AND t.Fecha BETWEEN v_date_start AND v_date_future; - - CALL ticket_total(); - - DROP TEMPORARY TABLE IF EXISTS ticket_total2; - CREATE TEMPORARY TABLE `ticket_total2` - ENGINE = MEMORY - SELECT t.*,s.`order` state_order - FROM ticket_total t - LEFT JOIN Tickets t1 ON t1.Id_Ticket = t.ticket_id - LEFT JOIN Tickets_state ts ON ts.Id_Ticket = t1.Id_Ticket - LEFT JOIN vncontrol.inter i ON ts.inter_id = i.inter_id - LEFT JOIN state s ON s.id = i.state_id - LEFT JOIN expeditions e ON e.ticket_id = t.ticket_id - LEFT JOIN Agencias a ON a.Id_Agencia = t1.Id_Agencia - LEFT JOIN agency ag ON ag.agency_id = a.agency_id - LEFT JOIN agency_warehouse aw ON aw.agency_id = a.agency_id AND aw.warehouse_id = wh_ - -- para pte recogida - LEFT JOIN warehouse w_out on w_out.id = t1.warehouse_id - LEFT JOIN warehouse w ON w.id = wh_ - LEFT JOIN warehouse_pickup wp on wp.agency_id = t1.Id_Agencia and wp.warehouse_id = wh_ - - WHERE /*t1.Fecha BETWEEN TIMESTAMPADD(DAY,-5,DATE(date_)) AND TIMESTAMPADD(DAY,days,DATE(date_)) - AND */IFNULL(aw.Vista,a.Vista) > 0 - AND ((t1.Anotadoencaja = FALSE - AND t1.Etiquetasemitidas = FALSE - AND e.ticket_id IS NULL - AND t1.warehouse_id = wh_ - AND IFNULL(s.alert_level,0) <= 3 - ) - OR (ts.state_name = 'Pte Recogida' - AND wp.warehouse_id IS NOT NULL)); - - DROP TEMPORARY TABLE IF EXISTS tmp.risk; - CREATE TEMPORARY TABLE tmp.risk - SELECT Id_Cliente, SUM(amount) risk - FROM Clientes c - JOIN ( - SELECT customer_id, SUM(amount) amount - FROM bi.customer_risk - GROUP BY customer_id - UNION ALL - SELECT Id_Cliente, SUM(Entregado) - FROM Recibos - WHERE Fechacobro > v_date_end - GROUP BY Id_Cliente - UNION ALL - SELECT t.Id_Cliente, SUM(total) - FROM ticket_total tt - JOIN Tickets t ON tt.ticket_id = t.Id_Ticket - WHERE t.Fecha <= v_date_end - GROUP BY t.Id_Cliente - UNION ALL - SELECT t.clientFk, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)) - FROM hedera.tpvTransaction t - WHERE t.receiptFk IS NULL - AND t.status = 'ok' - GROUP BY t.clientFk - ) t ON c.Id_Cliente = t.customer_id - WHERE c.activo != FALSE - GROUP BY c.Id_Cliente; - - CREATE TEMPORARY TABLE `Locator` - ENGINE = MEMORY - SELECT Congelado, Credito, risk Riesgo, Greuge, T.*,IFNULL(state_name,'libre') AS Estado, - Codigotrabajador, DATE(T.Fecha) AS Fecha_Simple, Averiguar_ComercialCliente_IdTicket(T.Id_Ticket) AS Comercial,C.calidad,UCASE(LEFT(w_out.`name`,5)) w_out - FROM Clientes C - INNER JOIN - ( - SELECT - t.Id_Ticket, t.Id_Cliente, t.warehouse_id, t.Fecha, t.Alias, - NULL Notas, t.Factura, t.factura_id, t.Anotadoencaja, t.Id_Consigna, t.Id_Trabajador, - t.Observaciones, t.Firmado, t.Etiquetasemitidas, t.PedidoImpreso, t.Bultos, t.Localizacion, - t.Hora, t.odbc_date, t.blocked, t.Solucion, t.Id_Ruta, t.Prioridad, t.priority, - t.empresa_id, t.Id_Agencia, - CS.Consignatario, IFNULL(aw.Vista,a.Vista) Vista,a.Agencia, DATEFEC AS Hora_MAX , - SUM(IF(Movimientos.OK = 0, 1, 0)) AS `lines`, - tt.total AS Importe, - IF(reino_id IN (5, 1), 0,tt.total) AS Plantas, - 0 AS inacabable,state_order, - CS.CODPOSTAL, CS.POBLACION, p.name PROVINCIA, a.Vista VistaTicket,p.zone - - FROM Tickets t - JOIN ticket_total2 tt ON tt.ticket_id = t.Id_Ticket - INNER JOIN Consignatarios CS USING(Id_Consigna) - LEFT JOIN province p USING(province_id) - LEFT JOIN Movimientos USING(Id_Ticket) - LEFT JOIN Articles on Movimientos.Id_Article = Articles.Id_Article - LEFT JOIN Tipos using(tipo_id) - LEFT JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN agency ag ON ag.agency_id = a.agency_id - LEFT JOIN agency_warehouse aw ON aw.agency_id = a.agency_id AND aw.warehouse_id = wh_ - - GROUP BY t.Id_Ticket - ) T USING(Id_Cliente) - LEFT JOIN Tickets_state ts ON ts.Id_Ticket = T.Id_Ticket - LEFT JOIN Trabajadores Tb ON Tb.Id_Trabajador = T.Id_Trabajador - LEFT JOIN tmp.risk as Peligros USING(Id_Cliente) - JOIN warehouse w_out on w_out.id = T.warehouse_id - LEFT JOIN - ( - SELECT Id_Cliente, SUM(Importe) AS Greuge FROM Greuges - GROUP BY Id_Cliente - ) AS Agravios USING(Id_Cliente); - - - ALTER TABLE `Locator` ADD PRIMARY KEY(Id_Ticket); - - UPDATE `Locator` JOIN - ( - SELECT d.Id_Ticket from Tickets_dits d - JOIN Tickets t using(Id_Ticket) - LEFT JOIN Agencias a using(Id_Agencia) - LEFT JOIN expeditions e on e.ticket_id = d.Id_Ticket - WHERE Fecha BETWEEN CURDATE() AND TIMESTAMP(curdate(),'23:59:59') - AND idaccion_dits = 18 AND ticket_id is null - AND t.warehouse_id = 1 - AND NOT Etiquetasemitidas - AND d.ODBC_DATE < TIMESTAMPADD(HOUR,-2, now()) - AND Vista in (1,2)) sub using(Id_Ticket) - SET Observaciones = CONCAT('F5 PERDIDO ',IFNULL(Observaciones,'')); - - - -- CODIGO 100 - UPDATE `Locator` - JOIN Movimientos using(Id_Ticket) - SET Observaciones = 'CODIGO 100' - WHERE Id_Article = 100; - - - -- ENTRADAS - INSERT INTO `Locator`(Fecha_Simple, Id_Ticket, Agencia, Id_Cliente, Alias, PedidoImpreso, CodigoTrabajador, Fecha, Estado, Consignatario, Vista, PROVINCIA,Riesgo) - SELECT DISTINCT v_compres.shipment AS Fecha_Simple, v_compres.Id_Entrada AS Id_Ticket, warehouse.name, v_compres.Id_Proveedor, - v_compres.ref AS Alias, v_compres.Pedida AS PedidoImpreso, v_compres.Id_Trabajador AS CodigoTrabajador, v_compres.shipment AS Fecha, 0 AS problem, v_compres.ref AS Consignatario, 1, 'TRASLADO',0 - FROM v_compres - INNER JOIN warehouse ON v_compres.warehouse_id = warehouse.id - WHERE warehouse_id_out = wh_ AND v_compres.Confirmada = False - AND v_compres.shipment >= date_; - - - - - DROP TEMPORARY TABLE IF EXISTS ticket_tmp; - DROP TEMPORARY TABLE IF EXISTS ticket_total; - DROP TEMPORARY TABLE IF EXISTS ticket_total2; - DROP TEMPORARY TABLE IF EXISTS tmp.risk; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_locator_experimentalKk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_locator_experimentalKk`(IN date_ DATETIME,IN wh_ INT, IN days TINYINT) -BEGIN - DECLARE DATEFEC DATE DEFAULT CURDATE(); - DECLARE v_date_start DATETIME DEFAULT TIMESTAMPADD(MONTH, -2, CURDATE()); - DECLARE v_date_end DATETIME DEFAULT TIMESTAMP(DATEFEC,'23:59:59'); - DECLARE v_date_future DATETIME DEFAULT TIMESTAMPADD(DAY,days,v_date_end); - DECLARE timeSTART DATETIME DEFAULT NOW(); - - SELECT timeSTART, 'ARRANCA'; - - DROP TEMPORARY TABLE IF EXISTS `Locator`; -/* --- usar ticket_total crear ticket_tmp(ticket_id) - DROP TEMPORARY TABLE IF EXISTS ticket_tmp; - CREATE TEMPORARY TABLE `ticket_tmp` - (INDEX idx USING HASH (ticket_id)) - ENGINE = MEMORY - SELECT Id_Ticket ticket_id FROM Tickets t - WHERE t.Factura IS NULL - AND t.Fecha BETWEEN v_date_start AND v_date_future; - - CALL ticket_total(); - */ - DROP TEMPORARY TABLE IF EXISTS ticket_total; - - CREATE TEMPORARY TABLE ticket_total - (INDEX idx USING HASH (ticket_id)) - ENGINE = MEMORY - SELECT m.Id_Ticket as ticket_id, red(SUM(Cantidad * Preu * (100 - Descuento)/100)) AS total - FROM Movimientos m - JOIN Tickets t using(Id_Ticket) - WHERE t.Factura IS NULL - AND t.Fecha BETWEEN v_date_start AND v_date_future - GROUP BY ticket_id; - - - - SELECT TIMEDIFF(NOW(), timeSTART), 'TICKET_TOTAL'; - - DROP TEMPORARY TABLE IF EXISTS ticket_total2; - CREATE TEMPORARY TABLE `ticket_total2` - ENGINE = MEMORY - SELECT t.* FROM ticket_total t - LEFT JOIN Tickets t1 ON t1.Id_Ticket = t.ticket_id - LEFT JOIN expeditions e ON e.ticket_id = t.ticket_id - LEFT JOIN Agencias a ON a.Id_Agencia = t1.Id_Agencia - LEFT JOIN agency ag ON ag.agency_id = a.agency_id - LEFT JOIN agency_warehouse aw ON aw.agency_id = a.agency_id AND aw.warehouse_id = wh_ - WHERE t1.Fecha BETWEEN TIMESTAMPADD(DAY,-5,DATE(date_)) AND TIMESTAMPADD(DAY,days,DATE(date_)) - AND t1.Anotadoencaja = FALSE - AND t1.Etiquetasemitidas = FALSE - AND e.ticket_id IS NULL - AND IFNULL(aw.Vista,a.Vista) > 0 - AND t1.warehouse_id = wh_; - - SELECT TIMEDIFF(NOW(), timeSTART), 'TICKET_TOTAL2'; - - DROP TEMPORARY TABLE IF EXISTS tmp.risk; - CREATE TEMPORARY TABLE tmp.risk - SELECT Id_Cliente, SUM(amount) risk - FROM Clientes c - JOIN ( - SELECT customer_id, SUM(amount) amount - FROM bi.customer_risk - GROUP BY customer_id - UNION ALL - SELECT Id_Cliente, SUM(Entregado) - FROM Recibos - WHERE Fechacobro > v_date_end - GROUP BY Id_Cliente - UNION ALL - SELECT t.Id_Cliente, SUM(total) - FROM ticket_total tt - JOIN Tickets t ON tt.ticket_id = t.Id_Ticket - WHERE t.Fecha <= v_date_end - GROUP BY t.Id_Cliente - UNION ALL - SELECT t.clientFk, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)) - FROM hedera.tpvTransaction t - WHERE t.receiptFk IS NULL - AND t.status = 'ok' - GROUP BY t.clientFk - ) t ON c.Id_Cliente = t.customer_id - WHERE c.activo != FALSE - GROUP BY c.Id_Cliente; - - SELECT TIMEDIFF(NOW(), timeSTART), 'RISK'; - - - CREATE TEMPORARY TABLE `Locator` - ENGINE = MEMORY - SELECT Congelado, Credito, risk Riesgo, Greuge, T.*,ticket_state(T.factura_id, T.PedidoImpreso, T.Etiquetasemitidas, T.Blocked) AS Estado, - Codigotrabajador, DATE(T.Fecha) AS Fecha_Simple, Averiguar_ComercialCliente_IdTicket(T.Id_Ticket) AS Comercial,C.calidad - FROM Clientes C - INNER JOIN - ( - SELECT - t.Id_Ticket, t.Id_Cliente, t.warehouse_id, t.Fecha, t.Alias, - NULL Notas, t.Factura, t.factura_id, t.Anotadoencaja, t.Id_Consigna, t.Id_Trabajador, - t.Observaciones, t.Firmado, t.Etiquetasemitidas, t.PedidoImpreso, t.Bultos, t.Localizacion, - t.Hora, t.odbc_date, t.blocked, t.Solucion, t.Id_Ruta, t.Prioridad, t.priority, - t.empresa_id, t.Id_Agencia, - CS.Consignatario, IFNULL(aw.Vista,a.Vista) Vista,a.Agencia, DATEFEC AS Hora_MAX , - SUM(IF(Movimientos.OK = 0, 1, 0)) AS `lines`, - tt.total AS Importe, - IF(reino_id IN (5, 1), 0,tt.total) AS Plantas, - 0 AS inacabable, - CS.CODPOSTAL, CS.POBLACION, p.name PROVINCIA, a.Vista VistaTicket,p.zone - - FROM Tickets t - JOIN ticket_total2 tt ON tt.ticket_id = t.Id_Ticket - INNER JOIN Consignatarios CS USING(Id_Consigna) - LEFT JOIN province p USING(province_id) - LEFT JOIN Movimientos USING(Id_Ticket) - LEFT JOIN Articles on Movimientos.Id_Article = Articles.Id_Article - LEFT JOIN Tipos using(tipo_id) - LEFT JOIN Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN agency ag ON ag.agency_id = a.agency_id - LEFT JOIN agency_warehouse aw ON aw.agency_id = a.agency_id AND aw.warehouse_id = wh_ - GROUP BY t.Id_Ticket - ) T USING(Id_Cliente) - LEFT JOIN Trabajadores Tb ON Tb.Id_Trabajador = T.Id_Trabajador - LEFT JOIN tmp.risk as Peligros USING(Id_Cliente) - LEFT JOIN - ( - SELECT Id_Cliente, SUM(Importe) AS Greuge FROM Greuges - GROUP BY Id_Cliente - ) AS Agravios USING(Id_Cliente); - - SELECT TIMEDIFF(NOW(), timeSTART), 'LOCATOR'; -ALTER TABLE `Locator` ADD PRIMARY KEY(Id_Ticket); - - SELECT TIMEDIFF(NOW(), timeSTART), 'LOCATOR INDEX'; - -UPDATE `Locator` JOIN -( -SELECT d.Id_Ticket from Tickets_dits d -JOIN Tickets t using(Id_Ticket) -LEFT JOIN Agencias a using(Id_Agencia) -LEFT JOIN expeditions e on e.ticket_id = d.Id_Ticket -WHERE Fecha BETWEEN CURDATE() AND TIMESTAMP(curdate(),'23:59:59') -AND idaccion_dits = 18 AND ticket_id is null -AND t.warehouse_id = 1 -AND NOT Etiquetasemitidas -AND d.ODBC_DATE < TIMESTAMPADD(HOUR,-2, now()) -AND Vista in (1,2)) sub using(Id_Ticket) -SET Observaciones = CONCAT('F5 PERDIDO ',IFNULL(Observaciones,'')); - - SELECT TIMEDIFF(NOW(), timeSTART), 'UPDATE'; - --- ENTRADAS -INSERT INTO `Locator`(Fecha_Simple, Id_Ticket, Agencia, Id_Cliente, Alias, PedidoImpreso, CodigoTrabajador, Fecha, Estado, Consignatario, Vista, PROVINCIA,Riesgo) -SELECT DISTINCT v_compres.shipment AS Fecha_Simple, v_compres.Id_Entrada AS Id_Ticket, warehouse.name, v_compres.Id_Proveedor, -v_compres.ref AS Alias, v_compres.Pedida AS PedidoImpreso, v_compres.Id_Trabajador AS CodigoTrabajador, v_compres.shipment AS Fecha, 0 AS problem, v_compres.ref AS Consignatario, 1, 'TRASLADO',0 -FROM v_compres -INNER JOIN warehouse ON v_compres.warehouse_id = warehouse.id -WHERE warehouse_id_out = wh_ AND v_compres.Confirmada = False -AND v_compres.shipment >= date_; - - SELECT TIMEDIFF(NOW(), timeSTART), 'ENTRADAS'; --- TICKET PTE RECOGIDA -INSERT INTO `Locator`(Fecha_Simple - , Id_Ticket - , Agencia - , Id_Cliente - , Alias - , PedidoImpreso - , CodigoTrabajador - , Fecha - , Estado - , Consignatario - , Vista - , PROVINCIA - , Riesgo - , Comercial - ,calidad - ,Bultos) - -SELECT date(t.Fecha) - , t.Id_Ticket - , a.Agencia - , t.Id_Cliente - , t.Alias - , t.PedidoImpreso - , UCASE(LEFT(w_out.name,5)) as CodigoTrabajador -- es el almacen de origen - , t.Fecha - , 0 as Estado - , t.Alias - ,3 - , w.name - , NULL - ,Averiguar_ComercialCliente_IdTicket(t.Id_Ticket) AS Comercial - ,c.calidad - ,t.Bultos -FROM Tickets t -JOIN Clientes c using(Id_Cliente) -JOIN warehouse w_out on w_out.id = t.warehouse_id -JOIN warehouse w ON w.id = wh_ -JOIN Agencias a using(Id_Agencia) -JOIN warehouse_pickup wp on wp.agency_id = t.Id_Agencia and wp.warehouse_id = wh_ -JOIN - (select Id_Ticket, state_id from - ( - select Id_Ticket, odbc_date, state_id - from vncontrol.inter - where odbc_date >= timestampadd(day,-3,curdate()) - order by odbc_date desc, state_id desc - ) sub - group by Id_Ticket - having state_id = 15 -- Pendiente de entrega - ) sub2 using(Id_Ticket); - - SELECT TIMEDIFF(NOW(), timeSTART), 'PTE RECOGIDA'; - -DROP TEMPORARY TABLE IF EXISTS ticket_tmp; -DROP TEMPORARY TABLE IF EXISTS ticket_total; -DROP TEMPORARY TABLE IF EXISTS ticket_total2; -DROP TEMPORARY TABLE IF EXISTS tmp.risk; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_new` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_new`( - IN idC INT - , IN newFEC DATE - , IN idWH INT - , IN idUSER INT - , IN idEMP INT - , IN idCON INT - , IN intTIPO INT - , IN idRUTA INT - , IN datLANDING DATE - , OUT newTICKET INT) -BEGIN --- DEPRECATED usar ticketCreate - DECLARE boolaux TINYINT; - - SET boolaux = If(IdC = 200 Or IdC = 400 Or intTIPO = 23, True, False); - - INSERT INTO Tickets ( - Id_Cliente, - Fecha, - Id_Consigna, - Id_Trabajador, - Id_Agencia, - Alias, - Etiquetasemitidas, - Firmado, - warehouse_id, - Id_Ruta, - empresa_id, - landing) - SELECT - IdC, - newFEC, - Id_Consigna, - idUSER, - IF(intTIPO,intTIPO,Id_Agencia), - consignatario, - boolaux, - boolaux, - idWH, - IF(idRUTA,idRuta,NULL), - idEMP, - datLANDING - FROM Consignatarios c - INNER JOIN Agencias a USING(Id_Agencia) - WHERE IF(IdCON, Id_Consigna = IdCON, Predeterminada != 0) - AND Id_Cliente = idC - LIMIT 1; - - SELECT LAST_INSERT_ID() INTO newTICKET; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_new_complet` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_new_complet`( - IN idC INT - , IN newFEC DATE - , IN idWH INT - , IN idUSER INT - , IN idEMP INT - , IN idCON INT - , IN intTIPO INT - , IN idRUTA INT - , OUT newTICKET INT) -BEGIN --- DEPRECATED usar ticketCreate - DECLARE boolaux TINYINT; - - - SET boolaux = If(IdC = 200 Or IdC = 400 Or intTIPO = 23, True, False); - - INSERT INTO Tickets ( - Id_Cliente, - Fecha, - Id_Consigna, - Id_Trabajador, - Id_Agencia, - Alias, - Etiquetasemitidas, - Firmado, - warehouse_id, - Id_Ruta, - empresa_id) - SELECT - IdC, - newFEC, - Id_Consigna, - idUSER, - IF(intTIPO,intTIPO,Id_Agencia), - consignatario, - boolaux, - boolaux, - idWH, - IF(idRUTA,idRuta,NULL), - idEMP - FROM Consignatarios c - INNER JOIN Agencias a USING(Id_Agencia) - WHERE IF(IdCON, Id_Consigna = IdCON, Predeterminada != 0) - AND Id_Cliente = idC - LIMIT 1; - - SELECT LAST_INSERT_ID() INTO newTICKET; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_portes_cobrados` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_portes_cobrados`(IN idTICKET BIGINT) -BEGIN - -SELECT m.Id_Article, m.Concepte, m.Cantidad, mc.Valor, round(m.Cantidad * mc.Valor,2) as Porte -FROM vn2008.Movimientos m -JOIN vn2008.Movimientos_componentes mc using(Id_Movimiento) -INNER JOIN bi.tarifa_componentes tc ON mc.Id_Componente = tc.Id_Componente -WHERE m.Id_Ticket = idTICKET -AND tc.tarifa_componentes_series_id = 6; -- agencia - - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_portes_estimados` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_portes_estimados`(IN vTicketId BIGINT) -BEGIN - -SELECT - TICKET_FREIGHT(vTicketId) AS Porte_Volumen, - SUM(CAST(es.shipping_charge AS DECIMAL (10 , 2 ))) AS Porte_Bultos, - IFNULL(is_volumetric,0) AS is_volumetric -FROM - vn2008.v_expeditions_shipping_charge2 es -JOIN - vn2008.Tickets t on es.Id_Ticket = t.Id_Ticket -LEFT JOIN - vn2008.Rutas r on r.Id_Ruta = t.Id_Ruta -LEFT JOIN - vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia -WHERE - es.Id_Ticket = vTicketId; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_total` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_total`() -BEGIN -/** - * Calcula el total con IVA de un conjunto de tickets. - * - * @deprecated Use procedure vn.ticketGetTotal() instead - * - * @table ticket_tmp(ticket_id) Tabla con el listado de tickets - * @return table ticket_total - */ - CALL ticket_iva (NULL); - - DROP TEMPORARY TABLE IF EXISTS ticket_total; - CREATE TEMPORARY TABLE ticket_total - (INDEX (ticket_id)) - ENGINE = MEMORY - SELECT ticket_id, red(SUM(bi + iva + re)) AS total - FROM ticket_iva GROUP BY ticket_id; - - DROP TEMPORARY TABLE ticket_iva; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_volumen` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_volumen`(IN idT INT) -BEGIN - DECLARE intWh INTEGER; - DECLARE datFecha DATE; - - DROP TEMPORARY TABLE IF EXISTS ticket_volumen; - SELECT warehouse_id, Fecha INTO intWh,datFecha FROM Tickets WHERE Id_Ticket = idT; - - CREATE TEMPORARY TABLE IF NOT EXISTS ticket_volumen ENGINE MEMORY - SELECT Id_Article,Cantidad, Concepte, VolUd as m3_uni, Volumen as m3, @m3:= @m3 + ifnull(Volumen,0) as m3_total - FROM - ( - SELECT round(r.cm3 / 1000000,3) as VolUd ,M.Cantidad, round(r.cm3 * M.Cantidad / 1000000,3) as Volumen, - M.Id_Article, Concepte, @m3:= 0, @vol:=0, Id_Agencia - FROM Movimientos M - JOIN Tickets T on T.Id_Ticket = M.Id_Ticket - JOIN bi.rotacion r ON r.Id_Article = M.Id_Article AND r.warehouse_id = T.warehouse_id - WHERE M.Id_Ticket = idT - ) sub; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `top_seller` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `top_seller`() -BEGIN - - drop table if exists top_sellers_min; - create temporary table top_sellers_min ENGINE = MEMORY - select a.Id_Article , tip.reino_id as Reino, count(m.Id_Article) as contados - from Movimientos m - inner join Tickets t - on m.Id_Ticket = t.Id_Ticket - inner join Articles a - on a.Id_Article = m.Id_Article - inner join Tipos tip - on a.tipo_id = tip.tipo_id - inner join reinos r - on r.id = tip.reino_id - where t.Fecha between timestampadd(day,-7,curdate()) and curdate() - group by m.Id_Article; - - drop table if exists top_seller; - create temporary table top_seller ENGINE = MEMORY - select a.Article, tmp.Id_Article , a.Foto as foto, a.tipo_id as Id_Tipo, - tmp.Reino, r.reino as ReinoNombre, tip.Tipo as Tipo, tmp.contados - from top_sellers_min tmp - inner join Articles a - on a.Id_Article = tmp.Id_Article - inner join Tipos tip - on a.tipo_id = tip.tipo_id - inner join reinos r - on r.id = tmp.Reino - where tmp.Reino = 1 - order by contados desc - limit 5; - - insert into top_seller - select - a.Article, tmp.Id_Article , a.Foto as foto, a.tipo_id as Id_Tipo, - tmp.Reino, r.reino as ReinoNombre, tip.Tipo as Tipo, tmp.contados - from top_sellers_min tmp - inner join Articles a - on a.Id_Article = tmp.Id_Article - inner join Tipos tip - on a.tipo_id = tip.tipo_id - inner join reinos r - on r.id = tmp.Reino - where tmp.Reino = 2 - order by contados desc - limit 5; - - insert into top_seller - select - a.Article, tmp.Id_Article , a.Foto as foto, a.tipo_id as Id_Tipo, - tmp.Reino, r.reino as ReinoNombre, tip.Tipo as Tipo, tmp.contados - from top_sellers_min tmp - inner join Articles a - on a.Id_Article = tmp.Id_Article - inner join Tipos tip - on a.tipo_id = tip.tipo_id - inner join reinos r - on r.id = tmp.Reino - where tmp.Reino = 3 - order by contados desc - limit 5; - - insert into top_seller - select - a.Article, tmp.Id_Article , a.Foto as foto, a.tipo_id as Id_Tipo, - tmp.Reino, r.reino as ReinoNombre, tip.Tipo as Tipo, tmp.contados - from top_sellers_min tmp - inner join Articles a - on a.Id_Article = tmp.Id_Article - inner join Tipos tip - on a.tipo_id = tip.tipo_id - inner join reinos r - on r.id = tmp.Reino - where tmp.Reino = 4 - order by contados desc - limit 5; - - insert into top_seller - select - a.Article, tmp.Id_Article , a.Foto as foto, a.tipo_id as Id_Tipo, - tmp.Reino, r.reino as ReinoNombre, tip.Tipo as Tipo, tmp.contados - from top_sellers_min tmp - inner join Articles a - on a.Id_Article = tmp.Id_Article - inner join Tipos tip - on a.tipo_id = tip.tipo_id - inner join reinos r - on r.id = tmp.Reino - where tmp.Reino = 5 - order by contados desc - limit 5; - - insert into top_seller - select - a.Article, tmp.Id_Article , a.Foto as foto, a.tipo_id as Id_Tipo, - tmp.Reino, r.reino as ReinoNombre, tip.Tipo as Tipo, tmp.contados - from top_sellers_min tmp - inner join Articles a - on a.Id_Article = tmp.Id_Article - inner join Tipos tip - on a.tipo_id = tip.tipo_id - inner join reinos r - on r.id = tmp.Reino - where tmp.Reino = 7 - order by contados desc - limit 5; - - drop table if exists top_sellers_min; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Trabuque` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Trabuque`(IN intIDTICKET BIGINT, IN dblINCREMENTO DOUBLE ) -BEGIN - - - -#Vamos a calcular el porcentaje a incrementar las cantidades de las lineas de movimiento para inflar / desinflar la base final - -DECLARE dblBASE_INICIAL DOUBLE DEFAULT 0; -DECLARE dblBASE_FINAL DOUBLE DEFAULT 0; -DECLARE dblAUMENTO DOUBLE DEFAULT 1; - - -SELECT SUM(Cantidad * Preu * (100 - Descuento) / 100) -INTO dblBASE_INICIAL -FROM Movimientos -WHERE Id_Ticket = intIDTICKET; - -SET dblBASE_FINAL = dblBASE_INICIAL; - - -#Eliminamos lineas a 0 - -DELETE FROM Movimientos WHERE Cantidad = 0 AND Id_Ticket = intIDTICKET; - -# Vamos a ir probando incrementos paulatinos hasta que encontremos el que supera lo pedido, teniendo en cuenta el sentido del incremento - -IF dblINCREMENTO < 0 THEN - - - - WHILE (dblBASE_FINAL > dblBASE_INICIAL + dblINCREMENTO) or (dblAUMENTO < 0 ) DO - - SET dblAUMENTO = dblAUMENTO - 0.01; - - SELECT SUM(IF(@cantidad:= ROUND(dblAUMENTO * Cantidad),@cantidad,1) * Preu * (100 - Descuento) / 100) - INTO dblBASE_FINAL - FROM Movimientos - WHERE Id_Ticket = intIDTICKET; - - END WHILE; - -ELSE - - WHILE dblBASE_FINAL < dblBASE_INICIAL + dblINCREMENTO DO - - SET dblAUMENTO = dblAUMENTO + 0.01; - - SELECT SUM(IF(@cantidad:= ROUND(dblAUMENTO * Cantidad),@cantidad,1) * Preu * (100 - Descuento) / 100) - INTO dblBASE_FINAL - FROM Movimientos - WHERE Id_Ticket = intIDTICKET; - - END WHILE; - -END IF; - -UPDATE Movimientos -SET Cantidad = IF(@cantidad:= ROUND(dblAUMENTO * Cantidad),@cantidad,1) -WHERE Id_Ticket = intIDTICKET; - -SELECT tipoiva - , ROUND(SUM(Cantidad * Preu * (100 - Descuento) / 100),2) as Base - , ROUND(ROUND(SUM(Cantidad * Preu * (100 - Descuento) / 100),2) * iva / 100,2) as Cuota -FROM Movimientos M -INNER JOIN Articles A USING(Id_Article) -INNER JOIN tblIVA USING(tipoiva) -WHERE Id_Ticket = intIDTICKET -GROUP BY tipoiva; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `traslado` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `traslado`(IN i_entrada INTEGER) -BEGIN - DECLARE dateShipment DATE; - DECLARE dateLanding DATE; - DECLARE warehouseShipment INTEGER; - DECLARE warehouseLanding INTEGER; - DECLARE v_calc_available INTEGER; - DECLARE v_calc_visible INTEGER; - - SELECT shipment, landing, warehouse_id_out, warehouse_id - INTO dateShipment, dateLanding, warehouseShipment, warehouseLanding - FROM travel t JOIN Entradas e ON t.id = e.travel_id - WHERE Id_Entrada = i_entrada; - - CALL buy_tarifas_table(i_entrada); - - -- Traslado en almacen origen - - DROP TEMPORARY TABLE IF EXISTS buy_edi_temp; - - CREATE TEMPORARY TABLE buy_edi_temp - (KEY (Id_Article)) ENGINE = MEMORY - - SELECT * - FROM (SELECT c.Id_Article, c.Id_Compra - FROM Compres c INNER JOIN Entradas e USING(Id_Entrada) - INNER JOIN travel t ON t.id = e.travel_id - WHERE t.landing BETWEEN date_inv() AND dateShipment - AND c.Novincular = FALSE - AND c.Tarifa2 >= 0 - ORDER BY (warehouseShipment = t.warehouse_id) DESC, t.landing DESC) t - GROUP BY Id_Article; - - IF dateShipment >= CURDATE() THEN - - CALL availableTraslate(warehouseShipment, dateShipment,NULL); - CALL `cache`.visible_refresh(v_calc_visible,TRUE,warehouseShipment); - DROP TEMPORARY TABLE IF EXISTS tmp_item; - CREATE TEMPORARY TABLE tmp_item (UNIQUE INDEX i USING HASH (item_id)) ENGINE = MEMORY - SELECT item_id, visible,0 available FROM `cache`.visible WHERE calc_id = v_calc_visible; - INSERT INTO tmp_item(item_id, available) - SELECT a.item_id, a.available FROM availableTraslate a - ON DUPLICATE KEY UPDATE available = a.available; - ELSE - CALL item_stock(warehouseShipment, dateShipment,NULL); - END IF; - - DROP TEMPORARY TABLE IF EXISTS Traslados; - CREATE TEMPORARY TABLE Traslados ENGINE MEMORY - SELECT tp.Id_Tipo AS Tipo, - - tp.reino_id, - - ar.tipo_id, - - ar.Id_Article AS article_id, - - ar.Article, - - ar.Medida, - - ar.Categoria, - - ar.Color, - - Origen.abreviatura as Origen, - - CE.Cantidad, - - ar.Tallos, - - CAST(AIM.visible AS DECIMAL(10,0)) as vis1, - - CAST(AIM.available AS DECIMAL(10,0)) as dis1, - - 0 as vis2, - - 0 as dis2, - - IFNULL(CE.grouping,C.grouping) as grouping, - - IFNULL(CE.Packing,C.Packing) as Packing, - - IFNULL(CE.caja,C.caja) as caja, - - IFNULL(C.Productor, P2.Alias) AS Productor, - - C.Id_Cubo, - - 1 Tinta, - - CE.Id_Compra, - - CE.Etiquetas, - - C.buy_edi_id, - - tp.Id_Trabajador, - - CB.Volumen, - - CB.x, CB.y, CB.z, - - IFNULL(C.Costefijo,0) Costefijo, - - IFNULL(C.Comisionfija,0) Comisionfija, - - IFNULL(C.Portefijo,0) Portefijo, - - A.m3, - - E.comision, - - CB.Retornable, - - IFNULL(CEB.Valor,CB.Valor) Valor, - - t3, t2, tp.promo, - - C.grouping groupingOrigin, - - C.Packing PackingOrigin, - - C.Id_Compra CompraOrigin, - - CB.costeRetorno - - FROM Articles ar - LEFT JOIN tmp_item AIM ON AIM.item_id = ar.Id_Article - LEFT JOIN Tipos tp ON tp.tipo_id = ar.tipo_id - LEFT JOIN Origen ON Origen.id = ar.id_origen - LEFT JOIN buy_edi_temp lb ON lb.Id_Article = ar.Id_Article - LEFT JOIN Compres C ON C.Id_Compra = lb.Id_Compra - LEFT JOIN Cubos CB ON CB.Id_Cubo = C.Id_Cubo - LEFT JOIN Entradas E2 ON E2.Id_Entrada = C.Id_Entrada - LEFT JOIN Proveedores P2 ON P2.Id_Proveedor = E2.Id_Proveedor - LEFT JOIN Entradas E ON E.Id_Entrada = i_entrada - LEFT JOIN travel TR ON TR.id = E.travel_id - LEFT JOIN Agencias A ON A.Id_Agencia = TR.agency_id - LEFT JOIN Compres CE ON CE.Id_Article = ar.Id_Article AND CE.Id_Entrada = i_entrada - LEFT JOIN Cubos CEB ON CEB.Id_Cubo = CE.Id_Cubo - LEFT JOIN tblTARIFAS ON TRUE - WHERE tp.reino_id <> 6 AND tp.reino_id <> 8 - AND E.Redada = FALSE; - - CREATE INDEX tindex USING HASH ON Traslados (article_id); - --- Inventario en el warehouse destino - IF dateShipment >= CURDATE() THEN - - CALL cache.visible_refresh(v_calc_visible, TRUE, warehouseLanding); - CALL availableTraslate(warehouseLanding, dateLanding,warehouseShipment); - - UPDATE Traslados t - LEFT JOIN availableTraslate a ON t.article_id = a.item_id - LEFT JOIN `cache`.visible v ON v.calc_id = v_calc_visible AND t.article_id = v.item_id - SET vis2 = v.visible, dis2 = a.available; - - END IF; --- --------------------------------------------- - - SELECT t.*, - - Cantidad - MOD(Cantidad , grouping) as Subcantidad, - - MOD(Cantidad , grouping) as Soll, - - ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) / Packing,0) as cm3, - - Costefijo + Comisionfija + Portefijo AS Cost, - - @porte := ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) * m3 / 1000000 / Packing ,3) AS Porte, - - @comision := ROUND((Costefijo + Comisionfija + Portefijo) * comision / 100 ,3) AS Comision, - - ROUND(@embalaje := (costeRetorno + IF(Retornable != 0, 0, Valor)) / packing ,3) AS Embalaje, - - @coste := IFNULL((Costefijo + Comisionfija + Portefijo),0) + IFNULL(@embalaje,0) + IFNULL(@porte,0) + IFNULL(@comision,0) AS Coste, - - @t3 := ROUND(@coste / ( (100 - t3 - t.promo)/100),2) AS Tarifa3, - - ROUND(@t3 * (1 + ((t2 - t3)/100)),2) AS Tarifa2, - - 0 selected - - FROM Traslados t - WHERE vis1 <> 0 OR dis1 <> 0 OR vis2 <> 0 OR dis2 <> 0 - ORDER BY tipo_id, Article, Medida, Categoria, Origen; - - DROP TEMPORARY TABLE IF EXISTS Traslados; - DROP TEMPORARY TABLE IF EXISTS tmp_item; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `trasladoBeta` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `trasladoBeta`(IN i_entrada INTEGER) -BEGIN - DECLARE dateShipment DATE; - DECLARE dateLanding DATE; - DECLARE warehouseShipment INTEGER; - DECLARE warehouseLanding INTEGER; - DECLARE v_calc_available INTEGER; - DECLARE v_calc_visible INTEGER; - - SELECT shipment, landing, warehouse_id_out, warehouse_id - INTO dateShipment, dateLanding, warehouseShipment, warehouseLanding - FROM travel t JOIN Entradas e ON t.id = e.travel_id - WHERE Id_Entrada = i_entrada; - - CALL buy_tarifas_table(i_entrada); - - -- Traslado en almacen origen - - DROP TEMPORARY TABLE IF EXISTS buy_edi_temp; - - CREATE TEMPORARY TABLE buy_edi_temp - (KEY (Id_Article)) ENGINE = MEMORY - - SELECT * FROM (SELECT c.Id_Article, c.Id_Compra - FROM Compres c INNER JOIN Entradas e USING(Id_Entrada) - INNER JOIN travel t ON t.id = e.travel_id - WHERE t.landing BETWEEN date_inv() AND dateShipment - AND c.Novincular = FALSE - AND c.Tarifa2 >= 0 - ORDER BY (warehouseShipment = t.warehouse_id) DESC, t.landing DESC) t - GROUP BY Id_Article; - - IF dateShipment >= CURDATE() THEN - - -- CALL `cache`.available_refresh(v_calc_available, TRUE, warehouseShipment, dateShipment); - CALL availableTraslate(warehouseShipment, dateShipment,NULL); - CALL `cache`.visible_refresh(v_calc_visible,TRUE,warehouseShipment); - DROP TEMPORARY TABLE IF EXISTS tmp_item; - CREATE TEMPORARY TABLE tmp_item (UNIQUE INDEX i USING HASH (item_id)) ENGINE = MEMORY - SELECT item_id, visible,0 available FROM `cache`.visible WHERE calc_id = v_calc_visible; - INSERT INTO tmp_item(item_id, available) - SELECT a.item_id, a.available FROM availableTraslate a - ON DUPLICATE KEY UPDATE available = a.available; - ELSE - CALL item_stock(warehouseShipment, dateShipment,NULL); - END IF; - - DROP TEMPORARY TABLE IF EXISTS Traslados; - CREATE TEMPORARY TABLE Traslados ENGINE MEMORY - SELECT TP.Id_Tipo AS Tipo, - - TP.reino_id, - - ar.tipo_id, - - ar.Id_Article AS article_id, - - ar.Article, - - ar.Medida, - - ar.Categoria, - - ar.Color, - - Origen.abreviatura as Origen, - - CE.Cantidad, - - ar.Tallos, - - CAST(AIM.visible AS DECIMAL(10,0)) as vis1, - - CAST(AIM.available AS DECIMAL(10,0)) as dis1, - - 0 as vis2, - - 0 as dis2, - - IFNULL(CE.grouping,C.grouping) as grouping, - - IFNULL(CE.Packing,C.Packing) as Packing, - - IFNULL(CE.caja,C.caja) as caja, - - IFNULL(C.Productor, P2.Alias) AS Productor, - - C.Id_Cubo, - - 1 Tinta, - - CE.Id_Compra, - - CE.Etiquetas, - - C.buy_edi_id, - - TP.Id_Trabajador, - - CB.Volumen, - - CB.x, CB.y, CB.z, - - IFNULL(C.Costefijo,0) Costefijo, - - IFNULL(C.Comisionfija,0) Comisionfija, - - IFNULL(C.Portefijo,0) Portefijo, - - A.m3, - - E.comision, - - CB.Retornable, - - IFNULL(CEB.Valor,CB.Valor) Valor, - - t3, t2, TP.promo - - FROM Articles ar - LEFT JOIN tmp_item AIM ON AIM.item_id = ar.Id_Article - LEFT JOIN Tipos TP USING(tipo_id) - LEFT JOIN Origen ON Origen.id = ar.id_origen - LEFT JOIN buy_edi_temp lb ON lb.Id_Article = ar.Id_Article - LEFT JOIN Compres C ON C.Id_Compra = lb.Id_Compra - LEFT JOIN Cubos CB ON CB.Id_Cubo = C.Id_Cubo - LEFT JOIN Entradas E2 ON E2.Id_Entrada = C.Id_Entrada - LEFT JOIN Proveedores P2 ON P2.Id_Proveedor = E2.Id_Proveedor - LEFT JOIN Entradas E ON E.Id_Entrada = i_entrada - LEFT JOIN travel TR ON TR.id = E.travel_id - LEFT JOIN Agencias A ON A.Id_Agencia = TR.agency_id - LEFT JOIN Compres CE ON CE.Id_Article = ar.Id_Article AND CE.Id_Entrada = i_entrada - LEFT JOIN Cubos CEB ON CEB.Id_Cubo = CE.Id_Cubo - LEFT JOIN tblTARIFAS ON TRUE - WHERE TP.reino_id <> 6 AND TP.reino_id <> 8 - AND E.Redada = FALSE; - - - CREATE INDEX tindex USING HASH ON Traslados (article_id); - --- Inventario en el warehouse destino - IF dateShipment >= CURDATE() THEN - - CALL cache.visible_refresh(v_calc_visible, TRUE, warehouseLanding); - SELECT warehouseLanding, dateLanding,warehouseShipment; - CALL availableTraslateTesting(warehouseLanding, dateLanding,warehouseShipment); - - SELECT * FROM availableTraslate; - - UPDATE Traslados t - LEFT JOIN availableTraslate a ON t.article_id = a.item_id - LEFT JOIN `cache`.visible v ON v.calc_id = v_calc_visible AND t.article_id = v.item_id - SET vis2 = v.visible, dis2 = a.available; - - END IF; --- --------------------------------------------- - - SELECT t.*, - - Cantidad - MOD(Cantidad , grouping) as Subcantidad, - - MOD(Cantidad , grouping) as Soll, - - (IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) / Packing as cm3, - - Costefijo + Comisionfija + Portefijo AS Cost, - - @porte := ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) * m3 / 1000000 / Packing ,3) AS Porte, - - @comision := ROUND((Costefijo + Comisionfija + Portefijo) * comision / 100 ,3) AS Comision, - - @embalaje := IF(Retornable != 0, 0,ROUND(Valor / Packing,3)) AS Embalaje, - - @coste := IFNULL((Costefijo + Comisionfija + Portefijo),0) + IFNULL(@embalaje,0) + IFNULL(@porte,0) + IFNULL(@comision,0) AS Coste, - - @t3 := ROUND(@coste / ( (100 - t3 - t.promo)/100),2) AS Tarifa3, - - ROUND(@t3 * (1 + ((t2 - t3)/100)),2) AS Tarifa2, - - 0 selected - - FROM Traslados t - WHERE vis1 <> 0 OR dis1 <> 0 OR vis2 <> 0 OR dis2 <> 0 - ORDER BY tipo_id, Article, Medida, Categoria, Origen; - - DROP TEMPORARY TABLE IF EXISTS Traslados; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `trasladoKK` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `trasladoKK`(IN i_entrada INTEGER) -BEGIN - DECLARE dateShipment DATE; - DECLARE dateLanding DATE; - DECLARE warehouseShipment INTEGER; - DECLARE warehouseLanding INTEGER; - DECLARE v_calc_available INTEGER; - DECLARE v_calc_visible INTEGER; - - - SELECT shipment, landing, warehouse_id_out, warehouse_id - INTO dateShipment, dateLanding, warehouseShipment, warehouseLanding - FROM travel t JOIN Entradas e ON t.id = e.travel_id - WHERE Id_Entrada = i_entrada; - - CALL buy_tarifas_table(i_entrada); - - -- Traslado en almacen origen - - DROP TEMPORARY TABLE IF EXISTS buy_edi_temp; - - CREATE TEMPORARY TABLE buy_edi_temp - (KEY (Id_Article)) ENGINE = MEMORY - - SELECT * - FROM (SELECT c.Id_Article, c.Id_Compra - FROM Compres c INNER JOIN Entradas e USING(Id_Entrada) - INNER JOIN travel t ON t.id = e.travel_id - WHERE t.landing BETWEEN date_inv() AND dateShipment - AND c.Novincular = FALSE - AND c.Tarifa2 >= 0 - ORDER BY (warehouseShipment = t.warehouse_id) DESC, t.landing DESC) t - GROUP BY Id_Article; - - IF dateShipment >= CURDATE() THEN - - CALL availableTraslate(warehouseShipment, dateShipment,NULL); - CALL `cache`.visible_refresh(v_calc_visible,TRUE,warehouseShipment); - DROP TEMPORARY TABLE IF EXISTS tmp_item; - CREATE TEMPORARY TABLE tmp_item (UNIQUE INDEX i USING HASH (item_id)) ENGINE = MEMORY - SELECT item_id, visible,0 available FROM `cache`.visible WHERE calc_id = v_calc_visible; - INSERT INTO tmp_item(item_id, available) - SELECT a.item_id, a.available FROM availableTraslate a - ON DUPLICATE KEY UPDATE available = a.available; - ELSE - CALL item_stock(warehouseShipment, dateShipment,NULL); - END IF; - - DROP TEMPORARY TABLE IF EXISTS Traslados; - CREATE TEMPORARY TABLE Traslados ENGINE MEMORY - SELECT tp.Id_Tipo AS Tipo, - - tp.reino_id, - - ar.tipo_id, - - ar.Id_Article AS article_id, - - ar.Article, - - ar.Medida, - - ar.Categoria, - - ar.Color, - - Origen.abreviatura as Origen, - - CE.Cantidad, - - ar.Tallos, - - CAST(AIM.visible AS DECIMAL(10,0)) as vis1, - - CAST(AIM.available AS DECIMAL(10,0)) as dis1, - - 0 as vis2, - - 0 as dis2, - - IFNULL(CE.grouping,C.grouping) as grouping, - - IFNULL(CE.Packing,C.Packing) as Packing, - - IFNULL(CE.caja,C.caja) as caja, - - IFNULL(C.Productor, P2.Alias) AS Productor, - - C.Id_Cubo, - - 1 Tinta, - - CE.Id_Compra, - - CE.Etiquetas, - - C.buy_edi_id, - - tp.Id_Trabajador, - - CB.Volumen, - - CB.x, CB.y, CB.z, - - IFNULL(C.Costefijo,0) Costefijo, - - IFNULL(C.Comisionfija,0) Comisionfija, - - IFNULL(C.Portefijo,0) Portefijo, - - A.m3, - - E.comision, - - CB.Retornable, - - IFNULL(CEB.Valor,CB.Valor) Valor, - - t3, t2, tp.promo, - - C.grouping groupingOrigin, - - C.Packing PackingOrigin, - - C.Id_Compra CompraOrigin - - FROM Articles ar - LEFT JOIN tmp_item AIM ON AIM.item_id = ar.Id_Article - LEFT JOIN Tipos tp ON tp.tipo_id = ar.tipo_id - LEFT JOIN Origen ON Origen.id = ar.id_origen - LEFT JOIN buy_edi_temp lb ON lb.Id_Article = ar.Id_Article - LEFT JOIN Compres C ON C.Id_Compra = lb.Id_Compra - LEFT JOIN Cubos CB ON CB.Id_Cubo = C.Id_Cubo - LEFT JOIN Entradas E2 ON E2.Id_Entrada = C.Id_Entrada - LEFT JOIN Proveedores P2 ON P2.Id_Proveedor = E2.Id_Proveedor - LEFT JOIN Entradas E ON E.Id_Entrada = i_entrada - LEFT JOIN travel TR ON TR.id = E.travel_id - LEFT JOIN Agencias A ON A.Id_Agencia = TR.agency_id - LEFT JOIN Compres CE ON CE.Id_Article = ar.Id_Article AND CE.Id_Entrada = i_entrada - LEFT JOIN Cubos CEB ON CEB.Id_Cubo = CE.Id_Cubo - LEFT JOIN tblTARIFAS ON TRUE - WHERE tp.reino_id <> 6 AND tp.reino_id <> 8 - AND E.Redada = FALSE; - - CREATE INDEX tindex USING HASH ON Traslados (article_id); - --- Inventario en el warehouse destino - IF dateShipment >= CURDATE() THEN - - CALL cache.visible_refresh(v_calc_visible, TRUE, warehouseLanding); - CALL availableTraslate(warehouseLanding, dateLanding,warehouseShipment); - - UPDATE Traslados t - LEFT JOIN availableTraslate a ON t.article_id = a.item_id - LEFT JOIN `cache`.visible v ON v.calc_id = v_calc_visible AND t.article_id = v.item_id - SET vis2 = v.visible, dis2 = a.available; - - END IF; --- --------------------------------------------- - - SELECT t.*, - - Cantidad - MOD(Cantidad , grouping) as Subcantidad, - - MOD(Cantidad , grouping) as Soll, - - (IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) / Packing as cm3, - - Costefijo + Comisionfija + Portefijo AS Cost, - - @porte := ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) * m3 / 1000000 / Packing ,3) AS Porte, - - @comision := ROUND((Costefijo + Comisionfija + Portefijo) * comision / 100 ,3) AS Comision, - - @embalaje := IF(Retornable != 0, 0,ROUND(Valor / Packing,3)) AS Embalaje, - - @coste := IFNULL((Costefijo + Comisionfija + Portefijo),0) + IFNULL(@embalaje,0) + IFNULL(@porte,0) + IFNULL(@comision,0) AS Coste, - - @t3 := ROUND(@coste / ( (100 - t3 - t.promo)/100),2) AS Tarifa3, - - ROUND(@t3 * (1 + ((t2 - t3)/100)),2) AS Tarifa2, - - 0 selected - - FROM Traslados t - WHERE vis1 <> 0 OR dis1 <> 0 OR vis2 <> 0 OR dis2 <> 0 - ORDER BY tipo_id, Article, Medida, Categoria, Origen; - - DROP TEMPORARY TABLE IF EXISTS Traslados; - DROP TEMPORARY TABLE IF EXISTS tmp_item; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `trasladoTesting` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `trasladoTesting`(IN i_entrada INTEGER) -BEGIN - DECLARE dateShipment DATE; - DECLARE dateLanding DATE; - DECLARE warehouseShipment INTEGER; - DECLARE warehouseLanding INTEGER; - DECLARE v_calc_available INTEGER; - DECLARE v_calc_visible INTEGER; - - SELECT shipment, landing, warehouse_id_out, warehouse_id - INTO dateShipment, dateLanding, warehouseShipment, warehouseLanding - FROM travel t JOIN Entradas e ON t.id = e.travel_id - WHERE Id_Entrada = i_entrada; - - CALL buy_tarifas_table(i_entrada); - - -- Traslado en almacen origen - - DROP TEMPORARY TABLE IF EXISTS buy_edi_temp; - - CREATE TEMPORARY TABLE buy_edi_temp - (KEY (Id_Article)) ENGINE = MEMORY - - SELECT * FROM (SELECT c.Id_Article, c.Id_Compra - FROM Compres c INNER JOIN Entradas e USING(Id_Entrada) - INNER JOIN travel t ON t.id = e.travel_id - WHERE t.landing BETWEEN date_inv() AND dateShipment - AND c.Novincular = FALSE - AND c.Tarifa2 >= 0 - ORDER BY (warehouseShipment = t.warehouse_id) DESC, t.landing DESC) t - GROUP BY Id_Article; - - IF dateShipment >= CURDATE() THEN - - CALL `cache`.available_refresh(v_calc_available, TRUE, warehouseShipment, dateShipment); - -- CALL `cache`.availableTraslate(warehouseShipment, dateShipment,NULL); - CALL `cache`.visible_refresh(v_calc_visible,TRUE,warehouseShipment); - DROP TEMPORARY TABLE IF EXISTS tmp_item; - CREATE TEMPORARY TABLE tmp_item (UNIQUE INDEX i USING HASH (item_id)) ENGINE = MEMORY - SELECT item_id, visible,0 available FROM `cache`.visible WHERE calc_id = v_calc_visible; - INSERT INTO tmp_item(item_id, available) - SELECT a.item_id, a.available FROM `cache`.available a WHERE a.calc_id = v_calc_available - ON DUPLICATE KEY UPDATE available = a.available; - ELSE - CALL item_stock(warehouseShipment, dateShipment,NULL); - END IF; - - DROP TEMPORARY TABLE IF EXISTS Traslados; - CREATE TEMPORARY TABLE Traslados ENGINE MEMORY - SELECT TP.Id_Tipo AS Tipo, - - TP.reino_id, - - ar.tipo_id, - - ar.Id_Article AS article_id, - - ar.Article, - - ar.Medida, - - ar.Categoria, - - ar.Color, - - Origen.abreviatura as Origen, - - CE.Cantidad, - - ar.Tallos, - - CAST(AIM.visible AS DECIMAL(10,0)) as vis1, - - CAST(AIM.available AS DECIMAL(10,0)) as dis1, - - 0 as vis2, - - 0 as dis2, - - IFNULL(CE.grouping,C.grouping) as grouping, - - IFNULL(CE.Packing,C.Packing) as Packing, - - IFNULL(CE.caja,C.caja) as caja, - - IFNULL(C.Productor, P2.Alias) AS Productor, - - C.Id_Cubo, - - 1 Tinta, - - CE.Id_Compra, - - CE.Etiquetas, - - C.buy_edi_id, - - TP.Id_Trabajador, - - CB.Volumen, - - CB.x, CB.y, CB.z, - - IFNULL(C.Costefijo,0) Costefijo, - - IFNULL(C.Comisionfija,0) Comisionfija, - - IFNULL(C.Portefijo,0) Portefijo, - - A.m3, - - E.comision, - - CB.Retornable, - - IFNULL(CEB.Valor,CB.Valor) Valor, - - t3, t2, TP.promo - - FROM Articles ar - LEFT JOIN tmp_item AIM ON AIM.item_id = ar.Id_Article - LEFT JOIN Tipos TP USING(tipo_id) - LEFT JOIN Origen ON Origen.id = ar.id_origen - LEFT JOIN buy_edi_temp lb ON lb.Id_Article = ar.Id_Article - LEFT JOIN Compres C ON C.Id_Compra = lb.Id_Compra - LEFT JOIN Cubos CB ON CB.Id_Cubo = C.Id_Cubo - LEFT JOIN Entradas E2 ON E2.Id_Entrada = C.Id_Entrada - LEFT JOIN Proveedores P2 ON P2.Id_Proveedor = E2.Id_Proveedor - LEFT JOIN Entradas E ON E.Id_Entrada = i_entrada - LEFT JOIN travel TR ON TR.id = E.travel_id - LEFT JOIN Agencias A ON A.Id_Agencia = TR.agency_id - LEFT JOIN Compres CE ON CE.Id_Article = ar.Id_Article AND CE.Id_Entrada = i_entrada - LEFT JOIN Cubos CEB ON CEB.Id_Cubo = CE.Id_Cubo - LEFT JOIN tblTARIFAS ON TRUE - WHERE TP.reino_id <> 6 AND TP.reino_id <> 8 - AND E.Redada = FALSE; - - - CREATE INDEX tindex USING HASH ON Traslados (article_id); - --- Inventario en el warehouse destino - IF dateShipment >= CURDATE() THEN - - CALL cache.visible_refresh(v_calc_visible, TRUE, warehouseLanding); - CALL availableTraslate(warehouseLanding, dateLanding,warehouseShipment); - - UPDATE Traslados t - LEFT JOIN availableTraslate a ON t.article_id = a.item_id - LEFT JOIN `cache`.visible v ON v.calc_id = v_calc_visible AND t.article_id = v.item_id - SET vis2 = v.visible, dis2 = a.available; - - END IF; --- --------------------------------------------- - - SELECT t.*, - - Cantidad - MOD(Cantidad , grouping) as Subcantidad, - - MOD(Cantidad , grouping) as Soll, - - (IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) / Packing as cm3, - - Costefijo + Comisionfija + Portefijo AS Cost, - - @porte := ROUND((IF(Volumen > 0,Volumen,x * y * IF(z = 0, Medida + 10, z))) * m3 / 1000000 / Packing ,3) AS Porte, - - @comision := ROUND((Costefijo + Comisionfija + Portefijo) * comision / 100 ,3) AS Comision, - - @embalaje := IF(Retornable != 0, 0,ROUND(Valor / Packing,3)) AS Embalaje, - - @coste := IFNULL((Costefijo + Comisionfija + Portefijo),0) + IFNULL(@embalaje,0) + IFNULL(@porte,0) + IFNULL(@comision,0) AS Coste, - - @t3 := ROUND(@coste / ( (100 - t3 - t.promo)/100),2) AS Tarifa3, - - ROUND(@t3 * (1 + ((t2 - t3)/100)),2) AS Tarifa2, - - 0 selected - - FROM Traslados t - WHERE vis1 <> 0 OR dis1 <> 0 OR vis2 <> 0 OR dis2 <> 0 - ORDER BY tipo_id, Article, Medida, Categoria, Origen; - - DROP TEMPORARY TABLE IF EXISTS Traslados; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `traslado_label` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `traslado_label`(IN intArticle INTEGER,IN i_entrada_FV INTEGER, IN i_entrada_PCA INTEGER) -BEGIN - -DECLARE intEntrada INTEGER; -DECLARE i_FV INTEGER; - -SELECT FV INTO i_FV -FROM Articles a -JOIN Tipos tp ON tp.tipo_id = a.tipo_id -WHERE a.Id_Article = intArticle; - -SET intEntrada = IF(i_FV, i_entrada_FV,i_entrada_PCA); - -SET intEntrada = IF(intEntrada = 0, i_entrada_PCA + i_entrada_FV, intEntrada); - - - IF intEntrada > 0 THEN - - CALL buy_tarifas_table(intEntrada); - - INSERT INTO Compres (Id_Article, Etiquetas, Cantidad, Id_Entrada, Id_Cubo, Packing,grouping,caja, - Costefijo, Portefijo, Embalajefijo, Comisionfija, novincular,buy_edi_id) - SELECT - land.Id_Article, - land.Etiquetas - IFNULL(ship.Etiquetas,0) - (IFNULL(Ventas,0) / land.Packing), - land.Cantidad - IFNULL(ship.Cantidad,0) - IFNULL(Ventas,0), - intEntrada, - land.Id_Cubo, - land.Packing, - land.grouping, - land.caja, - @cost := ROUND(IFNULL(land.Costefijo, 0) + IFNULL(land.Comisionfija, 0) + IFNULL(land.Portefijo, 0), - 3) Costefij, - @porte := ROUND((@cm3:= cm3_2(land.Id_Cubo, land.Id_Article)) * a.m3 / 1000000 / land.Packing, - 3) Porte, - land.EmbalajeFijo AS Embalaje, - @comision := ROUND(land.Costefijo * e2.comision / 100, 3) Comision, - land.novincular,land.buy_edi_id - FROM ( - select c_land.Id_Cubo,c_land.Packing,c_land.grouping,c_land.Costefijo,c_land.Comisionfija,c_land.Portefijo,c_land.caja,SUM(c_land.Etiquetas) Etiquetas,c_land.EmbalajeFijo, - c_land.novincular,c_land.buy_edi_id,c_land.Id_Article,SUM(c_land.Cantidad) Cantidad - from - -- Entradas que llegan a vnh - Compres c_land - JOIN - Entradas e_land ON c_land.Id_Entrada = e_land.Id_Entrada AND c_land.Id_Article = intArticle - JOIN - travel t_land ON t_land.id = e_land.travel_id - JOIN - Cubos cu ON cu.Id_Cubo = c_land.Id_Cubo - WHERE - -- Entradas que llegan a vnh - (t_land.warehouse_id = 7 AND t_land.landing = CURDATE()) - ) land - LEFT JOIN -- Entradas que salen de vnh - (SELECT SUM(c_ship.Etiquetas) Etiquetas,c_ship.Packing,SUM(c_ship.Cantidad) Cantidad - FROM Compres c_ship - LEFT JOIN Entradas e_ship ON c_ship.Id_Entrada = e_ship.Id_Entrada AND c_ship.Id_Article = intArticle - LEFT JOIN travel t_ship ON t_ship.id = e_ship.travel_id - WHERE t_ship.warehouse_id_out = 7 AND t_ship.shipment = CURDATE() - -- Entrada destino - ) ship ON TRUE - JOIN Entradas e2 ON e2.Id_Entrada = intEntrada - JOIN travel t ON t.id = e2.travel_id - JOIN Agencias a ON t.agency_id = a.Id_Agencia - -- Ventas ese dia en VNH - LEFT JOIN - (SELECT sum(Cantidad) as Ventas - FROM Movimientos m - JOIN Tickets t on t.Id_Ticket = m.Id_Ticket - WHERE t.Fecha = CURDATE() AND m.Id_Article = intArticle AND t.warehouse_id = 7) v on true - GROUP BY land.Id_Article; - CALL buy_tarifas(LAST_INSERT_ID()); - - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `traslado_label_2` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `traslado_label_2`(IN i_compra INTEGER,IN i_entrada_FV INTEGER, IN i_entrada_PCA INTEGER, i_cantidad INTEGER) -BEGIN - --- PAK 2015-09-15 -DECLARE idARTICLE INT; - -SELECT Id_Article INTO idARTICLE FROM Compres WHERE Id_Compra = i_compra; - -call traslado_label_3(idARTICLE,i_entrada_FV,i_entrada_PCA); - -/* -DECLARE i_entrada_shipment INTEGER; -DECLARE i_entrada_landing INTEGER; -DECLARE i_FV INTEGER; - -SELECT c.Id_Entrada, FV INTO i_entrada_shipment, i_FV -FROM Compres c -JOIN Articles a ON a.Id_Article = c.Id_Article -JOIN Tipos tp ON tp.tipo_id = a.tipo_id -WHERE Id_Compra = i_compra; - -SET i_entrada_landing = IF(i_FV, i_entrada_FV,i_entrada_PCA); - -SET i_entrada_landing = IF(i_entrada_landing = 0, i_entrada_PCA + i_entrada_FV, i_entrada_landing); - -IF i_entrada_landing > 0 THEN - - CALL buy_tarifas_table(i_entrada_landing); - - INSERT INTO Compres (Id_Article, Etiquetas, Cantidad, Id_Entrada, Id_Cubo, Packing,grouping,caja, - Costefijo, Portefijo, Embalajefijo, Comisionfija, Productor, S3, S4, S2, novincular,k01,k02,k03,k04,buy_edi_id) - SELECT - Id_Article, - i_cantidad / Packing, - i_cantidad, - i_entrada_landing, - Id_Cubo, - Packing, - c.grouping, - c.caja, - @cost := ROUND(IFNULL(Costefijo, 0) + IFNULL(Comisionfija, 0) + IFNULL(Portefijo, 0), - 3) Costefij, - @porte := ROUND((@cm3:= cm3_2(Id_Cubo, Id_Article)) * a.m3 / 1000000 / Packing, - 3) Porte, - EmbalajeFijo AS Embalaje, - @comision := ROUND(Costefijo * e2.comision / 100, 3) Comision, - Productor, - S3, - S4, - S2, - novincular,c.k01,c.k02,c.k03,c.k04,c.buy_edi_id - FROM - Compres c - JOIN - Entradas e USING (Id_Entrada) - JOIN - Cubos cu USING (Id_Cubo) - JOIN - Entradas e2 ON e2.Id_Entrada = i_entrada_landing - JOIN - travel t ON t.id = e2.travel_id - JOIN - Agencias a ON t.agency_id = a.Id_Agencia - WHERE - Id_Compra = i_compra and i_cantidad; - - -CALL buy_tarifas(LAST_INSERT_ID()); - -END IF; -*/ -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `traslado_label_3` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `traslado_label_3`(IN intArticle INTEGER,IN i_entrada_FV INTEGER, IN i_entrada_PCA INTEGER) -BEGIN --- DEPRECATED usar traslado_label -DECLARE intEntrada INTEGER; -DECLARE i_FV INTEGER; - -SELECT FV INTO i_FV -FROM Articles a -JOIN Tipos tp ON tp.tipo_id = a.tipo_id -WHERE a.Id_Article = intArticle; - -SET intEntrada = IF(i_FV, i_entrada_FV,i_entrada_PCA); - -SET intEntrada = IF(intEntrada = 0, i_entrada_PCA + i_entrada_FV, intEntrada); - - - IF intEntrada > 0 THEN - - CALL buy_tarifas_table(intEntrada); - - INSERT INTO Compres (Id_Article, Etiquetas, Cantidad, Id_Entrada, Id_Cubo, Packing,grouping,caja, - Costefijo, Portefijo, Embalajefijo, Comisionfija, novincular,buy_edi_id) - SELECT - land.Id_Article, - land.Etiquetas - IFNULL(ship.Etiquetas,0) - (IFNULL(Ventas,0) / land.Packing), - land.Cantidad - IFNULL(ship.Cantidad,0) - IFNULL(Ventas,0), - intEntrada, - land.Id_Cubo, - land.Packing, - land.grouping, - land.caja, - @cost := ROUND(IFNULL(land.Costefijo, 0) + IFNULL(land.Comisionfija, 0) + IFNULL(land.Portefijo, 0), - 3) Costefij, - @porte := ROUND((@cm3:= cm3_2(land.Id_Cubo, land.Id_Article)) * a.m3 / 1000000 / land.Packing, - 3) Porte, - land.EmbalajeFijo AS Embalaje, - @comision := ROUND(land.Costefijo * e2.comision / 100, 3) Comision, - land.novincular,land.buy_edi_id - FROM ( - select c_land.Id_Cubo,c_land.Packing,c_land.grouping,c_land.Costefijo,c_land.Comisionfija,c_land.Portefijo,c_land.caja,SUM(c_land.Etiquetas) Etiquetas,c_land.EmbalajeFijo, - c_land.novincular,c_land.buy_edi_id,c_land.Id_Article,SUM(c_land.Cantidad) Cantidad - from - -- Entradas que llegan a vnh - Compres c_land - JOIN - Entradas e_land ON c_land.Id_Entrada = e_land.Id_Entrada AND c_land.Id_Article = intArticle - JOIN - travel t_land ON t_land.id = e_land.travel_id - JOIN - Cubos cu ON cu.Id_Cubo = c_land.Id_Cubo - WHERE - -- Entradas que llegan a vnh - (t_land.warehouse_id = 7 AND t_land.landing = CURDATE()) - ) land - LEFT JOIN -- Entradas que salen de vnh - (SELECT SUM(c_ship.Etiquetas) Etiquetas,c_ship.Packing,SUM(c_ship.Cantidad) Cantidad - FROM Compres c_ship - LEFT JOIN Entradas e_ship ON c_ship.Id_Entrada = e_ship.Id_Entrada AND c_ship.Id_Article = intArticle - LEFT JOIN travel t_ship ON t_ship.id = e_ship.travel_id - WHERE t_ship.warehouse_id_out = 7 AND t_ship.shipment = CURDATE() - -- Entrada destino - ) ship ON TRUE - JOIN Entradas e2 ON e2.Id_Entrada = intEntrada - JOIN travel t ON t.id = e2.travel_id - JOIN Agencias a ON t.agency_id = a.Id_Agencia - -- Ventas ese dia en VNH - LEFT JOIN - (SELECT sum(Cantidad) as Ventas - FROM Movimientos m - JOIN Tickets t on t.Id_Ticket = m.Id_Ticket - WHERE t.Fecha = CURDATE() AND m.Id_Article = intArticle AND t.warehouse_id = 7) v on true - GROUP BY land.Id_Article; - CALL buy_tarifas(LAST_INSERT_ID()); - - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `traslado_ticket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `traslado_ticket`(IN i_entrada INTEGER, IN i_ticket INTEGER) -BEGIN - - DECLARE intWarehouse INT; - DECLARE datTicket DATE; - - SELECT warehouse_id, Fecha INTO intWarehouse,datTicket FROM Tickets WHERE Id_Ticket = i_ticket; - - CALL buy_tarifas_table(i_entrada); - - CALL item_last_buy_(intWarehouse,datTicket); - - - INSERT INTO Compres( Id_Article, - Cantidad, - Novincular, - Id_Entrada, - Id_Cubo, - Packing, - grouping, - caja, - Portefijo, - Comisionfija, - Embalajefijo, - Costefijo, - Productor, - Tarifa2, - Tarifa3 - ) - - SELECT M.Id_Article, - IF(T.Id_Cliente IN (1625, 1118, 400), -1, 1) * M.Cantidad, - - IF(T.Id_Cliente IN (1625, 1118, 400), TRUE, FALSE), - i_entrada, - IFNULL(C.Id_Cubo,'--'), - C.Packing, - C.grouping, - C.caja, - @pf := ROUND(@cm3:=cm3_2(IFNULL(C.Id_Cubo,'--'), b.item_id) * AG.m3 / 1000000 / C.Packing ,3) AS Porte, - @cf := IFNULL(ROUND(C.Costefijo * E.comision / 100 ,3),0) AS Comision, - @ef := ROUND(IF(CB.Retornable = FALSE,CB.Valor/ C.Packing,0) ,3) AS Embalaje, - @cost := ROUND(IFNULL(C.Costefijo,0) + @cf + @ef + @pf,3), - C.Productor, - @t3 := ROUND(@cost / ((100 - TC.t3)/100),2) Tarifa3, - @t2 := IF(@cost / ((100 - TC.t2)/100) <= @t3,@t3+0.01,@cost / ((100 - TC.t2)/100)) Tarifa2 - - FROM Movimientos M - LEFT JOIN Tickets T USING(Id_Ticket) - LEFT JOIN t_item_last_buy b ON M.Id_Article = b.item_id AND T.warehouse_id = b.warehouse_id - LEFT JOIN Compres C ON C.Id_Compra = b.buy_id - LEFT JOIN Cubos CB ON CB.Id_Cubo = C.Id_Cubo - LEFT JOIN Entradas E ON E.Id_Entrada = i_entrada - LEFT JOIN travel TR ON TR.id = E.travel_id - LEFT JOIN Agencias AG ON AG.Id_Agencia = TR.agency_id - LEFT JOIN Proveedores P ON P.Id_Proveedor = E.Id_Proveedor - JOIN tblTARIFAS TC - LEFT JOIN tblContadores ON TRUE - JOIN (SELECT m3 as ZEL_PORT FROM Agencias WHERE Id_Agencia = 618) Z - WHERE M.Id_Ticket = i_ticket; - - - DROP TEMPORARY TABLE t_item_last_buy; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `travelDetail` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `travelDetail`() -BEGIN - -DECLARE vGap VARCHAR(10) DEFAULT ' '; -DECLARE vDateFrom DATE DEFAULT TIMESTAMPADD(WEEK,-1,CURDATE()); - -SELECT * FROM -( -SELECT - 1 as IsTravel, - tr.id as travel, - NULL as Entrada, - ag.Agencia, - tr.ref, - tr.shipment, - wo.name as OrigenCajas, - tr.landing, - w.name as Destino, - sum(c.Etiquetas) as Etiquetas, - NULL as Notas_Eva, - kg, - cast(sum(a.density * c.Etiquetas * IF(cb.Volumen, cb.Volumen, cb.X * cb.Y * cb.Z) / 1000000 ) as DECIMAL(10,0)) as loadedKg, - NULL as loadPriority, - NULL as Notas, - pc.Alias as Carguera - FROM travel tr - LEFT JOIN Proveedores pc ON pc.Id_Proveedor = tr.cargoSupplierFk - LEFT JOIN Entradas e ON e.travel_id = tr.id - LEFT JOIN Compres c ON c.Id_Entrada = e.Id_Entrada - LEFT JOIN Cubos cb ON cb.Id_Cubo = c.Id_Cubo - LEFT JOIN Articles a ON a.Id_Article = c.Id_Article - LEFT JOIN Tipos tp ON tp.tipo_id = a.tipo_id - JOIN warehouse w ON w.id = tr.warehouse_id - JOIN warehouse wo ON wo.id = tr.warehouse_id_out - JOIN Agencias ag ON ag.Id_Agencia = tr.agency_id - WHERE tr.landing >= vDateFrom - GROUP BY tr.id - -UNION ALL - -SELECT - 0 as IsTravel, - e.travel_id as travel, - e.Id_Entrada, - CONCAT(vGap,p.Proveedor), - e.Referencia, - tr.shipment, - wo.name as OrigenCajas, - tr.landing, - w.name as Destino, - sum(Etiquetas) as Etiquetas, - e.Notas_Eva, - NULL as kg, - cast(sum(a.density * c.Etiquetas * IF(cb.Volumen, cb.Volumen, cb.X * cb.Y * cb.Z) / 1000000 ) as DECIMAL(10,0)) as loadedkg, - loadPriority, - -- CAST(awb.codigo AS DECIMAL(11,0)) as awb, - e.Notas, - pc.Proveedor as carguera - - FROM Entradas e - /* LEFT JOIN recibida_entrada re ON re.Id_Entrada = e.Id_Entrada - LEFT JOIN awb_recibida ar ON ar.recibida_id = re.awb_recibida - LEFT JOIN awb ON awb.id = ar.awb_id - */ JOIN Compres c ON c.Id_Entrada = e.Id_Entrada - JOIN Cubos cb ON cb.Id_Cubo = c.Id_Cubo - JOIN Articles a ON a.Id_Article = c.Id_Article - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor - JOIN travel tr ON tr.id = e.travel_id - LEFT JOIN Proveedores pc ON pc.Id_Proveedor = tr.cargoSupplierFk - JOIN warehouse w ON w.id = tr.warehouse_id - JOIN warehouse wo ON wo.id = tr.warehouse_id_out - WHERE tr.landing >= vDateFrom - GROUP BY e.Id_Entrada -) sub -ORDER BY landing, travel, IsTravel DESC, (loadPriority > 0) DESC,loadPriority, Agencia, Notas_Eva ; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `travel_tree` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `travel_tree`(vDate DATE, vAddress INT, vAgency INT) -BEGIN -/** - * Devuelve la lista de almacenes disponibles y la fecha de - * envío desde cada uno. - * - * @param vDate Fecha de recepción de mercancía - * @param vAddress Id consignatario, %NULL para recogida - * @param vAgency Id de subagencia - * @table travel_tree Lista de almacenes disponibles - */ - DECLARE vDone BOOL; - DECLARE vWh SMALLINT; - - DECLARE vCur CURSOR FOR - SELECT w.id warehouse_id - FROM warehouse w - WHERE reserve; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DROP TEMPORARY TABLE IF EXISTS travel_tree; - CREATE TEMPORARY TABLE travel_tree - ( - warehouse_id TINYINT NOT NULL PRIMARY KEY, - Fecha_envio DATE NOT NULL, - Fecha_recepcion DATE NOT NULL - ) - ENGINE = MEMORY; - - -- Establecemos los almacenes y las fechas que van a entrar - - OPEN vCur; - - l: LOOP - SET vDone = FALSE; - FETCH vCur INTO vWh; - - IF vDone THEN - LEAVE l; - END IF; - - INSERT INTO travel_tree (warehouse_id, Fecha_envio, Fecha_recepcion) - SELECT vWh, shipping, vDate FROM ( - SELECT TIMESTAMPADD(DAY, -ah.subtract_day, vDate) shipping, ah.max_hour - FROM agency_hour ah - LEFT JOIN Consignatarios c ON c.Id_Consigna = vAddress - WHERE ah.warehouse_id = vWh - AND (week_day = WEEKDAY(vDate) - OR week_day IS NULL) - AND (ah.agency_id = vAgency - OR ah.agency_id IS NULL) - AND (ah.province_id = c.province_id - OR ah.province_id IS NULL - OR vAddress IS NULL) - ORDER BY ( - (ah.week_day IS NOT NULL) + - (ah.agency_id IS NOT NULL) + - ((ah.province_id IS NOT NULL) * 3) - ) DESC - LIMIT 1 - ) t - WHERE shipping >= CURDATE() - AND IF(shipping = CURDATE(), max_hour > HOUR(NOW()), TRUE); - END LOOP; - - CLOSE vCur; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `travel_tree_list` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `travel_tree_list`(vAddress INT, vDate DATE) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha - * y dirección pasadas. - * - * @param vAddress Id de dirección de envío, %NULL si es recogida - * @param vDate Fecha de recogida - * @table agency_list Listado de agencias disponibles - */ - DECLARE vAgency INT; - DECLARE vDone BOOL DEFAULT FALSE; - - DECLARE vCur CURSOR FOR - SELECT DISTINCT agency_id - FROM agency - JOIN agency_hour USING(agency_id); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DROP TEMPORARY TABLE IF EXISTS agency_list; - CREATE TEMPORARY TABLE agency_list ( - Id_Agencia INT NOT NULL, - Agencia VARCHAR(20), - description VARCHAR(45), - Vista VARCHAR(45), - shipment DATE, - Descripcion VARCHAR(45), - PRIMARY KEY(Id_Agencia) - ) - ENGINE = MEMORY; - - OPEN vCur; - FETCH vCur INTO vAgency; - - WHILE NOT vDone - DO - CALL travel_tree (vDate, vAddress, vAgency); - - INSERT INTO agency_list - SELECT a.Id_Agencia, a.Agencia, a.description, - a.Vista, t.Fecha_Envio, w.name as Descripcion - FROM Agencias a - JOIN travel_tree t - JOIN warehouse w on w.id = t.warehouse_id - WHERE agency_id = vAgency - AND a.web - ON DUPLICATE KEY UPDATE - Descripcion = CONCAT(Descripcion, ', ', w.name); - - FETCH vCur INTO vAgency; - END WHILE; - - CLOSE vCur; - - SELECT * FROM agency_list; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `travel_tree_shipment` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `travel_tree_shipment`(v_date DATE, v_consigna INT, v_agency INT, v_warehouse INT) -BEGIN -/** - * Devuelve una tabla temporal con el dia de recepcion para v_date. - * - * @param v_date Fecha de preparacion de mercancia - * @param v_consigna Id de consignatario, %NULL para recogida - * @param v_agency Id agencia - * @table travel_tree_shipment Datos de recepción - */ - DROP TEMPORARY TABLE IF EXISTS travel_tree_shipment; - CREATE TEMPORARY TABLE travel_tree_shipment - ENGINE = MEMORY - SELECT v_warehouse warehouse_id, v_envio landing FROM ( - SELECT * FROM ( - SELECT v_warehouse, TIMESTAMPADD(DAY, subtract_day, v_date) v_envio, subtract_day, ah.max_hour - FROM agency_hour ah - LEFT JOIN Consignatarios c ON c.Id_Consigna = v_consigna - WHERE (week_day = weekday(TIMESTAMPADD(DAY, subtract_day, v_date)) OR week_day IS NULL) - AND (ah.agency_id = v_agency OR ah.agency_id IS NULL) - AND ah.warehouse_id = v_warehouse - AND (ah.province_id = c.province_id OR ah.province_id IS NULL OR v_consigna IS NULL) - ORDER BY ( - (ah.week_day IS NOT NULL) + - (ah.agency_id IS NOT NULL) + - ((ah.province_id IS NOT NULL)*3) - ) DESC - ) t - LIMIT 1 - ) t - WHERE IF(v_date = CURDATE(), max_hour > HOUR(NOW()), TRUE) AND subtract_day < 225; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `turnoClon` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `turnoClon`(IN vWeek INT, IN vYear INT) -BEGIN - -DECLARE done BIT DEFAULT 0; -DECLARE myEntrada INT; -DECLARE myWeekday INT; -DECLARE myLanding DATE; -DECLARE myShipment DATE; -DECLARE myDateDiff INT; -DECLARE myTravel INT; -DECLARE myNuevaEntrada INT; -DECLARE myWH_IN INT; -DECLARE myWH_OUT INT; - -DECLARE rs CURSOR FOR -SELECT Id_Entrada, weekDay FROM Entradas_turno; - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - -IF vWeek = 0 THEN - - SET vWeek = WEEK(TIMESTAMPADD(WEEK,1,CURDATE())); - SET vYear = YEAR(TIMESTAMPADD(WEEK,1,CURDATE())); - -END IF; - - -OPEN rs; - -FETCH rs INTO myEntrada, myWeekday; - -WHILE NOT done DO - - SELECT DATEDIFF(landing,shipment), warehouse_id, warehouse_id_out INTO myDateDiff, myWH_IN, myWH_OUT - FROM travel t - JOIN Entradas e on e.travel_id = t.id - WHERE Id_Entrada = myEntrada; - - SELECT date, TIMESTAMPADD(DAY, - myDateDiff, date) - INTO myLanding , myShipment - FROM time - WHERE year = vYear AND week = vWeek - AND WEEKDAY(date) = myWeekday; - - SELECT t.id INTO myTravel - FROM travel t - WHERE shipment = myShipment - AND landing = myLanding - AND warehouse_id = myWH_IN - AND warehouse_id_out = myWH_OUT - LIMIT 1; - - IF IFNULL(myTravel,0) = 0 THEN - - INSERT INTO travel(shipment, shipment_hour, landing,landing_hour, warehouse_id, warehouse_id_out,agency_id, ref) - SELECT myShipment, shipment_hour, myLanding ,landing_hour, warehouse_id, warehouse_id_out,agency_id, ref - FROM travel t - JOIN Entradas e on e.travel_id = t.id - WHERE Id_Entrada = myEntrada; - - SELECT LAST_INSERT_ID() INTO myTravel; - - - END IF; - - INSERT INTO Entradas(Id_Proveedor,Referencia, Notas, Id_Moneda, empresa_id, travel_id) - SELECT Id_Proveedor, Referencia, Notas, Id_Moneda, empresa_id, myTravel - FROM Entradas - WHERE Id_Entrada = myEntrada; - - SELECT LAST_INSERT_ID() INTO myNuevaEntrada; - - INSERT INTO Compres(Id_Entrada, Id_Article, Cantidad, Costefijo, Portefijo, Embalajefijo, Novincular, Comisionfija, Etiquetas, Packing - ,grouping, caja, /*container_id, */Nicho, Id_Cubo, Tarifa1,Tarifa2,Tarifa3, PVP, Productor) - SELECT myNuevaEntrada, Id_Article, Cantidad, Costefijo, Portefijo, Embalajefijo, Novincular, Comisionfija, Etiquetas, Packing - ,grouping, caja,/* container_id, */Nicho, Id_Cubo, Tarifa1,Tarifa2,Tarifa3, PVP, Productor - FROM Compres - WHERE Id_Entrada = myEntrada; - - - FETCH rs INTO myEntrada, myWeekday; - -END WHILE; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `turn_calculartiempomedio` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `turn_calculartiempomedio`() -BEGIN - -DECLARE strTiempoAprox NVARCHAR(255); - -SELECT -CASE WHEN @min>45 THEN concat(@hora:=@hora+1,' horas ') -WHEN @hora >0 THEN concat(@hora,' horas ') -WHEN @min>=0 and @min<15 THEN '15 Minutos' -WHEN @min<30 THEN '30 Minutos' -WHEN @min<45 THEN '45 Minutos' -ELSE '' and @hora=@hora+1 END AS tiempoaprox -INTO strTiempoAprox -FROM ( - select min(sub1.adate) as adate,max(sub1.bdate) as bdate, - @hora:=ROUND((TIMESTAMPDIFF(HOUR,min(sub1.adate),max(sub1.bdate)) /10),0), - @min:=ROUND((TIMESTAMPDIFF(MINUTE,min(sub1.adate),max(sub1.bdate)) mod 60)/10,0) - from ( - select a.odbc_date as adate,b.odbc_date as bdate - from turn a - INNER JOIN turn b on a.number=(b.number-1) - WHERE TIMESTAMPDIFF(HOUR,b.odbc_date,a.odbc_date)<1 - ORDER BY a.odbc_date DESC,b.odbc_date DESC - LIMIT 10) sub1) sub2; - -SELECT strTiempoAprox as TiempoAprox; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ubicator` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ubicator`(IN i_wh TINYINT, IN d_fecha DATE,IN filtro VARCHAR(255)) -BEGIN - - - DECLARE date_inv DATE; - - -DROP TEMPORARY TABLE IF EXISTS stock_actual; -DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_ubicator_stock; - - -SELECT FechaInventario INTO date_inv - FROM tblContadores LIMIT 1; - - -CREATE TEMPORARY TABLE stock_actual -SELECT Id_Article article_id,SUM(Cantidad) amount FROM ( - SELECT Id_Article,Cantidad - FROM Compres c - JOIN Entradas e USING(Id_Entrada) - JOIN travel t ON t.id = e.travel_id - WHERE landing BETWEEN date_inv AND d_fecha - AND warehouse_id = i_wh AND NOT Redada - - UNION ALL - - -- JGF Error cuando se pedia para una fecha futura 30/06/14 - /*SELECT Id_Article,-Cantidad - FROM Compres c - JOIN Entradas e USING(Id_Entrada) - JOIN travel t ON t.id = e.travel_id - WHERE shipment BETWEEN date_inv AND timestampadd(DAY,-1,d_fecha) - AND warehouse_id_out = i_wh AND NOT Redada*/ - SELECT Id_Article,-Cantidad - FROM Compres c - JOIN Entradas e USING(Id_Entrada) - JOIN travel t ON t.id = e.travel_id - WHERE shipment BETWEEN date_inv AND CURDATE() - AND warehouse_id_out = i_wh AND NOT Redada AND delivered - UNION ALL - - -- JGF Error cuando se pedia para una fecha futura 30/06/14 - - /*SELECT Id_Article, -Cantidad - FROM Movimientos m - JOIN Tickets t USING(Id_Ticket) - WHERE Fecha BETWEEN date_inv AND timestampadd(DAY,-1,d_fecha) - AND warehouse_id = i_wh */ - SELECT Id_Article, -Cantidad - FROM Movimientos m - JOIN Tickets t USING(Id_Ticket) - WHERE Fecha BETWEEN date_inv AND CURDATE() - AND warehouse_id = i_wh AND Etiquetasemitidas - - -) t GROUP BY article_id; - -/* -SELECT * from stock_actual;*/ - --- TEMPORARY -CALL util.exec (sql_printf(' - CREATE TEMPORARY TABLE IF NOT EXISTS vn2008.tmp_ubicator_stock AS - SELECT A.Id_Article,A.Article, T.Id_Cubo,IF(Z > 0,Z,0) as z,x,y, - CEIL(S.Suma/T.packing) as etiquetas,A.Medida,A.Nicho - FROM vn2008.Articles A - INNER JOIN - (SELECT article_id, amount as SUMA - FROM vn2008.stock_actual - WHERE amount > 0 - ) as S ON S.article_id = A.Id_Article - LEFT JOIN ( - SELECT * FROM ( - SELECT c.Id_Article item_id, c.Id_Compra id, c.Id_Cubo,c.packing - FROM vn2008.Compres c INNER JOIN vn2008.Entradas e USING(Id_Entrada) - INNER JOIN vn2008.travel t ON t.id = e.travel_id - WHERE t.landing BETWEEN vn2008.date_inv() AND %v - AND c.Novincular = FALSE - AND c.Tarifa2 >= 0 AND Id_Cubo IS NOT NULL - ORDER BY 1 = t.warehouse_id DESC, t.landing DESC - ) t1 GROUP BY item_id - ) as T ON T.item_id = A.Id_Article - LEFT JOIN vn2008.Cubos C USING(Id_Cubo) - WHERE %s AND CEIL(S.Suma/T.packing) > 0',d_fecha,filtro)); - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ubicator_calcularhuecosvacios` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ubicator_calcularhuecosvacios`(int_H int,int_X int,int_Y int,int_Z int,intId_Estanterias int,intId_Baldas int,contId_Estanterias int) -BEGIN -DECLARE intnumcubostotal,intnumcubosocup SMALLINT DEFAULT 0; -DECLARE posX,posY,posZ,intId_Article,x_cubo,y_cubo INT DEFAULT 0; -DECLARE strId_Cubo VARCHAR(10); -DECLARE strArticle,strmodelo VARCHAR(50) DEFAULT '---'; -DECLARE intContador INT DEFAULT 1; - - SELECT COUNT(*) INTO intnumcubosocup FROM Ubicator_Cajas - WHERE W=int_X and D=int_Y and Id_Estanterias=intId_Estanterias and Id_Baldas=intId_Baldas and NumEstanterias=contId_Estanterias; - - SELECT W,D,H,Id_Cubo,Id_Article,modelo,Article,x,y - INTO posX,posY,posZ,strId_Cubo,intId_Article,strmodelo,strArticle,x_cubo,y_cubo - FROM Ubicator_Cajas - WHERE W=int_X and D=int_Y and Id_Estanterias=intId_Estanterias and Id_Baldas=intId_Baldas and NumEstanterias=contId_Estanterias - ORDER BY H DESC LIMIT 1; - - WHILE (int_Z*intContador0) DO - SET posZ=posZ+int_Z; - -- INSERT INTO Ubicator_Cajas - -- (Id_Estanterias,NumEtiquetas,W ,D,H ,Id_Cubo ,Id_Article,POSX,POSY,POSZ,Id_Article_aux ,Id_Baldas,modelo,Article,Medida) - -- VALUES (intId_Estanterias ,1,posX,posY,posZ,strId_Cubo ,intId_Article,0,0,0,0,intId_Baldas,strmodelo,'',int_Z); - INSERT INTO Ubicator_Cajas (Id_Estanterias,Id_Baldas,modelo,W ,D,H ,Id_Cubo,X,Y,Z,Medida,Id_Article,Article,numEstanterias) - VALUES (intId_Estanterias,intId_Baldas,strmodelo,posX,posY,posZ,strId_Cubo,x_cubo,y_cubo,int_Z,null,intId_Article,'',contId_Estanterias); - SET intnumcubosocup=intnumcubosocup+1; - END WHILE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ubicator_ordenacion` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ubicator_ordenacion`(date DATE,boolORDALFA TINYINT(1), intWAREHOUSE INT,strFILTRO NVARCHAR(255), boolESAPILABLE TINYINT(1),boolESABIERTO TINYINT(1),intCmNichoExtra SMALLINT,inEstanteria SMALLINT,strOrdenacion varchar(255)) -BEGIN --- Inicializo variables --- boolESABIERTO --> permite apilar las cajas de diferentes articulos (cerrada) para aprovechar el espacio. -DECLARE intPOSX,intPOSY,intPOSZ,intSUMAH,intCMNICHO_EXTRA INT DEFAULT 0; -DECLARE intId_Estanterias,intW,intD,intId_Baldas,intH,intEtiquetas, - intX,intY,intZ,ReturnX,ReturnY,ReturnZ,Cantidad,intId_Baldas_aux INT DEFAULT 0; -DECLARE strId_Cubo VARCHAR(10) DEFAULT '---'; -DECLARE intId_Article,Id_Article_aux,alturabalda,intZ_aux INT DEFAULT 0; -DECLARE contId_Estanterias INT DEFAULT 1; -DECLARE strmodelo VARCHAR(255) DEFAULT '---'; -DECLARE done BIT DEFAULT 0; -DECLARE strArticle VARCHAR(50); -DECLARE boolCabeCaja,boolPasarZ,boolPasarX,boolNoNextRecord,fin BOOLEAN DEFAULT FALSE; -DECLARE intMedida,intX_ant,intY_ant,IntZ_ant INT(10) DEFAULT 0; - --- ejemplo: call ubicator_ordenacion(CURDATE(),false,1,'tipo_id = 2',TRUE,FALSE,2,1) - --- Declaro el cursor para leer las estanterias y las baldas ordenadas por las baldas. (La primera es la de arriba). -DECLARE cursor_estanterias CURSOR FOR SELECT Id_Estanterias,w,d,modelo,Id_Baldas,h FROM Estanterias - INNER JOIN Baldas USING (Id_Estanterias) WHERE Id_Estanterias=inEstanteria ORDER BY Id_Estanterias,Id_Baldas; - --- Declaro el cursor para leer el recorset de los cubos a colocar en las estanterias obteniendo las variables X,Y,Z del cubo. -DECLARE cursor_ubicator CURSOR FOR SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,Z,Article,Medida FROM ubicator_stock; - -- Creo la tabla temporal donde devuelvo la ordenación de las cajas. - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; -- handler para el cursor de las estanterias y baldas - -DROP TEMPORARY TABLE IF EXISTS Ubicator_Cajas; -/* - CREATE TEMPORARY TABLE IF NOT EXISTS Ubicator_Cajas (Id_Estanterias INT,Id_Baldas SMALLINT,modelo varchar(255), - W SMALLINT,D SMALLINT,H SMALLINT,Id_Cubo VARCHAR(10),X SMALLINT,Y SMALLINT,Z SMALLINT,Medida SMALLINT,Id_Article INT(11),Article varchar(50),NumEstanterias SMALLINT); -*/ - - CREATE TEMPORARY TABLE IF NOT EXISTS Ubicator_Cajas(Id_Estanterias INT,Id_Baldas SMALLINT,modelo varchar(255), - W SMALLINT,D SMALLINT,H SMALLINT,Id_Cubo VARCHAR(10),X SMALLINT,Y SMALLINT,Z SMALLINT,Medida SMALLINT, - Id_Article INT(11),Article varchar(50),NumEstanterias SMALLINT,NumEtiquetas INT,POSX INT (11),POSY INT(11), - POSZ INT(11),Id_Article_aux int(11)); - --- Creo la tabla temporal donde voy a insertar las cajas que no caben en las estanterias. -DROP TEMPORARY TABLE IF EXISTS Ubicator_CajasNoCaben; -CREATE TEMPORARY TABLE IF NOT EXISTS Ubicator_CajasNoCaben (Id_Cubo VARCHAR(10),Id_Estanteria SMALLINT); - -CALL ubicator (intWAREHOUSE,date,strFILTRO); -- Ejecuto el procedimiento de stock para recorrer los articulos con las cajas. - -DROP TEMPORARY TABLE IF EXISTS ubicator_stock; - -SET @SQL=CONCAT('CREATE TEMPORARY TABLE IF NOT EXISTS ubicator_stock SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,IF(Z=0,Medida,Z) Z,Article,Medida,IF(LOWER(Article) like "%mix%",1,0) AS MIX FROM tmp_ubicator_stock - ORDER BY MIX,',strOrdenacion); - -PREPARE stmt1 FROM @SQL; -EXECUTE stmt1; -DEALLOCATE PREPARE stmt1; - - -- IF (boolORDALFA) THEN - -- CREATE TEMPORARY TABLE IF NOT EXISTS ubicator_stock SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,IF(Z=0,Medida,Z) Z,Article,Medida FROM tmp_ubicator_stock - -- ORDER BY Article,Medida; - -- ELSE - -- CREATE TEMPORARY TABLE IF NOT EXISTS ubicator_stock SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,IF(Z=0,Medida,Z) Z,Article,Medida FROM tmp_ubicator_stock - -- ORDER BY Id_Article; - -- END IF; - --- Open Recordsets -OPEN cursor_estanterias; -OPEN cursor_ubicator; - -REPEAT - FETCH cursor_estanterias INTO intId_Estanterias,intW,intD,strmodelo,intId_Baldas,intH; - - IF (done) THEN -- Si llega a la ultima balda, empieza de nuevo. - CLOSE cursor_estanterias; - SET done=FALSE; - OPEN cursor_estanterias; - SET contId_Estanterias=contId_Estanterias+1; - FETCH cursor_estanterias INTO intId_Estanterias,intW,intD,strmodelo,intId_Baldas,intH; - END IF; - - -- Obtengo la altura absoluta de la balda. - SELECT CASE WHEN (SUM(H)>=0) THEN SUM(H) ELSE 0 END As suma INTO intSUMAH - FROM Baldas WHERE Id_Estanterias=intId_Estanterias and Baldas.Id_Baldas>intId_Baldas; - - SELECT H INTO alturabalda - FROM Baldas WHERE Id_Estanterias=intId_Estanterias and Baldas.Id_Baldas=intId_Baldas; - - SET intPOSX=0,intPOSY=0,intPOSZ=0,intId_Baldas_aux=0; - - ITERACION:WHILE NOT done DO - IF (NOT boolNoNextRecord) THEN - FETCH cursor_ubicator INTO strId_Cubo,intEtiquetas,intId_Article,intX,intY,intZ,strArticle,intMedida; - IF (DONE) THEN - LEAVE ITERACION; - END IF; - SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,Z,Article,Medida FROM ubicator_stock ORDER BY Id_Article; - SET Cantidad=0; - END IF; - -- SET Medida=intZ; - -- 1. Compruebo que cabe la caja en la estanteria - - SELECT ubicator_cabecaja(intX,intY,intZ,intW,intD,intH) INTO boolCabeCaja; - IF (NOT boolCabeCaja) THEN -- Compruebo si la caja cabe en la estanteria sino la coloco en una tabla temporal. - INSERT INTO Ubicator_CajasNoCaben (Id_Cubo,Id_Estanteria) VALUES (strId_Cubo,intId_Estanterias); - SET Id_Article_aux=intId_Article,boolNoNextRecord=FALSE; - ITERATE ITERACION; - END IF; - - SET boolPasarX=FALSE,boolPasarZ=FALSE; - -- Inicializo el contador - REPEAT - SET Cantidad=Cantidad+1; -- Incremento el contador en 1 - IF (intId_Baldas_aux<>intId_Baldas) THEN - SET intId_Baldas_aux=intId_Baldas; - SET intPOSX=0,intPOSY=0,intPOSZ=0; - END IF; - IF (boolESAPILABLE AND intPOSZ>0 AND intZ>0) THEN -- Es Apilable - IF (boolESABIERTO) THEN -- abierto - -- SET intPOSX=intPOSX+intCmNichoExtra,intPOSZ=0,intPOSY=0,Id_Article_aux=intId_Article; - IF (intId_Article=Id_Article_aux) THEN -- mismo articulo - SET boolPasarX=FALSE,boolPasarZ=TRUE; - SET intPOSX=intPOSX-intX; - ELSE -- distinto articulo - SET boolPasarX=TRUE,boolPasarZ=TRUE; - SET intPOSY=intY,intPOSZ=intZ; - SET Id_Article_aux=intId_Article; - SET intPOSX=intPOSX+intCmNichoExtra; - END IF; - ELSE -- cerrado - IF ((intZ=intZ_ant) AND (intY=intY_ant) AND (intX=intX_ant)) THEN -- tienen que ser del mismo tamaño - SET intPOSX=intPOSX-intX; - SET boolPasarX=FALSE,boolPasarZ=FALSE; - ELSE - CALL ubicator_calcularhuecosvacios (alturabalda,ReturnX,ReturnY,intZ_aux,intId_Estanterias,intId_Baldas,contId_Estanterias); -- Calculo las cajas vacias - SET intPOSY=intY,intPOSZ=intZ; - SET boolPasarX=TRUE,boolPasarZ=TRUE; - SET intPOSX=intPOSX+intCmNichoExtra; - END IF; -- article - END IF; - ELSE -- No apilable or posz<>0 - IF (NOT boolESAPILABLE AND boolESABIERTO) THEN - SET boolPasarX=FALSE,boolPasarZ=FALSE; - -- @@@ cambio abierto no apilable - SET intPOSZ=0; -- no se puede subir en altura - IF (intId_Article<>Id_Article_aux and Id_Article_aux<>0) THEN -- cambio @@@vicente, añado id_Article_aux<>0 - SET intPOSY=0; - END IF; - ELSE - SET boolPasarX=TRUE,boolPasarZ=TRUE; - SET intPOSY=intY,intPOSZ=intZ; - END IF; - - -- @@@@ cambio - IF (intPOSX>0) THEN -- SI ES EL PRIMER ELEMENTO (X=0) NO LE INCREMENTE LOS CM EXTRA DEL NICHO si la profundidad es menor no lo incrementa - SET intPOSX=intPOSX+intCmNichoExtra; - END IF; - END IF; -- apilable - - Condicional:loop - IF (NOT boolPasarX) THEN - IF (NOT boolPasarZ) THEN - IF (intD-intPOSY>intY) THEN -- cabe de profundo - SET intPOSY=intPOSY+intY; - -- @@@@ULTIMO CAMBIO - IF (intPOSX>0) and (intId_Article=Id_Article_aux) THEN - IF (intPOSX-intX-intCmNichoExtra<0) THEN - SET intPOSX=0,boolNoNextRecord=TRUE,Cantidad=Cantidad-1; - LEAVE ITERACION; - END IF; - SET intPOSX=intPOSX-intX-intCmNichoExtra; -- cambio @@@vicente quito descomentando - END IF; - -- @@@@ fin ultimo cambio - ELSE - SET intPOSY=intY; - END IF; - END IF; -- boolpasarz (depth) - - IF (intH-intPOSZ>intZ) THEN - SET intPOSZ=intPOSZ+intZ; - ELSE - IF (intD-intPOSY>intY) THEN - SET boolPasarZ=FALSE,boolPasarX=FALSE,intPOSZ=intZ; - ITERATE Condicional; - END IF; - SET intPOSZ=intZ; - SET intPOSY=intY; - SET intPOSX=intPOSX+intX+intCmNichoExtra; - END IF; - END IF; -- boolpasarx - - IF (intW-intPOSX>intX) THEN - SET intPOSX=intPOSX+intX; - ELSE - SET intPOSX=0,boolNoNextRecord=TRUE,Cantidad=Cantidad-1; - LEAVE ITERACION; - END IF; - LEAVE Condicional; - END loop Condicional; - - SET ReturnX=intPOSX-intX; -- Anchura absoluta x del artículo - SET ReturnZ=intSUMAH+intPOSZ-intZ; -- Altura absoluta del cubo - SET ReturnY=intPOSY-intY; -- Profundidad absoluta del artículo - - SET boolPasarZ=FALSE,boolPasarX=FALSE; - - /* - INSERT INTO Ubicator_Cajas (Id_Estanterias,Id_Baldas,modelo,W ,D,H ,Id_Cubo,X,Y,Z,Medida,Id_Article,Article,NumEstanterias) - VALUES (intId_Estanterias,intId_Baldas,strmodelo,ReturnX ,ReturnY,ReturnZ ,strId_Cubo,intX,intY,intZ,intMedida,intId_Article,strArticle,contId_Estanterias); - */ - - INSERT INTO Ubicator_Cajas (Id_Estanterias,Id_Baldas,modelo,W ,D,H ,Id_Cubo,X,Y,Z,Medida,Id_Article,Article,NumEstanterias, - NumEtiquetas,POSX,POSY,POSZ,Id_Article_aux) - VALUES (intId_Estanterias,intId_Baldas,strmodelo,ReturnX ,ReturnY,ReturnZ ,strId_Cubo,intX,intY,intZ,intMedida,intId_Article,strArticle,contId_Estanterias, - intEtiquetas,intPOSX,intPOSY,intPOSZ,Id_Article_aux); - - SET Id_Article_aux=intId_Article,intZ_aux=intZ,boolNoNextRecord=FALSE; - -- Cambio - SET intZ_ant=intZ,intY_ant=intY,intX_ant=intX; - UNTIL Cantidad=intEtiquetas END REPEAT; - END WHILE ITERACION; - - IF (done) THEN - SET fin=TRUE; - END IF; -UNTIL fin END REPEAT; -CLOSE cursor_ubicator; -CLOSE cursor_estanterias; - --- select * from Ubicator_Cajas; --- select * from ubicator_stock; --- select * from Ubicator_CajasNoCaben; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ubicator_ordenacion_distrib` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ubicator_ordenacion_distrib`(date DATE,boolORDALFA TINYINT(1), intWAREHOUSE INT,strFILTRO NVARCHAR(255), boolESAPILABLE TINYINT(1),boolESABIERTO TINYINT(1),intCmNichoExtra SMALLINT,inEstant_distrib SMALLINT) -BEGIN --- Inicializo variables --- boolESABIERTO --> permite apilar las cajas de diferentes articulos (cerrada) para aprovechar el espacio. -DECLARE intPOSX,intPOSY,intPOSZ,intSUMAH,intCMNICHO_EXTRA INT DEFAULT 0; -DECLARE intId_Estanterias,intW,intD,intId_Baldas,intH,intEtiquetas, - intX,intY,intZ,ReturnX,ReturnY,ReturnZ,Cantidad,intId_Baldas_aux INT DEFAULT 0; -DECLARE strId_Cubo VARCHAR(10) DEFAULT '---'; -DECLARE intId_Article,Id_Article_aux,alturabalda,intZ_aux INT DEFAULT 0; -DECLARE contId_Estanterias INT DEFAULT 0; -DECLARE strmodelo VARCHAR(255) DEFAULT '---'; -DECLARE done BIT DEFAULT 0; -DECLARE strArticle VARCHAR(50); -DECLARE boolCabeCaja,boolPasarZ,boolPasarX,boolNoNextRecord,fin BOOLEAN DEFAULT FALSE; -DECLARE intMedida,intX_ant,intY_ant,IntZ_ant ,intposinicial,intposfinal,auxintId_Estanterias,auxintposinicial,auxintposfinal,intnumdistrib,nestanterias INT(11) DEFAULT 0; - --- ejemplo: call ubicator_ordenacion(CURDATE(),false,1,'tipo_id = 2',TRUE,FALSE,2,1) - --- Declaro el cursor para leer las estanterias y las baldas ordenadas por las baldas. (La primera es la de arriba). -DECLARE cursor_estanterias CURSOR FOR SELECT Id_Estanterias,w,d,modelo,Id_Baldas,h,posinicial,posfinal FROM Estanterias - INNER JOIN Baldas USING (Id_Estanterias) - INNER JOIN Estanterias_distri using (Id_Estanterias) - WHERE IdEstanterias_distri=inEstant_distrib - -- AND Id_Estanterias>nestanterias - AND posinicial>auxintposinicial - ORDER BY posinicial; - --- Declaro el cursor para leer el recorset de los cubos a colocar en las estanterias obteniendo las variables X,Y,Z del cubo. -DECLARE cursor_ubicator CURSOR FOR SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,Z,Article,Medida FROM ubicator_stock; - -- Creo la tabla temporal donde devuelvo la ordenación de las cajas. - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; -- handler para el cursor de las estanterias y baldas - -DROP TEMPORARY TABLE IF EXISTS Ubicator_Cajas; -CREATE TEMPORARY TABLE IF NOT EXISTS Ubicator_Cajas (Id_Estanterias INT,Id_Baldas SMALLINT,modelo varchar(255), -W SMALLINT,D SMALLINT,H SMALLINT,Id_Cubo VARCHAR(10),X SMALLINT,Y SMALLINT,Z SMALLINT,Medida SMALLINT,Id_Article INT(11),Article varchar(50),NumEstanterias SMALLINT); - - /* - CREATE TEMPORARY TABLE IF NOT EXISTS Ubicator_Cajas(Id_Estanterias INT,Id_Baldas SMALLINT,modelo varchar(255), - W SMALLINT,D SMALLINT,H SMALLINT,Id_Cubo VARCHAR(10),X SMALLINT,Y SMALLINT,Z SMALLINT,Medida SMALLINT, - Id_Article INT(11),Article varchar(50),NumEstanterias SMALLINT,NumEtiquetas INT,POSX INT (11),POSY INT(11), - POSZ INT(11),Id_Article_aux int(11)); - */ - --- Creo la tabla temporal donde voy a insertar las cajas que no caben en las estanterias. -DROP TEMPORARY TABLE IF EXISTS Ubicator_CajasNoCaben; -CREATE TEMPORARY TABLE IF NOT EXISTS Ubicator_CajasNoCaben (Id_Cubo VARCHAR(10),Id_Estanteria SMALLINT); - -CALL ubicator (intWAREHOUSE,date,strFILTRO); -- Ejecuto el procedimiento de stock para recorrer los articulos con las cajas. - -DROP TEMPORARY TABLE IF EXISTS ubicator_stock; -IF (boolORDALFA) THEN - CREATE TEMPORARY TABLE IF NOT EXISTS ubicator_stock SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,Z,Article,Medida FROM tmp_ubicator_stock - ORDER BY Article,Medida; -ELSE - CREATE TEMPORARY TABLE IF NOT EXISTS ubicator_stock SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,Z,Article,Medida FROM tmp_ubicator_stock - ORDER BY Id_Article; - END IF; - --- Open Recordsets -OPEN cursor_estanterias; -OPEN cursor_ubicator; -SET contId_Estanterias=0; -REPEAT - FETCH cursor_estanterias INTO intId_Estanterias,intW,intD,strmodelo,intId_Baldas,intH,intposinicial,intposfinal; - - IF (contId_Estanterias=0) THEN - SET contId_Estanterias=1; - SET auxintId_Estanterias=intId_Estanterias; - SELECT (intposfinal-intposinicial+1)*Id_Baldas into auxintposfinal from Baldas where Id_Estanterias=intId_Estanterias order by Id_Baldas DESC limit 1; - END IF; - - IF (done) THEN - SELECT DISTINCT posinicial-1 INTO auxintposinicial - FROM Estanterias_distri - WHERE Id_Estanterias=auxintId_Estanterias; - -- SET nestanterias=auxintId_Estanterias-1; - - CLOSE cursor_estanterias; - OPEN cursor_estanterias; - FETCH cursor_estanterias INTO intId_Estanterias,intW,intD,strmodelo,intId_Baldas,intH,intposinicial,intposfinal; - END IF; - - IF (auxintId_Estanterias<>IFNULL(intId_Estanterias,auxintId_Estanterias)) THEN - SET done=TRUE; - END IF; - SET intnumdistrib=intnumdistrib+1; - - IF (done) THEN -- Si llega a la ultima balda, empieza de nuevo. - IF (intnumdistrib=0) THEN SUM(H) ELSE 0 END As suma INTO intSUMAH - FROM Baldas WHERE Id_Estanterias=intId_Estanterias and Baldas.Id_Baldas>intId_Baldas; - - SELECT H INTO alturabalda - FROM Baldas WHERE Id_Estanterias=intId_Estanterias and Baldas.Id_Baldas=intId_Baldas; - - SET intPOSX=0,intPOSY=0,intPOSZ=0,intId_Baldas_aux=0; - - ITERACION:WHILE NOT done DO - IF (NOT boolNoNextRecord) THEN - FETCH cursor_ubicator INTO strId_Cubo,intEtiquetas,intId_Article,intX,intY,intZ,strArticle,intMedida; - IF (DONE) THEN - LEAVE ITERACION; - END IF; - SELECT Id_Cubo,Etiquetas,Id_Article,X,Y,Z,Article,Medida FROM ubicator_stock ORDER BY Id_Article; - SET Cantidad=0; - END IF; - -- SET Medida=intZ; - -- 1. Compruebo que cabe la caja en la estanteria - - SELECT ubicator_cabecaja(intX,intY,intZ,intW,intD,intH) INTO boolCabeCaja; - IF (NOT boolCabeCaja) THEN -- Compruebo si la caja cabe en la estanteria sino la coloco en una tabla temporal. - INSERT INTO Ubicator_CajasNoCaben (Id_Cubo,Id_Estanteria) VALUES (strId_Cubo,intId_Estanterias); - SET Id_Article_aux=intId_Article,boolNoNextRecord=FALSE; - ITERATE ITERACION; - END IF; - - SET boolPasarX=FALSE,boolPasarZ=FALSE; - -- Inicializo el contador - REPEAT - SET Cantidad=Cantidad+1; -- Incremento el contador en 1 - IF (intId_Baldas_aux<>intId_Baldas) THEN - SET intId_Baldas_aux=intId_Baldas; - SET intPOSX=0,intPOSY=0,intPOSZ=0; - END IF; - IF (boolESAPILABLE AND intPOSZ>0 AND intZ>0) THEN -- Es Apilable - IF (boolESABIERTO) THEN -- abierto - -- SET intPOSX=intPOSX+intCmNichoExtra,intPOSZ=0,intPOSY=0,Id_Article_aux=intId_Article; - IF (intId_Article=Id_Article_aux) THEN -- mismo articulo - SET boolPasarX=FALSE,boolPasarZ=TRUE; - SET intPOSX=intPOSX-intX; - ELSE -- distinto articulo - SET boolPasarX=TRUE,boolPasarZ=TRUE; - SET intPOSY=intY,intPOSZ=intZ; - SET Id_Article_aux=intId_Article; - SET intPOSX=intPOSX+intCmNichoExtra; - END IF; - ELSE -- cerrado - IF ((intZ=intZ_ant) AND (intY=intY_ant) AND (intX=intX_ant)) THEN -- tienen que ser del mismo tamaño - SET intPOSX=intPOSX-intX; - SET boolPasarX=FALSE,boolPasarZ=FALSE; - ELSE - CALL ubicator_calcularhuecosvacios (alturabalda,ReturnX,ReturnY,intZ_aux,intId_Estanterias,intId_Baldas,contId_Estanterias); -- Calculo las cajas vacias - SET intPOSY=intY,intPOSZ=intZ; - SET boolPasarX=TRUE,boolPasarZ=TRUE; - SET intPOSX=intPOSX+intCmNichoExtra; - END IF; -- article - END IF; - ELSE -- No apilable or posz<>0 - IF (NOT boolESAPILABLE AND boolESABIERTO) THEN - SET boolPasarX=FALSE,boolPasarZ=FALSE; - -- @@@ cambio abierto no apilable - SET intPOSZ=0; -- no se puede subir en altura - ELSE - SET boolPasarX=TRUE,boolPasarZ=TRUE; - SET intPOSY=intY,intPOSZ=intZ; - END IF; - - IF (intPOSX>0) THEN -- SI ES EL PRIMER ELEMENTO (X=0) NO LE INCREMENTE LOS CM EXTRA DEL NICHO - SET intPOSX=intPOSX+intCmNichoExtra; - END IF; - END IF; -- apilable - - Condicional:loop - IF (NOT boolPasarX) THEN - IF (NOT boolPasarZ) THEN - IF (intD-intPOSY>intY) THEN -- cabe de profundo - SET intPOSY=intPOSY+intY; - ELSE - SET intPOSY=intY; - END IF; - END IF; -- boolpasarz (depth) - - IF (intH-intPOSZ>intZ) THEN - SET intPOSZ=intPOSZ+intZ; - ELSE - IF (intD-intPOSY>intY) THEN - SET boolPasarZ=FALSE,boolPasarX=FALSE,intPOSZ=intZ; - ITERATE Condicional; - END IF; - SET intPOSZ=intZ; - SET intPOSY=intY, intPOSX=intPOSX+intX+intCmNichoExtra; - END IF; - END IF; -- boolpasarx - - IF (intW-intPOSX>intX) THEN - SET intPOSX=intPOSX+intX; - ELSE - SET intPOSX=0,boolNoNextRecord=TRUE,Cantidad=Cantidad-1; - LEAVE ITERACION; - END IF; - LEAVE Condicional; - END loop Condicional; - - SET ReturnX=intPOSX-intX; -- Anchura absoluta x del artículo - SET ReturnZ=intSUMAH+intPOSZ-intZ; -- Altura absoluta del cubo - SET ReturnY=intPOSY-intY; -- Profundidad absoluta del artículo - - SET boolPasarZ=FALSE,boolPasarX=FALSE; - - INSERT INTO Ubicator_Cajas (Id_Estanterias,Id_Baldas,modelo,W ,D,H ,Id_Cubo,X,Y,Z,Medida,Id_Article,Article,NumEstanterias) - VALUES (intId_Estanterias,intId_Baldas,strmodelo,ReturnX ,ReturnY,ReturnZ ,strId_Cubo,intX,intY,intZ,intMedida,intId_Article,strArticle,contId_Estanterias); - /* - INSERT INTO Ubicator_Cajas (Id_Estanterias,Id_Baldas,modelo,W ,D,H ,Id_Cubo,X,Y,Z,Medida,Id_Article,Article,NumEstanterias, - NumEtiquetas,POSX,POSY,POSZ,Id_Article_aux) - VALUES (intId_Estanterias,intId_Baldas,strmodelo,ReturnX ,ReturnY,ReturnZ ,strId_Cubo,intX,intY,intZ,intMedida,intId_Article,strArticle,contId_Estanterias, - intEtiquetas,intPOSX,intPOSY,intPOSZ,Id_Article_aux); - */ - SET Id_Article_aux=intId_Article,intZ_aux=intZ,boolNoNextRecord=FALSE; - -- Cambio - SET intZ_ant=intZ,intY_ant=intY,intX_ant=intX; - UNTIL Cantidad=intEtiquetas END REPEAT; - END WHILE ITERACION; - - IF (done) THEN - SET fin=TRUE; - END IF; - -UNTIL fin END REPEAT; -CLOSE cursor_ubicator; -CLOSE cursor_estanterias; - --- select * from Ubicator_Cajas; --- select * from ubicator_stock; --- select * from Ubicator_CajasNoCaben; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ubicator_test` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ubicator_test`(IN i_wh TINYINT, IN d_fecha DATE,IN filtro VARCHAR(255)) -BEGIN - - - DECLARE date_inv DATE; - - -DROP TEMPORARY TABLE IF EXISTS stock_actual; -DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_ubicator_stock; - - -SELECT FechaInventario INTO date_inv - FROM tblContadores LIMIT 1; - - -CREATE TEMPORARY TABLE stock_actual -SELECT Id_Article article_id,SUM(Cantidad) amount FROM ( - SELECT Id_Article,Cantidad - FROM Compres c - JOIN Entradas e USING(Id_Entrada) - JOIN travel t ON t.id = e.travel_id - WHERE landing BETWEEN date_inv AND d_fecha - AND warehouse_id = i_wh AND NOT Redada - - UNION ALL - - SELECT Id_Article,-Cantidad - FROM Compres c - JOIN Entradas e USING(Id_Entrada) - JOIN travel t ON t.id = e.travel_id - WHERE shipment BETWEEN date_inv AND timestampadd(DAY,-1,d_fecha) - AND warehouse_id_out = i_wh AND NOT Redada - - UNION ALL - - SELECT Id_Article, -Cantidad - FROM Movimientos m - JOIN Tickets t USING(Id_Ticket) - WHERE Fecha BETWEEN date_inv AND timestampadd(DAY,-1,d_fecha) - AND warehouse_id = i_wh - - - -) t GROUP BY article_id; - -/* -SELECT * from stock_actual;*/ - --- TEMPORARY -CALL util.exec (sql_printf(' - CREATE TEMPORARY TABLE IF NOT EXISTS vn2008.tmp_ubicator_stock AS - SELECT A.Id_Article,A.Article, T.Id_Cubo,IF(Z > 0,Z,0) as z,x,y, - CEIL(S.Suma/T.grouping) as etiquetas,A.Medida,A.Nicho - FROM vn2008.Articles A - INNER JOIN - (SELECT article_id, amount as SUMA - FROM vn2008.stock_actual - WHERE amount > 0 - ) as S ON S.article_id = A.Id_Article - LEFT JOIN ( - SELECT * FROM ( - SELECT c.Id_Article item_id, c.Id_Compra id, c.Id_Cubo,c.grouping - FROM vn2008.Compres c INNER JOIN vn2008.Entradas e USING(Id_Entrada) - INNER JOIN vn2008.travel t ON t.id = e.travel_id - WHERE t.landing BETWEEN vn2008.date_inv() AND CURDATE() - AND c.Novincular = FALSE - AND c.Tarifa2 >= 0 AND Id_Cubo IS NOT NULL - ORDER BY 1 = t.warehouse_id DESC, t.landing DESC - ) t1 GROUP BY item_id - ) as T ON T.item_id = A.Id_Article - LEFT JOIN vn2008.Cubos C USING(Id_Cubo) - WHERE %s AND CEIL(S.Suma/T.grouping) > 0',filtro)); - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `unary_delete` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `unary_delete`(v_node INT, v_delete bool) -BEGIN -/** - * Borra un nodo. Se puede indicar si se quieren mantener los hijos. - * En este caso los hijos pasan al padre del nodo. - * Si no tiene padre, los hijos pasaran a ser padres. - * - * @v_node: Nodo que se quiere borrar. - * @v_delete: Se indica si se borran los nodos. - **/ - - DECLARE v_parent INT; - - SELECT parent - INTO v_parent - FROM unary - WHERE id = v_node; - - IF(v_delete = FALSE) THEN - UPDATE unary - SET parent = v_parent - WHERE parent = v_node; - END IF; - - DELETE FROM unary - WHERE id = v_node; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `unary_insert` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `unary_insert`(OUT v_unary INT, v_parent INT) -BEGIN - - /** - * Inserta un nuevo nodo. Se puede indicar el padre. - * - * @v_parent: Nodo padre. - * @v_unary: Id del nuevo nodo. - **/ - - INSERT INTO unary(parent) VALUES(v_parent); - - SELECT last_insert_id() INTO v_unary; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `unary_leaves` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `unary_leaves`(v_top INT) -BEGIN -/** - * A partir de un nodo devuelve todos sus descendientes. - * - * @table tmp.tree Tabla con los ids de los nodos descendientes; - **/ - DECLARE v_count INT; - DECLARE v_parent INT; - DECLARE v_depth INT DEFAULT 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.tree; - CREATE TEMPORARY TABLE tmp.tree - (INDEX (id)) - ENGINE = MEMORY - SELECT v_top id, v_parent parent, v_depth depth; - - DROP TEMPORARY TABLE IF EXISTS tmp.parent; - CREATE TEMPORARY TABLE tmp.parent - ENGINE = MEMORY - SELECT v_top id; - - l: LOOP - - SET v_depth = v_depth + 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.child; - CREATE TEMPORARY TABLE tmp.child - ENGINE = MEMORY - SELECT c.`id`, c.parent - FROM `unary` c - JOIN tmp.parent p ON c.`parent` = p.id; - - DROP TEMPORARY TABLE tmp.parent; - CREATE TEMPORARY TABLE tmp.parent - ENGINE = MEMORY - SELECT c.id, c.parent - FROM tmp.child c - LEFT JOIN tmp.tree t ON t.id = c.id - WHERE t.id IS NULL; - - INSERT INTO tmp.tree - SELECT id, parent, v_depth FROM tmp.parent; - - SELECT COUNT(*) INTO v_count - FROM tmp.parent; - - IF v_count = 0 THEN - LEAVE l; - END IF; - END LOOP; - - DROP TEMPORARY TABLE - tmp.parent, - tmp.child; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `unary_scan_ident` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `unary_scan_ident`(v_top INT, v_space INT) -BEGIN -/** - * A partir de un nodo devuelve el id y el nombre del nodod y sus hijos. - * El nombre viene identado segun el numero de espacios multiplicado por la profundiad del nodo. - * - * v_top: Id del nodo padre. - * v_space: Spacios a dejar al identar, - * @table tmp.tree_ident Tabla con los ids de los nodos descendientes y su nombre identado; - **/ - - DROP TEMPORARY TABLE IF EXISTS tmp.tree_ident; - CALL tree_leaves(v_top); - - CREATE TEMPORARY TABLE tmp.tree_ident - ENGINE = MEMORY - SELECT t.id, - CONCAT( REPEAT(REPEAT(" ",v_space), t.depth), sp.name) AS name - FROM tmp.tree t - INNER JOIN unary_scan sp - ON t.id = sp.id; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `unary_scan_insert` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `unary_scan_insert`(v_name VARCHAR(45), v_parent INT, v_type VARCHAR(45)) -BEGIN - - /** - * Inserta un nuevo nodo de tipo unary_scan. Se puede indicar el padre. - * - * @v_name: Nombre del nodo. - * @v_parent: Nodo padre. - * @v_type: Tipo del nodo a crear. - **/ - - DECLARE v_unary INT; - - CALL unary_insert(v_unary, v_parent); - - INSERT INTO unary_scan(name, unary_id, type) VALUES(v_name, v_unary, v_type); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `unary_tops` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `unary_tops`() -BEGIN -/** - * Devuelve todos los nodos que no tienen padre. - * - * @table tmp.tree Tabla con los ids de los nodos que no tienen padre; - **/ - - DROP TEMPORARY TABLE IF EXISTS tmp.tree; - CREATE TEMPORARY TABLE tmp.tree - ENGINE = MEMORY - SELECT s.`unary_id` AS id, s.name, s.odbc_date, s.type - FROM `unary_scan` s - INNER JOIN `unary` u ON s.unary_id = u.id - WHERE u.parent IS NULL; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `unary_update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `unary_update`(v_node INT, v_new_parent INT, v_move bool) -BEGIN -/** - * Cambia el padre de un nodo. Se puede indicar si se quieren mover los hijos. - * En este caso los hijos pasan al padre del nodo. - * Si no tiene padre, los hijos pasaran a ser padres. - * - * @v_node: Nodo que se quiere mover. - * @v_new_parent: Padre al que se quiere mover el nodo. - * @v_move: Se indica si se mueven los nodos. - **/ - - DECLARE v_parent INT; - - SELECT parent - INTO v_parent - FROM unary - WHERE id = v_node; - - IF(v_move = TRUE) THEN - UPDATE unary - SET parent = v_parent - WHERE parent = v_node; - END IF; - - UPDATE unary - SET parent = v_new_parent - WHERE id = v_node; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `valor_faltas` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `valor_faltas`(IN intReino_id INT,IN dateDesde DATE,IN dateHasta DATE,IN wh INT) -BEGIN - - DROP TEMPORARY TABLE IF EXISTS item; - - CREATE TEMPORARY TABLE item - SELECT Id_Article id,Id_Movimiento,Cantidad,Id_Tipo,Fecha - FROM Tickets t - JOIN Movimientos m USING (Id_Ticket) - JOIN Articles a USING (Id_Article) - JOIN Tipos tip USING (tipo_id) - WHERE - Id_Cliente = 400 - AND Fecha BETWEEN dateDesde AND dateHasta - AND reino_id = 4; - - CREATE INDEX pk USING HASH ON item (id); - - CALL item_buy (wh, dateHasta); - CALL item_buy_price (1240,dateDesde,wh); - -SELECT *,Cantidad * price as total FROM item; - -DROP TEMPORARY TABLE item; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `valuatedInventory` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `valuatedInventory`(IN vDate DATE, IN vIsItemised BOOLEAN) -BEGIN - - DECLARE vLastInventoryDate DATE; - - SELECT landing INTO vLastInventoryDate - FROM travel TR - INNER JOIN Entradas E ON E.travel_id = TR.id - WHERE landing <= vDate - AND E.Id_Proveedor = 4 - ORDER BY landing DESC - LIMIT 1; - - DROP TEMPORARY TABLE IF EXISTS inv; - - CREATE TEMPORARY TABLE inv - (warehouseFk SMALLINT, - itemFk BIGINT, - amount INT, - cost DOUBLE DEFAULT 0, - total DOUBLE DEFAULT 0) - ENGINE = MEMORY; - - ALTER TABLE inv ADD PRIMARY KEY USING HASH (warehouseFk, itemFk); - - -- Valor del inventario - INSERT INTO inv(warehouseFk, itemFk, amount) - SELECT TR.warehouse_id, C.Id_Article, C.Cantidad - FROM Compres C - JOIN Articles A USING(Id_Article) - JOIN Entradas E USING (Id_Entrada) - JOIN travel TR ON TR.id = E.travel_id - JOIN Tipos t USING(tipo_id) - JOIN warehouse w ON w.id = TR.warehouse_id - WHERE landing = vLastInventoryDate - AND E.Id_Proveedor = 4 - AND reino_id NOT IN (7) - ON DUPLICATE KEY UPDATE inv.amount = inv.amount + C.Cantidad; - - -- Añadimos compras - INSERT INTO inv(warehouseFk, itemFk, amount) - SELECT TR.warehouse_id, C.Id_Article, C.Cantidad - FROM Compres C - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN Tipos t USING(tipo_id) - INNER JOIN warehouse w ON w.id = TR.warehouse_id - WHERE landing BETWEEN vLastInventoryDate AND vDate - AND NOT redada - AND NOT w.fuente - AND reino_id NOT IN (7) - AND t.inventory - AND E.Id_Proveedor <> 4 - ON DUPLICATE KEY UPDATE inv.amount = inv.amount + C.Cantidad; - - -- Restamos salidas - INSERT INTO inv(warehouseFk, itemFk, amount) - SELECT TR.warehouse_id_out, C.Id_Article, - C.Cantidad - FROM Compres C - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Entradas E USING (Id_Entrada) - INNER JOIN travel TR ON TR.id = E.travel_id - INNER JOIN Tipos t USING(tipo_id) - INNER JOIN warehouse w ON w.id = warehouse_id_out - WHERE shipment BETWEEN vLastInventoryDate AND vDate - AND NOT redada - AND NOT w.fuente - AND reino_id NOT IN (7) - AND t.inventory - ON DUPLICATE KEY UPDATE inv.amount = inv.amount - C.Cantidad; - - -- Restamos ventas - INSERT INTO inv(warehouseFk, itemFk, amount) - SELECT w.id, M.Id_Article, - M.Cantidad - FROM Movimientos M - INNER JOIN Tickets T USING (Id_Ticket) - INNER JOIN Clientes C USING(Id_Cliente) - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos t USING(tipo_id) - INNER JOIN warehouse w ON w.id = warehouse_id - WHERE T.Fecha BETWEEN vLastInventoryDate AND TIMESTAMPADD(DAY, -1 ,vDate) - AND NOT w.fuente - AND reino_id NOT IN (7) - AND t.inventory - ON DUPLICATE KEY UPDATE inv.amount = inv.amount - M.Cantidad; - - -- Restamos el dia de hoy - INSERT INTO inv(warehouseFk, itemFk, amount) - SELECT w.id, M.Id_Article, - M.Cantidad - FROM Movimientos M - INNER JOIN Tickets T USING (Id_Ticket) - INNER JOIN Clientes C USING(Id_Cliente) - INNER JOIN Articles A USING(Id_Article) - INNER JOIN Tipos t USING(tipo_id) - INNER JOIN warehouse w ON w.id = warehouse_id - WHERE date(T.Fecha) = vDate - AND (vDate <> CURDATE() or (M.OK <> 0 or T.Etiquetasemitidas <> 0 )) - AND NOT w.fuente - AND reino_id NOT IN (7) - AND t.inventory - ON DUPLICATE KEY UPDATE inv.amount = inv.amount - M.Cantidad ; - - CALL item_last_buy_from_interval(NULL,vLastInventoryDate,vDate); - - UPDATE inv - JOIN tmp.item_last_buy_from_interval lb - ON inv.warehouseFk = lb.warehouse_id AND inv.itemFk = lb.item_id - JOIN Compres C ON C.Id_Compra = lb.buy_id - SET total = inv.amount * (ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0)), - cost = ifnull(C.Costefijo,0) + IFNULL(C.Embalajefijo,0) + IFNULL(C.Portefijo,0) + IFNULL(C.Comisionfija,0) - WHERE inv.amount <> 0; - - DELETE FROM inv WHERE amount IS NULL or amount = 0; - - IF vIsItemised THEN - - SELECT inv.warehouseFk, a.Id_Article, a.Article, a.Medida, inv.amount, tp.Id_Tipo, - tp.reino_id, inv.cost, cast(inv.total as decimal(10,2)) total, an.nicho - FROM inv - JOIN warehouse w on w.id = inv.warehouseFk - JOIN Articles a ON a.Id_Article = inv.itemFk - JOIN Tipos tp ON tp.tipo_id = a.tipo_id - JOIN Articles_nicho an ON an.Id_Article = a.Id_Article AND an.warehouse_id = w.id - where w.valuatedInventory - and inv.total > 0 - order by inv.total desc; - - ELSE - - SELECT w.name as Almacen, r.reino as Reino, cast(inv.total as decimal) as Euros - FROM inv - JOIN warehouse w ON w.id = inv.warehouseFk - JOIN Articles A ON A.Id_Article = inv.itemFk - JOIN Tipos t ON t.tipo_id = A.tipo_id - JOIN reinos r ON r.id = t.reino_id - WHERE w.valuatedInventory; - - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `verdecora` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `verdecora`(vDelivered DATE) -BEGIN - -DECLARE vConsigna INT DEFAULT 21025; -DECLARE vAgencia INT DEFAULT 639; - -DROP TEMPORARY TABLE IF EXISTS tmp.bionic_calc; - - CREATE TEMPORARY TABLE tmp.bionic_calc - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT Id_Article AS item_id - FROM Articles - JOIN Tipos using(tipo_id) - WHERE reino_id IN (1,5) - AND Id_Article < 170000; - -CALL vn2008.bionic_calc(vDelivered, vConsigna, vAgencia); - -SELECT - bi.item_id AS 'Ref_VN', - iv.codin, - NULL as Recomendado, - bi.available as Disponible, - CASE c.caja - WHEN 0 THEN 1 - WHEN 1 THEN c.grouping - WHEN 2 THEN c.packing - END AS 'Venta x', - c.Packing AS 'Uds/Caja', - bl.min_price as Precio, - REPLACE(bi.item,'_','') AS 'Artículo', - ita.tag1 as Caracter1, - ita.val1 as Valor1, - ita.tag2 as Caracter2, - ita.val2 as Valor2, - ita.tag3 as Caracter3, - ita.val3 as Valor3, - ita.tag4 as Caracter4, - ita.val4 as Valor4, - ita.tag5 as Caracter5, - ita.val5 as Valor5, - ita.tag6 as Caracter6, - ita.val6 as valor6 - -FROM tmp.bionic_item bi - JOIN vn.itemTagArranged ita ON ita.itemFk = bi.item_id - JOIN bi.Last_buy_id lb ON lb.Id_Article = bi.item_id - JOIN vn2008.Compres c ON c.Id_Compra = lb.Id_Compra - JOIN ( - SELECT MIN(price) min_price, item_id - FROM tmp.bionic_price - GROUP BY item_id - ) bl ON bl.item_id = bi.item_id - LEFT JOIN vn.itemVerdecora iv ON iv.itemFk = bi.item_id -WHERE lb.warehouse_id = 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 DROP PROCEDURE IF EXISTS `vips_in_a_week` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vips_in_a_week`(vCondition VARCHAR(512)) -BEGIN - CALL util.exec (CONCAT( - 'SELECT C.Id_Cliente, C.Cliente, ROUND(SUM((M.Cantidad * M.Preu) * 100 - M.Descuento) / 100, 2) as Importe - FROM vn2008.Clientes C - JOIN vn2008.Tickets T ON T.Id_Cliente = C.Id_Cliente - JOIN vn2008.Movimientos M ON M.Id_Ticket = T.Id_Ticket - JOIN vn2008.Articles A ON A.Id_Article = M.Id_Article - JOIN vn2008.Tipos TP ON A.tipo_id = TP.tipo_id - JOIN vn2008.Trabajadores TR ON TR.Id_Trabajador = TP.Id_Trabajador - WHERE ', vCondition, ' - GROUP BY Id_Cliente - HAVING Importe > 0 - ORDER BY Importe DESC' - )); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vips_in_a_week_by_client` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vips_in_a_week_by_client`(vCondition VARCHAR(512)) -BEGIN - CALL util.exec (CONCAT( - 'SELECT M.Id_Article, A.Article, A.Medida, A.Color, A.Categoria, - SUM(M.Cantidad) Cantidad, M.Preu, M.Descuento, - RED(SUM(M.Cantidad) * M.Preu * (100 - M.Descuento) / 100) as Importe - FROM vn2008.Clientes C - JOIN vn2008.Tickets T ON T.Id_Cliente = C.Id_Cliente - JOIN vn2008.Movimientos M ON M.Id_Ticket = T.Id_Ticket - JOIN vn2008.Articles A ON A.Id_Article = M.Id_Article - JOIN vn2008.Tipos TP ON A.tipo_id = TP.tipo_id - JOIN vn2008.Trabajadores TR ON TR.Id_Trabajador = TP.Id_Trabajador - WHERE ', vCondition, ' - GROUP BY M.Id_Article, A.Article, A.Medida, A.Color, A.Categoria, M.Preu, M.Descuento' - )); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `volumetricoReparto` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `volumetricoReparto`( IN IdTicket INT(11), OUT atot DOUBLE ) -BEGIN - - DECLARE ticket INT(11); - - DECLARE rutaid INT(11); - - DECLARE art INT(11); - - DECLARE ax, ay, az, atot double; - - DECLARE CUR1 CURSOR FOR SELECT a.Id_Article FROM vn2008.Movimientos m, vn2008.Articles a - WHERE m.Id_Ticket = IdTicket AND m.Id_Article = a.Id_Article ; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET @atot = 0; - - set @atot = 0; - - OPEN CUR1; - - REPEAT - - FETCH CUR1 INTO art ; - - SELECT x, y, z into ax,ay,az - FROM vn2008.Cubos cu, vn2008.Compres co - WHERE cu.Id_Cubo = co.Id_Cubo AND Id_Compra = - (SELECT max(Id_Compra) FROM vn2008.Compres c - WHERE c.Id_Article = @art); - - set @atot = @atot +((@ax * @ay * @az)* 1,10); - - UNTIL done END REPEAT; - CLOSE CUR1; - - - select 'hola ',@atot; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `weekly_sales_new` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `weekly_sales_new`(v_wh SMALLINT, v_date_ini DATETIME, v_date_end DATETIME) -BEGIN - IF v_date_end IS NULL THEN - SET v_date_end = v_date_ini; - END IF; - - SET v_date_end = TIMESTAMPADD(DAY, 1, v_date_end); - - CREATE TEMPORARY TABLE weekly_ticket - (INDEX idx USING HASH (Id_Ticket)) - ENGINE = MEMORY - SELECT Id_Ticket, to_weeks (DATE(Fecha)) week, warehouse_id - FROM Tickets t - JOIN warehouse w ON w.id = t.warehouse_id - WHERE Fecha >= v_date_ini AND Fecha < v_date_end - AND Id_Cliente NOT IN (400, 200) - AND NOT w.fuente - AND v_wh IN (t.warehouse_id, 0); - - CREATE TEMPORARY TABLE weekly_sales - ENGINE = MEMORY - SELECT week, warehouse_id, a.Id_Article item_id, SUM(Cantidad) AS amount, - SUM(Cantidad * Preu * (100 - Descuento) / 100) AS price - FROM Movimientos m - JOIN weekly_ticket t USING (Id_Ticket) - JOIN Articles a USING (Id_Article) - INNER JOIN Tipos USING (tipo_id) - WHERE reino_id != 6 - GROUP BY week, warehouse_id, item_id; - - DROP TEMPORARY TABLE weekly_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 DROP PROCEDURE IF EXISTS `workerCreate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerCreate`( - vName VARCHAR(50), - vCognames VARCHAR(50), - vDNI VARCHAR(9), - vAddress TEXT, - vPostalCode VARCHAR(5), - vTown VARCHAR(25), - vProvince SMALLINT(5), - vCompany SMALLINT(5), - vPhone VARCHAR(11), - vMail VARCHAR(80) CHARSET utf8, - vDniExpiration DATETIME, - vEmployeeBoss INT, - vRole INT, - vUsername VARCHAR(50) CHARSET utf8, - vPassword VARCHAR(50), - vWorkerCode VARCHAR(8) -) -BEGIN - DECLARE vClient INT; - DECLARE vUser INT; - DECLARE vWorker INT; - DECLARE vOficial INT DEFAULT 1; - DECLARE vDiscount INT DEFAULT 3; - DECLARE vPayMethodFk INT DEFAULT 4; - DECLARE vDueDay INT DEFAULT 5; - DECLARE vDefaultCredit DECIMAL(10, 2) DEFAULT 300.00; - DECLARE vIsTaxDataChecked TINYINT(1) DEFAULT 1; - DECLARE vHasCoreVnl TINYINT(1) DEFAULT 1; - DECLARE vMandateType INT DEFAULT 2; - - -############################################################################## -#### GENERAR CLIENTE -############################################################################## - - -- Comprobar si existe un cliente con el mismo DNI. - SELECT Id_cliente INTO vClient FROM vn2008.Clientes WHERE `if` = vDNI; - - -- Si no existe el cliente creamos uno nuevo. - IF vClient IS NULL THEN - SELECT (MAX(Id_Cliente) + 1) INTO vClient FROM Clientes WHERE Id_Cliente < 999999; - END IF; - - REPLACE INTO Clientes ( - Id_Cliente, - Cliente, - Domicilio, - `IF`, - Telefono, - province_id, - Poblacion, - CodPostal, - RazonSocial, - Contacto, - Oficial, - Descuento, - Codpos, - pay_met_id, - Vencimiento, - credito, - contabilizado, - coreVnl) - SELECT - vClient, - Concat('TR ', vName, ' ', vCognames), - vAddress, - vDNI, - vPhone, - vProvince, - vTown, - vPostalCode, - CONCAT(vCognames, ' ', vName), - vName, - vOficial, - vDiscount, - vPostalCode, - vPayMethodFk, - vDueDay, - vDefaultCredit, - vIsTaxDataChecked, - vHasCoreVnl; - - REPLACE INTO mandato (Id_Cliente, empresa_id, idmandato_tipo) - VALUES (vClient, vCompany, vMandateType); - -############################################################################## -#### GENERAR USUARIO -############################################################################## - - -- Comprobamos si existe un usuario con el mismo ID de cliente. - IF NOT (SELECT COUNT(*) FROM account.user where id = vClient) THEN - - -- Alta del usuario. - INSERT INTO account.user (id, role, `name`, `password`, active) VALUES (vClient, vRole, LCASE(vUsername), MD5(LCASE(vPassword)), TRUE); - SET vUser = vClient; - INSERT INTO account.account SET id = vClient; - - END IF; - -############################################################################## -#### GENERAR TRABAJADOR -############################################################################## - - - -- Comprobamos si ya existe un trabajador con el mismo DNI. - IF NOT (SELECT COUNT(*) FROM Trabajadores WHERE dni = vDNI) THEN - - -- Alta en la tabla trabajadores. - INSERT INTO Trabajadores (CodigoTrabajador, Nombre, Apellidos, `Password`, dni, empresa_id, user_id, boss, DniExpiration) - VALUES (vWorkerCode, vName, vCognames, LCASE(vPassword), vDNI, vCompany, vUser, vEmployeeBoss, VDniExpiration); - - SET vWorker = LAST_INSERT_ID(); - ELSE - UPDATE Trabajadores SET user_id = vUser WHERE dni = vDNI; - END IF; - -############################################################################## -#### REENVIO EMAIL -############################################################################## - - IF vMail IS NOT NULL AND NOT (SELECT COUNT(*) FROM account.mailForward WHERE forwardTo = vMail) THEN - INSERT INTO account.mailForward (account, forwardTo) VALUES (vUser, vMail); - UPDATE Trabajadores SET email = CONCAT(vUsername, '@verdnatura.es') WHERE user_id = vUser; - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `XDiario_Quadrator` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `XDiario_Quadrator`() -BEGIN - -UPDATE XDiario -SET EURODEBE = ROUND(EURODEBE,2), - EUROHABER = ROUND(EUROHABER,2) -WHERE NOT enlazado; - - -UPDATE XDiario XD -INNER JOIN -( -SELECT XD.id, SUBCTA, Quadre FROM XDiario XD -INNER JOIN ( -SELECT ASIEN, SUM(IFNULL(ROUND(Eurodebe,2),0))- SUM(IFNULL(ROUND(EUROHABER,2),0)) as Quadre -FROM XDiario -WHERE enlazado = FALSE -GROUP BY ASIEN -HAVING Quadre != 0 -) sub USING(ASIEN) -WHERE SUBCTA > '5999999999' -GROUP BY ASIEN -) sub2 USING(id) -SET Eurohaber = IF(IFNULL(Eurohaber,0) = 0, Eurohaber, Eurohaber + Quadre), - Eurodebe = IF(IFNULL(Eurodebe,0) = 0, Eurodebe, Eurodebe - Quadre); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `__proveedores_extracto` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `__proveedores_extracto`(IN idPROV INT, IN idMONEDA INT, IN idEMP INT) -BEGIN - - -SET @saldo_eur:= 0; -SET @saldo_div:= 0; - -SELECT - *, - @saldo_eur:= round(@saldo_eur + IFNULL(Pago_Euros, 0) - IFNULL(Fac_Euros, 0) ,2 ) AS saldo_eur, - @saldo_div:= round(@saldo_div + IFNULL(Pago_Divisas, 0) - IFNULL(Fac_Divisas, 0) ,2 ) AS saldo_div -FROM - (SELECT - * - FROM - (SELECT - 'R', - NULL as banco_id, - r.empresa_id, - r.serie, - r.id, - r.fecha, - CONCAT('S/Fra ', r.sref) sref, - if(r.moneda_id > 1,round(sum(divisa) / sum(cantidad),3),NULL) val_cambio, - CAST(sum(cantidad) as DECIMAL(10,2)) as Fac_Euros, - CAST(sum(divisa) as DECIMAL(10,2)) as Fac_Divisas, - NULL AS Pago_Euros, - NULL AS Pago_Divisas, - r.moneda_id, - r.contabilizada, - Moneda, - NULL as pago_sdc_id - FROM - recibida r - JOIN recibida_vencimiento rv on rv.recibida_id = r.id - JOIN Monedas m on m.Id_Moneda = r.moneda_id - WHERE - r.fecha > '2014-12-31' - AND r.proveedor_id = idPROV - AND idMONEDA IN (r.moneda_id, 0) - AND idEMP IN (r.empresa_id,0) - GROUP BY r.id - - - - UNION ALL SELECT - - 'P', - p.id_banco, - p.empresa_id, - NULL, - p.id, - Fecha, - CONCAT(IFNULL(name, ''), IF(pre.concepto <> '', CONCAT(' : ', pre.concepto), '')), - if(p.id_moneda > 1, p.divisa / importe, NULL) tip_cambio, - NULL, - NULL, - p.importe, - p.divisa, - p.id_moneda, - IFNULL(conciliado, 0), - Moneda, - pago_sdc_id - FROM - pago p - LEFT JOIN Monedas ON Monedas.Id_Moneda = p.id_moneda - LEFT JOIN Bancos ON p.id_banco = Bancos.Id_banco - LEFT JOIN pay_met pm ON p.pay_met_id = pm.id - LEFT JOIN Pagares pre ON pre.pago_id = p.id - WHERE - Fecha > '2014-12-31' - AND p.Id_Proveedor = idPROV - AND idMONEDA IN (p.id_moneda,0) - AND idEMP IN (p.empresa_id,0) - ) AS SUB - ORDER BY fecha) t; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `__proveedores_extracto_vtos` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `__proveedores_extracto_vtos`(IN idPROV INT, IN idMONEDA INT, IN idEMP INT) -BEGIN - - -SET @saldo_eur:= 0; -SET @saldo_div:= 0; - -SELECT - *, - @saldo_eur:= round(@saldo_eur + IFNULL(Pago_Euros, 0) - IFNULL(Fac_Euros, 0) ,2 ) AS saldo_eur, - @saldo_div:= round(@saldo_div + IFNULL(Pago_Divisas, 0) - IFNULL(Fac_Divisas, 0) ,2 ) AS saldo_div -FROM - (SELECT - * - FROM - (SELECT - 'V', - NULL as banco_id, - r.empresa_id, - r.serie, - r.id, - rv.fecha, - CONCAT('S/Fra ', r.sref) sref, - if(r.moneda_id > 1,round(sum(divisa) / sum(cantidad),3),NULL) val_cambio, - CAST(sum(cantidad) as DECIMAL(10,2)) as Fac_Euros, - CAST(sum(divisa) as DECIMAL(10,2)) as Fac_Divisas, - NULL AS Pago_Euros, - NULL AS Pago_Divisas, - r.moneda_id, - r.contabilizada, - Moneda, - NULL as pago_sdc_id - FROM - recibida r - JOIN recibida_vencimiento rv on rv.recibida_id = r.id - JOIN Monedas m on m.Id_Moneda = r.moneda_id - WHERE - r.fecha > '2014-12-31' - AND r.proveedor_id = idPROV - AND idMONEDA IN (r.moneda_id, 0) - AND idEMP IN (r.empresa_id,0) - GROUP BY rv.id - - - - UNION ALL SELECT - - 'P', - p.id_banco, - p.empresa_id, - NULL, - p.id, - Fecha, - CONCAT(IFNULL(name, ''), IF(pre.concepto <> '', CONCAT(' : ', pre.concepto), '')), - if(p.id_moneda > 1, p.divisa / importe, NULL) tip_cambio, - NULL, - NULL, - p.importe, - p.divisa, - p.id_moneda, - IFNULL(conciliado, 0), - Moneda, - pago_sdc_id - FROM - pago p - LEFT JOIN Monedas ON Monedas.Id_Moneda = p.id_moneda - LEFT JOIN Bancos ON p.id_banco = Bancos.Id_banco - LEFT JOIN pay_met pm ON p.pay_met_id = pm.id - LEFT JOIN Pagares pre ON pre.pago_id = p.id - WHERE - Fecha > '2014-12-31' - AND p.Id_Proveedor = idPROV - AND idMONEDA IN (p.id_moneda,0) - AND idEMP IN (p.empresa_id,0) - ) AS SUB - ORDER BY fecha, id) t; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Current Database: `vn` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `vn`; - --- --- Temporary view structure for view `accounting` --- - -DROP TABLE IF EXISTS `accounting`; -/*!50001 DROP VIEW IF EXISTS `accounting`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `accounting` AS SELECT - 1 AS `id`, - 1 AS `bank`, - 1 AS `account`, - 1 AS `accountingTypeFk`, - 1 AS `entityFk`, - 1 AS `isActive`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `accountingType` --- - -DROP TABLE IF EXISTS `accountingType`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `accountingType` ( - `id` smallint(6) NOT NULL DEFAULT '0', - `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='descripcio dels valors de la columna "cash" de la taula vn2008.Bancios'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `activityTaxDismissed` --- - -DROP TABLE IF EXISTS `activityTaxDismissed`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `activityTaxDismissed` ( - `clientFk` int(11) NOT NULL, - `isNotified` tinyint(1) DEFAULT '0', - `isDismissed` tinyint(1) DEFAULT '0', - `notified` int(11) DEFAULT '0', - PRIMARY KEY (`clientFk`), - CONSTRAINT `clientFk` FOREIGN KEY (`clientFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `address` --- - -DROP TABLE IF EXISTS `address`; -/*!50001 DROP VIEW IF EXISTS `address`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `address` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `street`, - 1 AS `city`, - 1 AS `postalCode`, - 1 AS `provinceFk`, - 1 AS `phone`, - 1 AS `mobile`, - 1 AS `nickname`, - 1 AS `isDefaultAddress`, - 1 AS `longitude`, - 1 AS `latitude`, - 1 AS `warehouseFk`, - 1 AS `agencyModeFk`, - 1 AS `isEqualizated`, - 1 AS `isActive`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `addressForPackaging` --- - -DROP TABLE IF EXISTS `addressForPackaging`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `addressForPackaging` ( - `addressFk` int(11) NOT NULL, - `packagingValue` decimal(10,2) NOT NULL DEFAULT '0.04', - PRIMARY KEY (`addressFk`), - CONSTRAINT `addresForPackaging_fk1` FOREIGN KEY (`addressFk`) REFERENCES `vn2008`.`Consignatarios` (`id_consigna`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `addressObservation` --- - -DROP TABLE IF EXISTS `addressObservation`; -/*!50001 DROP VIEW IF EXISTS `addressObservation`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `addressObservation` AS SELECT - 1 AS `id`, - 1 AS `addressFk`, - 1 AS `observationTypeFk`, - 1 AS `description`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `agency` --- - -DROP TABLE IF EXISTS `agency`; -/*!50001 DROP VIEW IF EXISTS `agency`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `agency` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `warehouseFk`, - 1 AS `isVolumetric`, - 1 AS `bankFk`, - 1 AS `warehouseAliasFk`, - 1 AS `own`, - 1 AS `labelZone`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `agencyHour` --- - -DROP TABLE IF EXISTS `agencyHour`; -/*!50001 DROP VIEW IF EXISTS `agencyHour`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `agencyHour` AS SELECT - 1 AS `id`, - 1 AS `agencyFk`, - 1 AS `weekDay`, - 1 AS `warehouseFk`, - 1 AS `provinceFk`, - 1 AS `substractDay`, - 1 AS `maxHour`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `agencyMode` --- - -DROP TABLE IF EXISTS `agencyMode`; -/*!50001 DROP VIEW IF EXISTS `agencyMode`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `agencyMode` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `description`, - 1 AS `deliveryMethodFk`, - 1 AS `m3`, - 1 AS `cod71`, - 1 AS `web`, - 1 AS `agencyFk`, - 1 AS `agencyServiceFk`, - 1 AS `inflation`, - 1 AS `isVolumetric`, - 1 AS `reportMail`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `agencyWarehouse` --- - -DROP TABLE IF EXISTS `agencyWarehouse`; -/*!50001 DROP VIEW IF EXISTS `agencyWarehouse`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `agencyWarehouse` AS SELECT - 1 AS `agencyFk`, - 1 AS `warehouseFk`, - 1 AS `agencyType`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `autoRadioConfig` --- - -DROP TABLE IF EXISTS `autoRadioConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `autoRadioConfig` ( - `id` int(11) NOT NULL, - `password` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `user` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `port` int(11) DEFAULT NULL, - `url` varchar(75) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `autonomousRegion` --- - -DROP TABLE IF EXISTS `autonomousRegion`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `autonomousRegion` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(50) CHARACTER SET utf8 NOT NULL, - `geoFk` int(11) DEFAULT NULL, - `countryFk` mediumint(8) unsigned DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `countryFk` (`countryFk`), - CONSTRAINT `countryFk` FOREIGN KEY (`countryFk`) REFERENCES `vn2008`.`Paises` (`Id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `awb` --- - -DROP TABLE IF EXISTS `awb`; -/*!50001 DROP VIEW IF EXISTS `awb`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `awb` AS SELECT - 1 AS `id`, - 1 AS `code`, - 1 AS `package`, - 1 AS `weight`, - 1 AS `created`, - 1 AS `transitoryFk`, - 1 AS `taxFk`, - 1 AS `docFk`, - 1 AS `amount`, - 1 AS `freightFk`, - 1 AS `m3`, - 1 AS `stems`, - 1 AS `flightFk`, - 1 AS `volumeWeight`, - 1 AS `hb`, - 1 AS `rate`, - 1 AS `booked`, - 1 AS `issued`, - 1 AS `operated`, - 1 AS `bookEntried`, - 1 AS `invoiceInFk`, - 1 AS `isChecked`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `bank` --- - -DROP TABLE IF EXISTS `bank`; -/*!50001 DROP VIEW IF EXISTS `bank`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `bank` AS SELECT - 1 AS `id`, - 1 AS `bank`, - 1 AS `account`, - 1 AS `cash`, - 1 AS `entityFk`, - 1 AS `isActive`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `bankEntity` --- - -DROP TABLE IF EXISTS `bankEntity`; -/*!50001 DROP VIEW IF EXISTS `bankEntity`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `bankEntity` AS SELECT - 1 AS `id`, - 1 AS `countryFk`, - 1 AS `name`, - 1 AS `bic`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `bookingPlanner` --- - -DROP TABLE IF EXISTS `bookingPlanner`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `bookingPlanner` ( - `id` int(10) NOT NULL AUTO_INCREMENT, - `effectived` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `pgcFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `taxAreaFk` varchar(15) CHARACTER SET utf8 NOT NULL DEFAULT 'SPAIN', - `priority` int(2) unsigned DEFAULT NULL, - `taxClassFk` tinyint(3) unsigned NOT NULL DEFAULT '1', - `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1', - PRIMARY KEY (`id`), - KEY `pgcFk_bookingPlanner_idx` (`pgcFk`), - KEY `taxClassFk` (`taxClassFk`), - KEY `countryFk` (`countryFk`), - KEY `bookingPlannerTaxArea` (`taxAreaFk`), - CONSTRAINT `bookingPlannerTaxArea` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON UPDATE CASCADE, - CONSTRAINT `bookingPlanner_ibfk_1` FOREIGN KEY (`pgcFk`) REFERENCES `pgc` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `bookingPlanner_ibfk_2` FOREIGN KEY (`taxClassFk`) REFERENCES `vn2008`.`iva_group` (`iva_group_id`) ON DELETE CASCADE, - CONSTRAINT `bookingPlanner_ibfk_3` FOREIGN KEY (`countryFk`) REFERENCES `vn2008`.`Paises` (`Id`) ON DELETE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=82 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `botanicExport` --- - -DROP TABLE IF EXISTS `botanicExport`; -/*!50001 DROP VIEW IF EXISTS `botanicExport`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `botanicExport` AS SELECT - 1 AS `id`, - 1 AS `ediGenusFk`, - 1 AS `ediSpecieFk`, - 1 AS `countryFk`, - 1 AS `restriction`, - 1 AS `description`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `buy` --- - -DROP TABLE IF EXISTS `buy`; -/*!50001 DROP VIEW IF EXISTS `buy`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `buy` AS SELECT - 1 AS `id`, - 1 AS `entryFk`, - 1 AS `itemFk`, - 1 AS `amount`, - 1 AS `buyingValue`, - 1 AS `quantity`, - 1 AS `packageFk`, - 1 AS `stickers`, - 1 AS `freightValue`, - 1 AS `packageValue`, - 1 AS `comissionValue`, - 1 AS `packing`, - 1 AS `grouping`, - 1 AS `groupingMode`, - 1 AS `location`, - 1 AS `price1`, - 1 AS `price2`, - 1 AS `price3`, - 1 AS `minPrice`, - 1 AS `producer`, - 1 AS `printedStickers`, - 1 AS `isChecked`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `calendarHolidays` --- - -DROP TABLE IF EXISTS `calendarHolidays`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `calendarHolidays` ( - `calendarHolidaysTypeFk` int(11) NOT NULL, - `dated` date NOT NULL, - `calendarHolidaysNameFk` int(11) DEFAULT NULL, - `workCenterFk` int(11) NOT NULL, - PRIMARY KEY (`dated`,`workCenterFk`), - KEY `calendarholidaystypeFk_idx` (`calendarHolidaysTypeFk`), - KEY `calendarHolidaysNameFk_idx` (`calendarHolidaysNameFk`), - KEY `workCenterFk_idx` (`workCenterFk`), - CONSTRAINT `calendarHolidaysNameFk` FOREIGN KEY (`calendarHolidaysNameFk`) REFERENCES `calendarHolidaysName` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `calendarholidaystypeFk` FOREIGN KEY (`calendarHolidaysTypeFk`) REFERENCES `calendarHolidaysType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `workCenterFk` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `calendarHolidaysName` --- - -DROP TABLE IF EXISTS `calendarHolidaysName`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `calendarHolidaysName` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(100) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `calendarHolidaysType` --- - -DROP TABLE IF EXISTS `calendarHolidaysType`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `calendarHolidaysType` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(50) NOT NULL, - `hexColour` char(7) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `category` --- - -DROP TABLE IF EXISTS `category`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `category` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `nick` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `city` --- - -DROP TABLE IF EXISTS `city`; -/*!50001 DROP VIEW IF EXISTS `city`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `city` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `provinceFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `claimRatio` --- - -DROP TABLE IF EXISTS `claimRatio`; -/*!50001 DROP VIEW IF EXISTS `claimRatio`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `claimRatio` AS SELECT - 1 AS `clientFk`, - 1 AS `yearSale`, - 1 AS `claimAmount`, - 1 AS `claimingRate`, - 1 AS `priceIncreasing`, - 1 AS `packingRate`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `client` --- - -DROP TABLE IF EXISTS `client`; -/*!50001 DROP VIEW IF EXISTS `client`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `client` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `fi`, - 1 AS `socialName`, - 1 AS `contact`, - 1 AS `street`, - 1 AS `city`, - 1 AS `postcode`, - 1 AS `phone`, - 1 AS `mobile`, - 1 AS `fax`, - 1 AS `isRelevant`, - 1 AS `email`, - 1 AS `iban`, - 1 AS `dueDay`, - 1 AS `accountingAccount`, - 1 AS `isEqualizated`, - 1 AS `provinceFk`, - 1 AS `hasToInvoice`, - 1 AS `credit`, - 1 AS `countryFk`, - 1 AS `isActive`, - 1 AS `gestdocFk`, - 1 AS `quality`, - 1 AS `payMethodFk`, - 1 AS `created`, - 1 AS `isToBeMailed`, - 1 AS `contactChannelFk`, - 1 AS `hasSepaVnl`, - 1 AS `hasCoreVnl`, - 1 AS `hasCoreVnh`, - 1 AS `defaultAddressFk`, - 1 AS `riskCalculated`, - 1 AS `clientTypeFk`, - 1 AS `mailAddress`, - 1 AS `cplusTerIdNifFk`, - 1 AS `hasToInvoiceByAddress`, - 1 AS `isTaxDataChecked`, - 1 AS `isFreezed`, - 1 AS `creditInsurance`, - 1 AS `isCreatedAsServed`, - 1 AS `hasInvoiceSimplified`, - 1 AS `salesPersonFk`, - 1 AS `isVies`, - 1 AS `eypbc`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `clientCredit` --- - -DROP TABLE IF EXISTS `clientCredit`; -/*!50001 DROP VIEW IF EXISTS `clientCredit`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `clientCredit` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `workerFk`, - 1 AS `amount`, - 1 AS `created`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `clientCreditLimit` --- - -DROP TABLE IF EXISTS `clientCreditLimit`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `clientCreditLimit` ( - `id` int(11) NOT NULL, - `maxAmount` int(10) unsigned NOT NULL, - `roleFk` int(10) unsigned NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `clientDefaultCompany` --- - -DROP TABLE IF EXISTS `clientDefaultCompany`; -/*!50001 DROP VIEW IF EXISTS `clientDefaultCompany`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `clientDefaultCompany` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `companyFk`, - 1 AS `started`, - 1 AS `finished`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `clientLog` --- - -DROP TABLE IF EXISTS `clientLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `clientLog` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `originFk` int(11) NOT NULL, - `userFk` int(10) unsigned NOT NULL, - `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, - `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `description` text COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`), - KEY `originFk` (`originFk`), - KEY `userFk` (`userFk`), - CONSTRAINT `clientLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT `clientLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB AUTO_INCREMENT=155666 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `clientManaCache` --- - -DROP TABLE IF EXISTS `clientManaCache`; -/*!50001 DROP VIEW IF EXISTS `clientManaCache`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `clientManaCache` AS SELECT - 1 AS `clientFk`, - 1 AS `mana`, - 1 AS `dated`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `clientNotification` --- - -DROP TABLE IF EXISTS `clientNotification`; -/*!50001 DROP VIEW IF EXISTS `clientNotification`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `clientNotification` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `clientNotificationTypeFk`, - 1 AS `created`, - 1 AS `workerFk`, - 1 AS `userFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `clientNotificationType` --- - -DROP TABLE IF EXISTS `clientNotificationType`; -/*!50001 DROP VIEW IF EXISTS `clientNotificationType`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `clientNotificationType` AS SELECT - 1 AS `id`, - 1 AS `code`, - 1 AS `description`, - 1 AS `isVisible`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `clientObservation` --- - -DROP TABLE IF EXISTS `clientObservation`; -/*!50001 DROP VIEW IF EXISTS `clientObservation`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `clientObservation` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `workerFk`, - 1 AS `text`, - 1 AS `created`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `clientType` --- - -DROP TABLE IF EXISTS `clientType`; -/*!50001 DROP VIEW IF EXISTS `clientType`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `clientType` AS SELECT - 1 AS `id`, - 1 AS `code`, - 1 AS `type`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `color` --- - -DROP TABLE IF EXISTS `color`; -/*!50001 DROP VIEW IF EXISTS `color`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `color` AS SELECT - 1 AS `id`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `company` --- - -DROP TABLE IF EXISTS `company`; -/*!50001 DROP VIEW IF EXISTS `company`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `company` AS SELECT - 1 AS `id`, - 1 AS `code`, - 1 AS `supplierAccountFk`, - 1 AS `CodigoEmpresa`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `comparative` --- - -DROP TABLE IF EXISTS `comparative`; -/*!50001 DROP VIEW IF EXISTS `comparative`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `comparative` AS SELECT - 1 AS `timePeriod`, - 1 AS `itemFk`, - 1 AS `warehouseFk`, - 1 AS `quantity`, - 1 AS `price`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `comparativeFilter` --- - -DROP TABLE IF EXISTS `comparativeFilter`; -/*!50001 DROP VIEW IF EXISTS `comparativeFilter`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `comparativeFilter` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `whereSql`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `componentRate` --- - -DROP TABLE IF EXISTS `componentRate`; -/*!50001 DROP VIEW IF EXISTS `componentRate`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `componentRate` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `componentTypeRate`, - 1 AS `classRate`, - 1 AS `tax`, - 1 AS `isRenewable`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `componentTypeRate` --- - -DROP TABLE IF EXISTS `componentTypeRate`; -/*!50001 DROP VIEW IF EXISTS `componentTypeRate`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `componentTypeRate` AS SELECT - 1 AS `id`, - 1 AS `type`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `confectionType` --- - -DROP TABLE IF EXISTS `confectionType`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `confectionType` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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(10) unsigned NOT NULL AUTO_INCREMENT, - `mdbServer` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `fakeEmail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `defaultersMaxAmount` int(10) DEFAULT '200' COMMENT 'maxima deuda permitida a partir de la cual se bloquea a un usuario', - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `contactChannel` --- - -DROP TABLE IF EXISTS `contactChannel`; -/*!50001 DROP VIEW IF EXISTS `contactChannel`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `contactChannel` AS SELECT - 1 AS `id`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `country` --- - -DROP TABLE IF EXISTS `country`; -/*!50001 DROP VIEW IF EXISTS `country`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `country` AS SELECT - 1 AS `id`, - 1 AS `country`, - 1 AS `CEE`, - 1 AS `isUeeMember`, - 1 AS `code`, - 1 AS `currencyFk`, - 1 AS `politicalCountryFk`, - 1 AS `geoFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `cplusCorrectingType` --- - -DROP TABLE IF EXISTS `cplusCorrectingType`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusCorrectingType` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cplusInvoiceType472` --- - -DROP TABLE IF EXISTS `cplusInvoiceType472`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusInvoiceType472` ( - `id` int(10) unsigned NOT NULL, - `description` varchar(255) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*18) TIPO FACTURA (Asientos)SOPORTADO – DEDUCIBLE (472)'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cplusInvoiceType477` --- - -DROP TABLE IF EXISTS `cplusInvoiceType477`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusInvoiceType477` ( - `id` int(10) unsigned NOT NULL, - `description` varchar(255) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*18) TIPO FACTURA (Asientos)REPERCUTIDO - DEVENGADO (477)'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cplusRectificationType` --- - -DROP TABLE IF EXISTS `cplusRectificationType`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusRectificationType` ( - `id` int(10) unsigned NOT NULL, - `description` varchar(255) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*20) TIPO RECTIFICATIVA (Asientos)'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cplusSubjectOp` --- - -DROP TABLE IF EXISTS `cplusSubjectOp`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusSubjectOp` ( - `id` int(10) unsigned NOT NULL, - `description` varchar(255) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*17) TIPO OPERACIÓN SUJETA/NO SUJETA (Asientos)'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cplusTaxBreak` --- - -DROP TABLE IF EXISTS `cplusTaxBreak`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusTaxBreak` ( - `id` int(10) unsigned NOT NULL, - `description` varchar(255) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*16) TIPO EXENCIÓN (Asientos)'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cplusTerIdNif` --- - -DROP TABLE IF EXISTS `cplusTerIdNif`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusTerIdNif` ( - `id` int(11) NOT NULL, - `description` varchar(255) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cplusTrascendency472` --- - -DROP TABLE IF EXISTS `cplusTrascendency472`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusTrascendency472` ( - `id` int(10) unsigned NOT NULL, - `description` varchar(255) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*15) CLAVE DE RÉGIMEN ESPECIAL O TRASCENDENCIA(Asientos)SOPORTADO – DEDUCIBLE (472)'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cplusTrascendency477` --- - -DROP TABLE IF EXISTS `cplusTrascendency477`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusTrascendency477` ( - `id` int(10) unsigned NOT NULL, - `description` varchar(255) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*15) CLAVE DE RÉGIMEN ESPECIAL O TRASCENDENCIA(Asientos) REPERCUTIDO - DEVENGADO (477)'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `creditClassification` --- - -DROP TABLE IF EXISTS `creditClassification`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `creditClassification` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `client` int(11) NOT NULL, - `dateStart` date NOT NULL, - `dateEnd` date DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `creditClassifClientFk_idx` (`client`), - KEY `creditClassifdateEnd_idx` (`dateEnd`), - CONSTRAINT `creditClassifClientFk` FOREIGN KEY (`client`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2687 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditClassification_BEFORE_UPDATE` BEFORE UPDATE ON `creditClassification` FOR EACH ROW -BEGIN - IF NEW.client <> OLD.client THEN - CALL util.throw('NOT_ALLOWED_CHANGE_CLIENT'); - END IF; - IF NEW.dateEnd IS NOT NULL AND OLD.dateEnd IS NULL THEN - UPDATE vn2008.Clientes c - SET creditInsurance = 0 WHERE c.Id_cliente = NEW.client; - 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 */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- --- Table structure for table `creditInsurance` --- - -DROP TABLE IF EXISTS `creditInsurance`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `creditInsurance` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `creditClassification` int(11) DEFAULT NULL, - `credit` int(11) DEFAULT NULL, - `creationDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `grade` tinyint(1) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `CreditInsurance_Fk1_idx` (`creditClassification`), - CONSTRAINT `CreditInsurance_Fk1` FOREIGN KEY (`creditClassification`) REFERENCES `creditClassification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=1780 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalla los clientes que tienen seguro de credito'; -/*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditInsurance_AFTER_INSERT` AFTER INSERT ON `creditInsurance` FOR EACH ROW -BEGIN - UPDATE vn2008.Clientes c - JOIN vn.creditClassification cc ON cc.client = c.Id_Cliente - SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- --- Temporary view structure for view `currency` --- - -DROP TABLE IF EXISTS `currency`; -/*!50001 DROP VIEW IF EXISTS `currency`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `currency` AS SELECT - 1 AS `id`, - 1 AS `code`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `dailyTaskLog` --- - -DROP TABLE IF EXISTS `dailyTaskLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `dailyTaskLog` ( - `state` varchar(250) COLLATE utf8_unicode_ci NOT NULL, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `deliveryError` --- - -DROP TABLE IF EXISTS `deliveryError`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `deliveryError` ( - `ticket` int(11) NOT NULL, - `description` varchar(255) CHARACTER SET latin1 NOT NULL, - `worker` int(11) NOT NULL, - `creation_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - KEY `errorTickets_idx` (`ticket`), - KEY `errorWorker_idx` (`worker`), - CONSTRAINT `errorTickets` FOREIGN KEY (`ticket`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT `errorWorker` FOREIGN KEY (`worker`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `deliveryMethod` --- - -DROP TABLE IF EXISTS `deliveryMethod`; -/*!50001 DROP VIEW IF EXISTS `deliveryMethod`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `deliveryMethod` AS SELECT - 1 AS `id`, - 1 AS `code`, - 1 AS `description`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `ediGenus` --- - -DROP TABLE IF EXISTS `ediGenus`; -/*!50001 DROP VIEW IF EXISTS `ediGenus`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ediGenus` AS SELECT - 1 AS `id`, - 1 AS `latinGenusName`, - 1 AS `entried`, - 1 AS `dued`, - 1 AS `modified`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `ediSpecie` --- - -DROP TABLE IF EXISTS `ediSpecie`; -/*!50001 DROP VIEW IF EXISTS `ediSpecie`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ediSpecie` AS SELECT - 1 AS `id`, - 1 AS `genusFk`, - 1 AS `latinSpeciesName`, - 1 AS `entried`, - 1 AS `dued`, - 1 AS `modified`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `entity` --- - -DROP TABLE IF EXISTS `entity`; -/*!50001 DROP VIEW IF EXISTS `entity`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `entity` AS SELECT - 1 AS `countryFk`, - 1 AS `id`, - 1 AS `description`, - 1 AS `bic`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `entry` --- - -DROP TABLE IF EXISTS `entry`; -/*!50001 DROP VIEW IF EXISTS `entry`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `entry` AS SELECT - 1 AS `id`, - 1 AS `supplierFk`, - 1 AS `ref`, - 1 AS `isInventory`, - 1 AS `isConfirmed`, - 1 AS `isOrdered`, - 1 AS `isRaid`, - 1 AS `commission`, - 1 AS `created`, - 1 AS `evaNotes`, - 1 AS `travelFk`, - 1 AS `currencyFk`, - 1 AS `companyFk`, - 1 AS `gestDocFk`, - 1 AS `invoiceReceivedFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `entryLog` --- - -DROP TABLE IF EXISTS `entryLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `entryLog` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `originFk` int(11) NOT NULL, - `userFk` int(10) unsigned NOT NULL, - `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, - `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `description` text COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`), - KEY `userFk` (`userFk`), - KEY `logEntry_ibfk_1` (`originFk`), - CONSTRAINT `entryLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `vn2008`.`Entradas` (`Id_Entrada`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `entryLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB AUTO_INCREMENT=31221 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `especialPrice` --- - -DROP TABLE IF EXISTS `especialPrice`; -/*!50001 DROP VIEW IF EXISTS `especialPrice`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `especialPrice` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `itemFk`, - 1 AS `value`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `excuse` --- - -DROP TABLE IF EXISTS `excuse`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `excuse` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `txt` varchar(255) CHARACTER SET latin1 NOT NULL, - `date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `expedition` --- - -DROP TABLE IF EXISTS `expedition`; -/*!50001 DROP VIEW IF EXISTS `expedition`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `expedition` AS SELECT - 1 AS `id`, - 1 AS `agency`, - 1 AS `agencyFk`, - 1 AS `agencyModeFk`, - 1 AS `ticket`, - 1 AS `ticketFk`, - 1 AS `isBox`, - 1 AS `printingTime`, - 1 AS `item`, - 1 AS `itemFk`, - 1 AS `counter`, - 1 AS `checked`, - 1 AS `workerFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `expence` --- - -DROP TABLE IF EXISTS `expence`; -/*!50001 DROP VIEW IF EXISTS `expence`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `expence` AS SELECT - 1 AS `id`, - 1 AS `taxTypeFk`, - 1 AS `name`, - 1 AS `isWithheld`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `firstTicketShipped` --- - -DROP TABLE IF EXISTS `firstTicketShipped`; -/*!50001 DROP VIEW IF EXISTS `firstTicketShipped`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `firstTicketShipped` AS SELECT - 1 AS `shipped`, - 1 AS `clientFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `gateArea` --- - -DROP TABLE IF EXISTS `gateArea`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `gateArea` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `name_UNIQUE` (`name`) -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `grant` --- - -DROP TABLE IF EXISTS `grant`; -/*!50001 DROP VIEW IF EXISTS `grant`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `grant` AS SELECT - 1 AS `group`, - 1 AS `worker`, - 1 AS `company`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `grantGroup` --- - -DROP TABLE IF EXISTS `grantGroup`; -/*!50001 DROP VIEW IF EXISTS `grantGroup`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `grantGroup` AS SELECT - 1 AS `id`, - 1 AS `description`, - 1 AS `observationType`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `greuge` --- - -DROP TABLE IF EXISTS `greuge`; -/*!50001 DROP VIEW IF EXISTS `greuge`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `greuge` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `description`, - 1 AS `amount`, - 1 AS `shipped`, - 1 AS `created`, - 1 AS `greugeTypeFk`, - 1 AS `ticketFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `greugeType` --- - -DROP TABLE IF EXISTS `greugeType`; -/*!50001 DROP VIEW IF EXISTS `greugeType`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `greugeType` AS SELECT - 1 AS `id`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `ink` --- - -DROP TABLE IF EXISTS `ink`; -/*!50001 DROP VIEW IF EXISTS `ink`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ink` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `picture`, - 1 AS `showOrder`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `inkI18n` --- - -DROP TABLE IF EXISTS `inkI18n`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `inkI18n` ( - `inkFk` char(3) COLLATE utf8_unicode_ci NOT NULL, - `lang` char(2) CHARACTER SET utf8 NOT NULL, - `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`inkFk`,`lang`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `inkL10n` --- - -DROP TABLE IF EXISTS `inkL10n`; -/*!50001 DROP VIEW IF EXISTS `inkL10n`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `inkL10n` AS SELECT - 1 AS `id`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `intrastat` --- - -DROP TABLE IF EXISTS `intrastat`; -/*!50001 DROP VIEW IF EXISTS `intrastat`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `intrastat` AS SELECT - 1 AS `id`, - 1 AS `description`, - 1 AS `taxClassFk`, - 1 AS `taxCodeFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `invoiceCorrection` --- - -DROP TABLE IF EXISTS `invoiceCorrection`; -/*!50001 DROP VIEW IF EXISTS `invoiceCorrection`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `invoiceCorrection` AS SELECT - 1 AS `correctingFk`, - 1 AS `correctedFk`, - 1 AS `cplusRectificationTypeFk`, - 1 AS `cplusInvoiceType477Fk`, - 1 AS `invoiceCorrectionTypeFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `invoiceCorrectionDataSource` --- - -DROP TABLE IF EXISTS `invoiceCorrectionDataSource`; -/*!50001 DROP VIEW IF EXISTS `invoiceCorrectionDataSource`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `invoiceCorrectionDataSource` AS SELECT - 1 AS `itemFk`, - 1 AS `quantity`, - 1 AS `concept`, - 1 AS `price`, - 1 AS `discount`, - 1 AS `refFk`, - 1 AS `saleFk`, - 1 AS `shipped`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `invoiceCorrectionType` --- - -DROP TABLE IF EXISTS `invoiceCorrectionType`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `invoiceCorrectionType` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `description_UNIQUE` (`description`) -) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `invoiceIn` --- - -DROP TABLE IF EXISTS `invoiceIn`; -/*!50001 DROP VIEW IF EXISTS `invoiceIn`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `invoiceIn` AS SELECT - 1 AS `id`, - 1 AS `serialNumber`, - 1 AS `serial`, - 1 AS `supplierFk`, - 1 AS `issued`, - 1 AS `supplierRef`, - 1 AS `isBooked`, - 1 AS `currencyFk`, - 1 AS `created`, - 1 AS `companyFk`, - 1 AS `docFk`, - 1 AS `booked`, - 1 AS `operated`, - 1 AS `cplusInvoiceType472Fk`, - 1 AS `cplusRectificationTypeFk`, - 1 AS `cplusSubjectOpFk`, - 1 AS `cplusTaxBreakFk`, - 1 AS `cplusTrascendency472Fk`, - 1 AS `bookEntried`, - 1 AS `isVatDeductible`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `invoiceInAwb` --- - -DROP TABLE IF EXISTS `invoiceInAwb`; -/*!50001 DROP VIEW IF EXISTS `invoiceInAwb`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `invoiceInAwb` AS SELECT - 1 AS `invoiceInFk`, - 1 AS `awbFk`, - 1 AS `dua`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `invoiceInDueDay` --- - -DROP TABLE IF EXISTS `invoiceInDueDay`; -/*!50001 DROP VIEW IF EXISTS `invoiceInDueDay`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `invoiceInDueDay` AS SELECT - 1 AS `id`, - 1 AS `invoiceInFk`, - 1 AS `dueDated`, - 1 AS `bankFk`, - 1 AS `amount`, - 1 AS `foreignValue`, - 1 AS `created`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `invoiceInEntry` --- - -DROP TABLE IF EXISTS `invoiceInEntry`; -/*!50001 DROP VIEW IF EXISTS `invoiceInEntry`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `invoiceInEntry` AS SELECT - 1 AS `id`, - 1 AS `invoiceInFk`, - 1 AS `entryFk`, - 1 AS `percentage`, - 1 AS `invoiceInAwbFk`, - 1 AS `isBooked`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `invoiceInIntrastat` --- - -DROP TABLE IF EXISTS `invoiceInIntrastat`; -/*!50001 DROP VIEW IF EXISTS `invoiceInIntrastat`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `invoiceInIntrastat` AS SELECT - 1 AS `invoiceInFk`, - 1 AS `intrastatFk`, - 1 AS `amount`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `invoiceInSerial` --- - -DROP TABLE IF EXISTS `invoiceInSerial`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `invoiceInSerial` ( - `code` varchar(2) COLLATE utf8_unicode_ci NOT NULL, - `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `cplusTerIdNifFk` int(11) NOT NULL DEFAULT '1', - `taxAreaFk` varchar(15) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`code`), - KEY `InvoiceInSerial_Fk1_idx` (`cplusTerIdNifFk`), - KEY `InvoiceInSerialTaxArea_idx` (`taxAreaFk`), - CONSTRAINT `InvoiceInSerialTaxArea` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON UPDATE CASCADE, - CONSTRAINT `InvoiceInSerial_Fk1` FOREIGN KEY (`cplusTerIdNifFk`) REFERENCES `cplusTerIdNif` (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `invoiceInTax` --- - -DROP TABLE IF EXISTS `invoiceInTax`; -/*!50001 DROP VIEW IF EXISTS `invoiceInTax`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `invoiceInTax` AS SELECT - 1 AS `id`, - 1 AS `invoiceInFk`, - 1 AS `taxCodeFk`, - 1 AS `taxableBase`, - 1 AS `expenceFk`, - 1 AS `foreignValue`, - 1 AS `created`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `invoiceOut` --- - -DROP TABLE IF EXISTS `invoiceOut`; -/*!50001 DROP VIEW IF EXISTS `invoiceOut`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `invoiceOut` AS SELECT - 1 AS `id`, - 1 AS `ref`, - 1 AS `serial`, - 1 AS `issued`, - 1 AS `amount`, - 1 AS `clientFk`, - 1 AS `created`, - 1 AS `companyFk`, - 1 AS `dued`, - 1 AS `booked`, - 1 AS `bankFk`, - 1 AS `cplusInvoiceType477Fk`, - 1 AS `cplusTaxBreakFk`, - 1 AS `cplusSubjectOpFk`, - 1 AS `cplusTrascendency477Fk`, - 1 AS `pdf`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `invoiceOutExpence` --- - -DROP TABLE IF EXISTS `invoiceOutExpence`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `invoiceOutExpence` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `invoiceOutFk` int(10) unsigned NOT NULL, - `amount` decimal(10,2) NOT NULL DEFAULT '0.00', - `expenceFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - UNIQUE KEY `invoiceOutExpence_restriccion` (`expenceFk`,`invoiceOutFk`), - KEY `invoiceOutExpence_FK_1_idx` (`invoiceOutFk`), - KEY `invoiceOutExpence_FK_2_idx` (`expenceFk`), - CONSTRAINT `invoiceOutExpence_FK_1` FOREIGN KEY (`invoiceOutFk`) REFERENCES `vn2008`.`Facturas` (`factura_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `invoiceOutExpence_FK_2` FOREIGN KEY (`expenceFk`) REFERENCES `vn2008`.`Gastos` (`Id_Gasto`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=52304 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Desglosa la base imponible de una factura en funcion del tipo de gasto/venta'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `invoiceOutSerial` --- - -DROP TABLE IF EXISTS `invoiceOutSerial`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `invoiceOutSerial` ( - `code` varchar(2) COLLATE utf8_unicode_ci NOT NULL, - `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `isTaxed` tinyint(1) NOT NULL DEFAULT '1', - `taxAreaFk` varchar(15) CHARACTER SET utf8 NOT NULL DEFAULT 'NATIONAL', - `isCEE` tinyint(1) NOT NULL DEFAULT '0', - `cplusInvoiceType477Fk` int(10) unsigned DEFAULT '1', - PRIMARY KEY (`code`), - KEY `taxAreaFk_idx` (`taxAreaFk`), - CONSTRAINT `invoiceOutSeriaTaxArea` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `invoiceOutTax` --- - -DROP TABLE IF EXISTS `invoiceOutTax`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `invoiceOutTax` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `invoiceOutFk` int(10) unsigned NOT NULL, - `taxableBase` decimal(10,2) NOT NULL, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `vat` decimal(10,2) NOT NULL DEFAULT '0.00', - `pgcFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0000000000', - PRIMARY KEY (`id`), - UNIQUE KEY `invoiceOutTax_Resctriccion` (`invoiceOutFk`,`pgcFk`), - KEY `invoiceOutFk_idx` (`invoiceOutFk`), - KEY `pgcFk` (`pgcFk`), - CONSTRAINT `invoiceOutFk` FOREIGN KEY (`invoiceOutFk`) REFERENCES `vn2008`.`Facturas` (`factura_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `invoiceOutTax_ibfk_1` FOREIGN KEY (`pgcFk`) REFERENCES `pgc` (`code`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=880014 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `item` --- - -DROP TABLE IF EXISTS `item`; -/*!50001 DROP VIEW IF EXISTS `item`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `item` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `typeFk`, - 1 AS `size`, - 1 AS `inkFk`, - 1 AS `category`, - 1 AS `stems`, - 1 AS `originFk`, - 1 AS `description`, - 1 AS `producerFk`, - 1 AS `intrastatFk`, - 1 AS `isOnOffer`, - 1 AS `expenceFk`, - 1 AS `isBargain`, - 1 AS `comment`, - 1 AS `relevancy`, - 1 AS `image`, - 1 AS `taxClassFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `itemBarcode` --- - -DROP TABLE IF EXISTS `itemBarcode`; -/*!50001 DROP VIEW IF EXISTS `itemBarcode`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `itemBarcode` AS SELECT - 1 AS `id`, - 1 AS `itemFk`, - 1 AS `code`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `itemBotanical` --- - -DROP TABLE IF EXISTS `itemBotanical`; -/*!50001 DROP VIEW IF EXISTS `itemBotanical`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `itemBotanical` AS SELECT - 1 AS `itemFk`, - 1 AS `botanical`, - 1 AS `genusFk`, - 1 AS `specieFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `itemBotanicalWithGenus` --- - -DROP TABLE IF EXISTS `itemBotanicalWithGenus`; -/*!50001 DROP VIEW IF EXISTS `itemBotanicalWithGenus`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `itemBotanicalWithGenus` AS SELECT - 1 AS `itemFk`, - 1 AS `ediBotanic`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `itemCategory` --- - -DROP TABLE IF EXISTS `itemCategory`; -/*!50001 DROP VIEW IF EXISTS `itemCategory`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `itemCategory` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `display`, - 1 AS `color`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `itemCategoryI18n` --- - -DROP TABLE IF EXISTS `itemCategoryI18n`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `itemCategoryI18n` ( - `categoryFk` int(10) unsigned NOT NULL, - `lang` char(2) CHARACTER SET utf8 NOT NULL, - `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`categoryFk`,`lang`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `itemCategoryL10n` --- - -DROP TABLE IF EXISTS `itemCategoryL10n`; -/*!50001 DROP VIEW IF EXISTS `itemCategoryL10n`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `itemCategoryL10n` AS SELECT - 1 AS `id`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `itemConversor` --- - -DROP TABLE IF EXISTS `itemConversor`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `itemConversor` ( - `espItemFk` int(11) NOT NULL, - `genItemFk` int(11) DEFAULT NULL, - PRIMARY KEY (`espItemFk`), - KEY `itemConversor_fk2_idx` (`genItemFk`), - CONSTRAINT `itemConversor_fk1` FOREIGN KEY (`espItemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `itemConversor_fk2` FOREIGN KEY (`genItemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Relaciona los item específicos con los genéricos'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `itemLog` --- - -DROP TABLE IF EXISTS `itemLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `itemLog` ( - `id` int(11) NOT NULL DEFAULT '0', - `originFk` int(11) NOT NULL, - `userFk` int(10) unsigned NOT NULL, - `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, - `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `description` text COLLATE utf8_unicode_ci NOT NULL, - KEY `itemLogItemFk_idx` (`originFk`), - KEY `itemLogUserFk_idx` (`userFk`), - CONSTRAINT `itemLogItemFk` FOREIGN KEY (`originFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE NO ACTION ON UPDATE CASCADE, - CONSTRAINT `itemLogUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `itemPlacement` --- - -DROP TABLE IF EXISTS `itemPlacement`; -/*!50001 DROP VIEW IF EXISTS `itemPlacement`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `itemPlacement` AS SELECT - 1 AS `id`, - 1 AS `itemFk`, - 1 AS `warehouseFk`, - 1 AS `code`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `itemTag` --- - -DROP TABLE IF EXISTS `itemTag`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `itemTag` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `itemFk` int(11) NOT NULL, - `tagFk` int(11) NOT NULL, - `value` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `priority` int(2) NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - KEY `priorityItem` (`itemFk`,`priority`), - KEY `tagFk` (`tagFk`,`value`), - CONSTRAINT `itemFK` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=263224 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `itemTagArranged` --- - -DROP TABLE IF EXISTS `itemTagArranged`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `itemTagArranged` ( - `itemFk` int(11) NOT NULL, - `tag1` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `val1` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `tag2` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `val2` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `tag3` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `val3` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `tag4` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `val4` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `tag5` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `val5` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `tag6` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `val6` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`itemFk`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Cache de columnas de características de artículo'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `itemTagged` --- - -DROP TABLE IF EXISTS `itemTagged`; -/*!50001 DROP VIEW IF EXISTS `itemTagged`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `itemTagged` AS SELECT - 1 AS `itemFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `itemTaxCountry` --- - -DROP TABLE IF EXISTS `itemTaxCountry`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `itemTaxCountry` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `itemFk` int(11) DEFAULT NULL, - `countryFk` mediumint(8) unsigned DEFAULT NULL, - `taxClassFk` tinyint(3) unsigned NOT NULL DEFAULT '1', - `effectived` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `taxClassFK_idx` (`taxClassFk`), - KEY `countryFK_paises_idx` (`countryFk`), - KEY `itemFK_Article_idx` (`itemFk`), - CONSTRAINT `countryFK_paises` FOREIGN KEY (`countryFk`) REFERENCES `vn2008`.`Paises` (`Id`) ON UPDATE CASCADE, - CONSTRAINT `itemFK_Article` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `taxClassFK_Iva_Group` FOREIGN KEY (`taxClassFk`) REFERENCES `vn2008`.`iva_group` (`iva_group_id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=454112 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Define la clase de iva por artículo y pais'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `itemType` --- - -DROP TABLE IF EXISTS `itemType`; -/*!50001 DROP VIEW IF EXISTS `itemType`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `itemType` AS SELECT - 1 AS `id`, - 1 AS `code`, - 1 AS `name`, - 1 AS `categoryFk`, - 1 AS `life`, - 1 AS `workerFk`, - 1 AS `isPackaging`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `itemTypeI18n` --- - -DROP TABLE IF EXISTS `itemTypeI18n`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `itemTypeI18n` ( - `typeFk` smallint(5) unsigned NOT NULL, - `lang` char(2) CHARACTER SET utf8 NOT NULL, - `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`typeFk`,`lang`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `itemTypeL10n` --- - -DROP TABLE IF EXISTS `itemTypeL10n`; -/*!50001 DROP VIEW IF EXISTS `itemTypeL10n`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `itemTypeL10n` AS SELECT - 1 AS `id`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `itemVerdecora` --- - -DROP TABLE IF EXISTS `itemVerdecora`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `itemVerdecora` ( - `itemFk` int(11) NOT NULL, - `codin` int(11) DEFAULT NULL, - PRIMARY KEY (`itemFk`), - CONSTRAINT `itemVerdecora_fk1` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Relaciona nuestros articulos con los de Verdecora'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `mail` --- - -DROP TABLE IF EXISTS `mail`; -/*!50001 DROP VIEW IF EXISTS `mail`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `mail` AS SELECT - 1 AS `id`, - 1 AS `senderFk`, - 1 AS `recipientFk`, - 1 AS `sender`, - 1 AS `replyTo`, - 1 AS `subject`, - 1 AS `body`, - 1 AS `plainTextBody`, - 1 AS `attachment`, - 1 AS `creationDate`, - 1 AS `sent`, - 1 AS `status`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `mailTemplates` --- - -DROP TABLE IF EXISTS `mailTemplates`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mailTemplates` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(50) CHARACTER SET utf8 NOT NULL, - `attachmentPath` text CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `manaSpellers` --- - -DROP TABLE IF EXISTS `manaSpellers`; -/*!50001 DROP VIEW IF EXISTS `manaSpellers`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `manaSpellers` AS SELECT - 1 AS `worker`, - 1 AS `size`, - 1 AS `used`, - 1 AS `pricesModifierRate`, - 1 AS `pricesModifierActivated`, - 1 AS `workerCode`, - 1 AS `firstname`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `mandate` --- - -DROP TABLE IF EXISTS `mandate`; -/*!50001 DROP VIEW IF EXISTS `mandate`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `mandate` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `companyFk`, - 1 AS `code`, - 1 AS `created`, - 1 AS `finished`, - 1 AS `mandateTypeFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `mandateType` --- - -DROP TABLE IF EXISTS `mandateType`; -/*!50001 DROP VIEW IF EXISTS `mandateType`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `mandateType` AS SELECT - 1 AS `id`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `manuscript` --- - -DROP TABLE IF EXISTS `manuscript`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `manuscript` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `code` varchar(45) CHARACTER SET utf8 NOT NULL, - `description` text COLLATE utf8_unicode_ci, - `enabled` tinyint(1) NOT NULL DEFAULT '1', - PRIMARY KEY (`id`), - UNIQUE KEY `code_UNIQUE` (`code`) -) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `message` --- - -DROP TABLE IF EXISTS `message`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `message` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `uuid` varchar(50) CHARACTER SET utf8 NOT NULL, - `sender` varchar(50) CHARACTER SET utf8 NOT NULL, - `recipient` varchar(50) CHARACTER SET utf8 NOT NULL, - `message` longtext CHARACTER SET utf8, - `sendDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `sender` (`sender`), - KEY `recipient` (`recipient`), - KEY `uuid` (`uuid`(8)) -) ENGINE=InnoDB AUTO_INCREMENT=1385526 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `messageInbox` --- - -DROP TABLE IF EXISTS `messageInbox`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `messageInbox` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `uuid` varchar(50) CHARACTER SET utf8 NOT NULL, - `sender` varchar(50) CHARACTER SET utf8 NOT NULL, - `recipient` varchar(45) CHARACTER SET utf8 NOT NULL, - `finalRecipient` varchar(50) CHARACTER SET utf8 NOT NULL, - `message` longtext CHARACTER SET utf8, - `sendDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `read` varchar(45) CHARACTER SET utf8 NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - KEY `uuid` (`uuid`(8)), - KEY `finalRecipient` (`finalRecipient`) -) ENGINE=InnoDB AUTO_INCREMENT=1530071 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `movement` --- - -DROP TABLE IF EXISTS `movement`; -/*!50001 DROP VIEW IF EXISTS `movement`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `movement` AS SELECT - 1 AS `id`, - 1 AS `item`, - 1 AS `ticket`, - 1 AS `concept`, - 1 AS `amount`, - 1 AS `quantity`, - 1 AS `price`, - 1 AS `discount`, - 1 AS `cost`, - 1 AS `reservado`, - 1 AS `od`, - 1 AS `priceFixed`, - 1 AS `lastUpdate`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `movementkk` --- - -DROP TABLE IF EXISTS `movementkk`; -/*!50001 DROP VIEW IF EXISTS `movementkk`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `movementkk` AS SELECT - 1 AS `id`, - 1 AS `item`, - 1 AS `ticket`, - 1 AS `concept`, - 1 AS `amount`, - 1 AS `quantity`, - 1 AS `price`, - 1 AS `discount`, - 1 AS `cost`, - 1 AS `reservado`, - 1 AS `od`, - 1 AS `priceFixed`, - 1 AS `lastUpdate`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `noticeCategory` --- - -DROP TABLE IF EXISTS `noticeCategory`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `noticeCategory` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `keyName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `subject` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `description` text COLLATE utf8_unicode_ci, - `isEnabled` tinyint(1) NOT NULL DEFAULT '1', - `requiredRole` int(11) NOT NULL DEFAULT '1', - PRIMARY KEY (`id`), - UNIQUE KEY `keyName_UNIQUE` (`keyName`) -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `noticeSubscription` --- - -DROP TABLE IF EXISTS `noticeSubscription`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `noticeSubscription` ( - `noticeCategoryFk` int(11) NOT NULL DEFAULT '0', - `userFk` int(10) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`noticeCategoryFk`,`userFk`), - KEY `noticeSubscription_ibfk_2` (`userFk`), - CONSTRAINT `noticeSubscription_ibfk_1` FOREIGN KEY (`noticeCategoryFk`) REFERENCES `noticeCategory` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `noticeSubscription_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `observationType` --- - -DROP TABLE IF EXISTS `observationType`; -/*!50001 DROP VIEW IF EXISTS `observationType`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `observationType` AS SELECT - 1 AS `id`, - 1 AS `description`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `origin` --- - -DROP TABLE IF EXISTS `origin`; -/*!50001 DROP VIEW IF EXISTS `origin`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `origin` AS SELECT - 1 AS `id`, - 1 AS `code`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `originI18n` --- - -DROP TABLE IF EXISTS `originI18n`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `originI18n` ( - `originFk` tinyint(2) unsigned NOT NULL, - `lang` char(2) CHARACTER SET utf8 NOT NULL, - `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`originFk`,`lang`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `originL10n` --- - -DROP TABLE IF EXISTS `originL10n`; -/*!50001 DROP VIEW IF EXISTS `originL10n`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `originL10n` AS SELECT - 1 AS `id`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `outgoingInvoice` --- - -DROP TABLE IF EXISTS `outgoingInvoice`; -/*!50001 DROP VIEW IF EXISTS `outgoingInvoice`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `outgoingInvoice` AS SELECT - 1 AS `id`, - 1 AS `serie`, - 1 AS `dateInvoice`, - 1 AS `total`, - 1 AS `dueDate`, - 1 AS `bank`, - 1 AS `client`, - 1 AS `remittance`, - 1 AS `remit`, - 1 AS `worker`, - 1 AS `creationDate`, - 1 AS `company`, - 1 AS `liquidacion?`, - 1 AS `isPdf`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `outgoingInvoiceVat` --- - -DROP TABLE IF EXISTS `outgoingInvoiceVat`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `outgoingInvoiceVat` ( - `outgoingInvoice` mediumint(8) NOT NULL, - `taxBase` decimal(12,2) DEFAULT NULL, - `equalizationTax` decimal(12,2) DEFAULT NULL, - `Vat` decimal(12,2) DEFAULT NULL, - PRIMARY KEY (`outgoingInvoice`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `package` --- - -DROP TABLE IF EXISTS `package`; -/*!50001 DROP VIEW IF EXISTS `package`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `package` AS SELECT - 1 AS `id`, - 1 AS `volume`, - 1 AS `width`, - 1 AS `height`, - 1 AS `depth`, - 1 AS `isPackageReturnable`, - 1 AS `created`, - 1 AS `itemFk`, - 1 AS `price`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `packageEquivalent` --- - -DROP TABLE IF EXISTS `packageEquivalent`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `packageEquivalent` ( - `packageFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `equivalentFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`packageFk`,`equivalentFk`), - KEY `packageEquivalent_fk2_idx` (`equivalentFk`), - CONSTRAINT `packageEquivalent_fk1` FOREIGN KEY (`packageFk`) REFERENCES `vn2008`.`Cubos` (`Id_Cubo`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `packageEquivalent_fk2` FOREIGN KEY (`equivalentFk`) REFERENCES `vn2008`.`Cubos` (`Id_Cubo`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='recoge los modelos de cubos que se han de sustituir a efectos de presentar informes resumidos'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `packageEquivalentItem` --- - -DROP TABLE IF EXISTS `packageEquivalentItem`; -/*!50001 DROP VIEW IF EXISTS `packageEquivalentItem`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `packageEquivalentItem` AS SELECT - 1 AS `itemFk`, - 1 AS `equivalentFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `payMethod` --- - -DROP TABLE IF EXISTS `payMethod`; -/*!50001 DROP VIEW IF EXISTS `payMethod`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `payMethod` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `graceDays`, - 1 AS `outstandingDebt`, - 1 AS `ibanRequired`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `payment` --- - -DROP TABLE IF EXISTS `payment`; -/*!50001 DROP VIEW IF EXISTS `payment`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `payment` AS SELECT - 1 AS `id`, - 1 AS `received`, - 1 AS `supplierFk`, - 1 AS `amount`, - 1 AS `currencyFk`, - 1 AS `divisa`, - 1 AS `bankFk`, - 1 AS `payMethod`, - 1 AS `companyFk`, - 1 AS `paymentExchangeInsuranceFk`, - 1 AS `isConciliate`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `paymentExchangeInsurance` --- - -DROP TABLE IF EXISTS `paymentExchangeInsurance`; -/*!50001 DROP VIEW IF EXISTS `paymentExchangeInsurance`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `paymentExchangeInsurance` AS SELECT - 1 AS `id`, - 1 AS `amount`, - 1 AS `created`, - 1 AS `dueDay`, - 1 AS `entityFk`, - 1 AS `ref`, - 1 AS `rate`, - 1 AS `companyFk`, - 1 AS `financialProductTypefk`, - 1 AS `upperBarrier`, - 1 AS `lowerBarrier`, - 1 AS `strike`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `payrollCenter` --- - -DROP TABLE IF EXISTS `payrollCenter`; -/*!50001 DROP VIEW IF EXISTS `payrollCenter`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `payrollCenter` AS SELECT - 1 AS `codCenter`, - 1 AS `name`, - 1 AS `nss`, - 1 AS `street`, - 1 AS `city`, - 1 AS `postcode`, - 1 AS `companyFk`, - 1 AS `companyCode`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `person` --- - -DROP TABLE IF EXISTS `person`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `person` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `firstname` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `surnames` varchar(60) COLLATE utf8_unicode_ci NOT NULL, - `fi` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `birth` date DEFAULT NULL, - `readerId` int(11) DEFAULT NULL, - `workerFk` int(11) DEFAULT NULL, - `isDisable` tinyint(1) NOT NULL DEFAULT '0', - `isFreelance` tinyint(1) NOT NULL DEFAULT '0', - `isSsDiscounted` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - UNIQUE KEY `nif` (`fi`), - KEY `nifIndex` (`fi`), - KEY `workerFk_idx` (`workerFk`) -) ENGINE=InnoDB AUTO_INCREMENT=818 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `pgc` --- - -DROP TABLE IF EXISTS `pgc`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `pgc` ( - `code` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `rate` decimal(10,2) NOT NULL, - `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `cplusTaxBreakFk` int(10) unsigned DEFAULT '1', - `mod340` tinyint(1) NOT NULL DEFAULT '0', - `mod347` tinyint(1) NOT NULL DEFAULT '0', - `cplusTrascendency477Fk` int(10) unsigned DEFAULT '1', - PRIMARY KEY (`code`), - KEY `pgc_fk1_idx` (`cplusTaxBreakFk`), - KEY `pgc_fk2_idx` (`cplusTrascendency477Fk`), - CONSTRAINT `pgc_fk1` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE, - CONSTRAINT `pgc_fk2` FOREIGN KEY (`cplusTrascendency477Fk`) REFERENCES `cplusTrascendency477` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Plan General Contable'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `pgcEqu` --- - -DROP TABLE IF EXISTS `pgcEqu`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `pgcEqu` ( - `vatFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Cuenta de IVA', - `equFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Cuenta de recargo de equivalencia', - PRIMARY KEY (`vatFk`,`equFk`), - KEY `pgcEqu_fk2_idx` (`equFk`), - CONSTRAINT `pgcEqu_fk1` FOREIGN KEY (`vatFk`) REFERENCES `pgc` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `pgcEqu_fk2` FOREIGN KEY (`equFk`) REFERENCES `pgc` (`code`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Recoge las cuentas contables con recargo de equivalencia e identifica a la que corresponde al iva y la que corresponde al recargo'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `plantpassport` --- - -DROP TABLE IF EXISTS `plantpassport`; -/*!50001 DROP VIEW IF EXISTS `plantpassport`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `plantpassport` AS SELECT - 1 AS `producerFk`, - 1 AS `plantpassportAuthorityFk`, - 1 AS `number`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `plantpassportAuthority` --- - -DROP TABLE IF EXISTS `plantpassportAuthority`; -/*!50001 DROP VIEW IF EXISTS `plantpassportAuthority`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `plantpassportAuthority` AS SELECT - 1 AS `id`, - 1 AS `denomination`, - 1 AS `countryFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `postCode` --- - -DROP TABLE IF EXISTS `postCode`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `postCode` ( - `code` char(5) COLLATE utf8_unicode_ci NOT NULL, - `townFk` int(11) NOT NULL, - `geoFk` int(11) DEFAULT NULL, - PRIMARY KEY (`code`,`townFk`), - KEY `postCodeTownFk_idx` (`townFk`), - CONSTRAINT `postCodeTownFk` FOREIGN KEY (`townFk`) REFERENCES `town` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `priceBuilder` --- - -DROP TABLE IF EXISTS `priceBuilder`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `priceBuilder` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `itemTypeFk` smallint(5) unsigned NOT NULL COMMENT 'Sirve para definir precios en tarifa2 para grupos de items', - `started` date DEFAULT NULL, - `finished` date DEFAULT NULL, - `price` decimal(10,3) NOT NULL, - `userFk` int(10) unsigned DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `priceBuilder_fk1_idx` (`itemTypeFk`), - KEY `priceBuilder_fk2_idx` (`userFk`), - CONSTRAINT `priceBuilder_fk1` FOREIGN KEY (`itemTypeFk`) REFERENCES `vn2008`.`Tipos` (`tipo_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `priceBuilder_fk2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `priceBuilderDistinctTags` --- - -DROP TABLE IF EXISTS `priceBuilderDistinctTags`; -/*!50001 DROP VIEW IF EXISTS `priceBuilderDistinctTags`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `priceBuilderDistinctTags` AS SELECT - 1 AS `priceBuilderFk`, - 1 AS `numTags`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `priceBuilderTag` --- - -DROP TABLE IF EXISTS `priceBuilderTag`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `priceBuilderTag` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `priceBuilderFk` int(11) NOT NULL, - `tagFk` int(11) NOT NULL, - `value` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`), - KEY `priceBuilderTag_fk1_idx` (`priceBuilderFk`), - KEY `priceBuilderTag_fk2_idx` (`tagFk`), - CONSTRAINT `priceBuilderTag_fk1` FOREIGN KEY (`priceBuilderFk`) REFERENCES `priceBuilder` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `priceBuilderTag_fk2` FOREIGN KEY (`tagFk`) REFERENCES `tag` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `priceBuilderWarehouse` --- - -DROP TABLE IF EXISTS `priceBuilderWarehouse`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `priceBuilderWarehouse` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `warehouseFk` smallint(6) unsigned NOT NULL, - `priceBuilderFk` int(11) NOT NULL, - PRIMARY KEY (`id`), - KEY `priceBuilderWarehouse_fk1_idx` (`warehouseFk`), - KEY `priceBuilderWarehouse_fk2_idx` (`priceBuilderFk`), - CONSTRAINT `priceBuilderWarehouse_fk1` FOREIGN KEY (`warehouseFk`) REFERENCES `vn2008`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `priceBuilderWarehouse_fk2` FOREIGN KEY (`priceBuilderFk`) REFERENCES `priceBuilder` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `priceFixed` --- - -DROP TABLE IF EXISTS `priceFixed`; -/*!50001 DROP VIEW IF EXISTS `priceFixed`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `priceFixed` AS SELECT - 1 AS `itemFk`, - 1 AS `rate0`, - 1 AS `rate1`, - 1 AS `rate2`, - 1 AS `rate3`, - 1 AS `started`, - 1 AS `ended`, - 1 AS `bonus`, - 1 AS `warehouseFk`, - 1 AS `created`, - 1 AS `id`, - 1 AS `grouping`, - 1 AS `packing`, - 1 AS `box`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `printServerQueue` --- - -DROP TABLE IF EXISTS `printServerQueue`; -/*!50001 DROP VIEW IF EXISTS `printServerQueue`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `printServerQueue` AS SELECT - 1 AS `id`, - 1 AS `printerFk`, - 1 AS `priorityFk`, - 1 AS `reportFk`, - 1 AS `statusFk`, - 1 AS `started`, - 1 AS `finished`, - 1 AS `param1`, - 1 AS `workerFk`, - 1 AS `param2`, - 1 AS `param3`, - 1 AS `error`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `printingQueue` --- - -DROP TABLE IF EXISTS `printingQueue`; -/*!50001 DROP VIEW IF EXISTS `printingQueue`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `printingQueue` AS SELECT - 1 AS `id`, - 1 AS `printer`, - 1 AS `priority`, - 1 AS `report`, - 1 AS `state`, - 1 AS `startingTime`, - 1 AS `endingTime`, - 1 AS `text`, - 1 AS `worker`, - 1 AS `text2`, - 1 AS `text3`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `producer` --- - -DROP TABLE IF EXISTS `producer`; -/*!50001 DROP VIEW IF EXISTS `producer`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `producer` AS SELECT - 1 AS `id`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `profile` --- - -DROP TABLE IF EXISTS `profile`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `profile` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `personFk` int(11) DEFAULT NULL, - `profileTypeFk` int(11) NOT NULL DEFAULT '1', - PRIMARY KEY (`id`), - KEY `personFk` (`personFk`), - KEY `profileTypeFk` (`profileTypeFk`), - CONSTRAINT `profile_ibfk_1` FOREIGN KEY (`personFk`) REFERENCES `person` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `profile_ibfk_2` FOREIGN KEY (`profileTypeFk`) REFERENCES `profileType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=697 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `profileType` --- - -DROP TABLE IF EXISTS `profileType`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `profileType` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `promissoryNote` --- - -DROP TABLE IF EXISTS `promissoryNote`; -/*!50001 DROP VIEW IF EXISTS `promissoryNote`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `promissoryNote` AS SELECT - 1 AS `id`, - 1 AS `Concept`, - 1 AS `paymentFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `province` --- - -DROP TABLE IF EXISTS `province`; -/*!50001 DROP VIEW IF EXISTS `province`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `province` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `countryFk`, - 1 AS `warehouseFk`, - 1 AS `zoneFk`, - 1 AS `geoFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `receipt` --- - -DROP TABLE IF EXISTS `receipt`; -/*!50001 DROP VIEW IF EXISTS `receipt`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `receipt` AS SELECT - 1 AS `Id`, - 1 AS `invoiceFk`, - 1 AS `amountPaid`, - 1 AS `amountUnpaid`, - 1 AS `payed`, - 1 AS `workerFk`, - 1 AS `bankFk`, - 1 AS `clientFk`, - 1 AS `created`, - 1 AS `companyFk`, - 1 AS `isConciliate`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `recovery` --- - -DROP TABLE IF EXISTS `recovery`; -/*!50001 DROP VIEW IF EXISTS `recovery`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `recovery` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `started`, - 1 AS `finished`, - 1 AS `amount`, - 1 AS `period`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `referenceRate` --- - -DROP TABLE IF EXISTS `referenceRate`; -/*!50001 DROP VIEW IF EXISTS `referenceRate`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `referenceRate` AS SELECT - 1 AS `currencyFk`, - 1 AS `dated`, - 1 AS `value`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `role` --- - -DROP TABLE IF EXISTS `role`; -/*!50001 DROP VIEW IF EXISTS `role`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `role` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `description`, - 1 AS `hasLogin`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `route` --- - -DROP TABLE IF EXISTS `route`; -/*!50001 DROP VIEW IF EXISTS `route`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `route` AS SELECT - 1 AS `id`, - 1 AS `workerFk`, - 1 AS `created`, - 1 AS `vehicleFk`, - 1 AS `agencyModeFk`, - 1 AS `time`, - 1 AS `isOk`, - 1 AS `kmStart`, - 1 AS `kmEnd`, - 1 AS `started`, - 1 AS `finished`, - 1 AS `gestdocFk`, - 1 AS `cost`, - 1 AS `m3`, - 1 AS `description`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `routeGate` --- - -DROP TABLE IF EXISTS `routeGate`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `routeGate` ( - `deviceId` varchar(30) CHARACTER SET utf8 NOT NULL, - `displayText` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `status` set('idle','doing','done','') CHARACTER SET utf8 DEFAULT 'idle', - `gateAreaFk` int(11) NOT NULL DEFAULT '1', - `routeFk` int(11) DEFAULT NULL, - `freeTickets` int(11) DEFAULT NULL, - `expeditions` int(11) DEFAULT NULL, - `scanned` int(11) DEFAULT NULL, - `flag` blob, - `pallets` int(11) DEFAULT NULL, - `lastScanned` datetime DEFAULT NULL, - PRIMARY KEY (`deviceId`), - UNIQUE KEY `routeFk_UNIQUE` (`routeFk`), - KEY `routeGate_fk1_idx` (`gateAreaFk`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`routeGateBeforeUpdate` - BEFORE UPDATE ON `routeGate` - FOR EACH ROW -BEGIN - IF (NOT (NEW.expeditions <=> OLD.expeditions) - OR NOT (NEW.scanned <=> OLD.scanned)) - AND NEW.status <=> OLD.status - THEN - IF NEW.expeditions = 0 - THEN - SET NEW.status = 'idle'; - ELSEIF NEW.expeditions = NEW.scanned - THEN - SET NEW.status = 'done'; - ELSE - SET NEW.status = 'doing'; - END IF; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `routeLog` --- - -DROP TABLE IF EXISTS `routeLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `routeLog` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `originFk` int(11) NOT NULL, - `userFk` int(10) unsigned NOT NULL, - `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, - `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `description` text COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=375081 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `routesControl` --- - -DROP TABLE IF EXISTS `routesControl`; -/*!50001 DROP VIEW IF EXISTS `routesControl`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `routesControl` AS SELECT - 1 AS `routeFk`, - 1 AS `expeditions`, - 1 AS `scanned`, - 1 AS `pallets`, - 1 AS `lastScanned`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `sale` --- - -DROP TABLE IF EXISTS `sale`; -/*!50001 DROP VIEW IF EXISTS `sale`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `sale` AS SELECT - 1 AS `id`, - 1 AS `itemFk`, - 1 AS `ticketFk`, - 1 AS `concept`, - 1 AS `quantity`, - 1 AS `price`, - 1 AS `discount`, - 1 AS `reserved`, - 1 AS `isPicked`, - 1 AS `created`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `saleComponent` --- - -DROP TABLE IF EXISTS `saleComponent`; -/*!50001 DROP VIEW IF EXISTS `saleComponent`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `saleComponent` AS SELECT - 1 AS `saleFk`, - 1 AS `componentFk`, - 1 AS `value`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `sms` --- - -DROP TABLE IF EXISTS `sms`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `sms` ( - `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `senderFk` int(11) NOT NULL, - `destinationFk` int(11) DEFAULT NULL, - `sender` varchar(15) CHARACTER SET utf8 NOT NULL DEFAULT '693474205', - `destination` varchar(15) CHARACTER SET utf8 NOT NULL, - `message` varchar(160) COLLATE utf8_unicode_ci NOT NULL, - `statusCode` smallint(9) NOT NULL DEFAULT '0', - `status` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=89795 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `smsConfig` --- - -DROP TABLE IF EXISTS `smsConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `smsConfig` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `uri` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `user` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `password` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `title` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='SMS configuration parameters'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `solunionCAP` --- - -DROP TABLE IF EXISTS `solunionCAP`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `solunionCAP` ( - `creditInsurance` int(11) NOT NULL, - `dateStart` date NOT NULL, - `dateEnd` date NOT NULL, - `dateLeaving` date DEFAULT NULL, - PRIMARY KEY (`creditInsurance`,`dateStart`), - KEY `solunionCAPdateLeavingIdx` (`dateLeaving`), - CONSTRAINT `solunionCAP` FOREIGN KEY (`creditInsurance`) REFERENCES `creditInsurance` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`solunionCAP_AFTER_INSERT` AFTER INSERT ON `solunionCAP` FOR EACH ROW -BEGIN - UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client - JOIN creditInsurance ci ON ci.creditClassification = cc.id - SET creditInsurance = ci.credit * 2 WHERE ci.id = NEW.creditInsurance; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`solunionCAP_AFTER_UPDATE` AFTER UPDATE ON `solunionCAP` FOR EACH ROW -BEGIN - IF NEW.dateLeaving IS NOT NULL THEN - UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client - JOIN creditInsurance ci ON ci.creditClassification = cc.id - SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; - ELSE - UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client - JOIN creditInsurance ci ON ci.creditClassification = cc.id - SET creditInsurance = ci.credit * 2 WHERE ci.id = OLD.creditInsurance; - 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 */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`solunionCAP_BEFORE_DELETE` BEFORE DELETE ON `solunionCAP` FOR EACH ROW -BEGIN - UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client - JOIN creditInsurance ci ON ci.creditClassification = cc.id - SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- --- Temporary view structure for view `state` --- - -DROP TABLE IF EXISTS `state`; -/*!50001 DROP VIEW IF EXISTS `state`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `state` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `order`, - 1 AS `alertLevel`, - 1 AS `code`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `stockBuyed` --- - -DROP TABLE IF EXISTS `stockBuyed`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `stockBuyed` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `user` int(10) unsigned DEFAULT NULL, - `buyed` decimal(10,2) DEFAULT NULL, - `date` date DEFAULT NULL, - `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `reserved` decimal(10,2) DEFAULT NULL, - `requested` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `date_UNIQUE` (`date`,`user`), - KEY `stockBuyed_user_idx` (`user`), - CONSTRAINT `stockBuyedUserFk` FOREIGN KEY (`user`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=254813 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `supplier` --- - -DROP TABLE IF EXISTS `supplier`; -/*!50001 DROP VIEW IF EXISTS `supplier`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `supplier` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `account`, - 1 AS `countryFk`, - 1 AS `nif`, - 1 AS `isFarmer`, - 1 AS `retAccount`, - 1 AS `commission`, - 1 AS `created`, - 1 AS `postcodeFk`, - 1 AS `isActive`, - 1 AS `street`, - 1 AS `city`, - 1 AS `provinceFk`, - 1 AS `postCode`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `supplierAccount` --- - -DROP TABLE IF EXISTS `supplierAccount`; -/*!50001 DROP VIEW IF EXISTS `supplierAccount`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `supplierAccount` AS SELECT - 1 AS `id`, - 1 AS `supplierFk`, - 1 AS `iban`, - 1 AS `bankEntityFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `tag` --- - -DROP TABLE IF EXISTS `tag`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tag` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(25) CHARACTER SET utf8 NOT NULL, - `isFree` tinyint(1) NOT NULL DEFAULT '1', - `isQuantitatif` tinyint(4) NOT NULL DEFAULT '1', - `sourceTable` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `unit` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=71 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Categorias para etiquetar los productos'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tagI18n` --- - -DROP TABLE IF EXISTS `tagI18n`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tagI18n` ( - `tagFk` int(10) unsigned NOT NULL, - `lang` char(2) CHARACTER SET utf8 NOT NULL, - `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`tagFk`,`lang`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `tagL10n` --- - -DROP TABLE IF EXISTS `tagL10n`; -/*!50001 DROP VIEW IF EXISTS `tagL10n`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `tagL10n` AS SELECT - 1 AS `id`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `taxArea` --- - -DROP TABLE IF EXISTS `taxArea`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `taxArea` ( - `code` varchar(15) CHARACTER SET utf8 NOT NULL, - `ClaveOperacionFactura` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, - `CodigoTransaccion` int(2) DEFAULT NULL, - PRIMARY KEY (`code`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `taxClass` --- - -DROP TABLE IF EXISTS `taxClass`; -/*!50001 DROP VIEW IF EXISTS `taxClass`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `taxClass` AS SELECT - 1 AS `id`, - 1 AS `description`, - 1 AS `code`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `taxClassCode` --- - -DROP TABLE IF EXISTS `taxClassCode`; -/*!50001 DROP VIEW IF EXISTS `taxClassCode`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `taxClassCode` AS SELECT - 1 AS `taxClassFk`, - 1 AS `effectived`, - 1 AS `taxCodeFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `taxCode` --- - -DROP TABLE IF EXISTS `taxCode`; -/*!50001 DROP VIEW IF EXISTS `taxCode`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `taxCode` AS SELECT - 1 AS `id`, - 1 AS `dated`, - 1 AS `code`, - 1 AS `taxTypeFk`, - 1 AS `rate`, - 1 AS `equalizationTax`, - 1 AS `type`, - 1 AS `link`, - 1 AS `isActive`, - 1 AS `updated`, - 1 AS `transactionCode`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `taxType` --- - -DROP TABLE IF EXISTS `taxType`; -/*!50001 DROP VIEW IF EXISTS `taxType`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `taxType` AS SELECT - 1 AS `id`, - 1 AS `nickname`, - 1 AS `isAccrued`, - 1 AS `serial`, - 1 AS `TIPOOPE`, - 1 AS `description`, - 1 AS `countryFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `ticket` --- - -DROP TABLE IF EXISTS `ticket`; -/*!50001 DROP VIEW IF EXISTS `ticket`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ticket` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `warehouseFk`, - 1 AS `shipped`, - 1 AS `landed`, - 1 AS `nickname`, - 1 AS `refFk`, - 1 AS `addressFk`, - 1 AS `location`, - 1 AS `solution`, - 1 AS `routeFk`, - 1 AS `companyFk`, - 1 AS `agencyModeFk`, - 1 AS `priority`, - 1 AS `packages`, - 1 AS `created`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `ticketLog` --- - -DROP TABLE IF EXISTS `ticketLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ticketLog` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `originFk` int(11) NOT NULL, - `userFk` int(10) unsigned NOT NULL, - `action` set('insert','update','delete','select') COLLATE utf8_unicode_ci NOT NULL, - `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `description` text COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`), - KEY `logTicketoriginFk` (`originFk`), - KEY `logTicketuserFk` (`userFk`), - CONSTRAINT `ticketLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `ticketLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=462427 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketLog_AFTER_INSERT` AFTER INSERT ON `ticketLog` FOR EACH ROW -BEGIN - DECLARE vActionId INT DEFAULT 84; - DECLARE vWorkerFk INT; - DECLARE vWebWorkerFk INT DEFAULT 4; - - SELECT id INTO vWorkerFk - FROM worker w - WHERE w.userFk = NEW.userFk; - - IF ISNULL(vWorkerFk) THEN - SET vWorkerFk = vWebWorkerFk; - END IF; - - INSERT INTO vn2008.Tickets_dits(idaccion_dits,Id_Trabajador,Id_Ticket,value_old,value_new) - VALUES (vActionId, vWorkerFk, NEW.originFk, NULL, NULL); -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 */ ; - --- --- Temporary view structure for view `ticketObservation` --- - -DROP TABLE IF EXISTS `ticketObservation`; -/*!50001 DROP VIEW IF EXISTS `ticketObservation`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ticketObservation` AS SELECT - 1 AS `id`, - 1 AS `ticketFk`, - 1 AS `observationTypeFk`, - 1 AS `description`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `ticketPackage` --- - -DROP TABLE IF EXISTS `ticketPackage`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ticketPackage` ( - `ticket` int(11) NOT NULL, - `counter` int(10) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`ticket`), - CONSTRAINT `ticketPackage_ticketFk` FOREIGN KEY (`ticket`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ticketPackaging` --- - -DROP TABLE IF EXISTS `ticketPackaging`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ticketPackaging` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `ticketFk` int(11) NOT NULL, - `packagingFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `quantity` int(10) DEFAULT '0', - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `pvp` double DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `ticketPackaging_fk1_idx` (`ticketFk`), - KEY `ticketPackaging_fk2_idx` (`packagingFk`), - CONSTRAINT `ticketPackaging_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `ticketPackaging_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `vn2008`.`Cubos` (`Id_Cubo`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=12252 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ticketPackagingStartingStock` --- - -DROP TABLE IF EXISTS `ticketPackagingStartingStock`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ticketPackagingStartingStock` ( - `clientFk` int(11) NOT NULL, - `packagingFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL, - `itemFk` int(11) NOT NULL, - `sent` int(11) DEFAULT NULL, - `returned` int(11) DEFAULT NULL, - PRIMARY KEY (`clientFk`,`packagingFk`), - KEY `ticketPackagingStartingStock_fk2_idx` (`packagingFk`), - KEY `ticketPackagingStartingStock_fk3_idx` (`itemFk`), - CONSTRAINT `ticketPackagingStartingStock_fk1` FOREIGN KEY (`clientFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `ticketPackagingStartingStock_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `vn2008`.`Cubos` (`Id_Cubo`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `ticketPackagingStartingStock_fk3` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `ticketState` --- - -DROP TABLE IF EXISTS `ticketState`; -/*!50001 DROP VIEW IF EXISTS `ticketState`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ticketState` AS SELECT - 1 AS `updated`, - 1 AS `stateFk`, - 1 AS `workerFk`, - 1 AS `ticketFk`, - 1 AS `state`, - 1 AS `productionOrder`, - 1 AS `alertLevel`, - 1 AS `code`, - 1 AS `ticket`, - 1 AS `worker`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `ticketStateToday` --- - -DROP TABLE IF EXISTS `ticketStateToday`; -/*!50001 DROP VIEW IF EXISTS `ticketStateToday`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ticketStateToday` AS SELECT - 1 AS `ticket`, - 1 AS `state`, - 1 AS `productionOrder`, - 1 AS `alertLevel`, - 1 AS `worker`, - 1 AS `code`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `ticketTracking` --- - -DROP TABLE IF EXISTS `ticketTracking`; -/*!50001 DROP VIEW IF EXISTS `ticketTracking`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ticketTracking` AS SELECT - 1 AS `id`, - 1 AS `stateFk`, - 1 AS `created`, - 1 AS `ticketFk`, - 1 AS `workerFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `ticketTrolley` --- - -DROP TABLE IF EXISTS `ticketTrolley`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ticketTrolley` ( - `ticket` int(11) NOT NULL, - `labelCount` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`ticket`), - CONSTRAINT `fk_ticketTrolley_vs_ticket` FOREIGN KEY (`ticket`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `till` --- - -DROP TABLE IF EXISTS `till`; -/*!50001 DROP VIEW IF EXISTS `till`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `till` AS SELECT - 1 AS `id`, - 1 AS `created`, - 1 AS `serie`, - 1 AS `concept`, - 1 AS `in`, - 1 AS `out`, - 1 AS `bankFk`, - 1 AS `supplierFk`, - 1 AS `isAccountable`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `tillConfig` --- - -DROP TABLE IF EXISTS `tillConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tillConfig` ( - `id` int(11) NOT NULL, - `openingBalance` decimal(10,2) NOT NULL, - `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `time` --- - -DROP TABLE IF EXISTS `time`; -/*!50001 DROP VIEW IF EXISTS `time`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `time` AS SELECT - 1 AS `dated`, - 1 AS `period`, - 1 AS `month`, - 1 AS `year`, - 1 AS `day`, - 1 AS `week`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `town` --- - -DROP TABLE IF EXISTS `town`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `town` ( - `id` int(11) NOT NULL, - `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - `provinceFk` smallint(6) unsigned NOT NULL, - `geoFk` int(11) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `townProvinceFk_idx` (`provinceFk`), - CONSTRAINT `townProvinceFk` FOREIGN KEY (`provinceFk`) REFERENCES `vn2008`.`province` (`province_id`) ON DELETE NO ACTION ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `travel` --- - -DROP TABLE IF EXISTS `travel`; -/*!50001 DROP VIEW IF EXISTS `travel`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `travel` AS SELECT - 1 AS `id`, - 1 AS `shipped`, - 1 AS `shipmentHour`, - 1 AS `landed`, - 1 AS `landingHour`, - 1 AS `warehouseInFk`, - 1 AS `warehouseOutFk`, - 1 AS `agencyFk`, - 1 AS `ref`, - 1 AS `isDelivered`, - 1 AS `isReceived`, - 1 AS `m3`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `travelObservation` --- - -DROP TABLE IF EXISTS `travelObservation`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `travelObservation` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `originFk` int(11) NOT NULL, - `userFk` int(11) NOT NULL, - `description` text COLLATE utf8_unicode_ci NOT NULL, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Observaciones de travel'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `unary` --- - -DROP TABLE IF EXISTS `unary`; -/*!50001 DROP VIEW IF EXISTS `unary`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `unary` AS SELECT - 1 AS `id`, - 1 AS `parent`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `unaryScan` --- - -DROP TABLE IF EXISTS `unaryScan`; -/*!50001 DROP VIEW IF EXISTS `unaryScan`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `unaryScan` AS SELECT - 1 AS `unaryFk`, - 1 AS `name`, - 1 AS `created`, - 1 AS `type`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `unaryScanLine` --- - -DROP TABLE IF EXISTS `unaryScanLine`; -/*!50001 DROP VIEW IF EXISTS `unaryScanLine`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `unaryScanLine` AS SELECT - 1 AS `id`, - 1 AS `code`, - 1 AS `created`, - 1 AS `unaryScanFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `unaryScanLineBuy` --- - -DROP TABLE IF EXISTS `unaryScanLineBuy`; -/*!50001 DROP VIEW IF EXISTS `unaryScanLineBuy`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `unaryScanLineBuy` AS SELECT - 1 AS `unaryScanLineFk`, - 1 AS `itemFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `unaryScanLineExpedition` --- - -DROP TABLE IF EXISTS `unaryScanLineExpedition`; -/*!50001 DROP VIEW IF EXISTS `unaryScanLineExpedition`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `unaryScanLineExpedition` AS SELECT - 1 AS `unaryScanLineFk`, - 1 AS `expeditionFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `user` --- - -DROP TABLE IF EXISTS `user`; -/*!50001 DROP VIEW IF EXISTS `user`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `user` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `password`, - 1 AS `role`, - 1 AS `active`, - 1 AS `recoverPass`, - 1 AS `lastPassChange`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `vehicle` --- - -DROP TABLE IF EXISTS `vehicle`; -/*!50001 DROP VIEW IF EXISTS `vehicle`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `vehicle` AS SELECT - 1 AS `id`, - 1 AS `numberPlate`, - 1 AS `tradeMark`, - 1 AS `model`, - 1 AS `companyFk`, - 1 AS `warehouseFk`, - 1 AS `description`, - 1 AS `m3`, - 1 AS `isActive`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `warehouse` --- - -DROP TABLE IF EXISTS `warehouse`; -/*!50001 DROP VIEW IF EXISTS `warehouse`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `warehouse` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `isInventory`, - 1 AS `isComparative`, - 1 AS `hasComission`, - 1 AS `isManaged`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `warehouseAlias` --- - -DROP TABLE IF EXISTS `warehouseAlias`; -/*!50001 DROP VIEW IF EXISTS `warehouseAlias`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `warehouseAlias` AS SELECT - 1 AS `id`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `workCenter` --- - -DROP TABLE IF EXISTS `workCenter`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `workCenter` ( - `id` int(11) NOT NULL DEFAULT '0', - `name` varchar(255) DEFAULT NULL, - `payrollCenterFk` int(11) DEFAULT NULL, - `counter` bigint(20) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `worker` --- - -DROP TABLE IF EXISTS `worker`; -/*!50001 DROP VIEW IF EXISTS `worker`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `worker` AS SELECT - 1 AS `id`, - 1 AS `workerCode`, - 1 AS `firstName`, - 1 AS `name`, - 1 AS `userFk`, - 1 AS `phone`, - 1 AS `bossFk`, - 1 AS `photo`, - 1 AS `fi`, - 1 AS `fiDueDate`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `workerDocument` --- - -DROP TABLE IF EXISTS `workerDocument`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `workerDocument` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `worker` int(10) unsigned DEFAULT NULL, - `document` int(11) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `workerDocument_ibfk_1` (`worker`), - KEY `workerDocument_ibfk_2` (`document`), - CONSTRAINT `workerDocument_ibfk_1` FOREIGN KEY (`worker`) REFERENCES `vn2008`.`Trabajadores` (`user_id`) ON UPDATE CASCADE, - CONSTRAINT `workerDocument_ibfk_2` FOREIGN KEY (`document`) REFERENCES `vn2008`.`gestdoc` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=3788 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `workerLog` --- - -DROP TABLE IF EXISTS `workerLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `workerLog` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `originFk` int(11) NOT NULL, - `userFk` int(10) unsigned NOT NULL, - `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, - `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `description` text COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`), - KEY `workerFk_idx` (`originFk`), - KEY `userFk_idx` (`userFk`), - CONSTRAINT `userFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT `workerFk` FOREIGN KEY (`originFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE NO ACTION -) ENGINE=InnoDB AUTO_INCREMENT=1476 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `workerTeam` --- - -DROP TABLE IF EXISTS `workerTeam`; -/*!50001 DROP VIEW IF EXISTS `workerTeam`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `workerTeam` AS SELECT - 1 AS `team`, - 1 AS `user`, - 1 AS `id`, - 1 AS `Id_Trabajador`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `workerTeam_kk` --- - -DROP TABLE IF EXISTS `workerTeam_kk`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `workerTeam_kk` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `team` int(11) NOT NULL, - `user` int(10) unsigned NOT NULL, - PRIMARY KEY (`id`), - KEY `user_team_idx` (`user`), - CONSTRAINT `user_team` FOREIGN KEY (`user`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=77 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `workingHours` --- - -DROP TABLE IF EXISTS `workingHours`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `workingHours` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `timeIn` datetime NOT NULL, - `timeOut` datetime DEFAULT NULL, - `userId` int(10) unsigned NOT NULL, - PRIMARY KEY (`id`), - KEY `user_working_hour_idx` (`userId`), - CONSTRAINT `user_working_hour` FOREIGN KEY (`userId`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=17538 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena horas de Entrada y de Salida del personal'; -/*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`workingHoursBeforeInsert` BEFORE INSERT ON `workingHours` FOR EACH ROW -BEGIN - IF (SELECT COUNT(*) FROM workingHours WHERE userId = NEW.userId AND DATE(timeIn) = CURDATE()) > 0 THEN - CALL util.throw ('ALREADY_LOGGED'); - 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 */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- --- Table structure for table `zone` --- - -DROP TABLE IF EXISTS `zone`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `zone` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(45) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, - `hour` int(11) NOT NULL, - `warehouseFk` int(11) NOT NULL, - `agencyFk` int(11) NOT NULL, - `travelingDays` int(11) NOT NULL DEFAULT '1', - `price` double NOT NULL DEFAULT '0', - `bonus` double NOT NULL DEFAULT '0', - PRIMARY KEY (`id`,`name`), - UNIQUE KEY `name_UNIQUE` (`name`) -) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `zoneCalendar` --- - -DROP TABLE IF EXISTS `zoneCalendar`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `zoneCalendar` ( - `zoneFk` int(11) NOT NULL, - `delivered` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`zoneFk`,`delivered`), - CONSTRAINT `zoneFk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `zoneGeo` --- - -DROP TABLE IF EXISTS `zoneGeo`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `zoneGeo` ( - `zoneFk` int(11) NOT NULL, - `geoFk` int(11) NOT NULL, - `isIncluded` tinyint(1) DEFAULT NULL, - PRIMARY KEY (`zoneFk`,`geoFk`), - KEY `geoFk_idx` (`geoFk`), - CONSTRAINT `geoFk` FOREIGN KEY (`geoFk`) REFERENCES `zoneNest` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT `zoneGeoFk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `zoneNest` --- - -DROP TABLE IF EXISTS `zoneNest`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `zoneNest` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - `lft` int(11) DEFAULT NULL, - `rgt` int(11) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=23039 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `zoneNestTree` --- - -DROP TABLE IF EXISTS `zoneNestTree`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `zoneNestTree` ( - `id` int(11) NOT NULL DEFAULT '0', - `name` longtext COLLATE utf8_unicode_ci, - `lft` int(11) DEFAULT NULL, - `rgt` int(11) DEFAULT NULL, - `depth` bigint(22) NOT NULL DEFAULT '0', - `sons` decimal(10,0) DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'vn' --- -/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `ticketClosure` */; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `ticketClosure` ON SCHEDULE EVERY 1 DAY STARTS '2017-09-18 00:30:00' ON COMPLETION NOT PRESERVE ENABLE COMMENT 'Realiza el cierre de todos los almacenes del dia actual' DO CALL ticketClosureMultiWarehouse(DATE_ADD(CURDATE(), INTERVAL -1 DAY)) */ ;; -/*!50003 SET time_zone = @saved_time_zone */ ;; -/*!50003 SET sql_mode = @saved_sql_mode */ ;; -/*!50003 SET character_set_client = @saved_cs_client */ ;; -/*!50003 SET character_set_results = @saved_cs_results */ ;; -/*!50003 SET collation_connection = @saved_col_connection */ ;; -DELIMITER ; -/*!50106 SET TIME_ZONE= @save_time_zone */ ; - --- --- Dumping routines for database 'vn' --- -/*!50003 DROP FUNCTION IF EXISTS `addressTaxArea` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `addressTaxArea`(vAddresId INT, vCompanyId INT) RETURNS varchar(25) CHARSET utf8 - DETERMINISTIC -BEGIN -/** - * Devuelve el area de un Consignatario, - * intracomunitario, extracomunitario, nacional o recargo de equivalencia. - * Asumimos que no tenemos ninguna empresa - * - * @param vAddresId Id del Consignatario - * @param vCompanyId Compañia desde la que se factura - * @return Código de area - */ - DECLARE vTaxArea VARCHAR(25); - DECLARE vClientIsUeeMember INT; - DECLARE vSupplierIsUeeMember INT; - DECLARE vSpainCountryCode INT DEFAULT 1; - DECLARE vSupplierCountry INT; - DECLARE vClientCountry INT; - DECLARE vIsEqualizated BOOLEAN; - DECLARE vIsVies BOOLEAN; - - SELECT cClient.isUeeMember, c.countryFk, a.isEqualizated, cSupplier.isUeeMember, s.countryFk, c.isVies - INTO vClientIsUeeMember, vClientCountry, vIsEqualizated, vSupplierIsUeeMember, vSupplierCountry, vIsVies - FROM address a - JOIN `client` c ON c.id = a.clientFk - JOIN country cClient ON cClient.id = c.countryFk - JOIN supplier s ON s.id = vCompanyId - JOIN country cSupplier ON cSupplier.id = s.countryFk - WHERE a.id = vAddresId; - - CASE - WHEN (NOT vClientIsUeeMember OR NOT vSupplierIsUeeMember) AND vSupplierCountry != vClientCountry THEN - SET vTaxArea = 'WORLD'; - WHEN vClientIsUeeMember AND vSupplierIsUeeMember AND vClientCountry != vSupplierCountry AND vIsVies THEN - SET vTaxArea = 'CEE'; - WHEN vIsEqualizated AND vClientCountry = vSpainCountryCode THEN - SET vTaxArea = 'EQU'; - ELSE - SET vTaxArea = 'NATIONAL'; - END CASE; - - RETURN vTaxArea; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `agencyIsAvailable` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `agencyIsAvailable`(vAgency INT, vDate DATE, vAddress INT) RETURNS tinyint(1) -BEGIN -/** - * Comprueba si la agencia esta disponible para la fecha y - * dirección dadas, es decir, si es posible enviar mercancía - * desde al menos uno de los almacenes por la agencia, fecha - * y direcciones especificadas. - * - * @param vAgency Id de agencia - * @param vDate Fecha de recepción de mercancía - * @param vAddress Id consignatario, %NULL para recogida - * @return %TRUE si la agencia esta disponible, %FALSE en caso contrario - */ - DECLARE vMaxDays INT DEFAULT DATEDIFF(vDate, CURDATE()); - DECLARE vWday TINYINT DEFAULT WEEKDAY(vDate); - DECLARE vHour TINYINT DEFAULT HOUR(NOW()); - DECLARE vProvince INT; - DECLARE isAvailable BOOL; - - SELECT provinceFk INTO vProvince - FROM address - WHERE id = vAddress; - - SELECT COUNT(*) > 0 INTO isAvailable - FROM agencyHour h - JOIN agencyMode a - ON a.agencyFk = h.agencyFk - WHERE (h.provinceFk = vProvince - OR h.provinceFk IS NULL) - AND (h.weekDay = vWday - OR h.weekDay IS NULL) - AND (h.substractDay < vMaxDays - OR (h.substractDay = vMaxDays AND h.maxHour > vHour)) - AND a.id = vAgency; - - RETURN isAvailable; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `clientGetDebt` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `clientGetDebt`(vClient INT, vDate DATE) RETURNS decimal(10,2) -BEGIN -/** - * Devuelve el saldo de un cliente. - * - * @param vClient Identificador del cliente - * @param vDate Fecha hasta la que tener en cuenta - * @return Saldo del cliente - */ - DECLARE vDateEnd DATETIME; - DECLARE vDateIni DATETIME; - DECLARE vDebt DECIMAL(10,2); - - SET vDate = IFNULL(vDate, CURDATE()); - - SET vDateIni = TIMESTAMPADD(MONTH, -2, CURDATE()); - SET vDateEnd = TIMESTAMP(vDate, '23:59:59'); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT id ticketFk - FROM ticket - WHERE clientFk = vClient - AND refFk IS NULL - AND shipped BETWEEN vDateIni AND vDateEnd; - - CALL vn.ticketGetTotal; - - SELECT IFNULL(SUM(t.amount), 0) INTO vDebt - FROM ( - SELECT SUM(total) amount - FROM tmp.ticketTotal - UNION ALL - SELECT SUM(Entregado) - FROM vn2008.Recibos - WHERE Id_Cliente = vClient - AND Fechacobro > vDateEnd - UNION ALL - SELECT SUM(amount) - FROM bi.customer_risk r - WHERE customer_id = vClient - UNION ALL - SELECT CAST(-SUM(amount) / 100 AS DECIMAL(10,2)) - FROM hedera.tpvTransaction - WHERE clientFk = vClient - AND receiptFk IS NULL - AND `status` = 'ok' - ) t; - - DROP TEMPORARY TABLE - tmp.ticket, - tmp.ticketTotal; - - RETURN vDebt; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `clientGetMana` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `clientGetMana`(vClient INT) RETURNS decimal(10,2) -BEGIN -/** - * Devuelve el maná del cliente. - * - * @param vClient Id del cliente - * @return Maná del cliente - */ - -DECLARE vMana DECIMAL(10,2); -DECLARE vFromDated DATE; - -SELECT max(dated) INTO vFromDated -FROM vn.clientManaCache -WHERE clientFk = vClient; - -SELECT sum(mana) INTO vMana - FROM - ( - SELECT mana - FROM vn.clientManaCache - WHERE clientFk = vClient - AND dated = vFromDated - - UNION ALL - - SELECT s.quantity * Valor - FROM vn.ticket t - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.sale s on s.ticketFk = t.id - JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = s.id - WHERE Id_Componente IN (37, 39) - AND t.shipped > vFromDated - AND t.clientFk = vClient - - UNION ALL - - SELECT - Entregado - FROM vn2008.Recibos r - JOIN vn2008.Clientes c using(Id_Cliente) - WHERE r.Id_Banco = 66 - AND r.Fechacobro > vFromDated - AND c.Id_Cliente = vClient - - UNION ALL - - SELECT g.Importe - FROM vn2008.Greuges g - JOIN vn2008.Clientes c using(Id_Cliente) - WHERE g.Greuges_type_id = 3 -- Maná - AND g.Fecha > vFromDated - AND c.Id_Cliente = vClient - - ) sub; - -RETURN IFNULL(vMana,0); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `clientTaxArea` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `clientTaxArea`(vClientId INT, vCompanyId INT) RETURNS varchar(25) CHARSET utf8 -BEGIN -/** - * Devuelve el area de un cliente, - * intracomunitario, extracomunitario y nacional. - * - * @param vClient Id del cliente - * @param vCompanyFk Compañia desde la que se factura - * @return Código de area - */ - DECLARE vTaxArea VARCHAR(25); - DECLARE vCee INT; - - SELECT ct.Cee INTO vCee - FROM `client` c - JOIN country ct ON ct.id = c.countryFk - JOIN supplier s ON s.id = vCompanyId - WHERE - c.id = vClientId - AND c.isVies - AND c.countryFk != s.countryFk; - - IF vCee < 2 THEN - SET vTaxArea = 'CEE'; - ELSEIF vCee = 2 THEN - SET vTaxArea = 'WORLD'; - ELSE - SET vTaxArea = 'NATIONAL'; - END IF; - - RETURN vTaxArea; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `getAlert3State` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getAlert3State`(vTicket INT) RETURNS varchar(45) CHARSET latin1 -BEGIN - DECLARE vDeliveryType INTEGER DEFAULT 0; - DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; - DECLARE vCode VARCHAR(45); - - SELECT a.Vista - INTO vDeliveryType - FROM vn2008.Tickets t - JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia - WHERE Id_Ticket = vTicket; - - CASE vDeliveryType - WHEN 1 THEN -- AGENCIAS - SET vCode = 'DELIVERED'; - - WHEN 2 THEN -- REPARTO - SET vCode = 'ON_DELIVERY'; - - ELSE -- MERCADO, OTROS - SELECT MIN(t.warehouse_id <> w.warehouse_id) INTO isWaitingForPickUp - FROM vn2008.Tickets t - LEFT JOIN vn2008.warehouse_pickup w - ON w.agency_id = t.Id_Agencia - WHERE t.Id_Ticket = vTicket; - - IF isWaitingForPickUp THEN - SET vCode = 'WAITING_FOR_PICKUP'; - ELSE - SET vCode = 'DELIVERED'; - END IF; - END CASE; - RETURN vCode; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `getAlert3StateKk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getAlert3StateKk`(vTicket INT) RETURNS varchar(45) CHARSET latin1 -BEGIN - DECLARE vDeliveryType INTEGER DEFAULT 0; - DECLARE vWorker INT; - DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; - DECLARE vCode VARCHAR(45); - - SELECT IFNULL(aw.Vista,a.Vista) INTO vDeliveryType - FROM vn2008.Tickets t - JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN vn2008.agency_warehouse aw ON a.agency_id = aw.agency_id AND t.warehouse_id = aw.warehouse_id - WHERE Id_Ticket = vTicket; - - SELECT getUser() INTO vWorker; - - CASE vDeliveryType - WHEN 1 THEN -- AGENCIAS - SELECT COUNT(*) INTO isWaitingForPickUp - FROM vn2008.Tickets t - JOIN vn2008.warehouse_pickup w ON w.agency_id = t.Id_Agencia - WHERE t.Id_Ticket = vTicket AND w.warehouse_id <> t.warehouse_id; - - IF isWaitingForPickUp THEN - SET vCode = 'WAITING_FOR_PICKUP'; - ELSE - SET vCode = 'DELIVERED'; - END IF; - - WHEN 2 THEN -- REPARTO - SET vCode = 'ON_DELIVERY'; - - ELSE -- MERCADO, OTROS - SET vCode = 'DELIVERED'; - END CASE; - RETURN vCode; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `getAlert3StateTest` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getAlert3StateTest`(vTicket INT) RETURNS varchar(45) CHARSET latin1 -BEGIN - DECLARE vDeliveryType INTEGER DEFAULT 0; - DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; - DECLARE vCode VARCHAR(45); - - SELECT - a.Vista - INTO vDeliveryType - FROM vn2008.Tickets t - JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia - WHERE Id_Ticket = vTicket; - - CASE vDeliveryType - WHEN 1 THEN -- AGENCIAS - SET vCode = 'DELIVERED'; - - WHEN 2 THEN -- REPARTO - SET vCode = 'ON_DELIVERY'; - - ELSE -- MERCADO, OTROS - SELECT t.warehouse_id <> w.warehouse_id INTO isWaitingForPickUp - FROM vn2008.Tickets t - LEFT JOIN vn2008.warehouse_pickup w - ON w.agency_id = t.Id_Agencia AND w.warehouse_id = t.warehouse_id - WHERE t.Id_Ticket = vTicket; - - IF isWaitingForPickUp THEN - SET vCode = 'WAITING_FOR_PICKUP'; - ELSE - SET vCode = 'DELIVERED'; - END IF; - END CASE; - RETURN vCode; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `getDueDate` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getDueDate`(vDated DATE, vDayToPay INT) RETURNS date -BEGIN - -DECLARE vDued DATE; - -SET vDued = IF (vDayToPay > 30 or vDayToPay < 1 - ,TIMESTAMPADD(DAY, vDayToPay, vDated) - ,TIMESTAMPADD(DAY, vDayToPay, LAST_DAY(vDated))); - -RETURN vDued; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP FUNCTION IF EXISTS `getInventoryDate` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getInventoryDate`() RETURNS date - DETERMINISTIC -BEGIN - RETURN vn2008.date_inv(); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP FUNCTION IF EXISTS `getNewItemId` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getNewItemId`() RETURNS int(11) -BEGIN - - DECLARE newItemId INT; - - SELECT i1.id + 1 INTO newItemId - FROM item i1 - LEFT JOIN item i2 ON i1.id + 1 = i2.id - WHERE i2.id IS NULL - ORDER BY i1.id - LIMIT 1; - - RETURN newItemId; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `getShipmentHour` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getShipmentHour`(vTicket INT) RETURNS int(11) -BEGIN - DECLARE vShipmentHour INT; - - SELECT HOUR(shipped) INTO vShipmentHour - FROM ticket - WHERE id = vTicket; - - IF vShipmentHour = 0 - THEN - DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; - CREATE TEMPORARY TABLE tmp.production_buffer - ENGINE = MEMORY - SELECT am.agencyFk as agency_id - , t.warehouseFk as warehouse_id - , a.provinceFk as province_id - , 0 as Hora - , 0 as Departure - FROM ticket t - JOIN agencyMode am on am.id = t.agencyModeFk - JOIN address a on a.id = t.addressFk - WHERE t.id = vTicket; - - CALL vn2008.production_buffer_set_priority; - - SELECT Hora INTO vShipmentHour - FROM tmp.production_buffer; - END IF; - - RETURN vShipmentHour; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `getSpecialPrice` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getSpecialPrice`(vItemFk int(11),vClientFk int(11)) RETURNS decimal(10,2) -BEGIN - DECLARE price DECIMAL(10,2); - - SELECT rate3 INTO price - FROM vn.priceFixed - WHERE itemFk = vItemFk - AND CURDATE() BETWEEN started AND ended ORDER BY created DESC LIMIT 1; - - SELECT `value` INTO price - FROM vn.especialPrice - WHERE itemFk = vItemFk - AND clientFk = vClientFk ; -RETURN price; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `getTicketToPrepare` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getTicketToPrepare`(`vWorker` INT, `vWarehouse` INT) RETURNS int(11) -BEGIN -/** - * Devuelve el ticket que debe de preparar el trabajador - * - * @param vWorker Id del trabajador - * @param vWarehouse Id del almacén - * @return Id del ticket - **/ - - DECLARE vToday DATETIME DEFAULT CURDATE(); - DECLARE vYesterday DATETIME; - DECLARE vTodayvMidniight DATETIME DEFAULT midnight(vToday); - DECLARE vTicket INT DEFAULT NULL; - - SET vYesterday = TIMESTAMPADD(DAY,-1,vToday); - - DROP TEMPORARY TABLE IF EXISTS tmp.workerComercial; - CREATE TEMPORARY TABLE tmp.workerComercial - ENGINE = MEMORY - SELECT worker FROM `grant` g - JOIN grantGroup gg ON g.`group` = gg.id - WHERE gg.description = 'Comerciales' - AND worker != 2; -- PAKO numero - - - DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; - CREATE TEMPORARY TABLE tmp.production_buffer - ENGINE = MEMORY - SELECT t.id as ticket - , am.agencyFk as agency_id - , t.warehouseFk as warehouse_id - , a.provinceFk as province_id - , Hour(t.shipped) as Hora - , Hour(t.shipped) as Departure - , Minute(t.shipped) as Minuto - , tls.code - , IFNULL(t.priority,0) loadingOrder - FROM ticket t - JOIN ticketState tls on t.id = tls.ticket - JOIN agencyMode am on am.id = t.agencyModeFk - JOIN address a on a.id = t.addressFk - LEFT JOIN tmp.workerComercial wc ON wc.worker = vWorker - WHERE t.shipped BETWEEN vYesterday AND vTodayvMidniight - AND t.warehouseFk = vWarehouse - AND - ( - (tls.code = 'PRINTED' AND wc.worker IS NULL) - OR - (tls.code ='PICKER_DESIGNED' AND tls.worker = vWorker) - OR - (tls.code = 'PRINTED_BACK') - ); - - - CALL vn2008.production_buffer_set_priority; - - SELECT ticket INTO vTicket - FROM tmp.production_buffer - ORDER BY (code = 'PICKER_DESIGNED') DESC , Hora, Minuto, loadingOrder - LIMIT 1; - - RETURN vTicket; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `getTicketTrolleyLabelCount` */; -ALTER DATABASE `vn` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getTicketTrolleyLabelCount`(vTicket INT) RETURNS int(11) -BEGIN - -DECLARE vLabelCount INT DEFAULT 0; - -SELECT labelCount INTO vLabelCount -FROM ticketTrolley -WHERE ticket = vTicket; - -SET vLabelCount = vLabelCount +1 ; - -REPLACE ticketTrolley(ticket,labelCount) -SELECT vTicket, vLabelCount; - -RETURN vlabelCount; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP FUNCTION IF EXISTS `getUser` */; -ALTER DATABASE `vn` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getUser`() RETURNS int(11) - DETERMINISTIC -BEGIN - RETURN getWorker(); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP FUNCTION IF EXISTS `getUserId` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getUserId`(userName varchar(30)) RETURNS int(11) -BEGIN - DECLARE vUser INT; - - SELECT id INTO vUser - FROM account.user - WHERE `name` = userName; - - RETURN vUser; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP FUNCTION IF EXISTS `getWorker` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getWorker`() RETURNS int(11) - DETERMINISTIC -BEGIN - DECLARE vUser INT; - - SELECT id INTO vUser - FROM worker - WHERE userFk = account.userGetId(); - - RETURN vUser; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `getWorkerkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `getWorkerkk`() RETURNS int(11) - DETERMINISTIC -BEGIN - DECLARE vUser INT; - - SELECT id INTO vUser - FROM worker - WHERE user = account.userGetId(); - - RETURN vUser; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `hasAnyNegativeBase` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `hasAnyNegativeBase`() RETURNS tinyint(1) -BEGIN - -/* Calcula si existe alguna base imponible negativa -* Requiere la tabla temporal vn.ticketToInvoice(id) -* -* returns BOOLEAN -*/ - - DECLARE vCountry INT; - DECLARE hasAnyNegativeBase BOOLEAN; - - SELECT s.countryFk - INTO vCountry - FROM supplier s - JOIN ticket t ON t.companyFk = s.id - JOIN vn.ticketToInvoice tl ON tl.id = t.id - LIMIT 1; - - SELECT COUNT(*) INTO hasAnyNegativeBase - FROM ( - SELECT SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)) taxableBase - FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN itemTaxCountry itc - ON itc.itemFk = i.id AND itc.countryFk = vCountry - JOIN vn.ticketToInvoice tl ON tl.id = s.ticketFk - GROUP BY itc.taxClassFk - HAVING taxableBase < 0 - ) t1 ; - - RETURN hasAnyNegativeBase; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `hasSomeNegativeBase` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `hasSomeNegativeBase`(vTicket INT) RETURNS tinyint(1) -BEGIN - - DECLARE vCountry INT; - DECLARE hasSomeNegativeBase BOOLEAN; - - SELECT s.countryFk - INTO vCountry - FROM supplier s - JOIN ticket t ON t.companyFk = s.id - WHERE t.id = vTicket; - - SELECT COUNT(*) INTO hasSomeNegativeBase - FROM ( - SELECT SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)) taxableBase - FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN itemTaxCountry itc - ON itc.itemFk = i.id AND itc.countryFk = vCountry - WHERE s.ticketFk = vTicket - GROUP BY itc.taxClassFk - HAVING taxableBase < 0 - ) t1 ; - - RETURN hasSomeNegativeBase; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `invoiceOutAmount` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `invoiceOutAmount`(vInvoiceRef VARCHAR(15)) RETURNS decimal(10,2) -BEGIN - DECLARE totalAmount DECIMAL(10,2); - - SELECT SUM(vat) INTO totalAmount - FROM - ( - SELECT iot.vat - FROM invoiceOutTax iot - JOIN invoiceOut io ON io.id = iot.invoiceOutFk - WHERE io.ref = vInvoiceRef - UNION ALL - SELECT ioe.amount - FROM invoiceOutExpence ioe - JOIN invoiceOut io ON io.id = ioe.invoiceOutFk - WHERE io.ref = vInvoiceRef - ) t1; - -RETURN totalAmount; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `invoiceSerial` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `invoiceSerial`(vClientFk INT, vCompanyFk INT, vType CHAR(1)) RETURNS char(1) CHARSET utf8 -BEGIN - /** - * Obtiene la serie de de una factura - * dependiendo del area del cliente. - * - * @param vClientFk Id del cliente - * @param vCompanyFk Id de la empresa - * @param vType Tipo de factura ["R", "M", "G"] - * @return Serie de la factura - */ - DECLARE vArea VARCHAR(25); - DECLARE vSerie CHAR(1); - - IF (SELECT hasInvoiceSimplified FROM client WHERE id = vClientFk) THEN - RETURN 'S'; - END IF; - - SELECT clientTaxArea(vClientFk, vCompanyFk) INTO vArea; - -- Factura rápida - IF vType = 'R' THEN - SELECT - CASE vArea - WHEN 'CEE' - THEN 'H' - WHEN 'WORLD' - THEN 'E' - WHEN 'NATIONAL' - THEN 'T' - END - INTO vSerie; - -- Factura multiple - ELSEIF vType = 'M' THEN - SELECT - CASE vArea - WHEN 'CEE' - THEN 'H' - WHEN 'WORLD' - THEN 'E' - WHEN 'NATIONAL' - THEN 'M' - END - INTO vSerie; - -- Factura global - ELSEIF vType = 'G' THEN - SELECT - CASE vArea - WHEN 'CEE' - THEN 'V' - WHEN 'WORLD' - THEN 'X' - WHEN 'NATIONAL' - THEN 'A' - END - INTO vSerie; - END IF; - RETURN vSerie; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `isPalletHomogeneus` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `isPalletHomogeneus`(vExpedition INT) RETURNS tinyint(1) -BEGIN - DECLARE vScanId INT; - DECLARE vDistinctRoutesInThePallet INT; - - SELECT scan_id INTO vScanId - FROM vn2008.scan_line - WHERE code = vExpedition - LIMIT 1; - - SELECT COUNT(*) INTO vDistinctRoutesInThePallet - FROM ( - SELECT DISTINCT t.Id_Ruta - FROM vn2008.scan_line sl - JOIN vn2008.expeditions e ON e.expeditions_id = sl.code - JOIN vn2008.Tickets t ON t.Id_Ticket = e.ticket_id - WHERE sl.scan_id = vScanId - AND t.Id_Ruta - ) t1; - - RETURN vDistinctRoutesInThePallet = 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 DROP FUNCTION IF EXISTS `isWorkerBoss` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `isWorkerBoss`(vUserId INT(11)) RETURNS tinyint(1) - DETERMINISTIC -BEGIN - - DECLARE subjectId INT(11) DEFAULT vUserId; - DECLARE tmpSubjectId INT(11); - DECLARE tmpBossId INT(11); - - LOOP - SELECT - bossWorker.user_id AS tmpBossId, - subjectWorker.user_id AS tmpSubjectId - INTO tmpBossId, tmpSubjectId - FROM - vn2008.Trabajadores AS subjectWorker - JOIN - vn2008.Trabajadores AS bossWorker ON bossWorker.Id_Trabajador = subjectWorker.boss - WHERE - subjectWorker.user_id = subjectId; - - IF tmpBossId = tmpSubjectId THEN - RETURN FALSE; - ELSEIF tmpBossId = account.userGetId() THEN - RETURN TRUE; - ELSE - SET subjectId = tmpBossId; - END IF; - END LOOP; - -RETURN FALSE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP FUNCTION IF EXISTS `messageSend` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `messageSend`(vRecipient VARCHAR(255), vMessage TEXT) RETURNS int(11) -BEGIN -/** - * Envia un mensaje a un usuario o a una lista de usuarios. - * - * @param vRecipient Nombre de usuario o de alias - * @param vMessage Texto del mensaje - * @return Número de destinatarios - **/ - DECLARE vCount INT; - DECLARE vUuid VARCHAR(255); - DECLARE vSendDate DATETIME DEFAULT NOW(); - DECLARE vUser VARCHAR(255) DEFAULT account.userGetName(); - - SET vRecipient = LOWER(vRecipient); - - DROP TEMPORARY TABLE IF EXISTS tRecipients; - CREATE TEMPORARY TABLE tRecipients - SELECT u.name finalRecipient - FROM account.mailAlias a - JOIN account.mailAliasAccount aa ON aa.mailAlias = a.id - JOIN account.user u ON u.id = aa.account - WHERE a.alias = vRecipient COLLATE utf8_unicode_ci - AND u.name != vUser - AND u.active - UNION - SELECT u.name FROM account.user u - WHERE u.name = vRecipient - AND u.active; - - SELECT COUNT(*) INTO vCount FROM tRecipients; - - IF vCount = 0 THEN - RETURN vCount; - END IF; - - SET vUuid = UUID(); - - INSERT INTO message - SET uuid = vUuid, - sender = vUser, - recipient = vRecipient, - message = vMessage, - sendDate = vSendDate; - - INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate) - SELECT vUuid, vUser, vRecipient, finalRecipient, vMessage, vSendDate - FROM tRecipients; - - DROP TEMPORARY TABLE tRecipients; - RETURN vCount; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP FUNCTION IF EXISTS `midnight` */; -ALTER DATABASE `vn` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `MIDNIGHT`(vDate DATE) RETURNS datetime - DETERMINISTIC -BEGIN - RETURN TIMESTAMP(vDate,'23:59:59'); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP FUNCTION IF EXISTS `phytoPassport` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `phytoPassport`(vRef VARCHAR(15)) RETURNS text CHARSET utf8 -BEGIN -DECLARE vPhyto TEXT CHARSET utf8 COLLATE utf8_unicode_ci; -SELECT - GROUP_CONCAT(i.id, - ':', - ppa.denomination, - ' ', - pp.number, - CHAR(13,10) - SEPARATOR '') fitosanitario - INTO vPhyto -FROM - sale s - JOIN - ticket t ON t.id = s.ticketFk - JOIN - item i ON i.id = s.itemFk - JOIN - plantpassport pp ON pp.producerFk = i.producerFk - JOIN - plantpassportAuthority ppa ON ppa.id = pp.plantpassportAuthorityFk - JOIN - itemBotanicalWithGenus ib ON ib.itemFk = i.id - JOIN - botanicExport be ON be.restriction = 'Se Requiere Certificado' - LEFT JOIN - ediGenus eg ON eg.id = be.ediGenusFk - LEFT JOIN - ediSpecie es ON es.id = be.ediSpecieFk -WHERE - t.refFk = vRef - AND ib.ediBotanic LIKE CONCAT(IFNULL(eg.latinGenusName, ''), - IF(latinSpeciesName > '', - CONCAT(' ', latinSpeciesName), - ''), - '%'); -RETURN vPhyto; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `ticketGetTotal` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `ticketGetTotal`(vTicketId INT) RETURNS decimal(10,2) - READS SQL DATA - DETERMINISTIC -BEGIN -/** - * Calcula el total con IVA de un ticket. - * - * @param vTicketId Identificador del ticket - * @return Total del ticket - */ - DECLARE vTotal DECIMAL(10,2); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - ENGINE = MEMORY - SELECT vTicketId ticketFk; - - CALL ticketGetTotal; - - SELECT total INTO vTotal FROM tmp.ticketTotal; - - DROP TEMPORARY TABLE - tmp.ticket, - tmp.ticketTotal; - - RETURN vTotal; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `ticketGetTotalkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `ticketGetTotalkk`(vTicketId INT) RETURNS decimal(10,2) - READS SQL DATA - DETERMINISTIC -BEGIN -/** - * Calcula el total con IVA de un ticket. - * - * @param vTicketId Identificador del ticket - * @return Total del ticket - */ - DECLARE vTotal DECIMAL(10,2); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - ENGINE = MEMORY - SELECT vTicketId ticketFk; - - CALL ticketGetTotal; - - SELECT total INTO vTotal FROM tmp.ticketTotal; - - DROP TEMPORARY TABLE - tmp.ticket, - tmp.ticketTotal; - - RETURN vTotal; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `ticketPositionInPath` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `ticketPositionInPath`(vTicketId INT) RETURNS varchar(10) CHARSET utf8 -BEGIN - - DECLARE vRestTicketsMaxOrder INT; - DECLARE vRestTicketsMinOrder INT; - DECLARE vRestTicketsPacking INT; - DECLARE vMyProductionOrder INT; - DECLARE vPosition VARCHAR(10) DEFAULT 'MID'; - DECLARE vMyPath INT; - DECLARE vMyWarehouse INT; - DECLARE PACKING_ORDER INT; - DECLARE vExpeditionsCount INT; - DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE; - -SELECT `order` - INTO PACKING_ORDER - FROM state - WHERE code = 'PACKING'; - -SELECT t.routeFk, t.warehouseFk, IFNULL(ts.productionOrder,0) - INTO vMyPath, vMyWarehouse, vMyProductionOrder - FROM ticket t - LEFT JOIN ticketState ts on ts.ticket = t.id - WHERE t.id = vTicketId; - -SELECT (ag.`name` = 'VN_VALENCIA') - INTO vIsValenciaPath - FROM vn2008.Rutas r - JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia - JOIN vn2008.agency ag on ag.agency_id = a.agency_id - WHERE r.Id_Ruta = vMyPath; - -IF vIsValenciaPath THEN -- Rutas Valencia - - SELECT COUNT(*) - INTO vExpeditionsCount - FROM expedition e - JOIN ticket t ON t.id = e.ticket - WHERE t.routeFk = vMyPath; - - SELECT MAX(ts.productionOrder), MIN(ts.productionOrder) - INTO vRestTicketsMaxOrder, vRestTicketsMinOrder - FROM ticket t - LEFT JOIN ticketState ts on t.id = ts.ticket - WHERE t.routeFk = vMyPath - AND t.warehouseFk = vMyWarehouse - AND t.id != vTicketid; - - SELECT COUNT(*) - INTO vRestTicketsPacking - FROM ticket t - LEFT JOIN ticketState ts on t.id = ts.ticket - WHERE ts.productionOrder = PACKING_ORDER - AND t.routeFk = vMyPath - AND t.warehouseFk = vMyWarehouse - AND t.id != vTicketid; - - IF vExpeditionsCount = 1 THEN - SET vPosition = 'FIRST'; - ELSEIF vRestTicketsMinOrder > PACKING_ORDER THEN - SET vPosition = 'LAST'; - ELSEIF vRestTicketsPacking THEN - SET vPosition = 'SHARED'; - ELSE - SET vPosition = 'MID'; - END IF; - -ELSE - SET vPosition = 'MID'; - -END IF; - -RETURN vPosition; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `ticketPositionInPathkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `ticketPositionInPathkk`(vTicketId INT) RETURNS varchar(10) CHARSET utf8 -BEGIN - - -DECLARE vRestTicketsMaxOrder INT; -DECLARE vRestTicketsMinOrder INT; -DECLARE vRestTicketsPacking INT; -DECLARE vMyProductionOrder INT; -DECLARE vPosition VARCHAR(10) DEFAULT 'MID'; -DECLARE vMyPath INT; -DECLARE vMyWarehouse INT; -DECLARE PACKING_ORDER INT; -DECLARE vExpeditionsCount INT; -DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE; - -SELECT `order` - INTO PACKING_ORDER - FROM state - WHERE code = 'PACKING'; - -SELECT path, warehouse, IFNULL(productionOrder,0) - INTO vMyPath, vMyWarehouse, vMyProductionOrder - FROM ticket t - LEFT JOIN ticketState ts on ts.ticket = t.id - WHERE id = vTicketId; - -SELECT (ag.`name` = 'VN_VALENCIA') - INTO vIsValenciaPath - FROM vn2008.Rutas r - JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia - JOIN vn2008.agency ag on ag.agency_id = a.agency_id - WHERE r.Id_Ruta = vMyPath; - - -IF vIsValenciaPath THEN -- Rutas Valencia - - SELECT COUNT(*) - INTO vExpeditionsCount - FROM expedition e - JOIN ticket t ON t.id = e.ticket - WHERE t.path = vMyPath; - - SELECT MAX(productionOrder), MIN(productionOrder) - INTO vRestTicketsMaxOrder, vRestTicketsMinOrder - FROM ticket t - LEFT JOIN ticketState ts on t.id = ts.ticket - WHERE t.path = vMyPath - AND t.warehouse = vMyWarehouse - AND t.id != vTicketid; - - SELECT COUNT(*) - INTO vRestTicketsPacking - FROM ticket t - LEFT JOIN ticketState ts on t.id = ts.ticket - WHERE productionOrder = PACKING_ORDER - AND t.path = vMyPath - AND t.warehouse = vMyWarehouse - AND t.id != vTicketid; - - - - IF vExpeditionsCount = 1 THEN - - SET vPosition = 'FIRST'; - - ELSEIF vRestTicketsMinOrder > PACKING_ORDER THEN - - SET vPosition = 'LAST'; - - ELSEIF vRestTicketsPacking THEN - - SET vPosition = 'SHARED'; - - ELSE - - SET vPosition = 'MID'; - - END IF; - -ELSE - - SET vPosition = 'MID'; - -END IF; - -RETURN vPosition; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `workerIsBoss` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `workerIsBoss`(vUserId INT) RETURNS int(11) -BEGIN -/** - * Comprueba por jerarquía si el trabajador actual es jefe - * de un trabajador en concreto. - * - * @param vUserId Id del trabajador que se desea comprobar. - * @return Revuelve verdadero si es jefe del empleado por escala jerárquica. - */ - DECLARE vWorkerId INT; - DECLARE vBossId INT; - - SELECT id INTO vWorkerId - FROM vn.worker - WHERE userFk = vUserId; - IF vWorkerId IS NULL THEN - CALL util.throw('USER_NOT_FOUND'); - END IF; - - DROP TEMPORARY TABLE IF EXISTS tCheckedWorker; - CREATE TEMPORARY TABLE tCheckedWorker - (PRIMARY KEY (workerFk)) - ENGINE = MEMORY - SELECT id workerFk FROM worker LIMIT 0; - LOOP - SELECT bossFk INTO vBossId - FROM vn.worker - WHERE id = vWorkerId; - IF (SELECT COUNT(*) FROM tCheckedWorker WHERE workerFk = vBossId) THEN - CALL util.throw('INFINITE_LOOP'); - END IF; - IF vBossId = vWorkerId THEN - RETURN FALSE; - ELSEIF vBossId = vn.getWorker() THEN - RETURN TRUE; - ELSE - INSERT INTO tCheckedWorker VALUES (vWorkerId); - SET vWorkerId = vBossId; - END IF; - END LOOP; - DROP TEMPORARY TABLE tCheckedWorker; - RETURN FALSE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `addressTaxArea` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `addressTaxArea`() - READS SQL DATA -BEGIN -/** - * Devuelve el taxArea para un conjunto de Consignatarios y empresas, - * - * @table tmp.addressCompany(addressFk, companyFk) valores a calcular - * @return tmp.addressTaxArea(addressFk,companyFk) - */ - - DECLARE vSpainCountryCode INT DEFAULT 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; - CREATE TEMPORARY TABLE tmp.addressTaxArea - (PRIMARY KEY (addressFk, companyFk)) - ENGINE = MEMORY - SELECT CASE - WHEN (NOT cClient.isUeeMember OR NOT cSupplier.isUeeMember) AND s.countryFk != c.countryFk THEN - 'WORLD' - WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN - 'CEE' - WHEN a.isEqualizated AND c.countryFk = vSpainCountryCode THEN - 'EQU' - ELSE - 'NATIONAL' - END AS areaFk, ac.addressFk, ac.companyFk - FROM tmp.addressCompany ac - JOIN address a ON a.id = ac.addressFk - JOIN `client` c ON c.id = a.clientFk - JOIN country cClient ON cClient.id = c.countryFk - JOIN supplier s ON s.id = ac.companyFk - JOIN country cSupplier ON cSupplier.id = s.countryFk; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `agencyListAvailable` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `agencyListAvailable`(vDate DATE, vAddress INT) -BEGIN -/** - * Devuelve la lista de almacenes disponibles y la fecha de - * envío desde cada uno. - * - * @param vDate Fecha de recepción de mercancía - * @param vAddress Id consignatario, %NULL para recogida - * @return travel_tree Lista de almacenes disponibles - */ - DECLARE vMaxDays INT DEFAULT DATEDIFF(vDate, CURDATE()); - DECLARE vWday TINYINT DEFAULT WEEKDAY(vDate); - DECLARE vHour TINYINT DEFAULT HOUR(NOW()); - DECLARE vProvince INT; - - SELECT provinceFk INTO vProvince - FROM address - WHERE id = vAddress; - - DROP TEMPORARY TABLE IF EXISTS tmp.agencyAvailable; - CREATE TEMPORARY TABLE tmp.agencyAvailable - (INDEX (agencyFk)) - ENGINE = MEMORY - SELECT agencyFk, warehouseFk - FROM agencyHour h - WHERE (provinceFk = vProvince - OR provinceFk IS NULL) - AND (weekDay = vWday - OR weekDay IS NULL) - AND (substractDay < vMaxDays - OR (substractDay = vMaxDays AND maxHour > vHour)); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clean` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN - - DECLARE vDateShort DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); - - DELETE FROM vn.dailyTaskLog WHERE created < vDateShort; - - INSERT INTO vn.dailyTaskLog(state) VALUES('clean START'); - - DELETE FROM vn.message WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - - INSERT INTO vn.dailyTaskLog(state) VALUES('clean END'); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clientCreate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clientCreate`( - vFirstname VARCHAR(50), - vSurnames VARCHAR(50), - vFi VARCHAR(9), - vAddress TEXT, - vPostcode CHAR(5), - vCity VARCHAR(25), - vProvinceFk SMALLINT(5), - vCompanyFk SMALLINT(5), - vPhone VARCHAR(11)) -BEGIN -/** - * Create new client - * - */ - DECLARE vClientFk INT; - DECLARE vPayMethodFk INT DEFAULT 4; - DECLARE vDueDay INT DEFAULT 5; - DECLARE vDefaultCredit DECIMAL(10, 2) DEFAULT 300.00; - DECLARE vIsTaxDataChecked TINYINT(1) DEFAULT 1; - DECLARE vHasCoreVnl BOOLEAN DEFAULT TRUE; - DECLARE vMandateTypeFk INT DEFAULT 2; - - SELECT id INTO vClientFk - FROM `client` - WHERE `fi` = vFi; - - IF ISNULL(vClientFk) THEN - - SELECT (MAX(id) + 1) INTO vClientFk - FROM `client` - WHERE id < 999999; - - INSERT INTO `client` ( - id, - name, - street, - fi, - phone, - provinceFk, - city, - postcode, - socialName, - payMethodFk, - dueDay, - credit, - isTaxDataChecked, - hasCoreVnl, - isEqualizated) - VALUES ( - vClientFk, - CONCAT('TR ', vFirstname, ' ', vSurnames), - vAddress, - vFi, - vPhone, - vProvinceFk, - vCity, - vPostcode, - CONCAT(vSurnames, ' ', vFirstname), - vPayMethodFk, - vDueDay, - vDefaultCredit, - vIsTaxDataChecked, - vHasCoreVnl, - FALSE - ); - - INSERT INTO mandate (clientFk, companyFk, mandateTypeFk) - VALUES (vClientFk, vCompanyFk, vMandateTypeFk); - END IF; - - SELECT vClientFk; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clientFreeze` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clientFreeze`() -BEGIN - - IF day(CURDATE()) IN (10,20,30) THEN - - UPDATE vn.client c - JOIN vn.clientType ct ON ct.id = c.id - JOIN bi.defaulters d ON d.client = c.id AND d.date = CURDATE() - JOIN vn.config ON TRUE - SET c.isFreezed = TRUE - WHERE d.amount > config.defaultersMaxAmount AND ct.code = 'normal'; - - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `copyComponentsFromSaleList` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `copyComponentsFromSaleList`(vTargetTicketFk INT) -BEGIN - -/* Copy sales and components to the target ticket -* -* ¡¡¡¡ Requires tmp.saleList(saleFk, itemFk, quantity, concept, price, discount, orden) !!!!! -* -* param VTargetTicketFk id del ticket a rellenar -*/ - - INSERT INTO vn.sale(ticketFk, itemFk, quantity,concept,price,discount) - SELECT vTargetTicketFk, itemFk, quantity,concept,price,discount - FROM tmp.saleList - ORDER BY orden; - - SET @order = 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.newSaleList; - - CREATE TEMPORARY TABLE tmp.newSaleList - SELECT id as saleFk, @order := @order + 1 as orden - FROM vn.sale - WHERE ticketFk = vTargetTicketFk - ORDER BY saleFk; - - INSERT INTO vn.saleComponent(saleFk,componentFk,value) - SELECT ns.saleFk, sc.componentFk, sc.value - FROM vn.saleComponent sc - JOIN tmp.saleList s ON s.saleFk = sc.saleFk - JOIN tmp.newSaleList ns ON ns.orden = s.orden; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `createExternalWorkerkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `createExternalWorkerkk`( - vFirstName VARCHAR(50), - vSurname1 VARCHAR(50), - vSurname2 VARCHAR(50), - vUser VARCHAR(20), - vPassword VARCHAR(50), - vWorkerCode VARCHAR(3) - ) -BEGIN - - DECLARE vUserId INT; - DECLARE vWorkerPako INT DEFAULT 2; - DECLARE vSurnames VARCHAR(100); - - INSERT INTO account.user(name,password,role) - SELECT vUser,MD5(vPassword),1; - - SET vUserId = LAST_INSERT_ID(); - /* - INSERT INTO vn.worker(firstName,name,bossFk,workerCode,user_id) - SELECT vFirstName,CONCAT(vSurname1,' ',vSurname2),2,vWorkerCode,vUser; - */ - - IF vSurname2 IS NULL THEN - SET vSurnames = vSurname1; - ELSE - SET vSurnames = CONCAT(vSurname1, ' ', vSurname2); - END IF; - - INSERT INTO vn2008.Trabajadores(Nombre, Apellidos, boss, CodigoTrabajador, user_id) - SELECT vFirstName, vSurnames, vWorkerPako, vWorkerCode, vUserId; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `entryConverter` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `entryConverter`(vEntry INT) -BEGIN - - DECLARE vWarehouseIn INT; - DECLARE vWarehouseOut INT; - DECLARE vTravel INT; - - DECLARE done BOOL DEFAULT FALSE; - - DECLARE vId_Entrada INT; - DECLARE vId_Article INT; - DECLARE vEtiquetas INT; - DECLARE vId_Cubo VARCHAR(10); - DECLARE vPacking INT; - DECLARE vGrouping INT; - DECLARE vCantidad INT; - DECLARE vCostefijo DECIMAL(10,3); - DECLARE vPortefijo DECIMAL(10,3); - DECLARE vEmbalajefijo DECIMAL(10); - DECLARE vComisionfija DECIMAL(10,3); - DECLARE vCaja INT; - DECLARE vNicho VARCHAR(5); - DECLARE vTarifa1 DECIMAL(10,2); - DECLARE vTarifa2 DECIMAL(10,2); - DECLARE vTarifa3 DECIMAL(10,2); - DECLARE vPVP DECIMAL(10,2); - DECLARE vCompra INT; - - DECLARE rs CURSOR FOR - SELECT - b.Id_Entrada, - b.Id_Article, - b.Etiquetas, - b.Id_Cubo, - b.Packing, - b.grouping, - b.Cantidad, - b.Costefijo, - b.Portefijo, - b.Embalajefijo, - b.Comisionfija, - b.caja, - b.Nicho, - b.Tarifa1, - b.Tarifa2, - b.Tarifa3, - b.PVP - FROM vn2008.Compres b - JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article - WHERE Id_Entrada = vEntry; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT warehouseInFk, warehouseOutFk, tr.id - INTO vWarehouseIn, vWarehouseOut, vTravel - FROM travel tr - JOIN entry e ON e.travelFk = tr.id - WHERE e.id = vEntry; - - UPDATE travel - SET warehouseInFk = vWarehouseOut, - warehouseOutFk = vWarehouseIn - WHERE id = vTravel; - - UPDATE vn2008.Compres c - LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article - SET Etiquetas = 0, Cantidad = 0 - WHERE c.Id_Entrada = vEntry - AND ic.espItemFk IS NULL; - - OPEN rs; - - DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - WHILE NOT done DO - - -- Primero la linea original con las cantidades invertidas - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - grouping, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - VALUES - ( - vId_Entrada, - vId_Article, - - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP); - - -- Ahora la linea nueva, con el item genérico - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - grouping, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - SELECT - vId_Entrada, - genItemFk as Id_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP - FROM itemConversor - WHERE espItemFk = vId_Article; - - SELECT LAST_INSERT_ID() - INTO vCompra; - - REPLACE vn2008.Compres_mark(Id_Compra,`comment`) - SELECT vCompra, vId_Article; - - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - END WHILE; - - - CLOSE rs; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `getDebt` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `getDebt`(vDate DATE) -BEGIN -/** - * Calcula el riesgo para los clientes activos de la tabla temporal tmp.client_list - * - * @table tmp.client_list - * @param vDate Fecha maxima de los registros - * @treturn tmp.risk - */ - DECLARE vDateIni DATETIME DEFAULT TIMESTAMPADD(DAY, - DAYOFMONTH(CURDATE()) - 5, CURDATE()); - DECLARE vDateEnd DATETIME; - DECLARE MAX_RISK_ALLOWED INT DEFAULT 200; - - SET vDateEnd = TIMESTAMP(IFNULL(vDate, CURDATE()), '23:59:59'); - - DROP TEMPORARY TABLE IF EXISTS tmp.clientList2; - CREATE TEMPORARY TABLE tmp.clientList2 - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT * - FROM tmp.client_list; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientList3; - CREATE TEMPORARY TABLE tmp.clientList3 - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT * - FROM tmp.client_list; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT id ticketFk, cl.Id_Cliente - FROM ticket t - JOIN tmp.clientList2 cl ON t.clientFk = cl.Id_Cliente - WHERE refFk IS NULL - AND shipped BETWEEN vDateIni AND vDateEnd; - - CALL vn.ticketGetTotal(); - - DROP TEMPORARY TABLE IF EXISTS tmp.risk; - CREATE TEMPORARY TABLE tmp.risk - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT Id_Cliente, SUM(amount) risk - FROM vn2008.Clientes c - JOIN ( - SELECT customer_id, SUM(amount) amount - FROM bi.customer_risk cr - JOIN tmp.client_list on tmp.client_list.Id_Cliente = cr.customer_id - GROUP BY customer_id - UNION ALL - SELECT Id_Cliente, SUM(Entregado) - FROM vn2008.Recibos - JOIN tmp.clientList2 using(Id_Cliente) - WHERE Fechacobro > vDateIni - GROUP BY Id_Cliente - UNION ALL - SELECT t.Id_Cliente, total - FROM tmp.ticketTotal tt - JOIN tmp.ticket t ON t.ticketFk = tt.ticketFk - UNION ALL - SELECT t.clientFk customer_id, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)) - FROM hedera.tpvTransaction t - JOIN tmp.clientList3 l ON l.Id_Cliente = t.clientFk - WHERE t.receiptFk IS NULL - AND t.status = 'ok' - GROUP BY t.clientFk - ) t ON c.Id_Cliente = t.customer_id - WHERE c.activo != FALSE - GROUP BY c.Id_Cliente; - - DROP TEMPORARY TABLE - tmp.ticket, - tmp.clientList2, - tmp.clientList3; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `getDebtKk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `getDebtKk`(vDate DATE) -BEGIN -/** - * Calcula el riesgo para los clientes activos de la tabla temporal tmp.client_list - * - * @deprecated usar vn.clientGetDebt - * @table tmp.client_list - * @param vDate Fecha maxima de los registros - * @treturn tmp.risk - */ - DECLARE vDateIni DATETIME DEFAULT TIMESTAMPADD(DAY, - DAYOFMONTH(CURDATE()) - 5, CURDATE()); - DECLARE vDateEnd DATETIME; - DECLARE MAX_RISK_ALLOWED INT DEFAULT 200; - - SET vDateEnd = TIMESTAMP(IFNULL(vDate, CURDATE()), '23:59:59'); - - DROP TEMPORARY TABLE IF EXISTS tmp.clientList2; - CREATE TEMPORARY TABLE tmp.clientList2 - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT * - FROM tmp.client_list; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientList3; - CREATE TEMPORARY TABLE tmp.clientList3 - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT * - FROM tmp.client_list; - - DROP TEMPORARY TABLE IF EXISTS vn2008.ticket_tmp; - CREATE TEMPORARY TABLE vn2008.ticket_tmp - (INDEX (ticket_id)) - ENGINE = MEMORY - SELECT id ticket_id, cl.Id_Cliente - FROM ticket t - JOIN tmp.clientList2 cl ON t.clientFk = cl.Id_Cliente - WHERE refFk IS NULL - AND shipped BETWEEN vDateIni AND vDateEnd; - - CALL vn2008.ticket_total; - - DROP TEMPORARY TABLE IF EXISTS tmp.risk; - CREATE TEMPORARY TABLE tmp.risk - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT Id_Cliente, SUM(amount) risk - FROM vn2008.Clientes c - JOIN ( - SELECT customer_id, SUM(amount) amount - FROM bi.customer_risk cr - JOIN tmp.client_list on tmp.client_list.Id_Cliente = cr.customer_id - GROUP BY customer_id - UNION ALL - SELECT Id_Cliente, SUM(Entregado) - FROM vn2008.Recibos - JOIN tmp.clientList2 using(Id_Cliente) - WHERE Fechacobro > vDateIni - GROUP BY Id_Cliente - UNION ALL - SELECT t.Id_Cliente, total - FROM vn2008.ticket_total tt - JOIN vn2008.ticket_tmp t ON tt.ticket_id = t.ticket_id - UNION ALL - SELECT t.clientFk customer_id, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)) - FROM hedera.tpvTransaction t - JOIN tmp.clientList3 l ON l.Id_Cliente = t.clientFk - WHERE t.receiptFk IS NULL - AND t.status = 'ok' - GROUP BY t.clientFk - ) t ON c.Id_Cliente = t.customer_id - WHERE c.activo != FALSE - GROUP BY c.Id_Cliente; - - DROP TEMPORARY TABLE - vn2008.ticket_tmp, - vn2008.ticket_total, - tmp.clientList2, - tmp.clientList3; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `getItemVisibleAvailable` */; -ALTER DATABASE `vn` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `getItemVisibleAvailable`(IN vItem INT,IN vDate DATE,IN vWarehouse TINYINT,IN isForcedToRecalculate BOOLEAN) -BEGIN - - DECLARE vCacheVisibleCalculated INTEGER; - DECLARE vCacheAvailableCalculated INTEGER; - - CALL cache.visible_refresh(vCacheVisibleCalculated, isForcedToRecalculate, vWarehouse); - CALL cache.available_refresh(vCacheAvailableCalculated, isForcedToRecalculate, vWarehouse, vDate); - - SELECT a.Id_Article, a.Article, a.Medida, a.Tallos, a.caja, O.Abreviatura as origen, a.Color, tipo_id, an.Nicho, - a.Categoria, p.`name` as producer, v.visible, av.available - FROM vn2008.Articles a - LEFT JOIN vn2008.Articles_nicho an ON a.Id_Article = an.Id_Article AND an.warehouse_id = vWarehouse - LEFT JOIN vn2008.Origen O ON O.id = a.id_origen - LEFT JOIN vn2008.producer p ON p.producer_id = a.producer_id - LEFT JOIN cache.visible v ON (vItem IS NULL OR v.item_id = vItem) AND v.calc_id = vCacheVisibleCalculated - LEFT JOIN cache.available av ON (vItem IS NULL OR av.item_id = vItem) AND av.calc_id = vCacheAvailableCalculated - WHERE (vItem IS NULL OR a.Id_Article = vItem); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `greugeSpray` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `greugeSpray`(IN vClientFk INT, IN onlyForHisOwner BOOL, IN vWorkerCode VARCHAR(3)) -BEGIN - - DECLARE vGreuge DECIMAL(10,2); - DECLARE vOwner INT; - DECLARE vTotalSale INT; - DECLARE vGreugeTypeFk INT DEFAULT 5; -- HERENCIA - - SELECT sum(amount) INTO vGreuge - FROM vn.greuge - WHERE clientFk = vClientFk; - - IF LENGTH(vWorkerCode) = 0 THEN - - SELECT salesPersonFk INTO vOwner - FROM vn.client - WHERE id = vClientFk; - - ELSE - - SELECT id INTO vOwner - FROM vn.worker - WHERE workerCode = vWorkerCode COLLATE utf8_general_ci; - - END IF; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientList; - CREATE TEMPORARY TABLE tmp.clientList - SELECT DISTINCT t.clientFk, floor(cr.yearSale / 12) AS monthSale - FROM vn.ticket t - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.manaSpellers ms ON ms.worker = c.salesPersonFk - JOIN vn.claimRatio cr ON cr.clientFk = c.id - WHERE ms.worker = IF(onlyForHisOwner, vOwner, ms.worker) - AND t.shipped >= TIMESTAMPADD(MONTH,-1,CURDATE()) - AND c.id != vClientFk - HAVING monthSale > 100; - - SELECT SUM(monthSale) INTO vTotalSale - FROM tmp.clientList; - - INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) - SELECT clientFk, CONCAT('Cliente: ',vClientFk), vGreuge * monthSale / vTotalSale, CURDATE(), vGreugeTypeFk - FROM tmp.clientList - UNION ALL - SELECT vClientFk, 'Reparto greuge', -vGreuge, CURDATE(), vGreugeTypeFk; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenceMake` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceExpenceMake`(IN vInvoice INT) -BEGIN -/* Inserta las partidas de gasto correspondientes a la factura - * REQUIERE tabla ticketToInvoice - * - * @param vInvoice Numero de factura - * - */ - DELETE FROM invoiceOutExpence - WHERE invoiceOutFk = vInvoice; - - INSERT INTO invoiceOutExpence( - invoiceOutFk, - expenceFk, - amount - ) - SELECT - vInvoice, - expenceFk, - SUM(ROUND(quantity * price * (100 - discount)/100,2)) amount - FROM ticketToInvoice t - JOIN sale s ON s.ticketFk = t.id - JOIN item i ON i.id = s.itemFk - GROUP BY i.expenceFk - HAVING amount != 0; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceFromAddress` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceFromAddress`(vMaxTicketDate DATETIME,vAddress INT,vCompany INT) -BEGIN - - DECLARE vMinDateTicket DATE DEFAULT TIMESTAMPADD(MONTH, -3, CURDATE()); - - SET vMaxTicketDate = vn2008.DAYEND(vMaxTicketDate); - - DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`; - - CREATE TEMPORARY TABLE `ticketToInvoice` - (PRIMARY KEY (`id`)) - ENGINE = MEMORY - SELECT Id_Ticket id FROM vn2008.Tickets WHERE (Fecha BETWEEN vMinDateTicket - AND vMaxTicketDate) AND Id_Consigna = vAddress - AND Factura IS NULL AND empresa_id = vCompany; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceFromClient` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceFromClient`(vMaxTicketDate DATETIME, vClient INT, vCompany INT) -BEGIN - - DECLARE vMinDateTicket DATE DEFAULT TIMESTAMPADD(YEAR, -3, CURDATE()); - - SET vMaxTicketDate = vn2008.DAYEND(vMaxTicketDate); - - DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`; - - CREATE TEMPORARY TABLE `ticketToInvoice` - (PRIMARY KEY (`id`)) - ENGINE = MEMORY - SELECT Id_Ticket id FROM vn2008.Tickets - WHERE Id_Cliente = vClient - AND Factura IS NULL - AND empresa_id = vCompany - AND (Fecha BETWEEN vMinDateTicket AND vMaxTicketDate) - ; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceFromTicket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceFromTicket`(IN vTicket INT) -BEGIN - - DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`; - - CREATE TEMPORARY TABLE `ticketToInvoice` - (PRIMARY KEY (`id`)) - ENGINE = MEMORY - SELECT id FROM vn.ticket - WHERE id = vTicket AND refFk IS NULL; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceInBookingCommon` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceInBookingCommon`(vInvoiceInId INT, OUT vSerialNumber INT) -BEGIN - - DROP TEMPORARY TABLE IF EXISTS newInvoiceIn; - - CREATE TEMPORARY TABLE newInvoiceIn - SELECT - i.*, - YEAR(i.booked) datedYear, - -- CONCAT('s/fra',RIGHT(i.supplierRef,8)) concept, - CONCAT('s/fra',RIGHT(i.supplierRef,8),':',LEFT(s.name, 10)) conceptWithSupplier, - (cc.id = c.id) isSameCountry, - cit.id invoicesCount - FROM invoiceIn i - JOIN cplusInvoiceType472 cit ON cit.id = i.cplusInvoiceType472Fk - JOIN supplier s ON s.id = i.supplierFk - JOIN country c ON c.id = s.countryFk - JOIN supplier sc ON sc.id = i.companyFk - JOIN country cc ON cc.id = sc.countryFk - WHERE i.id = vInvoiceInId; - - DROP TEMPORARY TABLE IF EXISTS newSupplier; - CREATE TEMPORARY TABLE newSupplier - SELECT - s.*, - REPLACE(s.account,' ','') supplierAccount, - IF(c.CEE < 2, TRUE, FALSE) isUeeMember - FROM supplier s - JOIN newInvoiceIn n - JOIN country c ON c.id = s.countryFk - WHERE s.id = n.supplierFk; - - IF (SELECT isActive FROM newSupplier) = 0 THEN - CALL util.throw('INACTIVE_PROVIDER'); - END IF; - - SELECT IFNULL(MAX(i.serialNumber) + 1,1) - INTO vSerialNumber - FROM invoiceIn i - JOIN newInvoiceIn n - WHERE i.serial LIKE n.serial - AND YEAR(i.booked) = n.datedYear - AND i.companyFk = n.companyFk - GROUP BY i.companyFk; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceInBookingExtra` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceInBookingExtra`(vInvoiceInId INT) -BEGIN - DECLARE vBookNumber,vSerialNumber INT; - - CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber); - - SELECT MAX(ASIEN) + 1 - INTO vBookNumber - FROM vn2008.XDiario; - - -- Actualizacion de la fecha de contabilizado y de operacion de las importaciones - UPDATE invoiceInEntry iie - JOIN invoiceIn ii ON ii.id = iie.invoiceInFk - JOIN invoiceInAwb iia ON iia.invoiceInFk = iie.invoiceInAwbFk - JOIN awb a ON a.id = iia.awbFk - SET ii.isBooked = TRUE, - ii.booked = IFNULL(ii.booked,a.booked), - ii.operated = IFNULL(ii.operated,a.operated), - ii.issued = IFNULL(ii.issued,a.issued), - ii.bookEntried = IFNULL(ii.bookEntried,a.bookEntried) - WHERE iie.invoiceInAwbFk = vInvoiceInId; - - -- Extracomunitarias gasto contra proveedor/acreedor - INSERT INTO vn2008.XDiario ( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EURODEBE, - CONCEPTO, - CAMBIO, - DEBEME, - NFACTICK, - empresa_id - ) - SELECT - vBookNumber ASIEN, - IFNULL(a.bookEntried, n.bookEntried) FECHA, - iit.expenceFk SUBCTA, - s.account CONTRA, - ROUND(SUM(iit.taxableBase) * (iie.percentage / 100),2) EURODEBE, - CONCAT('COMPRA s/fra ',i.supplierRef,':',LEFT(s.name, 10)) CONCEPTO, - SUM(iit.taxableBase) / SUM(iit.foreignValue) CAMBIO, - ROUND(SUM(iit.foreignValue) * (iie.percentage / 100),2) DEBEME, - n.invoicesCount NFACTICK, - n.companyFk empresa_id - FROM newInvoiceIn n - JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = n.id - JOIN invoiceInTax iit ON iit.invoiceInFk = iie.invoiceInFk - JOIN invoiceIn i ON i.id = iit.invoiceInFk - JOIN supplier s ON s.id = i.supplierFk - LEFT JOIN invoiceInAwb iia ON iia.invoiceInFk = n.id - LEFT JOIN awb a ON a.id = iia.awbFk - WHERE iie.percentage - GROUP BY i.id; - - -- Extracomunitarias proveedor contra gasto - INSERT INTO vn2008.XDiario ( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EUROHABER, - CONCEPTO, - CAMBIO, - HABERME, - NFACTICK, - empresa_id - ) - SELECT - vBookNumber ASIEN, - IFNULL(a.bookEntried, n.bookEntried) FECHA, - s.account SUBCTA, - iit.expenceFk CONTRA, - ROUND(SUM(iit.taxableBase) * (iie.percentage / 100),2) EUROHABER, - CONCAT('COMPRA s/fra ',i.supplierRef,':',LEFT(s.name, 10)) CONCEPTO, - SUM(iit.taxableBase) / SUM(iit.foreignValue) CAMBIO, - SUM(iit.foreignValue) HABERME, - n.invoicesCount NFACTICK, - n.companyFk empresa_id - FROM newInvoiceIn n - JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = n.id - JOIN invoiceInTax iit ON iit.invoiceInFk = iie.invoiceInFk - JOIN invoiceIn i ON i.id = iit.invoiceInFk - JOIN supplier s ON s.id = i.supplierFk - LEFT JOIN invoiceInAwb iia ON iia.invoiceInFk = n.id - LEFT JOIN awb a ON a.id = iia.awbFk - WHERE iie.percentage - GROUP BY i.id; - - -- Iva Importacion pendiente - - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - CONCEPTO, - EUROHABER,-- EURODEBE - SERIE, - empresa_id) - - SELECT - vBookNumber, - a.bookEntried, - '4700000999', - n.conceptWithSupplier, - ROUND(SUM(iii.amount * (tc.rate/100)),2) eurohaber, - n.serial, - n.companyFk - FROM newInvoiceIn n - JOIN invoiceInIntrastat iii ON n.id = iii.invoiceInFk - JOIN intrastat ii ON ii.id = iii.intrastatFk - JOIN taxCode tc ON tc.id = ii.taxCodeFk - JOIN invoiceInAwb iia ON iia.invoiceInFk = iii.invoiceInFk - JOIN awb a ON a.id = iia.awbFk - HAVING eurohaber IS NOT NULL; - - -- Linea iva importacion extracomunitaria - - SET @cont:=1; - SET @total:=0; - - INSERT INTO vn2008.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, - x.FECHA, - x.SUBCTA, - x.CONTRA, - IF (n.isSameCountry OR NOT s.isUeeMember, - x.EURODEBE, - NULL - ) EURODEBE, - x.BASEEURO, - x.CONCEPTO, - vSerialNumber FACTURA, - x.IVA, - '*' AUXILIAR, - x.SERIE, - x.FECHA_EX, - x.FECHA_OP, - x.dua FACTURAEX, - n.invoicesCount NFACTICK, - IF(@total:=@total + x.EURODEBE AND @cont:=@cont + 1 ,1,1) L340, - TRUE LDIFADUAN, - x.TIPOCLAVE, - n.cplusTaxBreakFk TIPOEXENCI, - n.cplusSubjectOpFk TIPONOSUJE, - 5 TIPOFACT, - n.cplusRectificationTypeFk TIPORECTIF, - x.TERIDNIF, - x.TERNIF, - x.TERNOM, - n.companyFk, - IFNULL(x.FECREGCON,n.booked) FECREGCON - - FROM newInvoiceIn n - JOIN newSupplier s - JOIN ( - SELECT - -- CONCAT('COMPRA s/fra ',sref,':',LEFT(p.Proveedor, 10)) - CONCAT('COMPRA s/fra ',ii.supplierRef,':',LEFT(s.name, 10)) CONCEPTO, - tc.code SUBCTA, - s.account CONTRA, - tc.rate IVA, - ROUND(sum(b.buyingValue * b.quantity / intraSub.intrastatSum * taxSub.amount)*(tc.rate/100),2) EURODEBE, - ROUND(sum(b.buyingValue * b.quantity / intraSub.intrastatSum * taxSub.amount),2) BASEEURO, - ii.serial SERIE, - e.supplierFk, - iia.dua, - iis.cplusTerIdNifFk TERIDNIF, - s.nif AS TERNIF, - s.name AS TERNOM, - ii.booked FECREGCON, - ii.cplusTrascendency472Fk TIPOCLAVE, - a.issued FECHA_EX, - a.operated FECHA_OP, - a.bookEntried FECHA - FROM invoiceInAwb iia - JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = iia.invoiceInFk - JOIN awb a ON a.id = iia.awbFk - JOIN invoiceIn ii ON ii.id = iie.invoiceInFk - JOIN invoiceInSerial iis ON iis.code = ii.serial - JOIN buy b ON b.entryFk = iie.entryFk - JOIN item i ON i.id = b.itemFk - JOIN ( - SELECT - i.intrastatFk, - sum(b.buyingValue * b.quantity) as intrastatSum - FROM buy b - JOIN item i ON i.id = b.itemFk - JOIN invoiceInEntry iie ON iie.entryFk = b.entryFk - JOIN invoiceInAwb iia ON iia.invoiceInFk = iie.invoiceInAwbFk - JOIN awb aw ON aw.id =iia.awbFk - WHERE iie.percentage AND iia.invoiceInFk = vInvoiceInId - GROUP BY i.intrastatFk - ) intraSub ON intraSub.intrastatFk = i.intrastatFk - JOIN ( - SELECT - iii.intrastatFk, - iii.amount, - intr.taxCodeFk - FROM invoiceInIntrastat iii - JOIN intrastat intr ON intr.id = iii.intrastatFk - WHERE iii.invoiceInFk = vInvoiceInId - ) taxSub ON taxSub.intrastatFk = i.intrastatFk - JOIN taxCode tc ON tc.id = taxSub.taxCodeFk - JOIN entry e ON e.id = iie.entryFk - JOIN supplier s ON s.id = e.supplierFk - WHERE iie.invoiceInAwbFk = vInvoiceInId AND iie.percentage - GROUP BY e.supplierFk, taxSub.taxCodeFk - ) x - GROUP BY x.supplierFk, x.IVA; - - /*UPDATE newInvoiceIn n - JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = vInvoiceInId - JOIN invoiceIn ii ON ii.id = iie.invoiceInFk - SET ii.isBooked = TRUE, - ii.booked = IFNULL(ii.booked,n.booked), - ii.operated = IFNULL(ii.operated,n.operated), - ii.issued = IFNULL(ii.issued,n.issued);*/ - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceInBookingkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceInBookingkk`(vInvoiceInId INT) -BEGIN - /* OBSOLETO usar invoiceInBookingMain o invoiceInBookingExtra */ - DECLARE vSerialNumber, vBookNumber, vBookNumberPlus1 INT; - DECLARE vTotalAmount DECIMAL(10,2); - - DROP TEMPORARY TABLE IF EXISTS newInvoiceIn; - - CREATE TEMPORARY TABLE newInvoiceIn - SELECT - i.*, - YEAR(i.booked) datedYear, - -- CONCAT('s/fra',RIGHT(i.supplierRef,8)) concept, - CONCAT('s/fra',RIGHT(i.supplierRef,8),':',LEFT(s.name, 10)) conceptWithSupplier, - (cc.id = c.id) isSameCountry, - cit.id invoicesCount - FROM invoiceIn i - JOIN cplusInvoiceType472 cit ON cit.id = i.cplusInvoiceType472Fk - JOIN supplier s ON s.id = i.supplierFk - JOIN country c ON c.id = s.countryFk - JOIN supplier sc ON sc.id = i.companyFk - JOIN country cc ON cc.id = sc.countryFk - WHERE i.id = vInvoiceInId; - - DROP TEMPORARY TABLE IF EXISTS newSupplier; - CREATE TEMPORARY TABLE newSupplier - SELECT - s.*, - REPLACE(s.account,' ','') supplierAccount, - IF(c.CEE < 2, TRUE, FALSE) isUeeMember - FROM supplier s - JOIN newInvoiceIn n - JOIN country c ON c.id = s.countryFk - WHERE s.id = n.supplierFk; - - IF (SELECT isActive FROM newSupplier) = 0 THEN - CALL util.throw('INACTIVE_PROVIDER'); - END IF; - - SELECT IFNULL(MAX(i.serialNumber) + 1,1) - INTO vSerialNumber - FROM invoiceIn i - JOIN newInvoiceIn n - WHERE i.serial LIKE n.serial - AND YEAR(i.booked) = n.datedYear - AND i.companyFk = n.companyFk - GROUP BY i.companyFk; - - SELECT MAX(ASIEN) + 1 - INTO vBookNumber - FROM vn2008.XDiario; - - SET vBookNumberPlus1 = vBookNumber + 1; - - SELECT SUM(iit.taxableBase * IF(i.serial = 'R', 1 +(tc.rate/100),1)) - INTO vTotalAmount - FROM invoiceIn i - JOIN invoiceInTax iit ON iit.invoiceInFk = i.id - JOIN taxCode tc ON iit.taxCodeFk = tc.id - WHERE i.id = vInvoiceInId; - - -- Apunte del proveedor - - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - EUROHABER, - CONCEPTO, - NFACTICK, - empresa_id) - SELECT - vBookNumber, - n.booked, - s.supplierAccount, - vTotalAmount, - n.conceptWithSupplier, - n.invoicesCount, - n.companyFk - FROM newInvoiceIn n - JOIN newSupplier s; - - -- ----------------------------------------------------------- Linea de Gastos - INSERT INTO vn2008.XDiario ( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EURODEBE, - EUROHABER, - CONCEPTO, - NFACTICK, - empresa_id - ) - SELECT - vBookNumber ASIEN, - n.booked FECHA, - if( - e.isWithheld, - LPAD(RIGHT(s.supplierAccount ,5),10,iit.expenceFk), - iit.expenceFk - ) SUBCTA, - s.supplierAccount CONTRA, - if( - e.isWithheld, - NULL, - ABS(ROUND(SUM(iit.taxableBase),2)) - ) EURODEBE, - if( - e.isWithheld, - ABS(ROUND(SUM(iit.taxableBase),2)), - NULL - ) EUROHABER, - n.conceptWithSupplier CONCEPTO, - n.invoicesCount NFACTICK, - n.companyFk empresa_id - FROM newInvoiceIn n - JOIN newSupplier s - JOIN invoiceInTax iit ON iit.invoiceInFk = n.id - JOIN taxCode tc ON tc.id = iit.taxCodeFk - JOIN expence e ON e.id = iit.expenceFk AND e.taxTypeFk = tc.taxTypeFk - WHERE iit.expenceFk != 5660000002 - GROUP BY iit.expenceFk; - - -- Extracomunitarias gasto contra proveedor/acreedor - INSERT INTO vn2008.XDiario ( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EURODEBE, - CONCEPTO, - NFACTICK, - empresa_id - ) - SELECT - vBookNumberPlus1 ASIEN, - IFNULL(a.booked, n.booked) FECHA, - iit.expenceFk SUBCTA, - s.account CONTRA, - ROUND(SUM(iit.taxableBase) * (iie.percentage / 100),2) EURODEBE, - CONCAT('COMPRA s/fra ',i.supplierRef,':',LEFT(s.name, 10)) CONCEPTO, - n.invoicesCount NFACTICK, - n.companyFk empresa_id - FROM newInvoiceIn n - JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = n.id - JOIN invoiceInTax iit ON iit.invoiceInFk = iie.invoiceInFk - JOIN invoiceIn i ON i.id = iit.invoiceInFk - JOIN supplier s ON s.id = i.supplierFk - LEFT JOIN invoiceInAwb iia ON iia.invoiceInFk = n.id - LEFT JOIN awb a ON a.id = iia.awbFk - WHERE iie.percentage - GROUP BY i.id; - - -- Extracomunitarias proveedor contra gasto - INSERT INTO vn2008.XDiario ( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EUROHABER, - CONCEPTO, - NFACTICK, - empresa_id - ) - SELECT - vBookNumberPlus1 ASIEN, - IFNULL(a.booked, n.booked) FECHA, - s.account SUBCTA, - iit.expenceFk CONTRA, - ROUND(SUM(iit.taxableBase) * (iie.percentage / 100),2) EUROHABER, - CONCAT('COMPRA s/fra ',i.supplierRef,':',LEFT(s.name, 10)) CONCEPTO, - n.invoicesCount NFACTICK, - n.companyFk empresa_id - FROM newInvoiceIn n - JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = n.id - JOIN invoiceInTax iit ON iit.invoiceInFk = iie.invoiceInFk - JOIN invoiceIn i ON i.id = iit.invoiceInFk - JOIN supplier s ON s.id = i.supplierFk - LEFT JOIN invoiceInAwb iia ON iia.invoiceInFk = n.id - LEFT JOIN awb a ON a.id = iia.awbFk - WHERE iie.percentage - GROUP BY i.id; - - -- -------------------------------------------------------------------- - -- ------- Lineas de IVA --------------- - -- -------------------------------------------------------------------- - - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EURODEBE, - BASEEURO, - CONCEPTO, - FACTURA, - IVA, - AUXILIAR, - SERIE, - TIPOOPE, - FECHA_EX, - FECHA_OP, - NFACTICK, - FACTURAEX, - L340, - LRECT349, - TIPOCLAVE, - TIPOEXENCI, - TIPONOSUJE, - TIPOFACT, - TIPORECTIF, - TERIDNIF, - TERNIF, - TERNOM, - FECREGCON, - empresa_id - ) - SELECT vBookNumber ASIEN, - n.booked FECHA, - tc.code SUBCTA, - s.supplierAccount CONTRA, - SUM(ROUND(tc.rate/100*it.taxableBase + 0.0001,2)) EURODEBE, - SUM(it.taxableBase) BASEEURO, - GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, - vSerialNumber FACTURA, - tc.rate IVA, - IF(isUeeMember AND eWithheld.id IS NULL,'','*') AUXILIAR, - n.serial SERIE, - tt.TIPOOPE, - n.issued FECHA_EX, - n.operated FECHA_OP, - n.invoicesCount NFACTICK, - n.supplierRef FACTURAEX, - TRUE L340, - (isSameCountry OR NOT isUeeMember) LRECT349, - n.cplusTrascendency472Fk TIPOCLAVE, - n.cplusTaxBreakFk TIPOEXENCI, - n.cplusSubjectOpFk TIPONOSUJE, - n.cplusInvoiceType472Fk TIPOFACT, - n.cplusRectificationTypeFk TIPORECTIF, - iis.cplusTerIdNifFk TERIDNIF, - s.nif AS TERNIF, - s.name AS TERNOM, - n.booked FECREGCON, - n.companyFk - - FROM newInvoiceIn n - JOIN newSupplier s - JOIN invoiceInTax it ON n.id = it.invoiceInFk - JOIN taxCode tc ON tc.id = it.taxCodeFk - JOIN taxType tt ON tt.id = tc.taxTypeFk - JOIN invoiceInSerial iis ON iis.code = tt.serial - JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk - LEFT JOIN - (SELECT eWithheld.id - FROM invoiceInTax hold - JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld - WHERE hold.invoiceInFk = 58262 LIMIT 1 - ) eWithheld ON TRUE - WHERE tc.type != '-' - AND tc.isActive - GROUP BY tc.rate; - - -- Linea iva inversor sujeto pasivo - - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EUROHABER, - BASEEURO, - CONCEPTO, - FACTURA, - IVA, - AUXILIAR, - SERIE, - TIPOOPE, - FECHA_EX, - FECHA_OP, - NFACTICK, - FACTURAEX, - L340, - LRECT349, - TIPOCLAVE, - TIPOEXENCI, - TIPONOSUJE, - TIPOFACT, - TIPORECTIF, - TERIDNIF, - TERNIF, - TERNOM, - empresa_id - ) - - SELECT - vBookNumber ASIEN, - n.booked FECHA, - tcLink.code SUBCTA, - s.supplierAccount CONTRA, - ROUND(tcLink.rate/100*SUM(it.taxableBase) + 0.0001,2) EUROHABER, - ROUND(SUM(it.taxableBase),2) BASEEURO, - GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, - vSerialNumber FACTURA, - tcLink.rate IVA, - '*' AUXILIAR, - n.serial SERIE, - tt.TIPOOPE, - n.issued FECHA_EX, - n.operated FECHA_OP, - n.invoicesCount NFACTICK, - n.supplierRef FACTURAEX, - FALSE L340, - (isSameCountry OR NOT isUeeMember) LRECT349, - 1 TIPOCLAVE, - n.cplusTaxBreakFk TIPOEXENCI, - n.cplusSubjectOpFk TIPONOSUJE, - n.cplusInvoiceType472Fk TIPOFACT, - n.cplusRectificationTypeFk TIPORECTIF, - iis.cplusTerIdNifFk TERIDNIF, - s.nif AS TERNIF, - s.name AS TERNOM, - n.companyFk - - FROM newInvoiceIn n - JOIN newSupplier s - JOIN invoiceInTax it ON n.id = it.invoiceInFk - JOIN taxCode tc ON tc.id = it.taxCodeFk - JOIN taxType tt ON tt.id = tc.taxTypeFk - JOIN invoiceInSerial iis ON iis.code = tt.serial - JOIN taxCode tcLink ON tcLink.linkFk = tc.linkFk AND tc.id != tcLink.id - JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk - WHERE tc.isActive - GROUP BY tcLink.rate, e.id; - - -- Iva Importacion pendiente - - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - CONCEPTO, - EUROHABER,-- EURODEBE - SERIE, - empresa_id) - - SELECT - vBookNumberPlus1, - a.booked, - '4700000999', - n.conceptWithSupplier, - ROUND(SUM(iii.amount * (tc.rate/100)),2) eurohaber, - n.serial, - n.companyFk - FROM newInvoiceIn n - JOIN invoiceInIntrastat iii ON n.id = iii.invoiceInFk - JOIN intrastat ii ON ii.id = iii.intrastatFk - JOIN taxCode tc ON tc.id = ii.taxCodeFk - JOIN invoiceInAwb iia ON iia.invoiceInFk = iii.invoiceInFk - JOIN awb a ON a.id = iia.awbFk - HAVING eurohaber IS NOT NULL; - - - -- Linea iva importacion extracomunitaria - - SET @cont:=1; - SET @total:=0; - SET @base:=2; - - INSERT INTO vn2008.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 - vBookNumberPlus1 ASIEN, - x.FECHA, - x.SUBCTA, - x.CONTRA, - IF (n.isSameCountry OR NOT s.isUeeMember, - x.EURODEBE, - NULL - ) EURODEBE, - x.BASEEURO, - x.CONCEPTO, - vSerialNumber FACTURA, - x.IVA, - '*' AUXILIAR, - x.SERIE, - x.FECHA_EX, - x.FECHA_OP, - x.dua FACTURAEX, - n.invoicesCount NFACTICK, - IF(@total:=@total + x.EURODEBE AND @cont:=@cont + 1 ,1,1) L340, - TRUE LDIFADUAN, - x.TIPOCLAVE, - n.cplusTaxBreakFk TIPOEXENCI, - n.cplusSubjectOpFk TIPONOSUJE, - 5 TIPOFACT, - n.cplusRectificationTypeFk TIPORECTIF, - x.TERIDNIF, - x.TERNIF, - x.TERNOM, - n.companyFk, - IFNULL(x.FECREGCON,n.booked) FECREGCON - - FROM newInvoiceIn n - JOIN newSupplier s - JOIN ( - SELECT - -- CONCAT('COMPRA s/fra ',sref,':',LEFT(p.Proveedor, 10)) - CONCAT('COMPRA s/fra ',ii.supplierRef,':',LEFT(s.name, 10)) CONCEPTO, - tc.code SUBCTA, - s.account CONTRA, - tc.rate IVA, - ROUND(sum(b.buyingValue * b.quantity / intraSub.intrastatSum * taxSub.amount)*(tc.rate/100),2) EURODEBE, - ROUND(sum(b.buyingValue * b.quantity / intraSub.intrastatSum * taxSub.amount),2) BASEEURO, - ii.serial SERIE, - e.supplierFk, - iia.dua, - iis.cplusTerIdNifFk TERIDNIF, - s.nif AS TERNIF, - s.name AS TERNOM, - ii.booked FECREGCON, - ii.cplusTrascendency472Fk TIPOCLAVE, - a.issued FECHA_EX, - a.operated FECHA_OP, - a.booked FECHA - FROM invoiceInAwb iia - JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = iia.invoiceInFk - JOIN awb a ON a.id = iia.awbFk - JOIN invoiceIn ii ON ii.id = iie.invoiceInFk - JOIN invoiceInSerial iis ON iis.code = ii.serial - JOIN buy b ON b.entryFk = iie.entryFk - JOIN item i ON i.id = b.itemFk - JOIN ( - SELECT - i.intrastatFk, - sum(b.buyingValue * b.quantity) as intrastatSum - FROM buy b - JOIN item i ON i.id = b.itemFk - JOIN invoiceInEntry iie - ON iie.entryFk = b.entryFk - JOIN invoiceInAwb iia - ON iia.invoiceInFk = iie.invoiceInAwbFk - JOIN awb aw ON aw.id =iia.awbFk - WHERE iie.percentage AND iia.invoiceInFk = vInvoiceInId - GROUP BY i.intrastatFk - ) intraSub ON intraSub.intrastatFk = i.intrastatFk - JOIN ( - SELECT - iii.intrastatFk, - iii.amount, - intr.taxCodeFk - FROM invoiceInIntrastat iii - JOIN intrastat intr - ON intr.id = iii.intrastatFk - WHERE iii.invoiceInFk = vInvoiceInId - ) taxSub ON taxSub.intrastatFk = i.intrastatFk - JOIN taxCode tc ON tc.id = taxSub.taxCodeFk - JOIN entry e ON e.id = iie.entryFk - JOIN supplier s ON s.id = e.supplierFk - WHERE iie.invoiceInAwbFk = vInvoiceInId AND iie.percentage - GROUP BY e.supplierFk, taxSub.taxCodeFk - ) x - GROUP BY x.supplierFk, x.IVA; - - -- Actualizacion de la fecha de contabilizado y de operacion de las importaciones - UPDATE newInvoiceIn n - JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = vInvoiceInId - JOIN invoiceIn ii ON ii.id = iie.invoiceInFk - SET ii.booked = IFNULL(ii.booked,n.booked), - ii.operated = IFNULL(ii.operated,n.issued); - - -- Actualización del registro original - UPDATE invoiceIn - SET - serialNumber = vSerialNumber, - isBooked = TRUE - WHERE - id = vInvoiceInId; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceInBookingMain` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceInBookingMain`(vInvoiceInId INT) -BEGIN - DECLARE vTotalAmount,vTotalAmountDivisa DECIMAL(10,2); - DECLARE vBookNumber,vSerialNumber INT; - DECLARE vRate DECIMAL(10,4); - - CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber); - - SELECT SUM(iit.taxableBase * IF(i.serial = 'R', 1 +(tc.rate/100),1)), - SUM(iit.foreignValue * IF(i.serial = 'R', 1 +(tc.rate/100),1)), - iit.taxableBase/iit.foreignValue - INTO vTotalAmount, vTotalAmountDivisa, vRate - FROM newInvoiceIn i - JOIN invoiceInTax iit ON iit.invoiceInFk = i.id - JOIN taxCode tc ON iit.taxCodeFk = tc.id; - - SELECT MAX(ASIEN) + 1 - INTO vBookNumber - FROM vn2008.XDiario; - - -- Apunte del proveedor - - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - EUROHABER, - CONCEPTO, - CAMBIO, - HABERME, - NFACTICK, - CLAVE, - empresa_id) - SELECT - vBookNumber, - n.bookEntried, - s.supplierAccount, - vTotalAmount, - n.conceptWithSupplier, - vRate, - vTotalAmountDivisa, - n.invoicesCount, - vInvoiceInId, - n.companyFk - FROM newInvoiceIn n - JOIN newSupplier s; - - -- ----------------------------------------------------------- Linea de Gastos - INSERT INTO vn2008.XDiario ( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EURODEBE, - EUROHABER, - CONCEPTO, - CAMBIO, - DEBEME, - HABERME, - NFACTICK, - empresa_id - ) - SELECT - vBookNumber ASIEN, - n.bookEntried FECHA, - if( - e.isWithheld, - LPAD(RIGHT(s.supplierAccount,5),10,iit.expenceFk), - iit.expenceFk - ) SUBCTA, - s.supplierAccount CONTRA, - if( - e.isWithheld, - NULL, - ABS(ROUND(SUM(iit.taxableBase),2)) - ) EURODEBE, - if( - e.isWithheld, - ABS(ROUND(SUM(iit.taxableBase),2)), - NULL - ) EUROHABER, - n.conceptWithSupplier CONCEPTO, - vRate, - if( - e.isWithheld, - NULL, - ABS(ROUND(SUM(iit.foreignValue),2)) - ) DEBEME, - if( - e.isWithheld, - ABS(ROUND(SUM(iit.foreignValue),2)), - NULL - ) HABERME, - n.invoicesCount NFACTICK, - n.companyFk empresa_id - FROM newInvoiceIn n - JOIN newSupplier s - JOIN invoiceInTax iit ON iit.invoiceInFk = n.id - JOIN taxCode tc ON tc.id = iit.taxCodeFk - JOIN expence e ON e.id = iit.expenceFk AND e.taxTypeFk = tc.taxTypeFk - WHERE iit.expenceFk != 5660000002 - GROUP BY iit.expenceFk; - - - -- -------------------------------------------------------------------- - -- ------- Lineas de IVA --------------- - -- -------------------------------------------------------------------- - - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EURODEBE, - BASEEURO, - CONCEPTO, - FACTURA, - IVA, - AUXILIAR, - SERIE, - TIPOOPE, - FECHA_EX, - FECHA_OP, - NFACTICK, - FACTURAEX, - L340, - LRECT349, - TIPOCLAVE, - TIPOEXENCI, - TIPONOSUJE, - TIPOFACT, - TIPORECTIF, - TERIDNIF, - TERNIF, - TERNOM, - FECREGCON, - empresa_id - ) - SELECT vBookNumber ASIEN, - n.bookEntried FECHA, - tc.code SUBCTA, - s.supplierAccount CONTRA, - SUM(ROUND(tc.rate/100*it.taxableBase + 0.0001,2)) EURODEBE, - SUM(it.taxableBase) BASEEURO, - GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, - vSerialNumber FACTURA, - tc.rate IVA, - IF(isUeeMember AND eWithheld.id IS NULL,'','*') AUXILIAR, - n.serial SERIE, - tt.TIPOOPE, - n.issued FECHA_EX, - n.operated FECHA_OP, - n.invoicesCount NFACTICK, - n.supplierRef FACTURAEX, - TRUE L340, - (isSameCountry OR NOT isUeeMember) LRECT349, - n.cplusTrascendency472Fk TIPOCLAVE, - n.cplusTaxBreakFk TIPOEXENCI, - n.cplusSubjectOpFk TIPONOSUJE, - n.cplusInvoiceType472Fk TIPOFACT, - n.cplusRectificationTypeFk TIPORECTIF, - iis.cplusTerIdNifFk TERIDNIF, - s.nif AS TERNIF, - s.name AS TERNOM, - n.booked FECREGCON, - n.companyFk - - FROM newInvoiceIn n - JOIN newSupplier s - JOIN invoiceInTax it ON n.id = it.invoiceInFk - JOIN taxCode tc ON tc.id = it.taxCodeFk - JOIN taxType tt ON tt.id = tc.taxTypeFk - JOIN invoiceInSerial iis ON iis.code = tt.serial - JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk - LEFT JOIN - (SELECT eWithheld.id - FROM invoiceInTax hold - JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld - WHERE hold.invoiceInFk = 58262 LIMIT 1 - ) eWithheld ON TRUE - WHERE tc.type != '-' - AND tc.isActive - GROUP BY tc.rate; - - -- Linea iva inversor sujeto pasivo - - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EUROHABER, - BASEEURO, - CONCEPTO, - FACTURA, - IVA, - AUXILIAR, - SERIE, - TIPOOPE, - FECHA_EX, - FECHA_OP, - NFACTICK, - FACTURAEX, - L340, - LRECT349, - TIPOCLAVE, - TIPOEXENCI, - TIPONOSUJE, - TIPOFACT, - TIPORECTIF, - TERIDNIF, - TERNIF, - TERNOM, - empresa_id - ) - - SELECT - vBookNumber ASIEN, - n.bookEntried FECHA, - tcLink.code SUBCTA, - s.supplierAccount CONTRA, - ROUND(tcLink.rate/100*SUM(it.taxableBase) + 0.0001,2) EUROHABER, - ROUND(SUM(it.taxableBase),2) BASEEURO, - GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, - vSerialNumber FACTURA, - tcLink.rate IVA, - '*' AUXILIAR, - n.serial SERIE, - tt.TIPOOPE, - n.issued FECHA_EX, - n.operated FECHA_OP, - n.invoicesCount NFACTICK, - n.supplierRef FACTURAEX, - FALSE L340, - (isSameCountry OR NOT isUeeMember) LRECT349, - 1 TIPOCLAVE, - n.cplusTaxBreakFk TIPOEXENCI, - n.cplusSubjectOpFk TIPONOSUJE, - n.cplusInvoiceType472Fk TIPOFACT, - n.cplusRectificationTypeFk TIPORECTIF, - iis.cplusTerIdNifFk TERIDNIF, - s.nif AS TERNIF, - s.name AS TERNOM, - n.companyFk - - FROM newInvoiceIn n - JOIN newSupplier s - JOIN invoiceInTax it ON n.id = it.invoiceInFk - JOIN taxCode tc ON tc.id = it.taxCodeFk - JOIN taxType tt ON tt.id = tc.taxTypeFk - JOIN invoiceInSerial iis ON iis.code = tt.serial - JOIN taxCode tcLink ON tcLink.link = tc.link AND tc.id != tcLink.id - JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk - WHERE tc.isActive - GROUP BY tcLink.rate, e.id; - --- Actualización del registro original - UPDATE invoiceIn ii - JOIN newInvoiceIn ni ON ii.id = ni.id - SET - ii.serialNumber = vSerialNumber, - ii.isBooked = TRUE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceInBookingMainkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceInBookingMainkk`(vInvoiceInId INT) -BEGIN - DECLARE vTotalAmount DECIMAL(10,2); - DECLARE vBookNumber,vSerialNumber INT; - - CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber); - - SELECT SUM(iit.taxableBase * IF(i.serial = 'R', 1 +(tc.rate/100),1)) - INTO vTotalAmount - FROM newInvoiceIn i - JOIN invoiceInTax iit ON iit.invoiceInFk = i.id - JOIN taxCode tc ON iit.taxCodeFk = tc.id; - - SELECT MAX(ASIEN) + 1 - INTO vBookNumber - FROM vn2008.XDiario; - - -- Apunte del proveedor - - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - EUROHABER, - CONCEPTO, - NFACTICK, - empresa_id) - SELECT - vBookNumber, - n.bookEntried, - s.supplierAccount, - vTotalAmount, - n.conceptWithSupplier, - n.invoicesCount, - n.companyFk - FROM newInvoiceIn n - JOIN newSupplier s; - - -- ----------------------------------------------------------- Linea de Gastos - INSERT INTO vn2008.XDiario ( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EURODEBE, - EUROHABER, - CONCEPTO, - NFACTICK, - empresa_id - ) - SELECT - vBookNumber ASIEN, - n.bookEntried FECHA, - if( - e.isWithheld, - LPAD(RIGHT(s.supplierAccount ,5),10,iit.expenceFk), - iit.expenceFk - ) SUBCTA, - s.supplierAccount CONTRA, - if( - e.isWithheld, - NULL, - ABS(ROUND(SUM(iit.taxableBase),2)) - ) EURODEBE, - if( - e.isWithheld, - ABS(ROUND(SUM(iit.taxableBase),2)), - NULL - ) EUROHABER, - n.conceptWithSupplier CONCEPTO, - n.invoicesCount NFACTICK, - n.companyFk empresa_id - FROM newInvoiceIn n - JOIN newSupplier s - JOIN invoiceInTax iit ON iit.invoiceInFk = n.id - JOIN taxCode tc ON tc.id = iit.taxCodeFk - JOIN expence e ON e.id = iit.expenceFk AND e.taxTypeFk = tc.taxTypeFk - WHERE iit.expenceFk != 5660000002 - GROUP BY iit.expenceFk; - - - -- -------------------------------------------------------------------- - -- ------- Lineas de IVA --------------- - -- -------------------------------------------------------------------- - - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EURODEBE, - BASEEURO, - CONCEPTO, - FACTURA, - IVA, - AUXILIAR, - SERIE, - TIPOOPE, - FECHA_EX, - FECHA_OP, - NFACTICK, - FACTURAEX, - L340, - LRECT349, - TIPOCLAVE, - TIPOEXENCI, - TIPONOSUJE, - TIPOFACT, - TIPORECTIF, - TERIDNIF, - TERNIF, - TERNOM, - FECREGCON, - empresa_id - ) - SELECT vBookNumber ASIEN, - n.bookEntried FECHA, - tc.code SUBCTA, - s.supplierAccount CONTRA, - SUM(ROUND(tc.rate/100*it.taxableBase + 0.0001,2)) EURODEBE, - SUM(it.taxableBase) BASEEURO, - GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, - vSerialNumber FACTURA, - tc.rate IVA, - IF(isUeeMember AND eWithheld.id IS NULL,'','*') AUXILIAR, - n.serial SERIE, - tt.TIPOOPE, - n.issued FECHA_EX, - n.operated FECHA_OP, - n.invoicesCount NFACTICK, - n.supplierRef FACTURAEX, - TRUE L340, - (isSameCountry OR NOT isUeeMember) LRECT349, - n.cplusTrascendency472Fk TIPOCLAVE, - n.cplusTaxBreakFk TIPOEXENCI, - n.cplusSubjectOpFk TIPONOSUJE, - n.cplusInvoiceType472Fk TIPOFACT, - n.cplusRectificationTypeFk TIPORECTIF, - iis.cplusTerIdNifFk TERIDNIF, - s.nif AS TERNIF, - s.name AS TERNOM, - n.booked FECREGCON, - n.companyFk - - FROM newInvoiceIn n - JOIN newSupplier s - JOIN invoiceInTax it ON n.id = it.invoiceInFk - JOIN taxCode tc ON tc.id = it.taxCodeFk - JOIN taxType tt ON tt.id = tc.taxTypeFk - JOIN invoiceInSerial iis ON iis.code = tt.serial - JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk - LEFT JOIN - (SELECT eWithheld.id - FROM invoiceInTax hold - JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld - WHERE hold.invoiceInFk = 58262 LIMIT 1 - ) eWithheld ON TRUE - WHERE tc.type != '-' - AND tc.isActive - GROUP BY tc.rate; - - -- Linea iva inversor sujeto pasivo - - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EUROHABER, - BASEEURO, - CONCEPTO, - FACTURA, - IVA, - AUXILIAR, - SERIE, - TIPOOPE, - FECHA_EX, - FECHA_OP, - NFACTICK, - FACTURAEX, - L340, - LRECT349, - TIPOCLAVE, - TIPOEXENCI, - TIPONOSUJE, - TIPOFACT, - TIPORECTIF, - TERIDNIF, - TERNIF, - TERNOM, - empresa_id - ) - - SELECT - vBookNumber ASIEN, - n.bookEntried FECHA, - tcLink.code SUBCTA, - s.supplierAccount CONTRA, - ROUND(tcLink.rate/100*SUM(it.taxableBase) + 0.0001,2) EUROHABER, - ROUND(SUM(it.taxableBase),2) BASEEURO, - GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, - vSerialNumber FACTURA, - tcLink.rate IVA, - '*' AUXILIAR, - n.serial SERIE, - tt.TIPOOPE, - n.issued FECHA_EX, - n.operated FECHA_OP, - n.invoicesCount NFACTICK, - n.supplierRef FACTURAEX, - FALSE L340, - (isSameCountry OR NOT isUeeMember) LRECT349, - 1 TIPOCLAVE, - n.cplusTaxBreakFk TIPOEXENCI, - n.cplusSubjectOpFk TIPONOSUJE, - n.cplusInvoiceType472Fk TIPOFACT, - n.cplusRectificationTypeFk TIPORECTIF, - iis.cplusTerIdNifFk TERIDNIF, - s.nif AS TERNIF, - s.name AS TERNOM, - n.companyFk - - FROM newInvoiceIn n - JOIN newSupplier s - JOIN invoiceInTax it ON n.id = it.invoiceInFk - JOIN taxCode tc ON tc.id = it.taxCodeFk - JOIN taxType tt ON tt.id = tc.taxTypeFk - JOIN invoiceInSerial iis ON iis.code = tt.serial - JOIN taxCode tcLink ON tcLink.linkFk = tc.linkFk AND tc.id != tcLink.id - JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk - WHERE tc.isActive - GROUP BY tcLink.rate, e.id; - --- Actualización del registro original - UPDATE invoiceIn ii - JOIN newInvoiceIn ni ON ii.id = ni.id - SET - ii.serialNumber = vSerialNumber, - ii.isBooked = TRUE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceMakeByClient` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceMakeByClient`(vClientFk INT, vSerial CHAR(1), vShipped DATE, vCompanyFk INT, OUT vInvoiceId INT) -BEGIN -/** - * Factura un ticket - * @param vTicketFk Id del ticket - * @param vSerial Serie de factura - * @return Id factura - */ - CALL invoiceFromClient(vShipped, vClientFk, vCompanyFk); - CALL invoiceOutMake(vSerial, CURDATE(), vInvoiceId); - - IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN - CALL invoiceOutBooking(vInvoiceId); - INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(1, 3, vInvoiceId); - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceMakeByTicket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceMakeByTicket`(vTicketFk INT, vSerial CHAR(1), OUT vInvoiceId INT) -BEGIN -/** - * Factura un ticket - * @param vTicketFk Id del ticket - * @param vSerial Serie de factura - * @return Id factura - */ - CALL invoiceFromTicket(vTicketFk); - CALL invoiceOutMake(vSerial, CURDATE(), vInvoiceId); - - IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN - CALL invoiceOutBooking(vInvoiceId); - INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(1, 3, vInvoiceId); - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutAgain` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutAgain`(IN vInvoiceRef VARCHAR(15)) -BEGIN - -/* Para tickets ya facturados, vuelve a repetir el proceso de facturación. -* -* @param vInvoice Numero de factura -*/ - - DECLARE vInvoice INT; - DECLARE vCountry INT; - DECLARE vTaxArea VARCHAR(15); - DECLARE vSpainCountryCode INT DEFAULT 1; - - SELECT id - INTO vInvoice - FROM invoiceOut - WHERE ref = vInvoiceRef; - - UPDATE invoiceOut - SET pdf = 0 - WHERE id = vInvoice; - - SELECT s.countryFk - INTO vCountry - FROM supplier s - JOIN invoiceOut io ON io.companyFk = s.id - WHERE io.id = vInvoice; - /* - SELECT IF(a.isEqualizated - AND c.countryFk = vSpainCountryCode - AND i.taxAreaFk = 'NATIONAL', - 'EQU', - i.taxAreaFk) - INTO vTaxArea - FROM invoiceOutSerial i - JOIN invoiceOut io - JOIN ticket t ON t.refFk = io.ref - JOIN address a ON a.id = t.addressFk - JOIN client c ON c.id = t.clientFk - WHERE io.id = vInvoice AND i.code = invoiceSerial(io.clientFk,io.companyFk,'R') - LIMIT 1; - */ - DROP TEMPORARY TABLE IF EXISTS ticketToInvoice; - - CREATE TEMPORARY TABLE ticketToInvoice - SELECT id - FROM ticket - WHERE refFk = vInvoiceRef; - - CALL invoiceExpenceMake(vInvoice); - - -- CALL invoiceTaxMake(vInvoice,vCountry,vTaxArea); - CALL invoiceTaxMake(vInvoice,vCountry); - - UPDATE invoiceOut io - JOIN ( - SELECT SUM(amount) AS total - FROM invoiceOutExpence - WHERE invoiceOutFk = vInvoice - ) base - JOIN ( - SELECT SUM(vat) AS total - FROM invoiceOutTax - WHERE invoiceOutFk = vInvoice - ) vat - SET io.amount = base.total + vat.total - WHERE io.id = vInvoice; - - CALL vn.invoiceOutBooking(vInvoice); - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutAgainDateRange` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutAgainDateRange`(IN vFirstDate DATE, IN vLastDate DATE) -BEGIN - - DECLARE done BOOL DEFAULT FALSE; - DECLARE vInvoice INT; - DECLARE vInvoiceRef VARCHAR(15); - DECLARE vContador INT DEFAULT 0; - - DECLARE rs CURSOR FOR - SELECT id, ref - FROM vn.invoiceOut - WHERE issued BETWEEN vFirstDate AND vLastDate - AND booked IS NULL; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - OPEN rs; - - FETCH rs INTO vInvoice, vInvoiceRef; - - WHILE NOT done DO - - CALL vn.invoiceOutAgain(vInvoiceRef); - - FETCH rs INTO vInvoice, vInvoiceRef; - - SET vContador = vContador + 1; - - IF vContador MOD 50 = 0 THEN - - SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS; - - END IF; - END WHILE; - - CLOSE rs; - - SELECT CONCAT(vContador, ' total') AS FACTURAS_ASENTADAS; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutBooking` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutBooking`(IN vInvoice INT) -BEGIN - -/* Asienta la factura emitida -* -* param vInvoice factura_id -*/ - - DECLARE vBookNumber INT; - DECLARE vExpenceConcept VARCHAR(50); - DECLARE isUEENotSpain INT DEFAULT 1; - DECLARE vSpain INT DEFAULT 1; - DECLARE vOldBookNumber INT; - - SELECT ASIEN - INTO vOldBookNumber - FROM vn2008.XDiario x - JOIN vn.invoiceOut io ON io.id = vInvoice - WHERE x.SERIE = io.serial - AND x.FACTURA = RIGHT(io.ref, LENGTH(io.ref) - 1) - LIMIT 1; - - DELETE - FROM vn2008.XDiario - WHERE ASIEN = vOldBookNumber; - - 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, - opDate.FECHA_OP, - io.issued AS FECHA, - 1 AS NFACTICK, - IF(ic.correctingFk,'D','') AS TIPOOPE, - io.cplusTrascendency477Fk AS TIPOCLAVE, - io.cplusTaxBreakFk AS TIPOEXENCI, - io.cplusSubjectOpFk AS TIPONOSUJE, - io.cplusInvoiceType477Fk AS TIPOFACT, - ic.cplusRectificationTypeFk AS TIPORECTIF, - io.companyFk, - RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum, - IF(ct.politicalCountryFk = vSpain, 1, IF(ct.CEE = isUEENotSpain,2,4)) AS TERIDNIF, - CONCAT(IF(ct.CEE = isUEENotSpain,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 - - FROM invoiceOut io - JOIN ( - SELECT GREATEST(MAX(shipped), TIMESTAMPADD(DAY,-15,io.issued)) as FECHA_OP - FROM ticket t - JOIN invoiceOut io ON io.ref = t.refFk - WHERE io.id = vInvoice ) opDate - 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 - WHERE io.id = vInvoice; - - SELECT MAX(ASIEN) + 1 - INTO vBookNumber - FROM vn2008.XDiario; - - -- Linea del cliente - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - EURODEBE, - CONCEPTO, - FECHA_EX, - FECHA_OP, - empresa_id - ) - SELECT - vBookNumber AS ASIEN, - rs.FECHA, - rs.clientBookingAccount AS SUBCTA, - rs.totalAmount AS EURODEBE, - rs.simpleConcept AS CONCEPTO, - rs.FECHA_EX, - rs.FECHA_OP, - rs.companyFk AS empresa_id - FROM rs; - - -- Lineas de gasto - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EUROHABER, - CONCEPTO, - FECHA_EX, - FECHA_OP, - empresa_id - ) - SELECT - vBookNumber AS ASIEN, - rs.FECHA, - ioe.expenceFk 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 invoiceOutExpence ioe - WHERE ioe.invoiceOutFk = vInvoice; - - SELECT GROUP_CONCAT(`name` SEPARATOR ',') - INTO vExpenceConcept - FROM expence e - JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id - WHERE ioe.invoiceOutFk = vInvoice; - - -- Lineas de IVA - INSERT INTO vn2008.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, - rs.FECHA, - iot.pgcFk AS SUBCTA, - rs.clientBookingAccount AS CONTRA, - iot.vat AS EUROHABER, - iot.taxableBase AS BASEEURO, - CONCAT(vExpenceConcept,' : ',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, - rs.SERIE, - rs.SERIE_RT, - rs.FACTU_RT, - rs.RECTIFICA, - rs.FECHA_RT, - rs.FECHA_OP, - rs.FECHA_EX, - rs.TIPOOPE, - rs.NFACTICK, - rs.TERIDNIF, - rs.TERNIF, - rs.TERNOM, - pgc.mod340 AS L340, - pgc.cplusTrascendency477Fk AS TIPOCLAVE, - pgc.cplusTaxBreakFk as TIPOEXENCI, - rs.TIPONOSUJE, - rs.TIPOFACT, - rs.TIPORECTIF, - rs.companyFk AS empresa_id - 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. - WHERE iot.invoiceOutFk = vInvoice; - - UPDATE invoiceOut - SET booked = CURDATE() - WHERE id = vInvoice; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutBookingkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutBookingkk`(IN vInvoice INT) -BEGIN - -/* Asienta la factura emitida -* -* param vInvoice factura_id -*/ - - DECLARE vBookNumber INT; - DECLARE vExpenceConcept VARCHAR(50); - DECLARE isUEENotSpain INT DEFAULT 1; - DECLARE vOldBookNumber INT; - - SELECT ASIEN - INTO vOldBookNumber - FROM vn2008.XDiario x - JOIN vn.invoiceOut io ON io.id = vInvoice - WHERE x.SERIE = io.serial - AND x.FACTURA = RIGHT(io.ref, LENGTH(io.ref) - 1) - LIMIT 1; - - DELETE - FROM vn2008.XDiario - WHERE ASIEN = vOldBookNumber; - - SELECT MAX(ASIEN) + 1 - INTO vBookNumber - FROM vn2008.XDiario; - - 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, - opDate.FECHA_OP, - io.issued AS FECHA, - 1 AS NFACTICK, - IF(ic.correctingFk,'D','') AS TIPOOPE, - io.cplusTrascendency477Fk AS TIPOCLAVE, - io.cplusTaxBreakFk AS TIPOEXENCI, - io.cplusSubjectOpFk AS TIPONOSUJE, - io.cplusInvoiceType477Fk AS TIPOFACT, - ic.cplusRectificationTypeFk AS TIPORECTIF, - io.companyFk, - RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum, - IF(ct.CEE = 0, 1, IF(ct.CEE = isUEENotSpain,2,4)) AS TERIDNIF, - CONCAT(IF(ct.CEE = isUEENotSpain,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 - - FROM invoiceOut io - JOIN ( - SELECT MAX(shipped) as FECHA_OP - FROM ticket t - JOIN invoiceOut io ON io.ref = t.refFk - WHERE io.id = vInvoice ) opDate - 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 - WHERE io.id = vInvoice; - - -- Linea del cliente - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - EURODEBE, - CONCEPTO, - FECHA_EX, - FECHA_OP, - empresa_id - ) - SELECT - vBookNumber AS ASIEN, - rs.FECHA, - rs.clientBookingAccount AS SUBCTA, - rs.totalAmount AS EURODEBE, - rs.simpleConcept AS CONCEPTO, - rs.FECHA_EX, - rs.FECHA_OP, - rs.companyFk AS empresa_id - FROM rs; - - -- Lineas de gasto - INSERT INTO vn2008.XDiario( - ASIEN, - FECHA, - SUBCTA, - CONTRA, - EUROHABER, - CONCEPTO, - FECHA_EX, - FECHA_OP, - empresa_id - ) - SELECT - vBookNumber AS ASIEN, - rs.FECHA, - ioe.expenceFk 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 invoiceOutExpence ioe - WHERE ioe.invoiceOutFk = vInvoice; - - SELECT GROUP_CONCAT(`name` SEPARATOR ',') - INTO vExpenceConcept - FROM expence e - JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id - WHERE ioe.invoiceOutFk = vInvoice; - - -- Lineas de IVA - INSERT INTO vn2008.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, - rs.FECHA, - iot.pgcFk AS SUBCTA, - rs.clientBookingAccount AS CONTRA, - iot.vat AS EUROHABER, - iot.taxableBase AS BASEEURO, - CONCAT(vExpenceConcept,' : ',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, - rs.SERIE, - rs.SERIE_RT, - rs.FACTU_RT, - rs.RECTIFICA, - rs.FECHA_RT, - rs.FECHA_OP, - rs.FECHA_EX, - rs.TIPOOPE, - rs.NFACTICK, - rs.TERIDNIF, - rs.TERNIF, - rs.TERNOM, - pgc.mod340 AS L340, - pgc.cplusTrascendency477Fk AS TIPOCLAVE, - pgc.cplusTaxBreakFk as TIPOEXENCI, - rs.TIPONOSUJE, - rs.TIPOFACT, - rs.TIPORECTIF, - rs.companyFk AS empresa_id - 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. - WHERE iot.invoiceOutFk = vInvoice; - - UPDATE invoiceOut - SET booked = CURDATE() - WHERE id = vInvoice; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutBookingRange` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutBookingRange`() -BEGIN - -/* Reasentar facturas -*/ - - - DECLARE vInvoice INT; - DECLARE vContador INT DEFAULT 0; - - DECLARE done BOOL DEFAULT FALSE; - - DECLARE rs CURSOR FOR - SELECT io.id - FROM invoiceOut io - WHERE RIGHT(ref,7) BETWEEN 1724215 AND 1724224 - AND serial = 'T'; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - OPEN rs; - - FETCH rs INTO vInvoice; - - WHILE NOT done DO - - CALL invoiceOutBooking(vInvoice); - - FETCH rs INTO vInvoice ; - - SET vContador = vContador + 1; - - IF vContador MOD 50 = 0 THEN - - SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS; - - END IF; - - END WHILE; - - CLOSE rs; - - SELECT CONCAT(vContador, ' total') AS FACTURAS_ASENTADAS; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutDelete` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutDelete`(vRef VARCHAR(15)) -BEGIN - - UPDATE ticket - SET refFk = NULL - WHERE refFk = vRef; - - DELETE - FROM invoiceOut - WHERE ref = vRef; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutFix_BI_RE_IVA` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutFix_BI_RE_IVA`() -BEGIN - -DECLARE done BOOL DEFAULT FALSE; -DECLARE vInvoice INT; - -DECLARE rs CURSOR FOR - SELECT factura_id - FROM vn2008.Facturas - WHERE Importe != BI7 + BI16 + RE4 + RE1 + IVA7 + IVA16 - AND Fecha >= '2017-07-01'; - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - -OPEN rs; - -FETCH rs INTO vInvoice; - -SELECT vInvoice, done; - -WHILE NOT done DO - - UPDATE invoiceOut io - JOIN ( - SELECT SUM(amount) AS total - FROM invoiceOutExpence - WHERE invoiceOutFk = vInvoice - ) base - JOIN ( - SELECT SUM(vat) AS total - FROM invoiceOutTax - WHERE invoiceOutFk = vInvoice - ) vat - SET io.amount = base.total + vat.total - WHERE io.id = vInvoice; - - UPDATE vn2008.Facturas - SET BI16 = 0, - BI7 = 0, - RE1 = 0, - RE4 = 0, - IVA7 = 0, - IVA16 = 0 - WHERE factura_id = vInvoice; - - UPDATE vn2008.Facturas f - JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id - SET f.BI16 = iot.taxableBase, f.IVA16 = iot.vat - WHERE f.factura_id = vInvoice - AND iot.pgcFk IN ('4770000021' ,'4770000215', '4770000002','4771000000','4770000000','4770000020'); - - UPDATE vn2008.Facturas f - JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id - SET f.RE4 = iot.vat - WHERE f.factura_id = vInvoice - AND iot.pgcFk = '4770000521'; - - UPDATE vn2008.Facturas f - JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id - SET f.BI7 = iot.taxableBase, f.IVA7 = iot.vat - WHERE f.factura_id = vInvoice - AND iot.pgcFk IN ('4770000010' ,'4770000101'); - - UPDATE vn2008.Facturas f - JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id - SET f.RE1 = iot.vat - WHERE f.factura_id = vInvoice - AND iot.pgcFk = '4770000110'; - -FETCH rs INTO vInvoice; - -END WHILE; - - -CLOSE rs; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutListByCompany` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutListByCompany`(vCompany INT, vStarted DATE, vEnded DATE) -BEGIN - -SELECT - c.socialName as RazonSocial, - c.fi as NIF, - io.ref as Factura, - io.serial as Serie, - io.issued as Fecha, - io.amount as Importe, - c.id as Id_Cliente, - iot.taxableBase as Base, - pgc.rate as Tipo, - iot.vat as Cuota, - pgc.name as Concepto - - FROM vn.invoiceOut io - JOIN vn.invoiceOutTax iot ON iot.invoiceOutFk = io.id - JOIN vn.client c ON c.id = io.clientFk - JOIN vn.pgc ON pgc.code = iot.pgcFk - WHERE io.companyFk = vCompany - AND io.issued BETWEEN vStarted AND vEnded - ORDER BY io.ref DESC; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutMake` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutMake`( - vSerial VARCHAR(255), - vInvoiceDate DATETIME, - OUT vNewInvoiceId INT) -BEGIN - -/* Creación de facturas emitidas. -* REQUIERE previamente tabla ticketToInvoice. -* -* @param vSerial, vInvoiceDate, vCompany, vClient -* -* @return vNewInvoiceId -*/ - - DECLARE vSpainCountryCode INT DEFAULT 1; - DECLARE vIsAnySaleToInvoice BOOL; - DECLARE vCountry TINYINT DEFAULT 1; - DECLARE vNewRef VARCHAR(255); - DECLARE vWorker INT DEFAULT vn.getWorker(); - DECLARE vCompany INT; - DECLARE vClient INT; - DECLARE vCplusStandardInvoiceTypeFk INT DEFAULT 1; - DECLARE vCplusCorrectingInvoiceTypeFk INT DEFAULT 6; - DECLARE vCplusSimplifiedInvoiceTypeFk INT DEFAULT 2; - DECLARE vCorrectingSerial VARCHAR(1) DEFAULT 'R'; - DECLARE vSimplifiedSerial VARCHAR(1) DEFAULT 'S'; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - ROLLBACK; - RESIGNAL; - END; - - SET vInvoiceDate = IFNULL(vInvoiceDate,CURDATE()); - - SELECT t.clientFk, t.companyFk - INTO vClient, vCompany - FROM ticketToInvoice tt - JOIN ticket t ON t.id = tt.id - LIMIT 1; - - START TRANSACTION; - - -- Elimina tickets sense moviments -/* UPDATE ticket t - JOIN ticketToInvoice ti ON ti.id = t.id - LEFT JOIN sale s ON s.ticketFk = ti.id - LEFT JOIN expedition e ON e.ticketFk = t.id - LEFT JOIN ticketPackaging tp ON tp.ticketFk = t.id - SET t.shipped = '2000-02-01 00:00:00' - WHERE s.ticketFk IS NULL AND e.ticketFk IS NULL AND e.ticketFk IS NULL; -*/ - -- Eliminem de ticketToInvoice els tickets que no han de ser facturats - DELETE ti.* - FROM ticketToInvoice ti - JOIN ticket t ON t.id = ti.id - JOIN client c ON c.id = t.clientFk - WHERE YEAR(t.shipped) < 2001 - OR c.isTaxDataChecked = FALSE; - - SELECT SUM(quantity * price * (100 - discount)/100) - INTO vIsAnySaleToInvoice - FROM sale s - JOIN ticketToInvoice t on t.id = s.ticketFk; - - IF vIsAnySaleToInvoice THEN - - -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial - -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial - INSERT INTO invoiceOut - ( - ref, - serial, - issued, - clientFk, - dued, - companyFk, - cplusInvoiceType477Fk - ) - SELECT - 1, - vSerial, - vInvoiceDate, - vClient, - getDueDate(vInvoiceDate, dueDay), - vCompany, - IF(vSerial = vCorrectingSerial, - vCplusCorrectingInvoiceTypeFk, - IF(vSerial = vSimplifiedSerial, - vCplusSimplifiedInvoiceTypeFk, - vCplusStandardInvoiceTypeFk)) - FROM client - WHERE id = vClient; - - - SET vNewInvoiceId = LAST_INSERT_ID(); - - SELECT ref - INTO vNewRef - FROM invoiceOut - WHERE id = vNewInvoiceId; - - UPDATE ticket t - JOIN ticketToInvoice ti ON ti.id = t.id - SET t.refFk = vNewRef; - - DROP TEMPORARY TABLE IF EXISTS tmp.updateInter; - CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY - SELECT s.id,ti.id ticket_id,vWorker Id_Trabajador - FROM ticketToInvoice ti - JOIN vn.ticketState ts ON ti.id = ts.ticket - JOIN state s - WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = vn.getAlert3State(ti.id); - - INSERT INTO vncontrol.inter(state_id,Id_Ticket,Id_Trabajador) - SELECT * FROM tmp.updateInter; - - - INSERT INTO ticketLog (action, userFk,originFk, description) - SELECT 'UPDATE',account.userGetId(),ti.id, CONCAT('Crea factura ',vNewRef) - FROM ticketToInvoice ti; - - CALL invoiceExpenceMake(vNewInvoiceId); - CALL invoiceTaxMake(vNewInvoiceId,vCountry); - - UPDATE invoiceOut io - JOIN ( - SELECT SUM(amount) AS total - FROM invoiceOutExpence - WHERE invoiceOutFk = vNewInvoiceId - ) base - JOIN ( - SELECT SUM(vat) AS total - FROM invoiceOutTax - WHERE invoiceOutFk = vNewInvoiceId - ) vat - SET io.amount = base.total + vat.total - WHERE io.id = vNewInvoiceId; - - END IF; - - DROP TEMPORARY TABLE `ticketToInvoice`; - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutMakekk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutMakekk`( - vSerial VARCHAR(255), - vInvoiceDate DATETIME, - OUT vNewInvoiceId INT) -BEGIN - -/* Creación de facturas emitidas. -* REQUIERE previamente tabla ticketToInvoice. -* -* @param vSerial, vInvoiceDate, vCompany, vClient -* -* @return vNewInvoiceId -*/ - - DECLARE vSpainCountryCode INT DEFAULT 1; - DECLARE vIsAnySaleToInvoice BOOL; - DECLARE vCountry TINYINT DEFAULT 1; - DECLARE vTaxArea VARCHAR(15); - DECLARE vNewRef VARCHAR(255); - DECLARE vWorker INT DEFAULT vn.getWorker(); - DECLARE vCompany INT; - DECLARE vClient INT; - DECLARE vCplusStandardInvoiceTypeFk INT DEFAULT 1; - DECLARE vCplusCorrectingInvoiceTypeFk INT DEFAULT 6; - DECLARE vCorrectingSerial VARCHAR(1) DEFAULT 'R'; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - ROLLBACK; - RESIGNAL; - END; - - SET vInvoiceDate = IFNULL(vInvoiceDate,CURDATE()); - - SELECT t.clientFk, t.companyFk - INTO vClient, vCompany - FROM ticketToInvoice tt - JOIN ticket t ON t.id = tt.id - LIMIT 1; - - SELECT countryFk - INTO vCountry - FROM supplier - WHERE id = vCompany; - - SELECT IF(a.isEqualizated - AND c.countryFk = vSpainCountryCode - AND i.taxAreaFk = 'NATIONAL', - 'EQU', - i.taxAreaFk) - INTO vTaxArea - FROM invoiceOutSerial i - JOIN ticketToInvoice tti - JOIN ticket t ON t.id = tti.id - JOIN address a ON a.id = t.addressFk - JOIN client c ON c.id = t.clientFk - WHERE i.code = invoiceSerial(t.clientFk,t.companyFk,'R') - LIMIT 1; - - START TRANSACTION; - - -- Elimina tickets sense moviments -/* UPDATE ticket t - JOIN ticketToInvoice ti ON ti.id = t.id - LEFT JOIN sale s ON s.ticketFk = ti.id - LEFT JOIN expedition e ON e.ticketFk = t.id - LEFT JOIN ticketPackaging tp ON tp.ticketFk = t.id - SET t.shipped = '2000-02-01 00:00:00' - WHERE s.ticketFk IS NULL AND e.ticketFk IS NULL AND e.ticketFk IS NULL; -*/ - -- Eliminem de ticketToInvoice els tickets que no han de ser facturats - DELETE ti.* - FROM ticketToInvoice ti - JOIN ticket t ON t.id = ti.id - JOIN client c ON c.id = t.clientFk - WHERE YEAR(t.shipped) < 2001 - OR c.isTaxDataChecked = FALSE; - - SELECT SUM(quantity * price * (100 - discount)/100) - INTO vIsAnySaleToInvoice - FROM sale s - JOIN ticketToInvoice t on t.id = s.ticketFk; - - IF vIsAnySaleToInvoice THEN - - -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial - -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial - INSERT INTO invoiceOut - ( - ref, - serial, - issued, - clientFk, - dued, - companyFk, - cplusInvoiceType477Fk - ) - SELECT - 1, - vSerial, - vInvoiceDate, - vClient, - getDueDate(vInvoiceDate, dueDay), - vCompany, - IF(vSerial = vCorrectingSerial, vCplusCorrectingInvoiceTypeFk, vCplusStandardInvoiceTypeFk) - FROM client - WHERE id = vClient; - - - SET vNewInvoiceId = LAST_INSERT_ID(); - - SELECT ref - INTO vNewRef - FROM invoiceOut - WHERE id = vNewInvoiceId; - - UPDATE ticket t - JOIN ticketToInvoice ti ON ti.id = t.id - SET t.refFk = vNewRef; - - DROP TEMPORARY TABLE IF EXISTS tmp.updateInter; - CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY - SELECT s.id,ti.id ticket_id,vWorker Id_Trabajador - FROM ticketToInvoice ti - JOIN vn.ticketState ts ON ti.id = ts.ticket - JOIN state s - WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = vn.getAlert3State(ti.id); - - INSERT INTO vncontrol.inter(state_id,Id_Ticket,Id_Trabajador) - SELECT * FROM tmp.updateInter; - - - INSERT INTO ticketLog (action, userFk,originFk, description) - SELECT 'UPDATE',account.userGetId(),ti.id, CONCAT('Crea factura ',vNewRef) - FROM ticketToInvoice ti; - - CALL invoiceExpenceMake(vNewInvoiceId); - CALL invoiceTaxMake(vNewInvoiceId,vCountry,vTaxArea); - - UPDATE invoiceOut io - JOIN ( - SELECT SUM(amount) AS total - FROM invoiceOutExpence - WHERE invoiceOutFk = vNewInvoiceId - ) base - JOIN ( - SELECT SUM(vat) AS total - FROM invoiceOutTax - WHERE invoiceOutFk = vNewInvoiceId - ) vat - SET io.amount = base.total + vat.total - WHERE io.id = vNewInvoiceId; - - END IF; - - DROP TEMPORARY TABLE `ticketToInvoice`; - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutTaxAndExpence` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceOutTaxAndExpence`() -BEGIN - -/* Para tickets ya facturados, vuelve a repetir el proceso de facturación. -* -* @param vInvoice Numero de factura -*/ - - - - DECLARE vInvoice INT; - DECLARE vInvoiceRef VARCHAR(15); - DECLARE vCountry INT; - DECLARE vTaxArea VARCHAR(15); - DECLARE vContador INT DEFAULT 0; - - DECLARE done BOOL DEFAULT FALSE; - - DECLARE rs CURSOR FOR - SELECT id,ref - FROM invoiceOut io - - WHERE issued >= '2017-07-01' - AND companyFk = 1381 - AND io.amount IS NULL - ; - - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - OPEN rs; - - FETCH rs INTO vInvoice ,vInvoiceRef; - - WHILE NOT done DO - - SELECT s.countryFk - INTO vCountry - FROM supplier s - JOIN invoiceOut io ON io.companyFk = s.id - WHERE io.id = vInvoice; - - SELECT IF(c.isEqualizated AND i.taxAreaFk = 'NATIONAL','EQU',i.taxAreaFk) - INTO vTaxArea - FROM invoiceOutSerial i - JOIN invoiceOut io ON io.serial = i.code - JOIN client c ON c.id = io.clientFk - WHERE io.id = vInvoice; - - DROP TEMPORARY TABLE IF EXISTS ticketToInvoice; - - CREATE TEMPORARY TABLE ticketToInvoice - SELECT id - FROM ticket - WHERE refFk = vInvoiceRef; - - CALL invoiceExpenceMake(vInvoice); - CALL invoiceTaxMake(vInvoice,vCountry,vTaxArea); - - FETCH rs INTO vInvoice ,vInvoiceRef; - - SET vContador = vContador + 1; - - IF vContador MOD 50 = 0 THEN - - SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS; - - END IF; - - END WHILE; - - CLOSE rs; - - SELECT CONCAT(vContador, ' total') AS FACTURAS_ASENTADAS; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceTaxMake` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceTaxMake`(IN vInvoice INT, IN vCountry INT) -BEGIN - - DELETE FROM invoiceOutTax - WHERE invoiceOutFk = vInvoice; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - (KEY (ticketFk)) - ENGINE = MEMORY - SELECT id ticketFk - FROM ticketToInvoice; - - CALL ticketGetTax(); - - INSERT INTO invoiceOutTax( - invoiceOutFk, - pgcFk, - taxableBase, - vat - ) - SELECT vInvoice, - pgcFk, - SUM(taxableBase), - SUM(tax) - FROM tmp.ticketTax - GROUP BY pgcFk; - - DROP TEMPORARY TABLE tmp.ticket; - DROP TEMPORARY TABLE tmp.ticketTax; - DROP TEMPORARY TABLE tmp.ticketAmount; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceTaxMakekk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `invoiceTaxMakekk`(IN vInvoice INT, IN vCountry INT, IN vTaxArea VARCHAR(15)) -BEGIN -/* Inserta los registros de iva de la factura emitida -* REQUIERE tabla ticketToInvoice -* -* @param vInvoice Id de la factura -*/ - - DELETE FROM invoiceOutTax - WHERE invoiceOutFk = vInvoice; - - INSERT INTO invoiceOutTax( - invoiceOutFk, - pgcFk, - taxableBase, - vat - ) - SELECT vInvoice, - bp.pgcFk, - SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) - ) taxableBase, - SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) - ) * pgc.rate / 100 - FROM ticketToInvoice t - JOIN sale s ON s.ticketFk = t.id - JOIN item i ON i.id = s.itemFk - JOIN itemTaxCountry itc - ON itc.itemFk = i.id AND itc.countryFk = vCountry - JOIN bookingPlanner bp - ON bp.countryFk = vCountry - AND bp.taxAreaFk = vTaxArea - AND bp.taxClassFk = itc.taxClassFk - JOIN pgc ON pgc.code = bp.pgcFk - GROUP BY pgc.code - HAVING taxableBase != 0; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemTagArrangedUpdate` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `itemTagArrangedUpdate`(IN vItem BIGINT) -BEGIN -/** - * Actualiza la tabla itemTagArranged - * - * @param vItem El Id_item de toda la vida. Si es cero, equivale a todos. - **/ - DELETE - FROM itemTagArranged - WHERE vItem IS NULL - OR vItem = itemFk; - - INSERT INTO itemTagArranged(itemFk) - SELECT id - FROM item - WHERE vItem IS NULL - OR vItem = id; - - REPLACE itemTagArranged - SELECT i.id, - 'Medida' as tag1, - LEFT(i.size,15) as val1, - 'Color' as tag2, - LEFT(ink.`name`,15) as val2, - 'Categoria' as tag3, - LEFT(i.category,15) as val3, - 'Productor' as tag4, - LEFT(p.`name`,15) as val4, - 'Tallos' as tag5, - i.stems as val5, - 'Origen' as tag6, - o.code as val6, - i.description - FROM item i - LEFT JOIN itemTagged it ON it.itemFk = i.id - LEFT JOIN ink on ink.id = i.inkFk - JOIN origin o ON o.id = i.originFk - LEFT JOIN producer p ON p.id = i.producerFk - WHERE it.itemFk IS NULL - AND (vItem IS NULL OR vItem = i.id); - - CALL itemTagUpdatePriority(vItem); - - UPDATE itemTagArranged ita - JOIN itemTag it ON it.itemFk = ita.itemFk - JOIN tag t ON t.id = it.tagFk - SET tag1 = t.name, val1 = it.value - WHERE it.priority = 1 - AND (vItem IS NULL OR vItem = it.itemFk); - - UPDATE itemTagArranged ita - JOIN itemTag it ON it.itemFk = ita.itemFk - JOIN tag t ON t.id = it.tagFk - SET tag2 = t.name, val2 = it.value - WHERE it.priority = 2 - AND (vItem IS NULL OR vItem = it.itemFk); - - UPDATE itemTagArranged ita - JOIN itemTag it ON it.itemFk = ita.itemFk - JOIN tag t ON t.id = it.tagFk - SET tag3 = t.name, val3 = it.value - WHERE it.priority = 3 - AND (vItem IS NULL OR vItem = it.itemFk); - - UPDATE itemTagArranged ita - JOIN itemTag it ON it.itemFk = ita.itemFk - JOIN tag t ON t.id = it.tagFk - SET tag4 = t.name, val4 = it.value - WHERE it.priority = 4 - AND (vItem IS NULL OR vItem = it.itemFk); - - UPDATE itemTagArranged ita - JOIN itemTag it ON it.itemFk = ita.itemFk - JOIN tag t ON t.id = it.tagFk - SET tag5 = t.name, val5 = it.value - WHERE it.priority = 5 - AND (vItem IS NULL OR vItem = it.itemFk); - - UPDATE itemTagArranged ita - JOIN itemTag it ON it.itemFk = ita.itemFk - JOIN tag t ON t.id = it.tagFk - SET tag6 = t.name, val6 = it.value - WHERE it.priority = 6 - AND (vItem IS NULL OR vItem = it.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 */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `itemTagMake` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `itemTagMake`(vItemFk INT) -BEGIN - - DELETE FROM itemTag WHERE itemFk = vItemFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id, CONCAT(val1,' cm'), 1 - FROM itemTagArranged ita - JOIN tag t ON t.name = 'Longitud' COLLATE utf8_general_ci - WHERE ita.itemFk = vItemFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id, val2, 2 - FROM itemTagArranged ita - JOIN tag t ON t.name = ita.tag2 COLLATE utf8_general_ci - WHERE ita.itemFk = vItemFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id, val3, 3 - FROM itemTagArranged ita - JOIN tag t ON t.name = ita.tag3 COLLATE utf8_general_ci - WHERE ita.itemFk = vItemFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id, val4, 4 - FROM itemTagArranged ita - JOIN tag t ON t.name = ita.tag4 COLLATE utf8_general_ci - WHERE ita.itemFk = vItemFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id, val5, 5 - FROM itemTagArranged ita - JOIN tag t ON t.name = ita.tag5 COLLATE utf8_general_ci - WHERE ita.itemFk = vItemFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id, val6, 6 - FROM itemTagArranged ita - JOIN tag t ON t.name = ita.tag6 COLLATE utf8_general_ci - WHERE ita.itemFk = vItemFk; - - CALL itemTagArrangedUpdate(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 DROP PROCEDURE IF EXISTS `itemTagUpdatePriority` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `itemTagUpdatePriority`(IN vItem INT) -BEGIN -/* -* Recalcula las prioridades de articleTag -* -* @param vItem Id_Article. Si es 0, lo recalcula todo -*/ - - SET vItem = IFNULL(vItem,0); - - SET @p := 0; - SET @a := 0; - - UPDATE itemTag a - JOIN ( - SELECT - id, - @p := IF(itemFk = @a, @p, 0) + 1 as NewPriority, - @a := itemFk - FROM itemTag - WHERE vItem IS NULL - OR vItem = itemFk - ORDER BY itemFk, priority - ) sub ON sub.id = a.id - SET a.priority = NewPriority; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `itemTagUpdatePriority_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `itemTagUpdatePriority_launcher`() -BEGIN - - CALL vn.itemTagUpdatePriority(0); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `logAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `logAdd`(vOriginFk INT, vActionCode VARCHAR(45), vEntity VARCHAR(45), vDescription TEXT) -BEGIN -/** - * Guarda las acciones realizadas por el usuario - * - * @param vOriginFk Id del registro de origen - * @param vActionCode Código de la acción {insert | delete | update} - * @param vEntity Nombre que hace referencia a la tabla. - * @param descripcion Descripción de la acción realizada por el usuario - */ - DECLARE vTableName VARCHAR(45); - - SET vTableName = CONCAT(vEntity, 'Log'); - - SET @qryLog := CONCAT( - 'INSERT INTO ', vTableName, ' (originFk, userFk, action, description)', - ' VALUES (', vOriginFk, ', ', account.userGetId(), ', "', vActionCode, '", "', vDescription, '")' - ); - - PREPARE stmt FROM @qryLog; - EXECUTE stmt; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `logShow` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `logShow`(vOriginFk INT, vEntity VARCHAR(45)) -BEGIN -/** - * Muestra las acciones realizadas por el usuario - * - * @param vOriginFk Id del registro de origen - * @param vEntity Nombre que hace referencia a la tabla. - */ - DECLARE vTableName VARCHAR(45); - - SET vTableName = CONCAT(vEntity, 'Log'); - - SET @qryLog := CONCAT( - 'SELECT ot.id, ot.originFk, ot.userFk, u.name, ot.action, ot.creationDate, ot.description FROM ', vTableName, ' AS ot', - ' INNER JOIN account.user u ON u.id = ot.userFk', - ' WHERE ot.originFk = ', vOriginFk, ' ORDER BY ot.creationDate DESC' - ); - - PREPARE stmt FROM @qryLog; - EXECUTE stmt; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `mergeTicketUnattended` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `mergeTicketUnattended`(IN vMainTicket INT(11), IN hasSameAgency BOOLEAN) -BEGIN - - DECLARE isBilled BOOLEAN; - DECLARE arrayTickets VARCHAR(255); - - SELECT Factura IS NOT NULL INTO isBilled FROM vn2008.Tickets WHERE Id_Ticket = vMainTicket; - - IF NOT isBilled THEN - - SELECT GROUP_CONCAT(distinct T.Id_Ticket) INTO arrayTickets - FROM vn2008.Tickets T LEFT JOIN vn.ticketState ts ON T.Id_Ticket = ts.ticket - JOIN vn2008.Tickets ticketOriginal ON ticketOriginal.Id_Ticket = vMainTicket - AND T.empresa_id = ticketOriginal.empresa_id - AND T.Id_Consigna = ticketOriginal.Id_Consigna - AND DATE(T.Fecha) = DATE(ticketOriginal.Fecha) - AND T.warehouse_id = ticketOriginal.warehouse_id - AND IF(hasSameAgency <> 0,T.Id_Agencia = ticketOriginal.Id_Agencia,TRUE) - LEFT JOIN vn.ticketState tsOriginal ON ticketOriginal.Id_Ticket = tsOriginal.ticket - WHERE ts.alertLevel < 3 - AND T.Factura IS NULL - AND T.Anotadoencaja = FALSE - AND T.Id_Ticket <> vMainTicket - AND ts.alertLevel = tsOriginal.alertLevel; - - CALL mergeTicketWithArray(vMainTicket,arrayTickets); - - 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 */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `mergeTicketWithArray` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `mergeTicketWithArray`(IN vMainTicket INT(11), IN arrayTickets VARCHAR(50)) -BEGIN - - DECLARE isBilled BOOLEAN; - DECLARE messageLog VARCHAR(50); - DECLARE company INT; - DECLARE messageForSplit VARCHAR(255); - DECLARE vMainSplit INT; - DECLARE worker INT(3); - - SELECT Factura IS NOT NULL INTO isBilled FROM vn2008.Tickets WHERE Id_Ticket = vMainTicket; - - IF NOT isBilled THEN - - SELECT Id_Trabajador INTO worker from vn2008.Trabajadores where user_id = account.userGetId(); - IF worker IS NULL THEN - SET worker = 20; - END IF; - - DROP TEMPORARY TABLE IF EXISTS vn2008.Tickets_to_fusion; - - -- He usado el util.exec porque da error la variable strId_Tickets puesta dentro del IN() - CALL util.exec(sql_printf(' - CREATE TEMPORARY TABLE vn2008.Tickets_to_fusion - SELECT Id_Ticket, Localizacion - FROM vn2008.Tickets T - WHERE Id_Ticket IN (%s);',arrayTickets)); - - INSERT INTO vn2008.ticket_observation (Id_Ticket,observation_type_id,text) - SELECT vMainTicket,observation_type_id,CONCAT(' Ticket ', Id_Ticket, ':' , tco.text, '. ') - FROM vn2008.Tickets_to_fusion tf - INNER JOIN vn2008.ticket_observation tco USING(Id_Ticket) - ON DUPLICATE KEY UPDATE `text` = CONCAT(ticket_observation.`text`,CONCAT(' Ticket ', VALUES(Id_Ticket), ':' , VALUES(`text`), '. ')); - - UPDATE vn2008.Movimientos M - JOIN vn2008.Tickets_to_fusion USING(Id_Ticket) - SET M.Id_Ticket = vMainTicket; - - UPDATE vn2008.expeditions M - JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = M.ticket_id - SET M.ticket_id = vMainTicket; - - UPDATE vn.ticketPackaging tp - JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = tp.ticketFk - SET tp.ticketFk = vMainTicket; - - UPDATE vn2008.Tickets - SET Bultos = (SELECT COUNT(*) FROM vn2008.expeditions WHERE ticket_id = vMainTicket AND EsBulto) - WHERE Id_Ticket = vMainTicket; - - UPDATE vn2008.Tickets - JOIN vn2008.Tickets_to_fusion USING(Id_Ticket) - SET Fecha = TIMESTAMPADD(YEAR,-1 * (YEAR(Fecha)-2000), Fecha); - - UPDATE vn2008.Tickets_dits ts - JOIN vn2008.Tickets_to_fusion t USING(Id_Ticket) - SET ts.Id_Ticket = vMainTicket; - - UPDATE vn2008.Tickets - SET Localizacion = CONCAT(Tickets.Localizacion,' ',IFNULL((SELECT GROUP_CONCAT(Localizacion SEPARATOR ' ') FROM vn2008.Tickets_to_fusion),'')) - WHERE Id_Ticket = vMainTicket; - - UPDATE vn2008.Splits s - RIGHT JOIN vn2008.Tickets_to_fusion t USING(Id_Ticket) - SET s.Id_Ticket = vMainTicket; - - IF (SELECT COUNT(*) FROM vn2008.Splits WHERE Id_Ticket=vMainTicket) > 1 THEN - - SELECT Id_Split INTO vMainSplit FROM vn2008.Splits WHERE Id_Ticket = vMainTicket LIMIT 1; - - SELECT group_concat(Notas,',') INTO messageForSplit FROM vn2008.Splits WHERE Id_Ticket = vMainTicket; - UPDATE vn2008.Splits SET Notas = messageForSplit WHERE Id_Split=vMainSplit; - UPDATE vn2008.Split_lines sl JOIN vn2008.Splits s USING (Id_Split) SET sl.Id_Split=vMainSplit WHERE Id_Ticket=vMainTicket; - DELETE FROM vn2008.Splits WHERE Id_Ticket=vMainTicket AND Id_Split<>vMainSplit; - END IF; - - SELECT GROUP_CONCAT(Id_Ticket SEPARATOR ',') into messageLog FROM vn2008.Tickets_to_fusion; - CALL vn2008.Ditacio(vMainTicket,'Fusion','T',worker,messageLog,NULL); - - DELETE ts FROM vn2008.Tickets_state ts JOIN vn2008.Tickets_to_fusion t USING(Id_Ticket); - /* - UPDATE vncontrol.inter M - JOIN vn2008.Tickets_to_fusion USING(Id_Ticket) - SET M.Id_Ticket = vMainTicket; - */ - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nestAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nestAdd`(vScheme VARCHAR(45), vTable VARCHAR(45), vParentFk INT, vChild VARCHAR(45)) -BEGIN - DECLARE vSql TEXT; - - -- Check parent childs - SET vSql = sql_printf(' - SELECT COUNT(c.id) INTO @childs - FROM %t.%t p - LEFT JOIN %t.%t c ON c.lft BETWEEN p.lft AND p.rgt AND c.id != %v - WHERE p.id = %v', - vScheme, vTable, vScheme, vTable, vParentFk, vParentFk); - SET @qrySql := vSql; - - PREPARE stmt FROM @qrySql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - - -- Select left from last child - IF @childs = 0 THEN - SET vSql = sql_printf('SELECT lft INTO @vLeft FROM %t.%t WHERE id = %v', vScheme, vTable, vParentFk); - SET @qrySql := vSql; - ELSE - SET vSql = sql_printf(' - SELECT c.rgt INTO @vLeft - FROM %t.%t p - JOIN %t.%t c ON c.lft BETWEEN p.lft AND p.rgt - WHERE p.id = %v - ORDER BY c.lft - DESC LIMIT 1', - vScheme, vTable, vScheme, vTable, vParentFk); - SET @qrySql := vSql; - END IF; - - PREPARE stmt FROM @qrySql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - - -- Update right - SET vSql = sql_printf('UPDATE %t.%t SET rgt = rgt + 2 WHERE rgt > %v ORDER BY rgt DESC', vScheme, vTable, @vLeft); - SET @qrySql := vSql; - - PREPARE stmt FROM @qrySql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - - SET vSql = sql_printf('UPDATE %t.%t SET lft = lft + 2 WHERE lft > %v ORDER BY lft DESC', vScheme, vTable, @vLeft); - SET @qrySql := vSql; - - PREPARE stmt FROM @qrySql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - - -- Escape character - SET vChild = REPLACE(vChild, "'", "\\'"); - - -- Add child - SET vSql = sql_printf('INSERT INTO %t.%t (name, lft, rgt) VALUES (%v, %v, %v)', vScheme, vTable, vChild, @vLeft + 1, @vLeft + 2); - SET @qrySql := vSql; - - PREPARE stmt FROM @qrySql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nestLeave` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nestLeave`(vScheme VARCHAR(45), vTable VARCHAR(45), vParentFk INT) -BEGIN - DECLARE vSql TEXT; - - DROP TEMPORARY TABLE IF EXISTS tmp.tree; - - SET vSql = sql_printf(' - CREATE TEMPORARY TABLE tmp.tree - SELECT - node.id, - node.name, - node.lft, - node.rgt, - node.depth, - node.sons - FROM - %t.%t AS node, - %t.%t AS parent - WHERE - node.lft BETWEEN parent.lft AND parent.rgt - AND node.depth = parent.depth + 1 - AND parent.id = %v - GROUP BY node.id - ORDER BY node.lft', - vScheme, vTable, vScheme, vTable, vParentFk); - SET @qrySql := vSql; - - PREPARE stmt FROM @qrySql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nestTree` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nestTree`( - vSourceSchema VARCHAR(45), - vSourceTable VARCHAR(45), - vDestinationSchema VARCHAR(45), - vDestinationTable VARCHAR(45)) -BEGIN - DECLARE vSql TEXT; - - - SET vSql = sql_printf('DROP TABLE IF EXISTS %t.%t', vDestinationSchema, vDestinationTable); - SET @qrySql := vSql; - - PREPARE stmt FROM @qrySql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - - SET vSql = sql_printf(' - CREATE TABLE %t.%t - SELECT - node.id, - CONCAT( REPEAT(" ", 5 * (COUNT(parent.id) - 1)), node.name) name, - node.lft, - node.rgt, - COUNT(parent.id) - 1 depth, - CAST((node.rgt - node.lft - 1) / 2 as DECIMAL) as sons - FROM - %t.%t AS node, - %t.%t AS parent - WHERE node.lft BETWEEN parent.lft AND parent.rgt - GROUP BY node.id - ORDER BY node.lft', - vDestinationSchema, vDestinationTable, vSourceSchema, vSourceTable, vSourceSchema, vSourceTable); - SET @qrySql := vSql; - - PREPARE stmt FROM @qrySql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `observationAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `observationAdd`(vOriginFk INT, vTableCode VARCHAR(45), vDescription TEXT) -BEGIN -/** - * Guarda las observaciones realizadas por el usuario - * - * @param vOriginFk Id del registro de origen - * @param vTypeCode Código que referencia a la tabla. - * @param descripcion Texto de la observacion - */ - DECLARE vTableName VARCHAR(45); - - SET vTableName = CONCAT(vTableCode,'Observation'); - - IF ISNULL(vTableName) THEN - CALL util.throw('CODE_NOT_FOUND'); - END IF; - - SET @qryLog := CONCAT( - 'INSERT INTO ', vTableName, ' (originFk, userFk, description)', - ' VALUES (', vOriginFk, ', ', account.userGetId(), ', "', vDescription, '")' - ); - - PREPARE stmt FROM @qryLog; - EXECUTE stmt; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `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 vAgenciaEmbalajes INT DEFAULT 628; - DECLARE vComponentCost INT DEFAULT 28; - DECLARE vGraceDate DATE; - - SET vGraceDays = IF(vIsAllInvoiceable,0,30); - SET vGraceDate = TIMESTAMPADD(DAY, - vGraceDays, vDate); - - /* Clientes especiales: - 3240 MADEFLOR - 992 JAVIER FELIU - */ - - IF vClient IN (992, 3240) THEN - - SET vGraceDays = 365; - - END IF; - - /* Fin clientes especiales */ - - - 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 package p ON p.id = tp.packagingFk - JOIN ticket t ON t.id = tp.ticketFk - WHERE t.shipped BETWEEN vDateStart AND vDate - AND t.clientFk = vClient - AND t.companyFk = vCompany; - - 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 GREATEST(COUNT(*),vIsAllInvoiceable) - INTO vIsInvoiceable - FROM tmp.packageToInvoicePositives; - - IF vIsInvoiceable THEN - - CALL vn.ticketCreate(vClient, vDate, vWarehouse, vCompany, 0, vAgenciaEmbalajes, 0, vDate, 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 DROP PROCEDURE IF EXISTS `printTrolleyLabel` */; -ALTER DATABASE `vn` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `printTrolleyLabel`(vTicket INT, vPrinter INT, vReport INT) -BEGIN -/** - * Inserta en la cola de impresion una nueva etiqueta de carro, para el sacador - * - * @param vTicket Numero del ticket - * @param vPrinter Numero de impresora - * @param vReport Numero del informe - **/ - DECLARE vlabelCount INT DEFAULT 0; - DECLARE PRIORITY INT DEFAULT 3; - DECLARE vWorker INT; - DECLARE vShipmentHour VARCHAR(10); - - SELECT getTicketTrolleyLabelCount(vTicket) INTO vLabelCount; - SELECT getUser() INTO vWorker; - SELECT CONCAT(getShipmentHour(vTicket),':00') INTO vShipmentHour; - - INSERT INTO printingQueue(printer - , priority - , report - , `text` - , worker - , text2 - , text3) - VALUES (vPrinter - , PRIORITY - , vReport - , vTicket - , vWorker - , vLabelCount - , vShipmentHour); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `refund` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `refund`(IN vMainTicket INT, OUT vNewTicket INT) -BEGIN - - DECLARE vCustomer MEDIUMINT; - DECLARE vNewDate DATE; - DECLARE vWarehouse TINYINT; - DECLARE vCompany MEDIUMINT; - DECLARE vAddress MEDIUMINT; - DECLARE vRefundAgencyMode INT DEFAULT 23; - - SELECT clientFk, TIMESTAMPADD(DAY, 1,shipped), warehouseFk, companyFk, addressFk - INTO vCustomer, vNewDate, vWarehouse, vCompany, vAddress - FROM ticket - WHERE id = vMainTicket; - - CALL ticketCreate(vCustomer, vNewDate, vWarehouse, vCompany, vAddress, vRefundAgencyMode,NULL,vNewDate,vNewTicket); - - INSERT INTO vn2008.Movimientos(Id_Ticket, Id_Article, Cantidad, Concepte, Preu, Descuento, PrecioFijado) - SELECT vNewTicket, Id_Article, - Cantidad, Concepte, Preu, Descuento, TRUE FROM vn2008.Movimientos WHERE Id_Ticket = vMainTicket; - SELECT vNewTicket; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `routeGateAsign` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `routeGateAsign`(vDevice VARCHAR(30), vRouteFk INT) -BEGIN - - UPDATE routeGate - SET displayText = NULL, - routeFk = NULL, - freeTickets = NULL, - expeditions = NULL, - scanned = NULL, - flag = NULL, - pallets = NULL, - lastScanned = NULL - WHERE routeFk = vRouteFk; - - UPDATE routeGate - SET routeFk = vRouteFk - WHERE deviceId = vDevice COLLATE utf8_general_ci; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `routeGateUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `routeGateUpdate`() -BEGIN - - UPDATE vn.routeGate rg - LEFT JOIN vn.routesControl rc ON rg.routeFk = rc.routeFk - LEFT JOIN vn.route r ON r.id = rg.routeFk - LEFT JOIN vn2008.Agencias a ON a.Id_Agencia = r.agencyModeFk - LEFT JOIN - ( - SELECT Id_Ruta, count(*) AS pedidosLibres - FROM vn2008.Tickets t - JOIN vn2008.Tickets_state ts ON t.Id_Ticket = ts.Id_Ticket - JOIN vncontrol.inter i ON i.inter_id = ts.inter_id - JOIN vn2008.state s ON i.state_id = s.id AND s.alert_level = 0 - WHERE t.Fecha BETWEEN CURDATE() AND util.dayend(CURDATE()) - AND Id_Ruta - GROUP BY Id_Ruta - ) t ON t.Id_Ruta = rg.routeFk - SET rg.scanned = rc.scanned, - rg.expeditions = rc.expeditions, - rg.flag = a.flag, - rg.freeTickets = t.pedidosLibres, - rg.pallets = rc.pallets, - rg.lastScanned = rc.lastScanned, - rg.displayText = IF(rg.routeFk is null, rg.displayText, rg.routeFk MOD 1000); - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `saleSplit` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `saleSplit`(IN vIdMovement BIGINT, IN vQuantity int) -BEGIN - DECLARE vId INT; - DECLARE vCreated DATE; - DECLARE vWarehouseId INT; - DECLARE vCompanyId INT; - DECLARE vAddressId INT; - DECLARE vAgencyMode INT; - DECLARE vNewTicketId BIGINT; - DECLARE vNewSale BIGINT; - DECLARE vLanded DATE; - DECLARE vStarted DATETIME; - DECLARE vEnded DATETIME; - DECLARE vCurrentTicket INT; - - - - SELECT clientFk - , shipped - , warehouseFk - , companyFk - , addressFk - , AgencyModeFk - , Landed - , t.id - - INTO vId - , vCreated - , vWarehouseId - , vCompanyId - , vAddressId - , vAgencyMode - , vLanded - , vCurrentTicket - FROM ticket t - JOIN sale m on t.id = m.ticketFk - WHERE m.id = vIdMovement; - - -- Busca un ticket existente que coincida con los parametros del nuevo pedido - - SET vStarted = TIMESTAMP(vCreated); - SET vEnded = TIMESTAMP(vCreated, '23:59:59'); - - SELECT id INTO vNewTicketId - FROM ticket t - JOIN ticketState ts on t.id = ts.ticketFk - WHERE vAddressId = t.addressFk - AND vWarehouseId = t.warehouseFk - AND vAgencyMode = t.AgencyModeFk - AND vLanded <=> t.landed - AND t.shipment BETWEEN vStarted AND vEnded -- uso BETWEEN para aprovechar el indice - AND t.refFk IS NULL - AND ts.alertLevel = 0 - AND t.clientFk <> 1118 - AND t.id <> vCurrentTicket - LIMIT 1; - - IF vNewTicketId IS NULL THEN - Call vn.ticketCreate( vId - , vCreated - , vWarehouseId - , vCompanyId - , vAddressId - , vAgencyMode - , NULL - , vLanded - , vNewTicketId); - - CALL vn2008.bionic_calc_ticket(vNewTicketId); - ELSE - UPDATE ticket SET landed = vLanded WHERE id = vNewTicketId; - END IF; - - INSERT INTO vncontrol.inter(Id_Ticket, state_id) - SELECT vNewTicketId, s.id - FROM state s - WHERE s.code = 'FIXING'; - - INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) - SELECT vNewTicketId, itemFk, Concept, vQuantity, price, discount - FROM sale - WHERE id = vIdMovement; - - SELECT LAST_INSERT_ID() INTO vNewSale; - - INSERT INTO saleComponent(saleFk, componentFk, `value`) - SELECT vNewSale, componentFk, `value` - FROM saleComponent - WHERE saleFk = vIdMovement; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `scanTreeCreate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `scanTreeCreate`() -BEGIN - - CALL vn.nestTree( 'vn2008', - 'scan', - 'vn2008', - 'scanTree'); - - ALTER TABLE vn2008.scanTree - ADD COLUMN lastScanned DATETIME NULL, - ADD COLUMN routeCount INT NULL, - ADD COLUMN minRoute INT, - ADD COLUMN maxRoute INT, - ADD COLUMN scanned INT; - - UPDATE vn2008.scanTree st - JOIN ( - SELECT sl.scan_id, - MAX(sl.odbc_date) lastScanned, - COUNT(DISTINCT t.routeFk) routeCount, - MIN(t.routeFk) mod 1000 as minRoute, - MAX(t.routeFk) mod 1000 as maxRoute, - COUNT(sl.scan_line_id) as scanned - FROM vn2008.scan_line sl - JOIN vn.expedition e ON e.id = sl.`code` - JOIN vn.ticket t ON t.id = e.ticketFk - WHERE t.routeFk - GROUP BY sl.scan_id - ) rs ON rs.scan_id = st.id - SET st.lastScanned = rs.lastScanned, - st.routeCount = rs.routeCount, - st.minRoute = rs.minRoute, - st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), - st.scanned = rs.scanned; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `solunionRiskRequest` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `solunionRiskRequest`() -BEGIN - - DROP TEMPORARY TABLE IF EXISTS tmp.client_list; - CREATE TEMPORARY TABLE tmp.client_list - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc - JOIN vn.creditInsurance ci ON cc.id = ci.creditClassification - WHERE dateEnd IS NULL - ORDER BY ci.creationDate DESC) t1 GROUP BY Id_Cliente; - - CALL vn2008.risk_vs_client_list(CURDATE()); - - SELECT - c.Id_Cliente, c.Cliente, c.Credito credito_vn, c.creditInsurance solunion, cast(r.risk as DECIMAL(10,0)) riesgo_vivo, - cast(c.creditInsurance - r.risk as decimal(10,0)) margen_vivo, - f.Consumo consumo_anual, c.Vencimiento, ci.grade - FROM - vn2008.Clientes c - JOIN tmp.risk r ON r.Id_Cliente = c.Id_Cliente - JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente - JOIN bi.facturacion_media_anual f ON c.Id_Cliente = f.Id_Cliente - GROUP BY Id_cliente; - - DROP TEMPORARY TABLE IF EXISTS tmp.risk; - DROP TEMPORARY TABLE IF EXISTS tmp.client_list; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `stockBuyed` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `stockBuyed`(vDate DATE) -BEGIN - DECLARE vVolume DECIMAL(10,2); - DECLARE vWarehouse INT DEFAULT 7; - - CALL stockTraslation(vDate); - - SELECT Volumen INTO vVolume FROM vn2008.Cubos WHERE Id_Cubo = 'cc' LIMIT 1; - - INSERT INTO stockBuyed(user, buyed, `date`) - SELECT tr.user_id, SUM(0.6 * ( amount / c.packing ) * vn2008.cm3(Id_Compra))/vVolume buyed, vDate - FROM tmp_item i - JOIN vn2008.Articles a ON a.Id_Article = i.item_id - JOIN vn2008.Tipos t ON a.tipo_id = t.tipo_id - JOIN vn2008.reinos r ON r.id = t.reino_id - JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = t.Id_Trabajador - JOIN vn2008.t_item_last_buy ilb ON ilb.item_id = Id_Article AND ilb.warehouse_id = vWarehouse - JOIN vn2008.Compres c ON c.Id_compra = ilb.buy_id - WHERE r.display <> 0 - GROUP BY tr.Id_Trabajador - ON DUPLICATE KEY UPDATE buyed = VALUES(buyed); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `stockBuyedByWorker` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `stockBuyedByWorker`(vDate DATE, vWorker INT) -BEGIN - - DECLARE vVolume DECIMAL(10,2); - DECLARE vWarehouse INT DEFAULT 7; - CALL stockTraslation(vDate); - - SELECT Volumen INTO vVolume FROM vn2008.Cubos WHERE Id_Cubo = 'cc' LIMIT 1; - - SELECT c.Id_Entrada, a.Id_Article, a.Article, i.amount Cantidad, (0.6 * ( i.amount / c.packing ) * vn2008.cm3(Id_Compra))/vVolume buyed - FROM tmp_item i - JOIN vn2008.Articles a ON a.Id_Article = i.item_id - JOIN vn2008.Tipos t ON a.tipo_id = t.tipo_id - JOIN vn2008.reinos r ON r.id = t.reino_id - JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = t.Id_Trabajador - JOIN vn2008.t_item_last_buy ilb ON ilb.item_id = a.Id_Article AND ilb.warehouse_id = vWarehouse - JOIN vn2008.Compres c ON c.Id_compra = ilb.buy_id - WHERE r.display <> 0 AND tr.user_id = vWorker; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stockBuyedByWorkerTest` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `stockBuyedByWorkerTest`(vDate DATE, vWorker INT) -BEGIN - - DECLARE vVolume DECIMAL(10,2); - DECLARE vWarehouse INT DEFAULT 7; - CALL stockTraslationTest(vDate); - - SELECT Volumen INTO vVolume FROM vn2008.Cubos WHERE Id_Cubo = 'cc' LIMIT 1; - - SELECT c.Id_Entrada, a.Id_Article, a.Article, i.amount Cantidad, (0.6 * ( i.amount / c.packing ) * vn2008.cm3(Id_Compra))/vVolume buyed - FROM tmp.item i - JOIN vn2008.Articles a ON a.Id_Article = i.item_id - JOIN vn2008.Tipos t ON a.tipo_id = t.tipo_id - JOIN vn2008.reinos r ON r.id = t.reino_id - JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = t.Id_Trabajador - JOIN vn2008.t_item_last_buy ilb ON ilb.item_id = a.Id_Article AND ilb.warehouse_id = vWarehouse - JOIN vn2008.Compres c ON c.Id_compra = ilb.buy_id - WHERE r.display <> 0 AND tr.user_id = vWorker; - DROP TEMPORARY TABLE IF EXISTS tmp_item; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stockTraslation` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `stockTraslation`(vDate DATE) -BEGIN - /** - * Calcula el stock del vWarehouse desde FechaInventario hasta v_date - sin tener en cuenta las salidas del mismo dia vDate - para ver el transporte a reservar - **/ - - DECLARE vWarehouse INT DEFAULT 7; - - DELETE FROM stockBuyed WHERE `date` = vDate; - - DROP TEMPORARY TABLE IF EXISTS tmp_item; - CREATE TEMPORARY TABLE tmp_item - (UNIQUE INDEX i USING HASH (item_id)) - ENGINE = MEMORY - SELECT item_id, SUM(amount) amount FROM vn2008.item_entry_in - WHERE dat = vDate and vDate >= CURDATE() - AND warehouse_id = vWarehouse - GROUP BY item_id HAVING amount != 0; - - CALL `cache`.stock_refresh (FALSE); - - INSERT INTO tmp_item (item_id,amount) - SELECT item_id,s.amount FROM `cache`.stock s - WHERE warehouse_id = vWarehouse - ON DUPLICATE KEY UPDATE - amount = tmp_item.amount + VALUES(amount); - - CALL vn2008.item_last_buy_(vWarehouse,vDate); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stockTraslationkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `stockTraslationkk`(vDate DATE) -BEGIN - /** - * Calcula el stock del vWarehouse desde FechaInventario hasta v_date - sin tener en cuenta las salidas del mismo dia vDate - para ver el transporte a reservar - **/ - - DECLARE vWarehouse INT DEFAULT 7; - - DELETE FROM stockBuyed WHERE `date` = vDate; - DROP TEMPORARY TABLE IF EXISTS tmp.item; - - CREATE TEMPORARY TABLE tmp.item ( - `item_id` INT, - `amount` DECIMAL(10, 2) DEFAULT 0.00, - PRIMARY KEY(item_id) - ) ENGINE = MEMORY; - - - IF vDate >= CURDATE() THEN - INSERT INTO tmp.item - SELECT item_id, SUM(amount) amount - FROM vn2008.item_entry_in - WHERE dat = vDate - AND warehouse_id = vWarehouse - GROUP BY item_id HAVING amount != 0; - END IF; - - CALL `cache`.stock_refresh (FALSE); - - INSERT INTO tmp.item (item_id,amount) - SELECT item_id,s.amount FROM `cache`.stock s - WHERE warehouse_id = vWarehouse - ON DUPLICATE KEY UPDATE - amount = tmp.item.amount + VALUES(amount); - - CALL vn2008.item_last_buy_(vWarehouse,vDate); - - select * FROM tmp.item; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stockTraslationTest` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `stockTraslationTest`(vDate DATE) -BEGIN - /** - * Calcula el stock del vWarehouse desde FechaInventario hasta v_date - sin tener en cuenta las salidas del mismo dia vDate - para ver el transporte a reservar - **/ - - DECLARE vWarehouse INT DEFAULT 7; - - DELETE FROM stockBuyed WHERE `date` = vDate; - DROP TEMPORARY TABLE IF EXISTS tmp.item; - - CREATE TEMPORARY TABLE tmp.item ( - `item_id` INT, - `amount` DECIMAL(10, 2) DEFAULT 0.00, - PRIMARY KEY(item_id) - ) ENGINE = MEMORY; - - - IF vDate >= CURDATE() THEN - INSERT INTO tmp.item - SELECT item_id, SUM(amount) amount - FROM vn2008.item_entry_in - WHERE dat = vDate - AND warehouse_id = vWarehouse - GROUP BY item_id HAVING amount != 0; - END IF; - - CALL `cache`.stock_refresh (FALSE); - - INSERT INTO tmp.item (item_id,amount) - SELECT item_id,s.amount FROM `cache`.stock s - WHERE warehouse_id = vWarehouse - ON DUPLICATE KEY UPDATE - amount = tmp.item.amount + VALUES(amount); - - CALL vn2008.item_last_buy_(vWarehouse,vDate); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `subordinateGetList` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `subordinateGetList`(vBossFk INT) -BEGIN - DECLARE vBossId INT; - DECLARE vDone BOOL; - DECLARE workerCur CURSOR FOR - SELECT workerFk - FROM tmp.subordinate - WHERE NOT isChecked; - - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR 1062 BEGIN - CALL util.throw('INFINITE_LOOP'); - END; - - DROP TEMPORARY TABLE IF EXISTS tmp.subordinate; - - CREATE TEMPORARY TABLE tmp.subordinate - (PRIMARY KEY (workerFk)) - ENGINE = MEMORY - SELECT vBossFk AS workerFk, 0 AS isChecked; - - WHILE (SELECT COUNT(*) FROM tmp.subordinate WHERE NOT isChecked) > 0 DO - OPEN workerCur; - workerLoop: LOOP - SET vDone = FALSE; - - FETCH workerCur INTO vBossId; - - IF vDone THEN - LEAVE workerLoop; - END IF; - - INSERT INTO tmp.subordinate - SELECT id, 0 - FROM worker - WHERE bossFk = vBossId; - - UPDATE tmp.subordinate - SET isChecked = 1 - WHERE workerFk = vBossId; - END LOOP; - - CLOSE workerCur; - END WHILE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `taxGetRates` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `taxGetRates`(vTaxDate DATE) - READS SQL DATA -BEGIN -/** - * Calcula una tabla con el IVA aplicable para la fecha data. - * - * @param vTaxDate - * @treturn tmp.taxGroup - * @treturn tmp.taxTax - */ - SET vTaxDate = IFNULL(vTaxDate, CURDATE()); - - DROP TEMPORARY TABLE IF EXISTS - tmp.taxClass, - tmp.taxType; - - -- Calcula el tipo de IVA para cada clase en cada país. - - CREATE TEMPORARY TABLE tmp.taxClass - (INDEX (countryFk, taxClassFk)) - ENGINE = MEMORY - SELECT * - FROM ( - SELECT t.countryFk, g.taxClassFk, c.type - FROM vn.taxClassCode g - JOIN vn.taxCode c ON c.id = g.taxCodeFk - JOIN vn.taxType t ON t.id = c.taxTypeFk - WHERE g.effectived <= vTaxDate - ORDER BY g.effectived DESC - ) t - GROUP BY countryFk, taxClassFk; - - -- Calcula el impuesto para cada tipo de IVA en cada país. - - CREATE TEMPORARY TABLE tmp.taxType - (INDEX (countryFk, type)) - ENGINE = MEMORY - SELECT * - FROM ( - SELECT t.countryFk, c.type, - c.rate / 100 rate, - c.equalizationTax / 100 equalizationTax - FROM vn.taxCode c - JOIN vn.taxType t ON t.id = c.taxTypeFk - WHERE c.dated <= vTaxDate AND t.isAccrued - ORDER BY c.dated DESC, c.equalizationTax DESC - ) t - GROUP BY countryFk, type; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketClosure` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosure`() -BEGIN -/** - * Realiza el cierre de todos los - * tickets de la table ticketClosure. - */ - - DECLARE vDone BOOL; - DECLARE vClientFk INT; - DECLARE vTicketFk INT; - DECLARE vIsTaxDataChecked BOOL; - DECLARE vCompanyFk INT; - DECLARE vShipped DATE; - DECLARE vPriority INT DEFAULT 1; - DECLARE vReportDeliveryNote INT DEFAULT 1; - DECLARE vNewInvoiceId INT; - DECLARE vIsUeeMember BOOL; - DECLARE vWithPackage BOOL; - - DECLARE cur CURSOR FOR - SELECT ticketFk FROM tmp.ticketClosure; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - RESIGNAL; - END; - - INSERT INTO dailyTaskLog(state) VALUES('ticketClosure: START'); - - OPEN cur; - - proc: LOOP - SET vDone = FALSE; - - FETCH cur INTO vTicketFk; - - IF vDone THEN - LEAVE proc; - END IF; - - -- ticketClosure start - SELECT - c.id, - c.isTaxDataChecked, - t.companyFk, - t.shipped, - co.isUeeMember, - w.isManaged - INTO vClientFk, - vIsTaxDataChecked, - vCompanyFk, - vShipped, - vIsUeeMember, - vWithPackage - FROM ticket t - JOIN `client` c ON c.id = t.clientFk - JOIN province p ON p.id = c.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.id = vTicketFk; - - -- Fusión de ticket - -- CALL mergeTicketUnattended(vTicketFk, TRUE); JGF 2017/12/04 - - INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) - (SELECT vTicketFk, p.id, COUNT(*) - FROM expedition e - JOIN package p ON p.itemFk = e.itemFk - WHERE e.ticketFk = vTicketFk AND p.isPackageReturnable - AND vWithPackage - GROUP BY p.itemFk); - - -- No retornables o no catalogados - INSERT INTO movement (item, ticket, concept, amount, price, priceFixed) - (SELECT e.itemFk, vTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.itemFk, vClientFk), 1 - FROM expedition e - JOIN item i ON i.id = e.itemFk - LEFT JOIN package p ON p.itemFk = i.id - WHERE e.ticketFk = vTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 - AND getSpecialPrice(e.itemFk, vClientFk) > 0 - GROUP BY e.itemFk); - - IF(vIsUeeMember = FALSE) THEN - - -- Facturacion rapida - CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', 20); - -- Facturar si está contabilizado - IF vIsTaxDataChecked THEN - - IF (SELECT clientTaxArea(vClientFk, vCompanyFk)) = 'NATIONAL' THEN - CALL invoiceMakeByClient( - vClientFk, - (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), - vShipped, - vCompanyFk, - vNewInvoiceId); - ELSE - CALL invoiceMakeByTicket(vTicketFk, (SELECT invoiceSerial(vClientFk, vCompanyFk, 'R')), vNewInvoiceId); - END IF; - - END IF; - ELSE - -- Albaran_print - CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), 20); - INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); - END IF; - - -- ticketClosure end - END LOOP; - - CLOSE cur; - - INSERT INTO dailyTaskLog(state) VALUES('ticketClosure: END'); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureAgencyList` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureAgencyList`(vWarehouseFk INT, vDateTo DATE) -BEGIN -/** - * Inserta los tickets de todos los almacenes en la tabla temporal - * para ser cerrados. - * - * @param vWarehouseFk Id del almacén - * @param vDate Fecha del cierre - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; - - CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY ( - SELECT - t.id AS ticketFk - FROM expedition e - INNER JOIN ticket t ON t.id = e.ticketFk - INNER JOIN tmp.ticketClosureAgencyList al ON al.agencyModeFk = t.agencyModeFk - LEFT JOIN ticketState ts ON ts.ticketFk = t.id - WHERE - ts.alertLevel = 2 - AND t.warehouseFk = vWarehouseFk - AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo - AND t.refFk IS NULL - GROUP BY e.ticketFk); - - DROP TEMPORARY TABLE tmp.ticketClosureAgencyList; - - CALL ticketClosure(); - - DROP TEMPORARY TABLE tmp.ticketClosure; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureAgencyListAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureAgencyListAdd`(vAgencyModeFk INT) -BEGIN -/** - * Prepara un listado de agencias sobre los que se realizará el cierre. - * Es necesario llamar al procedimiento por cada agencia. - * - * @param vAgencyModeFk Id almacén - */ - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.ticketClosureAgencyList ( - `agencyModeFk` INT, - PRIMARY KEY(agencyModeFk)) ENGINE = MEMORY; - - INSERT INTO tmp.ticketClosureAgencyList(agencyModeFk) VALUES(vAgencyModeFk); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketClosurekk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosurekk`() -BEGIN -/** - * Realiza el cierre de todos los - * tickets de la table ticketClosure. - */ - - DECLARE vDone BOOL; - DECLARE vClientFk INT; - DECLARE vCredit INT; - DECLARE vPayMethod INT; - DECLARE vTicketFk INT; - DECLARE vIsToBeMailed BOOL; - DECLARE vIsTaxDataChecked BOOL; - DECLARE vCompanyFk INT; - DECLARE vDeliveryMethod INT; - DECLARE vAgencyFk INT; - DECLARE vAgencyModeFk INT; - DECLARE vWarehouseFk INT; - DECLARE vShipped DATE; - DECLARE vPayMethodCard INT DEFAULT 5; - DECLARE vPriority INT DEFAULT 1; - DECLARE vReportDeliveryNote INT DEFAULT 1; - DECLARE vNewInvoiceId INT; - DECLARE vHasToInvoice BOOL; - - DECLARE cur CURSOR FOR - SELECT ticketFk FROM tmp.ticketClosure; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - RESIGNAL; - END; - - INSERT INTO dailyTaskLog(state) VALUES('ticketClosure: START'); - - OPEN cur; - - proc: LOOP - SET vDone = FALSE; - - FETCH cur INTO vTicketFk; - - IF vDone THEN - LEAVE proc; - END IF; - - -- ticketClosure start - SELECT - c.id, - c.credit, - c.paymentMethodFk, - c.isToBeMailed, - c.isTaxDataChecked, - t.companyFk, - IFNULL(aw.agencyType, a.deliveryMethod) AS deliveryMethod, - a.id AS agencyFk, - t.agencyModeFk, - t.warehouseFk, - t.shipped, - c.hasToInvoice - INTO vClientFk, - vCredit, - vPayMethod, - vIsToBeMailed, - vIsTaxDataChecked, - vCompanyFk, - vDeliveryMethod, - vAgencyFk, - vAgencyModeFk, - vWarehouseFk, - vShipped, - vHasToInvoice - FROM ticket t - INNER JOIN `client` c ON c.id = t.clientFk - LEFT JOIN agencyMode a ON a.id = t.agencyModeFk - LEFT JOIN agencyWarehouse aw ON a.id = aw.agencyFk AND t.warehouseFk = aw.warehouseFk - WHERE t.id = vTicketFk; - - -- Fusión de ticket - CALL mergeTicketUnattended(vTicketFk, TRUE); - - INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) - (SELECT vTicketFk, p.id, COUNT(*) - FROM expedition e - JOIN package p ON p.itemFk = e.itemFk - WHERE e.ticketFk = vTicketFk AND p.isPackageReturnable - GROUP BY p.itemFk); - - -- No retornables o no catalogados - INSERT INTO movement (item, ticket, concept, amount, price, priceFixed) - (SELECT e.itemFk, vTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.itemFk, vClientFk), 1 - FROM expedition e - JOIN item i ON i.id = e.itemFk - LEFT JOIN package p ON p.itemFk = i.id - WHERE e.ticketFk = vTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 - GROUP BY e.itemFk); - - -- Albaran_print - CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), 20); - INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); - - IF((vCredit <= 1 OR vPayMethod = vPayMethodCard) AND vHasToInvoice <> FALSE) THEN - - -- Facturacion rapida - CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', 20); - -- Facturar si está contabilizado - IF vIsTaxDataChecked THEN - - IF (SELECT clientTaxArea(vClientFk, vCompanyFk)) = 'NATIONAL' THEN - CALL invoiceMakeByClient( - vClientFk, - (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), - vShipped, - vCompanyFk, - vNewInvoiceId); - ELSE - CALL invoiceMakeByTicket(vTicketFk, (SELECT invoiceSerial(vClientFk, vCompanyFk, 'R')), vNewInvoiceId); - END IF; - - END IF; - ELSE - -- Albaran_print - CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), 20); - INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); - END IF; - - -- ticketClosure end - END LOOP; - - CLOSE cur; - - INSERT INTO dailyTaskLog(state) VALUES('ticketClosure: END'); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureMultiWarehouse` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureMultiWarehouse`(vDateTo DATE) -BEGIN -/** - * Inserta los tickets de todos los almacenes en la tabla temporal - * para ser cerrados. - * - * @param vDate Fecha del cierre - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; - - CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY ( - SELECT - t.id AS ticketFk - FROM expedition e - INNER JOIN ticket t ON t.id = e.ticketFk - INNER JOIN warehouse w ON w.id = t.warehouseFk AND hasComission - LEFT JOIN ticketState ts ON ts.ticketFk = t.id - WHERE - ts.alertLevel = 2 - AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo - AND t.refFk IS NULL - GROUP BY e.ticketFk); - - CALL ticketClosure(); - - DROP TEMPORARY TABLE tmp.ticketClosure; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureRoute` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureRoute`(vWarehouseFk INT, vRouteFk INT, vDateTo DATE) -BEGIN -/** - * Inserta los tickets de la ruta en la tabla temporal - * para ser cerrados. - * - * @param vWarehouseFk Almacén a cerrar - * @param vRouteFk Ruta a cerrar - * @param vDate Fecha del cierre - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; - - CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY ( - SELECT - t.id AS ticketFk - FROM expedition e - INNER JOIN ticket t ON t.id = e.ticketFk - LEFT JOIN ticketState ts ON ts.ticketFk = t.id - WHERE - ts.alertLevel = 2 - AND t.warehouseFk = vWarehouseFk - AND t.routeFk = vRouteFk - AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo - AND t.refFk IS NULL - GROUP BY e.ticketFk); - - CALL ticketClosure(); - - DROP TEMPORARY TABLE tmp.ticketClosure; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureTicket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureTicket`(vTicketFk INT) -BEGIN - -/** - * Inserta el ticket en la tabla temporal - * para ser cerrado. - * - * @param vTicketFk Id del ticket - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; - - CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY ( - SELECT - t.id AS ticketFk - FROM expedition e - INNER JOIN ticket t ON t.id = e.ticketFk - LEFT JOIN ticketState ts ON ts.ticketFk = t.id - WHERE - ts.alertLevel = 2 - AND t.id = vTicketFk - AND t.refFk IS NULL - GROUP BY e.ticketFk); - - CALL ticketClosure(); - - DROP TEMPORARY TABLE tmp.ticketClosure; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureWarehouse` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosureWarehouse`(vWarehouseFk INT, vDateTo DATE) -BEGIN -/** - * Inserta los tickets del almacen en la tabla temporal - * para ser cerrados. - * - * @param vWarehouseFk Almacén a cerrar - * @param vDate Fecha del cierre - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure; - - CREATE TEMPORARY TABLE ticketClosure ENGINE = MEMORY( - SELECT - t.id AS ticketFk - FROM expedition e - INNER JOIN ticket t ON t.id = e.ticketFk - LEFT JOIN ticketState ts ON ts.ticketFk = t.id - WHERE - ts.alertLevel = 2 - AND t.warehouseFk = vWarehouseFk - AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo - AND t.refFk IS NULL - GROUP BY e.ticketFk); - - CALL ticketClosure(); - - DROP TEMPORARY TABLE tmp.ticketClosure; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketCreate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreate`( - vClientId INT - ,vShipped DATE - ,vWarehouseId INT - ,vCompanyFk INT - ,vAddressFk INT - ,vAgencyType INT - ,vRouteFk INT - ,vlanded DATE - ,OUT vNewTicket INT) -BEGIN - DECLARE vClientOrnamentales INT DEFAULT 5270; - DECLARE vCompanyOrn INT DEFAULT 1381; - DECLARE vProvinceName VARCHAR(255); - - SELECT p.name INTO vProvinceName - FROM vn.client c - JOIN province p ON p.id = c.provinceFk - WHERE c.id = vClientId; - - IF vProvinceName IN ('SANTA CRUZ DE TENERIFE', 'LAS PALMAS DE GRAN CANARIA') - AND vClientId <> vClientOrnamentales - THEN - SET vCompanyFk = vCompanyOrn; - END IF; - - INSERT INTO vn2008.Tickets ( - Id_Cliente, - Fecha, - Id_Consigna, - Id_Agencia, - Alias, - warehouse_id, - Id_Ruta, - empresa_id, - landing - ) - SELECT - vClientId, - vShipped, - a.id, - IF(vAgencyType,vAgencyType,a.agencyModeFk), - a.nickname, - vWarehouseId, - IF(vRouteFk,vRouteFk,NULL), - vCompanyFk, - vlanded - FROM address a - JOIN agencyMode am ON am.id = a.agencyModeFk - WHERE IF(vAddressFk, a.id = vAddressFk, a.isDefaultAddress != FALSE) - AND a.clientFk = vClientId - LIMIT 1; - - SET vNewTicket = LAST_INSERT_ID(); - - INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) - SELECT vNewTicket,ao.observationTypeFk, ao.description - FROM addressObservation ao - JOIN address a ON a.id = ao.addressFk - WHERE a.clientFk = vClientId AND a.isDefaultAddress != FALSE; - - CALL logAdd(vNewTicket, 'insert', 'ticket', CONCAT('Ha creado el ticket', ' ', vNewTicket)); - - IF (SELECT isCreatedAsServed FROM vn.client WHERE id = vClientId ) <> FALSE - THEN - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vNewTicket, getWorker() - FROM state - WHERE `code` = 'DELIVERED'; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTax` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTax`() - READS SQL DATA -BEGIN -/** - * Calcula la base imponible, el IVA y el recargo de equivalencia para - * un conjunto de tickets. - * - * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular - * @return tmp.ticketTax Impuesto desglosado para cada ticket - * @return tmp.ticketAmount - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; - CREATE TEMPORARY TABLE tmp.addressCompany - (INDEX (addressFk, companyFk)) - ENGINE = MEMORY - SELECT DISTINCT t.addressFk, t.companyFk - FROM tmp.ticket tmpTicket - JOIN ticket t ON t.id = tmpTicket.ticketFk; - - CALL addressTaxArea (); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; - CREATE TEMPORARY TABLE tmp.ticketTax - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT tmpTicket.ticketFk, - bp.pgcFk, - SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) - ) AS taxableBase, - SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) - ) * pgc.rate / 100 AS tax, - tc.code - - FROM tmp.ticket tmpTicket - JOIN sale s ON s.ticketFk = tmpTicket.ticketFk - JOIN item i ON i.id = s.itemFk - JOIN ticket t ON t.id = tmpTicket.ticketFk - JOIN supplier su ON su.id = t.companyFk - JOIN tmp.addressTaxArea ata - ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk - JOIN itemTaxCountry itc - ON itc.itemFk = i.id AND itc.countryFk = su.countryFk - JOIN bookingPlanner bp - ON bp.countryFk = su.countryFk - AND bp.taxAreaFk = ata.areaFk - AND bp.taxClassFk = itc.taxClassFk - JOIN pgc ON pgc.code = bp.pgcFk - JOIN taxClass tc ON tc.id = bp.taxClassFk - GROUP BY tmpTicket.ticketFk, pgc.code - HAVING taxableBase != 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; - CREATE TEMPORARY TABLE tmp.ticketAmount - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT ticketFk, taxableBase, SUM(tax) tax - FROM tmp.ticketTax - GROUP BY ticketFk, code; - - DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; - DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTaxAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTaxAdd`(vTicketFk INT) -BEGIN -/** - * Añade un ticket a la tabla tmp.ticket para calcular - * el IVA y el recargo de equivalencia y devuelve el resultado. - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - ENGINE = MEMORY - SELECT vTicketFk ticketFk; - - CALL vn.ticketGetTax(); - - SELECT - tt.ticketFk, - CAST(tt.taxableBase AS DECIMAL(10, 2)) AS taxableBase, - CAST(tt.tax AS DECIMAL(10, 2)) AS tax, - pgc.*, - CAST(IF(pe.equFk IS NULL, taxableBase, 0) AS DECIMAL(10, 2)) AS Base, - pgc.rate / 100 as vatPercent - FROM tmp.ticketTax tt - JOIN vn.pgc ON pgc.code = tt.pgcFk - LEFT JOIN vn.pgcEqu pe ON pe.equFk = pgc.code; - - DROP TEMPORARY TABLE tmp.ticket; - DROP TEMPORARY TABLE tmp.ticketTax; - DROP TEMPORARY TABLE tmp.ticketAmount; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTaxkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTaxkk`(vBillingDate DATE) - READS SQL DATA -BEGIN -/** - * Calcula la base imponible, el IVA y el recargo de equivalencia para - * un conjunto de tickets. - * - * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular - * @param vBillingDate Fecha de facturación - * @treturn tmp.ticketTax Impuesto desglosado para cada ticket - */ - CALL vn.taxGetRates (vBillingDate); - - -- Calcula el IVA y el recargo desglosado para cada ticket. - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; - CREATE TEMPORARY TABLE tmp.ticketTax - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT t.ticketFk, t.type, t.taxBase, - CAST(IF(t.hasTax, t.taxBase * x.rate, 0) AS DECIMAL(10,2)) tax, - CAST(IF(t.hasEqualizationTax, t.taxBase * x.equalizationTax, 0) AS DECIMAL(10,2)) equalizationTax - FROM ( - SELECT i.ticketFk, g.countryFk, g.type - ,SUM(CAST(m.quantity * m.price * (100 - m.discount) / 100 AS DECIMAL(10,2))) AS taxBase - ,NOT(c.isVies AND p.countryFk <> c.countryFk) hasTax - ,c.isEqualizated != FALSE AS hasEqualizationTax - FROM tmp.ticket i - JOIN vn.ticket t ON t.id = i.ticketFk - JOIN vn.sale m ON m.ticketFk = t.id - JOIN vn.item a ON a.id = m.itemFk - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.supplier p ON p.id = t.companyFk - JOIN tmp.taxClass g - ON g.countryFk = p.countryFk AND g.taxClassFk = a.taxClassFk - GROUP BY i.ticketFk, g.type - ) t - JOIN tmp.taxType x - ON x.countryFk = t.countryFk AND x.type = t.type; - - DROP TEMPORARY TABLE - tmp.taxClass, - tmp.taxType; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTax_new` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTax_new`() - READS SQL DATA -BEGIN -/** - * Calcula la base imponible, el IVA y el recargo de equivalencia para - * un conjunto de tickets. - * - * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular - * @return tmp.ticketTax Impuesto desglosado para cada ticket - * @return tmp.ticketAmount - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; - CREATE TEMPORARY TABLE tmp.addressCompany - (INDEX (addressFk, companyFk)) - ENGINE = MEMORY - SELECT DISTINCT t.addressFk, t.companyFk - FROM tmp.ticket tmpTicket - JOIN ticket t ON t.id = tmpTicket.ticketFk; - - CALL addressTaxArea (); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; - CREATE TEMPORARY TABLE tmp.ticketTax - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT tmpTicket.ticketFk, - bp.pgcFk, - SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) - ) AS taxableBase, - SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) - ) * pgc.rate / 100 AS tax, - tc.code - - FROM tmp.ticket tmpTicket - JOIN sale s ON s.ticketFk = tmpTicket.ticketFk - JOIN item i ON i.id = s.itemFk - JOIN ticket t ON t.id = tmpTicket.ticketFk - JOIN supplier su ON su.id = t.companyFk - JOIN tmp.addressTaxArea ata - ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk - JOIN itemTaxCountry itc - ON itc.itemFk = i.id AND itc.countryFk = su.countryFk - JOIN bookingPlanner bp - ON bp.countryFk = su.countryFk - AND bp.taxAreaFk = ata.areaFk - AND bp.taxClassFk = itc.taxClassFk - JOIN pgc ON pgc.code = bp.pgcFk - JOIN taxClass tc ON tc.id = bp.taxClassFk - GROUP BY tmpTicket.ticketFk, pgc.code - HAVING taxableBase != 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; - CREATE TEMPORARY TABLE tmp.ticketAmount - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT ticketFk, taxableBase, SUM(tax) tax - FROM tmp.ticketTax - GROUP BY ticketFk, code; - - DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; - DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTotal` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTotal`() - READS SQL DATA -BEGIN -/** - * Calcula el total con IVA para un conjunto de tickets. - * - * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular - * @return tmp.ticketTotal Total para cada ticket - */ - CALL ticketGetTax (); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketTotal; - CREATE TEMPORARY TABLE tmp.ticketTotal - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT ticketFk, SUM(ta.taxableBase + ta.tax) AS total - FROM tmp.ticketAmount ta GROUP BY ticketFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; - DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTotalkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketGetTotalkk`() - READS SQL DATA -BEGIN -/** - * Calcula el total con IVA para un conjunto de tickets. - * - * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular - * @treturn tmp.ticketTotal Total para cada ticket - */ - CALL ticketGetTax (NULL); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketTotal; - CREATE TEMPORARY TABLE tmp.ticketTotal - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT ticketFk, SUM(taxBase + tax + equalizationTax) AS total - FROM tmp.ticketTax GROUP BY ticketFk; - - DROP TEMPORARY TABLE tmp.ticketTax; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByAddress` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketToInvoiceByAddress`( - vStarted DATE, - vEnded DATETIME, - vAddress INT, - vCompany INT - ) -BEGIN - - SET vEnded = util.dayEnd(vEnded); - - DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice; - - CREATE TEMPORARY TABLE vn.ticketToInvoice - SELECT id - FROM vn.ticket - WHERE addressFk = vAddress - AND companyFk = vCompany - AND shipped BETWEEN vStarted AND vEnded - AND refFk IS NULL; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByClient` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketToInvoiceByClient`( - vStarted DATE, - vEnded DATETIME, - vClient INT, - vCompany INT - ) -BEGIN - - SET vEnded = util.dayEnd(vEnded); - - DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice; - - CREATE TEMPORARY TABLE vn.ticketToInvoice - SELECT id - FROM vn.ticket - WHERE clientFk = vClient - AND companyFk = vCompany - AND shipped BETWEEN vStarted AND vEnded - AND refFk IS NULL; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByDate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketToInvoiceByDate`( - vStarted DATE, - vEnded DATETIME, - vClient INT, - vCompany INT - ) -BEGIN - - SET vEnded = util.dayEnd(vEnded); - - DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice; - - CREATE TEMPORARY TABLE vn.ticketToInvoice - SELECT id - FROM vn.ticket - WHERE clientFk = vClient - AND companyFk = vCompany - AND shipped BETWEEN vStarted AND vEnded - AND refFk IS NULL; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByRef` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketToInvoiceByRef`(IN vInvoiceRef VARCHAR(15)) -BEGIN - -/* Para tickets ya facturados, vuelve a repetir el proceso de facturación. -* -* @param vInvoiceRef Factura -*/ - - DECLARE vInvoice INT; - DECLARE vCountry INT; - DECLARE vTaxArea VARCHAR(15); - DECLARE vSpainCountryCode INT DEFAULT 1; - - SELECT id - INTO vInvoice - FROM vn.invoiceOut - WHERE ref = vInvoiceRef; - - SELECT s.countryFk - INTO vCountry - FROM vn.supplier s - JOIN vn.invoiceOut io ON io.companyFk = s.id - WHERE io.id = vInvoice; - - SELECT IF( - c.isEqualizated - AND c.countryFk = vSpainCountryCode - AND i.taxAreaFk = 'NATIONAL', - 'EQU', - i.taxAreaFk - ) - INTO vTaxArea - FROM vn.invoiceOutSerial i - JOIN vn.invoiceOut io ON io.serial = i.code - JOIN vn.client c ON c.id = io.clientFk - WHERE io.id = vInvoice; - - DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice; - - CREATE TEMPORARY TABLE vn.ticketToInvoice - SELECT id - FROM vn.ticket - WHERE refFk = vInvoiceRef; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketTrackingAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketTrackingAdd`(vTicketFk INT, vState VARCHAR(25) CHARSET UTF8, vWorkerFk INT) -BEGIN -/** - * Inserta un registro de cambios en un ticket. - * @param vTicketFk Id del ticket - * @param vState Código del estado - * @param vWorkerFk Id del trabajador - */ - INSERT INTO ticketTracking (stateFk, ticketFk, workerFk) - SELECT s.id, vTicketFk, vWorkerFk FROM state s WHERE s.code = vState; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `typeTagMake` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `typeTagMake`(vTypeFk INT) -BEGIN - - DELETE it.* - FROM itemTag it - JOIN item i ON i.id = it.itemFk - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, /*CONCAT(i.size,' cm')*/ i.size, 1 - FROM item i - JOIN tag t ON t.name = 'Nº flores' COLLATE utf8_general_ci - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, i.category, 3 - FROM item i - JOIN tag t ON t.name = 'Categoria' COLLATE utf8_general_ci - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, ink.name, 2 - FROM item i - JOIN tag t ON t.name = 'Color' COLLATE utf8_general_ci - JOIN ink ON ink.id = i.inkFk - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, p.name, 4 - FROM item i - JOIN tag t ON t.name = 'Productor' COLLATE utf8_general_ci - JOIN producer p ON p.id = i.producerFk - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, o.name, 5 - FROM item i - JOIN tag t ON t.name = 'Origen' COLLATE utf8_general_ci - JOIN origin o ON o.id = i.originFk - WHERE i.typeFk = vTypeFk; - /* - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, i.stems, 6 - FROM item i - JOIN tag t ON t.name = 'Tallos' COLLATE utf8_general_ci - WHERE i.typeFk = vTypeFk; - */ --- CALL itemTagArrangedUpdate(NULL); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `workerCreate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerCreate`( - vFirstname VARCHAR(50), - vSurnames VARCHAR(50), - vFi VARCHAR(9), - vFiDueDate DATETIME, - vWorkerCode CHAR(3), - vBossFk INT, - vUserFk INT -) -BEGIN -/** - * Create new worker - * - */ - DECLARE vWorkerFk INT; - - SELECT id INTO vWorkerFk FROM worker - WHERE fi = vFi; - - IF ISNULL(vWorkerFk) THEN - INSERT INTO worker (workerCode, firstName, name, fi, userFk, bossFk, fiDueDate) - VALUES (vWorkerCode, vFirstname, vSurnames, vFi, vUserFk, vBossFk, vFiDueDate); - - SET vWorkerFk = LAST_INSERT_ID(); - END IF; - - SELECT vWorkerFk; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `workerCreateExternal` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerCreateExternal`( - vFirstName VARCHAR(50), - vSurname1 VARCHAR(50), - vSurname2 VARCHAR(50), - vUser VARCHAR(20), - vPassword VARCHAR(50), - vWorkerCode VARCHAR(3), - vRole INT(2) - ) -BEGIN - - DECLARE vUserId INT; - DECLARE vWorkerPako INT DEFAULT 2; - DECLARE vSurnames VARCHAR(100); - - INSERT INTO account.user(name,password,role) - SELECT vUser,MD5(vPassword),vRole; - - SET vUserId = LAST_INSERT_ID(); - /* - INSERT INTO vn.worker(firstName,name,bossFk,workerCode,user_id) - SELECT vFirstName,CONCAT(vSurname1,' ',vSurname2),2,vWorkerCode,vUser; - */ - - IF vSurname2 IS NULL THEN - SET vSurnames = vSurname1; - ELSE - SET vSurnames = CONCAT(vSurname1, ' ', vSurname2); - END IF; - - INSERT INTO vn2008.Trabajadores(Nombre, Apellidos, boss, CodigoTrabajador, user_id) - SELECT vFirstName, vSurnames, vWorkerPako, vWorkerCode, vUserId; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `workerDisable` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `workerDisable`(vUserId int) -BEGIN - - DELETE FROM account.account - WHERE id = vUserId; - - UPDATE account.user - SET role = 2 - WHERE id = vUserId; - - UPDATE `client` - SET credit = 0 - WHERE id = vUserId; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `workingHours` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workingHours`(username varchar(255), logon boolean) -BEGIN - DECLARE userid int(11); - - SELECT vn.getUserId(username) INTO userid; - SELECT username, userid; - IF userid IS NOT NULL THEN - IF (logon) THEN - CALL vn.workingHoursTimeIn(userid); - ELSE - CALL vn.workingHoursTimeOut(userid); - END IF; - 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 */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `workingHoursTimeIn` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workingHoursTimeIn`(vUserId INT(11)) -BEGIN - INSERT INTO vn.workingHours (timeIn, userId) - VALUES (NOW(),vUserId); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `workingHoursTimeOut` */; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workingHoursTimeOut`(vUserId INT(11)) -BEGIN - UPDATE vn.workingHours - SET timeOut = NOW() - WHERE userId = vUserId - AND DATE(timeIn) = CURDATE(); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `zoneNestCountry` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneNestCountry`() -BEGIN - - DECLARE vDone BOOL; - DECLARE vParent INT DEFAULT 1; - DECLARE vGeoFk INT; - DECLARE vChildFk INT; - DECLARE vChildName VARCHAR(45); - - DECLARE countryCur CURSOR FOR - SELECT 1, c.id, c.`country` - FROM vn.country c - ORDER BY c.`country`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Reset geoFk from country table - UPDATE vn.country SET geoFk = 0; - - DELETE FROM `vn`.`zoneNest`; - - ALTER TABLE `vn`.`zoneNest` - AUTO_INCREMENT = 1 ; - - - -- > Country cursor start - OPEN countryCur; - - countryLoop: LOOP - SET vDone = FALSE; - - FETCH countryCur INTO vParent, vChildFk, vChildName; - - IF vDone THEN - LEAVE countryLoop; - END IF; - - CALL nestAdd('vn', 'zoneNest', vParent, vChildName); - - -- Update country geoFk - SET vGeoFk = LAST_INSERT_ID(); - UPDATE country SET geoFk = vGeoFk WHERE id = vChildFk; - END LOOP; - CLOSE countryCur; - -- < Country cursor end -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zoneNestPostcode` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneNestPostcode`() -BEGIN - - DECLARE vDone BOOL; - DECLARE vParent INT DEFAULT 1; - DECLARE vGeoFk INT; - DECLARE vChildFk INT; - DECLARE vChildName VARCHAR(45); - - DECLARE postcodeCur CURSOR FOR - SELECT t.geoFk, pc.`code`, pc.`code` - FROM vn.postCode pc - JOIN vn.town t ON t.id = pc.townFk - ORDER BY pc.`code`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Reset geoFk from postcode table - UPDATE vn.postCode SET geoFk = 0; - - -- > Postcode cursor start - OPEN postcodeCur; - - postcodeLoop: LOOP - SET vDone = FALSE; - - FETCH postcodeCur INTO vParent, vChildFk, vChildName; - - IF vDone THEN - LEAVE postcodeLoop; - END IF; - - CALL nestAdd('vn', 'zoneNest', vParent, vChildName); - - -- Update postcode geoFk - SET vGeoFk = LAST_INSERT_ID(); - UPDATE vn.postCode SET geoFk = vGeoFk WHERE `code` = vChildFk; - END LOOP; - CLOSE postcodeCur; - -- < Postcode cursor end -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zoneNestProvince` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneNestProvince`() -BEGIN - - DECLARE vDone BOOL; - DECLARE vParent INT DEFAULT 1; - DECLARE vGeoFk INT; - DECLARE vChildFk INT; - DECLARE vChildName VARCHAR(45); - - DECLARE provinceCur CURSOR FOR - SELECT c.geoFk, p.id, p.`name` - FROM province p - JOIN country c ON c.id = p.countryFk - ORDER BY p.`name`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Reset geoFk from province table - UPDATE vn.province SET geoFk = 0; - - -- > Province cursor start - OPEN provinceCur; - - provinceLoop: LOOP - SET vDone = FALSE; - - FETCH provinceCur INTO vParent, vChildFk, vChildName; - - IF vDone THEN - LEAVE provinceLoop; - END IF; - - CALL nestAdd('vn', 'zoneNest', vParent, vChildName); - - -- Update province geoFk - SET vGeoFk = LAST_INSERT_ID(); - UPDATE province SET geoFk = vGeoFk WHERE id = vChildFk; - END LOOP; - CLOSE provinceCur; - -- < Province cursor end -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zoneNestTown` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneNestTown`() -BEGIN - - DECLARE vDone BOOL; - DECLARE vParent INT DEFAULT 1; - DECLARE vGeoFk INT; - DECLARE vChildFk INT; - DECLARE vChildName VARCHAR(45); - - DECLARE townCur CURSOR FOR - SELECT p.geoFk, t.id, t.`name` - FROM vn.town t - JOIN vn.province p ON p.id = t.provinceFk - ORDER BY t.`name`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Reset geoFk from town table - UPDATE vn.town SET geoFk = 0; - - -- > Town cursor start - OPEN townCur; - - townLoop: LOOP - SET vDone = FALSE; - - FETCH townCur INTO vParent, vChildFk, vChildName; - - IF vDone THEN - LEAVE townLoop; - END IF; - - CALL nestAdd('vn', 'zoneNest', vParent, vChildName); - - -- Update town geoFk - SET vGeoFk = LAST_INSERT_ID(); - UPDATE town SET geoFk = vGeoFk WHERE id = vChildFk; - END LOOP; - CLOSE townCur; - -- < Town cursor end -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Current Database: `edi` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `edi` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `edi`; - --- --- Table structure for table `PriceDetails` --- - -DROP TABLE IF EXISTS `PriceDetails`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `PriceDetails` ( - `ID` int(11) NOT NULL, - `SuplyResponseID` int(11) NOT NULL, - `PriceType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `Location` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `Price` decimal(10,2) DEFAULT NULL, - `BasisQuantitiy` int(11) DEFAULT NULL, - `BasisQuantityType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `MinimumQuantity` int(11) DEFAULT NULL, - `MinimumQuantityType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `MaximumQuantity Integer` int(11) DEFAULT NULL, - `MaximumQuantityType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `LatestDeliveryDateTime` datetime DEFAULT NULL, - `EarliestDespatchDateTime` datetime DEFAULT NULL, - `FirstOrderDateTime` datetime DEFAULT NULL, - `LatestOrderDateTime` datetime DEFAULT NULL, - PRIMARY KEY (`ID`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `batch` --- - -DROP TABLE IF EXISTS `batch`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `batch` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `message_id` int(10) unsigned NOT NULL, - `type_id` smallint(5) unsigned NOT NULL, - `buy_edi_id` int(10) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `type_id` (`type_id`,`buy_edi_id`), - KEY `message_id` (`message_id`), - KEY `buy_edi_id` (`buy_edi_id`), - CONSTRAINT `batch_ibfk_1` FOREIGN KEY (`message_id`) REFERENCES `message` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `batch_ibfk_2` FOREIGN KEY (`buy_edi_id`) REFERENCES `vn2008`.`buy_edi` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=289696 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `batch_type` --- - -DROP TABLE IF EXISTS `batch_type`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `batch_type` ( - `id` mediumint(8) unsigned NOT NULL, - `description` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `bucket` --- - -DROP TABLE IF EXISTS `bucket`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `bucket` ( - `bucket_id` int(11) unsigned NOT NULL, - `bucket_type_id` mediumint(8) unsigned NOT NULL, - `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - `x_size` mediumint(8) unsigned NOT NULL, - `y_size` mediumint(8) unsigned NOT NULL, - `z_size` mediumint(8) unsigned NOT NULL, - `entry_date` date DEFAULT NULL, - `expiry_date` date DEFAULT NULL, - `change_date_time` datetime DEFAULT NULL, - PRIMARY KEY (`bucket_id`), - KEY `group_id` (`y_size`), - KEY `plant_id` (`x_size`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/VBN020101/CK090916.txt'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `bucket_type` --- - -DROP TABLE IF EXISTS `bucket_type`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `bucket_type` ( - `bucket_type_id` mediumint(8) unsigned NOT NULL, - `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - `entry_date` date DEFAULT NULL, - `expiry_date` date DEFAULT NULL, - `change_date_time` datetime DEFAULT NULL, - PRIMARY KEY (`bucket_type_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/VBN020101/FB090916.txt'; -/*!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` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `log_mail` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Mail where the log information is sent', - `presale_id` mediumint(8) unsigned DEFAULT NULL, - `default_kop` int(10) unsigned DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `presale_id` (`presale_id`), - CONSTRAINT `config_ibfk_1` FOREIGN KEY (`presale_id`) REFERENCES `batch_type` (`id`) ON DELETE SET NULL ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Configuration parameters'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `deliveryInformation` --- - -DROP TABLE IF EXISTS `deliveryInformation`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `deliveryInformation` ( - `ID` int(11) NOT NULL AUTO_INCREMENT, - `DeliveryType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `Location` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `DeliveryPrice` decimal(10,2) DEFAULT NULL, - `ChargeAmount` decimal(10,2) DEFAULT NULL, - `BasisQuantitiy` int(11) DEFAULT NULL, - `MinimumQuantity` int(11) DEFAULT NULL, - `MaximumQuantity Integer` int(11) DEFAULT NULL, - `LatestDeliveryDateTime` datetime DEFAULT NULL, - `EarliestDespatchDateTime` datetime DEFAULT NULL, - `FirstOrderDateTime` datetime DEFAULT NULL, - `LatestOrderDateTime` datetime DEFAULT NULL, - `supplyResponseID` int(11) DEFAULT NULL, - PRIMARY KEY (`ID`) -) ENGINE=InnoDB AUTO_INCREMENT=2046639 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `feature` --- - -DROP TABLE IF EXISTS `feature`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `feature` ( - `item_id` int(11) unsigned NOT NULL, - `feature_type_id` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `feature_value` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `entry_date` date NOT NULL, - `expiry_date` date NOT NULL, - `change_date_time` datetime NOT NULL, - PRIMARY KEY (`item_id`,`feature_type_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FF130916.txt'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `file_config` --- - -DROP TABLE IF EXISTS `file_config`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `file_config` ( - `file_name` varchar(2) COLLATE utf8_unicode_ci NOT NULL, - `to_table` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - `file` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `updated` date DEFAULT NULL, - PRIMARY KEY (`file_name`), - UNIQUE KEY `to_table` (`to_table`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ftp_config` --- - -DROP TABLE IF EXISTS `ftp_config`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ftp_config` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `host` varchar(255) CHARACTER SET utf8 NOT NULL, - `user` varchar(50) CHARACTER SET utf8 NOT NULL, - `password` varchar(50) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Configuration parameters'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `genus` --- - -DROP TABLE IF EXISTS `genus`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `genus` ( - `genus_id` mediumint(8) unsigned NOT NULL, - `latin_genus_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - `entry_date` date DEFAULT NULL, - `expiry_date` date DEFAULT NULL, - `change_date_time` datetime DEFAULT NULL, - PRIMARY KEY (`genus_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FG130916.txt'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `goodCharacteristic` --- - -DROP TABLE IF EXISTS `goodCharacteristic`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `goodCharacteristic` ( - `supplyResponse` varchar(26) COLLATE utf8_unicode_ci NOT NULL, - `type` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'edi.type', - `value` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'edi.value', - PRIMARY KEY (`supplyResponse`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `imap_config` --- - -DROP TABLE IF EXISTS `imap_config`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `imap_config` ( - `id` tinyint(3) unsigned NOT NULL, - `host` varchar(150) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'localhost', - `user` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `pass` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `clean_period` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'How long the old mails are preserved', - `success_folder` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, - `error_folder` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='IMAP configuration parameters'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `item` --- - -DROP TABLE IF EXISTS `item`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `item` ( - `id` int(11) unsigned NOT NULL, - `product_name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - `plant_id` mediumint(8) unsigned DEFAULT NULL, - `group_id` int(11) DEFAULT NULL, - `entry_date` date DEFAULT NULL, - `expiry_date` date DEFAULT NULL, - `change_date_time` datetime DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `group_id` (`group_id`), - KEY `plant_id` (`plant_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FP130916.txt'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `item_feature` --- - -DROP TABLE IF EXISTS `item_feature`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `item_feature` ( - `item_id` int(11) NOT NULL, - `presentation_order` tinyint(11) unsigned NOT NULL, - `feature` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `regulation_type` tinyint(3) unsigned NOT NULL, - `entry_date` date NOT NULL, - `expiry_date` date DEFAULT NULL, - `change_date_time` datetime NOT NULL, - PRIMARY KEY (`item_id`,`presentation_order`,`entry_date`,`change_date_time`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FY130916.txt'; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `item_feature_bi` BEFORE INSERT ON `item_feature` FOR EACH ROW -BEGIN - IF NEW.expiry_date = '0000-00-00' THEN - SET NEW.expiry_date = NULL; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `item_group` --- - -DROP TABLE IF EXISTS `item_group`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `item_group` ( - `group_code` int(11) unsigned NOT NULL, - `dutch_group_description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - `entry_date` date NOT NULL, - `expiry_date` date NOT NULL, - `change_date_time` datetime NOT NULL, - PRIMARY KEY (`group_code`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FO130916.txt'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `item_track` --- - -DROP TABLE IF EXISTS `item_track`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `item_track` ( - `item_id` int(10) unsigned NOT NULL, - `s1` tinyint(3) NOT NULL DEFAULT '0', - `s2` tinyint(3) NOT NULL DEFAULT '0', - `s3` tinyint(3) NOT NULL DEFAULT '0', - `s4` tinyint(3) NOT NULL DEFAULT '0', - `pac` tinyint(3) NOT NULL DEFAULT '0', - `cat` tinyint(3) NOT NULL DEFAULT '0', - `ori` tinyint(3) NOT NULL DEFAULT '0', - `pro` tinyint(3) NOT NULL DEFAULT '0', - `package` tinyint(3) NOT NULL DEFAULT '0', - `s5` tinyint(3) NOT NULL DEFAULT '0', - `s6` tinyint(3) NOT NULL DEFAULT '0', - `kop` tinyint(3) NOT NULL DEFAULT '0', - `sub` tinyint(3) NOT NULL DEFAULT '0', - PRIMARY KEY (`item_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `mail` --- - -DROP TABLE IF EXISTS `mail`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mail` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `mail` varchar(150) COLLATE utf8_unicode_ci NOT NULL, - `kop` int(10) unsigned DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `mail` (`mail`) -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='List of allowed mailers'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `message` --- - -DROP TABLE IF EXISTS `message`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `message` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `sender_id` int(10) unsigned DEFAULT NULL, - `mail_id` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - UNIQUE KEY `mail_id` (`mail_id`), - KEY `sender_id` (`sender_id`), - CONSTRAINT `message_ibfk_2` FOREIGN KEY (`sender_id`) REFERENCES `mail` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=310144 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `param` --- - -DROP TABLE IF EXISTS `param`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `param` ( - `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `code` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `name` varchar(5) COLLATE utf8_unicode_ci NOT NULL, - `subname` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `position` tinyint(3) unsigned NOT NULL DEFAULT '1', - `type` enum('INTEGER','DOUBLE','STRING','DATE','TIME') COLLATE utf8_unicode_ci NOT NULL, - `required` tinyint(3) unsigned NOT NULL DEFAULT '1', - PRIMARY KEY (`id`), - UNIQUE KEY `name` (`name`,`subname`) -) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Parameters to capture of every exchange'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `plant` --- - -DROP TABLE IF EXISTS `plant`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `plant` ( - `plant_id` mediumint(8) unsigned NOT NULL, - `genus_id` mediumint(8) unsigned NOT NULL, - `specie_id` mediumint(8) unsigned DEFAULT NULL, - `entry_date` date DEFAULT NULL, - `expiry_date` date DEFAULT NULL, - `change_date_time` datetime DEFAULT NULL, - PRIMARY KEY (`plant_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FT130916.txt'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `putOrder` --- - -DROP TABLE IF EXISTS `putOrder`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `putOrder` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `deliveryInformationID` int(11) DEFAULT NULL, - `supplyResponseID` int(11) DEFAULT NULL, - `orderTradelineItemID` int(11) DEFAULT NULL COMMENT 'ticketFk or EntryFk?', - `OrderTradeLineDateTime` datetime DEFAULT NULL, - `quantity` int(11) DEFAULT NULL, - `EndUserPartyID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `EndUserPartyGLN` tinyint(4) DEFAULT '0', - `OrderStatus` int(11) DEFAULT '0' COMMENT '1 pending\n2 confirmed\n3 canceled', - `isOrderProcessed` tinyint(4) DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `orderTradelineItemID_UNIQUE` (`orderTradelineItemID`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `specie` --- - -DROP TABLE IF EXISTS `specie`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `specie` ( - `specie_id` mediumint(8) unsigned NOT NULL, - `genus_id` mediumint(8) unsigned NOT NULL, - `latin_species_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - `entry_date` date DEFAULT NULL, - `expiry_date` date DEFAULT NULL, - `change_date_time` datetime DEFAULT NULL, - PRIMARY KEY (`specie_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FS130916.txt'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `supplier` --- - -DROP TABLE IF EXISTS `supplier`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `supplier` ( - `supplier_id` int(10) unsigned NOT NULL COMMENT 'FHRegistrationNr', - `glnAddressCode` varchar(13) CHARACTER SET utf8 DEFAULT NULL, - `company_name` varchar(70) COLLATE utf8_unicode_ci NOT NULL, - `entry_date` date NOT NULL, - `expiry_date` date NOT NULL, - `change_date_time` datetime NOT NULL, - PRIMARY KEY (`supplier_id`), - KEY `glnaddressCodeidx` (`glnAddressCode`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/FEC010104/CC090916.txt'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `supplyResponse` --- - -DROP TABLE IF EXISTS `supplyResponse`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `supplyResponse` ( - `ID` int(11) NOT NULL AUTO_INCREMENT, - `NumberBunchesPerCask` int(11) DEFAULT NULL, - `SupplierGLN` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `NewItem` tinyint(1) DEFAULT NULL, - `SendererID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `ItemSupplierID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `TransactionDate` datetime DEFAULT NULL, - `TransactionNumber` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `AuctionClockNumber` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `SupplierID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `ItemDatesupplyResponsecol` datetime DEFAULT NULL, - `Item_ArticleCode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `VBNOmschrijving` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `ExtraRemark` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `ArtCodeType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `VBNGroupCode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `VBNGroupDescription` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `TransactionTime` time DEFAULT NULL, - `CountryOfOrigin` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `NumberOfItemsPerCask` int(11) DEFAULT NULL, - `NumberOfLayersPerTrolley` int(11) DEFAULT NULL, - `NumberOfUnits` int(11) DEFAULT NULL, - `MinimumNumberToOrder` int(11) DEFAULT NULL, - `MinimumOrderUnitType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `Price` decimal(10,2) DEFAULT NULL, - `PotSize` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `Height` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `Length` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `Weight` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `Quality` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `NumberOfBuds` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `NumberOfBudsPerStem` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `ExaminiationCode1` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `ExaminiationCode2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `Diameter` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `PlantDiameter` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `Potshape` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `FlowerShape` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `FlowerColor` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `PotColor` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `PotMaterial` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `MaterialHeight` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `MaterialDiameter` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `OtherMaterial` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `OrderUnitType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `EmbalageCode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `PictureReference` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `AgentGLN` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `MaximumNumberToOrder` int(11) DEFAULT NULL, - `MaximumOrderType` tinyint(1) DEFAULT NULL COMMENT 'Unit: 1 = piece, 2 = bunch, 3 = box, 4 = layer, 5 = load carrier/trolley', - `IncrementalOrderableQuantity` int(11) DEFAULT NULL, - `IncrementalOrderableQuantityType` tinyint(1) DEFAULT NULL COMMENT 'Unit: 1 = piece, 2 = bunch, 3 = box, 4 = layer, 5 = load carrier/trolley', - `PackingPrice` decimal(10,2) DEFAULT NULL, - `PackingPriceType` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL, - `PackingPriceQuantity` int(11) DEFAULT NULL, - `PackingQuantityType` tinyint(1) DEFAULT NULL COMMENT 'Unit: 1 = piece, 2 = bunch, 3 = box, 4 = layer, 5 = load carrier/trolley', - `MarketPlaceID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`ID`), - UNIQUE KEY `ID_UNIQUE` (`ID`) -) ENGINE=InnoDB AUTO_INCREMENT=523827 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `type` --- - -DROP TABLE IF EXISTS `type`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `type` ( - `type_id` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `type_group_id` tinyint(3) unsigned NOT NULL, - `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - `entry_date` date NOT NULL, - `expiry_date` date NOT NULL, - `change_date_time` datetime NOT NULL, - PRIMARY KEY (`type_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FE130916.txt'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `value` --- - -DROP TABLE IF EXISTS `value`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `value` ( - `type_id` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `type_value` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `type_description` varchar(70) COLLATE utf8_unicode_ci NOT NULL, - `entry_date` date NOT NULL, - `expiry_date` date NOT NULL, - `change_date_time` datetime NOT NULL, - PRIMARY KEY (`type_id`,`type_value`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FV130916.txt'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'edi' --- - --- --- Dumping routines for database 'edi' --- -/*!50003 DROP PROCEDURE IF EXISTS `batchNew` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `batchNew`( - vMessage INT - ,vItem VARCHAR(255) - ,vType MEDIUMINT - ,vDeliveryNumber BIGINT - ,vDate DATE - ,vHour TIME - ,vRef INT - ,vAgj INT - ,vCat VARCHAR(2) - ,vPac INT - ,vSub MEDIUMINT - ,vKop INT - ,vPtd VARCHAR(6) - ,vPro MEDIUMINT - ,vOrigin VARCHAR(3) - ,vPtj MEDIUMINT - ,vQuantiy INT - ,vPrice DOUBLE - ,vClock SMALLINT - ,vS1 VARCHAR(3) - ,vS2 VARCHAR(3) - ,vS3 VARCHAR(3) - ,vS4 VARCHAR(4) - ,vS5 VARCHAR(3) - ,vS6 VARCHAR(3) - ,vK1 SMALLINT - ,vK2 SMALLINT - ,vP1 TINYINT - ,vP2 TINYINT - ,vAuction SMALLINT - ,vPackage INT -) -BEGIN -/** - * Añade un nuevo lote, genera su código de barras y - * inserta/actualiza el registro en la tabla #vn2008.buy_edi - */ - DECLARE vEdi INT; - DECLARE vRewriteKop INT DEFAULT NULL; - DECLARE vBarcode CHAR(15) DEFAULT NULL; - DECLARE vIsDuplicated BOOLEAN DEFAULT FALSE; - DECLARE vUpdateExistent BOOLEAN DEFAULT FALSE; - - DECLARE CONTINUE HANDLER FOR 1062 -- ER_DUP_KEY - SET vIsDuplicated = TRUE; - - -- Genera el código de barras - - IF vAgj != 0 AND vAgj IS NOT NULL - THEN - SET vBarcode = CONCAT( - LPAD(vAuction, 2, 0), - LPAD(IFNULL(vClock, 99), 2, 0), - LPAD(DAYOFYEAR(vDate), 3, 0), - IF(vClock IS NULL OR vClock = 99, - LPAD(vAgj, 7, 0), - CONCAT(LPAD(vAgj, 5, 0), '01') - ), - '0' - ); - END IF; - - -- Reescribe el parámetro kop - - IF vKop IS NULL - THEN - SELECT default_kop INTO vKop FROM config; - END IF; - - SELECT e.kop INTO vRewriteKop - FROM mail e - JOIN message m ON m.sender_id = e.id - WHERE m.id = vMessage; - - SET vKop = IFNULL(vRewriteKop, vKop); - - -- Inserta el nuevo EKT - - INSERT INTO vn2008.buy_edi SET - barcode = IFNULL(vBarcode, barcode) - ,delivery_number = vDeliveryNumber - ,entry_year = YEAR(vDate) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k01 = vK1 - ,k02 = vK2 - ,k03 = vP1 - ,k04 = vP2 - ,auction = vAuction - ,package = vPackage; - - - -- Si el EKT está duplicado y el que habia en la tabla era uno - -- provisional, lo actualiza con los nuevos valores. - - IF NOT vIsDuplicated - THEN - SET vEdi = LAST_INSERT_ID(); - CALL ediLoad (vEdi); - - ELSEIF vDeliveryNumber != 0 - AND vDeliveryNumber IS NOT NULL - THEN - SELECT id INTO vEdi - FROM vn2008.buy_edi - WHERE delivery_number = vDeliveryNumber; - - SELECT COUNT(*) = 0 INTO vUpdateExistent - FROM vn2008.buy_edi e - JOIN batch b ON b.buy_edi_id = e.id - JOIN config c - WHERE e.delivery_number = vDeliveryNumber - AND b.type_id != c.presale_id; - END IF; - - IF vUpdateExistent - THEN - UPDATE vn2008.buy_edi SET - barcode = IFNULL(vBarcode, barcode) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k01 = vK1 - ,k02 = vK2 - ,k03 = vP1 - ,k04 = vP2 - ,auction = vAuction - ,package = vPackage - WHERE id = vEdi; - END IF; - - -- Registra el lote - - INSERT INTO batch SET - message_id = vMessage - ,type_id = vType - ,buy_edi_id = vEdi; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ediLoad` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ediLoad`(vEdi INT) -BEGIN - DECLARE vRef INT; - DECLARE vBuy INT; - DECLARE vItem INT; - DECLARE vQty INT; - DECLARE vPackage INT; - DECLARE vIsLot BOOLEAN; - - -- Carga los datos necesarios del EKT - - SELECT ref, qty, package INTO vRef, vQty, vPackage - FROM vn2008.buy_edi e - LEFT JOIN item i ON e.ref = i.id - WHERE e.id = vEdi; - - -- Inserta el cubo si no existe - - IF vPackage = 800 - THEN - SET vPackage = 800 + vQty; - - INSERT IGNORE INTO vn2008.Cubos SET - Id_Cubo = vPackage, - x = 7200 / vQty, - y = 1; - ELSE - INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) - SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) - FROM bucket WHERE bucket_id = vPackage; - - IF ROW_COUNT() > 0 - THEN - INSERT INTO vn2008.mail SET - `subject` = 'Cubo añadido', - `text` = CONCAT('Se ha añadido el cubo: ', vPackage), - `to` = 'ekt@verdnatura.es'; - END IF; - END IF; - - -- Intenta obtener el artículo en base a los atributos holandeses - - INSERT IGNORE INTO item_track SET - item_id = vRef; - - SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem - FROM vn2008.buy_edi e - JOIN item_track t ON t.item_id = e.ref - LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref - LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id - JOIN vn2008.config cfg - WHERE e.id = vEdi - AND l.id != vEdi - AND c.Id_Article != cfg.generic_item - AND IF(t.s1, l.s1 = e.s1, TRUE) - AND IF(t.s2, l.s2 = e.s2, TRUE) - AND IF(t.s3, l.s3 = e.s3, TRUE) - AND IF(t.s4, l.s4 = e.s4, TRUE) - AND IF(t.s5, l.s5 = e.s5, TRUE) - AND IF(t.s6, l.s6 = e.s6, TRUE) - AND IF(t.kop, l.kop = e.kop, TRUE) - AND IF(t.pac, l.pac = e.pac, TRUE) - AND IF(t.cat, l.cat = e.cat, TRUE) - AND IF(t.ori, l.ori = e.ori, TRUE) - AND IF(t.pro, l.pro = e.pro, TRUE) - AND IF(t.sub, l.sub = e.sub, TRUE) - AND IF(t.package, l.package = e.package, TRUE) - AND c.Id_Article < 170000 - ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; - - -- Determina si el articulo se vende por lotes - - IF vItem - THEN - SELECT COUNT(*) > 0 INTO vIsLot - FROM vn2008.Articles a - LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - WHERE a.Id_Article = vItem - AND t.`transaction`; - - -- Si el articulo se vende por lotes se inserta un nuevo artículo - - IF vIsLot - THEN - INSERT INTO vn2008.Articles ( - Article - ,Medida - ,Categoria - ,Id_Origen - ,iva_group_id - ,Foto - ,Color - ,Codintrastat - ,tipo_id - ,Tallos - ) - SELECT - i.`name` - ,IFNULL(e.s1, e.pac) - ,e.cat - ,IFNULL(o.id, 17) - ,IFNULL(a.iva_group_id, 1) - ,a.Foto - ,a.Color - ,a.Codintrastat - ,IFNULL(a.tipo_id, 10) - ,IF(a.tipo_id = 15, 0, 1) - FROM vn2008.buy_edi e - LEFT JOIN item i ON i.id = e.ref - LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori - LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem - WHERE e.id = vEdi; - - SET vItem = LAST_INSERT_ID(); - END IF; - END IF; - - -- Inserta la compra asociada al EKT - - INSERT INTO vn2008.Compres - ( - Id_Entrada - ,buy_edi_id - ,Costefijo - ,Id_Article - ,grouping - ,caja - ,Packing - ,Cantidad - ,Productor - ,Etiquetas - ,Id_Cubo - ) - SELECT - cfg.edi_entry - ,vEdi - ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri - ,IFNULL(vItem, cfg.generic_item) - ,IFNULL(c.grouping, e.pac) - ,IFNULL(c.caja, TRUE) - ,@pac := e.pac / @t - ,@pac * e.qty - ,s.company_name - ,e.qty - ,IFNULL(c.Id_Cubo, e.package) - FROM vn2008.buy_edi e - LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy - LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article - LEFT JOIN supplier s ON e.pro = s.supplier_id - JOIN vn2008.config cfg - WHERE e.id = vEdi - 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 DROP PROCEDURE IF EXISTS `messageNew` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `messageNew`( - vMailId VARCHAR(100) - ,vSender VARCHAR(150) - ,OUT vMessageId INT -) -BEGIN -/** - * Registra un correo electronico. - * - * @param vMailId Message-ID del correo electrónico - * @param vSender Id del correo electrónio del remitente - */ - DECLARE vSenderId INT; - - SELECT id INTO vSenderId FROM mail - WHERE mail = vSender; - - INSERT IGNORE INTO message SET - sender_id = vSenderId - ,mail_id = vMailId; - - SET vMessageId = LAST_INSERT_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 */ ; - --- --- Current Database: `bs` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `bs`; - --- --- Temporary view structure for view `VentasPorCliente` --- - -DROP TABLE IF EXISTS `VentasPorCliente`; -/*!50001 DROP VIEW IF EXISTS `VentasPorCliente`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `VentasPorCliente` AS SELECT - 1 AS `Id_Cliente`, - 1 AS `VentaBasica`, - 1 AS `year`, - 1 AS `month`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `bancos_evolution` --- - -DROP TABLE IF EXISTS `bancos_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `bancos_evolution` ( - `Fecha` date NOT NULL, - `Id_Banco` int(11) NOT NULL, - `saldo` double NOT NULL DEFAULT '0', - `quilla` double NOT NULL DEFAULT '0', - `deuda` double NOT NULL DEFAULT '0', - `liquidez` double NOT NULL DEFAULT '0', - `disponibilidad ajena` double NOT NULL DEFAULT '0', - `saldo_aux` double NOT NULL DEFAULT '0' COMMENT 'Saldo auxiliar para el calculo de lo dispuesto en las polizas', - PRIMARY KEY (`Fecha`,`Id_Banco`), - KEY `fk_banco_evolution_idx` (`Id_Banco`), - CONSTRAINT `fk_banco_evolution` FOREIGN KEY (`Id_Banco`) REFERENCES `vn2008`.`Bancos` (`Id_Banco`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los saldos bancarios'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `carteras` --- - -DROP TABLE IF EXISTS `carteras`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `carteras` ( - `CodigoTrabajador` varchar(3) CHARACTER SET latin1 NOT NULL, - `Año` int(11) NOT NULL, - `Mes` int(11) NOT NULL, - `Peso` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`CodigoTrabajador`,`Año`,`Mes`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `compradores` --- - -DROP TABLE IF EXISTS `compradores`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `compradores` ( - `Id_Trabajador` int(11) NOT NULL, - `año` int(4) NOT NULL, - `semana` int(2) NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - `comision` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`,`año`,`semana`), - CONSTRAINT `comprador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `compradores_evolution` --- - -DROP TABLE IF EXISTS `compradores_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `compradores_evolution` ( - `Id_Trabajador` int(11) NOT NULL, - `fecha` date NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`,`fecha`), - CONSTRAINT `evo_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `experienceIberflora2016` --- - -DROP TABLE IF EXISTS `experienceIberflora2016`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `experienceIberflora2016` ( - `Id_Cliente` int(11) NOT NULL, - `isVisitor` tinyint(4) NOT NULL DEFAULT '0', - PRIMARY KEY (`Id_Cliente`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de clientes que participan en el estudio sobre la mejora del consumo tras la visita a las instalaciones de Silla'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `fondo_maniobra` --- - -DROP TABLE IF EXISTS `fondo_maniobra`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `fondo_maniobra` ( - `fecha` date NOT NULL, - `fondo` double DEFAULT NULL, - `clientes_facturas` double DEFAULT NULL, - `clientes_cobros` double DEFAULT NULL, - `proveedores_facturas` double DEFAULT NULL, - `proveedores_pagos` double DEFAULT NULL, - `fondo_medio` double DEFAULT NULL, - PRIMARY KEY (`fecha`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `m3` --- - -DROP TABLE IF EXISTS `m3`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `m3` ( - `fecha` date NOT NULL, - `provinceFk` smallint(5) unsigned DEFAULT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '0', - `m3` decimal(10,1) DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `manaCustomer` --- - -DROP TABLE IF EXISTS `manaCustomer`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `manaCustomer` ( - `Id_Cliente` int(11) NOT NULL, - `Mana` decimal(10,0) NOT NULL DEFAULT '0', - `dated` date NOT NULL, - PRIMARY KEY (`Id_Cliente`,`dated`), - KEY `manaCustomerIdx1` (`dated`), - CONSTRAINT `cliente_fk` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `mana_spellers` --- - -DROP TABLE IF EXISTS `mana_spellers`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mana_spellers` ( - `Id_Trabajador` int(11) NOT NULL, - `size` int(11) NOT NULL DEFAULT '300', - `used` int(11) NOT NULL DEFAULT '0', - `prices_modifier_rate` double NOT NULL DEFAULT '0', - `prices_modifier_activated` tinyint(1) NOT NULL DEFAULT '1', - PRIMARY KEY (`Id_Trabajador`), - KEY `fk_mana_spellers_Trabajadores_idx` (`Id_Trabajador`), - CONSTRAINT `fk_mana_spellers_Trabajadores` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`mana_spellers_AFTER_INSERT` AFTER INSERT ON `mana_spellers` FOR EACH ROW -BEGIN - - - REPLACE vn2008.Permisos(Id_Grupo, Id_Trabajador) - VALUES(6, NEW.Id_Trabajador); - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- --- Table structure for table `mana_spellers_excluded` --- - -DROP TABLE IF EXISTS `mana_spellers_excluded`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mana_spellers_excluded` ( - `Id_Trabajador` int(11) NOT NULL, - PRIMARY KEY (`Id_Trabajador`), - CONSTRAINT `mana_spellers_excluded_fk1` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Usuarios que tienen que estar excluidos del cálculo del maná'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `nightTask` --- - -DROP TABLE IF EXISTS `nightTask`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `nightTask` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `started` datetime DEFAULT NULL, - `finished` datetime DEFAULT NULL, - `order` int(11) DEFAULT NULL, - `schema` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `procedure` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeInsert` BEFORE INSERT ON `nightTask` FOR EACH ROW -BEGIN - - IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN - - CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); - - END IF; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeUpdate` BEFORE UPDATE ON `nightTask` FOR EACH ROW -BEGIN - - IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN - - CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); - - END IF; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Temporary view structure for view `v_ventas` --- - -DROP TABLE IF EXISTS `v_ventas`; -/*!50001 DROP VIEW IF EXISTS `v_ventas`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_ventas` AS SELECT - 1 AS `importe`, - 1 AS `recargo`, - 1 AS `year`, - 1 AS `month`, - 1 AS `week`, - 1 AS `day`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `vendedores` --- - -DROP TABLE IF EXISTS `vendedores`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `vendedores` ( - `Id_Trabajador` int(11) NOT NULL, - `año` int(4) NOT NULL, - `mes` int(2) NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - `comision` decimal(10,2) DEFAULT NULL, - `comisionArrendada` decimal(10,2) DEFAULT NULL COMMENT 'comision proveniente de clientes que han sido donados. Ver tabla Clientes_cedidos', - `comisionCedida` decimal(10,2) DEFAULT NULL COMMENT 'comision generada por los clientes que han sido donados. Ver tabla Clientes_cedidos', - PRIMARY KEY (`Id_Trabajador`,`año`,`mes`), - CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `vendedores_evolution` --- - -DROP TABLE IF EXISTS `vendedores_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `vendedores_evolution` ( - `Id_Trabajador` int(11) NOT NULL, - `fecha` date NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`,`fecha`), - CONSTRAINT `evo_vendedor_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ventas` --- - -DROP TABLE IF EXISTS `ventas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ventas` ( - `Id_Movimiento` int(11) NOT NULL, - `importe` decimal(10,3) NOT NULL DEFAULT '0.000', - `recargo` decimal(10,3) NOT NULL DEFAULT '0.000', - `fecha` date NOT NULL, - `tipo_id` smallint(5) unsigned NOT NULL, - `Id_Cliente` int(11) NOT NULL DEFAULT '1', - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - PRIMARY KEY (`Id_Movimiento`), - KEY `tip_to_tip_idx` (`tipo_id`), - KEY `clientes_bs_ventas_idx` (`Id_Cliente`), - KEY `empresa_bs_ventas_idx` (`empresa_id`), - KEY `fecha_bs` (`fecha`), - CONSTRAINT `clientes_bs_ventas` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `empresa_bs_ventas` FOREIGN KEY (`empresa_id`) REFERENCES `vn2008`.`empresa` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `mov_to_mov` FOREIGN KEY (`Id_Movimiento`) REFERENCES `vn2008`.`Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `tip_to_tip` FOREIGN KEY (`tipo_id`) REFERENCES `vn2008`.`Tipos` (`tipo_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ventasComponentes` --- - -DROP TABLE IF EXISTS `ventasComponentes`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ventasComponentes` ( - `Fecha` varchar(10) CHARACTER SET utf8 NOT NULL DEFAULT '', - `Id_Componente` int(11) NOT NULL, - `Importe` decimal(10,2) DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ventas_contables` --- - -DROP TABLE IF EXISTS `ventas_contables`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ventas_contables` ( - `year` int(4) NOT NULL, - `month` int(2) NOT NULL, - `venta` decimal(10,2) DEFAULT NULL, - `grupo` int(1) NOT NULL, - `reino_id` int(10) unsigned NOT NULL, - `tipo_id` smallint(5) unsigned NOT NULL, - `empresa_id` int(4) NOT NULL, - `gasto` varchar(10) CHARACTER SET latin1 NOT NULL, - PRIMARY KEY (`year`,`month`,`grupo`,`reino_id`,`tipo_id`,`empresa_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'bs' --- -/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `nightly_tasks` */; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8 */ ;; -/*!50003 SET character_set_results = utf8 */ ;; -/*!50003 SET collation_connection = utf8_general_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightly_tasks` ON SCHEDULE EVERY 1 DAY STARTS '2017-08-27 01:00:00' ON COMPLETION NOT PRESERVE ENABLE DO CALL bs.nightTaskLauncher() */ ;; -/*!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 `nightly_tasks2` */;; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8 */ ;; -/*!50003 SET character_set_results = utf8 */ ;; -/*!50003 SET collation_connection = utf8_general_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightly_tasks2` ON SCHEDULE EVERY 1 DAY STARTS '2017-03-24 02:00:00' ON COMPLETION NOT PRESERVE ENABLE DO call bs.nightTaskLauncher() */ ;; -/*!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 `nightly_tasks3` */;; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8 */ ;; -/*!50003 SET character_set_results = utf8 */ ;; -/*!50003 SET collation_connection = utf8_general_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightly_tasks3` ON SCHEDULE EVERY 1 DAY STARTS '2017-03-24 03:00:00' ON COMPLETION NOT PRESERVE ENABLE DO call bs.nightTaskLauncher() */ ;; -/*!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 `nightly_tasks4` */;; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8 */ ;; -/*!50003 SET character_set_results = utf8 */ ;; -/*!50003 SET collation_connection = utf8_general_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightly_tasks4` ON SCHEDULE EVERY 1 DAY STARTS '2017-03-24 04:00:00' ON COMPLETION NOT PRESERVE ENABLE DO call bs.nightTaskLauncher() */ ;; -/*!50003 SET time_zone = @saved_time_zone */ ;; -/*!50003 SET sql_mode = @saved_sql_mode */ ;; -/*!50003 SET character_set_client = @saved_cs_client */ ;; -/*!50003 SET character_set_results = @saved_cs_results */ ;; -/*!50003 SET collation_connection = @saved_col_connection */ ;; -DELIMITER ; -/*!50106 SET TIME_ZONE= @save_time_zone */ ; - --- --- Dumping routines for database 'bs' --- -/*!50003 DROP PROCEDURE IF EXISTS `analisisComponentes` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `analisisComponentes`() -BEGIN - -DECLARE vDateStart DATE DEFAULT '2016-01-01'; -DECLARE vDateEnd DATE DEFAULT '2016-11-30'; -DECLARE vDate DATE; - -SET vDate = vDateStart; - -DELETE FROM bs.ventasComponentes; - -WHILE vDate <= vDateEnd DO - - INSERT INTO bs.ventasComponentes - SELECT vDate as Fecha, mc.Id_Componente, cast(sum(m.Cantidad * mc.Valor) AS DECIMAL(10,2)) as Importe - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN bs.ventas v ON v.Id_Movimiento = mc.Id_Movimiento - WHERE v.fecha = vDate - AND empresa_id IN (442,567) - GROUP BY mc.Id_Componente; - - SET vDate = TIMESTAMPADD(DAY,1,vDate); - - IF DAY(vDate) MOD 28 = 0 THEN - - SELECT vDate; - - END IF; - -END WHILE; - - SELECT vDate; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bancos_evolution_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bancos_evolution_add`() -BEGIN -/* - -Inserta en la tabla bancos_evolution los saldos acumulados - -*/ - - -DECLARE vCurrentDate DATE; -DECLARE vStartingDate DATE DEFAULT '2015-01-01'; -DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 2, CURDATE()); - -SELECT max(Fecha) - INTO vStartingDate - FROM bs.bancos_evolution - WHERE Fecha > '2015-01-01'; - -DELETE FROM bs.bancos_evolution -WHERE Fecha > vStartingDate; - -SET vCurrentDate = vStartingDate; - - - - - WHILE vCurrentDate < vMaxDate DO - - IF day(vCurrentDate) mod 28 = 0 then - SELECT vCurrentDate; - end if; - - - REPLACE bs.bancos_evolution( Fecha - ,Id_Banco - ,saldo) - - SELECT vCurrentDate - , Id_Banco - , sum(saldo) - - FROM - ( - - SELECT Id_Banco - ,saldo_aux as saldo - FROM bs.bancos_evolution - - WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate) -- los saldos acumulados del dia anterior - - UNION ALL - - SELECT c.Id_Banco, IFNULL(sum(Entrada),0) - ifnull(sum(Salida),0) as saldo - FROM vn2008.Cajas c - JOIN vn2008.Bancos b using(Id_Banco) -- saldos de las cajas - WHERE cash IN (0,3) - AND Cajafecha = vCurrentDate - AND (Serie = 'MB' OR cash = 3) - GROUP BY Id_Banco - - UNION ALL - - SELECT id_banco, - importe -- pagos futuros - FROM vn2008.pago - WHERE fecha = vCurrentDate - AND fecha >= CURDATE() - AND NOT conciliado - - UNION ALL - - SELECT Id_Banco, Entregado -- cobros futuros - FROM vn2008.Recibos - WHERE Fechacobro = vCurrentDate - AND Fechacobro > CURDATE() - - UNION ALL - - SELECT sp.Id_Banco, Importe -- saldos de la tabla prevision - FROM vn2008.Saldos_Prevision sp - JOIN vn2008.Bancos b using(Id_Banco) - WHERE cash IN (0,3) - AND Fecha = vCurrentDate - - - - )sub - GROUP BY Id_Banco; - - -- Utilizamos el saldo_auxiliar para calcular lo dispuesto en las polizas - - UPDATE bs.bancos_evolution be - SET saldo_aux = saldo; - - -- Ahora actualizamos la quilla - UPDATE bs.bancos_evolution be - LEFT JOIN - ( - SELECT Id_Banco, - sum(importe) as quilla - FROM vn2008.Bancos_poliza - WHERE vCurrentDate between apertura AND IFNULL(cierre, vCurrentDate) - GROUP BY Id_Banco - ) sub using(Id_Banco) - SET be.quilla = sub.quilla - WHERE be.Fecha = vCurrentDate; - - - SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate); - - END WHILE; - - - -- Deuda - UPDATE bs.bancos_evolution be - JOIN vn2008.Bancos using(Id_Banco) - SET be.deuda = IF(cash = 3, be.saldo_aux, 0) - , be.saldo = IF(cash = 3, 0, be.saldo_aux) - WHERE Fecha >= vStartingDate; - - - -- Liquidez - update bs.bancos_evolution set liquidez = saldo - quilla + deuda WHERE Fecha >= vStartingDate; - - -- Disponibilidad - update bs.bancos_evolution set `disponibilidad ajena` = - quilla + deuda WHERE Fecha >= vStartingDate; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `campaignComparative` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `campaignComparative`(vDateFrom DATE, vDateTo DATE) -BEGIN - SELECT - workerName, - id, - name, - CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, - CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount - FROM ( - (SELECT - CONCAT(w.firstname, ' ', w.name) AS workerName, - c.id, - c.name, - SUM(v.importe) AS previousAmmount, - 0 currentAmmount - FROM bs.ventas v - INNER JOIN vn.`client` c ON v.Id_Cliente = c.id - INNER JOIN vn.worker w ON c.salesPersonFk = w.id - WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) - AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR) - GROUP BY w.id, v.Id_Cliente) - UNION ALL - (SELECT - CONCAT(w.firstname, ' ', w.name) AS workerName, - c.id, - c.name, - 0 AS previousAmmount, - SUM(s.quantity * s.price) AS currentAmmount - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.worker w ON c.salesPersonFk = w.id - WHERE t.shipped BETWEEN vDateFrom - AND vDateTo - GROUP BY w.id, c.id) - ) comparative - GROUP BY workerName, id - HAVING (previousAmmount <> 0 OR currentAmmount <> 0) - ORDER BY workerName, id; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `carteras_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `carteras_add`() -BEGIN - -DELETE FROM bs.carteras -WHERE Año >= YEAR(CURDATE()) - 1; - -INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) -SELECT year as Año, month as Mes, CodigoTrabajador, sum(importe) as Peso -FROM vn2008.time t -JOIN bs.ventas v on t.date = v.fecha -JOIN vn2008.Clientes c on c.Id_Cliente = v.Id_Cliente -JOIN vn2008.Trabajadores tr on tr.Id_Trabajador = c.Id_Trabajador -WHERE t.year >= YEAR(CURDATE()) - 1 -GROUP BY CodigoTrabajador, Año, Mes; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `comercialesCompleto` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `comercialesCompleto`(IN vWorker INT) -BEGIN -create TEMPORARY TABLE workerAndBelow ENGINE=MEMORY - -SELECT w.id - FROM vn.worker w - WHERE w.bossFk=vWorker OR w.id=vWorker; - - -SELECT - c.Id_Cliente id_cliente, - c.calidad, - c.Cliente cliente, - cr.recobro * 100 tarifa, - c.Telefono telefono, - c.movil, - c.POBLACION poblacion, - p.`name` provincia, - vn2008.red(f.futur) futur, - c.Credito credito, - pm.`name` forma_pago, - vn2008.red(c365 / 12) consumo_medio365, - vn2008.red(c365) consumo365, - vn2008.red(CmLy.peso) peso_mes_año_pasado, - vn2008.red(CmLy.peso * 1.19) objetivo, - tr.CodigoTrabajador, - vn2008.red(mes_actual.consumo) consumoMes, - vn2008.red(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0)) como_lo_llevo, - DATE(LastTicket) ultimo_ticket, - dead.muerto, - g.Greuge, - cr.recobro -FROM - vn2008.Clientes c - LEFT JOIN - (SELECT Id_Cliente, Greuge - FROM bi.Greuge_Evolution - WHERE Fecha = (SELECT MAX(Fecha) FROM bi.Greuge_Evolution) - ) g ON g.Id_Cliente = c.Id_Cliente - LEFT JOIN - vn2008.province p ON p.province_id = c.province_id - JOIN - vn2008.pay_met pm ON pm.id = c.pay_met_id - LEFT JOIN - vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - LEFT JOIN - bi.claims_ratio cr on cr.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT v.Id_Cliente, SUM(importe) c365 -- optimizat de 6s /5.3s/ 4.7s a 0.3/0.4/0.3 - FROM bs.ventas v - JOIN vn2008.Clientes c USING (Id_Cliente) - JOIN workerAndBelow w ON w.id = c.Id_Trabajador - WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, CURDATE()) AND CURDATE() - GROUP BY v.Id_Cliente) c365 ON c365.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - Id_Cliente, SUM(importe) consumo - FROM - bs.ventas v - INNER JOIN vn2008.Clientes c USING (Id_Cliente) - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - AND (v.fecha BETWEEN TIMESTAMPADD(DAY, - DAY(CURDATE()) + 1, CURDATE()) AND CURDATE() - 1) - GROUP BY Id_Cliente) mes_actual ON mes_actual.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - t.Id_Cliente, - SUM(m.preu * m.Cantidad * (1 - m.Descuento / 100)) futur - FROM - vn2008.Tickets t - JOIN vn2008.Clientes c ON c.Id_Cliente = t.Id_Cliente - JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - AND DATE(Fecha) BETWEEN CURDATE() AND LAST_DAY(CURDATE()) - GROUP BY Id_Cliente) f ON c.Id_Cliente = f.Id_Cliente - LEFT JOIN - (SELECT - MAX(t.Fecha) LastTicket, c.Id_Cliente - FROM - vn2008.Tickets t - JOIN vn2008.Clientes c ON c.Id_cliente = t.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY t.Id_Cliente) LastTicket ON LastTicket.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - SUM(importe) peso, c.Id_Cliente - FROM - bs.ventas v - JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - MONTH(fecha) = MONTH(CURDATE()) - AND YEAR(fecha) = YEAR(CURDATE()) - 1 - AND (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY c.Id_Cliente) CmLy ON CmLy.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - c.Id_Cliente, - IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, CURDATE()), '%Y- %m-01'), TRUE, FALSE) muerto - FROM - vn2008.Facturas f - JOIN vn2008.Clientes c ON c.Id_cliente = f.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente -WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker); -DROP TEMPORARY TABLE workerAndBelow; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `compradores_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compradores_add`(IN intYEAR INT, IN intWEEK_START INT, IN intWEEK_END INT) -BEGIN - -REPLACE bs.compradores - -SELECT tp.Id_Trabajador - , intYEAR as año - , tm.week as semana - , sum(importe) as importe - , 0 as comision - -FROM bs.ventas v -JOIN vn2008.time tm on tm.date = v.fecha -JOIN vn2008.Tipos tp using(tipo_id) -WHERE tm.year = intYEAR and tm.week between intWEEK_START and intWEEK_END -AND reino_id != 6 -GROUP BY tp.Id_Trabajador, tm.week; - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `compradores_evolution_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compradores_evolution_add`() -BEGIN -/* - -Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias - -*/ - -DECLARE datFEC DATE; - - -SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution; - - WHILE datFEC < CURDATE() DO - - SELECT datFEC; - - REPLACE bs.compradores_evolution( Id_Trabajador - , fecha - , importe) - - SELECT Id_Trabajador - , datFEC as fecha - , sum(importe) as importe - - FROM - ( - - SELECT Id_Trabajador - , importe - FROM bs.compradores_evolution - WHERE fecha = TIMESTAMPADD(DAY,-1,datFEC) -- las ventas acumuladas del dia anterior - - UNION ALL - - SELECT Id_Trabajador - , importe * IF(v.fecha < datFEC,-1,1) -- se restan las ventas del año anterior y se suman las del actual - FROM bs.ventas v - JOIN vn2008.Tipos tp using(tipo_id) - WHERE fecha IN (datFEC, TIMESTAMPADD(DAY,-365,datFEC)) - AND reino_id != 6 - - )sub - GROUP BY Id_Trabajador; - - - - - SET datFEC = TIMESTAMPADD(DAY,1,datFEC); - - END WHILE; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `fondo_evolution_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `fondo_evolution_add`() -BEGIN -/* - -Inserta en la tabla fondo_maniobra los saldos acumulados en los ultimos 365 dias - -*/ - -DECLARE datFEC DATE DEFAULT '2015-01-01'; - - -SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.fondo_maniobra; - - WHILE datFEC < CURDATE() DO - - -- esto solo sirve para no aburrirse mientras esperamos... - - IF day(datFEC) mod 28 = 0 then - SELECT datFEC; - end if; - - - REPLACE bs.fondo_maniobra(Fecha, clientes_facturas, clientes_cobros,proveedores_facturas,proveedores_pagos, fondo) - SELECT datFEC as Fecha, Facturas, Cobros,Recibidas,Pagos, Facturas + Cobros + Recibidas + Pagos - FROM - ( - SELECT Sum(Facturas.Importe) AS Facturas - FROM vn2008.Facturas - INNER JOIN vn2008.Clientes ON Facturas.Id_Cliente = Clientes.Id_cliente - WHERE Clientes.`real` - AND empresa_id <>1381 - AND Fecha between '2011-01-01' and datFEC) fac - JOIN - ( - SELECT - Sum(Entregado) AS Cobros - FROM vn2008.Recibos - INNER JOIN vn2008.Clientes ON Recibos.Id_Cliente = Clientes.Id_cliente - WHERE Clientes.`real` - AND empresa_id <> 1381 - AND Fechacobro Between '2011-01-01' and datFEC) cob - JOIN - ( - SELECT - Sum(cantidad) AS Recibidas - FROM vn2008.recibida - INNER JOIN vn2008.recibida_vencimiento ON recibida.id = recibida_vencimiento.recibida_id - WHERE empresa_id <> 1381 - AND recibida.fecha Between '2015-01-01' and datFEC) rec - JOIN - ( - SELECT Sum(importe) AS Pagos - FROM vn2008.pago - WHERE empresa_id <>1381 AND pago.fecha Between '2015-01-01' and datFEC) pag; - - - - UPDATE bs.fondo_maniobra - JOIN - (SELECT avg(fondo) as media - FROM bs.fondo_maniobra - WHERE fecha <= datFEC) sub - SET fondo_medio = media - WHERE fecha = datFEC; - - - SET datFEC = TIMESTAMPADD(DAY,1,datFEC); - - END WHILE; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `m3Add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `m3Add`() -BEGIN - - DECLARE datSTART DATE; - DECLARE datEND DATE; - - SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART - FROM bs.m3; - - SET datEND = TIMESTAMPADD(DAY,-1,CURDATE()); - - DELETE FROM bs.m3 - WHERE fecha >= datSTART; - - INSERT INTO bs.m3 - SELECT v.fecha, a.provinceFk, t.warehouseFk, cast(sum(s.quantity * r.cm3) / 1000000 as DECIMAL(10,1)) m3 - FROM vn.ticket t - JOIN vn.sale s ON s.ticketFk = t.id - JOIN bs.ventas v ON v.Id_Movimiento = s.id -- Filtra solo por ventas "buenas" - JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk - JOIN vn.address a ON a.id = t.addressFk - WHERE v.fecha BETWEEN datSTART AND datEND - GROUP BY t.warehouseFk, v.fecha, a.provinceFk; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `manaCustomerFill_kk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `manaCustomerFill_kk`() -BEGIN - - -/* Rellena la tabla caché bs.manaCustomer desde 0 -* -* Utilizar para reconstruirla en caso de que se corrompa. -* -*/ - -DECLARE vFromDated DATE; -DECLARE vToDated DATETIME DEFAULT '2015-12-31 23:59:59'; -DECLARE isDone BOOLEAN DEFAULT FALSE; - -DELETE FROM bs.manaCustomer; - -WHILE NOT isDone DO - - SELECT TIMESTAMPADD(DAY,1,vToDated), TIMESTAMPADD(MONTH, 1, vToDated) - INTO vFromDated, vToDated; - - IF vToDated >= CURDATE() THEN - - SET vToDated = TIMESTAMPADD(SECOND,-1,CURDATE()); - SET isDone = TRUE; - - END IF; - - INSERT INTO bs.manaCustomer(Id_Cliente, Mana) - SELECT Id_Cliente, newMana - FROM - (SELECT cs.Id_Cliente, - sum(Cantidad * Valor) as newMana - FROM vn2008.Tickets t - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Movimientos m using(Id_Ticket) - JOIN vn2008.Movimientos_componentes mc using(Id_Movimiento) - WHERE Id_Componente IN (39, 37) -- maná auto y maná - AND Fecha BETWEEN vFromDated AND vToDated - GROUP BY cs.Id_Cliente - ) t1 - ON DUPLICATE KEY UPDATE Mana = Mana + newMana; - - SELECT vFromDated, vToDated; - -END WHILE; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `manaCustomerUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `manaCustomerUpdate`() -BEGIN -DECLARE vToDated DATE; - DECLARE vFromDated DATE; - DECLARE vForDeleteDated DATE; - DECLARE vManaId INT DEFAULT 37; - DECLARE vManaAutoId INT DEFAULT 39; - DECLARE vManaBankId INT DEFAULT 66; - DECLARE vManaGreugeTypeId INT DEFAULT 3; - - SELECT IFNULL(max(dated), '2016-01-01') - INTO vFromDated - FROM bs.manaCustomer; - - WHILE timestampadd(week,1,vFromDated) < CURDATE() DO - - SELECT - timestampadd(week,1,vFromDated), - timestampadd(week,-4,vFromDated) - INTO - vToDated, - vForDeleteDated; - - DELETE FROM bs.manaCustomer - WHERE dated <= vForDeleteDated; - - - INSERT INTO bs.manaCustomer(Id_Cliente, Mana, dated) - - SELECT - Id_Cliente, - cast(sum(mana) as decimal(10,2)) as mana, - vToDated as dated - FROM - - ( - SELECT cs.Id_Cliente, Cantidad * Valor as mana - FROM vn2008.Tickets t - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket - JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento - WHERE Id_Componente IN (vManaAutoId, vManaId) - AND Fecha > vFromDated - AND Fecha <= vToDated - - - UNION ALL - - SELECT r.Id_Cliente, - Entregado - FROM vn2008.Recibos r - WHERE Id_Banco = vManaBankId - AND Fechacobro > vFromDated - AND Fechacobro <= vToDated - - UNION ALL - - SELECT g.Id_Cliente, g.Importe - FROM vn2008.Greuges g - WHERE Greuges_type_id = vManaGreugeTypeId - AND Fecha > vFromDated - AND Fecha <= vToDated - - UNION ALL - - SELECT Id_Cliente, mana - FROM bs.manaCustomer - WHERE dated = vFromDated - ) sub - - GROUP BY Id_Cliente - HAVING Id_Cliente; - - SET vFromDated = vToDated; - - END WHILE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `mana_price_modifier_update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `mana_price_modifier_update`() -BEGIN - -INSERT INTO vn2008.daily_task_log(consulta) -VALUES ('bs.mana_price_modifier_update'); - -UPDATE mana_spellers -JOIN - (SELECT Id_Trabajador, floor(sum(importe)/12) as pesoCarteraMensual - FROM bs.vendedores v - WHERE año * 100 + mes >= (year(curdate()) -1) * 100 + month(curdate()) - GROUP BY Id_Trabajador - ) ultimo_año_de_ventas using(Id_Trabajador) -SET prices_modifier_rate = GREATEST(-0.05,LEAST(0.05,round(- used/pesoCarteraMensual,3))) ; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nightly_tasks` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nightly_tasks`() -BEGIN - -DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN - INSERT INTO vn2008.mail SET `to` = 'informatica@verdnatura.es', subject = 'bs.nightly_tasks', `text` = CONCAT('ERROR ', @errno, ' (', @sqlstate, '): ', @text); - INSERT INTO vn2008.mail SET `to` = 'pako@verdnatura.es', subject = 'bs.nightly_tasks', `text` = CONCAT('ERROR ', @errno, ' (', @sqlstate, '): ', @text); -END; - - insert into vn2008.daily_task_log(consulta) VALUES('arranca el event bs.nightly_tasks'); - - call bancos_evolution_add; - - call fondo_evolution_add; - - call ventas_add(timestampadd(month,-1,curdate()),curdate()); - - call ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,CURDATE()))); - - call bs.vendedores_add(year(curdate()), month(curdate())); - - call bs.vendedores_add(year(timestampadd(month,-1,curdate())) - , month(timestampadd(month,-1,curdate())) - ); - - call carteras_add; - - call vn2008.mana_inventory_requery; - - call bs.mana_price_modifier_update; - - call bs.manaCustomerUpdate; - - call bs.m3Add; - - insert into vn2008.daily_task_log(consulta) VALUES('finalitza el event bs.nightly_tasks'); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nightTaskLauncher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nightTaskLauncher`() -BEGIN - - DECLARE done BOOL DEFAULT FALSE; - DECLARE vSchema VARCHAR(255); - DECLARE vProcedure VARCHAR(255); - DECLARE vId INT; - - DECLARE rs CURSOR FOR - SELECT id,`schema`, `procedure` - FROM bs.nightTask - WHERE IFNULL(finished,0) <= CURDATE() - ORDER BY `order`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - OPEN rs; - - FETCH rs INTO vId, vSchema, vProcedure; - - WHILE NOT done DO - - SELECT vId, vSchema, vProcedure; - - UPDATE bs.nightTask - SET started = now() - WHERE id = vId; - - CALL util.exec (sql_printf('CALL %s.%s',vSchema, vProcedure)); - - UPDATE bs.nightTask - SET finished = now() - WHERE id = vId; - - FETCH rs INTO vId, vSchema, vProcedure; - - END WHILE; - - CLOSE rs; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nocturnEvent_Tickets_Bionizar` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nocturnEvent_Tickets_Bionizar`() -BEGIN - -DECLARE MyDate DATE; -/* - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - - GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; - SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('jgallego@verdnatura.es', 'nocturnEvent_Tickets_Bionizar' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('pako@verdnatura.es', 'nocturnEvent_Tickets_Bionizar' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - -END; -*/ - - -SET MyDate = timestampadd(week,-1,curdate()); - - INSERT INTO vn2008.daily_task_log(consulta) VALUES('Comença la rebionització de tickets '); - -WHILE MyDate < CURDATE() DO - - CALL `vn2008`.`bionic_tickets_range_bionizar`(MyDate, MyDate); - - SET MyDate = timestampadd(DAY,1,MyDate); - - SELECT MyDate; - -END WHILE; - - INSERT INTO vn2008.daily_task_log(consulta) VALUES('finalitza la rebionització de tickets '); - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vendedores_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add`(IN intYEAR INT, IN intMONTH INT) -BEGIN - -REPLACE vendedores - -SELECT c.Id_Trabajador - , intYEAR - , intMONTH - , sum(importe) as importe - , sum(importe) * 0.029 as comision - , 0 as comisionCedida - , 0 as comisionArrendada - -FROM ventas v -JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente -JOIN vn2008.time on time.date = v.fecha -WHERE time.year = intYEAR and time.month = intMONTH -AND c.Id_Trabajador is not null -GROUP BY c.Id_Trabajador; - --- Ventas cedidas - -UPDATE vendedores -JOIN -( -SELECT cc.Id_Trabajador_old as Id_Trabajador - , sum(importe) * 0.029 * comision_old as cedido - -FROM ventas v -JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente -JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente -JOIN vn2008.time on time.date = v.fecha -WHERE time.year = intYEAR and time.month = intMONTH -AND c.Id_Trabajador is not null -GROUP BY cc.Id_Trabajador_old -) sub using(Id_Trabajador) -SET comisionCedida = cedido, comision = comision - cedido -WHERE año = intYEAR and mes = intMONTH; - --- Ventas arrendadas - -UPDATE vendedores -JOIN -( -SELECT cc.Id_Trabajador_new as Id_Trabajador - , sum(importe) * 0.029 * comision_new as arrendada - -FROM ventas v -JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente -JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente AND v.fecha between datSTART and datEND -JOIN vn2008.time on time.date = v.fecha -WHERE time.year = intYEAR and time.month = intMONTH -AND c.Id_Trabajador is not null -GROUP BY cc.Id_Trabajador_new -) sub using(Id_Trabajador) -SET comisionArrendada = arrendada, comision = comision - arrendada -WHERE año = intYEAR and mes = intMONTH; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vendedores_add_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add_launcher`() -BEGIN - - call bs.vendedores_add(year(curdate()), month(curdate())); - call bs.vendedores_add(year(timestampadd(month,-1,curdate())), month(timestampadd(month,-1,curdate()))); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vendedores_evolution_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_evolution_add`() -BEGIN -/* - -Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias - -*/ - -DECLARE datFEC DATE; - - -SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.vendedores_evolution; - - WHILE datFEC < CURDATE() DO - - SELECT datFEC; - - REPLACE bs.vendedores_evolution( Id_Trabajador - , fecha - , importe) - - SELECT Id_Trabajador - , datFEC as fecha - , sum(importe) as importe - - FROM - ( - - SELECT Id_Trabajador - , importe - FROM bs.vendedores_evolution - WHERE fecha = TIMESTAMPADD(DAY,-1,datFEC) -- las ventas acumuladas del dia anterior - - UNION ALL - - SELECT c.Id_Trabajador - , importe * IF(v.fecha < datFEC,-1,1) -- se restan las ventas del año anterior y se suman las del actual - FROM bs.ventas v - JOIN vn2008.Movimientos m using(Id_Movimiento) - JOIN vn2008.Tickets t using(Id_Ticket) - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Clientes c on cs.Id_Cliente = c.Id_Cliente - JOIN vn2008.Tipos using(tipo_id) - WHERE v.fecha IN (datFEC, TIMESTAMPADD(DAY,-365,datFEC)) - AND c.Id_Trabajador is not null - AND (Id_Article = 98 or Id_Article = 95 or reino_id != 6) - GROUP BY c.Id_Trabajador - - - )sub - GROUP BY Id_Trabajador; - - - - - SET datFEC = TIMESTAMPADD(DAY,1,datFEC); - - END WHILE; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add`(IN datSTART DATETIME, IN datEND DATETIME) -BEGIN - - -DECLARE vStartingPeriod INT; -DECLARE vStartingDate DATETIME; -DECLARE vEndingDate DATETIME; -DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - -SET datEND = vn2008.dayend(datEND); -SET vStartingDate = GREATEST('2015-10-01',datSTART); -SET vEndingDate = vn2008.dayend(vStartingDate); - -DELETE FROM ventas -WHERE fecha between vStartingDate and datEND; - -WHILE vEndingDate <= datEND DO - - --- Ventes bioniques - SELECT vStartingDate,vEndingDate, datEND; - - REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id) - SELECT Id_Movimiento - , sum( IF(base, Cantidad * Valor, 0) ) as importe - , sum( IF(base, 0, Cantidad * Valor) ) as recargo - , vStartingDate - , a.tipo_id - , cs.Id_Cliente - , t.empresa_id - FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc using(Id_Componente) - JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) - JOIN vn2008.Movimientos m using(Id_Movimiento) - JOIN vn2008.Articles a using(Id_Article) - JOIN vn2008.Tipos tp using(tipo_id) - JOIN vn2008.reinos r on r.id = tp.reino_id - JOIN vn2008.Tickets t using(Id_Ticket) - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - JOIN vn2008.empresa e on e.id = empresa_id - WHERE t.Fecha between vStartingDate and vEndingDate - AND datEND >= '2015-10-01' - AND ( - c.`Real` != 0 - OR c.Razonsocial = 'MIRIAM FERRER TORIBIO' - OR c.Razonsocial = 'VERDNATURA COMPLEMENTOS' - ) - AND Cantidad <> 0 - AND a.tipo_id != TIPO_PATRIMONIAL - AND c.Id_Trabajador IS NOT NULL - AND m.Descuento <> 100 - AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0) - GROUP BY mc.Id_Movimiento - HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; - -/* -UPDATE vn2008.Movimientos m -JOIN bs.ventas v ON v.Id_Movimiento = m.Id_Movimiento -SET m.Costfixat = IFNULL(round(v.importe/m.Cantidad,2),0) -WHERE v.fecha between vStartingDate and vEndingDate; -*/ - - SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); - SET vEndingDate = vn2008.dayend(vStartingDate); - - -END WHILE; - - - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_add_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add_launcher`() -BEGIN - - call bs.ventas_add(timestampadd(week,-1,curdate()),curdate()); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT) -BEGIN -/** - * Reemplaza las ventas contables. Es el origen de datos para el balance de Entradas - * - * @param vYear Año a reemplazar - * @param vMonth Mes a reemplazar - * - * - **/ -DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - -DELETE FROM bs.ventas_contables - WHERE year = vYear - AND month = vMonth; - -DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - -CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura - WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; - - -INSERT INTO bs.ventas_contables(year - , month - , venta - , grupo - , reino_id - , tipo_id - , empresa_id - , gasto) - - SELECT vYear - , vMonth - , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) - , if( - e.empresa_grupo = e2.empresa_grupo - ,1 - ,if(e2.empresa_grupo,2,0) - ) as grupo - , tp.reino_id - , a.tipo_id - , t.empresa_id - , 7000000000 - + if(e.empresa_grupo = e2.empresa_grupo - ,1 - ,if(e2.empresa_grupo,2,0) - ) * 1000000 - + IF(tp.Id_Trabajador = 24 , 7,tp.reino_id) * 10000 as Gasto - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles a on m.Id_Article = a.Id_Article - JOIN vn2008.empresa e on e.id = t.empresa_id - LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente - JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id - WHERE Cantidad <> 0 - AND Preu <> 0 - AND m.Descuento <> 100 - AND a.tipo_id != TIPO_PATRIMONIAL - GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto; - - -DROP TEMPORARY TABLE tmp.ticket_list; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add_launcher`() -BEGIN - - call bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,CURDATE()))); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_por_cliente` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_por_cliente`(IN vYear INT, IN vMonth INT) -BEGIN - - -DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - -CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura - WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; - - - - SELECT vYear Año - , vMonth Mes - , t.Id_Cliente - , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) Venta - , if( - e.empresa_grupo = e2.empresa_grupo - ,1 - ,if(e2.empresa_grupo,2,0) - ) as grupo - , t.empresa_id empresa - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles a on m.Id_Article = a.Id_Article - JOIN vn2008.empresa e on e.id = t.empresa_id - LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente - JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id - WHERE Cantidad <> 0 - AND Preu <> 0 - AND m.Descuento <> 100 - AND a.tipo_id != 188 - GROUP BY t.Id_Cliente, grupo,t.empresa_id; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `vivosMuertos` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vivosMuertos`() -BEGIN - -SET @datSTART = TIMESTAMPADD(YEAR,-2,CURDATE()); -SET @datEND = TIMESTAMPADD(DAY,-DAY(CURDATE()),CURDATE()); - -DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos; - -CREATE TEMPORARY TABLE tmp.VivosMuertos -SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto -FROM vn2008.Clientes c -JOIN (SELECT DISTINCT yearMonth FROM vn2008.time WHERE date BETWEEN @datSTART AND @datEND ) tm -LEFT JOIN - (SELECT DISTINCT tm.yearMonth, f.Id_Cliente , 1 as Compra - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - WHERE Fecha BETWEEN @datSTART AND @datEND) f ON f.yearMonth = tm.yearMonth AND f.Id_Cliente = c.Id_Cliente; - -UPDATE tmp.VivosMuertos vm -JOIN ( - SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente -SET Nuevo = 1; - -SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos; - -UPDATE tmp.VivosMuertos vm -JOIN ( - SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente -SET Muerto = 1 -WHERE yearMonth < @lastYearMonth; - - SELECT * FROM tmp.VivosMuertos; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Current Database: `bi` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bi` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `bi`; - --- --- Table structure for table `Equalizator` --- - -DROP TABLE IF EXISTS `Equalizator`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Equalizator` ( - `Vista` int(11) NOT NULL, - `Pedido` int(11) DEFAULT NULL, - `Impreso` int(11) DEFAULT NULL, - `Encajado` int(11) DEFAULT NULL, - PRIMARY KEY (`Vista`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Greuge_Evolution` --- - -DROP TABLE IF EXISTS `Greuge_Evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Greuge_Evolution` ( - `Id_Cliente` int(11) NOT NULL, - `Fecha` date NOT NULL, - `Greuge` decimal(10,2) NOT NULL DEFAULT '0.00', - `Ventas` decimal(10,2) NOT NULL DEFAULT '0.00', - `Fosil` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT 'greuge fósil, correspondiente a los clientes muertos', - `Recobro` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`Id_Cliente`,`Fecha`), - KEY `greuge_evolution_idx1` (`Fecha`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacenamos la evolucion del greuge de los ultimos dias '; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Greuge_comercial_recobro` --- - -DROP TABLE IF EXISTS `Greuge_comercial_recobro`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Greuge_comercial_recobro` ( - `Id_Trabajador` int(11) NOT NULL, - `recobro` decimal(10,2) NOT NULL DEFAULT '0.00', - `peso_cartera` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`Id_Trabajador`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Greuges_comercial_detail` --- - -DROP TABLE IF EXISTS `Greuges_comercial_detail`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Greuges_comercial_detail` ( - `Id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `Id_Trabajador` int(10) unsigned NOT NULL, - `Comentario` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `Importe` decimal(10,2) NOT NULL, - `Fecha` datetime DEFAULT NULL, - PRIMARY KEY (`Id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=FIXED; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Last_buy_id` --- - -DROP TABLE IF EXISTS `Last_buy_id`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Last_buy_id` ( - `Id_Article` int(11) NOT NULL DEFAULT '90', - `Id_Compra` int(11) NOT NULL DEFAULT '0', - `warehouse_id` smallint(6) unsigned NOT NULL, - PRIMARY KEY (`warehouse_id`,`Id_Article`), - UNIQUE KEY `Id_Compra_UNIQUE` (`Id_Compra`), - CONSTRAINT `Id_CompraFK` FOREIGN KEY (`Id_Compra`) REFERENCES `vn2008`.`Compres` (`Id_Compra`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Last_buy_idBackUp` --- - -DROP TABLE IF EXISTS `Last_buy_idBackUp`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Last_buy_idBackUp` ( - `Id_Article` int(11) NOT NULL DEFAULT '90', - `Id_Compra` int(11) NOT NULL DEFAULT '0', - `warehouse_id` smallint(6) unsigned NOT NULL, - PRIMARY KEY (`Id_Article`,`warehouse_id`), - UNIQUE KEY `Id_Compra_UNIQUE` (`Id_Compra`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Radar` --- - -DROP TABLE IF EXISTS `Radar`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Radar` ( - `Propio` int(1) NOT NULL DEFAULT '0', - `Credito` double NOT NULL DEFAULT '0', - `Riesgo` double(19,2) DEFAULT NULL, - `Greuge` double DEFAULT NULL, - `Id_Ticket` int(11) NOT NULL DEFAULT '0', - `wh` smallint(6) unsigned NOT NULL DEFAULT '1', - `Fecha` datetime NOT NULL, - `Alias` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Vista` int(11) DEFAULT '0', - `Tipo` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'RECOGIDA', - `Id_Trabajador` int(11) DEFAULT '20', - `Solucion` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL, - `Localizacion` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `Estado` varchar(15) CHARACTER SET utf8 DEFAULT NULL, - `Fecha_Simple` date DEFAULT NULL, - `Id_Comercial` int(11) DEFAULT '20', - `Risk` double NOT NULL DEFAULT '0', - `Rojo` bigint(21) DEFAULT '0', - `Naranja` bigint(21) DEFAULT '0', - `Amarillo` bigint(21) DEFAULT '0' -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `Ticket_Portes` --- - -DROP TABLE IF EXISTS `Ticket_Portes`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `Ticket_Portes` ( - `Id_Ticket` int(11) NOT NULL, - `rate` tinyint(4) NOT NULL COMMENT 'Tarifa', - `real_amount` double NOT NULL COMMENT 'Cantidad pactada con la agencia', - `payed_amount` double NOT NULL COMMENT 'Cantidad reflejada en el Ticket', - PRIMARY KEY (`Id_Ticket`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `VelocityKK` --- - -DROP TABLE IF EXISTS `VelocityKK`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `VelocityKK` ( - `tipo_id` int(11) NOT NULL, - `Fecha` datetime NOT NULL, - `Disponible` int(11) DEFAULT NULL, - `Visible` int(11) DEFAULT NULL, - `velocity_id` int(11) NOT NULL AUTO_INCREMENT, - PRIMARY KEY (`velocity_id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `XDiario_ALL` --- - -DROP TABLE IF EXISTS `XDiario_ALL`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `XDiario_ALL` ( - `empresa_id` int(5) NOT NULL, - `SUBCTA` varchar(11) COLLATE utf8_unicode_ci NOT NULL, - `Eurodebe` double DEFAULT NULL, - `Eurohaber` double DEFAULT NULL, - `Fecha` date DEFAULT NULL, - `FECHA_EX` date DEFAULT NULL, - KEY `Cuenta` (`SUBCTA`), - KEY `empresa` (`empresa_id`), - KEY `Fecha` (`Fecha`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `analisis_grafico_simple` --- - -DROP TABLE IF EXISTS `analisis_grafico_simple`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `analisis_grafico_simple` ( - `Año` smallint(5) unsigned NOT NULL, - `Semana` tinyint(3) unsigned NOT NULL, - `Importe` double DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `analisis_grafico_ventas` --- - -DROP TABLE IF EXISTS `analisis_grafico_ventas`; -/*!50001 DROP VIEW IF EXISTS `analisis_grafico_ventas`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `analisis_grafico_ventas` AS SELECT - 1 AS `Año`, - 1 AS `Semana`, - 1 AS `Importe`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `analisis_ventas` --- - -DROP TABLE IF EXISTS `analisis_ventas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `analisis_ventas` ( - `Familia` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `Reino` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `Comercial` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `Comprador` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `Provincia` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `almacen` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `Año` smallint(5) unsigned NOT NULL, - `Mes` tinyint(3) unsigned NOT NULL, - `Semana` tinyint(3) unsigned NOT NULL, - `Vista` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `Importe` double NOT NULL, - KEY `Año` (`Año`,`Semana`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `analisis_ventas_almacen_evolution` --- - -DROP TABLE IF EXISTS `analisis_ventas_almacen_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `analisis_ventas_almacen_evolution` ( - `Semana` int(11) NOT NULL, - `Almacen` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `Ventas` int(11) NOT NULL, - `Año` int(11) NOT NULL, - `Periodo` int(11) NOT NULL, - KEY `Almacen` (`Almacen`,`Periodo`), - KEY `Periodo` (`Periodo`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `analisis_ventas_comprador_evolution` --- - -DROP TABLE IF EXISTS `analisis_ventas_comprador_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `analisis_ventas_comprador_evolution` ( - `semana` int(11) NOT NULL, - `comprador` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `ventas` int(11) NOT NULL, - `año` int(11) NOT NULL, - `periodo` int(11) NOT NULL, - UNIQUE KEY `comprador` (`comprador`,`periodo`), - KEY `periodo` (`periodo`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `analisis_ventas_familia_evolution` --- - -DROP TABLE IF EXISTS `analisis_ventas_familia_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `analisis_ventas_familia_evolution` ( - `semana` int(11) NOT NULL, - `familia` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `ventas` int(11) NOT NULL, - `año` int(11) NOT NULL, - `periodo` int(11) NOT NULL, - KEY `familia` (`familia`,`periodo`), - KEY `periodo` (`periodo`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `analisis_ventas_provincia_evolution` --- - -DROP TABLE IF EXISTS `analisis_ventas_provincia_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `analisis_ventas_provincia_evolution` ( - `semana` int(11) NOT NULL, - `provincia` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `ventas` int(11) NOT NULL, - `año` int(11) NOT NULL, - `periodo` int(11) NOT NULL, - UNIQUE KEY `provincia` (`provincia`,`periodo`), - KEY `periodo` (`periodo`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `analisis_ventas_reino_evolution` --- - -DROP TABLE IF EXISTS `analisis_ventas_reino_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `analisis_ventas_reino_evolution` ( - `semana` int(11) NOT NULL, - `reino` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `ventas` int(11) NOT NULL, - `año` int(11) NOT NULL, - `periodo` int(11) NOT NULL, - UNIQUE KEY `reino` (`reino`,`periodo`), - KEY `periodo` (`periodo`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `analisis_ventas_simple` --- - -DROP TABLE IF EXISTS `analisis_ventas_simple`; -/*!50001 DROP VIEW IF EXISTS `analisis_ventas_simple`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `analisis_ventas_simple` AS SELECT - 1 AS `Año`, - 1 AS `Semana`, - 1 AS `Importe`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `analisis_ventas_vendedor_evolution` --- - -DROP TABLE IF EXISTS `analisis_ventas_vendedor_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `analisis_ventas_vendedor_evolution` ( - `semana` int(11) NOT NULL, - `vendedor` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `ventas` int(11) NOT NULL, - `año` int(11) NOT NULL, - `periodo` int(11) NOT NULL, - UNIQUE KEY `vendedor` (`vendedor`,`periodo`), - KEY `periodo` (`periodo`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `analisis_ventas_vista_evolution` --- - -DROP TABLE IF EXISTS `analisis_ventas_vista_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `analisis_ventas_vista_evolution` ( - `semana` int(11) NOT NULL, - `vista` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `ventas` int(11) NOT NULL, - `año` int(11) NOT NULL, - `periodo` int(11) NOT NULL, - UNIQUE KEY `vista` (`vista`,`periodo`), - KEY `periodo` (`periodo`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `calidad_detalle` --- - -DROP TABLE IF EXISTS `calidad_detalle`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `calidad_detalle` ( - `Id_Cliente` int(11) NOT NULL, - `calidad_parametros_id` int(2) NOT NULL, - `valor` int(3) DEFAULT NULL, - PRIMARY KEY (`Id_Cliente`,`calidad_parametros_id`), - KEY `calidad_parametros_detalle_idx` (`calidad_parametros_id`), - CONSTRAINT `calidad_parametros_detalle` FOREIGN KEY (`calidad_parametros_id`) REFERENCES `calidad_parametros` (`calidad_parametros_id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `calidad_parametros` --- - -DROP TABLE IF EXISTS `calidad_parametros`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `calidad_parametros` ( - `calidad_parametros_id` int(2) NOT NULL, - `descripcion` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`calidad_parametros_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `claims_ratio` --- - -DROP TABLE IF EXISTS `claims_ratio`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `claims_ratio` ( - `Id_Cliente` int(11) NOT NULL DEFAULT '0', - `Consumo` decimal(10,2) DEFAULT NULL, - `Reclamaciones` decimal(10,2) DEFAULT NULL, - `Ratio` decimal(5,2) DEFAULT NULL, - `recobro` decimal(5,2) DEFAULT NULL, - `inflacion` decimal(5,2) NOT NULL DEFAULT '1.00', - PRIMARY KEY (`Id_Cliente`), - CONSTRAINT `claims_ratio_ibfk_1` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `comparativa_clientes` --- - -DROP TABLE IF EXISTS `comparativa_clientes`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `comparativa_clientes` ( - `Fecha` date NOT NULL DEFAULT '0000-00-00', - `Id_Cliente` int(11) NOT NULL DEFAULT '0', - `Propietario` int(11) DEFAULT NULL, - `titular` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `suplente` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `trabajador` int(11) DEFAULT NULL, - `actual` double DEFAULT NULL, - `pasado` double DEFAULT NULL, - `concepto` varchar(10) CHARACTER SET utf8 NOT NULL DEFAULT '', - KEY `cc_data_indez` (`Fecha`), - KEY `cc_Id_Cliente_index` (`Id_Cliente`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `customerDebtInventory` --- - -DROP TABLE IF EXISTS `customerDebtInventory`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `customerDebtInventory` ( - `Id_Cliente` int(11) NOT NULL, - `Debt` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT 'CREATE TABLE bi.customerDebtInventory\n\nSELECT Id_Cliente, sum(Euros) as Debt\n\nFROM \n(\nSELECT Id_Cliente, Entregado as Euros\n\nFROM Recibos \n\nWHERE Fechacobro < ''2017-01-01\n''\nUNION ALL\n\nSELECT Id_Cliente, - Importe \nFROM Facturas\nWHERE Fecha < ''2017-01-01''\n) sub \nGROUP BY Id_Cliente', - PRIMARY KEY (`Id_Cliente`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `customerRiskOverdue` --- - -DROP TABLE IF EXISTS `customerRiskOverdue`; -/*!50001 DROP VIEW IF EXISTS `customerRiskOverdue`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `customerRiskOverdue` AS SELECT - 1 AS `customer_id`, - 1 AS `amount`, - 1 AS `company_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `customer_risk` --- - -DROP TABLE IF EXISTS `customer_risk`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `customer_risk` ( - `customer_id` int(11) NOT NULL DEFAULT '0', - `company_id` smallint(6) unsigned NOT NULL DEFAULT '0', - `amount` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`customer_id`,`company_id`), - KEY `company_id` (`company_id`), - CONSTRAINT `customer_risk_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `customer_risk_ibfk_2` FOREIGN KEY (`company_id`) REFERENCES `vn2008`.`empresa` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Saldo de apertura < 2015-01-01'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `dailyTaskLog` --- - -DROP TABLE IF EXISTS `dailyTaskLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `dailyTaskLog` ( - `state` varchar(250) COLLATE utf8_unicode_ci NOT NULL, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='No he encontrado el lugar en el que vicente almacena la hora en que se ejecutan las daily tasks, asi que he hecho esta tabla, a eliminar cuando se considere oportuno'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `defaulters` --- - -DROP TABLE IF EXISTS `defaulters`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `defaulters` ( - `client` int(11) NOT NULL, - `date` date NOT NULL, - `amount` double NOT NULL DEFAULT '0', - `defaulterSince` date DEFAULT NULL, - `hasChanged` tinyint(1) DEFAULT NULL, - PRIMARY KEY (`client`,`date`), - KEY `client` (`client`), - KEY `date` (`date`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `defaulting` --- - -DROP TABLE IF EXISTS `defaulting`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `defaulting` ( - `date` date NOT NULL, - `amount` double NOT NULL, - PRIMARY KEY (`date`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `f_tvc` --- - -DROP TABLE IF EXISTS `f_tvc`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `f_tvc` ( - `Id_Ticket` int(11) NOT NULL, - PRIMARY KEY (`Id_Ticket`), - CONSTRAINT `id_ticket_to_comisionantes` FOREIGN KEY (`Id_Ticket`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacenamos la lista de tickets para agilizar la consulta. Corresponde a los clientes REAL y en los almacenes COMISIONANTES'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `facturacion_media_anual` --- - -DROP TABLE IF EXISTS `facturacion_media_anual`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `facturacion_media_anual` ( - `Id_Cliente` int(11) NOT NULL, - `Consumo` double(17,0) DEFAULT NULL, - PRIMARY KEY (`Id_Cliente`), - CONSTRAINT `fmaId_Cliente` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `last_Id_Cubo` --- - -DROP TABLE IF EXISTS `last_Id_Cubo`; -/*!50001 DROP VIEW IF EXISTS `last_Id_Cubo`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `last_Id_Cubo` AS SELECT - 1 AS `Id_Compra`, - 1 AS `Id_Article`, - 1 AS `warehouse_id`, - 1 AS `Id_Cubo`, - 1 AS `Packing`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `lastaction` --- - -DROP TABLE IF EXISTS `lastaction`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `lastaction` ( - `Id_Cliente` int(11) unsigned NOT NULL, - `Cliente` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `Ultima_accion` date DEFAULT NULL, - `Comercial` varchar(3) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`Id_Cliente`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `live_counter` --- - -DROP TABLE IF EXISTS `live_counter`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `live_counter` ( - `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `amount` double NOT NULL, - PRIMARY KEY (`odbc_date`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `mana_inventory_kk` --- - -DROP TABLE IF EXISTS `mana_inventory_kk`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mana_inventory_kk` ( - `Id_Trabajador` int(11) NOT NULL, - `mana` double NOT NULL DEFAULT '0', - `dated` date NOT NULL, - PRIMARY KEY (`Id_Trabajador`,`dated`), - CONSTRAINT `fk_trabajador_mana_inventory` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `movimientos_log` --- - -DROP TABLE IF EXISTS `movimientos_log`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `movimientos_log` ( - `idmovimientos_log` int(11) NOT NULL AUTO_INCREMENT, - `Id_Movimiento` int(11) NOT NULL, - `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `Id_Trabajador` int(11) NOT NULL, - `field_name` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL, - `new_value` double DEFAULT NULL, - PRIMARY KEY (`idmovimientos_log`) -) ENGINE=InnoDB AUTO_INCREMENT=13371133 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `partitioning_information` --- - -DROP TABLE IF EXISTS `partitioning_information`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `partitioning_information` ( - `schema_name` varchar(10) CHARACTER SET utf8 NOT NULL, - `table_name` varchar(20) CHARACTER SET utf8 NOT NULL, - `date_field` varchar(20) CHARACTER SET utf8 DEFAULT NULL, - `table_depending` varchar(15) CHARACTER SET utf8 DEFAULT NULL, - `execution_order` tinyint(3) unsigned NOT NULL, - PRIMARY KEY (`schema_name`,`table_name`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `primer_pedido` --- - -DROP TABLE IF EXISTS `primer_pedido`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `primer_pedido` ( - `Id_Cliente` int(11) NOT NULL, - `Id_Ticket` int(11) NOT NULL, - `month` tinyint(1) NOT NULL, - `year` smallint(2) NOT NULL, - `total` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`Id_Cliente`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `rotacion` --- - -DROP TABLE IF EXISTS `rotacion`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `rotacion` ( - `Id_Article` int(11) NOT NULL, - `warehouse_id` smallint(6) unsigned NOT NULL, - `total` int(10) NOT NULL DEFAULT '0', - `rotacion` decimal(10,4) NOT NULL DEFAULT '0.0000', - `cm3` int(11) NOT NULL DEFAULT '0', - `almacenaje` decimal(10,4) NOT NULL DEFAULT '0.0000', - `manipulacion` decimal(10,4) NOT NULL DEFAULT '0.0000', - `auxiliar` decimal(10,4) NOT NULL DEFAULT '0.0000', - `mermas` decimal(10,4) NOT NULL DEFAULT '0.0000', - PRIMARY KEY (`Id_Article`,`warehouse_id`), - KEY `id_article_rotacion_idx` (`Id_Article`), - KEY `warehouse_id_rotacion_idx` (`warehouse_id`), - CONSTRAINT `id_article_rotaci` FOREIGN KEY (`Id_Article`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `warehouse_id_rotaci` FOREIGN KEY (`warehouse_id`) REFERENCES `vn2008`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los valores de rotacion en los ultimos 365 dias'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `saldos_bancos` --- - -DROP TABLE IF EXISTS `saldos_bancos`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `saldos_bancos` ( - `Semana` int(2) NOT NULL, - `Mes` int(2) NOT NULL, - `Año` int(4) NOT NULL, - `Entrada` double DEFAULT NULL, - `Salida` decimal(32,2) DEFAULT NULL, - `Saldo` double DEFAULT NULL, - `Id_Banco` int(11) NOT NULL DEFAULT '0', - `empresa_id` int(5) unsigned NOT NULL DEFAULT '0', - `Empresa` varchar(3) CHARACTER SET utf8 NOT NULL DEFAULT '' -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `saldos_bancos_pordia` --- - -DROP TABLE IF EXISTS `saldos_bancos_pordia`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `saldos_bancos_pordia` ( - `Fecha` date NOT NULL, - `Entrada` double DEFAULT NULL, - `Salida` decimal(32,2) DEFAULT NULL, - `Saldo` double DEFAULT NULL, - `Id_Banco` int(11) NOT NULL DEFAULT '0', - `empresa_id` int(5) unsigned NOT NULL DEFAULT '0', - `Empresa` varchar(3) CHARACTER SET utf8 NOT NULL DEFAULT '', - `Año` int(4) NOT NULL, - `Mes` int(2) NOT NULL, - `Dia` int(2) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `sales` --- - -DROP TABLE IF EXISTS `sales`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `sales` ( - `Id_Trabajador` int(10) unsigned NOT NULL, - `year` int(10) unsigned NOT NULL, - `month` int(10) unsigned NOT NULL, - `weight` int(11) NOT NULL DEFAULT '0', - `boss_aid` int(10) NOT NULL DEFAULT '0', - `boss_id` int(10) NOT NULL DEFAULT '0', - `comision` int(11) DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`,`year`,`month`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tarifa_componentes` --- - -DROP TABLE IF EXISTS `tarifa_componentes`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tarifa_componentes` ( - `Id_Componente` int(11) NOT NULL AUTO_INCREMENT, - `Componente` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `tarifa_componentes_series_id` int(11) NOT NULL, - `tarifa_class` smallint(6) DEFAULT NULL, - `tax` double DEFAULT NULL, - `is_renewable` tinyint(2) NOT NULL DEFAULT '1', - PRIMARY KEY (`Id_Componente`), - KEY `series_componentes_idx` (`tarifa_componentes_series_id`), - KEY `comp` (`tarifa_class`), - CONSTRAINT `serie_componente` FOREIGN KEY (`tarifa_componentes_series_id`) REFERENCES `tarifa_componentes_series` (`tarifa_componentes_series_id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tarifa_componentes_series` --- - -DROP TABLE IF EXISTS `tarifa_componentes_series`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tarifa_componentes_series` ( - `tarifa_componentes_series_id` int(11) NOT NULL AUTO_INCREMENT, - `Serie` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `base` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Marca aquellas series que se utilizan para calcular el precio base de las ventas, a efectos estadisticos', - `margen` tinyint(4) NOT NULL DEFAULT '0', - PRIMARY KEY (`tarifa_componentes_series_id`), - UNIQUE KEY `Serie_UNIQUE` (`Serie`) -) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Permite organizar de forma ordenada los distintos componentes'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tarifa_premisas` --- - -DROP TABLE IF EXISTS `tarifa_premisas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tarifa_premisas` ( - `Id_Premisa` int(11) NOT NULL AUTO_INCREMENT, - `premisa` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`Id_Premisa`) -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tarifa_warehouse` --- - -DROP TABLE IF EXISTS `tarifa_warehouse`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tarifa_warehouse` ( - `Id_Tarifa_Warehouse` int(11) NOT NULL AUTO_INCREMENT, - `warehouse_id` int(11) NOT NULL, - `Id_Premisa` int(11) NOT NULL, - `Valor` double NOT NULL, - PRIMARY KEY (`Id_Tarifa_Warehouse`) -) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los valores de gasto por almacen'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `v_clientes_jerarquia` --- - -DROP TABLE IF EXISTS `v_clientes_jerarquia`; -/*!50001 DROP VIEW IF EXISTS `v_clientes_jerarquia`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_clientes_jerarquia` AS SELECT - 1 AS `Id_Cliente`, - 1 AS `Cliente`, - 1 AS `Comercial`, - 1 AS `Jefe`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `v_ventas_contables` --- - -DROP TABLE IF EXISTS `v_ventas_contables`; -/*!50001 DROP VIEW IF EXISTS `v_ventas_contables`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `v_ventas_contables` AS SELECT - 1 AS `year`, - 1 AS `month`, - 1 AS `importe`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `variablesKK` --- - -DROP TABLE IF EXISTS `variablesKK`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `variablesKK` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `variable` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `value` double DEFAULT NULL, - `date` datetime DEFAULT NULL, - `text` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'bi' --- - --- --- Dumping routines for database 'bi' --- -/*!50003 DROP FUNCTION IF EXISTS `nz` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `nz`(dblCANTIDAD DOUBLE) RETURNS double -BEGIN - -DECLARE dblRESULT DOUBLE; - -SET dblRESULT = IFNULL(dblCANTIDAD,0); - -RETURN dblRESULT; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `analisis_ventas_evolution_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `analisis_ventas_evolution_add`() -BEGIN - DECLARE vPreviousPeriod INT; - DECLARE vCurrentPeriod INT; - DECLARE vLastPeriod INT; - DECLARE vMinPeriod INT DEFAULT 201400; - DECLARE vMaxPeriod INT DEFAULT vn2008.vnperiod(CURDATE()); - - DECLARE vYear INT; - DECLARE vWeek INT; - - -- Almacen - - SET vCurrentPeriod = IFNULL(vLastPeriod, vMinPeriod); - - WHILE vCurrentPeriod < vMaxPeriod - DO - SELECT MAX(Periodo) INTO vPreviousPeriod - FROM bi.analisis_ventas_almacen_evolution - WHERE Periodo < vMaxPeriod; - - SELECT MIN(period) INTO vCurrentPeriod - FROM vn2008.time - WHERE period > vPreviousPeriod; - - SET vYear = FLOOR(vCurrentPeriod / 100); - SET vWeek = vCurrentPeriod - (vYear * 100); - - DELETE FROM bi.analisis_ventas_almacen_evolution - WHERE Periodo = vCurrentPeriod; - - REPLACE bi.analisis_ventas_almacen_evolution(Almacen, Ventas, Semana,Año, Periodo) - SELECT Almacen, sum(Ventas) AS Ventas, vWeek, vYear, vCurrentPeriod - FROM ( - SELECT almacen, sum(Importe) AS Ventas - FROM bi.analisis_ventas - WHERE vYear = Año - AND vWeek = Semana - GROUP BY almacen - UNION ALL - SELECT almacen, - sum(Importe) AS Ventas - FROM bi.analisis_ventas - WHERE vYear - 1 = Año - AND vWeek = Semana - GROUP BY almacen - UNION ALL - SELECT Almacen, Ventas - FROM bi.analisis_ventas_almacen_evolution - WHERE Periodo = vPreviousPeriod - ) sub - GROUP BY Almacen; - END WHILE; - - -- Reino - - SET vCurrentPeriod = vMinPeriod; - - WHILE vCurrentPeriod < vMaxPeriod - DO - SELECT MAX(periodo) INTO vPreviousPeriod - FROM bi.analisis_ventas_reino_evolution - WHERE periodo < vMaxPeriod; - - SELECT MIN(period) INTO vCurrentPeriod - FROM vn2008.time - WHERE period > vPreviousPeriod; - - SET vYear = FLOOR(vCurrentPeriod / 100); - SET vWeek = vCurrentPeriod - (vYear * 100); - - DELETE FROM bi.analisis_ventas_reino_evolution - WHERE Periodo = vCurrentPeriod; - - REPLACE bi.analisis_ventas_reino_evolution(reino, ventas, semana,año, periodo) - SELECT reino, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod - FROM ( - SELECT Reino, sum(Importe) AS ventas - FROM bi.analisis_ventas - WHERE vYear = Año - AND vWeek = Semana - GROUP BY Reino - UNION ALL - SELECT Reino, - sum(Importe) AS ventas - FROM bi.analisis_ventas - WHERE vYear - 1 = Año - AND vWeek = Semana - GROUP BY Reino - UNION ALL - SELECT reino, ventas - FROM bi.analisis_ventas_reino_evolution - WHERE Periodo = vPreviousPeriod - ) sub - GROUP BY reino; - END WHILE; - - -- Familia - - SET vCurrentPeriod = vMinPeriod; - - WHILE vCurrentPeriod < vMaxPeriod - DO - SELECT MAX(periodo) INTO vPreviousPeriod - FROM bi.analisis_ventas_familia_evolution - WHERE periodo < vMaxPeriod; - - SELECT MIN(period) INTO vCurrentPeriod - FROM vn2008.time - WHERE period > vPreviousPeriod; - - SET vYear = FLOOR(vCurrentPeriod / 100); - SET vWeek = vCurrentPeriod - (vYear * 100); - - DELETE FROM bi.analisis_ventas_familia_evolution - WHERE Periodo = vCurrentPeriod; - - REPLACE bi.analisis_ventas_familia_evolution(familia, ventas, semana,año, periodo) - SELECT Familia, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod - FROM ( - SELECT Familia, sum(Importe) AS ventas - FROM bi.analisis_ventas - WHERE vYear = Año - AND vWeek = Semana - GROUP BY familia - UNION ALL - SELECT Familia, - sum(Importe) AS ventas - FROM bi.analisis_ventas - WHERE vYear - 1 = Año - AND vWeek = Semana - GROUP BY familia - UNION ALL - SELECT familia, ventas - FROM bi.analisis_ventas_familia_evolution - WHERE Periodo = vPreviousPeriod - ) sub - GROUP BY Familia; - END WHILE; - - -- Comprador - -- FIXME: Bucle infinito porque la tabla está vacía -/* - SET vCurrentPeriod = vMinPeriod; - - WHILE vCurrentPeriod < vMaxPeriod - DO - SELECT IFNULL(MAX(periodo),vMinPeriod) INTO vPreviousPeriod - FROM bi.analisis_ventas_comprador_evolution - WHERE periodo < vMaxPeriod; - - SELECT MIN(period) INTO vCurrentPeriod - FROM vn2008.time - WHERE period > vPreviousPeriod; - - SET vYear = FLOOR(vCurrentPeriod / 100); - SET vWeek = vCurrentPeriod - (vYear * 100); - - DELETE FROM bi.analisis_ventas_comprador_evolution - WHERE Periodo = vCurrentPeriod; - - REPLACE bi.analisis_ventas_comprador_evolution(comprador, ventas, semana,año, periodo) - SELECT Comprador, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod - FROM ( - SELECT Comprador, sum(Importe) AS ventas - FROM bi.analisis_ventas - WHERE vYear = Año - AND vWeek = Semana - GROUP BY Comprador - UNION ALL - SELECT Comprador, - sum(Importe) AS ventas - FROM bi.analisis_ventas - WHERE vYear - 1 = Año - AND vWeek = Semana - GROUP BY Comprador - UNION ALL - SELECT comprador, IFNULL(ventas,0) - FROM bi.analisis_ventas_comprador_evolution - WHERE Periodo = vPreviousPeriod - ) sub - GROUP BY Comprador; - END WHILE; -*/ - -- Provincia - - SET vCurrentPeriod = vMinPeriod; - - WHILE vCurrentPeriod < vMaxPeriod - DO - SELECT MAX(periodo) INTO vPreviousPeriod - FROM bi.analisis_ventas_provincia_evolution - WHERE periodo < vMaxPeriod; - - SELECT MIN(period) INTO vCurrentPeriod - FROM vn2008.time - WHERE period > vPreviousPeriod; - - SET vYear = FLOOR(vCurrentPeriod / 100); - SET vWeek = vCurrentPeriod - (vYear * 100); - - DELETE FROM bi.analisis_ventas_provincia_evolution - WHERE Periodo = vCurrentPeriod; - - REPLACE bi.analisis_ventas_provincia_evolution(provincia, ventas, semana,año, periodo) - SELECT Provincia, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod - FROM ( - SELECT Provincia, sum(Importe) AS ventas - FROM bi.analisis_ventas - WHERE vYear = Año - AND vWeek = Semana - GROUP BY Provincia - UNION ALL - SELECT Provincia, - sum(Importe) AS ventas - FROM bi.analisis_ventas - WHERE vYear - 1 = Año - AND vWeek = Semana - GROUP BY Provincia - UNION ALL - SELECT provincia, ventas - FROM bi.analisis_ventas_provincia_evolution - WHERE Periodo = vPreviousPeriod - ) sub - GROUP BY Provincia; - END WHILE; - - -- Vista - - SET vCurrentPeriod = vMinPeriod; - - WHILE vCurrentPeriod < vMaxPeriod - DO - SELECT MAX(periodo) INTO vPreviousPeriod - FROM bi.analisis_ventas_vista_evolution - WHERE periodo < vMaxPeriod; - - SELECT MIN(period) INTO vCurrentPeriod - FROM vn2008.time - WHERE period > vPreviousPeriod; - - SET vYear = FLOOR(vCurrentPeriod / 100); - SET vWeek = vCurrentPeriod - (vYear * 100); - - DELETE FROM bi.analisis_ventas_vista_evolution - WHERE Periodo = vCurrentPeriod; - - REPLACE bi.analisis_ventas_vista_evolution(vista, ventas, semana,año, periodo) - SELECT vista, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod - FROM ( - SELECT Vista, sum(Importe) AS ventas - FROM bi.analisis_ventas - WHERE vYear = Año - AND vWeek = Semana - GROUP BY Vista - UNION ALL - SELECT Vista, - sum(Importe) AS ventas - FROM bi.analisis_ventas - WHERE vYear - 1 = Año - AND vWeek = Semana - GROUP BY Vista - UNION ALL - SELECT vista, ventas - FROM bi.analisis_ventas_vista_evolution - WHERE Periodo = vPreviousPeriod - ) sub - GROUP BY Vista; - END WHILE; - - -- Vendedor - - SET vCurrentPeriod = vMinPeriod; - - WHILE vCurrentPeriod < vMaxPeriod - DO - SELECT MAX(periodo) INTO vPreviousPeriod - FROM bi.analisis_ventas_vendedor_evolution - WHERE periodo < vMaxPeriod; - - SELECT MIN(period) INTO vCurrentPeriod - FROM vn2008.time - WHERE period > vPreviousPeriod; - - SET vYear = FLOOR(vCurrentPeriod / 100); - SET vWeek = vCurrentPeriod - (vYear * 100); - - DELETE FROM bi.analisis_ventas_vendedor_evolution - WHERE Periodo = vCurrentPeriod; - - REPLACE bi.analisis_ventas_vendedor_evolution(vendedor, ventas, semana,año, periodo) - SELECT Comercial AS vendedor, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod - FROM ( - SELECT Comercial, sum(Importe) AS ventas - from bi.analisis_ventas - WHERE vYear = Año - AND vWeek = Semana - GROUP BY Comercial - UNION ALL - SELECT Comercial, - sum(Importe) AS ventas - from bi.analisis_ventas - WHERE vYear - 1 = Año - AND vWeek = Semana - GROUP BY Comercial - UNION ALL - SELECT vendedor, ventas - FROM bi.analisis_ventas_vendedor_evolution - WHERE Periodo = vPreviousPeriod - ) sub - GROUP BY vendedor; - END WHILE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `analisis_ventas_simple` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `analisis_ventas_simple`() -BEGIN - -TRUNCATE bi.analisis_grafico_simple; - -INSERT INTO bi.analisis_grafico_simple SELECT * FROM bi.analisis_grafico_ventas; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `analisis_ventas_update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `analisis_ventas_update`() -BEGIN - - DECLARE vLastMonth DATE; - - SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, CURDATE())); - - DELETE FROM bi.analisis_ventas - WHERE Año > YEAR(vLastMonth) - OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); - - INSERT INTO bi.analisis_ventas - - SELECT - `tp`.`Tipo` AS `Familia`, - `r`.`reino` AS `Reino`, - `tr`.`CodigoTrabajador` AS `Comercial`, - `tr2`.`CodigoTrabajador` AS `Comprador`, - `p`.`name` AS `Provincia`, - `w`.`name` AS `almacen`, - `time`.`year` AS `Año`, - `time`.`month` AS `Mes`, - `time`.`week` AS `Semana`, - `v`.`vista` AS `Vista`, - `bt`.`importe` AS `Importe` - FROM - (((((((((`bs`.`ventas` `bt` - LEFT JOIN `vn2008`.`Tipos` `tp` ON ((`tp`.`tipo_id` = `bt`.`tipo_id`))) - LEFT JOIN `vn2008`.`reinos` `r` ON ((`r`.`id` = `tp`.`reino_id`))) - LEFT JOIN `vn2008`.`Clientes` c on c.Id_Cliente = bt.Id_Cliente - LEFT JOIN `vn2008`.`Trabajadores` `tr` ON ((`tr`.`Id_Trabajador` = `c`.`Id_Trabajador`))) - LEFT JOIN `vn2008`.`Trabajadores` `tr2` ON ((`tr2`.`Id_Trabajador` = `tp`.`Id_Trabajador`))) - JOIN vn2008.time on time.date = bt.fecha - JOIN vn2008.Movimientos m on m.Id_Movimiento = bt.Id_Movimiento - LEFT JOIN `vn2008`.`Tickets` `t` ON ((`t`.`Id_Ticket` = `m`.`Id_Ticket`))) - JOIN vn2008.Agencias a on a.Id_Agencia = t.Id_Agencia - LEFT JOIN `vn2008`.`Vistas` `v` ON ((`v`.`vista_id` = `a`.`Vista`))) - LEFT JOIN `vn2008`.`Consignatarios` `cs` ON ((`cs`.`Id_Consigna` = `t`.`Id_Consigna`))) - LEFT JOIN `vn2008`.`province` `p` ON ((`p`.`province_id` = `cs`.`province_id`))) - LEFT JOIN `vn2008`.`warehouse` `w` ON ((`w`.`id` = `t`.`warehouse_id`))) - WHERE bt.fecha >= vLastMonth AND r.mercancia; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `call_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `call_add`() -BEGIN - -DECLARE datSTART DATETIME DEFAULT '2012-03-01'/*CURDATE()*/; --- control -INSERT INTO vn2008.daily_task_log(consulta) VALUES('bi.call_add'); - --- Seleccionamos la ultima fecha introducida -SELECT MAX(Fecha) INTO datSTART FROM `call`; - - --- Borramos todas las entradas del dia datSTART por si hubiese registros nuevos -DELETE FROM `call` WHERE Fecha = datSTART; - -INSERT INTO bi.`call`(CodTrabajadorCartera,CodTrabajadorTelefono,dur_in,dur_out,Fecha,`year`,`month`,`week`,`hour`,phone) -SELECT vn2008.Averiguar_ComercialCliente(pb.Id_Cliente,Fecha) CodTrabajadorCartera,ll.CodigoTrabajador, dur_in, - dur_out, ll.Fecha,YEAR(ll.Fecha) `year`, MONTH(ll.Fecha) `month`,WEEK(ll.Fecha,7) `week`, Hora,phone -FROM -( -SELECT Id_Trabajador,CodigoTrabajador, IFNULL(billsec,0) dur_in, 0 dur_out, 1 as Recibidas, NULL as Emitidas, calldate as Fecha, - hour(calldate) as Hora,src as phone -FROM vn2008.Trabajadores T -INNER JOIN vn2008.cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%') -WHERE calldate >= datSTART AND LENGTH(C.src) >=9 AND disposition = 'ANSWERED' AND duration -UNION ALL -SELECT Id_Trabajador,CodigoTrabajador,0 dur_in, IFNULL(billsec,0) dur_out, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate),dst -FROM vn2008.Trabajadores T -INNER JOIN vn2008.cdr C ON C.src = T.extension -WHERE calldate >= datSTART AND LENGTH(C.dst) >=9 AND disposition = 'ANSWERED' AND duration -) ll -INNER JOIN vn2008.Permisos USING(Id_Trabajador) -LEFT JOIN vn2008.v_phonebook pb ON pb.Telefono = ll.phone -WHERE Id_Grupo = 6; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `claim_ratio_routine` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `claim_ratio_routine`() -BEGIN - -DECLARE vMonthToRefund INT DEFAULT 4; - --- control -INSERT INTO vn2008.daily_task_log(consulta) - VALUES('bi.claim_ratio_routine START'); - -/* -* PAK 2015-11-20 -* Se trata de añadir a la tabla Greuges todos los -* cargos que luego vamos a utilizar para calcular el recobro -*/ - --- descuentos comerciales COD 11 - -INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, Importe, Id_Ticket) - SELECT Fecha, Id_Cliente, Concat('COD11 : ',Concepte), - round(Cantidad * - Preu * (100 - Descuento) / 100 ,2) AS Importe, t.Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket - WHERE Id_Article = 11 - AND Concepte NOT LIKE '$%' - AND Fecha > '2014-01-01' - HAVING nz(Importe) <> 0; - -DELETE mc.* - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - WHERE m.Id_Article = 11 - AND m.Concepte NOT LIKE '$%' - AND t.Fecha > '2017-01-01'; - -INSERT INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento, 34, round(m.Preu * (100 - m.Descuento)/100,4) - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - WHERE m.Id_Article = 11 - AND m.Concepte NOT LIKE '$%' - AND t.Fecha > '2017-01-01'; - -UPDATE vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - SET Concepte = CONCAT('$ ',Concepte) - WHERE Id_Article = 11 - AND Concepte NOT LIKE '$%' - AND Fecha > '2014-01-01'; - --- Reclamaciones demasiado sensibles - -INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, - Importe, Greuges_type_id,Id_Ticket) - SELECT cm.Fecha - , cm.Id_Cliente - , concat('Claim ',cm.id,' : ', m.Concepte) - ,round( -1 * ((sensib -1)/4) * Cantidad * - Preu * (100 - Descuento) / 100, 2) AS Reclamaciones - , 4 - , m.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca USING(Id_Movimiento) - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3; - - -- Reclamaciones que pasan a Maná - -INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, - Importe , Greuges_type_id,Id_Ticket) - SELECT cm.Fecha - , cm.Id_Cliente - , concat('Claim_mana ',cm.id,' : ', m.Concepte) - ,round( ((sensib -1)/4) * Cantidad * Preu * (100 - Descuento) / 100, 2) - AS Reclamaciones - ,3 - ,m.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca USING(Id_Movimiento) - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3 - AND cm.mana; - - -- Marcamos para no repetir -UPDATE vn2008.cl_act ca - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - SET greuge = 1 - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3; - - - --- Recobros - -DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; -CREATE TEMPORARY TABLE tmp.ticket_list -(PRIMARY KEY (Id_Ticket)) -SELECT DISTINCT t.Id_Ticket - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Tickets_state ts ON ts.Id_Ticket = t.Id_Ticket - JOIN vncontrol.inter i ON i.inter_id = ts.inter_id - JOIN vn2008.state s ON s.id = i.state_id - WHERE mc.Id_Componente = 17 - AND mc.greuge = 0 - AND t.Fecha >= '2016-10-01' - AND t.Fecha < CURDATE() - AND t.warehouse_id <> 41 - AND s.alert_level >= 3; - -DELETE g.* - FROM vn2008.Greuges g - JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket - WHERE Greuges_type_id = 2; - -INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, - Greuges_type_id, Id_Ticket) - SELECT Id_Cliente - ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2) - AS dif - ,date(t.Fecha) - , 2 - ,tt.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Movimientos_componentes mc - ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = 17 - GROUP BY t.Id_Ticket - HAVING ABS(dif) > 1; - -UPDATE vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN tmp.ticket_list tt ON tt.Id_Ticket = m.Id_Ticket - SET greuge = 1 - WHERE Id_Componente = 17; - -/* -* Recalculamos la ratio de las reclamaciones, que luego -* se va a utilizar en el recobro -*/ - -DELETE FROM bi.claims_ratio; - -REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, - round(Reclamaciones / (12*fm.Consumo),4) AS Ratio, 0 - FROM bi.facturacion_media_anual fm - LEFT JOIN( - SELECT cm.Id_Cliente, round(sum(-1 * ((sensib -1)/4) * - Cantidad * Preu * (100 - Descuento) / 100)) - AS Reclamaciones - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca - ON ca.Id_Movimiento = m.Id_Movimiento - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND cm.cl_est_id = 3 - AND cm.Fecha >= TIMESTAMPADD(YEAR, -1, CURDATE()) - GROUP BY cm.Id_Cliente - ) claims ON claims.Id_Cliente = fm.Id_Cliente; - - --- Calculamos el porcentaje del recobro para añadirlo al precio de venta -UPDATE bi.claims_ratio cr - JOIN ( - SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge - FROM vn2008.Greuges - WHERE Fecha <= CURDATE() - GROUP BY Id_Cliente - ) g ON g.Id_Cliente = cr.Id_Cliente - SET recobro = GREATEST(0,round(nz(Greuge) / - (nz(Consumo) * vMonthToRefund / 12 ) ,3)); - --- Protección neonatos -/* -UPDATE bi.claims_ratio cr - JOIN vn2008.Clientes c ON c.Id_Cliente = cr.Id_Cliente - SET recobro = 0, Ratio = 0 - WHERE c.created > TIMESTAMPADD(MONTH,-1,CURDATE()); - */ -UPDATE bi.claims_ratio cr - JOIN vn.firstTicketShipped fts ON fts.clientFk = cr.Id_Cliente - SET recobro = 0, Ratio = 0 - WHERE fts.shipped > TIMESTAMPADD(MONTH,-1,CURDATE()); - --- control -INSERT INTO vn2008.daily_task_log(consulta) - VALUES('bi.claim_ratio_routine END'); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clean` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN -DECLARE vDateShort DATETIME; -DECLARE vDateLong DATETIME; -DECLARE vOneYearAgo DATETIME; - -SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); -SET vDateLong = TIMESTAMPADD(MONTH, -18,CURDATE()); -SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,CURDATE()); - -INSERT INTO bi.dailyTaskLog(state) VALUES('clean START'); - -DELETE FROM bi.comparativa_clientes WHERE Fecha < vDateLong; - -DELETE - FROM bi.Greuge_Evolution - WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) - OR Fecha < vOneYearAgo; - -INSERT INTO bi.dailyTaskLog(state) VALUES('clean END'); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `clean_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clean_launcher`() -BEGIN - - call vn2008.clean(0); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `comparativa_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `comparativa_add`() -BEGIN - DECLARE lastCOMP INT; # Se trata de una variable para almacenar el ultimo valor del Periodo - - SELECT MAX(Periodo) INTO lastCOMP FROM vn2008.Comparativa; - -- Fijaremos las ventas con más de un mes de antiguedad en la tabla Comparativa - - IF lastCOMP < vn2008.vnperiod(CURDATE())- 3 AND vn2008.vnweek(CURDATE()) > 3 THEN - - REPLACE vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price) - SELECT tm.period as Periodo, m.Id_Article, t.warehouse_id, sum(m.Cantidad), sum(v.importe) - FROM bs.ventas v - JOIN vn2008.time tm ON tm.date = v.fecha - JOIN vn2008.Movimientos m ON m.Id_Movimiento = v.Id_Movimiento - JOIN vn2008.Articles a ON a.Id_Article = m.Id_Article - JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id - JOIN vn2008.reinos r ON r.id = tp.reino_id - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - WHERE tm.period BETWEEN lastCOMP AND vn2008.vnperiod(CURDATE())- 3 - AND t.Id_Cliente NOT IN(400,200) - AND r.display <> 0 - AND t.warehouse_id NOT IN (0,13) - GROUP BY Id_Article, Periodo, warehouse_id; - - -/* - REPLACE vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price) - SELECT vn2008.vnperiod(T.Fecha) AS Periodo - , Id_Article - , warehouse_id - , SUM(Cantidad) AS Total - , SUM(Cantidad * Preu * (100 - Descuento) / 100) precio - FROM vn2008.Movimientos M - JOIN vn2008.Tickets T USING (Id_Ticket) - JOIN vn2008.Articles A USING (Id_Article) - LEFT JOIN vn2008.Tipos ti ON ti.tipo_id = A.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = ti.reino_id - WHERE T.Fecha BETWEEN TIMESTAMPADD(DAY,-60,CURDATE()) AND TIMESTAMPADD(DAY,-30,CURDATE()) - AND T.Id_Cliente NOT IN(400,200) - AND display <> 0 AND warehouse_id NOT IN (0,13) - GROUP BY Id_Article, Periodo, warehouse_id; -*/ - - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `comparativa_add_manual` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `comparativa_add_manual`(IN dat_START DATE, IN dat_END DATE) -BEGIN - - DECLARE datINI DATETIME; - DECLARE datFIN DATETIME; - - -- Seleccionamos la fecha minima/maxima del periodo que vamos a consultar - SELECT MIN(`date`) INTO datINI FROM vn2008.`time` WHERE period = vn2008.vnperiod(dat_START); - SELECT TIMESTAMP(MAX(`date`),'23:59:59') INTO datFIN FROM vn2008.`time` WHERE period = vn2008.vnperiod(dat_END); - - DELETE FROM vn2008.Comparativa WHERE Periodo BETWEEN vn2008.vnperiod(dat_START) and vn2008.vnperiod(dat_END); - - REPLACE vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price) - SELECT tm.period AS Periodo - , M.Id_Article - , t.warehouse_id - , SUM(Cantidad) AS Total - , sum(v.importe) AS precio - FROM vn2008.Movimientos M - JOIN vn2008.Tickets t on t.Id_Ticket = M.Id_Ticket - JOIN bs.ventas v on v.Id_Movimiento = M.Id_Movimiento - JOIN vn2008.time tm on tm.date = v.fecha - JOIN vn2008.Tipos tp on v.tipo_id = tp.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id - WHERE v.fecha BETWEEN datINI and datFIN - AND r.display <> 0 AND t.warehouse_id NOT IN (0,13) - GROUP BY Id_Article, Periodo, t.warehouse_id; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `customer_risk_update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `customer_risk_update`(v_customer INT, v_company INT, v_amount DECIMAL(10,2)) -BEGIN - IF v_amount IS NOT NULL - THEN - INSERT INTO bi.customer_risk - SET - customer_id = v_customer, - company_id = v_company, - amount = v_amount - ON DUPLICATE KEY UPDATE - amount = amount + VALUES(amount); - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `defaultersFromDate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `defaultersFromDate`(IN vDate DATE) -BEGIN - -SELECT t1.*, c.Cliente, w.workerCode, c.pay_met_id,c.Vencimiento -FROM ( --- Filtramos aquellos clientes cuyo saldo se ha incrementado de ayer a hoy - select * from( - select today.client, today.amount todayAmount, yesterday.amount yesterdayAmount, round(yesterday.amount - today.amount,2) as difference, defaulterSince - from - (select client, amount, defaulterSince - from defaulters - where date = vDate and hasChanged) today - join - (select client, amount - from defaulters - where date = TIMESTAMPADD(DAY,-1,vDate)) yesterday using(client) - - having today.amount > 0 and difference <> 0 - ) newDefaulters -)t1 left join vn2008.Clientes c ON t1.client = c.Id_Cliente - left join vn.worker w ON w.id = c.Id_Trabajador; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `defaulting` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `defaulting`(IN vDate DATE) -BEGIN - DECLARE vDone BOOLEAN; - DECLARE vClient INT; - DECLARE vAmount INT; - DECLARE vDateInvoice DATE; - DECLARE vAmountInvoice DECIMAL(10,2); - DECLARE vDueDay INT; - DECLARE vGraceDays INT; - DECLARE defaulters CURSOR FOR - SELECT client, amount, Vencimiento, graceDays FROM bi.defaulters d - JOIN vn2008.Clientes c ON c.Id_Cliente = d.client - JOIN vn2008.pay_met pm ON pm.id = c.pay_met_id - WHERE hasChanged AND date = vDate; - - DECLARE invoices CURSOR FOR - SELECT Fecha, importe FROM vn2008.Facturas f - WHERE f.Fecha >= '2016-01-01' AND f.Id_Cliente = vClient ORDER BY f.Fecha DESC; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - -- Control - - INSERT INTO vn2008.daily_task_log(consulta) VALUES('defaulting'); - - DELETE FROM bi.defaulters WHERE date = vDate; - - INSERT INTO bi.defaulters(client, date, amount) - SELECT customer_id, vDate, FLOOR(SUM(amount)) AS amount - FROM bi.customerRiskOverdue - GROUP BY customer_id; - - -- marcamos si ha cambiado y heredamos la fecha defaulterSince - UPDATE bi.defaulters d - JOIN ( - SELECT * FROM( - SELECT client, amount , defaulterSince FROM bi.defaulters - WHERE date <= TIMESTAMPADD(DAY,-1, vDate) - ORDER BY date DESC) t GROUP BY client - ) yesterday using(client) - SET d.hasChanged = IF(d.amount <> yesterday.amount, 1, 0), - d.defaulterSince = yesterday.defaulterSince - WHERE d.date = vDate ; - - OPEN defaulters; - defaulters: LOOP - SET vDone = FALSE; - SET vAmount = 0; - FETCH defaulters INTO vClient,vAmount, vDueDay, vGraceDays; - IF vDone THEN - LEAVE defaulters; - END IF; - OPEN invoices; - invoices:LOOP - - FETCH invoices INTO vDateInvoice, vAmountInvoice; - IF vDone THEN - LEAVE invoices; - END IF; - - IF TIMESTAMPADD(DAY, vGraceDays, vn2008.paymentday(vDateInvoice, vDueDay)) <= vDate THEN - SET vAmount = vAmount - vAmountInvoice; - IF vAmount <= 0 THEN - UPDATE defaulters SET defaulterSince = vn2008.paymentday(vDateInvoice, vDueDay) - WHERE client = vClient and date = vDate; - - SET vAmount = 0; - LEAVE invoices; - END IF; - END IF; - END LOOP; - CLOSE invoices; - END LOOP; - CLOSE defaulters; - DELETE FROM bi.defaulting WHERE date = vDate; - - INSERT INTO bi.defaulting(date, amount) - SELECT vDate, SUM(amount) - FROM bi.defaulters - WHERE date = vDate and amount > 0; - - CALL vn.clientFreeze(); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `defaultingkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `defaultingkk`(IN vDate DATE) -BEGIN - DECLARE done BIT DEFAULT 0; - DECLARE vClient INT; - DECLARE vAmount INT; - DECLARE vDateInvoice DATE; - DECLARE vAmountInvoice DECIMAL(10,2); - DECLARE vDueDay INT; - DECLARE vGraceDays INT; - DECLARE defaulters CURSOR FOR - SELECT client, amount, Vencimiento, graceDays FROM bi.defaulters d - JOIN vn2008.Clientes c ON c.Id_Cliente = d.client - JOIN vn2008.pay_met pm ON pm.id = c.pay_met_id - WHERE hasChanged AND date = vDate; - - DECLARE invoices CURSOR FOR - SELECT Fecha, importe FROM vn2008.Facturas f - WHERE f.Fecha >= '2016-01-01' AND f.Id_Cliente = vClient ORDER BY f.Fecha DESC; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - -- Control - - INSERT INTO vn2008.daily_task_log(consulta) VALUES('defaulting'); - - DELETE FROM bi.defaulters WHERE date = vDate; - - INSERT INTO bi.defaulters(client, date, amount) - SELECT customer_id, vDate, FLOOR(SUM(amount)) AS amount - FROM bi.customerRiskOverdue - GROUP BY customer_id; - - -- marcamos si ha cambiado y heredamos la fecha defaulterSince - UPDATE bi.defaulters d - JOIN ( - SELECT client, amount , defaulterSince FROM bi.defaulters - WHERE date = TIMESTAMPADD(DAY,-1, vDate) - GROUP BY client - ) yesterday using(client) - SET d.hasChanged = IF(d.amount <> yesterday.amount, 1, 0), - d.defaulterSince = yesterday.defaulterSince - WHERE d.date = vDate ; - - OPEN defaulters; - defaulters: BEGIN - REPEAT - FETCH defaulters INTO vClient,vAmount, vDueDay, vGraceDays; - OPEN invoices; - invoices:BEGIN - REPEAT - - FETCH invoices INTO vDateInvoice, vAmountInvoice; - IF TIMESTAMPADD(DAY, vGraceDays, vn2008.paymentday(vDateInvoice, vDueDay)) <= vDate THEN - SET vAmount = vAmount - vAmountInvoice; - IF vAmount < 0 THEN - UPDATE defaulters SET defaulterSince = vn2008.paymentday(vDateInvoice, vDueDay) - WHERE client = vClient and date = vDate; - SET vAmount = 0; - LEAVE invoices; - END IF; - END IF; - UNTIL done END REPEAT; - END invoices; - CLOSE invoices; - UNTIL done OR vClient IS NULL END REPEAT; - END defaulters; - CLOSE defaulters; - DELETE FROM bi.defaulting WHERE date = vDate; - - INSERT INTO bi.defaulting(date, amount) - SELECT vDate, SUM(amount) - FROM bi.defaulters - WHERE date = vDate and amount > 0; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `defaulting_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `defaulting_launcher`() -BEGIN - - CALL bi.defaulting(curdate()); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `equaliza` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `equaliza`(IN wh_id INT) -BEGIN - -DECLARE datEQ DATETIME; -/* JGF 2017-03-20 cuelga el sistema - -SELECT `date` INTO datEQ FROM bi.variables WHERE variable = IF(wh_id = 17,'eq_mcf','equalizator'); - - -IF TIMEDIFF(now(), datEQ) > '00:05:00' THEN - - UPDATE bi.Equalizator e - JOIN - ( - SELECT - Vista, - sum(1) as pedido, - sum(PedidoImpreso) as impreso, - sum(t.Factura IS NOT NULL - OR t.Etiquetasemitidas - OR nz(ticket_id) <> 0) as encajado - FROM - vn2008.Movimientos - JOIN - vn2008.Tickets t USING (Id_Ticket) - JOIN - vn2008.Agencias a ON t.Id_Agencia = a.Id_Agencia - JOIN - vn2008.Clientes C USING (Id_Cliente) - LEFT JOIN - (SELECT distinct - ticket_id - FROM - vn2008.expeditions e JOIN vn2008.Tickets t ON t.Id_Ticket = e.ticket_id WHERE Fecha >= curDate()) exp ON ticket_id = Id_Ticket - WHERE - invoice And Fecha >= curDate() - AND t.warehouse_id = wh_id - AND fecha < (TIMESTAMPADD(DAY, 1, CURDATE())) - GROUP BY Vista) sub using(Vista) - SET e.Pedido = sub.pedido, e.Impreso = sub.impreso, e.Encajado = sub.encajado; - - UPDATE bi.variables SET `date`= now() WHERE variable = IF(wh_id = 17,'eq_mcf','equalizator'); - - -END IF; -*/ -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `facturacion_media_anual_update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `facturacion_media_anual_update`() -BEGIN - --- control -INSERT INTO vn2008.daily_task_log(consulta) VALUES('bi.facturacion_media_anual_update'); - -TRUNCATE TABLE bi.facturacion_media_anual; - -REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) -select Id_Cliente, avg(Consumo) -from ( - Select Id_Cliente, YEAR(fecha) year, MONTH(fecha) month, sum(importe) as Consumo - from bs.ventas - where fecha >= TIMESTAMPADD(YEAR,-1,CURDATE()) - group by Id_Cliente, year, month -) vol -group by Id_Cliente; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `greuge_dif_porte_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `greuge_dif_porte_add`() -BEGIN - -DECLARE datSTART DATETIME DEFAULT TIMESTAMPADD(DAY,-10,CURDATE()); -DECLARE datEND DATETIME DEFAULT TIMESTAMPADD(DAY,-1,CURDATE()); - - -DROP TEMPORARY TABLE IF EXISTS tmp.dp; - -CREATE TEMPORARY TABLE tmp.dp - (PRIMARY KEY (Id_Ticket)) - ENGINE = MEMORY - SELECT - t.Id_Ticket, - SUM(az.price * IF( - e.EsBulto = 71 - AND ISNULL(e.Id_Article) - AND a.Vista = 2, - 0.75, - 1 - ) - ) AS teorico, - 00000.00 as practico, - 00000.00 as greuge - FROM - vn2008.Tickets t - JOIN vn2008.Clientes cli ON cli.Id_cliente = t.Id_Cliente - LEFT JOIN vn2008.expeditions e ON e.ticket_id = t.Id_Ticket - JOIN vn2008.Consignatarios c ON c.Id_Consigna = t.Id_Consigna - JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia - JOIN vn2008.Agencias_province ap ON t.warehouse_id = ap.warehouse_id - AND ap.province_id = c.province_id - AND ap.agency_id = a.agency_id - JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = t.Id_Agencia - AND az.zona = ap.zona - AND t.warehouse_id = az.warehouse_id - AND az.Id_Article = e.EsBulto - WHERE - t.Fecha between datSTART AND datEND - AND cli.`real` - AND t.empresa_id IN (442 , 567) - GROUP BY t.Id_Ticket; - -DROP TEMPORARY TABLE IF EXISTS tmp.dp_aux; - -CREATE TEMPORARY TABLE tmp.dp_aux - (PRIMARY KEY (Id_Ticket)) - ENGINE = MEMORY - SELECT t.Id_Ticket, sum(freight) as porte - FROM tmp.dp - JOIN vn2008.Tickets t ON t.Id_Ticket = dp.Id_Ticket - JOIN vn2008.Rutas r on r.Id_Ruta = t.Id_Ruta - JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia - JOIN ( - SELECT - M.Id_Ticket, - (M.Cantidad * r.cm3 / cb.Volumen ) * az.price AS freight - FROM - vn2008.Movimientos M - JOIN vn2008.Tickets t ON t.Id_Ticket = M.Id_Ticket - JOIN vn2008.Consignatarios c ON c.Id_Consigna = t.Id_Consigna - JOIN bi.rotacion r ON M.Id_Article = r.Id_Article - AND t.warehouse_id = r.warehouse_id - JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia - JOIN vn2008.Agencias_province ap ON t.warehouse_id = ap.warehouse_id - AND ap.province_id = c.province_id - AND ap.agency_id = a.agency_id - JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = t.Id_Agencia - AND az.zona = ap.zona - AND t.warehouse_id = az.warehouse_id - AND az.Id_Article = 71 - JOIN vn2008.Cubos cb ON Id_Cubo = 94 - WHERE t.Fecha between datSTART AND datEND - ) vmv ON vmv.Id_Ticket = t.Id_Ticket - WHERE a.is_volumetric - GROUP BY t.Id_Ticket; - - UPDATE tmp.dp - JOIN tmp.dp_aux using(Id_Ticket) - SET teorico = porte; - -DROP TEMPORARY TABLE IF EXISTS tmp.dp_aux; - -CREATE TEMPORARY TABLE tmp.dp_aux - (PRIMARY KEY (Id_Ticket)) - ENGINE = MEMORY - SELECT dp.Id_Ticket, sum(Cantidad * Valor) as valor - FROM tmp.dp - JOIN vn2008.Movimientos m using(Id_Ticket) - JOIN vn2008.Movimientos_componentes mc using(Id_Movimiento) - WHERE mc.Id_Componente = 15 - GROUP BY m.Id_Ticket; - -UPDATE tmp.dp - JOIN tmp.dp_aux using(Id_Ticket) - SET practico = valor; - -DROP TEMPORARY TABLE tmp.dp_aux; - -CREATE TEMPORARY TABLE tmp.dp_aux - (PRIMARY KEY (Id_Ticket)) - ENGINE = MEMORY - SELECT dp.Id_Ticket, sum(Importe) Importe - FROM tmp.dp - JOIN vn2008.Greuges g using(Id_Ticket) - WHERE Greuges_type_id = 1 - GROUP BY Id_Ticket; - -UPDATE tmp.dp - JOIN tmp.dp_aux using(Id_Ticket) - SET greuge = Importe; - - -INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, Greuges_type_id, Id_Ticket) -SELECT t.Id_Cliente - , concat('dif_porte ', dp.Id_Ticket) - , round(teorico - practico - greuge,2) as Importe - , date(t.Fecha) - , 1 - ,t.Id_Ticket - FROM tmp.dp - JOIN vn2008.Tickets t on dp.Id_Ticket = t.Id_Ticket - WHERE ABS(teorico - practico - greuge) > 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 DROP PROCEDURE IF EXISTS `Greuge_Evolution_Add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Greuge_Evolution_Add`() -BEGIN - - /* - - Inserta en la tabla Greuge_Evolution el saldo acumulado de cada cliente, así como las ventas acumuladas en los ultimos 365 dias - , para poder controlar su evolucion - - */ - - DECLARE datFEC DATE; - DECLARE datFEC_TOMORROW DATE; - DECLARE datFEC_LASTYEAR DATE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - - GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; - SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('jgallego@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('pako@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - - END; - - SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; - - INSERT INTO vn2008.daily_task_log(consulta) VALUES('Greuge Evolution Add START'); - - SELECT TIMESTAMPADD(DAY,1,MAX(Fecha)), - TIMESTAMPADD(DAY,2,MAX(Fecha)) - INTO datFEC, - datFEC_TOMORROW - FROM bi.Greuge_Evolution; - - SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); - - DELETE FROM bi.Greuge_Evolution WHERE Fecha >= datFEC; - - DROP TEMPORARY TABLE IF EXISTS maxInvoice; - - CREATE TEMPORARY TABLE maxInvoice - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT DISTINCT Id_Cliente, max(Fecha) as maxFecha - FROM vn2008.Facturas - GROUP BY Id_Cliente - HAVING maxFecha < timestampadd(month,-2,datFEC); - - INSERT INTO vn2008.daily_task_log(consulta) VALUES('Greuge Evolution Add MIDDLE'); - - WHILE datFEC < CURDATE() DO - - REPLACE bi.Greuge_Evolution(Id_Cliente, Fecha, Greuge, Ventas, Fosil) - - SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0 - - FROM - - ( - SELECT Id_Cliente, sum(Importe) as Greuge - FROM vn2008.Greuges - where Fecha <= datFEC - group by Id_Cliente - - ) sub - - RIGHT JOIN - - ( - - SELECT Id_Cliente, sum(Ventas) as Ventas - FROM - ( - - SELECT Id_Cliente, IF (fecha != datFEC, -1,1) * (importe + recargo) as Ventas - FROM bs.ventas - WHERE fecha = datFEC or fecha = datFEC_LASTYEAR - - UNION ALL - - SELECT Id_Cliente, Ventas - FROM bi.Greuge_Evolution - WHERE Fecha = TIMESTAMPADD(DAY, -1, datFEC) - - ) sub - group by Id_Cliente - - ) v using(Id_Cliente) - ; - - - -- Ahora calcularemos el greuge muerto - - - - UPDATE bi.Greuge_Evolution ge - JOIN maxInvoice m using(Id_Cliente) - SET FOSIL = GREUGE - WHERE m.maxFecha < TIMESTAMPADD(MONTH,-2,ge.Fecha); - - - -- Recobro - - UPDATE bi.Greuge_Evolution ge - JOIN ( - SELECT cs.Id_Cliente, sum(Valor * Cantidad) as Importe - FROM vn2008.Tickets t - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket - JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento - WHERE t.Fecha >= datFEC - AND t.Fecha < datFEC_TOMORROW - AND mc.Id_Componente = 17 -- Recobro - GROUP BY cs.Id_Cliente - ) sub using(Id_Cliente) - SET Recobro = Importe - WHERE ge.Fecha = datFEC; - - INSERT INTO vn2008.daily_task_log(consulta) VALUES(CONCAT('Greuge Evolution ',datFEC)); - - SET datFEC = datFEC_TOMORROW; - SET datFEC_TOMORROW = TIMESTAMPADD(DAY,1,datFEC_TOMORROW); - SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); - - - END WHILE; - - DROP TEMPORARY TABLE IF EXISTS maxInvoice; - - INSERT INTO vn2008.daily_task_log(consulta) VALUES('Greuge Evolution Add END'); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `last_buy_id_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `last_buy_id_add`() -BEGIN - --- control --- INSERT INTO vn2008.daily_task_log(consulta) VALUES('bi.last_buy_id_add'); - --- DELETE FROM bi.Last_buy_id; -TRUNCATE TABLE bi.Last_buy_id; - - --- Primero metemos las del futuro, por si no hay en el presente - -INSERT INTO bi.Last_buy_id SELECT * FROM - (SELECT - Id_Article, Id_Compra, warehouse_id - FROM - vn2008.Compres c - JOIN vn2008.Entradas e USING (Id_Entrada) - JOIN vn2008.travel tr ON tr.id = e.travel_id - WHERE - Novincular = FALSE AND tarifa2 > 0 AND NOT Redada - AND landing > curdate() - ORDER BY landing DESC) t1 -GROUP BY Id_Article , warehouse_id; - --- Ahora el presente machaca al futuro - -REPLACE bi.Last_buy_id SELECT * FROM - (SELECT - Id_Article, Id_Compra, warehouse_id - FROM - vn2008.Compres c - JOIN vn2008.Entradas e USING (Id_Entrada) - JOIN vn2008.travel tr ON tr.id = e.travel_id - WHERE - Novincular = FALSE AND tarifa2 > 0 AND NOT Redada - AND landing BETWEEN vn2008.date_inv() AND curdate() - ORDER BY landing DESC) t1 -GROUP BY Id_Article , warehouse_id; - - TRUNCATE TABLE bi.Last_buy_idBackUp; - INSERT INTO bi.Last_buy_idBackUp - SELECT * FROM Last_buy_id; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `margenes` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `margenes`() -BEGIN - -TRUNCATE TABLE bi.margenes; - -INSERT INTO bi.margenes -SELECT Id_Article, Cantidad as Unidades, Cantidad * round(nz(Costefijo) + nz(Embalajefijo) + nz(Comisionfija) + nz(Portefijo),3) as Coste , w.name as almacen, month(landing) as Mes, year(landing) as Year, 0 as Venta -FROM vn2008.Compres C -JOIN vn2008.Entradas E using(Id_Entrada) -JOIN vn2008.travel tr on tr.id = travel_id -JOIN vn2008.warehouse w on w.id = tr.warehouse_id -LEFT JOIN vn2008.Articles A using(Id_Article) -JOIN vn2008.Tipos TP using(tipo_id) -WHERE landing between '2013-01-01' and ' 2013-12-31' -AND E.Id_Proveedor <> 4 -AND not redada -AND not inventario -union all -SELECT Id_Article, Cantidad as Unidades, 0 as Coste , w.name, month(Fecha) as Mes, year(Fecha) as Year, Cantidad * round(Preu * (100 - M.Descuento) / 100,2) as Venta -FROM vn2008.Movimientos M -JOIN vn2008.Articles A using(Id_Article) -JOIN vn2008.Tipos TP using(tipo_id) -JOIN vn2008.Tickets T using(Id_Ticket) -JOIN vn2008.Clientes C using(Id_Cliente) -JOIN vn2008.warehouse w on w.id = warehouse_id -WHERE Fecha between '2013-01-01' and ' 2013-12-31' -AND (Id_Cliente = 31 or invoice) -AND Id_Cliente NOT IN (2066,2067,2068); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nightly_tasks` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nightly_tasks`() -BEGIN - -call bi.analisis_ventas_evolution_add; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `nigthlyAnalisisVentas` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nigthlyAnalisisVentas`() -BEGIN - - INSERT INTO vn2008.daily_task_log(consulta) VALUES('analisis ventas START'); - - CALL bi.analisis_ventas_update; - CALL bi.analisis_ventas_simple; - CALL bi.analisis_ventas_evolution_add; - - INSERT INTO vn2008.daily_task_log(consulta) VALUES('analisis ventas END'); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `partitioning` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `partitioning`(IN intyear INT) -BEGIN - - DECLARE v_sql TEXT; - DECLARE strSquemaName VARCHAR(10); - DECLARE strTableName VARCHAR(20); - DECLARE strFieldName VARCHAR(20); - DECLARE strDateField VARCHAR(20); - DECLARE strTableDependingOn VARCHAR(20); - DECLARE strFieldDependingOn VARCHAR(20); - DECLARE done BIT DEFAULT 0; - DECLARE strCacheSchema VARCHAR(5); - DECLARE dat_start,dat_end DATE; - DECLARE cur1 CURSOR FOR - SELECT `schema_name`,`table_name` FROM `cache`.partitioning_information ORDER BY execution_order; - DECLARE cur2 CURSOR FOR - SELECT `schema_name`,`table_name`,`date_field` FROM `cache`.partitioning_information WHERE date_field > '' ORDER BY execution_order; - DECLARE cur3 CURSOR FOR - SELECT `schema_name`,`table_name`,`table_depending` FROM `cache`.partitioning_information WHERE table_depending > '' ORDER BY execution_order; - DECLARE cur4 CURSOR FOR - SELECT `schema_name`,`table_name`,`table_depending` FROM `cache`.partitioning_information WHERE table_depending > '' ORDER BY execution_order DESC; - DECLARE cur5 CURSOR FOR - SELECT `schema_name`,`table_name`,`date_field` FROM `cache`.partitioning_information WHERE date_field > '' ORDER BY execution_order DESC; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - - SET FOREIGN_KEY_CHECKS=0; - IF LENGTH(intyear) <> 4 THEN - CALL el_año_debe_contener_4_caracteres_yyyy(); - END IF; - SET dat_start = STR_TO_DATE(CONCAT('01,01,',intyear),'%d,%m,%Y'); - SET dat_end = STR_TO_DATE(CONCAT('31,12,',intyear),'%d,%m,%Y'); - SET strCacheSchema = CONCAT('vn_',right(intyear,2)); - SET v_sql = sql_printf ('CREATE SCHEMA IF NOT EXISTS %t',strCacheSchema); - CALL util.exec (v_sql); - - -- Insertamos en las tablas del cur1 - OPEN cur1; - FETCH cur1 INTO strSquemaName,strTableName; - WHILE NOT done DO - SET v_sql = sql_printf ('CREATE TABLE IF NOT EXISTS %t.%t LIKE %t.%t', - strCacheSchema, - strTableName, - strSquemaName, - strTableName); - - CALL util.exec (v_sql); - - FETCH cur1 INTO strSquemaName,strTableName; - - END WHILE; - CLOSE cur1; - - -- Insertamos en las tablas del cur2 - OPEN cur2; - FETCH cur2 INTO strSquemaName,strTableName,strDateField; - WHILE NOT done DO - SET v_sql = sql_printf ('REPLACE INTO %t.%t SELECT * FROM %t.%t WHERE %t BETWEEN %v AND %v', - strCacheSchema, - strTableName, - strSquemaName, - strTableName, - strDateField, - dat_start, - dat_end); - - SELECT v_sql; - CALL util.exec (v_sql); - - FETCH cur2 INTO strSquemaName,strTableName,strDateField; - - END WHILE; - CLOSE cur2; - - -- Insertamos en las tablas del cur3 - OPEN cur3; - SET done = 0; - FETCH cur3 INTO strSquemaName,strTableName,strTableDependingOn; - WHILE NOT done DO - - - -- Torna la columna per la qual vincular amb el seu pare - SELECT kcu.column_name INTO strFieldName - FROM information_schema.key_column_usage kcu - WHERE table_schema = CONVERT(strSquemaName USING utf8) COLLATE utf8_general_ci - AND REFERENCED_TABLE_NAME = CONVERT(strTableDependingOn USING utf8) COLLATE utf8_general_ci - AND table_name = CONVERT(strTableName USING utf8) COLLATE utf8_general_ci; - - -- Torna la columna per la qual vincular amb el seu fill - SELECT kcu.column_name INTO strFieldDependingOn - FROM information_schema.key_column_usage kcu - WHERE table_schema = CONVERT(strSquemaName USING utf8) COLLATE utf8_general_ci -- FIX mirar l'esquema del pare - AND constraint_name = 'PRIMARY' - AND table_name = CONVERT(strTableDependingOn USING utf8) COLLATE utf8_general_ci; - - SET v_sql = sql_printf ('REPLACE INTO %t.%t SELECT a.* FROM %t.%t a JOIN %t.%t b ON a.%t = b.%t', - strCacheSchema, - strTableName, - strSquemaName, - strTableName, - strCacheSchema, - strTableDependingOn, - strFieldName, - strFieldDependingOn); - select v_sql; - CALL util.exec (v_sql); - - FETCH cur3 INTO strSquemaName,strTableName,strTableDependingOn; - END WHILE; - - CLOSE cur3; - - -- Borramos en las tablas del cur4 que es igual que el dos pero en sentido descendente - -- para evitar errores con las foreign key - OPEN cur4; - SET done = 0; - FETCH cur4 INTO strSquemaName,strTableName,strTableDependingOn; - WHILE NOT done DO - - - -- Torna la columna per la qual vincular amb el seu pare - SELECT kcu.column_name INTO strFieldName - FROM information_schema.key_column_usage kcu - WHERE table_schema = CONVERT(strSquemaName USING utf8) COLLATE utf8_general_ci - AND REFERENCED_TABLE_NAME = CONVERT(strTableDependingOn USING utf8) COLLATE utf8_general_ci - AND table_name = CONVERT(strTableName USING utf8) COLLATE utf8_general_ci; - - -- Torna la columna per la qual vincular amb el seu fill - SELECT kcu.column_name INTO strFieldDependingOn - FROM information_schema.key_column_usage kcu - WHERE table_schema = CONVERT(strSquemaName USING utf8) COLLATE utf8_general_ci - AND constraint_name = 'PRIMARY' - AND table_name = CONVERT(strTableDependingOn USING utf8) COLLATE utf8_general_ci; - - SELECT v_sql; - SET v_sql = sql_printf ('DELETE a.* FROM %t.%t a JOIN %t.%t b ON a.%t = b.%t', - strSquemaName, - strTableName, - strCacheSchema, - strTableDependingOn, - strFieldName, - strFieldDependingOn); - CALL util.exec (v_sql); - - FETCH cur4 INTO strSquemaName,strTableName,strTableDependingOn; - END WHILE; - - CLOSE cur4; - - -- Borramos en las tablas del cur5 - OPEN cur5; - SET done = 0; - FETCH cur5 INTO strSquemaName,strTableName,strDateField; - WHILE NOT done DO - - SET v_sql = sql_printf ('DELETE FROM %t WHERE %t BETWEEN %v AND %v', - strTableName, - strDateField, - dat_start, - dat_end); - CALL util.exec (v_sql); - - FETCH cur5 INTO strSquemaName,strTableName,strDateField; - - END WHILE; - CLOSE cur5; - SET FOREIGN_KEY_CHECKS=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 DROP PROCEDURE IF EXISTS `primer_pedido_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `primer_pedido_add`() -BEGIN - INSERT IGNORE INTO bi.primer_pedido(Id_Ticket, Id_Cliente, month, year, total) - SELECT * - FROM - (SELECT - `m`.`Id_Ticket` , - `v`.`Id_Cliente` , - `t`.`month`, - `t`.`year`, - v.importe + v.recargo as total - FROM - bs.ventas v - JOIN - vn2008.Movimientos m on m.Id_Movimiento = v.Id_Movimiento - JOIN - vn2008.time t on t.date = v.fecha - WHERE - fecha > CURDATE() + INTERVAL -(1) YEAR - ORDER BY fecha) `s` - GROUP BY `s`.`Id_Cliente`; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `regularidad` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `regularidad`() -BEGIN - -select Id_Cliente, Meses, IF(Antiguedad = 13,12,Antiguedad) , Meses / IF(Antiguedad = 13,12,Antiguedad) as Regularidad from ( -SELECT Id_Cliente, count(*) as Meses, FLOOR(DATEDIFF('2012-07-31', IF(Created < '2011-08-01','2011-08-01', Created)) / 30) +1 as Antiguedad from -( - -SELECT DISTINCT Id_Cliente, Periodo(Fecha) as periodo from Facturas -where Fecha between '2011-08-01' AND '2012-07-31' - -) sub - -join Clientes using(Id_Cliente) -where Created <= '2012-07-31' - -group by Id_Cliente -having Antiguedad > 0 - -) sub44 -order by Antiguedad ; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `rotacion_update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `rotacion_update`() -BEGIN - --- control -INSERT INTO vn2008.daily_task_log(consulta) VALUES('bi.rotation_update'); - --- Sólo hace la consulta gorda los sábados de madrugada. Necesita casi dos horas. - - call rotacion_update_manual(1, 999999, TIMESTAMPADD(WEEK,-1,CURDATE()), CURDATE()) ; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `rotacion_update_manual` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `rotacion_update_manual`(IN intART_DESDE INT, IN intART_HASTA INT, IN datSTART DATE, IN datEND DATE) -BEGIN - - -DECLARE intLAPSO INT DEFAULT DATEDIFF(datEND,datSTART ); - - - - - REPLACE bi.rotacion(Id_Article,warehouse_id,total,rotacion) - SELECT Id_Article, warehouse_id, Total, round((sum(Saldo_Ponderado)/Total),2) as rotacion -- round(avg(Saldo_Ponderado) / (Total / intLAPSO),1) as Rotacion - FROM - ( - SELECT Id_Article, warehouse_id, - @intervalo:= IF(warehouse_id = @wh AND Id_Article = @art , DATEDIFF(Fecha, @fec),1) as Dias, - IF(warehouse_id = @wh AND Id_Article = @art , IF(@sd < 0,0,@sd) * @intervalo, IF(Unidades<0,0,Unidades)) as Saldo_Ponderado, - IF(warehouse_id = @wh AND Id_Article = @art , @sd:= @sd + Unidades, @sd:= Unidades) as Saldo - - , @fec:= Fecha, @art:= Id_Article, @wh:= warehouse_id - FROM - ( - SELECT Id_Article, landing as Fecha, sum(Cantidad) as Unidades, warehouse_id, @fec:= datSTART, @art := 0, @d := 0, @sd:= 0, @wh := 0, @intervalo := 0 - FROM - ( - SELECT Id_Article, landing, Cantidad, warehouse_id - FROM vn2008.Compres C - JOIN vn2008.Entradas E using(Id_Entrada) - JOIN vn2008.Articles A using(Id_Article) - JOIN vn2008.Tipos tp ON tp.tipo_id = A.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id - JOIN vn2008.travel tr on tr.id = travel_id - JOIN vn2008.warehouse w on w.id = tr.warehouse_id - WHERE landing between datSTART and datEND - AND Id_Article between intART_DESDE and intART_HASTA - AND Id_Proveedor <> 4 - AND r.display <> 0 - AND NOT E.Inventario - AND NOT fuente - AND NOT redada - UNION ALL - SELECT Id_Article, shipment, -Cantidad, warehouse_id_out - FROM vn2008.Compres C - JOIN vn2008.Entradas E using(Id_Entrada) - JOIN vn2008.Articles A using(Id_Article) - JOIN vn2008.Tipos tp ON tp.tipo_id = A.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id - JOIN vn2008.travel tr on tr.id = travel_id - JOIN vn2008.warehouse w on w.id = tr.warehouse_id_out - WHERE shipment between datSTART and datEND - AND Id_Article between intART_DESDE and intART_HASTA - AND Id_Proveedor <> 4 - AND r.display <> 0 - AND NOT fuente - AND NOT E.Inventario - AND NOT redada - UNION ALL - SELECT Id_Article, date(Fecha), -Cantidad, warehouse_id - FROM vn2008.Movimientos M - JOIN vn2008.Articles A using(Id_Article) - JOIN vn2008.Tipos tp ON tp.tipo_id = A.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id - JOIN vn2008.Tickets t using(Id_Ticket) - JOIN vn2008.warehouse w on w.id = t.warehouse_id - WHERE Fecha between datSTART and datEND - AND r.display <> 0 - AND NOT fuente - AND Id_Article between intART_DESDE and intART_HASTA - AND Id_Cliente NOT IN (2066,2067,2068) - ) sub - GROUP BY Id_Article, warehouse_id, Fecha - ) sub2 - ) sub4 - JOIN - ( - SELECT Id_Article, sum(Cantidad) as Total, warehouse_id - FROM vn2008.Compres C - JOIN vn2008.Entradas E using(Id_Entrada) - JOIN vn2008.Articles A using(Id_Article) - JOIN vn2008.Tipos tp ON tp.tipo_id = A.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id - JOIN vn2008.travel tr on tr.id = travel_id - JOIN vn2008.warehouse w on w.id = tr.warehouse_id - WHERE landing between datSTART and datEND - AND Id_Article between intART_DESDE and intART_HASTA - AND Id_Proveedor <> 4 - AND NOT E.Inventario - AND r.display <> 0 - AND NOT redada - AND NOT fuente - GROUP BY Id_Article, warehouse_id - ) sub3 using(Id_Article, warehouse_id) - - GROUP BY Id_Article, warehouse_id; - - - - CALL vn2008.item_last_buy_(NULL,datSTART); - - -- Añadimos el volumen por unidad de venta - update bi.rotacion r - JOIN vn2008.t_item_last_buy b ON r.Id_Article = b.item_id AND r.warehouse_id = b.warehouse_id - join vn2008.Compres ON Id_Compra = b.buy_id - set cm3 = vn2008.cm3_2(Id_Cubo, r.Id_Article) / Packing - where r.Id_Article between intART_DESDE and intART_HASTA; - --- Añadimos el coste de almacenamiento y manipulacion -UPDATE bi.rotacion -JOIN ( - SELECT warehouse_id, sum(total*rotacion*cm3) as Operacion - FROM bi.rotacion - WHERE Id_Article between intART_DESDE and intART_HASTA - GROUP BY warehouse_id - ) sub using(warehouse_id) - -JOIN ( - SELECT warehouse_id, sum(Valor) as Coste_Auxiliar - FROM bi.tarifa_warehouse - WHERE Id_Premisa = 1 - GROUP BY warehouse_id - ) sub2 using(warehouse_id) - -JOIN ( - SELECT warehouse_id, sum(Valor) as Coste_Operativo - FROM bi.tarifa_warehouse - WHERE Id_Premisa IN (2,3) - GROUP BY warehouse_id - ) sub3 using(warehouse_id) - -JOIN ( - SELECT warehouse_id, sum(Valor) as Coste_Manipulacion - FROM bi.tarifa_warehouse - WHERE Id_Premisa = 4 - GROUP BY warehouse_id - ) sub4 using(warehouse_id) - -SET auxiliar = if(rotacion < 0,0,round(rotacion *cm3 * Coste_Auxiliar / Operacion,4)) - ,almacenaje = if(rotacion < 0,0,round(rotacion *cm3 * Coste_Operativo / Operacion,4)) - , manipulacion = if(rotacion < 0,0,round(rotacion *cm3 * Coste_Manipulacion / Operacion,4)) - WHERE Id_Article between intART_DESDE and intART_HASTA; - - --- Añadimos todos los productos de los que no tenemos histórico, con la media de su familia como valor por defecto - -INSERT INTO bi.rotacion(Id_Article, warehouse_id, rotacion, cm3, almacenaje, manipulacion, auxiliar, mermas) -SELECT a.Id_Article, warehouse_id, rotacion_m, cm3_m, alm_m, man_m, aux_m, merm_m -FROM vn2008.Articles a -JOIN (SELECT tipo_id, warehouse_id, Id_Tipo, avg(rotacion) rotacion_m, avg(cm3) cm3_m, avg(almacenaje) alm_m, avg(manipulacion) man_m - , avg(auxiliar) aux_m, avg(mermas) merm_m - from bi.rotacion - join vn2008.Articles a using(Id_Article) - join vn2008.Tipos tp using(tipo_id) - group by tipo_id, warehouse_id) sub using(tipo_id) - -WHERE a.Id_Article between intART_DESDE and intART_HASTA -ON DUPLICATE KEY UPDATE rotacion = rotacion; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `rotacion_update_manual_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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `rotacion_update_manual_PCA`(IN datSTART DATE, IN datEND DATE) -BEGIN - - -DECLARE intLAPSO INT DEFAULT DATEDIFF(datEND,datSTART ); -DECLARE intART_DESDE BIGINT DEFAULT 1; -DECLARE intART_HASTA BIGINT DEFAULT 100; - -WHILE intART_HASTA < 999999 DO - - IF intART_HASTA MOD 1000 = 0 THEN - - SELECT intART_HASTA; - - END IF; - - REPLACE bi.rotacion(Id_Article,warehouse_id,total,rotacion) - SELECT Id_Article, warehouse_id, Total, round((sum(Saldo_Ponderado)/Total),2) as rotacion -- round(avg(Saldo_Ponderado) / (Total / intLAPSO),1) as Rotacion - FROM - ( - SELECT Id_Article, warehouse_id, - @intervalo:= IF(warehouse_id = @wh AND Id_Article = @art , DATEDIFF(Fecha, @fec),1) as Dias, - IF(warehouse_id = @wh AND Id_Article = @art , IF(@sd < 0,0,@sd) * @intervalo, IF(Unidades<0,0,Unidades)) as Saldo_Ponderado, - IF(warehouse_id = @wh AND Id_Article = @art , @sd:= @sd + Unidades, @sd:= Unidades) as Saldo - - , @fec:= Fecha, @art:= Id_Article, @wh:= warehouse_id - FROM - ( - SELECT Id_Article, landing as Fecha, sum(Cantidad) as Unidades, warehouse_id, @fec:= datSTART, @art := 0, @d := 0, @sd:= 0, @wh := 0, @intervalo := 0 - FROM - ( - SELECT Id_Article, landing, Cantidad, warehouse_id - FROM vn2008.Compres C - JOIN vn2008.Entradas E using(Id_Entrada) - JOIN vn2008.Articles A using(Id_Article) - JOIN vn2008.Tipos using(tipo_id) - JOIN vn2008.travel tr on tr.id = travel_id - JOIN vn2008.warehouse w on w.id = tr.warehouse_id - WHERE landing between datSTART and datEND - AND warehouse_id = 44 - AND Id_Article between intART_DESDE and intART_HASTA - AND Id_Proveedor <> 4 - AND reino_id IN (3,4) - AND NOT E.Inventario - AND NOT fuente - AND NOT redada - UNION ALL - SELECT Id_Article, shipment, -Cantidad, warehouse_id_out - FROM vn2008.Compres C - JOIN vn2008.Entradas E using(Id_Entrada) - JOIN vn2008.Articles A using(Id_Article) - JOIN vn2008.Tipos using(tipo_id) - JOIN vn2008.travel tr on tr.id = travel_id - JOIN vn2008.warehouse w on w.id = tr.warehouse_id_out - WHERE shipment between datSTART and datEND - AND warehouse_id_out = 44 - AND Id_Article between intART_DESDE and intART_HASTA - AND Id_Proveedor <> 4 - AND reino_id IN (3,4) - AND NOT fuente - AND NOT E.Inventario - AND NOT redada - UNION ALL - SELECT Id_Article, date(Fecha), -Cantidad, warehouse_id - FROM vn2008.Movimientos M - JOIN vn2008.Articles A using(Id_Article) - JOIN vn2008.Tipos using(tipo_id) - JOIN vn2008.Tickets t using(Id_Ticket) - JOIN vn2008.warehouse w on w.id = t.warehouse_id - WHERE Fecha between datSTART and datEND - AND t.warehouse_id = 44 - AND reino_id IN (3,4) - AND NOT fuente - AND Id_Article between intART_DESDE and intART_HASTA - AND Id_Cliente NOT IN (2066,2067,2068) - ) sub - GROUP BY Id_Article, warehouse_id, Fecha - ) sub2 - ) sub4 - JOIN - ( - SELECT Id_Article, sum(Cantidad) as Total, warehouse_id - FROM vn2008.Compres C - JOIN vn2008.Entradas E using(Id_Entrada) - JOIN vn2008.Articles A using(Id_Article) - JOIN vn2008.Tipos using(tipo_id) - JOIN vn2008.travel tr on tr.id = travel_id - JOIN vn2008.warehouse w on w.id = tr.warehouse_id - WHERE landing between datSTART and datEND - AND warehouse_id = 44 - AND Id_Article between intART_DESDE and intART_HASTA - AND Id_Proveedor <> 4 - AND NOT E.Inventario - AND reino_id IN (3,4) - AND NOT redada - AND NOT fuente - GROUP BY Id_Article, warehouse_id - ) sub3 using(Id_Article, warehouse_id) - GROUP BY Id_Article, warehouse_id; - -SET intART_DESDE = intART_DESDE + 100; -SET intART_DESDE = intART_HASTA + 100; - -END WHILE; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `rotacion_volumen_update` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`z-developer`@`%` PROCEDURE `rotacion_volumen_update`() -BEGIN - - CALL vn2008.item_last_buy_(NULL,curdate()); - - -- Añadimos el volumen por unidad de venta - update bi.rotacion r - JOIN vn2008.t_item_last_buy b ON r.Id_Article = b.item_id AND r.warehouse_id = b.warehouse_id - join vn2008.Compres ON Id_Compra = b.buy_id - set cm3 = vn2008.cm3_2(Id_Cubo, r.Id_Article) / Packing; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `rutas_m3_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `rutas_m3_add`() -BEGIN - - DECLARE datSTART DATE DEFAULT TIMESTAMPADD(DAY,-90,CURDATE()); - DECLARE datEND DATE DEFAULT CURDATE(); - DECLARE datFEC DATE; - - IF hour(now()) between 5 and 24 then - - SET datSTART = CURDATE(); - SET datEND = TIMESTAMPADD(DAY,1,CURDATE()); - - end if; - - SET datFEC = datSTART; - - CALL vn2008.item_last_buy_(NULL,CURDATE()); - WHILE datFEC <= datEND DO - - UPDATE vn2008.Rutas R - JOIN (SELECT R.Id_Ruta, sum(Cantidad * vn2008.cm3_unidad(b.buy_id)) / 1000000 as m3 - from vn2008.Rutas R - join vn2008.Tickets t using(Id_Ruta) - join vn2008.Movimientos m using(Id_Ticket) - join vn2008.t_item_last_buy b ON Id_Article = b.item_id AND b.warehouse_id = t.warehouse_id - where R.Fecha = datFEC AND R.m3 IS NULL - group by R.Id_Ruta - ) t using(Id_Ruta) - SET R.m3 = t.m3 - WHERE R.m3 IS NULL; - - SET datFEC = TIMESTAMPADD(DAY,1,datFEC); - - END WHILE; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_add2kk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_add2kk`(intNUMDAYS INTEGER) -BEGIN - -DECLARE datSTART,datEND DATETIME; --- Seleccionamos los tickets a tratar añadiendolos a la tabla bi.ticket - - SET @@session.max_sp_recursion_depth=250; -- Habilito la recursión en mysql hasta un límite de 250. - SET datSTART = TIMESTAMPADD(DAY, -intNUMDAYS, CURDATE()); - - - SET datEND = vn2008.DAYEND(datSTART); - - - - - -- Actualiza el valor de costfixat en Movimientos a efectos estadisticos -update vn2008.Movimientos m -join -( -select Id_Movimiento, round(IFNULL(sum(Valor) , IFNULL( Preu * (100 - m.Descuento) /100,0 ) ),2) as Cost -from vn2008.Tickets t -join vn2008.Movimientos m using(Id_Ticket) -left join vn2008.Movimientos_componentes mc using(Id_Movimiento) -join bi.tarifa_componentes tc using(Id_Componente) -join bi.tarifa_componentes_series tcs on tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id AND tcs.base -where t.Fecha between datSTART AND datEND -group by Id_Movimiento -) sub using(Id_Movimiento) -set CostFixat = Cost; - - - - - REPLACE INTO bi.ticket(Id_Ticket,Id_Cliente,`date`, tipo_id, `year`,`week`,`month`,`day`,`view`,amount,Id_Trabajador,Id_propietario ) - SELECT t.Id_Ticket,c.Id_Cliente,t.Fecha `date`,tipo_id, year(Fecha) as `year`, vn2008.vnweek(Fecha) as `week`, - month(Fecha) as `month`,vn2008.vnday(Fecha) as `day`, A.Vista `view`, - IFNULL( round( sum(cantidad * Preu * (100 - m.Descuento)/100) ,2) ,0) as amount, - c.Id_Trabajador, c.Id_Trabajador - FROM vn2008.Tickets t - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.warehouse W ON W.id = t.warehouse_id - INNER JOIN vn2008.Clientes c on cs.Id_Cliente = c.Id_Cliente - INNER JOIN vn2008.Movimientos m USING(Id_Ticket) - INNER JOIN vn2008.Articles USING(Id_Article) - INNER JOIN vn2008.Agencias A on A.Id_Agencia = t.Id_Agencia - INNER JOIN vn2008.Tipos TP USING(tipo_id) - WHERE Fecha BETWEEN datSTART AND datEND - AND NOT W.fuente - AND c.`Real` - AND (reino_id <> 6 OR m.Id_Article IN (95,98)) - GROUP BY t.Id_Ticket,tipo_id ; - - /* - UPDATE bi.ticket - JOIN vn2008.Tickets using(Id_Ticket) - JOIN vn2008.Agencias using(Id_Agencia) - JOIN vn2008.agency_warehouse aw using(agency_id,warehouse_id) - SET `view` = aw.Vista - WHERE Tickets.Fecha BETWEEN datSTART AND datEND; - */ - - - - IF (intNUMDAYS>0) THEN - CALL `bi`.`ticket_add2` (intNUMDAYS-1); - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_addkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_addkk`(intNUMDAYS INTEGER) -BEGIN - -DECLARE datSTART DATETIME; - - IF (intNUMDAYS > 0) THEN - SET datSTART = TIMESTAMPADD(DAY, -intNUMDAYS, CURDATE()); - DELETE FROM bi.ticket where `date` >= datSTART ; - CALL `bi`.`ticket_add2` (intNUMDAYS); - DELETE FROM bi.ticket where `date` < '2001-01-01'; - END IF; - -UPDATE bi.ticket bt -JOIN vn2008.Tickets USING(Id_Ticket) -JOIN vn2008.Consignatarios C USING(Id_Consigna) -SET bt.Id_Cliente = C.Id_Cliente -, bt.Id_Trabajador = @idT := vn2008.Averiguar_ComercialCliente_Id(C.Id_Cliente,bt.date) -, bt.Id_propietario = @idT -WHERE Tickets.Id_Cliente = 31 AND bt.date >= datSTART; - - --- Almacena los tickets que comisionan, para consultas rapidas - -truncate table bi.f_tvc; - -insert into bi.f_tvc -select Id_Ticket -from vn2008.Tickets t -join vn2008.Consignatarios cs using(Id_Consigna) -join vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente -join vn2008.warehouse w on w.id = t.warehouse_id -where c.`Real` = TRUE -and w.comisionantes = TRUE; - - - - --- Quita las horas de los tickets del mes anterior -IF DAY(CURDATE()) = 15 THEN - update vn2008.Tickets - set Fecha = date(Fecha) - where Fecha between TIMESTAMPADD(DAY,-46,CURDATE()) and TIMESTAMPADD(DAY, -1 - DAY(CURDATE()), CURDATE()); - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticket_add_bydaykk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_add_bydaykk`(datFEC DATE) -BEGIN - - DECLARE datSTART DATETIME; - DECLARE datEND DATETIME; - --- Seleccionamos los tickets a tratar añadiendolos a la tabla bi.ticket - - SET @@session.max_sp_recursion_depth=2500; -- Habilito la recursión en mysql hasta un límite de 2500. - - SET datSTART = DATE(datFEC); - SET datEND = TIMESTAMPADD(DAY,30,datSTART); - - DELETE FROM bi.ticket WHERE `date` between datSTART and datEND; - - INSERT INTO bi.ticket(Id_Ticket,`date`, tipo_id, `year`,`week`,`month`,`view`,amount,Id_Trabajador, Id_Cliente, Id_Propietario ) - SELECT t.Id_Ticket,t.Fecha `date`,tipo_id, vn2008.vnyear(Fecha) as `year`, vn2008.vnweek(Fecha) as `week`, - vn2008.vnmonth(Fecha) as `month`, A.Vista `view`, IFNULL(round(sum(cantidad * preu * (100 - m.Descuento)/100),2),0) as amount, - c.Id_Trabajador, c.Id_Cliente, ifnull(c.Id_Trabajador,20) - FROM vn2008.Tickets t - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.warehouse W ON W.id = t.warehouse_id - INNER JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - INNER JOIN vn2008.Movimientos m USING(Id_Ticket) - INNER JOIN vn2008.Articles USING(Id_Article) - INNER JOIN vn2008.Agencias A on A.Id_Agencia = t.Id_Agencia - INNER JOIN vn2008.Tipos TP USING(tipo_id) - LEFT JOIN vn2008.reinos r ON r.id = TP.reino_id - WHERE Fecha >= datSTART - AND Fecha < datEND - AND NOT W.fuente - AND (invoice or t.Id_Cliente in (5,31)) - AND r.display <> 0 - GROUP BY t.Id_Ticket,tipo_id - ON DUPLICATE KEY UPDATE amount = amount, - `view` = `view`, - `date` = `date`, - `week` = `week`, - `year` = `year`, - `month` = `month`, - tipo_id = tipo_id, - Id_Trabajador = Id_Trabajador, - Id_Cliente = Id_Cliente, - Id_Propietario = ifnull(Id_Trabajador,20); - - UPDATE bi.ticket - JOIN vn2008.Tickets using(Id_Ticket) - JOIN vn2008.Agencias using(Id_Agencia) - JOIN vn2008.agency_warehouse aw using(agency_id,warehouse_id) - SET `view` = aw.Vista - WHERE Tickets.Fecha BETWEEN datSTART AND datEND; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Ultima_Accion` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Ultima_Accion`() -BEGIN - -REPLACE INTO bi.lastaction(Id_Cliente, Cliente, Ultima_accion, Comercial) - -SELECT Id_Cliente, Cliente, Ultima_accion, Comercial -FROM vn2008.Clientes -JOIN -( -SELECT Id_Cliente, MAX(calldate) as Ultima_accion, vn2008.Averiguar_ComercialCliente(Id_Cliente, CURDATE()) as Comercial -FROM -( -SELECT Id_Cliente, calldate -FROM vn2008.cdr -JOIN vn2008.Contactos CT on CT.Telefono = dst -JOIN vn2008.Relaciones using(Id_Contacto) -WHERE Id_Cliente IS NOT NULL -AND duration > 30 -UNION ALL -SELECT Id_Cliente, calldate -FROM vn2008.cdr -JOIN vn2008.Contactos CT on CT.Movil = dst -JOIN vn2008.Relaciones using(Id_Contacto) -WHERE Id_Cliente IS NOT NULL -AND duration > 30 -UNION ALL -SELECT Id_Cliente, calldate -FROM vn2008.cdr -JOIN vn2008.Clientes CT on CT.Telefono = dst -WHERE duration > 30 -UNION ALL -SELECT Id_Cliente, calldate -FROM vn2008.cdr -JOIN vn2008.Clientes CT on CT.Movil = dst -WHERE duration > 30 -UNION ALL -SELECT C.Id_Cliente, Fecha -FROM vn2008.Tickets JOIN vn2008.Consignatarios C using(Id_Consigna) -) sub -GROUP BY Id_Cliente ) sub2 USING(Id_Cliente); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `Velocity_Add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `Velocity_Add`() -BEGIN - -DECLARE bol_EXISTS BOOL; -DECLARE datMAX DATETIME; -DECLARE v_buffer VARCHAR(11); -DECLARE v_sql VARCHAR(255); - - - -SELECT MAX(Fecha) INTO datMAX FROM bi.Velocity; - -IF Date(datMAX) = CURDATE() AND hour(datMAX) > hour(now()) THEN - - - SET v_buffer = vn2008.buffer_name(CURDATE(),1); - - SELECT count(*) INTO bol_EXISTS FROM information_schema.`TABLES` - WHERE TABLE_NAME = CONVERT(v_buffer using utf8) collate utf8_general_ci; - - IF bol_EXISTS THEN - - SET v_sql = sql_printf ( - 'INSERT INTO bi.Velocity(tipo_id, Fecha, Disponible, Visible) - SELECT A.tipo_id, NOW(), sum(avalaible), sum(visible) - FROM vn2008.%t b - JOIN Articles A ON b.item_id = A.Id_Article GROUP BY tipo_id; - ', - v_buffer - ); - - - CALL util.exec (v_sql); - - END IF; - -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 */ ; - --- --- Current Database: `pbx` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `pbx` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `pbx`; - --- --- Table structure for table `blacklist` --- - -DROP TABLE IF EXISTS `blacklist`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `blacklist` ( - `phone` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`phone`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Hangup input calls from this list'; -/*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`blacklistBeforeInsert` -BEFORE INSERT ON `blacklist` FOR EACH ROW -BEGIN - CALL phoneIsValid (NEW.phone); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`blacklistBerforeUpdate` -BEFORE UPDATE ON `blacklist` FOR EACH ROW -BEGIN - CALL phoneIsValid (NEW.phone); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- --- Table structure for table `cdr` --- - -DROP TABLE IF EXISTS `cdr`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cdr` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `call_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `clid` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `src` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `dst` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `dcontext` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `channel` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `dst_channel` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `last_app` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `last_data` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `duration` int(11) NOT NULL DEFAULT '0', - `billsec` int(11) NOT NULL DEFAULT '0', - `disposition` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `ama_flags` int(11) NOT NULL DEFAULT '0', - `account_code` varchar(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `unique_id` varchar(32) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `user_field` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - PRIMARY KEY (`id`), - KEY `calldate` (`call_date`), - KEY `dst` (`dst`), - KEY `accountcode` (`account_code`), - KEY `dstchannel` (`dst_channel`), - KEY `disposition` (`disposition`), - KEY `src` (`src`) -) ENGINE=MyISAM AUTO_INCREMENT=185216 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `cdrConf` --- - -DROP TABLE IF EXISTS `cdrConf`; -/*!50001 DROP VIEW IF EXISTS `cdrConf`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `cdrConf` AS SELECT - 1 AS `calldate`, - 1 AS `clid`, - 1 AS `src`, - 1 AS `dst`, - 1 AS `dcontext`, - 1 AS `channel`, - 1 AS `dstchannel`, - 1 AS `lastapp`, - 1 AS `lastdata`, - 1 AS `duration`, - 1 AS `billsec`, - 1 AS `disposition`, - 1 AS `amaflags`, - 1 AS `accountcode`, - 1 AS `uniqueid`, - 1 AS `userfield`*/; -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(10) unsigned NOT NULL AUTO_INCREMENT, - `sundayFestive` tinyint(4) NOT NULL, - `countryPrefix` varchar(20) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `followme` --- - -DROP TABLE IF EXISTS `followme`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `followme` ( - `extension` varchar(128) CHARACTER SET utf8 NOT NULL, - `phone` varchar(20) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`extension`), - CONSTRAINT `followme_ibfk_1` FOREIGN KEY (`extension`) REFERENCES `sip` (`extension`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`followmeBeforeInsert` -BEFORE INSERT ON `followme` FOR EACH ROW -BEGIN - CALL pbx.phoneIsValid (NEW.phone); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`followmeBeforeUpdate` -BEFORE UPDATE ON `followme` FOR EACH ROW -BEGIN - CALL pbx.phoneIsValid (NEW.phone); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- --- Temporary view structure for view `followmeConf` --- - -DROP TABLE IF EXISTS `followmeConf`; -/*!50001 DROP VIEW IF EXISTS `followmeConf`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `followmeConf` AS SELECT - 1 AS `name`, - 1 AS `music`, - 1 AS `context`, - 1 AS `takecall`, - 1 AS `declinecall`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `followmeConfig` --- - -DROP TABLE IF EXISTS `followmeConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `followmeConfig` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `music` varchar(50) CHARACTER SET utf8 DEFAULT NULL, - `context` varchar(50) CHARACTER SET utf8 NOT NULL, - `takeCall` char(1) CHARACTER SET utf8 NOT NULL, - `declineCall` char(1) CHARACTER SET utf8 NOT NULL, - `timeout` int(11) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `followmeNumberConf` --- - -DROP TABLE IF EXISTS `followmeNumberConf`; -/*!50001 DROP VIEW IF EXISTS `followmeNumberConf`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `followmeNumberConf` AS SELECT - 1 AS `name`, - 1 AS `ordinal`, - 1 AS `phonenumber`, - 1 AS `timeout`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `queue` --- - -DROP TABLE IF EXISTS `queue`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `queue` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `description` varchar(128) CHARACTER SET utf8 NOT NULL, - `name` varchar(128) CHARACTER SET utf8 NOT NULL, - `config` int(10) unsigned NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `name` (`name`), - UNIQUE KEY `description` (`description`), - KEY `config` (`config`), - CONSTRAINT `queue_ibfk_1` FOREIGN KEY (`config`) REFERENCES `queueConfig` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Queues'; -/*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`queueBeforeInsert` -BEFORE INSERT ON `queue` FOR EACH ROW -BEGIN - CALL queueIsValid (NEW.name); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`queueBeforeUpdate` -BEFORE UPDATE ON `queue` FOR EACH ROW -BEGIN - CALL queueIsValid (NEW.name); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- --- Temporary view structure for view `queueConf` --- - -DROP TABLE IF EXISTS `queueConf`; -/*!50001 DROP VIEW IF EXISTS `queueConf`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `queueConf` AS SELECT - 1 AS `name`, - 1 AS `strategy`, - 1 AS `timeout`, - 1 AS `retry`, - 1 AS `weight`, - 1 AS `maxlen`, - 1 AS `ringinuse`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `queueConfig` --- - -DROP TABLE IF EXISTS `queueConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `queueConfig` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `strategy` varchar(128) CHARACTER SET utf8 NOT NULL, - `timeout` int(10) unsigned NOT NULL, - `retry` int(10) unsigned NOT NULL, - `weight` int(10) unsigned NOT NULL, - `maxLen` int(10) unsigned NOT NULL, - `ringInUse` tinyint(4) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Default values for queues configuration'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `queueMember` --- - -DROP TABLE IF EXISTS `queueMember`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `queueMember` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `queue` varchar(128) CHARACTER SET utf8 NOT NULL, - `extension` varchar(128) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `queue` (`queue`,`extension`), - KEY `extension` (`extension`), - CONSTRAINT `queueMember_ibfk_1` FOREIGN KEY (`queue`) REFERENCES `queue` (`name`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `queueMember_ibfk_2` FOREIGN KEY (`extension`) REFERENCES `sip` (`extension`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=726 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Queue members'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `queueMemberConf` --- - -DROP TABLE IF EXISTS `queueMemberConf`; -/*!50001 DROP VIEW IF EXISTS `queueMemberConf`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `queueMemberConf` AS SELECT - 1 AS `uniqueid`, - 1 AS `queue_name`, - 1 AS `interface`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `queuePhone` --- - -DROP TABLE IF EXISTS `queuePhone`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `queuePhone` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `queue` varchar(128) CHARACTER SET utf8 NOT NULL, - `phone` varchar(128) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `queue` (`queue`,`phone`), - CONSTRAINT `queuePhone_ibfk_1` FOREIGN KEY (`queue`) REFERENCES `queue` (`name`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=1003 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`queuePhoneBeforeInsert` -BEFORE INSERT ON `queuePhone` FOR EACH ROW -BEGIN - CALL phoneIsValid (NEW.phone); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`queuePhoneBeforeUpdate` -BEFORE UPDATE ON `queuePhone` FOR EACH ROW -BEGIN - CALL phoneIsValid (NEW.phone); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- --- Table structure for table `schedule` --- - -DROP TABLE IF EXISTS `schedule`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `schedule` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `weekDay` tinyint(3) unsigned NOT NULL COMMENT '0 = Monday, 6 = Sunday', - `timeStart` time NOT NULL, - `timeEnd` time NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `sip` --- - -DROP TABLE IF EXISTS `sip`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `sip` ( - `user_id` int(10) unsigned NOT NULL DEFAULT '0', - `extension` varchar(128) CHARACTER SET utf8 NOT NULL, - `secret` varchar(80) CHARACTER SET utf8 NOT NULL, - `caller_id` varchar(80) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`user_id`), - UNIQUE KEY `extension` (`extension`), - CONSTRAINT `sip_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='SIP accounts'; -/*!40101 SET character_set_client = @saved_cs_client */; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`sipBeforeInsert` -BEFORE INSERT ON `sip` FOR EACH ROW -BEGIN - CALL extensionIsValid (NEW.extension); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sipAfterInsert` -AFTER INSERT ON `sip` FOR EACH ROW -BEGIN - INSERT INTO sipReg (userId) VALUES (NEW.user_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 */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`sipBeforeUpdate` -BEFORE UPDATE ON `sip` FOR EACH ROW -BEGIN - CALL extensionIsValid (NEW.extension); -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- --- Temporary view structure for view `sipConf` --- - -DROP TABLE IF EXISTS `sipConf`; -/*!50001 DROP VIEW IF EXISTS `sipConf`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `sipConf` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `secret`, - 1 AS `callerid`, - 1 AS `host`, - 1 AS `deny`, - 1 AS `permit`, - 1 AS `type`, - 1 AS `context`, - 1 AS `incominglimit`, - 1 AS `pickupgroup`, - 1 AS `careinvite`, - 1 AS `ipaddr`, - 1 AS `regseconds`, - 1 AS `port`, - 1 AS `defaultuser`, - 1 AS `useragent`, - 1 AS `lastms`, - 1 AS `fullcontact`, - 1 AS `regserver`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `sipConfig` --- - -DROP TABLE IF EXISTS `sipConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `sipConfig` ( - `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `host` varchar(40) CHARACTER SET utf8 DEFAULT NULL, - `deny` varchar(95) CHARACTER SET utf8 NOT NULL, - `permit` varchar(95) CHARACTER SET utf8 NOT NULL, - `type` enum('user','peer','friend') CHARACTER SET utf8 NOT NULL, - `context` varchar(80) CHARACTER SET utf8 NOT NULL, - `incomingLimit` varchar(10) CHARACTER SET utf8 NOT NULL, - `pickupGroup` varchar(10) CHARACTER SET utf8 NOT NULL, - `careInvite` varchar(10) CHARACTER SET utf8 NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Default values for SIP accounts'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `sipReg` --- - -DROP TABLE IF EXISTS `sipReg`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `sipReg` ( - `userId` int(10) unsigned NOT NULL, - `ipAddr` varchar(40) CHARACTER SET utf8 DEFAULT NULL, - `regSeconds` int(10) unsigned DEFAULT NULL, - `port` varchar(50) CHARACTER SET utf8 DEFAULT NULL, - `defaultUser` varchar(50) CHARACTER SET utf8 DEFAULT NULL, - `userAgent` varchar(80) CHARACTER SET utf8 DEFAULT NULL, - `lastMs` varchar(50) CHARACTER SET utf8 DEFAULT NULL, - `fullContact` varchar(50) CHARACTER SET utf8 DEFAULT NULL, - `regServer` varchar(20) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`userId`), - CONSTRAINT `sipReg_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `sip` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='SIP registrations'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'pbx' --- - --- --- Dumping routines for database 'pbx' --- -/*!50003 DROP FUNCTION IF EXISTS `clientFromPhone` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `clientFromPhone`(vPhone VARCHAR(255)) RETURNS int(11) - DETERMINISTIC -BEGIN - DECLARE vClient INT DEFAULT NULL; - - -- SET vPhone = vPhone COLLATE 'utf8_unicode_ci'; - - -- Searchs a customer associated to the phone number - - DROP TEMPORARY TABLE IF EXISTS tmp.customer; - CREATE TEMPORARY TABLE tmp.customer - ENGINE = MEMORY - SELECT id_cliente customer - FROM vn2008.Clientes c - WHERE telefono = vPhone - OR movil = vPhone - UNION - SELECT id_cliente - FROM vn2008.Consignatarios - WHERE telefono = vPhone - OR movil = vPhone - UNION - SELECT r.id_cliente - FROM vn2008.Relaciones r - JOIN vn2008.Contactos c ON r.Id_Contacto = c.Id_Contacto - WHERE c.telefono = vPhone - OR c.movil = vPhone; - - SELECT t.customer INTO vClient - FROM tmp.customer t - JOIN vn2008.Clientes c ON c.id_cliente = t.customer - WHERE c.activo - LIMIT 1; - - DROP TEMPORARY TABLE tmp.customer; - - RETURN vClient; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `phoneFormat` */; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `phoneFormat`(vPhone VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 -BEGIN - DECLARE vI INT DEFAULT 0; - DECLARE vChr VARCHAR(1); - DECLARE vLen INT DEFAULT LENGTH(vPhone); - DECLARE vNewPhone VARCHAR(255) DEFAULT ''; - - WHILE vI < vLen - DO - SET vChr = SUBSTR(vPhone, vI + 1, 1); - - IF vChr REGEXP '^[0-9]$' - THEN - SET vNewPhone = CONCAT(vNewPhone, vChr); - ELSEIF vChr = '+' AND vI = 0 - THEN - SET vNewPhone = CONCAT(vNewPhone, '00'); - END IF; - - SET vI = vI + 1; - END WHILE; - - IF vNewPhone REGEXP '^0+$' OR vNewPhone = '' THEN - RETURN NULL; - END IF; - - IF vNewPhone REGEXP '^0034' THEN - SET vNewPhone = SUBSTR(vNewPhone, 5); - END IF; - - RETURN vNewPhone; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `extensionIsValid` */; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `extensionIsValid`(vExtension VARCHAR(255)) - DETERMINISTIC -BEGIN - DECLARE vIsValid BOOLEAN; - - SET vIsValid = vExtension IS NULL - OR (vExtension REGEXP '^[0-9]{4}$' - AND MOD(vExtension, 100) != 0); - - IF NOT vIsValid - THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'EXTENSION_INVALID_FORMAT'; - 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 */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `phoneIsValid` */; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `phoneIsValid`(vPhone VARCHAR(255)) -BEGIN - DECLARE vIsValid BOOLEAN; - - SET vIsValid = vPhone IS NULL - OR (vPhone REGEXP '^[0-9]+$' - AND vPhone NOT REGEXP '^0+$' - AND vPhone NOT REGEXP '^0034'); - - IF NOT vIsValid - THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'PHONE_INVALID_FORMAT'; - 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 */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `queueIsValid` */; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `queueIsValid`(vQueue VARCHAR(255)) - DETERMINISTIC -BEGIN - DECLARE vIsValid BOOLEAN; - - SET vIsValid = vQueue IS NULL - OR vQueue REGEXP '^[1-9][0-9]00$'; - - IF NOT vIsValid - THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'QUEUE_INVALID_FORMAT'; - 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 */ ; -ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- --- Current Database: `cache` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `cache` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `cache`; - --- --- Table structure for table `available` --- - -DROP TABLE IF EXISTS `available`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `available` ( - `calc_id` int(10) unsigned NOT NULL, - `item_id` int(11) NOT NULL, - `available` int(11) NOT NULL, - KEY `calc_id_4` (`calc_id`) USING BTREE, - KEY `calc_id` (`item_id`,`calc_id`) -) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `barcodes` --- - -DROP TABLE IF EXISTS `barcodes`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `barcodes` ( - `code` varchar(22) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', - `Id_Article` int(11) NOT NULL DEFAULT '0', - `Article` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `Medida` int(10) unsigned DEFAULT NULL, - `Color` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `Categoria` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, - `Producer` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`code`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cache` --- - -DROP TABLE IF EXISTS `cache`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cache` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(50) CHARACTER SET utf8 NOT NULL, - `lifetime` time NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `name` (`name`) -) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cache_calc` --- - -DROP TABLE IF EXISTS `cache_calc`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cache_calc` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `cache_id` int(10) unsigned NOT NULL, - `cacheName` varchar(255) CHARACTER SET utf8 DEFAULT NULL, - `params` varchar(100) CHARACTER SET utf8 NOT NULL DEFAULT '', - `last_refresh` datetime DEFAULT NULL, - `expires` datetime DEFAULT NULL, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `connection_id` int(10) unsigned DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `cache_name` (`cache_id`,`params`), - KEY `cache_id` (`cache_id`), - KEY `cacheName` (`cacheName`), - KEY `expires` (`expires`) -) ENGINE=InnoDB AUTO_INCREMENT=91572 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cache_valid` --- - -DROP TABLE IF EXISTS `cache_valid`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cache_valid` ( - `valid` tinyint(3) unsigned NOT NULL -) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `dailyTaskLog` --- - -DROP TABLE IF EXISTS `dailyTaskLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `dailyTaskLog` ( - `state` varchar(250) COLLATE utf8_unicode_ci NOT NULL, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='No he encontrado el lugar en el que vicente almacena la hora en que se ejecutan las daily tasks, asi que he hecho esta tabla, a eliminar cuando se considere oportuno'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `departure_limit` --- - -DROP TABLE IF EXISTS `departure_limit`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `departure_limit` ( - `warehouse_id` smallint(6) unsigned NOT NULL, - `fecha` date NOT NULL, - `hora` int(11) NOT NULL DEFAULT '0', - `minSpeed` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`warehouse_id`,`fecha`), - CONSTRAINT `warehouse_departure` FOREIGN KEY (`warehouse_id`) REFERENCES `vn2008`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `equalizator` --- - -DROP TABLE IF EXISTS `equalizator`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `equalizator` ( - `warehouse_id` int(11) NOT NULL, - `Vista` int(11) NOT NULL, - `Pedido` int(11) DEFAULT NULL, - `Impreso` int(11) DEFAULT NULL, - `Encajado` int(11) DEFAULT NULL, - PRIMARY KEY (`Vista`,`warehouse_id`) -) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `itemTagFormat` --- - -DROP TABLE IF EXISTS `itemTagFormat`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `itemTagFormat` ( - `itemFk` int(11) NOT NULL, - `labels1` varchar(80) CHARACTER SET utf8 DEFAULT NULL, - `values1` varchar(80) CHARACTER SET utf8 DEFAULT NULL, - `labels2` varchar(80) CHARACTER SET utf8 DEFAULT NULL, - `values2` varchar(80) CHARACTER SET utf8 DEFAULT NULL, - `description` varchar(255) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`itemFk`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena el formato para los tags de los articulos'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `item_range` --- - -DROP TABLE IF EXISTS `item_range`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `item_range` ( - `calc_id` int(11) NOT NULL, - `item_id` int(11) NOT NULL, - `date_end` datetime DEFAULT NULL, - KEY `calc_item` (`calc_id`,`item_id`), - KEY `calc_id` (`calc_id`) USING BTREE -) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `last_buy` --- - -DROP TABLE IF EXISTS `last_buy`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `last_buy` ( - `item_id` int(10) unsigned NOT NULL, - `warehouse_id` smallint(5) unsigned NOT NULL, - `buy_id` int(10) unsigned DEFAULT NULL, - `landing` date DEFAULT NULL, - KEY `buy_id` (`buy_id`), - KEY `item_id` (`item_id`,`warehouse_id`), - KEY `warehouse_id` (`warehouse_id`) USING BTREE -) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `prod_graphic_source` --- - -DROP TABLE IF EXISTS `prod_graphic_source`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `prod_graphic_source` ( - `m3` double NOT NULL DEFAULT '0', - `warehouse_id` int(11) NOT NULL, - `hora` int(11) NOT NULL, - `order` int(11) NOT NULL DEFAULT '0', - `alert_level` int(11) NOT NULL DEFAULT '0', - `Agencia` varchar(45) CHARACTER SET utf8 NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `stock` --- - -DROP TABLE IF EXISTS `stock`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `stock` ( - `warehouse_id` smallint(5) unsigned NOT NULL, - `item_id` int(10) unsigned NOT NULL, - `amount` int(11) NOT NULL, - KEY `warehouse_id` (`warehouse_id`,`item_id`), - KEY `warehouse_id_2` (`warehouse_id`) USING BTREE -) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `visible` --- - -DROP TABLE IF EXISTS `visible`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `visible` ( - `calc_id` int(10) unsigned NOT NULL, - `item_id` int(11) NOT NULL, - `visible` int(11) NOT NULL, - KEY `id` (`calc_id`) USING BTREE, - KEY `calc_id` (`calc_id`,`item_id`) -) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `weekly_sales` --- - -DROP TABLE IF EXISTS `weekly_sales`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `weekly_sales` ( - `week` int(10) unsigned NOT NULL, - `item_id` int(10) unsigned NOT NULL, - `warehouse_id` smallint(5) unsigned NOT NULL, - `amount` int(11) NOT NULL, - `price` double NOT NULL, - KEY `item_id` (`item_id`,`warehouse_id`), - KEY `week` (`week`) USING BTREE -) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'cache' --- -/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `barcodes_update` */; -DELIMITER ;; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8 */ ;; -/*!50003 SET character_set_results = utf8 */ ;; -/*!50003 SET collation_connection = utf8_general_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `barcodes_update` ON SCHEDULE EVERY 1 HOUR STARTS '2016-08-17 00:00:00' ON COMPLETION NOT PRESERVE ENABLE DO CALL barcodes_update() */ ;; -/*!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 */ ;; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;; -/*!50106 DROP EVENT IF EXISTS `cacheCalcClean` */;; -DELIMITER ;; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `cacheCalcClean` ON SCHEDULE EVERY 30 MINUTE STARTS '2017-01-23 13:15:58' ON COMPLETION NOT PRESERVE ENABLE DO CALL cacheCalcClean() */ ;; -/*!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 */ ;; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;; -DELIMITER ; -/*!50106 SET TIME_ZONE= @save_time_zone */ ; - --- --- Dumping routines for database 'cache' --- -/*!50003 DROP PROCEDURE IF EXISTS `available_refresh` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `available_refresh`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT, v_date DATE) -proc: BEGIN - DECLARE v_date_ini DATE; - DECLARE v_date_end DATETIME; - DECLARE v_reserve_date DATETIME; - DECLARE v_params CHAR(100); - DECLARE v_date_inv DATE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - CALL cache_calc_unlock (v_calc); - RESIGNAL; - END; - - IF v_date < CURDATE() - THEN - LEAVE proc; - END IF; - - CALL vn2008.item_stock (v_warehouse, v_date, NULL); - - SET v_params = CONCAT_WS('/', v_warehouse, v_date); - CALL cache_calc_start (v_calc, v_refresh, 'available', v_params); - - IF !v_refresh - THEN - LEAVE proc; - END IF; - - -- Limpia las caches antiguas - - DELETE a - FROM available a - LEFT JOIN cache_calc c ON c.id = a.calc_id - WHERE c.id IS NULL; - - -- Calcula algunos parámetros necesarios - - SET v_date_ini = TIMESTAMP(v_date, '00:00:00'); - SET v_date_end = TIMESTAMP(TIMESTAMPADD(DAY, 4, v_date), '23:59:59'); - - SELECT FechaInventario INTO v_date_inv FROM vn2008.tblContadores; - - SELECT SUBTIME(NOW(), reserveTime) INTO v_reserve_date - FROM hedera.orderConfig; - - -- Calcula el ultimo dia de vida para cada producto - - DROP TEMPORARY TABLE IF EXISTS item_range; - CREATE TEMPORARY TABLE item_range - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT c.item_id, IF(t.life IS NULL, NULL, TIMESTAMP(TIMESTAMPADD(DAY, t.life, c.landing), '23:59:59')) AS date_end - FROM ( - SELECT c.Id_Article item_id, MAX(landing) landing - FROM vn2008.Compres c - JOIN vn2008.Entradas e ON c.Id_Entrada = e.Id_Entrada - JOIN vn2008.travel t ON t.id = e.travel_id - JOIN vn2008.warehouse w ON w.id = t.warehouse_id - WHERE t.landing BETWEEN v_date_inv AND v_date_ini - AND t.warehouse_id = v_warehouse - AND NOT e.Inventario - AND NOT e.Redada - GROUP BY Id_Article - ) c - JOIN vn2008.Articles a ON a.Id_Article = c.item_id - JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - HAVING date_end >= v_date_ini OR date_end IS NULL; -/* - -- Tabla con el ultimo dia de precios fijados para cada producto que hace un replace de la anterior - - DROP TEMPORARY TABLE IF EXISTS item_range_copy; - CREATE TEMPORARY TABLE item_range_copy LIKE item_range; - INSERT INTO item_range_copy - SELECT * FROM item_range; - - REPLACE item_range - SELECT item_id, TIMESTAMP(date_end, '23:59:59') date_end FROM ( - SELECT p.item_id, p.date_end - FROM vn2008.price_fixed p - LEFT JOIN item_range_copy i USING(item_id) - WHERE IFNULL(i.date_end,v_date_ini) BETWEEN p.date_start AND p.date_end - AND warehouse_id IN (0, v_warehouse) - ORDER BY item_id, warehouse_id DESC, date_end DESC - ) t GROUP BY item_id; - - DROP TEMPORARY TABLE item_range_copy; -*/ - -- Replica la tabla item_range para poder usarla varias veces en la misma consulta - - DROP TEMPORARY TABLE IF EXISTS item_range_copy1; - CREATE TEMPORARY TABLE item_range_copy1 LIKE item_range; - INSERT INTO item_range_copy1 - SELECT * FROM item_range; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy2; - CREATE TEMPORARY TABLE item_range_copy2 LIKE item_range; - INSERT INTO item_range_copy2 - SELECT * FROM item_range; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy3; - CREATE TEMPORARY TABLE item_range_copy3 LIKE item_range; - INSERT INTO item_range_copy3 - SELECT * FROM item_range; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy4; - CREATE TEMPORARY TABLE item_range_copy4 LIKE item_range; - INSERT INTO item_range_copy4 - SELECT * FROM item_range; - - -- Calcula el ATP - - DELETE FROM available WHERE calc_id = v_calc; - - INSERT INTO available (calc_id, item_id, available) - SELECT v_calc, t.item_id, SUM(stock) amount FROM ( - SELECT ti.item_id, stock - FROM vn2008.tmp_item ti - JOIN item_range ir ON ir.item_id = ti.item_id - UNION ALL - SELECT t.item_id, minacum(dt, amount, v_date) AS available FROM ( - SELECT item_id, DATE(dat) dt, SUM(amount) amount FROM ( - SELECT i.item_id, i.dat, i.amount - FROM vn2008.item_out i - JOIN item_range_copy1 ir ON ir.item_id = i.item_id - WHERE i.dat >= v_date_ini - AND (ir.date_end IS NULL OR i.dat <= ir.date_end) - AND i.warehouse_id = v_warehouse - UNION ALL - SELECT i.item_id, i.dat, i.amount - FROM vn2008.item_entry_in i - JOIN item_range_copy2 ir ON ir.item_id = i.item_id - WHERE i.dat >= v_date_ini - AND (ir.date_end IS NULL OR i.dat <= ir.date_end) - AND i.warehouse_id = v_warehouse - UNION ALL - SELECT i.item_id, i.dat, i.amount - FROM vn2008.item_entry_out i - JOIN item_range_copy3 ir ON ir.item_id = i.item_id - WHERE i.dat >= v_date_ini - AND (ir.date_end IS NULL OR i.dat <= ir.date_end) - AND i.warehouse_id = v_warehouse - UNION ALL - SELECT r.item_id, r.shipment, -r.amount - FROM hedera.order_row r - JOIN hedera.`order` o ON o.id = r.order_id - JOIN item_range_copy4 ir ON ir.item_id = r.item_id - WHERE r.shipment >= v_date_ini - AND (ir.date_end IS NULL OR r.shipment <= ir.date_end) - AND r.warehouse_id = v_warehouse - AND r.created >= v_reserve_date - AND NOT o.confirmed - ) t - GROUP BY item_id, dt - ) t - GROUP BY t.item_id - ) t GROUP BY t.item_id HAVING amount != 0; - - - DROP TEMPORARY TABLE - vn2008.tmp_item - ,item_range - ,item_range_copy1 - ,item_range_copy2 - ,item_range_copy3 - ,item_range_copy4; - - CALL cache_calc_end (v_calc); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `available_refreshtest` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `available_refreshtest`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT, v_date DATE) -proc: BEGIN - DECLARE v_date_ini DATE; - DECLARE v_date_end DATETIME; - DECLARE v_reserve_date DATETIME; - DECLARE v_params CHAR(100); - DECLARE v_date_inv DATE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - CALL cache_calc_unlock (v_calc); - RESIGNAL; - END; - - IF v_date < CURDATE() - THEN - LEAVE proc; - END IF; - - CALL vn2008.item_stock (v_warehouse, v_date, NULL); - - SET v_params = CONCAT_WS('/', v_warehouse, v_date); - CALL cache_calc_start (v_calc, v_refresh, 'available', v_params); - - IF !v_refresh - THEN - LEAVE proc; - END IF; - - -- Limpia las caches antiguas - - IF TRUE -- GET_LOCK('available/clean', 1) - THEN - DELETE FROM available WHERE calc_id NOT IN ( - SELECT cc.id - FROM `cache` c - JOIN cache_calc cc ON c.id = cc.cache_id - WHERE c.`name` = 'available'); - - -- DO RELEASE_LOCK('available/clean'); - END IF; - - -- Calcula algunos parámetros necesarios - - SET v_date_ini = TIMESTAMP(v_date, '00:00:00'); - SET v_date_end = TIMESTAMP(TIMESTAMPADD(DAY, 4, v_date), '23:59:59'); - - SELECT FechaInventario INTO v_date_inv FROM vn2008.tblContadores; - - SELECT SUBTIME(NOW(), reserveTime) INTO v_reserve_date - FROM hedera.orderConfig; - - -- Calcula el ultimo dia de vida para cada producto - - DROP TEMPORARY TABLE IF EXISTS item_range; - CREATE TEMPORARY TABLE item_range - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT c.item_id, IF(t.life IS NULL, NULL, TIMESTAMP(TIMESTAMPADD(DAY, t.life, c.landing), '23:59:59')) AS date_end - FROM ( - SELECT c.Id_Article item_id, MAX(landing) landing - FROM vn2008.Compres c - JOIN vn2008.Entradas e ON c.Id_Entrada = e.Id_Entrada - JOIN vn2008.travel t ON t.id = e.travel_id - JOIN vn2008.warehouse w ON w.id = t.warehouse_id - WHERE t.landing BETWEEN v_date_inv AND v_date_ini - AND t.warehouse_id = v_warehouse - AND NOT e.Inventario - AND NOT e.Redada - GROUP BY Id_Article - ) c - JOIN vn2008.Articles a ON a.Id_Article = c.item_id - JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - HAVING date_end >= v_date_ini OR date_end IS NULL; -/* - -- Tabla con el ultimo dia de precios fijados para cada producto que hace un replace de la anterior - - DROP TEMPORARY TABLE IF EXISTS item_range_copy; - CREATE TEMPORARY TABLE item_range_copy LIKE item_range; - INSERT INTO item_range_copy - SELECT * FROM item_range; - - REPLACE item_range - SELECT item_id, TIMESTAMP(date_end, '23:59:59') date_end FROM ( - SELECT p.item_id, p.date_end - FROM vn2008.price_fixed p - LEFT JOIN item_range_copy i USING(item_id) - WHERE IFNULL(i.date_end,v_date_ini) BETWEEN p.date_start AND p.date_end - AND warehouse_id IN (0, v_warehouse) - ORDER BY item_id, warehouse_id DESC, date_end DESC - ) t GROUP BY item_id; - - DROP TEMPORARY TABLE item_range_copy; -*/ - -- Replica la tabla item_range para poder usarla varias veces en la misma consulta - - DROP TEMPORARY TABLE IF EXISTS item_range_copy1; - CREATE TEMPORARY TABLE item_range_copy1 LIKE item_range; - INSERT INTO item_range_copy1 - SELECT * FROM item_range; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy2; - CREATE TEMPORARY TABLE item_range_copy2 LIKE item_range; - INSERT INTO item_range_copy2 - SELECT * FROM item_range; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy3; - CREATE TEMPORARY TABLE item_range_copy3 LIKE item_range; - INSERT INTO item_range_copy3 - SELECT * FROM item_range; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy4; - CREATE TEMPORARY TABLE item_range_copy4 LIKE item_range; - INSERT INTO item_range_copy4 - SELECT * FROM item_range; - - -- Calcula el ATP - - DELETE FROM available WHERE calc_id = v_calc; - - INSERT INTO available (calc_id, item_id, available) - SELECT v_calc, t.item_id, SUM(stock) amount FROM ( - SELECT ti.item_id, stock - FROM vn2008.tmp_item ti - JOIN item_range ir ON ir.item_id = ti.item_id - UNION ALL - SELECT t.item_id, minacum(dt, amount, v_date) AS available FROM ( - SELECT item_id, DATE(dat) dt, SUM(amount) amount FROM ( - SELECT i.item_id, i.dat, i.amount - FROM vn2008.item_out i - JOIN item_range_copy1 ir ON ir.item_id = i.item_id - WHERE i.dat >= v_date_ini - AND (ir.date_end IS NULL OR i.dat <= ir.date_end) - AND i.warehouse_id = v_warehouse - UNION ALL - SELECT i.item_id, i.dat, i.amount - FROM vn2008.item_entry_in i - JOIN item_range_copy2 ir ON ir.item_id = i.item_id - WHERE i.dat >= v_date_ini - AND (ir.date_end IS NULL OR i.dat <= ir.date_end) - AND i.warehouse_id = v_warehouse - UNION ALL - SELECT i.item_id, i.dat, i.amount - FROM vn2008.item_entry_out i - JOIN item_range_copy3 ir ON ir.item_id = i.item_id - WHERE i.dat >= v_date_ini - AND (ir.date_end IS NULL OR i.dat <= ir.date_end) - AND i.warehouse_id = v_warehouse - UNION ALL - SELECT r.item_id, r.shipment, -r.amount - FROM hedera.order_row r - JOIN hedera.`order` o ON o.id = r.order_id - JOIN item_range_copy4 ir ON ir.item_id = r.item_id - WHERE r.shipment >= v_date_ini - AND (ir.date_end IS NULL OR r.shipment <= ir.date_end) - AND r.warehouse_id = v_warehouse - AND r.created >= v_reserve_date - AND NOT o.confirmed - ) t - GROUP BY item_id, dt - ) t - GROUP BY t.item_id - ) t GROUP BY t.item_id HAVING amount != 0; - - DROP TEMPORARY TABLE - vn2008.tmp_item - ,item_range - ,item_range_copy1 - ,item_range_copy2 - ,item_range_copy3 - ,item_range_copy4; - - CALL cache_calc_end (v_calc); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `barcodes_articles_update` */; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `barcodes_articles_update`() -BEGIN - -REPLACE cache.barcodes - - SELECT - `Articles`.`Id_Article` AS `code`, - `Articles`.`Id_Article` AS `Id_Article`, - `Articles`.`Article` AS `Article`, - `Articles`.`Medida` AS `Medida`, - `Articles`.`Color` AS `Color`, - `Articles`.`Categoria` AS `Categoria`, - `p`.`name` AS `Producer` - FROM - vn2008.Articles - LEFT JOIN vn2008.`producer` `p` using(producer_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 */ ; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `barcodes_barcodes_update` */; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `barcodes_barcodes_update`() -BEGIN - -REPLACE cache.barcodes - - SELECT - `barcodes`.`code` AS `code`, - `barcodes`.`Id_Article` AS `Id_Article`, - `Articles`.`Article` AS `Article`, - `Articles`.`Medida` AS `Medida`, - `Articles`.`Color` AS `Color`, - `Articles`.`Categoria` AS `Categoria`, - `p`.`name` AS `Producer` - FROM - vn2008.`barcodes` - JOIN - vn2008.Articles using(Id_Article) - LEFT JOIN vn2008.`producer` `p` using(producer_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 */ ; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `barcodes_compres_update` */; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `barcodes_compres_update`() -BEGIN - -REPLACE cache.barcodes - - SELECT - Compres.`Id_Compra` AS `code`, - Compres.`Id_Article` AS `Id_Article`, - `Articles`.`Article` AS `Article`, - `Articles`.`Medida` AS `Medida`, - `Articles`.`Color` AS `Color`, - `Articles`.`Categoria` AS `Categoria`, - producer.`name` AS `Producer` - - - FROM - vn2008.Compres - JOIN vn2008.Articles using(Id_Article) - LEFT JOIN vn2008.producer using(producer_id) - JOIN vn2008.Entradas using(Id_Entrada) - JOIN vn2008.travel on travel.id = travel_id - WHERE - landing >= TIMESTAMPADD(WEEK, -2, CURDATE()) - ; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `barcodes_expeditions_update` */; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `barcodes_expeditions_update`(IN idExpedition BIGINT) -BEGIN - -REPLACE cache.barcodes - - SELECT - `e`.`expeditions_id` AS `code`, - `Tickets`.`Id_Ruta` AS `Id_Article`, - `Tickets`.`Alias` AS `Article`, - `Tickets`.`Bultos` AS `Medida`, - `Tickets`.`Id_Ruta` AS `Color`, - `w`.`name` AS `Categoria`, - `a`.`Agencia` AS `Producer` - FROM - vn2008.expeditions `e` - JOIN vn2008.Tickets ON `Tickets`.`Id_Ticket` = `e`.`ticket_id` - JOIN vn2008.warehouse `w` ON `w`.`id` = `Tickets`.`warehouse_id` - JOIN vn2008.Rutas `r` ON `r`.`Id_Ruta` = `Tickets`.`Id_Ruta` - JOIN vn2008.Agencias `a` ON `a`.`Id_Agencia` = `r`.`Id_Agencia` - WHERE - idExpedition IN (e.expeditions_id,0) - AND - `Tickets`.`Fecha` >= (CURDATE() + INTERVAL -(2) DAY) - - - ; - - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `barcodes_update` */; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `barcodes_update`() -BEGIN - - declare allExpeditions int default 0; - - call barcodes_articles_update; - - call barcodes_barcodes_update; - - call barcodes_compres_update; - - call barcodes_expeditions_update(allExpeditions); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `cacheCalcClean` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `cacheCalcClean`() -BEGIN - DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); - - DELETE FROM cache_calc WHERE expires < vCleanTime; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `cache_calc_end` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_end`(v_calc INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = ADDTIME(NOW(), c.lifetime), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `cache_calc_start` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_start`(OUT v_calc INT, INOUT v_refresh BOOL, v_cache_name VARCHAR(50), v_params VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK(v_lock_id); - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires - INTO v_cache_id, v_calc, v_expires - FROM cache c - LEFT JOIN cache_calc ca - ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' - WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; - - -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. - - IF !v_refresh AND NOW() < v_expires - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `cache_calc_unlock` */; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_unlock`(v_calc INT) -BEGIN - DECLARE v_cache_name VARCHAR(50); - DECLARE v_params VARCHAR(100); - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - DELETE FROM cache_calc WHERE id = v_calc; - - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `clean` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN - - DECLARE vDateShort DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); - - INSERT INTO cache.dailyTaskLog(state) VALUES('clean START'); - - DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; - - INSERT INTO cache.dailyTaskLog(state) VALUES('clean END'); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `departure_timing` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `departure_timing`(vWarehouseId INT) -BEGIN - -DECLARE done BOOL DEFAULT FALSE; -DECLARE rsDeparture INT; -DECLARE rsHoras DECIMAL(5,2); -DECLARE rsInicio DECIMAL(5,2); -DECLARE resto DECIMAL(5,2); -DECLARE horasProd DECIMAL(5,2); -DECLARE inicioProd DECIMAL(5,2) DEFAULT 24.00; -DECLARE myTime DECIMAL(5,2); -DECLARE departureLimit INT; -DECLARE myMinSpeed DECIMAL(10,2); -DECLARE vLoadingDelay DECIMAL(5) DEFAULT 2; - -DECLARE rs CURSOR FOR - SELECT Departure - , Sum(pb.m3)/(GREATEST(v.m3,IFNULL(minSpeed,0))/1.3) AS Horas - , curDate()+(Departure + vLoadingDelay -(Sum(pb.m3)/(GREATEST(v.m3,IFNULL(minSpeed,0))/1.3))/24) AS InicioPreparacion - FROM tmp.production_buffer pb - JOIN vn2008.v_encajado_ultima_hora v ON v.warehouse_id = pb.warehouse_id - LEFT JOIN cache.departure_limit dp ON dp.warehouse_id = pb.warehouse_id AND dp.fecha = CURDATE() - WHERE pb.Fecha = CURDATE() - AND alert_level < 2 - AND IFNULL(Departure,0) > 0 - GROUP BY Departure - ORDER BY Departure DESC; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SET myTime = HOUR(now()) + MINUTE(now()) / 60; - - OPEN rs; - - FETCH rs INTO rsDeparture, rsHoras , rsInicio; - - WHILE NOT done DO - - SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0); - - SET inicioProd = rsDeparture - rsHoras; - - IF inicioProd - resto < myTime THEN - - SET done = TRUE; - - ELSE - - SET departureLimit = rsDeparture; - - FETCH rs INTO rsDeparture, rsHoras , rsInicio; - - -- SELECT rsDeparture, rsHoras , rsInicio; - - END IF; - - END WHILE; - - SET departureLimit = IFNULL(departureLimit,24); - SET departureLimit = IF(departureLimit = 0, 24, departureLimit); - - SELECT minSpeed INTO myMinSpeed - FROM cache.departure_limit - WHERE warehouse_id = vWarehouseId - AND fecha = CURDATE(); - - REPLACE cache.departure_limit(warehouse_id, fecha, hora, minSpeed) - VALUES (vWarehouseId, CURDATE(), IFNULL(departureLimit,24), IFNULL(myMinSpeed,0)); - - CLOSE rs; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `departure_timing_beta` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `departure_timing_beta`(vWarehouseId INT) -BEGIN - -DECLARE done BOOL DEFAULT FALSE; -DECLARE rsDeparture INT; -DECLARE rsHoras DECIMAL(5,2); -DECLARE rsInicio DECIMAL(5,2); -DECLARE resto DECIMAL(5,2); -DECLARE horasProd DECIMAL(5,2); -DECLARE inicioProd DECIMAL(5,2) DEFAULT 24.00; -DECLARE myTime DECIMAL(5,2); -DECLARE departureLimit INT; - -DECLARE rs CURSOR FOR - SELECT Departure - , Sum(pb.m3)/GREATEST(v.m3,IFNULL(minSpeed,0)) AS Horas - , curDate()+(Departure-(Sum(pb.m3)/GREATEST(v.m3,IFNULL(minSpeed,0)))/24) AS InicioPreparacion - FROM tmp.production_buffer pb - JOIN vn2008.v_encajado_ultima_hora v ON v.warehouse_id = pb.warehouse_id - LEFT JOIN cache.departure_limit dp ON dp.warehouse_id = pb.warehouse_id AND dp.fecha = CURDATE() - WHERE pb.Fecha = CURDATE() - AND alert_level < 2 - AND IFNULL(Departure,0) > 0 - GROUP BY Departure - ORDER BY Departure DESC; - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - -SET myTime = HOUR(now()) + MINUTE(now()) / 60; - -OPEN rs; - -FETCH rs INTO rsDeparture, rsHoras , rsInicio; - -SELECT rsDeparture, rsHoras , rsInicio, vWarehouseId, done; - -WHILE NOT done DO - - SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0); - - SET inicioProd = rsDeparture - rsHoras; - - SELECT rsDeparture, rsHoras , rsInicio, resto,inicioProd; - - IF inicioProd - resto < myTime THEN - - SET done = TRUE; - - ELSE - - SET departureLimit = rsDeparture; - - FETCH rs INTO rsDeparture, rsHoras , rsInicio; - - END IF; - -END WHILE; - -SELECT rsDeparture, rsHoras , rsInicio, resto,inicioProd; - - -SET departureLimit = IFNULL(departureLimit,24); - -IF departureLimit > 0 THEN - - REPLACE cache.departure_limit(warehouse_id, fecha, hora, minSpeed) - VALUES (vWarehouseId, CURDATE(), departureLimit, myMinSpeed); - -END IF; - -CLOSE rs; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `departure_timing_kk` */; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `departure_timing_kk`() -BEGIN - -DECLARE done BOOL DEFAULT FALSE; -DECLARE rsDeparture INT; -DECLARE rsHoras DECIMAL(5,2); -DECLARE rsInicio DECIMAL(5,2); -DECLARE resto DECIMAL(5,2); -DECLARE horasProd DECIMAL(5,2); -DECLARE inicioProd DECIMAL(5,2) DEFAULT 24.00; -DECLARE myTime DECIMAL(5,2); -DECLARE departureLimit INT; -DECLARE myWarehouse INT; -DECLARE myMinSpeed DECIMAL(10,2); - - -DECLARE rs CURSOR FOR - SELECT Departure - , Sum(pb.m3)/(GREATEST(v.m3, 100)/1.3) AS Horas - , curDate()+(Departure-Sum(pb.m3)/(GREATEST(v.m3, 100)/1.3))/24 AS InicioPreparacion - FROM tmp.production_buffer pb - JOIN vn2008.v_encajado_ultima_hora v ON v.warehouse_id = pb.warehouse_id - WHERE Fecha = CURDATE() - AND alert_level < 2 - AND IFNULL(Departure,0) > 0 - GROUP BY Departure - ORDER BY Departure DESC; - -DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - -SELECT IFNULL(minSpeed,0) INTO myMinSpeed -FROM cache.departure_limit -WHERE warehouse_id = myWarehouse -AND fecha = CURDATE(); - -SET myTime = HOUR(now()) + MINUTE(now()) / 60; - -SELECT warehouse_id INTO myWarehouse -FROM tmp.production_buffer -LIMIT 1; - -OPEN rs; - -FETCH rs INTO rsDeparture, rsHoras , rsInicio; - -WHILE NOT done DO - - SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0); - - SET inicioProd = rsDeparture - rsHoras; - - IF inicioProd - resto < myTime THEN - - SET done = TRUE; - - ELSE - - SET departureLimit = rsDeparture; - - FETCH rs INTO rsDeparture, rsHoras , rsInicio; - - END IF; - -END WHILE; - -IF departureLimit > 0 THEN - - REPLACE cache.departure_limit(warehouse_id, fecha, hora, minSpeed) - VALUES (myWarehouse, CURDATE(), departureLimit, myMinSpeed); - -END IF; - -CLOSE rs; - - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `equaliza` */; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `equaliza`(wh_id INT) -BEGIN - -- DEPRECATED usar equalizator_refesh - - - - CALL equalizator_refresh (FALSE, wh_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 */ ; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `equalizator_refresh` */; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `equalizator_refresh`(v_refresh BOOL, wh_id INT) -proc: BEGIN - DECLARE datEQ DATETIME; - DECLARE timDIF TIME; - DECLARE v_calc INT; - /* JGF 2017-03-20 cuelga el sistema - CALL cache_calc_start (v_calc, v_refresh, 'equalizator', wh_id); - - IF !v_refresh - THEN - LEAVE proc; - END IF; - - REPLACE equalizator (warehouse_id, Vista, Encajado, Impreso, Pedido) - SELECT - t.warehouse_id, - Vista, - sum(IF(t.Factura IS NOT NULL - OR t.Etiquetasemitidas - OR IFNULL(ticket_id,0), Cantidad * r.cm3, 0)) as encajado, - sum(IF(PedidoImpreso, Cantidad * r.cm3,0)) as impreso, - sum(Cantidad * r.cm3 ) as Pedido - FROM - vn2008.Movimientos m - JOIN - vn2008.Tickets t USING (Id_Ticket) - JOIN - bi.rotacion r on r.warehouse_id = t.warehouse_id and r.Id_Article = m.Id_Article - JOIN - vn2008.Agencias a ON t.Id_Agencia = a.Id_Agencia - JOIN - vn2008.Clientes C USING (Id_Cliente) - LEFT JOIN - (SELECT distinct - ticket_id - FROM - vn2008.expeditions e JOIN vn2008.Tickets t - ON t.Id_Ticket = e.ticket_id - WHERE Fecha >= curDate() - ) exp ON ticket_id = Id_Ticket - WHERE - invoice And Fecha >= curDate() - AND wh_id in (0,t.warehouse_id) - AND fecha < (TIMESTAMPADD(DAY, 1, CURDATE())) - GROUP BY t.warehouse_id, Vista; - - -- Reducimos las cantidades para que el grafico tenga sentido - - UPDATE equalizator SET - pedido = (pedido - (impreso - encajado) - encajado) / 1000000, - impreso = (impreso - encajado) / 1000000, - encajado = encajado / 1000000 - WHERE wh_id in (0,warehouse_id); - - CALL cache_calc_end (v_calc); - */ -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `item_range_refresh` */; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_range_refresh`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT, v_date DATE) -proc: BEGIN - DECLARE v_params CHAR(100); - DECLARE v_date_inv DATE; - - IF v_date < CURDATE() - THEN - LEAVE proc; - END IF; - - SET v_params = CONCAT_WS('/', v_warehouse, v_date); - CALL cache_calc_start (v_calc, v_refresh, 'item_range', v_params); - - IF !v_refresh - THEN - LEAVE proc; - END IF; - - -- Limpia las caches antiguas - - DELETE FROM item_range WHERE calc_id NOT IN ( - SELECT cc.id - FROM `cache` c - JOIN cache_calc cc ON c.id = cc.cache_id - WHERE c.`name` = 'item_range'); - - -- Calculos previos - - CALL last_buy_refresh (FALSE); - - SET v_date_inv = vn2008.date_inv(); - - -- Calcula el ultimo dia de vida para cada producto - - DROP TEMPORARY TABLE IF EXISTS tmp.item_range; - CREATE TEMPORARY TABLE tmp.item_range - (INDEX (item_id)) - ENGINE = MEMORY - SELECT c.item_id, IF(t.life IS NULL, NULL, TIMESTAMPADD(DAY, t.life + 1, GREATEST(c.landing, b.landing))) AS date_end - FROM last_buy b - JOIN ( - SELECT c.Id_Article item_id, MAX(landing) landing - FROM vn2008.Compres c - JOIN vn2008.Entradas e ON c.Id_Entrada = e.Id_Entrada - JOIN vn2008.travel t ON t.id = e.travel_id - JOIN vn2008.warehouse w ON w.id = t.warehouse_id - WHERE t.landing BETWEEN v_date_inv AND v_date - AND t.warehouse_id = v_warehouse - AND NOT e.Inventario - AND NOT e.Redada - GROUP BY item_id - ) c ON c.item_id = b.item_id - JOIN vn2008.Articles a ON a.Id_Article = b.item_id - JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - WHERE b.warehouse_id = v_warehouse - HAVING date_end >= v_date OR date_end IS NULL; - - -- Tabla con el ultimo dia de precios fijados para cada producto - - DROP TEMPORARY TABLE IF EXISTS tmp.fix_range; - CREATE TEMPORARY TABLE tmp.fix_range - ENGINE = MEMORY - SELECT item_id, date_end FROM ( - SELECT p.item_id, p.date_end - FROM vn2008.price_fixed p - LEFT JOIN tmp.item_range i USING(item_id) - WHERE IFNULL(i.date_end, v_date) BETWEEN p.date_start AND p.date_end - AND warehouse_id IN (0, v_warehouse) - ORDER BY item_id, warehouse_id DESC, date_end DESC - ) t GROUP BY item_id; - - -- Calcula los rangos - - DELETE FROM item_range WHERE calc_id = v_calc; - - INSERT INTO item_range (calc_id, item_id, date_end) - SELECT v_calc, item_id, date_end - FROM ( - SELECT * FROM tmp.fix_range - UNION ALL - SELECT * FROM tmp.item_range - ) t - GROUP BY item_id; - - -- Limpieza - - DROP TEMPORARY TABLE tmp.item_range; - DROP TEMPORARY TABLE tmp.fix_range; - - CALL cache_calc_end (v_calc); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `last_buy_refresh` */; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `last_buy_refresh`(v_refresh BOOL) -proc: BEGIN -/** - * Crea o actualiza la cache con la última compra y fecha de cada - * artículo hasta ayer. Para obtener la última compra hasta una fecha - * determinada utilizar el procedimiento vn2008.item_last_buy_(). - * - * @param v_refresh %TRUE para forzar el recálculo de la cache - **/ - DECLARE v_calc INT; - DECLARE v_date_ini DATE; - DECLARE v_date_end DATE; - DECLARE v_last_refresh DATE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - CALL cache_calc_unlock (v_calc); - RESIGNAL; - END; - - CALL cache_calc_start (v_calc, v_refresh, 'last_buy', NULL); - - IF !v_refresh - THEN - LEAVE proc; - END IF; - - -- TODO: ¿Se puede usar la fecha del ultimo inventario? - SET v_date_ini = vn2008.date_inv();-- TIMESTAMPADD(DAY, -90, CURDATE()); - SET v_date_end = CURDATE(); -- TIMESTAMPADD(DAY, -1, CURDATE()); - - CALL vn2008.item_last_buy_from_interval (NULL, v_date_ini, v_date_end); - - DELETE FROM last_buy; - - INSERT INTO last_buy (item_id, warehouse_id, buy_id, landing) - SELECT item_id, warehouse_id, buy_id, landing - FROM tmp.item_last_buy_from_interval; - - DROP TEMPORARY TABLE tmp.item_last_buy_from_interval; - - CALL cache_calc_end (v_calc); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `prod_graphic_refresh` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `prod_graphic_refresh`(v_refresh BOOL, wh_id INT) -proc: BEGIN - DECLARE datEQ DATETIME; - DECLARE timDIF TIME; - DECLARE v_calc INT; - - CALL cache_calc_start (v_calc, v_refresh, 'prod_graphic', wh_id); - - IF !v_refresh - THEN - LEAVE proc; - END IF; - - CALL vn2008.production_control_source(wh_id, 0); - - DELETE FROM prod_graphic_source; - - INSERT INTO prod_graphic_source (warehouse_id, alert_level, m3, hora, `order`, Agencia) - SELECT - wh_id, - pb.alert_level, - m3, - pb.Hora, - pb.state_order, - pb.Agencia - FROM tmp.production_buffer pb - WHERE Fecha = CURDATE() - ; - - - CALL cache_calc_end (v_calc); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `sales_refreshkk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `sales_refreshkk`() -proc:BEGIN - - DECLARE v_calc INT; - DECLARE v_refresh BOOL DEFAULT TRUE; - DECLARE datMONTH INT; - DECLARE datYEAR INT; - - CALL cache_calc_start (v_calc, v_refresh, 'sales', NULL); - - IF !v_refresh - THEN - LEAVE proc; - END IF; - - - SELECT MONTH(CURDATE()) INTO datMONTH; - SELECT YEAR(CURDATE()) INTO datYEAR; - - -- preparamos una tabla con los meses y años que interesan - DROP TEMPORARY TABLE IF EXISTS tmp.periods; - CREATE TEMPORARY TABLE tmp.periods - select distinct month, year(date) as year - from vn2008.time - where date <= CURDATE() - order by year desc, month desc - limit 3; - - -- borramos los datos para evitar flecos - DELETE s.* - FROM bi.sales s - join tmp.periods using(year,month); - - -- insertamos las ventas de cada comercial - REPLACE bi.sales(Id_Trabajador, year, month, weight, boss_id) - select v.Id_Trabajador, year, month, round(sum(total)) as weight, IFNULL(j.boss_id,20) - from bi.v_ticket_total v - join tmp.periods using(year,month) - left join (SELECT jerarquia.boss_id, jerarquia.worker_id - FROM vn2008.jerarquia - ) j on j.worker_id = v.Id_Trabajador - group by v.Id_Trabajador, year, month; - - - - -- caso especial: Claudi ajuda a Josep a llegar a los 1200 euros de comision - /* - update bi.sales - set boss_aid = 34285 - weight - where Id_Trabajador = 378 - and year >= 2015 - and month > datmonth -2; - - update bi.sales s - join - (select year, month, boss_aid - from bi.sales - where Id_Trabajador = 378 - and year >= 2015 - and month > datmonth -2) sub using(year,month) - set s.boss_aid = s.boss_aid - sub.boss_aid - where Id_Trabajador = 208 - and year >= 2015 - and month > datmonth -2; - */ - - - - --- ahora, las comisiones - -update bi.sales s -set comision = weight * 0.029; - - DROP TEMPORARY TABLE IF EXISTS tmp.periods; - - CALL cache_calc_end (v_calc); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stock_refresh` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `stock_refresh`(v_refresh BOOL) -proc: BEGIN -/** - * Crea o actualiza la cache con el disponible hasta el día de - * ayer. Esta cache es usada como base para otros procedimientos - * como el cáculo del visible o del ATP. - * - * @param v_refresh %TRUE para forzar el recálculo de la cache - **/ - DECLARE v_calc INT; - DECLARE v_date_inv DATE; - DECLARE v_curdate DATE; - DECLARE v_last_refresh DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - CALL cache_calc_unlock (v_calc); - RESIGNAL; - END; - - CALL cache_calc_start (v_calc, v_refresh, 'stock', NULL); - - IF !v_refresh - THEN - LEAVE proc; - END IF; - - SET v_date_inv = (SELECT FechaInventario FROM vn2008.tblContadores LIMIT 1); - SET v_curdate = CURDATE(); - - DELETE FROM stock; - - INSERT INTO stock (item_id, warehouse_id, amount) - SELECT item_id, warehouse_id, SUM(amount) amount FROM - ( - SELECT item_id, warehouse_id, amount FROM vn2008.item_out - WHERE dat >= v_date_inv AND dat < v_curdate - UNION ALL - SELECT item_id, warehouse_id, amount FROM vn2008.item_entry_in - WHERE dat >= v_date_inv AND dat < v_curdate - UNION ALL - SELECT item_id ,warehouse_id, amount FROM vn2008.item_entry_out - WHERE dat >= v_date_inv AND dat < v_curdate - ) t - GROUP BY item_id, warehouse_id HAVING amount != 0; - - CALL cache_calc_end (v_calc); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `visible_refresh` */; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `visible_refresh`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT) -proc: BEGIN - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - CALL cache_calc_unlock (v_calc); - RESIGNAL; - END; - - CALL cache_calc_start (v_calc, v_refresh, 'visible', v_warehouse); - - IF !v_refresh - THEN - LEAVE proc; - END IF; - - -- Limpia las caches antiguas - - IF TRUE -- GET_LOCK('visible/clean', 1) - THEN - DELETE FROM visible WHERE calc_id NOT IN ( - SELECT cc.id - FROM `cache` c - JOIN cache_calc cc ON c.id = cc.cache_id - WHERE c.`name` = 'visible'); - - -- DO RELEASE_LOCK('visible/clean'); - END IF; - - -- Calculamos el stock hasta ayer - - CALL `cache`.stock_refresh(false); - - DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; - CREATE TEMPORARY TABLE vn2008.tmp_item - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT item_id, amount stock, amount visible FROM `cache`.stock - WHERE warehouse_id = v_warehouse; - - -- Calculamos los movimientos confirmados de hoy - - CALL vn2008.item_stock_visible(v_warehouse, NULL); - - DELETE FROM visible WHERE calc_id = v_calc; - - INSERT INTO visible (calc_id, item_id,visible) - SELECT v_calc, item_id, visible FROM vn2008.tmp_item; - - CALL cache_calc_end (v_calc); - - DROP TEMPORARY TABLE vn2008.tmp_item; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `weekly_sales_refresh` */; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_ci ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `weekly_sales_refresh`(v_refresh BOOL) -BEGIN - DECLARE v_week_ini INT; - DECLARE v_week_end INT; - DECLARE v_date_ini DATE; - DECLARE v_date_end DATE; - DECLARE v_last_refresh DATE; - - IF GET_LOCK('weekly_sales', 300) - THEN - SELECT last_refresh INTO v_last_refresh FROM weekly_sales_info; - - IF v_last_refresh IS NULL THEN - SET v_refresh = TRUE; - END IF; - - IF v_refresh || v_last_refresh < CURDATE() - THEN - SET v_date_ini = TIMESTAMPADD(DAY, -(366 * 1.5), CURDATE()); - SET v_date_end = TIMESTAMPADD(DAY, -1, CURDATE()); - - IF v_refresh - THEN - TRUNCATE TABLE weekly_sales; - ELSE - SET v_week_ini = vn2008.to_weeks (v_date_ini); - SET v_date_ini = TIMESTAMPADD(DAY, -WEEKDAY(v_last_refresh) - 7, v_last_refresh); - SET v_week_end = vn2008.to_weeks (v_date_ini); - - DELETE FROM weekly_sales - WHERE week < v_week_ini OR week >= v_week_end; - END IF; - - CALL vn2008.weekly_sales_new (0, v_date_ini, v_date_end); - - INSERT INTO weekly_sales (item_id, week, warehouse_id, amount, price) - SELECT item_id, week, warehouse_id, amount, price FROM vn2008.weekly_sales; - - DROP TEMPORARY TABLE vn2008.weekly_sales; - - TRUNCATE TABLE weekly_sales_info; - INSERT INTO weekly_sales_info (last_refresh) VALUES (CURDATE()); - END IF; - - DO RELEASE_LOCK('weekly_sales'); - 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 */ ; -ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; - --- --- Current Database: `salix` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `salix` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `salix`; - --- --- Table structure for table `ACL` --- - -DROP TABLE IF EXISTS `ACL`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ACL` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `model` varchar(512) CHARACTER SET utf8 DEFAULT NULL, - `property` varchar(512) CHARACTER SET utf8 DEFAULT NULL, - `accessType` set('READ','WRITE','*') COLLATE utf8_unicode_ci DEFAULT 'READ', - `permission` set('DENY','ALLOW') COLLATE utf8_unicode_ci DEFAULT 'ALLOW', - `principalType` set('ROLE','USER') COLLATE utf8_unicode_ci DEFAULT 'ROLE', - `principalId` varchar(512) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=62 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `AccessToken` --- - -DROP TABLE IF EXISTS `AccessToken`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `AccessToken` ( - `id` varchar(255) CHARACTER SET utf8 NOT NULL, - `ttl` int(11) DEFAULT NULL, - `scopes` varchar(255) CHARACTER SET utf8 DEFAULT NULL, - `created` datetime DEFAULT NULL, - `userId` int(11) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `Account` --- - -DROP TABLE IF EXISTS `Account`; -/*!50001 DROP VIEW IF EXISTS `Account`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Account` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `password`, - 1 AS `roleFk`, - 1 AS `active`, - 1 AS `email`, - 1 AS `created`, - 1 AS `updated`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Accounting` --- - -DROP TABLE IF EXISTS `Accounting`; -/*!50001 DROP VIEW IF EXISTS `Accounting`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Accounting` AS SELECT - 1 AS `id`, - 1 AS `bank`, - 1 AS `account`, - 1 AS `accountingTypeFk`, - 1 AS `entityFk`, - 1 AS `isActive`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Address` --- - -DROP TABLE IF EXISTS `Address`; -/*!50001 DROP VIEW IF EXISTS `Address`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Address` AS SELECT - 1 AS `id`, - 1 AS `consignee`, - 1 AS `street`, - 1 AS `city`, - 1 AS `postcode`, - 1 AS `provinceFk`, - 1 AS `phone`, - 1 AS `mobile`, - 1 AS `isEnabled`, - 1 AS `isDefaultAddress`, - 1 AS `clientFk`, - 1 AS `defaultAgencyFk`, - 1 AS `longitude`, - 1 AS `latitude`, - 1 AS `isEqualizated`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Agency` --- - -DROP TABLE IF EXISTS `Agency`; -/*!50001 DROP VIEW IF EXISTS `Agency`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Agency` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `warehouseFk`, - 1 AS `isVolumetric`, - 1 AS `bankFk`, - 1 AS `warehouseAliasFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `AgencyMode` --- - -DROP TABLE IF EXISTS `AgencyMode`; -/*!50001 DROP VIEW IF EXISTS `AgencyMode`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `AgencyMode` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `description`, - 1 AS `agencyTypeFk`, - 1 AS `m3`, - 1 AS `agencyFk`, - 1 AS `inflation`, - 1 AS `sendMailTo`, - 1 AS `isForTicket`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Bank` --- - -DROP TABLE IF EXISTS `Bank`; -/*!50001 DROP VIEW IF EXISTS `Bank`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Bank` AS SELECT - 1 AS `id`, - 1 AS `bank`, - 1 AS `account`, - 1 AS `cash`, - 1 AS `entityFk`, - 1 AS `isActive`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `City` --- - -DROP TABLE IF EXISTS `City`; -/*!50001 DROP VIEW IF EXISTS `City`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `City` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `provinceFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Client` --- - -DROP TABLE IF EXISTS `Client`; -/*!50001 DROP VIEW IF EXISTS `Client`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Client` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `fi`, - 1 AS `socialName`, - 1 AS `contact`, - 1 AS `street`, - 1 AS `city`, - 1 AS `postcode`, - 1 AS `provinceFk`, - 1 AS `countryFk`, - 1 AS `email`, - 1 AS `phone`, - 1 AS `mobile`, - 1 AS `fax`, - 1 AS `active`, - 1 AS `discount`, - 1 AS `credit`, - 1 AS `creditInsurance`, - 1 AS `iban`, - 1 AS `dueDay`, - 1 AS `equalizationTax`, - 1 AS `hasToInvoice`, - 1 AS `invoiceByEmail`, - 1 AS `payMethodFk`, - 1 AS `salesPersonFk`, - 1 AS `contactChannelFk`, - 1 AS `sepaVnl`, - 1 AS `coreVnl`, - 1 AS `coreVnh`, - 1 AS `eypbc`, - 1 AS `quality`, - 1 AS `vies`, - 1 AS `isRelevant`, - 1 AS `typeFk`, - 1 AS `accountingAccount`, - 1 AS `created`, - 1 AS `hasToInvoiceByAddress`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `ClientCredit` --- - -DROP TABLE IF EXISTS `ClientCredit`; -/*!50001 DROP VIEW IF EXISTS `ClientCredit`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ClientCredit` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `employeeFk`, - 1 AS `amount`, - 1 AS `created`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `ClientCreditLimit` --- - -DROP TABLE IF EXISTS `ClientCreditLimit`; -/*!50001 DROP VIEW IF EXISTS `ClientCreditLimit`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ClientCreditLimit` AS SELECT - 1 AS `id`, - 1 AS `maxAmount`, - 1 AS `roleFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `ClientObservation` --- - -DROP TABLE IF EXISTS `ClientObservation`; -/*!50001 DROP VIEW IF EXISTS `ClientObservation`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ClientObservation` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `employeeFk`, - 1 AS `text`, - 1 AS `created`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `ClientType` --- - -DROP TABLE IF EXISTS `ClientType`; -/*!50001 DROP VIEW IF EXISTS `ClientType`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ClientType` AS SELECT - 1 AS `id`, - 1 AS `code`, - 1 AS `type`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `ContactChannel` --- - -DROP TABLE IF EXISTS `ContactChannel`; -/*!50001 DROP VIEW IF EXISTS `ContactChannel`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `ContactChannel` AS SELECT - 1 AS `id`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Country` --- - -DROP TABLE IF EXISTS `Country`; -/*!50001 DROP VIEW IF EXISTS `Country`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Country` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `inCee`, - 1 AS `code`, - 1 AS `currencyFk`, - 1 AS `realCountryFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `CreditClassification` --- - -DROP TABLE IF EXISTS `CreditClassification`; -/*!50001 DROP VIEW IF EXISTS `CreditClassification`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `CreditClassification` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `started`, - 1 AS `ended`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Delivery` --- - -DROP TABLE IF EXISTS `Delivery`; -/*!50001 DROP VIEW IF EXISTS `Delivery`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Delivery` AS SELECT - 1 AS `id`, - 1 AS `date`, - 1 AS `m3`, - 1 AS `warehouseFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Employee` --- - -DROP TABLE IF EXISTS `Employee`; -/*!50001 DROP VIEW IF EXISTS `Employee`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Employee` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `surname`, - 1 AS `userFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `FakeProduction` --- - -DROP TABLE IF EXISTS `FakeProduction`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `FakeProduction` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `ticketFk` int(11) NOT NULL DEFAULT '0', - `clientFk` int(11) NOT NULL DEFAULT '0', - `client` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `date` date DEFAULT NULL, - `hour` time DEFAULT NULL, - `city` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `province` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `provinceFk` smallint(6) unsigned NOT NULL DEFAULT '0', - `agency` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `agencyFk` smallint(6) NOT NULL, - `lines` int(1) NOT NULL DEFAULT '0', - `m3` decimal(5,2) NOT NULL DEFAULT '0.00', - `problems` int(1) NOT NULL DEFAULT '0', - `problem` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `stateFk` bigint(4) NOT NULL DEFAULT '0', - `workerfk` int(11) NOT NULL DEFAULT '0', - `worker` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `salesPersonFk` int(11) NOT NULL DEFAULT '0', - `salesPerson` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `state` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `boxes` double DEFAULT NULL, - `routeFk` int(10) unsigned DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=826 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `PayMethod` --- - -DROP TABLE IF EXISTS `PayMethod`; -/*!50001 DROP VIEW IF EXISTS `PayMethod`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `PayMethod` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `graceDays`, - 1 AS `outstandingDebt`, - 1 AS `ibanRequired`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Province` --- - -DROP TABLE IF EXISTS `Province`; -/*!50001 DROP VIEW IF EXISTS `Province`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Province` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `countryFk`, - 1 AS `warehouseFk`, - 1 AS `zoneFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Role` --- - -DROP TABLE IF EXISTS `Role`; -/*!50001 DROP VIEW IF EXISTS `Role`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Role` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `description`, - 1 AS `created`, - 1 AS `modified`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `RoleMapping` --- - -DROP TABLE IF EXISTS `RoleMapping`; -/*!50001 DROP VIEW IF EXISTS `RoleMapping`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `RoleMapping` AS SELECT - 1 AS `id`, - 1 AS `principalType`, - 1 AS `principalId`, - 1 AS `roleId`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Route` --- - -DROP TABLE IF EXISTS `Route`; -/*!50001 DROP VIEW IF EXISTS `Route`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Route` AS SELECT - 1 AS `id`, - 1 AS `date`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `State` --- - -DROP TABLE IF EXISTS `State`; -/*!50001 DROP VIEW IF EXISTS `State`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `State` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `order`, - 1 AS `alertLevel`, - 1 AS `code`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Ticket` --- - -DROP TABLE IF EXISTS `Ticket`; -/*!50001 DROP VIEW IF EXISTS `Ticket`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Ticket` AS SELECT - 1 AS `id`, - 1 AS `agencyFk`, - 1 AS `employeeFk`, - 1 AS `date`, - 1 AS `hour`, - 1 AS `clientFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `TicketState` --- - -DROP TABLE IF EXISTS `TicketState`; -/*!50001 DROP VIEW IF EXISTS `TicketState`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `TicketState` AS SELECT - 1 AS `id`, - 1 AS `ticketFk`, - 1 AS `stateFk`, - 1 AS `employeeFk`, - 1 AS `updated`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Vehicle` --- - -DROP TABLE IF EXISTS `Vehicle`; -/*!50001 DROP VIEW IF EXISTS `Vehicle`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Vehicle` AS SELECT - 1 AS `id`, - 1 AS `numberPlate`, - 1 AS `tradeMark`, - 1 AS `model`, - 1 AS `companyFk`, - 1 AS `warehouseFk`, - 1 AS `description`, - 1 AS `m3`, - 1 AS `isActive`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Warehouse` --- - -DROP TABLE IF EXISTS `Warehouse`; -/*!50001 DROP VIEW IF EXISTS `Warehouse`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Warehouse` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `tpv`, - 1 AS `inventory`, - 1 AS `isManaged`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `WarehouseAlias` --- - -DROP TABLE IF EXISTS `WarehouseAlias`; -/*!50001 DROP VIEW IF EXISTS `WarehouseAlias`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `WarehouseAlias` AS SELECT - 1 AS `id`, - 1 AS `name`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Worker` --- - -DROP TABLE IF EXISTS `Worker`; -/*!50001 DROP VIEW IF EXISTS `Worker`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Worker` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `surname`, - 1 AS `userFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `Zone` --- - -DROP TABLE IF EXISTS `Zone`; -/*!50001 DROP VIEW IF EXISTS `Zone`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Zone` AS SELECT - 1 AS `id`, - 1 AS `name`, - 1 AS `printingOrder`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `user` --- - -DROP TABLE IF EXISTS `user`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `user` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `realm` varchar(512) CHARACTER SET utf8 DEFAULT NULL, - `username` varchar(512) CHARACTER SET utf8 DEFAULT NULL, - `password` varchar(512) CHARACTER SET utf8 NOT NULL, - `email` varchar(512) CHARACTER SET utf8 NOT NULL, - `emailVerified` tinyint(1) DEFAULT NULL, - `verificationToken` varchar(512) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=50054 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'salix' --- - --- --- Dumping routines for database 'salix' --- -/*!50003 DROP PROCEDURE IF EXISTS `production_control_source` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `production_control_source`(idWarehouse INT, scopeDays TINYINT) -BEGIN - CALL vn2008.production_control_source(idWarehouse, scopeDays); - - SET @id = 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.production; - CREATE TEMPORARY TABLE tmp.production - ENGINE = MEMORY - SELECT - @id := @id+1 id, - p.Id_Ticket ticketFk, - p.Id_Cliente clientFk, - p.Alias client, - p.Fecha `date`, - p.Hora hour, - p.POBLACION city, - p.PROVINCIA province, - p.province_id provinceFk, - p.Agencia agency, - p.agency_id agencyFk, - p.lines, - p.m3, - p.problems, - p.problem, - p.state stateFk, - t.Id_Trabajador workerfk, - CONCAT(t.Nombre, ' ', t.Apellidos) worker, - tt.Id_Trabajador salesPersonFk, - CONCAT(tt.Nombre, ' ', tt.Apellidos) salesPerson, - s.name state, - p.Cajas boxes, - p.Id_Ruta routeFk - FROM tmp.production_buffer p - JOIN vn2008.state s ON p.state = s.id - JOIN vn2008.Trabajadores t ON p.CodigoTrabajador = t.CodigoTrabajador COLLATE utf8_unicode_ci - JOIN vn2008.Trabajadores tt ON p.Comercial = tt.CodigoTrabajador COLLATE utf8_unicode_ci; - - DROP TEMPORARY TABLE tmp.production_buffer; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Current Database: `vncontrol` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vncontrol` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `vncontrol`; - --- --- Table structure for table `accion` --- - -DROP TABLE IF EXISTS `accion`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `accion` ( - `accion_id` int(11) NOT NULL AUTO_INCREMENT, - `accion` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`accion_id`) -) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `clientes_match` --- - -DROP TABLE IF EXISTS `clientes_match`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `clientes_match` ( - `Id_cliente` int(11) NOT NULL, - `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `dailyTaskLog` --- - -DROP TABLE IF EXISTS `dailyTaskLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `dailyTaskLog` ( - `state` varchar(250) COLLATE utf8_unicode_ci NOT NULL, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='No he encontrado el lugar en el que vicente almacena la hora en que se ejecutan las daily tasks, asi que he hecho esta tabla, a eliminar cuando se considere oportuno'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `fallo` --- - -DROP TABLE IF EXISTS `fallo`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `fallo` ( - `queja_id` int(10) unsigned NOT NULL, - `accion_id` int(11) NOT NULL, - PRIMARY KEY (`queja_id`,`accion_id`), - KEY `accion` (`accion_id`,`queja_id`), - KEY `fallo` (`queja_id`), - CONSTRAINT `accion` FOREIGN KEY (`accion_id`) REFERENCES `accion` (`accion_id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `inter` --- - -DROP TABLE IF EXISTS `inter`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `inter` ( - `inter_id` int(11) NOT NULL AUTO_INCREMENT, - `state_id` tinyint(3) unsigned NOT NULL, - `fallo_id` int(10) unsigned NOT NULL DEFAULT '21', - `nota` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `Id_Ticket` int(11) DEFAULT NULL, - `Id_Trabajador` int(11) DEFAULT NULL, - `Id_Supervisor` int(11) DEFAULT NULL, - PRIMARY KEY (`inter_id`), - KEY `currante` (`Id_Trabajador`), - KEY `responsable` (`Id_Supervisor`), - KEY `ticket` (`Id_Ticket`), - KEY `inter_state` (`state_id`), - CONSTRAINT `currante` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE, - CONSTRAINT `inter_ibfk_1` FOREIGN KEY (`Id_Ticket`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `inter_state` FOREIGN KEY (`state_id`) REFERENCES `vn2008`.`state` (`id`) ON UPDATE CASCADE, - CONSTRAINT `responsable` FOREIGN KEY (`Id_Supervisor`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=9384779 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `interBeforeInsert` -BEFORE INSERT ON `inter` FOR EACH ROW -BEGIN - - DECLARE contados INT; - DECLARE vSupervisor INT; - - SELECT Id_Trabajador INTO vSupervisor FROM vn2008.Trabajadores WHERE user_id = account.userGetId(); - - SET NEW.Id_Supervisor = IFNULL(vSupervisor,20); - - IF NEW.state_id = 5 - THEN - SELECT count(Id_Ticket) INTO contados - FROM vncontrol.inter - WHERE state_id = 5 - AND Id_Ticket = NEW.Id_Ticket - AND IFNULL(Id_Supervisor,-1) <> vSupervisor - AND TIMESTAMPADD(SECOND, 60, odbc_date) >= NOW(); - - IF contados <> 0 THEN - CALL util.throw ('FALLO_AL_INSERTAR'); - END IF; - END IF; - -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vncontrol`.`interAfterInsert` -AFTER INSERT ON `inter` FOR EACH ROW -BEGIN - REPLACE vn2008.Tickets_state(Id_Ticket, inter_id,state_name) - SELECT NEW.Id_Ticket, NEW.inter_id, s.`name` FROM vn2008.state s WHERE s.id = NEW.state_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_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vncontrol`.`interAfterUpdate` -AFTER UPDATE ON `inter` FOR EACH ROW -BEGIN - DECLARE intIdTicket INT; - DECLARE intInterId INT; - DECLARE strName VARCHAR(15); - - IF (NEW.state_id <> OLD.state_id) THEN - REPLACE INTO vn2008.Tickets_state(Id_Ticket, inter_id,state_name) - SELECT NEW.Id_Ticket, NEW.inter_id, s.`name` - FROM vn2008.state s WHERE s.id = NEW.state_id; - END IF; - IF (NEW.Id_Ticket <> OLD.Id_Ticket) THEN - - SELECT i.Id_Ticket, i.inter_id, s.`name` - INTO intIdTicket, intInterId, strName - FROM vncontrol.inter i - JOIN vn2008.state s ON i.state_id = s.id - WHERE Id_Ticket = NEW.Id_Ticket - ORDER BY odbc_date DESC - LIMIT 1; - IF intIdTicket > 0 THEN - REPLACE INTO vn2008.Tickets_state(Id_Ticket, inter_id,state_name) - VALUES(intIdTicket, intInterId, strName); - END IF; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vncontrol`.`interAfterDelete` -AFTER DELETE ON `inter` FOR EACH ROW -BEGIN - DECLARE intIdTicket INT; - DECLARE intInterId INT; - DECLARE strName VARCHAR(15); - - DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' - BEGIN - DELETE FROM vn2008.Tickets_state - WHERE Id_Ticket = OLD.Id_Ticket; - END; - - IF OLD.odbc_date > TIMESTAMPADD(WEEK, -1, CURDATE()) THEN - - SELECT i.Id_Ticket, i.inter_id, s.`name` - INTO intIdTicket, intInterId, strName - FROM vncontrol.inter i - JOIN vn2008.state s ON i.state_id = s.id - WHERE Id_Ticket = OLD.Id_Ticket - ORDER BY odbc_date DESC - LIMIT 1; - - IF intIdTicket > 0 THEN - REPLACE INTO vn2008.Tickets_state(Id_Ticket, inter_id,state_name) - VALUES (intIdTicket, intInterId, strName); - END IF; - - 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 */ ; - --- --- Dumping events for database 'vncontrol' --- - --- --- Dumping routines for database 'vncontrol' --- -/*!50003 DROP PROCEDURE IF EXISTS `clean` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN - - DECLARE v_date2 DATETIME DEFAULT TIMESTAMPADD(MONTH, -2,CURDATE()); - - INSERT INTO vncontrol.dailyTaskLog(state) VALUES('clean START'); - - DELETE FROM vncontrol.inter WHERE odbc_date <= v_date2; - - INSERT INTO vncontrol.dailyTaskLog(state) VALUES('clean END'); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ResumenKK` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ResumenKK`() -BEGIN - -select accion, CodigoTrabajador, semana, Pedidos, Lineas -from accion -join -( - SELECT * FROM - ( - select count(*) as Pedidos, semana, Id_Trabajador, accion_id - from - (select distinct * - from - ( - select vn2008.semana(odbc_date) as semana - ,Id_Trabajador - ,accion_id - ,Id_Ticket - from vncontrol.inter - ) sub - ) sub2 - group by semana, Id_Trabajador, accion_id - ) subpedidos - - inner join - ( - - select semana, Id_Trabajador, accion_id, count(*) as Lineas - from vn2008.Movimientos - inner join - ( - select distinct vn2008.semana(odbc_date) as semana, Id_Ticket, Id_Trabajador, accion_id from vncontrol.inter - ) vnc using(Id_Ticket) - group by semana, Id_Trabajador, accion_id - - ) sublineas using(semana, Id_Trabajador, accion_id) - -) sub3 using(accion_id) - -join vn2008.Trabajadores using(Id_Trabajador) -; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Current Database: `hedera` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `hedera` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `hedera`; - --- --- Temporary view structure for view `address_view` --- - -DROP TABLE IF EXISTS `address_view`; -/*!50001 DROP VIEW IF EXISTS `address_view`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `address_view` AS SELECT - 1 AS `id`, - 1 AS `customer_id`, - 1 AS `warehouse_id`, - 1 AS `name`, - 1 AS `city`, - 1 AS `province_id`, - 1 AS `zip_code`, - 1 AS `consignee`, - 1 AS `default`, - 1 AS `type_id`, - 1 AS `specs`, - 1 AS `insurance`, - 1 AS `postage`, - 1 AS `active`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `androidUser` --- - -DROP TABLE IF EXISTS `androidUser`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `androidUser` ( - `androidId` varchar(200) CHARACTER SET utf8 NOT NULL, - `userFk` int(10) unsigned NOT NULL, - PRIMARY KEY (`userFk`,`androidId`), - CONSTRAINT `androidUser_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `basket` --- - -DROP TABLE IF EXISTS `basket`; -/*!50001 DROP VIEW IF EXISTS `basket`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `basket` AS SELECT - 1 AS `id`, - 1 AS `date_make`, - 1 AS `date_send`, - 1 AS `customer_id`, - 1 AS `delivery_method_id`, - 1 AS `agency_id`, - 1 AS `address_id`, - 1 AS `company_id`, - 1 AS `note`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `basketOrder` --- - -DROP TABLE IF EXISTS `basketOrder`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `basketOrder` ( - `clientFk` int(11) NOT NULL, - `orderFk` int(10) unsigned NOT NULL, - PRIMARY KEY (`orderFk`,`clientFk`), - UNIQUE KEY `customer_id` (`clientFk`), - CONSTRAINT `basketOrder_ibfk_1` FOREIGN KEY (`orderFk`, `clientFk`) REFERENCES `order` (`id`, `customer_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `basketOrder_ibfk_2` FOREIGN KEY (`orderFk`) REFERENCES `order` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `basketOrder_ibfk_3` FOREIGN KEY (`clientFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `basket_defaults` --- - -DROP TABLE IF EXISTS `basket_defaults`; -/*!50001 DROP VIEW IF EXISTS `basket_defaults`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `basket_defaults` AS SELECT - 1 AS `address_id`, - 1 AS `agency_id`, - 1 AS `delivery_method`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `basket_item` --- - -DROP TABLE IF EXISTS `basket_item`; -/*!50001 DROP VIEW IF EXISTS `basket_item`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `basket_item` AS SELECT - 1 AS `id`, - 1 AS `order_id`, - 1 AS `warehouse_id`, - 1 AS `item_id`, - 1 AS `amount`, - 1 AS `price`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `browser` --- - -DROP TABLE IF EXISTS `browser`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `browser` ( - `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Browser name in browscap', - `version` float NOT NULL COMMENT 'Minimal version', - UNIQUE KEY `name` (`name`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='List of compatible web browsers and its version'; -/*!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` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `defaultLang` char(2) CHARACTER SET utf8 NOT NULL COMMENT 'The default language if none is specified', - `https` tinyint(3) unsigned NOT NULL COMMENT 'Wether to force de use of HTTPS', - `cookieLife` smallint(5) unsigned NOT NULL COMMENT 'The cookies life, in days', - `jwtKey` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The key used to encode/decode JWT tokens', - `default_form` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Form loaded at web login', - `restUri` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `testRestUri` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `image_host` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, - `image_dir` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Directory where images are allocated', - `guest_user` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Guest user name', - `guest_pass` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Guest password, base64 encoded', - `test_domain` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The address for beta website', - `production_domain` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The address for production website', - `pdfs_dir` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Directory where pdfs are allocated', - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration parameters'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `contact` --- - -DROP TABLE IF EXISTS `contact`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `contact` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `recipient` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `customer_view` --- - -DROP TABLE IF EXISTS `customer_view`; -/*!50001 DROP VIEW IF EXISTS `customer_view`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `customer_view` AS SELECT - 1 AS `user_id`, - 1 AS `name`, - 1 AS `email`, - 1 AS `mail`, - 1 AS `default_address`, - 1 AS `credit`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `imageCollection` --- - -DROP TABLE IF EXISTS `imageCollection`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `imageCollection` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `desc` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `maxWidth` int(10) unsigned NOT NULL, - `maxHeight` int(10) unsigned NOT NULL, - `schema` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `table` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `column` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `name` (`name`) -) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `imageCollectionSize` --- - -DROP TABLE IF EXISTS `imageCollectionSize`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `imageCollectionSize` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `collectionFk` int(10) unsigned NOT NULL, - `width` int(10) unsigned NOT NULL, - `height` int(10) unsigned NOT NULL, - `crop` tinyint(3) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - KEY `image_schema_id` (`collectionFk`), - CONSTRAINT `imageCollectionSize_ibfk_1` FOREIGN KEY (`collectionFk`) REFERENCES `imageCollection` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `imageConfig` --- - -DROP TABLE IF EXISTS `imageConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `imageConfig` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Identifier', - `maxSize` int(10) unsigned NOT NULL COMMENT 'Maximun size for uploaded images in MB', - `useXsendfile` tinyint(4) NOT NULL COMMENT 'Whether to use the apache module XSendfile', - `url` varchar(255) NOT NULL COMMENT 'Public URL where image are hosted', - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='Global image parameters'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `imageFile` --- - -DROP TABLE IF EXISTS `imageFile`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `imageFile` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `schemaFk` int(10) unsigned NOT NULL, - `file` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `stamp` int(11) DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `schema_id_file` (`schemaFk`,`file`), - CONSTRAINT `imageFile_ibfk_1` FOREIGN KEY (`schemaFk`) REFERENCES `imageCollection` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=32793 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `invoice_view` --- - -DROP TABLE IF EXISTS `invoice_view`; -/*!50001 DROP VIEW IF EXISTS `invoice_view`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `invoice_view` AS SELECT - 1 AS `invoice_id`, - 1 AS `serial_num`, - 1 AS `issued`, - 1 AS `amount`*/; -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) CHARACTER SET utf8 NOT NULL, - `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, - `orgName` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `isActive` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`code`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!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` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `image` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=37 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `location` --- - -DROP TABLE IF EXISTS `location`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `location` ( - `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `lat` varchar(12) COLLATE utf8_unicode_ci NOT NULL, - `lng` varchar(12) COLLATE utf8_unicode_ci NOT NULL, - `title` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `address` varchar(75) COLLATE utf8_unicode_ci DEFAULT NULL, - `postcode` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `city` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `province` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `phone` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, - `language` char(2) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `mailConfig` --- - -DROP TABLE IF EXISTS `mailConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mailConfig` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Identifier', - `host` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'localhost' COMMENT 'SMTP host', - `port` smallint(6) NOT NULL DEFAULT '465' COMMENT 'SMTP port', - `secure` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Wether to use a secure connection', - `sender` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The sender mail address', - `senderName` varchar(75) CHARACTER SET utf8 NOT NULL COMMENT 'The sender name', - `user` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'SMTP user', - `password` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'SMTP password, base64 encoded', - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `menu` --- - -DROP TABLE IF EXISTS `menu`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `menu` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `description` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `path` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `roleFk` int(10) unsigned NOT NULL, - `parentFk` int(10) unsigned DEFAULT NULL, - `displayOrder` tinyint(4) unsigned NOT NULL DEFAULT '1', - PRIMARY KEY (`id`), - KEY `group_id` (`roleFk`), - KEY `parent` (`parentFk`), - CONSTRAINT `menu_ibfk_1` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `message` --- - -DROP TABLE IF EXISTS `message`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `message` ( - `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, - `code` char(35) COLLATE utf8_unicode_ci NOT NULL, - `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `code` (`code`) -) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `metatag` --- - -DROP TABLE IF EXISTS `metatag`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `metatag` ( - `id` int(11) NOT NULL, - `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `content` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `name` (`name`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `myAddress` --- - -DROP TABLE IF EXISTS `myAddress`; -/*!50001 DROP VIEW IF EXISTS `myAddress`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `myAddress` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `street`, - 1 AS `city`, - 1 AS `postalCode`, - 1 AS `provinceFk`, - 1 AS `nickname`, - 1 AS `isDefaultAddress`, - 1 AS `isActive`, - 1 AS `longitude`, - 1 AS `latitude`, - 1 AS `warehouseFk`, - 1 AS `agencyModeFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `myClient` --- - -DROP TABLE IF EXISTS `myClient`; -/*!50001 DROP VIEW IF EXISTS `myClient`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `myClient` AS SELECT - 1 AS `id`, - 1 AS `isToBeMailed`, - 1 AS `defaultAddressFk`, - 1 AS `credit`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `myInvoice` --- - -DROP TABLE IF EXISTS `myInvoice`; -/*!50001 DROP VIEW IF EXISTS `myInvoice`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `myInvoice` AS SELECT - 1 AS `id`, - 1 AS `ref`, - 1 AS `issued`, - 1 AS `amount`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `myMenu` --- - -DROP TABLE IF EXISTS `myMenu`; -/*!50001 DROP VIEW IF EXISTS `myMenu`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `myMenu` AS SELECT - 1 AS `id`, - 1 AS `path`, - 1 AS `description`, - 1 AS `parentFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `myTicket` --- - -DROP TABLE IF EXISTS `myTicket`; -/*!50001 DROP VIEW IF EXISTS `myTicket`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `myTicket` AS SELECT - 1 AS `id`, - 1 AS `clientFk`, - 1 AS `warehouseFk`, - 1 AS `shipped`, - 1 AS `landed`, - 1 AS `nickname`, - 1 AS `agencyModeFk`, - 1 AS `refFk`, - 1 AS `addressFk`, - 1 AS `location`, - 1 AS `companyFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `myTicketRow` --- - -DROP TABLE IF EXISTS `myTicketRow`; -/*!50001 DROP VIEW IF EXISTS `myTicketRow`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `myTicketRow` AS SELECT - 1 AS `id`, - 1 AS `itemFk`, - 1 AS `ticketFk`, - 1 AS `concept`, - 1 AS `quantity`, - 1 AS `price`, - 1 AS `discount`, - 1 AS `reserved`, - 1 AS `isPicked`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `myTpvTransaction` --- - -DROP TABLE IF EXISTS `myTpvTransaction`; -/*!50001 DROP VIEW IF EXISTS `myTpvTransaction`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `myTpvTransaction` AS SELECT - 1 AS `id`, - 1 AS `merchantFk`, - 1 AS `clientFk`, - 1 AS `receiptFk`, - 1 AS `amount`, - 1 AS `response`, - 1 AS `status`, - 1 AS `created`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `news` --- - -DROP TABLE IF EXISTS `news`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `news` ( - `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `title` varchar(150) COLLATE utf8_unicode_ci NOT NULL, - `text` text COLLATE utf8_unicode_ci NOT NULL, - `image` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - `userFk` int(10) unsigned NOT NULL, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `priority` tinyint(3) unsigned NOT NULL DEFAULT '3', - `tag` varchar(15) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'new', - `__date_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Deprecated', - `__user_id` int(10) NOT NULL COMMENT 'Deprecated', - PRIMARY KEY (`id`), - KEY `user` (`userFk`), - KEY `tag` (`tag`), - CONSTRAINT `news_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`account` (`id`) ON UPDATE CASCADE, - CONSTRAINT `news_ibfk_2` FOREIGN KEY (`tag`) REFERENCES `newsTag` (`name`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=12999 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `newsTag` --- - -DROP TABLE IF EXISTS `newsTag`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `newsTag` ( - `name` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - `description` varchar(25) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`name`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `order` --- - -DROP TABLE IF EXISTS `order`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `order` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `date_send` date NOT NULL DEFAULT '0000-00-00', - `customer_id` int(11) NOT NULL, - `delivery_method_id` int(11) DEFAULT '3', - `agency_id` int(11) DEFAULT '2', - `address_id` int(11) DEFAULT NULL, - `company_id` smallint(5) unsigned NOT NULL DEFAULT '442', - `note` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `source_app` set('WEB','ANDROID','IOS','TPV','TABLET_VN','') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'TPV', - `is_bionic` tinyint(1) NOT NULL DEFAULT '1', - `confirmed` tinyint(1) NOT NULL DEFAULT '0', - `date_make` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `first_row_stamp` datetime DEFAULT NULL, - `confirm_date` datetime DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `address` (`address_id`), - KEY `delivery_method` (`delivery_method_id`), - KEY `agency` (`agency_id`), - KEY `customer_id` (`customer_id`), - KEY `company_id` (`company_id`), - KEY `id` (`id`,`customer_id`), - KEY `source_app` (`source_app`), - KEY `confirmed` (`confirmed`), - CONSTRAINT `order_ibfk_5` FOREIGN KEY (`address_id`) REFERENCES `vn2008`.`Consignatarios` (`id_consigna`) ON UPDATE CASCADE, - CONSTRAINT `order_ibfk_8` FOREIGN KEY (`delivery_method_id`) REFERENCES `vn2008`.`Vistas` (`vista_id`) ON UPDATE CASCADE, - CONSTRAINT `order_ibfk_9` FOREIGN KEY (`agency_id`) REFERENCES `vn2008`.`Agencias` (`Id_Agencia`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=1288000 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `orderCheck` --- - -DROP TABLE IF EXISTS `orderCheck`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `orderCheck` ( - `id` tinyint(1) unsigned NOT NULL AUTO_INCREMENT, - `maxTime` time NOT NULL, - `denySunday` tinyint(1) NOT NULL, - `denyDay` date DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Conditions to check when an order is confirmed'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `orderCheckFestive` --- - -DROP TABLE IF EXISTS `orderCheckFestive`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `orderCheckFestive` ( - `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, - `date` date NOT NULL, - `acceptOrders` tinyint(1) NOT NULL DEFAULT '1', - PRIMARY KEY (`id`), - UNIQUE KEY `date` (`date`) -) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `orderCheckWday` --- - -DROP TABLE IF EXISTS `orderCheckWday`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `orderCheckWday` ( - `weekday` tinyint(3) unsigned NOT NULL COMMENT '0 = Monday, 6 = Sunday', - `maxTime` time NOT NULL, - PRIMARY KEY (`weekday`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `orderConfig` --- - -DROP TABLE IF EXISTS `orderConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `orderConfig` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `employeeFk` int(11) NOT NULL, - `guestMethod` varchar(45) CHARACTER SET utf8 NOT NULL, - `guestAgencyFk` int(11) NOT NULL, - `reserveTime` time NOT NULL, - `defaultCompanyFk` smallint(6) unsigned DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `employeeFk` (`employeeFk`), - KEY `guestAgencyFk` (`guestAgencyFk`), - KEY `defaultCompanyFk` (`defaultCompanyFk`), - KEY `guestMethod` (`guestMethod`), - CONSTRAINT `orderConfig_ibfk_1` FOREIGN KEY (`employeeFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE, - CONSTRAINT `orderConfig_ibfk_2` FOREIGN KEY (`defaultCompanyFk`) REFERENCES `vn2008`.`empresa` (`id`) ON UPDATE CASCADE, - CONSTRAINT `orderConfig_ibfk_3` FOREIGN KEY (`guestAgencyFk`) REFERENCES `vn2008`.`Agencias` (`Id_Agencia`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `orderRow` --- - -DROP TABLE IF EXISTS `orderRow`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `orderRow` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `orderFk` int(10) unsigned NOT NULL DEFAULT '0', - `itemFk` int(11) NOT NULL DEFAULT '0', - `warehouseFk` int(11) DEFAULT NULL, - `shipment` date DEFAULT NULL, - `amount` smallint(6) unsigned NOT NULL DEFAULT '0', - `price` decimal(10,2) DEFAULT NULL, - `rate` smallint(5) unsigned DEFAULT NULL, - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `saleFk` int(11) DEFAULT NULL COMMENT 'Deprecated', - PRIMARY KEY (`id`), - KEY `item` (`itemFk`), - KEY `order_id` (`orderFk`), - KEY `created` (`created`), - KEY `warehouse_shipment` (`warehouseFk`,`shipment`), - CONSTRAINT `orderRow_ibfk_2` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON UPDATE CASCADE, - CONSTRAINT `orderRow_ibfk_3` FOREIGN KEY (`orderFk`) REFERENCES `order` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=7994327 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `orderRowBeforeInsert` - BEFORE INSERT ON `orderRow` - FOR EACH ROW -BEGIN - DECLARE vIsFirst BOOL; - - SELECT (first_row_stamp IS NULL) INTO vIsFirst - FROM `order` - WHERE id = NEW.orderFk; - - IF vIsFirst THEN - UPDATE `order` SET first_row_stamp = NOW() - WHERE id = NEW.orderFk; - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Table structure for table `orderRowComponent` --- - -DROP TABLE IF EXISTS `orderRowComponent`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `orderRowComponent` ( - `rowFk` int(10) unsigned NOT NULL, - `componentFk` int(11) NOT NULL, - `price` decimal(12,4) NOT NULL, - PRIMARY KEY (`rowFk`,`componentFk`), - KEY `component_id` (`componentFk`), - CONSTRAINT `orderRowComponent_ibfk_1` FOREIGN KEY (`rowFk`) REFERENCES `orderRow` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `order_basket` --- - -DROP TABLE IF EXISTS `order_basket`; -/*!50001 DROP VIEW IF EXISTS `order_basket`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `order_basket` AS SELECT - 1 AS `customer_id`, - 1 AS `order_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `order_component` --- - -DROP TABLE IF EXISTS `order_component`; -/*!50001 DROP VIEW IF EXISTS `order_component`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `order_component` AS SELECT - 1 AS `order_row_id`, - 1 AS `component_id`, - 1 AS `price`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `order_confirm_time` --- - -DROP TABLE IF EXISTS `order_confirm_time`; -/*!50001 DROP VIEW IF EXISTS `order_confirm_time`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `order_confirm_time` AS SELECT - 1 AS `date_make`, - 1 AS `source_app`, - 1 AS `customer_id`, - 1 AS `confirm_date`, - 1 AS `first_row_stamp`, - 1 AS `minutos`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `order_row` --- - -DROP TABLE IF EXISTS `order_row`; -/*!50001 DROP VIEW IF EXISTS `order_row`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `order_row` AS SELECT - 1 AS `id`, - 1 AS `order_id`, - 1 AS `item_id`, - 1 AS `warehouse_id`, - 1 AS `shipment`, - 1 AS `amount`, - 1 AS `price`, - 1 AS `rate`, - 1 AS `created`, - 1 AS `Id_Movimiento`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `order_row_view` --- - -DROP TABLE IF EXISTS `order_row_view`; -/*!50001 DROP VIEW IF EXISTS `order_row_view`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `order_row_view` AS SELECT - 1 AS `id`, - 1 AS `order_id`, - 1 AS `warehouse_id`, - 1 AS `item_id`, - 1 AS `amount`, - 1 AS `price2`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary view structure for view `order_view` --- - -DROP TABLE IF EXISTS `order_view`; -/*!50001 DROP VIEW IF EXISTS `order_view`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `order_view` AS SELECT - 1 AS `id`, - 1 AS `date_make`, - 1 AS `date_send`, - 1 AS `customer_id`, - 1 AS `delivery_method_id`, - 1 AS `agency_id`, - 1 AS `note`, - 1 AS `address_id`, - 1 AS `company_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `restPriv` --- - -DROP TABLE IF EXISTS `restPriv`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `restPriv` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `methodPath` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `role` int(10) unsigned NOT NULL, - PRIMARY KEY (`id`), - KEY `role` (`role`), - CONSTRAINT `restPriv_ibfk_1` FOREIGN KEY (`role`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `shelf` --- - -DROP TABLE IF EXISTS `shelf`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `shelf` ( - `id` int(10) unsigned NOT NULL, - `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `nTrays` tinyint(3) unsigned NOT NULL, - `trayheight` mediumint(8) unsigned NOT NULL, - `topTrayHeight` mediumint(8) unsigned NOT NULL, - `width` mediumint(8) unsigned NOT NULL, - `depth` mediumint(8) unsigned NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Dimensiones de las estanterias'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `shelfConfig` --- - -DROP TABLE IF EXISTS `shelfConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `shelfConfig` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, - `namePrefix` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - `warehouse` smallint(5) unsigned NOT NULL, - `family` smallint(5) unsigned NOT NULL, - `shelf` int(10) unsigned NOT NULL, - `maxAmount` smallint(5) unsigned DEFAULT NULL, - `showPacking` tinyint(4) NOT NULL, - `stack` tinyint(4) NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - KEY `shelf_id` (`shelf`), - KEY `family_id` (`family`), - KEY `warehouse_id` (`warehouse`), - CONSTRAINT `shelfConfig_ibfk_1` FOREIGN KEY (`family`) REFERENCES `vn2008`.`Tipos` (`tipo_id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `shelfConfig_ibfk_2` FOREIGN KEY (`shelf`) REFERENCES `shelf` (`id`) ON UPDATE CASCADE, - CONSTRAINT `shelfConfig_ibfk_3` FOREIGN KEY (`warehouse`) REFERENCES `vn2008`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `social` --- - -DROP TABLE IF EXISTS `social`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `social` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `title` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `icon` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `priority` tinyint(3) unsigned NOT NULL, - PRIMARY KEY (`id`), - KEY `priority` (`priority`) -) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `survey` --- - -DROP TABLE IF EXISTS `survey`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `survey` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `question` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `surveyAnswer` --- - -DROP TABLE IF EXISTS `surveyAnswer`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `surveyAnswer` ( - `id` int(10) unsigned NOT NULL, - `surveyFk` int(10) unsigned NOT NULL, - `answer` varchar(30) COLLATE utf8_unicode_ci NOT NULL, - `votes` int(10) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - KEY `survey` (`surveyFk`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `surveyVote` --- - -DROP TABLE IF EXISTS `surveyVote`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `surveyVote` ( - `surveyFk` int(10) unsigned NOT NULL, - `userFk` int(10) unsigned NOT NULL, - PRIMARY KEY (`surveyFk`,`userFk`), - KEY `surveyVote_ibfk_2` (`userFk`), - CONSTRAINT `surveyVote_ibfk_1` FOREIGN KEY (`surveyFk`) REFERENCES `survey` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `surveyVote_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tpvConfig` --- - -DROP TABLE IF EXISTS `tpvConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tpvConfig` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `currency` smallint(5) unsigned NOT NULL, - `terminal` tinyint(3) unsigned NOT NULL, - `transactionType` tinyint(3) unsigned NOT NULL, - `maxAmount` int(10) unsigned DEFAULT NULL, - `employeeFk` int(10) NOT NULL, - `url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The bank web service URL for production environment', - `testMode` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT 'Whether test mode is enabled', - `testUrl` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The bank web service URL for test environment', - `testKey` varchar(50) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The bank secret key for test environment', - `merchantUrl` varchar(255) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `employee_id` (`employeeFk`), - CONSTRAINT `employee_id` FOREIGN KEY (`employeeFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Virtual TPV parameters'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tpvError` --- - -DROP TABLE IF EXISTS `tpvError`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tpvError` ( - `code` char(7) COLLATE utf8_unicode_ci NOT NULL, - `message` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`code`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT=' List of possible TPV errors'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tpvImapConfig` --- - -DROP TABLE IF EXISTS `tpvImapConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tpvImapConfig` ( - `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, - `host` varchar(150) COLLATE utf8_unicode_ci NOT NULL, - `user` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `pass` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `cleanPeriod` varchar(15) CHARACTER SET utf8 NOT NULL, - `successFolder` varchar(150) CHARACTER SET utf8 DEFAULT NULL, - `errorFolder` varchar(150) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='IMAP configuration parameters for virtual TPV'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tpvMerchant` --- - -DROP TABLE IF EXISTS `tpvMerchant`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tpvMerchant` ( - `id` int(10) unsigned NOT NULL COMMENT 'Merchant identifier', - `description` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Small description', - `companyFk` smallint(6) unsigned DEFAULT NULL COMMENT 'Company associated with the merchant', - `bankFk` int(10) NOT NULL COMMENT 'The bank where merchant receipts are created', - `secretKey` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The merchant secret key to sign transactions', - PRIMARY KEY (`id`), - KEY `bank_id` (`bankFk`), - KEY `company_id` (`companyFk`), - KEY `id` (`id`,`companyFk`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Virtual TPV providers'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tpvMerchantEnable` --- - -DROP TABLE IF EXISTS `tpvMerchantEnable`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tpvMerchantEnable` ( - `merchantFk` int(10) unsigned NOT NULL DEFAULT '0', - `companyFk` smallint(6) unsigned NOT NULL, - PRIMARY KEY (`merchantFk`,`companyFk`), - UNIQUE KEY `company_id` (`companyFk`), - CONSTRAINT `tpvMerchantEnable_ibfk_1` FOREIGN KEY (`merchantFk`, `companyFk`) REFERENCES `tpvMerchant` (`id`, `companyFk`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Virtual TPV enabled providers'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tpvResponse` --- - -DROP TABLE IF EXISTS `tpvResponse`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tpvResponse` ( - `id` smallint(5) unsigned NOT NULL, - `message` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='List of possible TPV reponses'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `tpvTransaction` --- - -DROP TABLE IF EXISTS `tpvTransaction`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `tpvTransaction` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `merchantFk` int(10) unsigned NOT NULL, - `clientFk` int(11) NOT NULL, - `receiptFk` int(11) DEFAULT NULL, - `amount` int(10) unsigned NOT NULL, - `response` smallint(5) unsigned DEFAULT NULL COMMENT 'Status notified by bank: NULL if no notification, 0 if success, error otherwise', - `errorCode` char(7) COLLATE utf8_unicode_ci DEFAULT NULL, - `status` enum('started','ok','ko') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'started', - `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `merchant_id` (`merchantFk`), - KEY `receipt_id` (`receiptFk`), - KEY `user_id` (`clientFk`), - KEY `response` (`response`), - KEY `error_code` (`errorCode`), - CONSTRAINT `receipt_id` FOREIGN KEY (`receiptFk`) REFERENCES `vn2008`.`Recibos` (`Id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `tpvTransaction_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `tpvTransaction_ibfk_2` FOREIGN KEY (`merchantFk`) REFERENCES `tpvMerchant` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=195778 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Transactions realized through the virtual TPV'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `userSession` --- - -DROP TABLE IF EXISTS `userSession`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `userSession` ( - `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `lastUpdate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `ssid` char(64) COLLATE utf8_unicode_ci DEFAULT NULL, - `data` text COLLATE utf8_unicode_ci, - `userVisit` int(10) unsigned DEFAULT NULL, - UNIQUE KEY `ssid` (`ssid`), - KEY `userVisit` (`userVisit`), - KEY `lastUpdate` (`lastUpdate`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary view structure for view `user_android` --- - -DROP TABLE IF EXISTS `user_android`; -/*!50001 DROP VIEW IF EXISTS `user_android`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `user_android` AS SELECT - 1 AS `android_id`, - 1 AS `user_id`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `visit` --- - -DROP TABLE IF EXISTS `visit`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `visit` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `firstAgent` int(10) unsigned DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `firstAgent` (`firstAgent`), - CONSTRAINT `visit_ibfk_1` FOREIGN KEY (`firstAgent`) REFERENCES `visitAgent` (`id`) ON DELETE SET NULL ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=1187533 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `visitAccess` --- - -DROP TABLE IF EXISTS `visitAccess`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `visitAccess` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `agent` int(10) unsigned NOT NULL, - `stamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `ip` int(10) unsigned DEFAULT NULL, - `referer` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `visit_access_idx_agent` (`agent`), - KEY `stamp` (`stamp`), - CONSTRAINT `visitAccess_ibfk_1` FOREIGN KEY (`agent`) REFERENCES `visitAgent` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2541962 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `visitAgent` --- - -DROP TABLE IF EXISTS `visitAgent`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `visitAgent` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `visit` int(10) unsigned NOT NULL, - `firstAccess` int(10) unsigned DEFAULT NULL, - `platform` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, - `browser` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, - `version` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, - `javascript` tinyint(3) unsigned DEFAULT NULL, - `cookies` tinyint(3) unsigned DEFAULT NULL, - `agent` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `visit_id` (`visit`), - KEY `firstAccess` (`firstAccess`), - CONSTRAINT `visitAgent_ibfk_1` FOREIGN KEY (`visit`) REFERENCES `visit` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `visitAgent_ibfk_2` FOREIGN KEY (`firstAccess`) REFERENCES `visitAccess` (`id`) ON DELETE SET NULL ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=1713434 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `visitUser` --- - -DROP TABLE IF EXISTS `visitUser`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `visitUser` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `access` int(10) unsigned NOT NULL, - `user` int(10) unsigned DEFAULT NULL, - `stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `access_id` (`access`), - KEY `date_time` (`stamp`), - KEY `user_id` (`user`), - CONSTRAINT `visitUser_ibfk_1` FOREIGN KEY (`access`) REFERENCES `visitAccess` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=2452966 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'hedera' --- - --- --- Dumping routines for database 'hedera' --- -/*!50003 DROP FUNCTION IF EXISTS `basketGetId` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `basketGetId`() RETURNS int(11) - DETERMINISTIC -BEGIN - DECLARE v_order INT; - - SELECT order_id INTO v_order FROM order_basket - WHERE customer_id = account.userGetId(); - - RETURN v_order; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `invoiceGetPath` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `invoiceGetPath`(vInvoice INT) RETURNS varchar(255) CHARSET utf8 -BEGIN - DECLARE vIssued DATE; - DECLARE vSerial VARCHAR(15); - - SELECT issued, ref - INTO vIssued, vSerial - FROM vn.invoiceOut WHERE id = vInvoice; - - RETURN CONCAT_WS('/' - ,'invoice' - ,YEAR(vIssued) - ,MONTH(vIssued) - ,DAY(vIssued) - ,CONCAT(YEAR(vIssued), vSerial, '.pdf') - ); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `myClientGetDebt` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `myClientGetDebt`(vDate DATE) RETURNS decimal(10,2) -BEGIN -/** - * Calcula el saldo del cliente actual. - * - * @return Saldo del cliente - */ - RETURN vn.clientGetDebt(account.userGetId(), vDate); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `orderGetTotal` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `orderGetTotal`(vOrder INT) RETURNS decimal(10,2) - READS SQL DATA - DETERMINISTIC -BEGIN -/** - * Obtiene el total de un pedido con el IVA y el recargo de - * equivalencia incluidos. - * - * @param vOrder El identificador del pedido - * @return El total del pedido - */ - DECLARE vTotal DECIMAL(10,2); - - CALL orderGetTax (vOrder); - - SELECT SUM(taxBase) + SUM(tax) + SUM(equalizationTax) INTO vTotal - FROM tmp.orderTax; - - DROP TEMPORARY TABLE tmp.orderTax; - - RETURN vTotal; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `order_get_total` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `order_get_total`(vOrder INT) RETURNS decimal(10,2) - READS SQL DATA - DETERMINISTIC -BEGIN -/** - * Obtiene el total de un pedido con el IVA y el recargo de - * equivalencia incluidos. - * - * @deprecated Use function orderGetTotal() instead - * - * @param vOrder El identificador del pedido - * @return El total del pedido - */ - RETURN orderGetTotal (vOrder); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP FUNCTION IF EXISTS `userCheckRestPriv` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `userCheckRestPriv`(vMethodPath VARCHAR(255)) RETURNS tinyint(1) - DETERMINISTIC -BEGIN -/** - * Comprueba si el usuario actual tiene permiso para ejecutar - * un servicio REST. - * - * @param vMethodPath Ruta del servicio REST a ejecutar - * @return %TRUE si tiene permisos, %FALSE en caso contrario - **/ - DECLARE vRole INT DEFAULT NULL; - - SELECT role INTO vRole FROM restPriv - WHERE methodPath = vMethodPath; - - RETURN vRole IS NULL - OR account.userHasRoleId (vRole); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `basketAddItem` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `basketAddItem`( - vWarehouse INT, - vItem INT, - vAmount INT) -BEGIN - DECLARE vOrder INT; - DECLARE vRow INT; - DECLARE vAdd INT; - DECLARE vAvailable INT; - DECLARE vDone BOOL; - DECLARE vGrouping INT; - DECLARE vRate INT; - DECLARE vShipment DATE; - DECLARE vPrice DECIMAL(10,2); - - DECLARE cur CURSOR FOR - SELECT grouping, price, rate - FROM tmp.bionic_price - WHERE warehouse_id = vWarehouse - AND item_id = vItem - ORDER BY grouping DESC; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - CALL bionic_from_item (vItem); - - START TRANSACTION; - - SET vOrder = basketGetId(); - - SELECT Fecha_envio INTO vShipment - FROM tmp.travel_tree - WHERE warehouse_id = vWarehouse; - - SELECT available INTO vAvailable - FROM tmp.bionic_lot - WHERE warehouse_id = vWarehouse - AND item_id = vItem; - - IF vAmount > vAvailable - THEN - CALL util.throw ('ORDER_ROW_UNAVAILABLE'); - END IF; - - OPEN cur; - - l: LOOP - SET vDone = FALSE; - FETCH cur INTO vGrouping, vPrice, vRate; - - IF vDone THEN - LEAVE l; - END IF; - - SET vAdd = vAmount - MOD(vAmount, vGrouping); - SET vAmount = vAmount - vAdd; - - IF vAdd = 0 THEN - ITERATE l; - END IF; - - INSERT INTO order_row SET - order_id = vOrder, - item_id = vItem, - warehouse_id = vWarehouse, - shipment = vShipment, - rate = vRate, - amount = vAdd, - price = vPrice; - - SET vRow = LAST_INSERT_ID(); - - INSERT INTO order_component (order_row_id, component_id, price) - SELECT vRow, c.component_id, c.cost - FROM tmp.bionic_component c - JOIN bi.tarifa_componentes t - ON t.Id_Componente = c.component_id - AND (t.tarifa_class IS NULL OR t.tarifa_class = vRate) - WHERE c.warehouse_id = vWarehouse - AND c.item_id = vItem; - END LOOP; - - CLOSE cur; - COMMIT; - - CALL vn2008.bionic_free (); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `basketCheck` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `basketCheck`() -BEGIN -/** - * Comprueba que la cesta esta creada y que su configuración es - * correcta. Si la configuración es correcta pero lleva mucho - * tiempo creada actualiza los precios y cantidades de los artículos. - * - * @select El id del pedido y el estado de la cesta - */ - DECLARE vOrder INT; - DECLARE vCreated DATETIME; - DECLARE vStatus VARCHAR(15) DEFAULT 'OK'; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vStatus = 'NOT_EXISTS'; - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET vStatus = 'BAD_CONFIG'; - - SELECT id, date_make - INTO vOrder, vCreated - FROM basket; - - IF vStatus = 'OK' - THEN - CALL orderCheckConfig (vOrder); - - IF vStatus = 'OK' AND vCreated < TIMESTAMPADD(DAY, -1, NOW()) - THEN - CALL orderUpdate (vOrder); - SET vStatus = 'UPDATED'; - END IF; - END IF; - - SELECT vStatus stat; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `basketConfigure` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `basketConfigure`( - vDelivery DATE, - vDeliveryMethod VARCHAR(45), - vAgency INT, - vAddress INT) -BEGIN -/** - * Configura la cesta de la compra utilizando los parámetros - * pasados. Si los parámetros no son válidos devuelve un error. - * - * @param vDelivery Fecha de recogida - * @param vAgency Id de la agencia - * @param vAddress Id de dirección de envío, @NULL si es recogida - */ - DECLARE vOrder INT; - DECLARE vCompany INT; - DECLARE vDeliveryMethodId INT; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vOrder = NULL; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT id INTO vDeliveryMethodId - FROM vn.deliveryMethod - WHERE code = vDeliveryMethod; - - IF vDeliveryMethod = 'PICKUP' AND vAddress IS NULL - THEN - SELECT defaultAddressFk INTO vAddress - FROM myClient; - END IF; - - SET vOrder = basketGetId(); - - IF vOrder IS NULL - THEN - SELECT companyFk INTO vCompany - FROM vn.clientDefaultCompany - WHERE ClientFk = account.userGetId() - AND CURDATE() BETWEEN started AND finished - LIMIT 1; - - IF vCompany IS NULL - THEN - SELECT defaultCompanyFk INTO vCompany - FROM orderConfig; - END IF; - - INSERT INTO `order` - SET - customer_id = account.userGetId(), - date_send = vDelivery, - delivery_method_id = vDeliveryMethodId, - agency_id = vAgency, - address_id = vAddress, - source_app = 'WEB', - company_id = vCompany; - - SET vOrder = LAST_INSERT_ID(); - - INSERT INTO basketOrder SET - clientFk = account.userGetId(), - orderFk = vOrder; - ELSE - UPDATE `order` - SET - date_send = vDelivery, - delivery_method_id = vDeliveryMethodId, - agency_id = vAgency, - address_id = vAddress - WHERE - id = vOrder; - - CALL orderUpdate (vOrder); - END IF; - - CALL orderCheckConfig (vOrder); - - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `basketConfigureForGuest` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `basketConfigureForGuest`() -BEGIN - DECLARE vMethod VARCHAR(45); - DECLARE vAgency INT; - - SELECT guestMethod, guestAgencyFk - INTO vMethod, vAgency - FROM orderConfig - LIMIT 1; - - CALL basketConfigure (CURDATE(), vMethod, vAgency, NULL); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `basketConfirm` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `basketConfirm`() -BEGIN - DECLARE vOrder INT DEFAULT basketGetId (); - - IF vOrder IS NOT NULL - THEN - CALL order_confirm_bionic (vOrder); - - DELETE FROM order_basket - WHERE order_id = vOrder; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `basketGetTax` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `basketGetTax`() - READS SQL DATA -BEGIN -/** - * Returns the taxes for the current client basket. - * - * @treturn tmp.orderTax - */ - CALL orderGetTax (basketGetId()); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_calc` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_calc`() -BEGIN - DECLARE v_date DATE; - DECLARE v_address INT; - DECLARE v_agency INT; - - SELECT date_send, address_id, agency_id - INTO v_date, v_address, v_agency - FROM basket; - - CALL vn2008.bionic_calc (v_date, v_address, v_agency); - - IF account.userGetName () = 'visitor' - THEN - DROP TEMPORARY TABLE tmp.bionic_component; - UPDATE tmp.bionic_item SET price = NULL; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_from_basket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_from_basket`() -BEGIN - DECLARE v_order INT; - DECLARE v_date DATE; - DECLARE v_address INT; - DECLARE v_agency INT; - - SELECT id, date_send, address_id, agency_id - INTO v_order, v_date, v_address, v_agency - FROM basket; - - CALL vn2008.bionic_from_order (v_date, v_address, v_agency, v_order); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `bionic_from_item` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bionic_from_item`(v_item INT) -BEGIN - DECLARE v_date DATE; - DECLARE v_address INT; - DECLARE v_agency INT; - - SELECT date_send, address_id, agency_id - INTO v_date, v_address, v_agency - FROM basket; - - CALL vn2008.bionic_from_item (v_date, v_address, v_agency, v_item); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `catalogGetAvailable` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `catalogGetAvailable`() -BEGIN -/** - * Gets the available items list that meets the tag filter. - * - * @table tItems - */ - CALL itemGetAvailable; - - DELETE t FROM tItems t - JOIN tmp.itemAvailable a ON a.id = t.id - WHERE a.id IS NULL; - - DROP TEMPORARY TABLE tmp.itemAvailable; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `catalogGetItems` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `catalogGetItems`() -BEGIN -/** - * Returns the list of items. - * - * @table tItems The list of items - * @select The list of items - */ - DROP TEMPORARY TABLE IF EXISTS tmp.bionic_calc; - CREATE TEMPORARY TABLE tmp.bionic_calc - (INDEX (item_id)) - ENGINE = MEMORY - SELECT id item_id FROM tItems; - - CALL bionic_calc (); - DROP TEMPORARY TABLE tmp.bionic_calc; - - SELECT i.id, i.name, i.description, i.category, i.size, i.image, i.inkFk, - IF(i.stems > 1, i.stems, NULL) stems, b.available, b.price, b.producer, - a.tag1, a.val1, a.tag2, a.val2, a.tag3, a.val3 - FROM tmp.bionic_item b - JOIN vn.item i ON i.id = b.item_id - LEFT JOIN vn.itemTagArranged a ON a.itemFk = i.id - LEFT JOIN vn.producer p ON p.id = i.producerFk - WHERE b.available > 0 - ORDER BY i.relevancy DESC, i.name, i.size - LIMIT 40; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `catalogGetTags` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `catalogGetTags`(vLimit INT) -BEGIN -/** - * Returns the main tags for a list of items. - * - * @table tItems The list of items - * @select The main tags for the passed items - */ - CALL catalogGetAvailable; - - DROP TEMPORARY TABLE IF EXISTS tTags; - CREATE TEMPORARY TABLE tTags - (INDEX (tagFk)) - ENGINE = MEMORY - SELECT it.tagFk, SUM(it.priority) priority - FROM vn.itemTag it - JOIN tItems i ON i.id = it.itemFk - GROUP BY tagFk - LIMIT vLimit; - - SELECT l.id, l.name - FROM tTags t - JOIN vn.tagL10n l ON l.id = t.tagFk - ORDER BY priority DESC; - - DROP TEMPORARY TABLE tTags; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `catalogGetTagValues` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `catalogGetTagValues`(vTag INT) -BEGIN -/** - * Returns the list of available values for a tag and a list of items. - * - * @table tItems The list of items - * @param vTag The tag identifier - * @select The list of available tags - */ - CALL catalogGetAvailable; - - SELECT DISTINCT it.value - FROM vn.itemTag it - JOIN tItems i ON i.id = it.itemFk - WHERE it.tagFk = vTag - ORDER BY value - LIMIT 200; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemAllocator` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `itemAllocator`( - vWh TINYINT - ,vDate DATE - ,vType INT - ,vPrefix VARCHAR(255) - ,vUseIds BOOLEAN -) -BEGIN - DECLARE vPrefixLen SMALLINT; - DECLARE vFilter VARCHAR(255) DEFAULT NULL; - DECLARE vDateInv DATE DEFAULT vn2008.date_inv(); - - SET vPrefixLen = LENGTH(vPrefix); - - IF vPrefix IS NOT NULL AND vPrefixLen > 0 - THEN - SET vFilter = CONCAT(vPrefix, '%'); - SET vPrefixLen = vPrefixLen + 1; - END IF; - - DROP TEMPORARY TABLE IF EXISTS filter; - CREATE TEMPORARY TABLE filter - (INDEX (item_id)) - ENGINE = MEMORY - SELECT Id_Article item_id FROM vn2008.Articles - WHERE tipo_id = vType - AND (vFilter IS NULL OR Article LIKE vFilter); - - DROP TEMPORARY TABLE IF EXISTS current_stock; - CREATE TEMPORARY TABLE current_stock - (INDEX (item_id)) - ENGINE = MEMORY - SELECT item_id, SUM(Cantidad) amount FROM - ( - SELECT Id_Article item_id, Cantidad - FROM vn2008.Compres c - JOIN vn2008.Entradas e USING(Id_Entrada) - JOIN vn2008.travel t ON t.id = e.travel_id - WHERE landing BETWEEN vDateInv AND vDate - AND warehouse_id = vWh - AND NOT Redada - UNION ALL - SELECT Id_Article, -Cantidad - FROM vn2008.Compres c - JOIN vn2008.Entradas e USING(Id_Entrada) - JOIN vn2008.travel t ON t.id = e.travel_id - WHERE shipment BETWEEN vDateInv AND CURDATE() - AND warehouse_id_out = vWh - AND NOT Redada - AND delivered - UNION ALL - SELECT m.Id_Article, -m.Cantidad - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t USING(Id_Ticket) - JOIN vn.ticketState s ON s.ticket = t.Id_Ticket - WHERE t.Fecha BETWEEN vDateInv AND CURDATE() - AND t.warehouse_id = vWh - AND (t.Etiquetasemitidas OR s.alertLevel = 3) - ) t - GROUP BY item_id - HAVING amount > 0; - - DROP TEMPORARY TABLE IF EXISTS tmp; - CREATE TEMPORARY TABLE tmp - (INDEX (item_id)) - ENGINE = MEMORY - SELECT * FROM - ( - SELECT c.Id_Article item_id, c.Id_Compra id, c.Id_Cubo, c.packing - FROM vn2008.Compres c - JOIN vn2008.Entradas e USING(Id_Entrada) - JOIN vn2008.travel t ON t.id = e.travel_id - WHERE t.landing BETWEEN vDateInv AND vDate - AND c.Novincular = FALSE - AND c.Tarifa2 >= 0 - AND Id_Cubo IS NOT NULL - ORDER BY t.warehouse_id = 1 DESC, t.landing DESC - ) t GROUP BY item_id; - - DROP TEMPORARY TABLE IF EXISTS result; - CREATE TEMPORARY TABLE result - ENGINE = MEMORY - SELECT a.Id_Article, IF(vPrefixLen > 0, SUBSTRING(a.Article, vPrefixLen), a.Article) Article, - t.packing, CEIL(s.amount / t.packing) etiquetas, t.Id_Cubo, IF(c.z > 0, c.z, 0) z, c.x, c.y, a.Nicho - FROM vn2008.Articles a - JOIN filter f ON f.item_id = a.Id_Article - JOIN current_stock s ON s.item_id = a.Id_Article - LEFT JOIN tmp t ON t.item_id = a.Id_Article - LEFT JOIN vn2008.Cubos c ON c.Id_Cubo = t.Id_Cubo - WHERE CEIL(s.amount / t.packing) > 0 - AND c.box; - - IF vUseIds - THEN - SELECT * FROM result - ORDER BY Id_Article; - ELSE - SELECT * FROM result - ORDER BY Article, packing; - END IF; - - DROP TEMPORARY TABLE - filter, - current_stock, - tmp, - result; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemGetAvailable` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `itemGetAvailable`() -BEGIN -/** - * Gets the available items list. - * - * @table tmp.itemAvailable - */ - DECLARE vDelivery DATE; - DECLARE vAddress INT; - DECLARE vAgency INT; - - SELECT date_send, address_id, agency_id - INTO vDelivery, vAddress, vAgency - FROM basket; - - CALL vn2008.bionic_available_ (vDelivery, vAddress, vAgency); - - DROP TEMPORARY TABLE IF EXISTS tmp.itemAvailable; - CREATE TEMPORARY TABLE tmp.itemAvailable - (INDEX (id)) - ENGINE = MEMORY - SELECT c.item_id id - FROM cache.available c - JOIN vn2008.t_bionic_available a ON c.calc_id = a.calc_id - WHERE c.available > 0 - GROUP BY c.item_id; - - DROP TEMPORARY TABLE vn2008.t_bionic_available; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_available` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = '' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_available`() -BEGIN -/** - * Genera una tabla con los ids de los articulos disponibles. - * - * @table tmp.item_available - **/ - DECLARE v_delivery DATE; - DECLARE v_address INT; - DECLARE v_agency INT; - - SELECT date_send, address_id, agency_id - INTO v_delivery, v_address, v_agency - FROM basket; - - CALL vn2008.bionic_available_ (v_delivery, v_address, v_agency); - - DROP TEMPORARY TABLE IF EXISTS tmp.item_available; - CREATE TEMPORARY TABLE tmp.item_available - (INDEX (item_id)) - ENGINE = MEMORY - SELECT c.item_id - FROM `cache`.available c - JOIN vn2008.t_bionic_available a ON c.calc_id = a.calc_id - WHERE c.available > 0 - GROUP BY c.item_id; - - DROP TEMPORARY TABLE vn2008.t_bionic_available; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_list` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `item_list`(v_warehouse SMALLINT, v_shipping DATE, v_realm INT, v_rate TINYINT) -BEGIN - DECLARE v_calc INT; - - CALL cache.available_refresh (v_calc, TRUE, v_warehouse, v_shipping); - CALL vn2008.item_last_buy_ (v_warehouse, v_shipping); - - SELECT a.Id_Article, a.Article, a.Categoria, a.Medida, a.Tallos, - c.available, a.Color, o.Abreviatura, t.Tipo, a.tipo_id, a.Foto, - CASE b.caja - WHEN 0 THEN 1 - WHEN 2 THEN b.packing - ELSE b.grouping - END AS grouping, - CASE v_rate - WHEN 1 THEN b.Tarifa1 - WHEN 2 THEN b.Tarifa2 - WHEN 3 THEN b.Tarifa3 - ELSE NULL - END AS price - FROM cache.available c - JOIN vn2008.Articles a ON a.Id_Article = c.item_id - JOIN vn2008.t_item_last_buy l ON l.item_id = c.item_id - JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - JOIN vn2008.reinos r ON t.reino_id = r.id - JOIN vn2008.Compres b ON b.Id_Compra = l.buy_id - LEFT JOIN vn2008.Origen o ON a.id_origen = o.id - WHERE c.calc_id = v_calc - AND c.available > 0 - AND c.item_id != 90 - AND r.display - AND (v_realm IS NULL OR v_realm = r.id) - ORDER BY a.tipo_id, Article, Medida; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `myTicketGet` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `myTicketGet`(vTicket INT) -BEGIN -/** - * Returns a current user ticket header. - * - * @param vTicket The ticket identifier - */ - DECLARE vTaxBase DECIMAL(10,2); - DECLARE vTax DECIMAL(10,2); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - ENGINE = MEMORY - SELECT id ticketFk FROM myTicket - WHERE id = vTicket; - - CALL vn.ticketGetTax; - - SELECT SUM(taxableBase), SUM(tax) - INTO vTaxBase, vTax - FROM tmp.ticketAmount; - - SELECT t.id, t.landed, t.shipped, t.refFk, ag.description agency, m.code method, - a.street, a.postalCode, a.city, a.nickname, p.name province, - vTaxBase taxBase, vTaxBase + vTax AS total - FROM tmp.ticket v - JOIN vn.ticket t ON t.id = v.ticketFk - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.agencyMode ag ON ag.id = t.agencyModeFk - LEFT JOIN vn.deliveryMethod m ON m.id = ag.deliveryMethodFk - LEFT JOIN vn.province p ON p.id = a.provinceFk - WHERE t.id = vTicket; - - DROP TEMPORARY TABLE - tmp.ticket, - tmp.ticketTax, - tmp.ticketAmount; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `myTicketGetPackages` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `myTicketGetPackages`(vTicket INT) -BEGIN -/** - * Returns a current user ticket packages. - * - * @param vTicket The ticket identifier - * @select The ticket packages - */ - SELECT i.image, i.id, i.name, tp.quantity - FROM myTicket t - JOIN vn.ticketPackaging tp ON tp.ticketFk = t.id - JOIN vn.package p ON p.id = tp.packagingFk - JOIN vn.item i ON i.id = p.itemFk - WHERE t.id = vTicket; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `myTicketGetRows` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `myTicketGetRows`(vTicket INT) -BEGIN -/** - * Returns a current user ticket lines. - * - * @param vTicket The ticket identifier - * @select The ticket lines - */ - SELECT r.itemFk, r.quantity, r.concept, r.price, r.discount, - o.code origin, i.category, i.size, i.stems, i.inkFk, i.image - FROM myTicketRow r - JOIN vn.item i ON i.id = r.itemFk - LEFT JOIN vn.origin o ON o.id = i.originFk - WHERE r.ticketFk = vTicket - ORDER BY r.concept; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `myTicketList` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `myTicketList`(vFrom DATE, vTo DATE) -BEGIN -/** - * Returns the current user list of tickets between two dates reange. - * Also returns the total price with tax of every ticket. - * - * @param vFrom From date, if %NULL current date minus 25 days - * @param vTo To date, if %NULL current date - * @select The tickets list - */ - SET vFrom = IFNULL(vFrom, DATE_FORMAT(TIMESTAMPADD(DAY, -25, CURDATE()), '%Y-%m-01')); - SET vTo = IFNULL(vTo, TIMESTAMPADD(YEAR, 1, CURDATE())); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - (KEY (ticketFk)) - ENGINE = MEMORY - SELECT t.id ticketFk - FROM myTicket t - WHERE shipped BETWEEN TIMESTAMP(vFrom) AND TIMESTAMP(vTo, '23:59:59'); - - CALL vn.ticketGetTotal; - - SELECT v.id, IFNULL(v.landed, v.shipped) landed, v.shipped, v.companyFk, - a.city, a.nickname, ag.description agency, t.total - FROM tmp.ticket i - JOIN vn.ticket v ON v.id = i.ticketFk - JOIN vn.address a ON a.id = v.addressFk - JOIN vn.agencyMode ag ON ag.id = v.agencyModeFk - JOIN tmp.ticketTotal t ON t.ticketFk = i.ticketFk - ORDER BY IFNULL(v.landed, v.shipped) DESC, i.ticketFk DESC; - - DROP TEMPORARY TABLE - tmp.ticket, - tmp.ticketTotal; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `myTicketLogAccess` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `myTicketLogAccess`(vTicket INT) -BEGIN -/** - * Logs an access to a ticket. - * - * @param vTicket The ticket identifier - */ - INSERT INTO vn.ticketLog - (originFk, userFk, `action`, description) - SELECT vTicket, account.userGetId(), 'select', 'Accede a ticket' - FROM myTicket t - WHERE t.id = vTicket; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `orderCheckConfig` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `orderCheckConfig`(vOrder INT) -proc: BEGIN -/** - * Comprueba que la configuración del pedido es correcta. - * - * @param vOrder Identificador del pedido - */ - DECLARE vDeliveryMethod VARCHAR(255); - DECLARE vDelivery DATE; - DECLARE vAgency INT; - DECLARE vAddress INT; - - -- Obtiene los datos del pedido - - SELECT d.code, o.date_send, o.agency_id, o.address_id - INTO vDeliveryMethod, vDelivery, vAgency, vAddress - FROM `order` o - JOIN vn.deliveryMethod d ON d.id = o.delivery_method_id - WHERE o.id = vOrder; - - -- Comprueba que se ha seleccionado una dirección - - IF vDeliveryMethod IN ('AGENCY', 'DELIVERY') - && vAddress IS NULL - THEN - CALL util.throw ('ORDER_EMPTY_ADDRESS'); - END IF; - - -- Comprueba que la agencia es correcta - - IF !vn.AgencyIsAvailable (vAgency, vDelivery, vAddress) THEN - CALL util.throw ('ORDER_INVALID_AGENCY'); - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `orderCheckDate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `orderCheckDate`(vDate DATE) -BEGIN - DECLARE vMaxTime TIME; - DECLARE vFestive BOOLEAN; - DECLARE vDenyDay DATE; - DECLARE vDenySunday BOOLEAN; - - SELECT COUNT(*) INTO vFestive - FROM orderCheckFestive - WHERE TIMESTAMPADD(YEAR, -YEAR(vDate), vDate) = date - AND acceptOrders = FALSE; - - IF vDate < CURDATE() - THEN - CALL util.throw ('ORDER_DATE_PAST'); - ELSEIF vFestive > 0 - THEN - CALL util.throw ('ORDER_DATE_HOLIDAY'); - ELSE - SELECT c.denySunday, c.denyDay, IFNULL(w.maxTime, c.maxTime) - INTO vDenySunday, vDenyDay, vMaxTime - FROM orderCheck c - LEFT JOIN orderCheckWday w - ON w.weekday = WEEKDAY(CURDATE()); - - IF vDate = CURDATE() AND CURTIME() > vMaxTime - THEN - CALL util.throw ('ORDER_DATE_LAST'); - ELSEIF WEEKDAY(vDate) = 6 AND vDenySunday - THEN - CALL util.throw ('ORDER_DATE_SUNDAY'); - ELSEIF vDate = vDenyDay - THEN - CALL util.throw ('ORDER_DATE_SATURATED'); - END IF; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `orderConfirm` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `orderConfirm`(vOrder INT) -BEGIN -/** - * Confirms an order, creating each of its tickets on - * the corresponding date and store. - * - * @param vOrder The order identifier - */ - DECLARE vOk BOOL; - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vWarehouse INT; - DECLARE vShipment DATETIME; - DECLARE vTicket INT; - DECLARE vNotes VARCHAR(255); - DECLARE vItem INT; - DECLARE vConcept VARCHAR(30); - DECLARE vAmount INT; - DECLARE vPrice DECIMAL(10,2); - DECLARE vSale INT; - DECLARE vRate INT; - DECLARE vEmployee INT; - DECLARE vRowId INT; - DECLARE vDelivery DATE; - DECLARE vAddress INT; - DECLARE vAgency INT; - DECLARE vIsConfirmed BOOL; - DECLARE vClientId INT; - DECLARE vCompanyId INT; - DECLARE vAgencyModeId INT; - - DECLARE TICKET_FREE INT DEFAULT 2; - DECLARE SYSTEM_WORKER INT DEFAULT 20; - - DECLARE cDates CURSOR FOR - SELECT t.Fecha_envio, r.warehouse_id - FROM `order` o - JOIN order_row r ON r.order_id = o.id - LEFT JOIN vn2008.travel_tree t ON t.warehouse_id = r.warehouse_id - WHERE o.id = vOrder AND r.amount != 0 - GROUP BY warehouse_id; - - DECLARE cRows CURSOR FOR - SELECT r.id, r.item_id, a.Article, r.amount, r.price, r.rate - FROM order_row r - JOIN vn2008.Articles a ON a.Id_Article = r.item_id - WHERE r.amount != 0 - AND r.warehouse_id = vWarehouse - AND r.order_id = vOrder - ORDER BY r.rate DESC; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - -- Carga los datos del pedido - - SELECT o.date_send, o.address_id, o.note, a.agency_id, - o.confirmed, cs.Id_Cliente, o.company_id, o.agency_id - INTO vDelivery, vAddress, vNotes, vAgency, - vIsConfirmed, vClientId, vCompanyId, vAgencyModeId - FROM hedera.`order` o - JOIN vn2008.Agencias a ON a.Id_Agencia = o.agency_id - JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = o.address_id - WHERE id = vOrder; - - -- Comprueba que el pedido no está confirmado - - IF vIsConfirmed THEN - CALL util.throw ('ORDER_ALREADY_CONFIRMED'); - END IF; - - -- Comprueba que el pedido no está vacío - - SELECT COUNT(*) > 0 INTO vOk - FROM order_row WHERE order_id = vOrder AND amount > 0; - - IF !vOk THEN - CALL util.throw ('ORDER_EMPTY'); - END IF; - - -- Carga las fechas de salida de cada almacén - - CALL vn2008.travel_tree (vDelivery, vAddress, vAgency); - - -- Trabajador que realiza la acción - - SELECT Id_Trabajador INTO vEmployee - FROM vn2008.Trabajadores - WHERE user_id = account.userGetId(); - - IF vEmployee IS NULL THEN - SELECT employeeFk INTO vEmployee FROM orderConfig; - END IF; - - -- Crea los tickets del pedido - - START TRANSACTION; - - OPEN cDates; - - lDates: - LOOP - SET vTicket = NULL; - SET vDone = FALSE; - FETCH cDates INTO vShipment, vWarehouse; - - IF vDone THEN - LEAVE lDates; - END IF; - - -- Busca un ticket existente que coincida con los parametros del nuevo pedido - - SELECT Id_Ticket INTO vTicket - FROM vn2008.Tickets t - LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket - JOIN `order` o - ON o.address_id = t.Id_Consigna - AND vWarehouse = t.warehouse_id - AND o.agency_id = t.Id_Agencia - AND t.landing = o.date_send - AND vShipment = DATE(t.Fecha) - WHERE o.id = vOrder - AND t.Factura IS NULL - AND IFNULL(tls.alertLevel,0) = 0 - AND t.Id_Cliente <> 1118 - LIMIT 1; - - -- Crea el ticket en el caso de no existir uno adecuado - - IF vTicket IS NULL - THEN - CALL vn.ticketCreate ( - vClientId, - IFNULL(vShipment, CURDATE()), - vWarehouse, - vCompanyId, - vAddress, - vAgencyModeId, - NULL, - vDelivery, - vTicket - ); - ELSE - INSERT INTO vncontrol.inter - SET Id_Ticket = vTicket, - Id_Trabajador = SYSTEM_WORKER, - state_id = TICKET_FREE; - END IF; - - INSERT IGNORE INTO vn2008.order_Tickets - SET order_id = vOrder, - Id_Ticket = vTicket; - - -- Añade las notas - - IF vNotes IS NOT NULL AND vNotes != '' - THEN - INSERT INTO vn2008.ticket_observation (Id_Ticket, observation_type_id, text) - VALUES (vTicket, 4/*comercial*/, vNotes) - ON DUPLICATE KEY UPDATE text = CONCAT(VALUES(text),'. ', text); - END IF; - - -- Añade los movimientos y sus componentes - - OPEN cRows; - - lRows: - LOOP - SET vDone = FALSE; - FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate; - - IF vDone THEN - LEAVE lRows; - END IF; - - INSERT INTO vn2008.Movimientos - SET - Id_Article = vItem, - Id_Ticket = vTicket, - Concepte = vConcept, - Cantidad = vAmount, - Preu = vPrice, - CostFixat = 0, - PrecioFijado = TRUE; - - SET vSale = LAST_INSERT_ID(); - - INSERT INTO vn2008.Movimientos_componentes (Id_Movimiento, Id_Componente, Valor) - SELECT vSale, cm.component_id, cm.price - FROM order_component cm - JOIN bi.tarifa_componentes tc ON tc.Id_Componente = cm.component_id - WHERE cm.order_row_id = vRowId - GROUP BY vSale, cm.component_id; - - UPDATE order_row SET Id_Movimiento = vSale - WHERE id = vRowId; - - END LOOP; - - CLOSE cRows; - - -- Fija el Costfixat - - UPDATE vn2008.Movimientos m - JOIN (SELECT SUM(mc.Valor) sum_valor,mc.Id_Movimiento - FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc USING(Id_Componente) - JOIN bi.tarifa_componentes_series tcs on tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id AND tcs.base - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - WHERE m.Id_Ticket = vTicket - GROUP BY mc.Id_Movimiento) mc ON mc.Id_Movimiento = m.Id_Movimiento - SET m.CostFixat = sum_valor; - END LOOP; - - CLOSE cDates; - - DELETE FROM order_basket WHERE order_id = vOrder; - UPDATE `order` SET confirmed = TRUE, confirm_date = NOW() - WHERE id = vOrder; - - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `orderGetTax` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `orderGetTax`(vOrder INT) - READS SQL DATA -BEGIN -/** - * Calcula el IVA, y el recargo de equivalencia de un pedido - * desglosados por tipos. - * - * @param vOrder El identificador del pedido - * @treturn tmp.orderTax Bases imponibles, IVA y recargo de equivalencia - */ - CALL vn.taxGetRates (NULL); - - -- Calcula el IVA y el recargo desglosado. - - DROP TEMPORARY TABLE IF EXISTS tmp.orderTax; - CREATE TEMPORARY TABLE tmp.orderTax - (INDEX (orderFk)) - ENGINE = MEMORY - SELECT id orderFk, t.type, t.taxBase, - CAST(IF(t.hasTax, t.taxBase * x.rate, 0) AS DECIMAL(10,2)) tax, - CAST(IF(t.hasEqualizationTax, t.taxBase * x.equalizationTax, 0) AS DECIMAL(10,2)) equalizationTax - FROM ( - SELECT o.id, g.countryFk, g.type - ,SUM(CAST(m.amount * m.price AS DECIMAL(10,2))) taxBase - ,NOT(c.isVies AND p.countryFk <> c.countryFk) hasTax - ,c.isEqualizated != FALSE AS hasEqualizationTax - FROM `order` o - JOIN orderRow m ON m.orderFk = o.id - JOIN vn.item a ON a.id = m.itemFk - JOIN vn.client c ON c.id = o.customer_id - JOIN vn.supplier p ON p.id = o.company_id - JOIN tmp.taxClass g - ON g.countryFk = p.countryFk AND g.taxClassFk = a.taxClassFk - WHERE o.id = vOrder - GROUP BY o.id, g.type - ) t - JOIN tmp.taxType x - ON x.countryFk = t.countryFk AND x.type = t.type; - - DROP TEMPORARY TABLE - tmp.taxClass, - tmp.taxType; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `orderUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `orderUpdate`(vOrder INT) -proc: BEGIN -/** - * Actualiza la líneas de un pedido. - * - * @param vOrder Id del pedido - */ - DECLARE vDate DATE; - DECLARE vAddress INT; - DECLARE vAgency INT; - DECLARE vNRows INT; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT COUNT(*) INTO vNRows - FROM order_row WHERE order_id = vOrder; - - IF vNRows > 0 - THEN - SELECT date_send, address_id, agency_id - INTO vDate, vAddress, vAgency - FROM `order` - WHERE id = vOrder; - - CALL vn2008.bionic_from_order (vDate, vAddress, vAgency, vOrder); - - DELETE c - FROM order_row r - JOIN order_component c ON c.order_row_id = r.id - WHERE r.order_id = vOrder; - - UPDATE order_row r - LEFT JOIN tmp.bionic_price l - ON l.warehouse_id = r.warehouse_id - AND l.item_id = r.item_id - AND l.rate = r.rate - LEFT JOIN tmp.travel_tree t - ON t.warehouse_id = r.warehouse_id - SET - r.price = l.price, - r.amount = IF(l.item_id IS NOT NULL, r.amount + IF(@m := MOD(r.amount, l.grouping), l.grouping - @m, 0), 0), - r.shipment = t.Fecha_envio - WHERE r.order_id = vOrder; - - INSERT INTO order_component (order_row_id, component_id, price) - SELECT r.id, c.component_id, c.cost - FROM order_row r - JOIN tmp.bionic_component c - ON c.warehouse_id = r.warehouse_id - AND c.item_id = r.item_id - JOIN bi.tarifa_componentes t - ON t.Id_Componente = c.component_id - AND (t.tarifa_class IS NULL OR t.tarifa_class = r.rate) - WHERE r.order_id = vOrder; - END IF; - - UPDATE `order` SET date_make = NOW() - WHERE id = vOrder; - - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `order_confirm_bionic` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `order_confirm_bionic`(vOrder INT) -BEGIN -/** - * Confirma un pedido, creando cada uno de sus tickets en la fecha - * y almacén correspondientes. - * - * @deprecated Use orderConfirm() instead - * - * @param vOrder Identificador del pedido - */ - CALL orderConfirm (vOrder); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `order_get_vat` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `order_get_vat`(vOrder INT) - READS SQL DATA -BEGIN -/** - * Calcula el IVA, y el recargo de equivalencia de un pedido - * desglosados por tipos. - * - * @deprecated Use procedure orderGetTax() instead - * - * @param vOrder El identificador del pedido - * @table t_order_vat Bases imponibles, su IVA y su recargo de equivalencia. - */ - CALL orderGetTax (vOrder); - - DROP TEMPORARY TABLE IF EXISTS t_order_vat; - CREATE TEMPORARY TABLE t_order_vat - ENGINE = MEMORY - SELECT orderFk order_id, type rate, taxBase tax_base, - tax vat, equalizationTax surcharge - FROM tmp.orderTax; - - DROP TEMPORARY TABLE tmp.orderTax; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `surveyVote` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `surveyVote`(vAnswer INT) -BEGIN - DECLARE vSurvey INT; - DECLARE vCount TINYINT; - DECLARE EXIT HANDLER FOR 1062 - CALL util.throw ('SURVEY_MAX_ONE_VOTE'); - - SELECT survey_id INTO vSurvey - FROM survey_answer WHERE id = vAnswer; - - INSERT INTO survey_vote - VALUES (vSurvey, account.userGetId()); - - UPDATE survey_answer SET votes = votes + 1 - WHERE id = vAnswer; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `tpvTransactionConfirm` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransactionConfirm`( - vAmount INT - ,vOrder INT - ,vMerchant INT - ,vCurrency INT - ,vResponse INT - ,vErrorCode VARCHAR(10) -) -BEGIN -/** - * Confirma una transacción previamente iniciada, reescribiendo - * sus datos por los confirmados por el banco (solo si estos difieren). - * Genera el recibo y su correspondiente entrada en caja. - * - * @param vAmount Cantidad confirmada - * @param vOrder Identificador de transacción - * @param vMerchant Identificador de comercio - * @param vCurrency Identificador de moneda - * @param vResponse Identificador de respuesta del banco - * @param vErrorCode Código de error del banco, si lo hubiera - */ - DECLARE vReceipt INT; - DECLARE vStatus VARCHAR(10); - DECLARE vCustomer INT; - DECLARE vBank INT; - DECLARE vCompany INT; - DECLARE vEmployee INT; - DECLARE vIsDuplicated BOOLEAN; - DECLARE vDate DATE; - DECLARE vConcept VARCHAR(25) DEFAULT 'Cobro Web'; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT COUNT(*) > 0 INTO vIsDuplicated - FROM tpvTransaction - WHERE id = vOrder AND response IS NOT NULL - FOR UPDATE; - - IF vIsDuplicated - THEN - CALL util.throw ('TRANSACTION_DUPLICATED'); - END IF; - - IF vResponse BETWEEN 0 AND 99 - THEN - SELECT - t.clientFk - ,m.bankFk - ,m.companyFk - ,c.employeeFk - ,DATE(t.created) - INTO - vCustomer - ,vBank - ,vCompany - ,vEmployee - ,vDate - FROM tpvMerchant m - JOIN tpvConfig c ON c.id = 1 - LEFT JOIN tpvTransaction t ON t.id = vOrder - WHERE m.id = vMerchant; - - INSERT INTO vn2008.Recibos - SET - Entregado = vAmount / 100 - ,Fechacobro = vDate - ,Id_Trabajador = vEmployee - ,Id_Banco = vBank - ,Id_Cliente = vCustomer - ,empresa_id = vCompany - ,Id_Factura = vConcept - ,conciliado = TRUE; - - SET vReceipt = LAST_INSERT_ID(); - SET vStatus = 'ok'; - - -- Código redundante - - DO vn2008.till_entry - ( - vCustomer - ,vBank - ,vAmount / 100 - ,vConcept - ,vDate - ,'A' - ,TRUE - ,vCustomer - ,vCompany - ,vEmployee - ); - ELSE - SET vReceipt = NULL; - SET vStatus = 'ko'; - END IF; - - UPDATE tpvTransaction - SET - merchantFk = vMerchant - ,receiptFk = vReceipt - ,amount = vAmount - ,response = vResponse - ,errorCode = vErrorCode - ,status = vStatus - WHERE id = vOrder; - - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `tpvTransactionConfirmAll` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransactionConfirmAll`(vDate DATE) -BEGIN -/** - * Confirma todas las transacciones confirmadas por el cliente pero no - * por el banco para una fecha dada. - * - * @param vDate Fecha deseada - */ - DECLARE vOrder INT; - DECLARE vDone BOOLEAN DEFAULT FALSE; - DECLARE vDateIni DATETIME DEFAULT TIMESTAMP(vDate, '00:00:00'); - DECLARE vDateEnd DATETIME DEFAULT TIMESTAMP(vDate, '23:59:59'); - - DECLARE cTransactions CURSOR FOR - SELECT id - FROM tpvTransaction - WHERE created BETWEEN vDateIni AND vDateEnd - AND status = 'ok' - AND response IS NULL; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - OPEN cTransactions; - - l: LOOP - FETCH cTransactions INTO vOrder; - - IF vDone THEN - LEAVE l; - END IF; - - CALL tpvTransactionConfirmById (vOrder); - END LOOP l; - - CLOSE cTransactions; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `tpvTransactionConfirmById` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransactionConfirmById`(vOrder INT) -BEGIN -/** - * Confirma manualmente una transacción espedificando su identificador. - * - * @param vOrder Identificador de la transacción - */ - DECLARE vAmount INT; - DECLARE vMerchant INT; - DECLARE vCurrency INT; - - SELECT amount, merchantFk, currency - INTO vAmount, vMerchant, vCurrency - FROM tpvTransaction t - JOIN tpvMerchant m ON m.id = t.merchantFk - JOIN tpvConfig c - WHERE t.id = vOrder; - - CALL tpvTransactionConfirm ( - vAmount - ,vOrder - ,vMerchant - ,vCurrency - ,0 - ,NULL - ); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `tpvTransactionEnd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransactionEnd`(vTransaction INT, vStatus VARCHAR(12)) -BEGIN -/** - * Finaliza una transaccción estableciendo su estado a 'ok' o - * 'ko' en función de si esta se ha realizado correctamente. - * Este procedimiento debe ser llamado directamente por el cliente - * nada mas finalizar la transacción y solo tiene validez hasta que - * llega la notificacion definitiva desde el banco. - * - * @param vTransaction El identificador de la transacción - * @param vStatus El estado, 'ok' o 'ko' - */ - IF vStatus IN ('ok', 'ko') - THEN - UPDATE myTpvTransaction SET status = vStatus - WHERE id = vTransaction AND response IS NULL; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `tpvTransactionStart` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransactionStart`(vAmount INT, vCompany INT) -BEGIN -/** - * Inicia una nueva transacción con el TPV virtual, generando - * un identificador de transacción y devolviendo con un SELECT - * los parámetros que deben enviarse a la URL del servicio web - * del banco. - * - * @param vAmount Cantidad a pagar en céntimos - * @param vCompany El identificador de la empresa - * - * @select Los parámetros que deben pasarse al banco - */ - DECLARE vTransaction CHAR(12); - DECLARE vMerchant INT; - DECLARE vUrl VARCHAR(255); - DECLARE vKey VARCHAR(50); - DECLARE vTestMode BOOLEAN; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - IF vCompany IS NULL - THEN - SELECT companyFk INTO vCompany - FROM tpvMerchantEnable LIMIT 1; - END IF; - - SELECT merchantFk INTO vMerchant - FROM tpvMerchantEnable WHERE companyFk = vCompany; - - SELECT testMode INTO vTestMode - FROM tpvConfig; - - IF NOT vTestMode - THEN - SELECT c.url, m.secretKey INTO vUrl, vKey - FROM tpvMerchant m - JOIN tpvConfig c - WHERE m.id = vMerchant; - ELSE - SELECT testUrl, testKey INTO vUrl, vKey - FROM tpvConfig; - END IF; - - INSERT INTO myTpvTransaction - SET - merchantFk = vMerchant - ,clientFk = account.userGetId() - ,amount = vAmount; - - SET vTransaction = LAST_INSERT_ID(); - - SELECT - vAmount amount - ,vTransaction transactionId - ,vMerchant merchant - ,currency - ,transactionType - ,terminal - ,merchantUrl - ,vUrl url - ,vKey secretKey - FROM tpvConfig; - - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `tpvTransactionUndo` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `tpvTransactionUndo`( - vOrder INT -) -BEGIN - DECLARE vCustomer INT; - DECLARE vAmount DOUBLE; - DECLARE vReceipt INT; - DECLARE vDate DATE; - DECLARE vBank INT; - DECLARE vAccount VARCHAR(12); - DECLARE vSubaccount VARCHAR(12); - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT - t.clientFk - ,t.amount / 100 - ,t.receiptFk - ,DATE(t.created) - ,m.bankFk - INTO - vCustomer - ,vAmount - ,vReceipt - ,vDate - ,vBank - FROM tpvTransaction t - JOIN tpvMerchant m ON m.id = t.merchantFk - JOIN tpvConfig c - WHERE t.id = vOrder - FOR UPDATE; - - -- Elimina el recibo - - DELETE FROM vn2008.Recibos - WHERE Id = vReceipt LIMIT 1; - - -- Elimina la entrada de cajas - - DELETE FROM vn2008.Cajas - WHERE Id_Banco = vBank - AND DATE(CajaFecha) = vDate - AND Entrada = vAmount - LIMIT 1; - - -- Elimina los asientos contables - - SELECT Cuenta INTO vSubaccount - FROM vn2008.Clientes WHERE Id_Cliente = vCustomer; - - SELECT Cuenta INTO vAccount - FROM vn2008.Bancos WHERE Id_Banco = vBank; - - DELETE FROM vn2008.XDiario - WHERE SUBCTA = vSubaccount - AND CONTRA = vAccount - AND DATE(FECHA) = vDate - AND EUROHABER = vAmount - LIMIT 1; - - DELETE FROM vn2008.XDiario - WHERE CONTRA = vSubaccount - AND SUBCTA = vAccount - AND DATE(FECHA) = vDate - AND EURODEBE = vAmount - LIMIT 1; - - -- Actualiza la transaccion - - UPDATE tpvTransaction - SET response = NULL, status = 'started' - WHERE id = vOrder; - - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `transactionEnd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `transactionEnd`(vTransaction INT, vStatus VARCHAR(12)) -BEGIN -/** - * @deprecated Use procedure tpvTransactionEnd() instead - */ - CALL tpvTransactionEnd(vTransaction, vStatus); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `transactionStart` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `transactionStart`(vAmount INT, vCompany INT) -BEGIN -/** - * @deprecated Use procedure tpvtransactionStart() instead - */ - CALL tpvtransactionStart(vAmount, vCompany); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `visitRegister` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `visitRegister`( - vVisit INT - ,vPlatform VARCHAR(30) - ,vBrowser VARCHAR(30) - ,vVersion VARCHAR(15) - ,vJavascript TINYINT - ,vCookies TINYINT - ,vAgent VARCHAR(255) - ,vIp INT - ,vReferer VARCHAR(255) -) -BEGIN - DECLARE vFirstVisit TINYINT DEFAULT FALSE; - DECLARE vFirstAgent TINYINT DEFAULT FALSE; - DECLARE vAgentId INT DEFAULT NULL; - DECLARE vAccessId INT DEFAULT NULL; - - -- Registers the visit - - IF vVisit IS NULL || (SELECT COUNT(*) FROM visit WHERE id = vVisit) = 0 - THEN - INSERT INTO visit SET id = DEFAULT; - SET vVisit = LAST_INSERT_ID(); - SET vFirstVisit = TRUE; - END IF; - - SELECT id INTO vAgentId FROM visitAgent - WHERE visit = vVisit - AND (agent = vAgent OR (vAgent IS NULL AND agent IS NULL)) - LIMIT 1; - - -- Registers the user agent - - IF vAgentId IS NULL - THEN - INSERT INTO visitAgent SET - visit = vVisit - ,platform = vPlatform - ,browser = vBrowser - ,version = vVersion - ,javascript = vJavascript - ,cookies = vCookies - ,agent = vAgent; - - SET vAgentId = LAST_INSERT_ID(); - SET vFirstAgent = TRUE; - END IF; - - IF vFirstVisit - THEN - UPDATE visit SET firstAgent = vAgentId - WHERE id = vVisit; - END IF; - - -- Registers the user access - - INSERT INTO visitAccess SET - agent = vAgentId - ,ip = vIp - ,referer = vReferer; - - SET vAccessId = LAST_INSERT_ID(); - - IF vFirstAgent - THEN - UPDATE visitAgent SET firstAccess = vAccessId - WHERE id = vAgentId; - END IF; - - -- Returns the visit info - - SELECT vVisit visit, vAccessId access; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `visitUserNew` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `visitUserNew`( - vAccess INT - ,vSsid VARCHAR(64) -) -BEGIN - DECLARE vUserVisit INT; - - INSERT INTO visitUser SET - access = vAccess, - user = account.userGetId(); - - SET vUserVisit = LAST_INSERT_ID(); - - UPDATE userSession SET userVisit = vUserVisit - WHERE ssid = vSsid; - - DELETE FROM userSession - WHERE lastUpdate < TIMESTAMPADD(HOUR, -1, NOW()); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - --- --- Current Database: `stock` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `stock` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `stock`; - --- --- Table structure for table `buy` --- - -DROP TABLE IF EXISTS `buy`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `buy` ( - `buyFk` int(10) unsigned NOT NULL, - `entryFk` int(10) unsigned NOT NULL, - `travelFk` int(10) unsigned NOT NULL, - `itemFk` int(10) unsigned NOT NULL, - `shipped` date DEFAULT NULL, - `warehouseOutFk` smallint(6) unsigned DEFAULT NULL, - `isInventoryOut` tinyint(4) NOT NULL, - `isDelivered` tinyint(1) NOT NULL DEFAULT '0', - `landed` date NOT NULL, - `warehouseInFk` smallint(6) unsigned DEFAULT NULL, - `isInventoryIn` tinyint(4) NOT NULL, - `isReceived` tinyint(1) NOT NULL DEFAULT '0', - `isRaid` tinyint(1) NOT NULL DEFAULT '0', - `validUntil` date DEFAULT NULL, - `quantity` int(11) NOT NULL DEFAULT '0', - `available` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`buyFk`), - KEY `travelFk` (`travelFk`), - KEY `entryFk` (`entryFk`), - KEY `itemFkOut` (`itemFk`,`warehouseOutFk`), - KEY `itemFk` (`itemFk`,`warehouseInFk`,`validUntil`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `fault` --- - -DROP TABLE IF EXISTS `fault`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `fault` ( - `itemFk` int(10) unsigned NOT NULL, - `warehouseFk` int(10) unsigned NOT NULL, - `date` date NOT NULL, - `quantity` int(11) NOT NULL DEFAULT '0', - UNIQUE KEY `itemFk` (`itemFk`,`warehouseFk`,`date`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `itemRecalc` --- - -DROP TABLE IF EXISTS `itemRecalc`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `itemRecalc` ( - `itemFk` int(10) unsigned NOT NULL, - `warehouseFk` int(10) unsigned NOT NULL, - UNIQUE KEY `itemFk` (`itemFk`,`warehouseFk`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `queue` --- - -DROP TABLE IF EXISTS `queue`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `queue` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `operation` set('ADD','DEL') COLLATE utf8_unicode_ci NOT NULL, - `tableName` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `tableId` int(10) unsigned NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `sale` --- - -DROP TABLE IF EXISTS `sale`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `sale` ( - `saleFk` int(10) unsigned NOT NULL, - `ticketFk` int(10) unsigned NOT NULL, - `itemFk` int(10) unsigned NOT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL, - `shipped` date NOT NULL, - `isPicked` tinyint(1) NOT NULL DEFAULT '0', - `quantity` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`saleFk`), - KEY `ticketFk` (`ticketFk`), - KEY `itemFk` (`itemFk`,`warehouseFk`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `visible` --- - -DROP TABLE IF EXISTS `visible`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `visible` ( - `itemFk` int(10) unsigned NOT NULL, - `warehouseFk` int(10) unsigned NOT NULL, - `quantity` int(11) NOT NULL, - PRIMARY KEY (`itemFk`,`warehouseFk`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'stock' --- -/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `queuePoll` */; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `queuePoll` ON SCHEDULE EVERY 10 SECOND STARTS '2017-06-27 17:15:02' ON COMPLETION NOT PRESERVE DISABLE DO CALL queuePoll */ ;; -/*!50003 SET time_zone = @saved_time_zone */ ;; -/*!50003 SET sql_mode = @saved_sql_mode */ ;; -/*!50003 SET character_set_client = @saved_cs_client */ ;; -/*!50003 SET character_set_results = @saved_cs_results */ ;; -/*!50003 SET collation_connection = @saved_col_connection */ ;; -DELIMITER ; -/*!50106 SET TIME_ZONE= @save_time_zone */ ; - --- --- Dumping routines for database 'stock' --- -/*!50003 DROP PROCEDURE IF EXISTS `buyCalcAvailable` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buyCalcAvailable`(vItem INT, vWarehouse INT) -BEGIN -/** - * Calcula el disponible de un artículo en un almacén para - * todas sus compras. - * - * @param vItem El id del artículo - * @param vWarehouse El id de almacén - */ - DECLARE vShipped DATE; - DECLARE vQuantity INT; - DECLARE vUnavailable BOOL; - DECLARE vBuyId INT; - DECLARE vAvailable INT; - DECLARE vPick INT; - DECLARE vDone BOOL; - - DECLARE cSales CURSOR FOR - SELECT shipped, quantity - FROM tSale - ORDER BY shipped; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - START TRANSACTION; - - DROP TEMPORARY TABLE IF EXISTS tSale; - CREATE TEMPORARY TABLE tSale - ENGINE = MEMORY - SELECT shipped, quantity - FROM sale - WHERE itemFk = vItem - AND warehouseFk = vWarehouse - UNION ALL - SELECT shipped, quantity - FROM buy - WHERE itemFk = vItem - AND warehouseOutFk = vWarehouse; - - -- Resetea el disponible y el faltante de compras y ventas - - UPDATE buy SET available = quantity - WHERE itemFk = vItem - AND warehouseInFk = vWarehouse; - - DELETE FROM fault - WHERE itemFk = vItem - AND warehouseFk = vWarehouse; - - -- Calcula el disponible - - OPEN cSales; - - l: LOOP - SET vDone = FALSE; - FETCH cSales INTO vShipped, vQuantity; - - IF vDone THEN - LEAVE l; - END IF; - - SET vUnavailable = FALSE; - - WHILE vQuantity > 0 AND NOT vUnavailable - DO - SET vDone = FALSE; - - SELECT buyFk, available INTO vBuyId, vAvailable - FROM buy - WHERE itemFk = vItem - AND warehouseInFk = vWarehouse - AND landed <= vShipped - AND validUntil >= vShipped - AND available > 0 - ORDER BY landed - LIMIT 1; - - IF vDone - THEN - SET vUnavailable = TRUE; - - INSERT INTO fault SET - itemFk = vItem, - warehouseFk = vWarehouse, - date = vShipped, - quantity = vQuantity - ON DUPLICATE KEY UPDATE - quantity = quantity + vQuantity; - ELSE - SET vPick = LEAST(vQuantity, vAvailable); - SET vQuantity = vQuantity - vPick; - - UPDATE buy SET available = available - vPick - WHERE buyFk = vBuyId; - END IF; - END WHILE; - END LOOP; - - CLOSE cSales; - - DROP TEMPORARY TABLE tSale; - - -- Confirma los cambios - - COMMIT; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `queueAdd` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `queueAdd`(vTableName VARCHAR(255), vNewId INT, vOldId INT) -proc: BEGIN - -- XXX: Disabled while testing - LEAVE proc; - - IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) - THEN - INSERT INTO queue SET - tableName = vTableName, - tableId = vOldId, - operation = 'DEL'; - END IF; - - IF vNewId IS NOT NULL - THEN - INSERT INTO queue SET - tableName = vTableName, - tableId = vNewId, - operation = 'ADD'; - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `queuePoll` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `queuePoll`() -proc: BEGIN -/** - * Procesa las operaciones pendientes de la tabla #queue. - */ - DECLARE vCount INT; - DECLARE vOperation VARCHAR(255); - DECLARE vTableName VARCHAR(255); - DECLARE vTableId INT; - DECLARE vItem INT; - DECLARE vWarehouse INT; - DECLARE vDone BOOL; - - DECLARE cQueue CURSOR FOR - SELECT operation, tableName, tableId - FROM tQueue; - - DECLARE cItemRecalc CURSOR FOR - SELECT itemFk, warehouseFk - FROM itemRecalc; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - DO RELEASE_LOCK('stock.queuePoll'); - RESIGNAL; - END; - - IF NOT GET_LOCK('stock.queuePoll', 0) THEN - LEAVE proc; - END IF; - - -- Procesa las modificaciones sobre movimientos - - loopPoll: LOOP - START TRANSACTION; - - DROP TEMPORARY TABLE IF EXISTS tQueue; - CREATE TEMPORARY TABLE tQueue - ENGINE = MEMORY - SELECT * FROM queue - ORDER BY created - LIMIT 10; - - SELECT COUNT(*) INTO vCount - FROM tQueue; - - IF vCount = 0 THEN - COMMIT; - LEAVE loopPoll; - END IF; - - DELETE l FROM queue l - JOIN tQueue t ON t.id = l.id; - - OPEN cQueue; - - loopQueue: LOOP - SET vDone = FALSE; - FETCH cQueue INTO vOperation, vTableName, vTableId; - - IF vDone THEN - LEAVE loopQueue; - END IF; - - IF vTableName IN ('travel', 'entry', 'buy') - THEN - CALL queuePollBuy (vTableName, vTableId, vOperation); - END IF; - - IF vTableName IN ('ticket', 'sale') - THEN - CALL queuePollSale (vTableName, vTableId, vOperation); - END IF; - END LOOP; - - CLOSE cQueue; - - DROP TEMPORARY TABLE - tQueue; - END LOOP; - - -- Recalcula el disponible para los artículos y almacenes afectados - - OPEN cItemRecalc; - - loopRecalc: LOOP - SET vDone = FALSE; - FETCH cItemRecalc INTO vItem, vWarehouse; - - IF vDone THEN - LEAVE loopRecalc; - END IF; - - CALL buyCalcAvailable (vItem, vWarehouse); - CALL visibleCalc (vItem, vWarehouse); - - DELETE FROM itemRecalc - WHERE itemFk = vItem - AND warehouseFk = vWarehouse; - - END LOOP; - - CLOSE cItemRecalc; - - -- Libera el bloqueo - - DO RELEASE_LOCK('stock.queuePoll'); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `queuePollBuy` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `queuePollBuy`(vTableName VARCHAR(255), vTableId INT, vOperation VARCHAR(255)) -BEGIN - DROP TEMPORARY TABLE IF EXISTS tOldValues; - CREATE TEMPORARY TABLE tOldValues - (INDEX (buyFk)) - ENGINE = MEMORY - SELECT * FROM buy - WHERE (vTableName = 'travel' AND travelFk = vTableId) - OR (vTableName = 'entry' AND entryFk = vTableId) - OR (vTableName = 'buy' AND buyFk = vTableId); - - INSERT IGNORE INTO itemRecalc (itemFk, warehouseFk) - SELECT itemFk, warehouseOutFk FROM tOldValues - WHERE isInventoryOut; - - INSERT IGNORE INTO itemRecalc (itemFk, warehouseFk) - SELECT itemFk, warehouseInFk FROM tOldValues - WHERE isInventoryIn; - - IF vOperation = 'ADD' - THEN - DROP TEMPORARY TABLE IF EXISTS tNewValues; - CREATE TEMPORARY TABLE tNewValues - (INDEX (buyFk)) - ENGINE = MEMORY - SELECT - c.id buyFk, - c.entryFk, - e.travelFk, - c.itemFk, - t.shipped, - t.warehouseOutFk, - wo.isInventory isInventoryOut, - t.isDelivered, - t.landed, - t.warehouseInFk, - wi.isInventory isInventoryIn, - t.isReceived, - e.isRaid, - c.quantity, - TIMESTAMPADD(DAY, IFNULL(f.life, 365), landed) validUntil - FROM vn.buy c - JOIN vn.entry e ON e.id = c.entryFk - JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.item i ON i.id = c.itemFk - JOIN vn.itemType f ON f.id = i.typeFk - JOIN vn.warehouse wo ON wo.id = t.warehouseOutFk - JOIN vn.warehouse wi ON wi.id = t.warehouseInFk - WHERE ((vTableName = 'travel' AND t.id = vTableId) - OR (vTableName = 'entry' AND e.id = vTableId) - OR (vTableName = 'buy' AND c.id = vTableId)) - AND (t.landed >= vn.getInventoryDate() - AND NOT e.isInventory - AND c.quantity > 0 - AND (wo.isInventory OR wi.isInventory)); - - REPLACE INTO buy (buyFk, entryFk, travelFk, itemFk, - shipped, warehouseOutFk, isInventoryOut, isDelivered, - landed, warehouseInFk, isInventoryIn, isReceived, - isRaid, quantity, validUntil) - SELECT * FROM tNewValues; - - DELETE t - FROM buy t - JOIN tOldValues o ON o.buyFk = t.buyFk - LEFT JOIN tNewValues n ON n.buyFk = t.buyFk - WHERE n.buyFk IS NULL; - - INSERT IGNORE INTO itemRecalc (itemFk, warehouseFk) - SELECT itemFk, warehouseOutFk FROM tNewValues - WHERE isInventoryOut; - - INSERT IGNORE INTO itemRecalc (itemFk, warehouseFk) - SELECT itemFk, warehouseInFk FROM tNewValues - WHERE isInventoryIn; - - DROP TEMPORARY TABLE tNewValues; - - ELSEIF vOperation = 'DEL' - THEN - DELETE b FROM buy b - JOIN tOldValues t USING(buyFk); - END IF; - - DROP TEMPORARY TABLE tOldValues; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `queuePollSale` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `queuePollSale`(vTableName VARCHAR(255), vTableId INT, vOperation VARCHAR(255)) -BEGIN - DROP TEMPORARY TABLE IF EXISTS tOldValues; - CREATE TEMPORARY TABLE tOldValues - (INDEX (saleFk)) - ENGINE = MEMORY - SELECT * FROM sale - WHERE (vTableName = 'ticket' AND ticketFk = vTableId) - OR (vTableName = 'sale' AND saleFk = vTableId); - - INSERT IGNORE INTO itemRecalc (itemFk, warehouseFk) - SELECT itemFk, warehouseFk FROM tOldValues; - - IF vOperation = 'ADD' - THEN - DROP TEMPORARY TABLE IF EXISTS tNewValues; - CREATE TEMPORARY TABLE tNewValues - (INDEX (saleFk)) - ENGINE = MEMORY - SELECT - m.id saleFk, - m.ticketFk, - m.itemFk, - t.warehouseFk, - t.shipped, - m.isPicked OR s.alertLevel > 1 isPicked, - m.quantity - FROM vn.sale m - JOIN vn.ticket t ON t.id = m.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.ticketState s ON s.ticketFk = t.id - WHERE ((vTableName = 'ticket' AND t.id = vTableId) - OR (vTableName = 'sale' AND m.id = vTableId)) - AND (t.shipped >= vn.getInventoryDate() - AND m.quantity != 0 - AND w.isInventory); - - REPLACE INTO sale (saleFk, ticketFk, itemFk, warehouseFk, shipped, isPicked, quantity) - SELECT * FROM tNewValues; - - DELETE t - FROM sale t - JOIN tOldValues o ON o.saleFk = t.saleFk - LEFT JOIN tNewValues n ON n.saleFk = t.saleFk - WHERE n.saleFk IS NULL; - - INSERT IGNORE INTO itemRecalc (itemFk, warehouseFk) - SELECT itemFk, warehouseFk FROM tNewValues; - - DROP TEMPORARY TABLE tNewValues; - - ELSEIF vOperation = 'DEL' - THEN - DELETE m FROM sale m - JOIN tOldValues t USING(saleFk); - END IF; - - DROP TEMPORARY TABLE tOldValues; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `refreshAll` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `refreshAll`() -BEGIN -/** - * Recalcula la caché completa. - */ - TRUNCATE TABLE itemRecalc; - TRUNCATE TABLE queue; - TRUNCATE TABLE fault; - TRUNCATE TABLE visible; - TRUNCATE TABLE stock.buy; - TRUNCATE TABLE stock.sale; - - INSERT INTO queue (operation, tableName, tableId) - SELECT 'ADD', 'travel', id - FROM vn.travel - WHERE shipped >= vn.getInventoryDate(); - - INSERT INTO queue (operation, tableName, tableId) - SELECT 'ADD', 'ticket', id - FROM vn.ticket - WHERE shipped >= vn.getInventoryDate(); - - CALL queuePoll; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `refreshDaily` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `refreshDaily`() -BEGIN -/** - * Elimina de la cache todas las compras y ventas previas - * a la fecha del último inventario. - */ - INSERT INTO queue (operation, tableName, tableId) - SELECT 'DEL', 'movement', saleFk - FROM sale - WHERE shipped < vn.getInventoryDate(); - - INSERT INTO queue (operation, tableName, tableId) - SELECT 'DEL', 'buy', buyFk - FROM buy - WHERE landed < vn.getInventoryDate(); - - CALL queuePoll; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `visibleCalc` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `visibleCalc`(vItem INT, vWarehouse INT) -BEGIN -/** - * Recalcula el visible para un artículo en un almacén. - * - * @param vItem Id de artículo - * @param vWarehouse Id de almacén - */ - DECLARE vVisible INT; - DECLARE vCurdate DATE DEFAULT CURDATE(); - - SELECT SUM(quantity) INTO vVisible - FROM ( - SELECT SUM(IF(vCurdate > landed OR isReceived, quantity, 0)) quantity - FROM buy - WHERE itemFk = vItem - AND warehouseInFk = vWarehouse - AND landed <= vCurdate - UNION ALL - SELECT -SUM(IF(vCurdate > shipped OR isDelivered, quantity, 0)) - FROM buy - WHERE itemFk = vItem - AND warehouseOutFk = vWarehouse - AND shipped <= vCurdate - UNION ALL - SELECT -SUM(IF(vCurdate > shipped OR isPicked, quantity, 0)) - FROM sale - WHERE itemFk = vItem - AND warehouseFk = vWarehouse - AND shipped <= vCurdate - ) t; - - IF vVisible > 0 - THEN - REPLACE INTO visible SET - itemFk = vItem, - warehouseFk = vWarehouse, - quantity = vVisible; - ELSE - DELETE FROM visible - WHERE itemFk = vItem - AND warehouseFk = vWarehouse; - 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 */ ; - --- --- Current Database: `account` --- - -USE `account`; - --- --- Final view structure for view `accountDovecot` --- - -/*!50001 DROP VIEW IF EXISTS `accountDovecot`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `accountDovecot` AS select `u`.`name` AS `name`,`u`.`password` AS `password` from (`user` `u` join `account` `a` on((`a`.`id` = `u`.`id`))) where `u`.`active` */; -/*!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 `accountPam` --- - -/*!50001 DROP VIEW IF EXISTS `accountPam`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `accountPam` AS select `u`.`name` AS `name`,`u`.`password` AS `password` from (`user` `u` join `account` `a` on((`u`.`id` = `a`.`id`))) where (`u`.`active` <> 0) */; -/*!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 `userRole` --- - -/*!50001 DROP VIEW IF EXISTS `userRole`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `userRole` AS select `r`.`inheritsFrom` AS `id` from (`roleRole` `r` join `user` `u` on((`u`.`role` = `r`.`role`))) where (`u`.`id` = `USERGETID`()) */; -/*!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 `userView` --- - -/*!50001 DROP VIEW IF EXISTS `userView`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `userView` AS select `u`.`id` AS `id`,`u`.`name` AS `name`,`u`.`active` AS `active`,`u`.`email` AS `email`,`u`.`nickname` AS `nickname`,`u`.`lang` AS `lang`,`u`.`role` AS `role`,`u`.`recoverPass` AS `recoverPass` from `user` `u` where (`u`.`name` = `account`.`userGetName`()) */ -/*!50002 WITH CASCADED CHECK OPTION */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Current Database: `util` --- - -USE `util`; - --- --- Current Database: `vn2008` --- - -USE `vn2008`; - --- --- Final view structure for view `V_edi_item_track` --- - -/*!50001 DROP VIEW IF EXISTS `V_edi_item_track`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `V_edi_item_track` AS select `edi`.`item_track`.`item_id` AS `item_id`,`edi`.`item_track`.`s1` AS `s1`,`edi`.`item_track`.`s2` AS `s2`,`edi`.`item_track`.`s3` AS `s3`,`edi`.`item_track`.`s4` AS `s4`,`edi`.`item_track`.`s5` AS `s5`,`edi`.`item_track`.`s6` AS `s6`,`edi`.`item_track`.`kop` AS `kop`,`edi`.`item_track`.`pac` AS `pac`,`edi`.`item_track`.`cat` AS `cat`,`edi`.`item_track`.`ori` AS `ori`,`edi`.`item_track`.`pro` AS `pro`,`edi`.`item_track`.`sub` AS `sub`,`edi`.`item_track`.`package` AS `package` from `edi`.`item_track` */; -/*!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 `VerEspionaje` --- - -/*!50001 DROP VIEW IF EXISTS `VerEspionaje`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `VerEspionaje` AS select `Trabajadores`.`CodigoTrabajador` AS `CodigoTrabajador`,`Espionajes`.`Fecha` AS `Fecha`,`Espionajes`.`HoraEntrada` AS `HoraEntrada`,`Espionajes`.`HoraSalida` AS `HoraSalida`,`Espionajes`.`Id_Equipo` AS `Id_Equipo`,`Trabajadores`.`Id_Trabajador` AS `Id_Trabajador` from (`Espionajes` join `Trabajadores` on((`Espionajes`.`Id_Trabajador` = `Trabajadores`.`Id_Trabajador`))) order by `Trabajadores`.`CodigoTrabajador`,`Espionajes`.`Fecha` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `account_customer` --- - -/*!50001 DROP VIEW IF EXISTS `account_customer`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `account_customer` AS select `e`.`description` AS `description`,`vn2008`.`cc_to_iban`(concat(`a`.`entity_id`,`a`.`office`,`a`.`DC`,`a`.`number`)) AS `iban`,`a`.`entity_id` AS `entity_id`,`a`.`office` AS `office`,`a`.`DC` AS `dc`,`a`.`number` AS `number` from ((`provider_account_customer` `c` join `Proveedores_account` `a` on((`a`.`Id_Proveedores_account` = `c`.`account_id`))) join `entity` `e` on((`a`.`entity_id` = `e`.`entity_id`))) */; -/*!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 `awb_volume` --- - -/*!50001 DROP VIEW IF EXISTS `awb_volume`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `awb_volume` AS select `ar`.`awb_id` AS `awb_id`,(((`c`.`Etiquetas` * `a`.`density`) * if((`cu`.`Volumen` > 0),`cu`.`Volumen`,((`cu`.`X` * `cu`.`Y`) * if((`cu`.`Z` = 0),(`a`.`Medida` + 10),`cu`.`Z`)))) / 167000) AS `volume` from (((((((`Compres` `c` join `Articles` `a` on((`c`.`Id_Article` = `a`.`Id_Article`))) join `Tipos` `t` on((`a`.`tipo_id` = `t`.`tipo_id`))) join `Cubos` `cu` on((`cu`.`Id_Cubo` = `c`.`Id_Cubo`))) join `Entradas` `e` on((`c`.`Id_Entrada` = `e`.`Id_Entrada`))) join `travel` `tr` on((`tr`.`id` = `e`.`travel_id`))) join `recibida_entrada` `re` on((`c`.`Id_Entrada` = `re`.`Id_Entrada`))) join `awb_recibida` `ar` on((`re`.`awb_recibida` = `ar`.`recibida_id`))) where (`tr`.`shipment` > makedate((year(curdate()) - 1),1)) */; -/*!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 `cdr` --- - -/*!50001 DROP VIEW IF EXISTS `cdr`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `cdr` AS select `c`.`call_date` AS `calldate`,`c`.`clid` AS `clid`,`c`.`src` AS `src`,`c`.`dst` AS `dst`,`c`.`dcontext` AS `dcontext`,`c`.`channel` AS `channel`,`c`.`dst_channel` AS `dstchannel`,`c`.`last_app` AS `lastapp`,`c`.`last_data` AS `lastdata`,`c`.`duration` AS `duration`,`c`.`billsec` AS `billsec`,`c`.`disposition` AS `disposition`,`c`.`ama_flags` AS `amaflags`,`c`.`account_code` AS `accountcode`,`c`.`unique_id` AS `uniqueid`,`c`.`user_field` AS `userfield` from `pbx`.`cdr` `c` */; -/*!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 `clientMana` --- - -/*!50001 DROP VIEW IF EXISTS `clientMana`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `clientMana` AS select `t`.`Id_Cliente` AS `Id_Cliente`,`mc`.`Valor` AS `ManaUnitario`,(`mc`.`Valor` * `m`.`Cantidad`) AS `ManaTotal`,`t`.`Id_Ticket` AS `Id_Ticket`,`m`.`Id_Article` AS `Id_Article`,`m`.`Concepte` AS `Concepte`,`m`.`Cantidad` AS `Cantidad`,`m`.`Preu` AS `Preu`,`t`.`Fecha` AS `Fecha`,`m`.`Id_Movimiento` AS `Id_Movimiento` from ((((`vn2008`.`Tickets` `t` join `vn2008`.`Movimientos` `m` on((`m`.`Id_Ticket` = `t`.`Id_Ticket`))) join `vn2008`.`Movimientos_componentes` `mc` on((`mc`.`Id_Movimiento` = `m`.`Id_Movimiento`))) join `vn2008`.`tarifa_componentes` `tc` on((`tc`.`Id_Componente` = `mc`.`Id_Componente`))) join `vn2008`.`tarifa_componentes_series` `tcs` on((`tc`.`tarifa_componentes_series_id` = `tcs`.`tarifa_componentes_series_id`))) where ((`t`.`Fecha` >= '2016-01-01') and (`tcs`.`Serie` = 'cartera_comercial') and (`mc`.`Valor` <> 0)) */; -/*!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 `edi_article` --- - -/*!50001 DROP VIEW IF EXISTS `edi_article`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `edi_article` AS select `edi`.`item`.`id` AS `id`,`edi`.`item`.`product_name` AS `product_name`,`edi`.`item`.`name` AS `name`,`edi`.`item`.`plant_id` AS `plant_id`,`edi`.`item`.`group_id` AS `group_id`,`edi`.`item`.`entry_date` AS `entry_date`,`edi`.`item`.`expiry_date` AS `expiry_date`,`edi`.`item`.`change_date_time` AS `change_date_time` from `edi`.`item` */; -/*!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 `edi_bucket` --- - -/*!50001 DROP VIEW IF EXISTS `edi_bucket`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `edi_bucket` AS select (cast(`edi`.`bucket`.`bucket_id` as char charset utf8) collate utf8_general_ci) AS `bucket_id`,`edi`.`bucket`.`bucket_type_id` AS `bucket_type_id`,`edi`.`bucket`.`description` AS `description`,`edi`.`bucket`.`x_size` AS `x_size`,`edi`.`bucket`.`y_size` AS `y_size`,`edi`.`bucket`.`z_size` AS `z_size`,`edi`.`bucket`.`entry_date` AS `entry_date`,`edi`.`bucket`.`expiry_date` AS `expiry_date`,`edi`.`bucket`.`change_date_time` AS `change_date_time` from `edi`.`bucket` */; -/*!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 `edi_bucket_type` --- - -/*!50001 DROP VIEW IF EXISTS `edi_bucket_type`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `edi_bucket_type` AS select `edi`.`bucket_type`.`bucket_type_id` AS `bucket_type_id`,`edi`.`bucket_type`.`description` AS `description`,`edi`.`bucket_type`.`entry_date` AS `entry_date`,`edi`.`bucket_type`.`expiry_date` AS `expiry_date`,`edi`.`bucket_type`.`change_date_time` AS `change_date_time` from `edi`.`bucket_type` */; -/*!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 `edi_feature` --- - -/*!50001 DROP VIEW IF EXISTS `edi_feature`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `edi_feature` AS select `edi`.`feature`.`item_id` AS `item_id`,`edi`.`feature`.`feature_type_id` AS `feature_type_id`,`edi`.`feature`.`feature_value` AS `feature_value`,`edi`.`feature`.`entry_date` AS `entry_date`,`edi`.`feature`.`expiry_date` AS `expiry_date`,`edi`.`feature`.`change_date_time` AS `change_date_time` from `edi`.`feature` */; -/*!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 `edi_genus` --- - -/*!50001 DROP VIEW IF EXISTS `edi_genus`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `edi_genus` AS select `edi`.`genus`.`genus_id` AS `genus_id`,`edi`.`genus`.`latin_genus_name` AS `latin_genus_name`,`edi`.`genus`.`entry_date` AS `entry_date`,`edi`.`genus`.`expiry_date` AS `expiry_date`,`edi`.`genus`.`change_date_time` AS `change_date_time` from `edi`.`genus` */; -/*!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 `edi_item_feature` --- - -/*!50001 DROP VIEW IF EXISTS `edi_item_feature`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `edi_item_feature` AS select `edi`.`item_feature`.`item_id` AS `item_id`,`edi`.`item_feature`.`presentation_order` AS `presentation_order`,`edi`.`item_feature`.`feature` AS `feature`,`edi`.`item_feature`.`regulation_type` AS `regulation_type`,`edi`.`item_feature`.`entry_date` AS `entry_date`,`edi`.`item_feature`.`expiry_date` AS `expiry_date`,`edi`.`item_feature`.`change_date_time` AS `change_date_time` from `edi`.`item_feature` */; -/*!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 `edi_plant` --- - -/*!50001 DROP VIEW IF EXISTS `edi_plant`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `edi_plant` AS select `edi`.`plant`.`plant_id` AS `plant_id`,`edi`.`plant`.`genus_id` AS `genus_id`,`edi`.`plant`.`specie_id` AS `specie_id`,`edi`.`plant`.`entry_date` AS `entry_date`,`edi`.`plant`.`expiry_date` AS `expiry_date`,`edi`.`plant`.`change_date_time` AS `change_date_time` from `edi`.`plant` */; -/*!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 `edi_specie` --- - -/*!50001 DROP VIEW IF EXISTS `edi_specie`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `edi_specie` AS select `edi`.`specie`.`specie_id` AS `specie_id`,`edi`.`specie`.`genus_id` AS `genus_id`,`edi`.`specie`.`latin_species_name` AS `latin_species_name`,`edi`.`specie`.`entry_date` AS `entry_date`,`edi`.`specie`.`expiry_date` AS `expiry_date`,`edi`.`specie`.`change_date_time` AS `change_date_time` from `edi`.`specie` */; -/*!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 `edi_supplier` --- - -/*!50001 DROP VIEW IF EXISTS `edi_supplier`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `edi_supplier` AS select `edi`.`supplier`.`supplier_id` AS `supplier_id`,`edi`.`supplier`.`company_name` AS `company_name` from `edi`.`supplier` */; -/*!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 `edi_type` --- - -/*!50001 DROP VIEW IF EXISTS `edi_type`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `edi_type` AS select `edi`.`type`.`type_id` AS `type_id`,`edi`.`type`.`type_group_id` AS `type_group_id`,`edi`.`type`.`description` AS `description`,`edi`.`type`.`entry_date` AS `entry_date`,`edi`.`type`.`expiry_date` AS `expiry_date`,`edi`.`type`.`change_date_time` AS `change_date_time` from `edi`.`type` */; -/*!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 `edi_value` --- - -/*!50001 DROP VIEW IF EXISTS `edi_value`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `edi_value` AS select `edi`.`value`.`type_id` AS `type_id`,`edi`.`value`.`type_value` AS `type_value`,`edi`.`value`.`type_description` AS `type_description`,`edi`.`value`.`entry_date` AS `entry_date`,`edi`.`value`.`expiry_date` AS `expiry_date`,`edi`.`value`.`change_date_time` AS `change_date_time` from `edi`.`value` */; -/*!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 `itemTag` --- - -/*!50001 DROP VIEW IF EXISTS `itemTag`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `itemTag` AS select `i`.`id` AS `id`,`i`.`itemFk` AS `itemFk`,`i`.`tagFk` AS `tagFk`,`i`.`value` AS `value`,`i`.`priority` AS `priority` from `vn`.`itemTag` `i` */; -/*!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 `itemTagArranged` --- - -/*!50001 DROP VIEW IF EXISTS `itemTagArranged`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `itemTagArranged` AS select `i`.`itemFk` AS `itemFk`,`i`.`tag1` AS `tag1`,`i`.`val1` AS `val1`,`i`.`tag2` AS `tag2`,`i`.`val2` AS `val2`,`i`.`tag3` AS `tag3`,`i`.`val3` AS `val3`,`i`.`tag4` AS `tag4`,`i`.`val4` AS `val4`,`i`.`tag5` AS `tag5`,`i`.`val5` AS `val5`,`i`.`tag6` AS `tag6`,`i`.`val6` AS `val6`,`i`.`description` AS `description` from `vn`.`itemTagArranged` `i` */; -/*!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 `item_entry_in` --- - -/*!50001 DROP VIEW IF EXISTS `item_entry_in`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `item_entry_in` AS select `t`.`warehouse_id` AS `warehouse_id`,`t`.`landing` AS `dat`,`m`.`Id_Article` AS `item_id`,`m`.`Cantidad` AS `amount`,`t`.`received` AS `received` from ((`Compres` `m` join `Entradas` `e` on((`m`.`Id_Entrada` = `e`.`Id_Entrada`))) join `travel` `t` on((`e`.`travel_id` = `t`.`id`))) where ((`e`.`Inventario` = 0) and (`m`.`Cantidad` <> 0)) */; -/*!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 `item_entry_out` --- - -/*!50001 DROP VIEW IF EXISTS `item_entry_out`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `item_entry_out` AS select `t`.`warehouse_id_out` AS `warehouse_id`,`t`.`shipment` AS `dat`,`m`.`Id_Article` AS `item_id`,-(`m`.`Cantidad`) AS `amount`,(`t`.`delivered` or ifnull(`co`.`valor`,0)) AS `delivered` from (((`Compres` `m` join `Entradas` `e` on((`m`.`Id_Entrada` = `e`.`Id_Entrada`))) join `travel` `t` on((`e`.`travel_id` = `t`.`id`))) left join `Compres_ok` `co` on(((`co`.`Id_Compra` = `m`.`Id_Compra`) and (`co`.`Id_Accion` = 3)))) where ((`e`.`Inventario` = 0) and (`e`.`Redada` = 0) and (`m`.`Cantidad` <> 0)) */; -/*!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 `item_entry_outkk` --- - -/*!50001 DROP VIEW IF EXISTS `item_entry_outkk`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `item_entry_outkk` AS select `t`.`warehouse_id_out` AS `warehouse_id`,`t`.`shipment` AS `dat`,`m`.`Id_Article` AS `item_id`,-(`m`.`Cantidad`) AS `amount`,`t`.`delivered` AS `delivered` from ((`Compres` `m` join `Entradas` `e` on((`m`.`Id_Entrada` = `e`.`Id_Entrada`))) join `travel` `t` on((`e`.`travel_id` = `t`.`id`))) where ((`e`.`Inventario` = 0) and (`e`.`Redada` = 0) and (`m`.`Cantidad` <> 0)) */; -/*!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 `item_out` --- - -/*!50001 DROP VIEW IF EXISTS `item_out`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `item_out` AS select `t`.`warehouse_id` AS `warehouse_id`,`t`.`Fecha` AS `dat`,`m`.`Id_Article` AS `item_id`,-(`m`.`Cantidad`) AS `amount`,`m`.`OK` AS `ok`,`m`.`Reservado` AS `Reservado`,(`ts`.`alertLevel` = 3) AS `ready`,`t`.`Factura` AS `invoice`,ifnull(`ts`.`alertLevel`,0) AS `alertLevel` from ((`vn2008`.`Movimientos` `m` join `vn2008`.`Tickets` `t` on((`m`.`Id_Ticket` = `t`.`Id_Ticket`))) left join `vn`.`ticketState` `ts` on((`t`.`Id_Ticket` = `ts`.`ticket`))) where (`m`.`Cantidad` <> 0) */; -/*!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 `new_viewkk` --- - -/*!50001 DROP VIEW IF EXISTS `new_viewkk`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `new_viewkk` AS select `vn`.`workerDocument`.`id` AS `id`,`vn`.`workerDocument`.`worker` AS `worker`,`vn`.`workerDocument`.`document` AS `document` from `vn`.`workerDocument` */; -/*!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 `order` --- - -/*!50001 DROP VIEW IF EXISTS `order`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `order` AS select `hedera`.`order`.`id` AS `id`,`hedera`.`order`.`date_make` AS `date_make`,`hedera`.`order`.`date_send` AS `date_send`,`hedera`.`order`.`customer_id` AS `customer_id`,`hedera`.`order`.`delivery_method_id` AS `delivery_method_id`,`hedera`.`order`.`agency_id` AS `agency_id`,`hedera`.`order`.`address_id` AS `address_id`,`hedera`.`order`.`note` AS `note`,`hedera`.`order`.`confirmed` AS `confirmed`,`hedera`.`order`.`is_bionic` AS `is_bionic`,`hedera`.`order`.`source_app` AS `source_app` from `hedera`.`order` */; -/*!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 `order_component` --- - -/*!50001 DROP VIEW IF EXISTS `order_component`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `order_component` AS select `c`.`order_row_id` AS `order_row_id`,`c`.`component_id` AS `component_id`,`c`.`price` AS `price` from `hedera`.`order_component` `c` */; -/*!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 `order_row` --- - -/*!50001 DROP VIEW IF EXISTS `order_row`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `order_row` AS select `order_row`.`id` AS `id`,`order_row`.`order_id` AS `order_id`,`order_row`.`item_id` AS `item_id`,`order_row`.`warehouse_id` AS `warehouse_id`,`order_row`.`shipment` AS `shipment`,`order_row`.`amount` AS `amount`,`order_row`.`price` AS `price`,`order_row`.`rate` AS `rate`,`order_row`.`created` AS `created`,`order_row`.`Id_Movimiento` AS `Id_Movimiento` from `hedera`.`order_row` */; -/*!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 `person_user` --- - -/*!50001 DROP VIEW IF EXISTS `person_user`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `person_user` AS select `u`.`id` AS `id`,`u`.`role` AS `mysql_user_id`,`u`.`name` AS `name`,`u`.`password` AS `password`,`u`.`active` AS `active`,`u`.`lastPassChange` AS `last_pass_change` from `account`.`user` `u` */; -/*!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 `person_user_idtrabajador` --- - -/*!50001 DROP VIEW IF EXISTS `person_user_idtrabajador`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `person_user_idtrabajador` AS select `t`.`Id_Trabajador` AS `Id_Trabajador` from (`vn2008`.`person_user` `p` join `vn2008`.`Trabajadores` `t` on((`p`.`id` = `t`.`user_id`))) where (`t`.`user_id` = `account`.`userGetId`()) */; -/*!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 `proveedores_clientes` --- - -/*!50001 DROP VIEW IF EXISTS `proveedores_clientes`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `proveedores_clientes` AS select `Proveedores`.`Id_Proveedor` AS `Id_Proveedor`,`Proveedores`.`Proveedor` AS `Proveedor`,`Clientes`.`id_cliente` AS `Id_Cliente`,`Clientes`.`cliente` AS `Cliente` from (`Proveedores` join `Clientes` on((`Proveedores`.`NIF` = `Clientes`.`if`))) */; -/*!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 `sms` --- - -/*!50001 DROP VIEW IF EXISTS `sms`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `sms` AS select `t`.`id` AS `id`,`t`.`senderFk` AS `Id_trabajador`,`t`.`destinationFk` AS `Id_Cliente`,`t`.`sender` AS `from`,`t`.`destination` AS `to`,`t`.`message` AS `text`,`t`.`statusCode` AS `sent`,`t`.`status` AS `response`,`t`.`created` AS `DATE_ODBC` from `vn`.`sms` `t` */; -/*!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 `tag` --- - -/*!50001 DROP VIEW IF EXISTS `tag`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `tag` AS select `t`.`id` AS `id`,`t`.`name` AS `name`,`t`.`isFree` AS `isFree`,`t`.`isQuantitatif` AS `isQuantitatif`,`t`.`sourceTable` AS `sourceTable`,`t`.`unit` AS `unit` from `vn`.`tag` `t` */; -/*!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 `tarifa_componentes` --- - -/*!50001 DROP VIEW IF EXISTS `tarifa_componentes`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `tarifa_componentes` AS select `bi`.`tarifa_componentes`.`Id_Componente` AS `Id_Componente`,`bi`.`tarifa_componentes`.`Componente` AS `Componente`,`bi`.`tarifa_componentes`.`tarifa_componentes_series_id` AS `tarifa_componentes_series_id`,`bi`.`tarifa_componentes`.`tarifa_class` AS `tarifa_class`,`bi`.`tarifa_componentes`.`tax` AS `tax`,`bi`.`tarifa_componentes`.`is_renewable` AS `is_renewable` from `bi`.`tarifa_componentes` */; -/*!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 `tarifa_componentes_series` --- - -/*!50001 DROP VIEW IF EXISTS `tarifa_componentes_series`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `tarifa_componentes_series` AS select `bi`.`tarifa_componentes_series`.`tarifa_componentes_series_id` AS `tarifa_componentes_series_id`,`bi`.`tarifa_componentes_series`.`Serie` AS `Serie`,`bi`.`tarifa_componentes_series`.`base` AS `base` from `bi`.`tarifa_componentes_series` */; -/*!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 `ticketCreationData` --- - -/*!50001 DROP VIEW IF EXISTS `ticketCreationData`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ticketCreationData` AS select dayname(`h`.`confirm_date`) AS `DiadelaSemana`,hour(`h`.`confirm_date`) AS `Hora`,cast(`h`.`confirm_date` as date) AS `Fecha`,`h`.`source_app` AS `Dispositivo` from `hedera`.`order` `h` where `h`.`confirm_date` */; -/*!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 `v_Agenda` --- - -/*!50001 DROP VIEW IF EXISTS `v_Agenda`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_Agenda` AS select 'P' AS `Tipo`,`Proveedores`.`Id_Proveedor` AS `Id`,`Proveedores`.`Proveedor` AS `Nombre`,`Proveedores`.`Telefono` AS `Telephone` from `Proveedores` where (`Proveedores`.`Telefono` is not null) union select 'C' AS `Tipo`,`Clientes`.`id_cliente` AS `Id`,`Clientes`.`cliente` AS `Cliente`,`Clientes`.`telefono` AS `Telefono` from `Clientes` where (`Clientes`.`telefono` is not null) union select 'C' AS `Tipo`,`Clientes`.`id_cliente` AS `Id`,`Clientes`.`cliente` AS `Cliente`,`Clientes`.`movil` AS `Movil` from `Clientes` where (`Clientes`.`movil` is not null) union select if(isnull(`Relaciones`.`Id_Proveedor`),'C','P') AS `Tipo`,if(isnull(`Relaciones`.`Id_Proveedor`),`Relaciones`.`Id_Cliente`,`Relaciones`.`Id_Proveedor`) AS `Id`,`Contactos`.`Nombre` AS `Nombre`,`Contactos`.`Telefono` AS `Telefono` from (`Contactos` join `Relaciones` on((`Contactos`.`Id_Contacto` = `Relaciones`.`Id_Contacto`))) where (`Contactos`.`Telefono` is not null) union select if(isnull(`Relaciones`.`Id_Proveedor`),'C','P') AS `Tipo`,if(isnull(`Relaciones`.`Id_Proveedor`),`Relaciones`.`Id_Cliente`,`Relaciones`.`Id_Proveedor`) AS `Id`,`Contactos`.`Nombre` AS `Nombre`,`Contactos`.`Movil` AS `Movil` from (`Contactos` join `Relaciones` on((`Contactos`.`Id_Contacto` = `Relaciones`.`Id_Contacto`))) where (`Contactos`.`Movil` is not null) union select 'T' AS `Tipo`,`Trabajadores`.`Id_Trabajador` AS `Id_Trabajador`,`Trabajadores`.`CodigoTrabajador` AS `CodigoTrabajador`,`Trabajadores`.`extension` AS `extension` from `Trabajadores` where (`Trabajadores`.`extension` is not null) */; -/*!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 `v_Agenda2` --- - -/*!50001 DROP VIEW IF EXISTS `v_Agenda2`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_Agenda2` AS select `v_Agenda`.`Tipo` AS `Tipo`,`v_Agenda`.`Id` AS `Id`,`v_Agenda`.`Nombre` AS `Nombre`,replace(`v_Agenda`.`Telephone`,' ','') AS `Telefono` from `v_Agenda` where `v_Agenda`.`Telephone` group by replace(`v_Agenda`.`Telephone`,' ','') */; -/*!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 `v_Articles_botanical` --- - -/*!50001 DROP VIEW IF EXISTS `v_Articles_botanical`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_Articles_botanical` AS select `ab`.`Id_Article` AS `Id_Article`,ifnull(`ab`.`botanical`,concat(`g`.`latin_genus_name`,' ',ifnull(`s`.`latin_species_name`,''))) AS `edi_botanic` from ((`vn2008`.`Articles_botanical` `ab` left join `edi`.`genus` `g` on((`ab`.`genus_id` = `g`.`genus_id`))) left join `edi`.`specie` `s` on((`s`.`specie_id` = `ab`.`specie_id`))) */; -/*!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 `v_Movimientos_Volumen_shipping_charge` --- - -/*!50001 DROP VIEW IF EXISTS `v_Movimientos_Volumen_shipping_charge`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_Movimientos_Volumen_shipping_charge` AS select `M`.`Id_Ticket` AS `Id_Ticket`,`M`.`Id_Movimiento` AS `Id_Movimiento`,`t`.`Fecha` AS `Fecha`,`az`.`price` AS `price`,(((`M`.`Cantidad` * `r`.`cm3`) / `cb`.`Volumen`) * `az`.`price`) AS `freight` from (((((((`vn2008`.`Movimientos` `M` join `vn2008`.`Tickets` `t` on((`t`.`Id_Ticket` = `M`.`Id_Ticket`))) join `vn2008`.`Consignatarios` `c` on((`c`.`id_consigna` = `t`.`Id_Consigna`))) join `bi`.`rotacion` `r` on(((`r`.`Id_Article` = `M`.`Id_Article`) and (`r`.`warehouse_id` = `t`.`warehouse_id`)))) join `vn2008`.`Cubos` `cb` on((`cb`.`Id_Cubo` = 94))) join `vn2008`.`Agencias` `a` on((`a`.`Id_Agencia` = `t`.`Id_Agencia`))) join `vn2008`.`Agencias_province` `ap` on(((`t`.`warehouse_id` = `ap`.`warehouse_id`) and (`ap`.`province_id` = `c`.`province_id`) and (`ap`.`agency_id` = `a`.`agency_id`)))) join `vn2008`.`Agencias_zonas` `az` on(((`az`.`Id_Agencia` = `t`.`Id_Agencia`) and (`az`.`zona` = `ap`.`zona`) and (`t`.`warehouse_id` = `az`.`warehouse_id`) and (`az`.`Id_Article` = 71)))) */; -/*!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 `v_Ordenes` --- - -/*!50001 DROP VIEW IF EXISTS `v_Ordenes`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_Ordenes` AS select `Ordenes`.`Id_ORDEN` AS `Id_ORDEN`,`Ordenes`.`ORDEN` AS `ORDEN`,`Ordenes`.`datORDEN` AS `datORDEN`,`Ordenes`.`datTICKET` AS `datTICKET`,`Ordenes`.`CodVENDEDOR` AS `CodVENDEDOR`,`Ordenes`.`CodCOMPRADOR` AS `CodCOMPRADOR`,`Ordenes`.`CANTIDAD` AS `CANTIDAD`,`Ordenes`.`PRECIOMAX` AS `PRECIOMAX`,`Ordenes`.`PREU` AS `PREU`,`Ordenes`.`Id_ARTICLE` AS `Id_ARTICLE`,`Ordenes`.`Id_CLIENTE` AS `Id_CLIENTE`,`Ordenes`.`COMENTARIO` AS `COMENTARIO`,`Ordenes`.`OK` AS `OK`,`Ordenes`.`TOTAL` AS `TOTAL`,`Ordenes`.`datCOMPRA` AS `datCOMPRA`,`Ordenes`.`KO` AS `KO`,`Ordenes`.`Id_Movimiento` AS `Id_Movimiento`,`Ordenes`.`odbc_date` AS `odbc_date` from `Ordenes` */; -/*!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 `v_XDiario_ALL` --- - -/*!50001 DROP VIEW IF EXISTS `v_XDiario_ALL`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_XDiario_ALL` AS select `bi`.`XDiario_ALL`.`empresa_id` AS `empresa_id`,`bi`.`XDiario_ALL`.`SUBCTA` AS `SUBCTA`,`bi`.`XDiario_ALL`.`Eurodebe` AS `Eurodebe`,`bi`.`XDiario_ALL`.`Eurohaber` AS `Eurohaber`,`bi`.`XDiario_ALL`.`Fecha` AS `Fecha`,`bi`.`XDiario_ALL`.`FECHA_EX` AS `FECHA_EX` from `bi`.`XDiario_ALL` */; -/*!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 `v_accion` --- - -/*!50001 DROP VIEW IF EXISTS `v_accion`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_accion` AS select `vncontrol`.`accion`.`accion_id` AS `accion_id`,`vncontrol`.`accion`.`accion` AS `accion` from `vncontrol`.`accion` */; -/*!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 `v_account` --- - -/*!50001 DROP VIEW IF EXISTS `v_account`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_account` AS select `a`.`id` AS `user_id` from `account`.`account` `a` */; -/*!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 `v_analisis_ventas` --- - -/*!50001 DROP VIEW IF EXISTS `v_analisis_ventas`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_analisis_ventas` AS select `bi`.`analisis_ventas`.`Familia` AS `Familia`,`bi`.`analisis_ventas`.`Reino` AS `Reino`,`bi`.`analisis_ventas`.`Comercial` AS `Comercial`,`bi`.`analisis_ventas`.`Comprador` AS `Comprador`,`bi`.`analisis_ventas`.`Provincia` AS `Provincia`,`bi`.`analisis_ventas`.`almacen` AS `almacen`,`bi`.`analisis_ventas`.`Año` AS `Año`,`bi`.`analisis_ventas`.`Mes` AS `Mes`,`bi`.`analisis_ventas`.`Semana` AS `Semana`,`bi`.`analisis_ventas`.`Vista` AS `Vista`,`bi`.`analisis_ventas`.`Importe` AS `Importe` from `bi`.`analisis_ventas` */; -/*!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 `v_awb_volumen` --- - -/*!50001 DROP VIEW IF EXISTS `v_awb_volumen`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_awb_volumen` AS select `a`.`id` AS `awb_id`,`a`.`codigo` AS `codigo`,`a`.`importe` AS `importe`,cast(sum(`v`.`volume`) as signed) AS `Vol_Total` from (`awb` `a` join `awb_volume` `v` on((`v`.`awb_id` = `a`.`id`))) group by `a`.`id` */; -/*!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 `v_barcodes` --- - -/*!50001 DROP VIEW IF EXISTS `v_barcodes`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_barcodes` AS select `Articles`.`Id_Article` AS `code`,`Articles`.`Id_Article` AS `Id_Article` from `Articles` union all select `barcodes`.`code` AS `code`,`barcodes`.`Id_Article` AS `Id_Article` from `barcodes` union all select `c`.`Id_Compra` AS `Id_Compra`,`c`.`Id_Article` AS `Id_Article` from ((`Compres` `c` join `Entradas` `e` on((`c`.`Id_Entrada` = `e`.`Id_Entrada`))) join `travel` `tr` on((`tr`.`id` = `e`.`travel_id`))) where (`tr`.`landing` >= (curdate() + interval -(15) day)) */; -/*!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 `v_barcodes_plus` --- - -/*!50001 DROP VIEW IF EXISTS `v_barcodes_plus`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_barcodes_plus` AS select `cache`.`barcodes`.`code` AS `code`,`cache`.`barcodes`.`Id_Article` AS `Id_Article`,`cache`.`barcodes`.`Article` AS `Article`,`cache`.`barcodes`.`Medida` AS `Medida`,`cache`.`barcodes`.`Color` AS `Color`,`cache`.`barcodes`.`Categoria` AS `Categoria`,`cache`.`barcodes`.`Producer` AS `Producer` from `cache`.`barcodes` */; -/*!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 `v_botanic_export` --- - -/*!50001 DROP VIEW IF EXISTS `v_botanic_export`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_botanic_export` AS select concat(ifnull(concat(`eg`.`latin_genus_name`,' '),''),ifnull(`es`.`latin_species_name`,'')) AS `Nom_botanic`,`be`.`Id_Paises` AS `Id_Paises`,`be`.`restriction` AS `restriction`,`be`.`description` AS `description` from ((`vn2008`.`botanic_export` `be` left join `vn2008`.`edi_genus` `eg` on((`be`.`edi_genus_id` = `eg`.`genus_id`))) left join `vn2008`.`edi_specie` `es` on((`be`.`edi_specie_id` = `es`.`specie_id`))) order by concat(`eg`.`latin_genus_name`,' ',`es`.`latin_species_name`) */; -/*!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 `v_compres` --- - -/*!50001 DROP VIEW IF EXISTS `v_compres`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_compres` AS select `TP`.`Id_Tipo` AS `Familia`,`RN`.`id` AS `reino_id`,`C`.`Id_Compra` AS `Id_Compra`,`C`.`Id_Entrada` AS `Id_Entrada`,`C`.`Id_Article` AS `Id_Article`,`C`.`Cantidad` AS `Cantidad`,`C`.`Costefijo` AS `Costefijo`,`C`.`Portefijo` AS `Portefijo`,`C`.`Novincular` AS `Novincular`,`C`.`Etiquetas` AS `Etiquetas`,`C`.`Packing` AS `Packing`,`C`.`grouping` AS `grouping`,`C`.`Comisionfija` AS `Comisionfija`,`C`.`Embalajefijo` AS `Embalajefijo`,`an`.`nicho` AS `Nicho`,`C`.`Id_Cubo` AS `Id_Cubo`,`C`.`Tarifa1` AS `Tarifa1`,`C`.`Tarifa2` AS `Tarifa2`,`C`.`Tarifa3` AS `Tarifa3`,`C`.`PVP` AS `PVP`,`C`.`Vida` AS `Vida`,`C`.`Id_Trabajador` AS `Id_Trabajador`,`C`.`punteo` AS `punteo`,`C`.`odbc_date` AS `odbc_date`,`E`.`Inventario` AS `Inventario`,`E`.`Id_Proveedor` AS `Id_Proveedor`,`E`.`Fecha` AS `Fecha`,`E`.`Confirmada` AS `Confirmada`,`E`.`Redada` AS `Redada`,`E`.`empresa_id` AS `empresa_id`,`E`.`travel_id` AS `travel_id`,`E`.`Pedida` AS `Pedida`,`E`.`recibida_id` AS `recibida_id`,`TR`.`id` AS `id`,`TR`.`shipment` AS `shipment`,`TR`.`landing` AS `landing`,`TR`.`warehouse_id` AS `warehouse_id`,`TR`.`warehouse_id_out` AS `warehouse_id_out`,`TR`.`agency_id` AS `agency_id`,`TR`.`ref` AS `ref`,`TR`.`delivered` AS `delivered`,`TR`.`received` AS `received`,`A`.`Article` AS `Article`,`A`.`Medida` AS `Medida`,`A`.`Tallos` AS `Tallos`,`C`.`caja` AS `caja`,`A`.`Categoria` AS `Categoria`,`A`.`id_origen` AS `id_origen`,`TP`.`Id_Tipo` AS `Tipo`,`A`.`tipo_id` AS `tipo_id`,`A`.`Color` AS `Color`,`A`.`Min` AS `Min`,(((`C`.`Costefijo` + `C`.`Embalajefijo`) + `C`.`Comisionfija`) + `C`.`Portefijo`) AS `Coste`,`W_OUT`.`fuente` AS `fuente`,`A`.`iva_group_id` AS `iva_group_id`,(if((`cb`.`Volumen` > 0),`cb`.`Volumen`,((`cb`.`X` * `cb`.`Y`) * if((`cb`.`Z` = 0),(`A`.`Medida` + 10),`cb`.`Z`))) * `C`.`Etiquetas`) AS `cm3`,`A`.`producer_id` AS `producer_id` from (((((((((`Compres` `C` join `Entradas` `E` on((`C`.`Id_Entrada` = `E`.`Id_Entrada`))) join `travel` `TR` on((`TR`.`id` = `E`.`travel_id`))) join `warehouse` `W_IN` on((`W_IN`.`id` = `TR`.`warehouse_id`))) join `warehouse` `W_OUT` on((`W_OUT`.`id` = `TR`.`warehouse_id_out`))) join `Articles` `A` on((`C`.`Id_Article` = `A`.`Id_Article`))) join `Tipos` `TP` on((`A`.`tipo_id` = `TP`.`tipo_id`))) join `reinos` `RN` on((`RN`.`id` = `TP`.`reino_id`))) join `Cubos` `cb` on((`cb`.`Id_Cubo` = `C`.`Id_Cubo`))) left join `Articles_nicho` `an` on(((`A`.`Id_Article` = `an`.`Id_Article`) and (`an`.`warehouse_id` = `W_IN`.`id`)))) where ((not(`W_IN`.`fuente`)) and (not(`E`.`Inventario`)) and (not(`E`.`Redada`))) */; -/*!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 `v_departure_limit` --- - -/*!50001 DROP VIEW IF EXISTS `v_departure_limit`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_departure_limit` AS select `cache`.`departure_limit`.`warehouse_id` AS `warehouse_id`,`cache`.`departure_limit`.`fecha` AS `fecha`,`cache`.`departure_limit`.`hora` AS `hora`,`cache`.`departure_limit`.`minSpeed` AS `minSpeed` from `cache`.`departure_limit` */; -/*!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 `v_descuadre_bionic` --- - -/*!50001 DROP VIEW IF EXISTS `v_descuadre_bionic`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_descuadre_bionic` AS select `t`.`Id_Ticket` AS `Id_Ticket`,`t`.`Alias` AS `Alias`,`m`.`Concepte` AS `Concepte`,sum(`mc`.`Valor`) AS `suma_componente`,`m`.`Preu` AS `Preu`,`m`.`Descuento` AS `Descuento`,(((`m`.`Preu` * (100 - `m`.`Descuento`)) / 100) - sum(`mc`.`Valor`)) AS `diferencia`,`t`.`Fecha` AS `Fecha`,((`m`.`Preu` > 0) and (`tp`.`reino_id` <> 6) and (`a`.`tipo_id` not in (7,115)) and (`t`.`warehouse_id` <> 41)) AS `benvenut` from ((((((`Movimientos` `m` join `Tickets` `t` on((`m`.`Id_Ticket` = `t`.`Id_Ticket`))) join `Clientes` `c` on((`t`.`Id_Cliente` = `c`.`id_cliente`))) join `warehouse` `w` on((`w`.`id` = `t`.`warehouse_id`))) join `Articles` `a` on((`m`.`Id_Article` = `a`.`Id_Article`))) join `Tipos` `tp` on((`a`.`tipo_id` = `tp`.`tipo_id`))) left join `Movimientos_componentes` `mc` on((`m`.`Id_Movimiento` = `mc`.`Id_Movimiento`))) where ((`t`.`Fecha` >= '2015-09-01') and (`t`.`empresa_id` in (442,791,567)) and `w`.`reserve` and `c`.`real` and (`tp`.`reino_id` <> 6)) group by `m`.`Id_Movimiento` having ((abs(`diferencia`) > 0.01) or isnull(`diferencia`)) */; -/*!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 `v_descuadre_porte` --- - -/*!50001 DROP VIEW IF EXISTS `v_descuadre_porte`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_descuadre_porte` AS select `t`.`Id_Ticket` AS `Id_Ticket`,round(sum((`mc`.`Valor` * `m`.`Cantidad`)),2) AS `suma_componente`,round(`es`.`shipping_charge`,2) AS `teorico_agencia`,round((sum((`mc`.`Valor` * `m`.`Cantidad`)) - `es`.`shipping_charge`),2) AS `diferencia`,`t`.`Fecha` AS `Fecha` from ((((`vn2008`.`Movimientos` `m` left join `vn2008`.`Movimientos_componentes` `mc` on((`m`.`Id_Movimiento` = `mc`.`Id_Movimiento`))) join `vn2008`.`tarifa_componentes` `tc` on(((`tc`.`Id_Componente` = `mc`.`Id_Componente`) and (`tc`.`tarifa_componentes_series_id` = 6)))) join `vn2008`.`Tickets` `t` on((`t`.`Id_Ticket` = `m`.`Id_Ticket`))) left join `vn2008`.`v_expeditions_shipping_charge` `es` on((`es`.`Id_Ticket` = `t`.`Id_Ticket`))) where ((`t`.`Fecha` >= '2015-09-01') and (`t`.`empresa_id` in (442,791,567))) group by `t`.`Id_Ticket` having ((abs(`diferencia`) > 0.01) or isnull(`diferencia`)) */; -/*!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 `v_descuadre_porte2` --- - -/*!50001 DROP VIEW IF EXISTS `v_descuadre_porte2`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_descuadre_porte2` AS select `t`.`Id_Ticket` AS `Id_Ticket`,(`mc`.`Valor` * `m`.`Cantidad`) AS `suma_componente`,`t`.`Fecha` AS `Fecha` from (((`vn2008`.`Movimientos` `m` left join `vn2008`.`Movimientos_componentes` `mc` on((`m`.`Id_Movimiento` = `mc`.`Id_Movimiento`))) join `vn2008`.`tarifa_componentes` `tc` on(((`tc`.`Id_Componente` = `mc`.`Id_Componente`) and (`tc`.`tarifa_componentes_series_id` = 6)))) join `vn2008`.`Tickets` `t` on((`t`.`Id_Ticket` = `m`.`Id_Ticket`))) where ((`t`.`Fecha` >= '2015-09-01') and (`t`.`empresa_id` in (442,791,567))) */; -/*!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 `v_empresa` --- - -/*!50001 DROP VIEW IF EXISTS `v_empresa`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_empresa` AS select `e`.`logo` AS `logo`,`e`.`id` AS `id`,`e`.`registro` AS `registro`,`e`.`gerente_id` AS `gerente_id`,`e`.`alta` AS `alta`,`t`.`Nombre` AS `Nombre`,`t`.`Apellidos` AS `Apellidos`,`p`.`Proveedor` AS `Proveedor`,`p`.`Domicilio` AS `Domicilio`,`p`.`CP` AS `CP`,`p`.`Localidad` AS `Localidad`,`p`.`NIF` AS `NIF`,`p`.`Telefono` AS `Telefono`,`p`.`Alias` AS `Alias`,`e`.`abbreviation` AS `abbreviation` from ((`empresa` `e` join `Trabajadores` `t` on((`t`.`Id_Trabajador` = `e`.`gerente_id`))) join `Proveedores` `p` on((`p`.`Id_Proveedor` = `e`.`id`))) */; -/*!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 `v_encajado` --- - -/*!50001 DROP VIEW IF EXISTS `v_encajado`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_encajado` AS select hour(`e`.`odbc_date`) AS `hora`,minute(`e`.`odbc_date`) AS `minuto`,ifnull(`c`.`Volumen`,94500) AS `cm3`,`t`.`warehouse_id` AS `warehouse_id` from ((`expeditions` `e` left join `Cubos` `c` on((`c`.`item_id` = `e`.`EsBulto`))) join `Tickets` `t` on((`t`.`Id_Ticket` = `e`.`ticket_id`))) where (`e`.`odbc_date` between curdate() and `DAYEND`(curdate())) */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `v_encajado_ultima_hora` --- - -/*!50001 DROP VIEW IF EXISTS `v_encajado_ultima_hora`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_encajado_ultima_hora` AS select sum((ifnull(`c`.`Volumen`,94500) / 1000000)) AS `m3`,`t`.`warehouse_id` AS `warehouse_id` from ((`expeditions` `e` left join `Cubos` `c` on((`c`.`item_id` = `e`.`EsBulto`))) join `Tickets` `t` on((`t`.`Id_Ticket` = `e`.`ticket_id`))) where ((`e`.`odbc_date` > (now() + interval -(1) hour)) and (`t`.`warehouse_id` in (1,44))) group by `t`.`warehouse_id` */; -/*!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 `v_expeditions_shipping_charge` --- - -/*!50001 DROP VIEW IF EXISTS `v_expeditions_shipping_charge`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_expeditions_shipping_charge` AS select `t`.`Id_Ticket` AS `Id_Ticket`,sum((`az`.`price` * if(((`e`.`EsBulto` = 71) and isnull(`e`.`Id_Article`) and (`a`.`Vista` = 2)),0.75,1))) AS `shipping_charge`,`t`.`Fecha` AS `Fecha` from ((((((`Tickets` `t` join `Clientes` `cli` on((`cli`.`id_cliente` = `t`.`Id_Cliente`))) left join `expeditions` `e` on((`e`.`ticket_id` = `t`.`Id_Ticket`))) join `Consignatarios` `c` on((`c`.`id_consigna` = `t`.`Id_Consigna`))) join `Agencias` `a` on((`a`.`Id_Agencia` = `t`.`Id_Agencia`))) join `Agencias_province` `ap` on(((`t`.`warehouse_id` = `ap`.`warehouse_id`) and (`ap`.`province_id` = `c`.`province_id`) and (`ap`.`agency_id` = `a`.`agency_id`)))) join `Agencias_zonas` `az` on(((`az`.`Id_Agencia` = `t`.`Id_Agencia`) and (`az`.`zona` = `ap`.`zona`) and (`t`.`warehouse_id` = `az`.`warehouse_id`) and (`az`.`Id_Article` = `e`.`EsBulto`)))) where ((`t`.`Fecha` >= '2015-10-01') and (`cli`.`real` <> 0) and (`t`.`empresa_id` in (442,791,567))) group by `t`.`Id_Ticket` */; -/*!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 `v_expeditions_shipping_charge2` --- - -/*!50001 DROP VIEW IF EXISTS `v_expeditions_shipping_charge2`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_expeditions_shipping_charge2` AS select `t`.`Id_Ticket` AS `Id_Ticket`,(`az`.`price` * if(((`e`.`EsBulto` = 71) and isnull(`e`.`Id_Article`) and (`a`.`Vista` = 2)),0.75,1)) AS `shipping_charge`,`t`.`Fecha` AS `Fecha`,`t`.`warehouse_id` AS `warehouse_id` from (((((`Tickets` `t` left join `expeditions` `e` on((`e`.`ticket_id` = `t`.`Id_Ticket`))) join `Consignatarios` `c` on((`c`.`id_consigna` = `t`.`Id_Consigna`))) join `Agencias` `a` on((`a`.`Id_Agencia` = `t`.`Id_Agencia`))) join `Agencias_province` `ap` on(((`t`.`warehouse_id` = `ap`.`warehouse_id`) and (`ap`.`province_id` = `c`.`province_id`) and (`ap`.`agency_id` = `a`.`agency_id`)))) join `Agencias_zonas` `az` on(((`az`.`Id_Agencia` = `t`.`Id_Agencia`) and (`az`.`zona` = `ap`.`zona`) and (`t`.`warehouse_id` = `az`.`warehouse_id`) and (`az`.`Id_Article` = `e`.`EsBulto`)))) where ((`t`.`Fecha` >= '2016-01-01') and (`t`.`empresa_id` in (442,567))) */; -/*!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 `v_fallo` --- - -/*!50001 DROP VIEW IF EXISTS `v_fallo`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_fallo` AS select `vncontrol`.`fallo`.`queja_id` AS `queja_id`,`vncontrol`.`fallo`.`accion_id` AS `accion_id` from `vncontrol`.`fallo` */; -/*!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 `v_inter` --- - -/*!50001 DROP VIEW IF EXISTS `v_inter`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_inter` AS select `vncontrol`.`inter`.`inter_id` AS `inter_id`,`vncontrol`.`inter`.`state_id` AS `state_id`,`vncontrol`.`inter`.`nota` AS `nota`,`vncontrol`.`inter`.`odbc_date` AS `odbc_date`,`vncontrol`.`inter`.`Id_Ticket` AS `Id_Ticket`,`vncontrol`.`inter`.`Id_Trabajador` AS `Id_Trabajador`,`vncontrol`.`inter`.`Id_Supervisor` AS `Id_supervisor` from `vncontrol`.`inter` */; -/*!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 `v_jerarquia` --- - -/*!50001 DROP VIEW IF EXISTS `v_jerarquia`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_jerarquia` AS select `jerarquia`.`worker_id` AS `Id_Trabajador`,`jerarquia`.`boss_id` AS `boss_id` from `jerarquia` union all select distinct `jerarquia`.`boss_id` AS `Id_Trabajador`,`jerarquia`.`boss_id` AS `boss_id` from `jerarquia` */; -/*!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 `v_location` --- - -/*!50001 DROP VIEW IF EXISTS `v_location`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_location` AS select `tl`.`longitude` AS `longitude`,`tl`.`latitude` AS `latitude`,`t`.`Id_Consigna` AS `Id_Consigna` from (`ticket_location` `tl` join `Tickets` `t` on((`t`.`Id_Ticket` = `tl`.`Id_Ticket`))) where (`t`.`Fecha` >= (curdate() + interval -(3) month)) group by `t`.`Id_Consigna` order by `t`.`Id_Ticket` desc */; -/*!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 `v_mana_spellers` --- - -/*!50001 DROP VIEW IF EXISTS `v_mana_spellers`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_mana_spellers` AS select `bs`.`mana_spellers`.`Id_Trabajador` AS `Id_Trabajador`,`bs`.`mana_spellers`.`size` AS `size`,`bs`.`mana_spellers`.`used` AS `used` from `bs`.`mana_spellers` */; -/*!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 `v_miriam` --- - -/*!50001 DROP VIEW IF EXISTS `v_miriam`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_miriam` AS select `M`.`Id_Article` AS `Id_Article`,`M`.`Concepte` AS `Concepte`,`M`.`Cantidad` AS `Cantidad`,`M`.`Preu` AS `Preu`,`M`.`Descuento` AS `Descuento`,`T`.`Fecha` AS `Fecha`,`T`.`Id_Cliente` AS `Id_Cliente`,(((`M`.`Cantidad` * `M`.`Preu`) * (100 - `M`.`Descuento`)) / 100) AS `Importe` from (((`Tickets` `T` join `Movimientos` `M` on((`T`.`Id_Ticket` = `M`.`Id_Ticket`))) join `Articles` `A` on((`M`.`Id_Article` = `A`.`Id_Article`))) join `Tipos` `TP` on((`A`.`tipo_id` = `TP`.`tipo_id`))) where ((`T`.`Fecha` >= '2011-01-01') and (`A`.`tipo_id` = 7)) */; -/*!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 `v_movimientos_log` --- - -/*!50001 DROP VIEW IF EXISTS `v_movimientos_log`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_movimientos_log` AS select `bi`.`movimientos_log`.`idmovimientos_log` AS `idmovimientos_log`,`bi`.`movimientos_log`.`Id_Movimiento` AS `Id_Movimiento`,`bi`.`movimientos_log`.`odbc_date` AS `odbc_date`,`bi`.`movimientos_log`.`Id_Trabajador` AS `Id_Trabajador`,`bi`.`movimientos_log`.`field_name` AS `field_name`,`bi`.`movimientos_log`.`new_value` AS `new_value` from `bi`.`movimientos_log` */; -/*!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 `v_movimientos_mark` --- - -/*!50001 DROP VIEW IF EXISTS `v_movimientos_mark`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_movimientos_mark` AS select `Movimientos_mark`.`Id_Movimiento` AS `Id_Movimiento`,max(`Movimientos_mark`.`Id_Accion`) AS `Accion` from `Movimientos_mark` group by `Movimientos_mark`.`Id_Movimiento` having ((max(`Movimientos_mark`.`Id_Accion`) = '6') or (max(`Movimientos_mark`.`Id_Accion`) = '7')) */; -/*!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 `v_pedidos_auto_preparados` --- - -/*!50001 DROP VIEW IF EXISTS `v_pedidos_auto_preparados`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_pedidos_auto_preparados` AS select `t`.`CodigoTrabajador` AS `CodigoTrabajador`,`i`.`Id_Ticket` AS `Id_Ticket`,`i`.`odbc_date` AS `Momento` from ((`vn2008`.`v_jerarquia` `j` left join `vn2008`.`v_inter` `i` on((`j`.`Id_Trabajador` = `i`.`Id_Trabajador`))) join `vn2008`.`Trabajadores` `t` on((`t`.`Id_Trabajador` = `j`.`Id_Trabajador`))) where (`i`.`state_id` = 20) */; -/*!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 `v_pedidos_auto_preparadoskk` --- - -/*!50001 DROP VIEW IF EXISTS `v_pedidos_auto_preparadoskk`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_pedidos_auto_preparadoskk` AS select `t`.`CodigoTrabajador` AS `CodigoTrabajador`,`TK`.`Fecha` AS `Fecha`,`TK`.`Id_Ticket` AS `Id_Ticket`,`i`.`odbc_date` AS `Momento` from (((`vn2008`.`v_jerarquia` `j` left join `vn2008`.`v_inter` `i` on((`j`.`Id_Trabajador` = `i`.`Id_Trabajador`))) join `vn2008`.`Trabajadores` `t` on((`t`.`Id_Trabajador` = `j`.`Id_Trabajador`))) left join `vn2008`.`Tickets` `TK` on((`TK`.`Id_Ticket` = `i`.`Id_Ticket`))) where (`i`.`state_id` = 5) */; -/*!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 `v_phonebook` --- - -/*!50001 DROP VIEW IF EXISTS `v_phonebook`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_phonebook` AS select `Clientes`.`id_cliente` AS `Id_Cliente`,replace(`Clientes`.`telefono`,' ','') AS `Telefono` from `Clientes` where (`Clientes`.`telefono` and `Clientes`.`activo`) union select `Clientes`.`id_cliente` AS `Id_Cliente`,replace(`Clientes`.`movil`,' ','') AS `Movil` from `Clientes` where (`Clientes`.`movil` and `Clientes`.`activo`) union select `Consignatarios`.`Id_cliente` AS `Id_Cliente`,replace(`Consignatarios`.`telefono`,' ','') AS `TRIM(telefono)` from (`Consignatarios` join `Clientes` `c` on((`Consignatarios`.`Id_cliente` = `c`.`id_cliente`))) where (`Consignatarios`.`telefono` and `c`.`activo`) union select `Consignatarios`.`Id_cliente` AS `Id_Cliente`,replace(`Consignatarios`.`movil`,' ','') AS `TRIM(movil)` from (`Consignatarios` join `Clientes` `c` on((`Consignatarios`.`Id_cliente` = `c`.`id_cliente`))) where (`Consignatarios`.`movil` and `c`.`activo`) union select `r`.`Id_Cliente` AS `Id_Cliente`,replace(`c`.`Telefono`,' ','') AS `REPLACE(c.telefono,' ','')` from ((`Clientes` `cl` join `Relaciones` `r` on((`cl`.`id_cliente` = `r`.`Id_Cliente`))) join `Contactos` `c` on((`r`.`Id_Contacto` = `c`.`Id_Contacto`))) where (`cl`.`telefono` and `cl`.`activo`) union select `r`.`Id_Cliente` AS `Id_Cliente`,replace(`c`.`Movil`,' ','') AS `REPLACE(c.Movil,' ','')` from ((`Clientes` `cl` join `Relaciones` `r` on((`cl`.`id_cliente` = `r`.`Id_Cliente`))) join `Contactos` `c` on((`r`.`Id_Contacto` = `c`.`Id_Contacto`))) where (`cl`.`movil` and `cl`.`activo`) */; -/*!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 `v_price_fixed` --- - -/*!50001 DROP VIEW IF EXISTS `v_price_fixed`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_price_fixed` AS select `pf`.`warehouse_id` AS `warehouse_id`,`pf`.`item_id` AS `item_id`,`pf`.`rate_0` AS `rate_0`,`pf`.`rate_1` AS `rate_1`,`pf`.`rate_2` AS `rate_2`,`pf`.`rate_3` AS `rate_3`,`pf`.`date_start` AS `date_start`,`pf`.`date_end` AS `date_end`,`pf`.`bonus` AS `bonus`,`pf`.`grouping` AS `grouping`,`pf`.`Packing` AS `Packing`,`pf`.`caja` AS `caja` from `price_fixed` `pf` where (`pf`.`warehouse_id` < 1000) union all select `wg`.`warehouse_id` AS `warehouse_id`,`pf`.`item_id` AS `item_id`,`pf`.`rate_0` AS `rate_0`,`pf`.`rate_1` AS `rate_1`,`pf`.`rate_2` AS `rate_2`,`pf`.`rate_3` AS `rate_3`,`pf`.`date_start` AS `date_start`,`pf`.`date_end` AS `date_end`,`pf`.`bonus` AS `bonus`,`pf`.`grouping` AS `grouping`,`pf`.`Packing` AS `Packing`,`pf`.`caja` AS `caja` from (`price_fixed` `pf` join `warehouse_group` `wg`) where ((`wg`.`warehouse_alias_id` + 1000) = `pf`.`warehouse_id`) */; -/*!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 `v_price_fixed_group` --- - -/*!50001 DROP VIEW IF EXISTS `v_price_fixed_group`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_price_fixed_group` AS select `pf`.`warehouse_id` AS `warehouse_id`,`pf`.`item_id` AS `item_id`,`pf`.`rate_0` AS `rate_0`,`pf`.`rate_1` AS `rate_1`,`pf`.`rate_2` AS `rate_2`,`pf`.`rate_3` AS `rate_3`,`pf`.`date_start` AS `date_start`,`pf`.`date_end` AS `date_end`,`pf`.`bonus` AS `bonus`,`pf`.`grouping` AS `grouping`,`pf`.`Packing` AS `Packing`,`pf`.`caja` AS `caja` from `v_price_fixed` `pf` group by `pf`.`warehouse_id`,`pf`.`item_id`,`pf`.`date_start`,`pf`.`date_end` */; -/*!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 `v_session` --- - -/*!50001 DROP VIEW IF EXISTS `v_session`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_session` AS select 1 AS `id`,`t`.`CodigoTrabajador` AS `CodigoTrabajador`,if(isnull(`sc`.`Id_Suplente`),`c`.`Id_Trabajador`,`sc`.`Id_Suplente`) AS `Id_Trabajador`,`c`.`id_cliente` AS `Id_Cliente`,`c`.`cliente` AS `Cliente`,`s`.`lastUpdate` AS `Fecha` from ((((`hedera`.`userSession` `s` join `hedera`.`visitUser` `v` on((`v`.`id` = `s`.`userVisit`))) join `vn2008`.`Clientes` `c` on((`c`.`id_cliente` = `v`.`user`))) left join `vn2008`.`Trabajadores` `t` on((`c`.`Id_Trabajador` = `t`.`Id_Trabajador`))) left join `vn2008`.`sharingcart` `sc` on(((`sc`.`Id_Trabajador` = `c`.`Id_Trabajador`) and (curdate() between `sc`.`datSTART` and `sc`.`datEND`)))) */; -/*!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 `v_ticket_amount` --- - -/*!50001 DROP VIEW IF EXISTS `v_ticket_amount`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_ticket_amount` AS select `Movimientos`.`Id_Ticket` AS `Id_Ticket`,sum((((`Movimientos`.`Cantidad` * `Movimientos`.`Preu`) * (100 - `Movimientos`.`Descuento`)) / 100)) AS `amount` from (`Movimientos` join `Tickets` on((`Movimientos`.`Id_Ticket` = `Tickets`.`Id_Ticket`))) where (`Tickets`.`Fecha` >= (curdate() + interval -(6) month)) group by `Movimientos`.`Id_Ticket` */; -/*!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 `v_trabajadores` --- - -/*!50001 DROP VIEW IF EXISTS `v_trabajadores`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_trabajadores` AS select `t`.`CodigoTrabajador` AS `CodigoTrabajador`,`t`.`Nombre` AS `Nombre`,`t`.`Fecha_Inicio` AS `Fecha_Inicio`,`t`.`Password` AS `Password`,`t`.`user` AS `user`,`t`.`Apellidos` AS `Apellidos`,`t`.`Id_Trabajador` AS `Id_Trabajador`,`t`.`Foto` AS `Foto` from `vn2008`.`Trabajadores` `t` where (`t`.`Id_Cliente_Interno` = `account`.`userGetId`()) */; -/*!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 `v_user` --- - -/*!50001 DROP VIEW IF EXISTS `v_user`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_user` AS select `u`.`id` AS `id`,`u`.`role` AS `mysql_user_id`,`u`.`name` AS `name`,`u`.`password` AS `password`,`u`.`active` AS `active` from `account`.`user` `u` */; -/*!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 `v_ventes` --- - -/*!50001 DROP VIEW IF EXISTS `v_ventes`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_ventes` AS select `Agencias`.`Agencia` AS `Agencia`,`A`.`Categoria` AS `Categoria`,`A`.`tipo_id` AS `tipo_id`,`A`.`Medida` AS `Medida`,`A`.`Article` AS `Article`,`A`.`Color` AS `Color`,`CS`.`Id_cliente` AS `Id_Cliente`,`TP`.`Id_Tipo` AS `Tipo`,`T`.`Factura` AS `Factura`,`T`.`warehouse_id` AS `warehouse_id`,`M`.`Id_Movimiento` AS `Id_Movimiento`,`M`.`Id_Article` AS `Id_Article`,`TP`.`Id_Tipo` AS `Familia`,`M`.`Id_Ticket` AS `Id_Ticket`,`M`.`Concepte` AS `Concepte`,`M`.`Cantidad` AS `Cantidad`,`M`.`quantity` AS `quantity`,`M`.`Preu` AS `Preu`,`M`.`Descuento` AS `Descuento`,if((`T`.`Fecha` >= '2015-10-01'),`M`.`CostFixat`,((`M`.`Preu` * (100 - `M`.`Descuento`)) / 100)) AS `CostFixat`,`M`.`Reservado` AS `Reservado`,`M`.`OK` AS `OK`,`M`.`PrecioFijado` AS `PrecioFijado`,`M`.`odbc_date` AS `odbc_date`,cast(`T`.`Fecha` as date) AS `Fecha`,`T`.`Fecha` AS `FechaCompleta`,`CS`.`consignatario` AS `Alias`,`T`.`Id_Consigna` AS `Id_Consigna`,(((`M`.`Cantidad` * `M`.`Preu`) * (100 - `M`.`Descuento`)) / 100) AS `Importe`,`O`.`Origen` AS `Origen`,`TP`.`reino_id` AS `reino_id`,`C`.`invoice` AS `invoice`,`A`.`producer_id` AS `producer_id` from ((((((((`Movimientos` `M` join `Tickets` `T` on((`M`.`Id_Ticket` = `T`.`Id_Ticket`))) join `Consignatarios` `CS` on((`CS`.`id_consigna` = `T`.`Id_Consigna`))) join `Clientes` `C` on((`CS`.`Id_cliente` = `C`.`id_cliente`))) join `Articles` `A` on((`M`.`Id_Article` = `A`.`Id_Article`))) join `Origen` `O` on((`O`.`id` = `A`.`id_origen`))) join `Tipos` `TP` on((`A`.`tipo_id` = `TP`.`tipo_id`))) join `reinos` `r` on((`TP`.`reino_id` = `r`.`id`))) join `Agencias` on((`Agencias`.`Id_Agencia` = `T`.`Id_Agencia`))) where ((`T`.`Fecha` >= '2013-01-01') and (`C`.`real` > 0) and (`r`.`id` <> 6)) */; -/*!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 `v_venteskk` --- - -/*!50001 DROP VIEW IF EXISTS `v_venteskk`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_venteskk` AS select `Agencias`.`Agencia` AS `Agencia`,`A`.`Categoria` AS `Categoria`,`A`.`tipo_id` AS `tipo_id`,`A`.`Medida` AS `Medida`,`A`.`Article` AS `Article`,`A`.`Color` AS `Color`,`CS`.`Id_cliente` AS `Id_Cliente`,`TP`.`Id_Tipo` AS `Tipo`,`T`.`Factura` AS `Factura`,`T`.`warehouse_id` AS `warehouse_id`,`M`.`Id_Movimiento` AS `Id_Movimiento`,`M`.`Id_Article` AS `Id_Article`,`TP`.`Id_Tipo` AS `Familia`,`M`.`Id_Ticket` AS `Id_Ticket`,`M`.`Concepte` AS `Concepte`,`M`.`Cantidad` AS `Cantidad`,`M`.`quantity` AS `quantity`,`M`.`Preu` AS `Preu`,`M`.`Descuento` AS `Descuento`,if((`T`.`Fecha` >= '2015-10-01'),`M`.`CostFixat`,((`M`.`Preu` * (100 - `M`.`Descuento`)) / 100)) AS `CostFixat`,`M`.`Reservado` AS `Reservado`,`M`.`OK` AS `OK`,`M`.`PrecioFijado` AS `PrecioFijado`,`M`.`odbc_date` AS `odbc_date`,cast(`T`.`Fecha` as date) AS `Fecha`,`T`.`Fecha` AS `FechaCompleta`,`CS`.`consignatario` AS `Alias`,`T`.`Id_Consigna` AS `Id_Consigna`,(((`M`.`Cantidad` * `M`.`Preu`) * (100 - `M`.`Descuento`)) / 100) AS `Importe`,`O`.`Origen` AS `Origen`,`TP`.`reino_id` AS `reino_id`,`C`.`invoice` AS `invoice`,`A`.`producer_id` AS `producer_id` from ((((((((`Movimientos` `M` join `Tickets` `T` on((`M`.`Id_Ticket` = `T`.`Id_Ticket`))) join `Consignatarios` `CS` on((`CS`.`id_consigna` = `T`.`Id_Consigna`))) join `Clientes` `C` on((`CS`.`Id_cliente` = `C`.`id_cliente`))) join `Articles` `A` on((`M`.`Id_Article` = `A`.`Id_Article`))) join `Origen` `O` on((`O`.`id` = `A`.`id_origen`))) join `Tipos` `TP` on((`A`.`tipo_id` = `TP`.`tipo_id`))) join `reinos` `r` on((`TP`.`reino_id` = `r`.`id`))) join `Agencias` on((`Agencias`.`Id_Agencia` = `T`.`Id_Agencia`))) where ((`T`.`Fecha` >= '2013-01-01') and (`C`.`real` > 0) and (`r`.`id` <> 6)) */; -/*!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 `v_warehouse` --- - -/*!50001 DROP VIEW IF EXISTS `v_warehouse`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_warehouse` AS select `warehouse`.`id` AS `id`,`warehouse`.`name` AS `almacen` from `warehouse` union all select (1000 + `warehouse_alias`.`warehouse_alias_id`) AS `warehouse_alias_id`,concat(`warehouse_alias`.`alias`,'(G)') AS `concat(alias, '(G)')` from `warehouse_alias` */; -/*!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 `v_xsubclien` --- - -/*!50001 DROP VIEW IF EXISTS `v_xsubclien`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_xsubclien` AS select distinct `Facturas`.`Id_Cliente` AS `Id_Cliente`,`Facturas`.`empresa_id` AS `empresa_id` from `Facturas` where (`Facturas`.`Fecha` > (curdate() + interval -(2) month)) union select `Recibos`.`Id_Cliente` AS `Id_Cliente`,`Recibos`.`empresa_id` AS `empresa_id` from `Recibos` where (`Recibos`.`Fechacobro` > (curdate() + interval -(2) month)) */; -/*!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 `v_xsubcuentas` --- - -/*!50001 DROP VIEW IF EXISTS `v_xsubcuentas`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_xsubcuentas` AS select `Clientes`.`Cuenta` AS `COD`,`Clientes`.`razonSocial` AS `TITULO`,concat(if((`p`.`CEE` = 1),`p`.`Codigo`,''),`Clientes`.`if`) AS `NIF`,`Clientes`.`domicilio` AS `DOMICILIO`,`Clientes`.`poblacion` AS `POBLACION`,`province`.`name` AS `PROVINCIA`,`Clientes`.`codPostal` AS `CODPOSTAL`,`p`.`Codigo` AS `country_code`,`v_xsubclien`.`empresa_id` AS `empresa_id`,substr(`Clientes`.`e-mail`,1,(coalesce(nullif(locate(',',`Clientes`.`e-mail`),0),99) - 1)) AS `EMAIL`,if((`p`.`CEE` = 0),1,if((`p`.`CEE` = 1),2,4)) AS `IDNIF` from (((`Clientes` join `v_xsubclien` on((`Clientes`.`id_cliente` = `v_xsubclien`.`Id_Cliente`))) left join `Paises` `p` on((`p`.`Id` = `Clientes`.`Id_Pais`))) join `province` on((`Clientes`.`province_id` = `province`.`province_id`))) where (`Clientes`.`oficial` <> 0) group by `Clientes`.`id_cliente`,`v_xsubclien`.`empresa_id` union all select `Proveedores`.`cuenta` AS `Cuenta`,`Proveedores`.`Proveedor` AS `Proveedor`,concat(if((`p`.`CEE` = 1),`p`.`Codigo`,''),`Proveedores`.`NIF`) AS `NIF`,`Proveedores`.`Domicilio` AS `Domicilio`,`Proveedores`.`Localidad` AS `Localidad`,`prov`.`name` AS `Provincia`,`Proveedores`.`CP` AS `CP`,`p`.`Codigo` AS `country_code`,`v_xsubprov`.`empresa_id` AS `empresa_id`,substr(`c`.`email`,1,(coalesce(nullif(locate(',',`c`.`email`),0),99) - 1)) AS `EMAIL`,if((`p`.`CEE` = 0),1,if((`p`.`CEE` = 1),2,4)) AS `IDNIF` from (((((`Proveedores` join `v_xsubprov` on((`Proveedores`.`Id_Proveedor` = `v_xsubprov`.`proveedor_id`))) left join `Paises` `p` on((`p`.`Id` = `Proveedores`.`pais_id`))) left join `province` `prov` on((`prov`.`province_id` = `Proveedores`.`province_id`))) left join `Relaciones` `r` on((`r`.`Id_Proveedor` = `Proveedores`.`Id_Proveedor`))) left join `Contactos` `c` on((`c`.`Id_Contacto` = `r`.`Id_Contacto`))) where (`Proveedores`.`oficial` <> 0) group by `v_xsubprov`.`proveedor_id`,`v_xsubprov`.`empresa_id` union all select `Gastos`.`Id_Gasto` AS `Id_Gasto`,`Gastos`.`Gasto` AS `Gasto`,NULL AS `NULL`,NULL AS `My_exp_NULL`,NULL AS `My_exp_1_NULL`,NULL AS `My_exp_2_NULL`,NULL AS `My_exp_3_NULL`,NULL AS `country_code`,`e`.`id` AS `id`,NULL AS `EMAIL`,1 AS `IDNIF` from (`Gastos` join `empresa` `e` on((`e`.`id` = 442))) union all select `Bancos`.`Cuenta` AS `Cuenta`,`Bancos`.`Banco` AS `Banco`,NULL AS `NULL`,NULL AS `My_exp_NULL`,NULL AS `My_exp_1_NULL`,NULL AS `My_exp_2_NULL`,NULL AS `My_exp_3_NULL`,NULL AS `country_code`,`e`.`id` AS `id`,NULL AS `EMAIL`,1 AS `IDNIF` from (`Bancos` join `empresa` `e` on((`e`.`id` = 442))) union all select lpad(right(`Proveedores`.`cuenta`,5),10,'47510000') AS `Cuenta`,`Proveedores`.`Proveedor` AS `Proveedor`,`Proveedores`.`NIF` AS `NIF`,`Proveedores`.`Domicilio` AS `Domicilio`,`Proveedores`.`Localidad` AS `Localidad`,`prov`.`name` AS `Provincia`,`Proveedores`.`CP` AS `CP`,`p`.`Codigo` AS `country_code`,`v_xsubprov`.`empresa_id` AS `empresa_id`,substr(`c`.`email`,1,(coalesce(nullif(locate(',',`c`.`email`),0),99) - 1)) AS `EMAIL`,if((`p`.`CEE` = 0),1,if((`p`.`CEE` = 1),2,4)) AS `IDNIF` from (((((`Proveedores` join `v_xsubprov` on((`Proveedores`.`Id_Proveedor` = `v_xsubprov`.`proveedor_id`))) left join `Paises` `p` on((`p`.`Id` = `Proveedores`.`pais_id`))) left join `province` `prov` on((`prov`.`province_id` = `Proveedores`.`province_id`))) left join `Relaciones` `r` on((`r`.`Id_Proveedor` = `Proveedores`.`Id_Proveedor`))) left join `Contactos` `c` on((`c`.`Id_Contacto` = `r`.`Id_Contacto`))) where (((`Proveedores`.`cuenta` like '_____3____') or (`Proveedores`.`cuenta` like '_____2____')) and (`Proveedores`.`oficial` = 1)) group by `v_xsubprov`.`proveedor_id`,`v_xsubprov`.`empresa_id` */; -/*!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 `v_xsubprov` --- - -/*!50001 DROP VIEW IF EXISTS `v_xsubprov`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_xsubprov` AS select `recibida`.`proveedor_id` AS `proveedor_id`,`recibida`.`empresa_id` AS `empresa_id` from `recibida` where (`recibida`.`fecha` > (curdate() + interval -(3) month)) group by `recibida`.`proveedor_id`,`recibida`.`empresa_id` union all select `pago`.`id_proveedor` AS `id_proveedor`,`pago`.`empresa_id` AS `empresa_id` from `pago` where (`pago`.`fecha` > (curdate() + interval -(3) month)) group by `pago`.`id_proveedor`,`pago`.`empresa_id` */; -/*!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 `vnCreditClassification` --- - -/*!50001 DROP VIEW IF EXISTS `vnCreditClassification`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `vnCreditClassification` AS select `vn`.`creditClassification`.`id` AS `id`,`vn`.`creditClassification`.`client` AS `client`,`vn`.`creditClassification`.`dateStart` AS `dateStart`,`vn`.`creditClassification`.`dateEnd` AS `dateEnd` from `vn`.`creditClassification` */; -/*!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 `vnCreditInsurance` --- - -/*!50001 DROP VIEW IF EXISTS `vnCreditInsurance`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `vnCreditInsurance` AS select `vn`.`creditInsurance`.`id` AS `id`,`vn`.`creditInsurance`.`creditClassification` AS `creditClassification`,`vn`.`creditInsurance`.`credit` AS `credit`,`vn`.`creditInsurance`.`creationDate` AS `creationDate`,`vn`.`creditInsurance`.`grade` AS `grade` from `vn`.`creditInsurance` */; -/*!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 `vnSolunionCAP` --- - -/*!50001 DROP VIEW IF EXISTS `vnSolunionCAP`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `vnSolunionCAP` AS select `vn`.`solunionCAP`.`creditInsurance` AS `creditInsurance`,`vn`.`solunionCAP`.`dateStart` AS `dateStart`,`vn`.`solunionCAP`.`dateEnd` AS `dateEnd`,`vn`.`solunionCAP`.`dateLeaving` AS `dateLeaving` from `vn`.`solunionCAP` */; -/*!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 `workerDocument` --- - -/*!50001 DROP VIEW IF EXISTS `workerDocument`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `workerDocument` AS select `vn`.`workerDocument`.`id` AS `id`,`vn`.`workerDocument`.`worker` AS `worker`,`vn`.`workerDocument`.`document` AS `document` from `vn`.`workerDocument` */; -/*!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 `workerTeamCollegues` --- - -/*!50001 DROP VIEW IF EXISTS `workerTeamCollegues`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `workerTeamCollegues` AS select distinct `w`.`Id_Trabajador` AS `workerId`,`t`.`Id_Trabajador` AS `collegueId` from (`vn`.`workerTeam` `w` join `vn`.`workerTeam` `t` on((`w`.`team` = `t`.`team`))) */; -/*!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 `workerTeam_kk` --- - -/*!50001 DROP VIEW IF EXISTS `workerTeam_kk`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `workerTeam_kk` AS select `w`.`team` AS `team`,`w`.`user` AS `user`,`w`.`id` AS `id`,`t`.`Id_Trabajador` AS `Id_Trabajador` from (`vn`.`workerTeam` `w` left join `vn2008`.`Trabajadores` `t` on((`t`.`user_id` = `w`.`user`))) */; -/*!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 `zoneNickname` --- - -/*!50001 DROP VIEW IF EXISTS `zoneNickname`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `zoneNickname` AS select `ap`.`warehouse_id` AS `warehouse_id`,`ap`.`agency_id` AS `agency_id`,`ap`.`zona` AS `zona`,concat('ZONA ',`ap`.`zona`,' ',if((`ap`.`zona` = 20),'Madrid',`p`.`name`)) AS `alias` from (`Agencias_province` `ap` join `province` `p` on((`p`.`province_id` = `ap`.`province_id`))) group by `ap`.`zona`,`ap`.`warehouse_id`,`ap`.`agency_id` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Current Database: `vn` --- - -USE `vn`; - --- --- Final view structure for view `accounting` --- - -/*!50001 DROP VIEW IF EXISTS `accounting`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `accounting` AS select `b`.`Id_Banco` AS `id`,`b`.`Banco` AS `bank`,`b`.`Cuenta` AS `account`,`b`.`cash` AS `accountingTypeFk`,`b`.`entity_id` AS `entityFk`,`b`.`activo` AS `isActive` from `vn2008`.`Bancos` `b` */; -/*!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 `address` --- - -/*!50001 DROP VIEW IF EXISTS `address`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `address` AS select `t`.`id_consigna` AS `id`,`t`.`Id_cliente` AS `clientFk`,`t`.`domicilio` AS `street`,`t`.`poblacion` AS `city`,`t`.`codPostal` AS `postalCode`,`t`.`province_id` AS `provinceFk`,`t`.`telefono` AS `phone`,`t`.`movil` AS `mobile`,`t`.`consignatario` AS `nickname`,`t`.`predeterminada` AS `isDefaultAddress`,`t`.`longitude` AS `longitude`,`t`.`latitude` AS `latitude`,`t`.`warehouse_id` AS `warehouseFk`,`t`.`Id_Agencia` AS `agencyModeFk`,`t`.`isEqualizated` AS `isEqualizated`,`t`.`active` AS `isActive` from `vn2008`.`Consignatarios` `t` */; -/*!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 `addressObservation` --- - -/*!50001 DROP VIEW IF EXISTS `addressObservation`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `addressObservation` AS select `co`.`consignatarios_observation_id` AS `id`,`co`.`Id_Consigna` AS `addressFk`,`co`.`observation_type_id` AS `observationTypeFk`,`co`.`text` AS `description` from `vn2008`.`consignatarios_observation` `co` */; -/*!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 `agency` --- - -/*!50001 DROP VIEW IF EXISTS `agency`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `agency` AS select `a`.`agency_id` AS `id`,`a`.`name` AS `name`,`a`.`warehouse_id` AS `warehouseFk`,`a`.`por_volumen` AS `isVolumetric`,`a`.`Id_Banco` AS `bankFk`,`a`.`warehouse_alias_id` AS `warehouseAliasFk`,`a`.`propios` AS `own`,`a`.`zone_label` AS `labelZone` from `vn2008`.`agency` `a` */; -/*!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 `agencyHour` --- - -/*!50001 DROP VIEW IF EXISTS `agencyHour`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `agencyHour` AS select `h`.`agency_hour_id` AS `id`,`h`.`agency_id` AS `agencyFk`,`h`.`week_day` AS `weekDay`,`h`.`warehouse_id` AS `warehouseFk`,`h`.`province_id` AS `provinceFk`,`h`.`subtract_day` AS `substractDay`,`h`.`max_hour` AS `maxHour` from `vn2008`.`agency_hour` `h` */; -/*!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 `agencyMode` --- - -/*!50001 DROP VIEW IF EXISTS `agencyMode`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `agencyMode` AS select `a`.`Id_Agencia` AS `id`,`a`.`Agencia` AS `name`,`a`.`description` AS `description`,`a`.`Vista` AS `deliveryMethodFk`,`a`.`m3` AS `m3`,`a`.`cod71` AS `cod71`,`a`.`web` AS `web`,`a`.`agency_id` AS `agencyFk`,`a`.`agency_service_id` AS `agencyServiceFk`,`a`.`inflacion` AS `inflation`,`a`.`is_volumetric` AS `isVolumetric`,`a`.`send_mail` AS `reportMail` from `vn2008`.`Agencias` `a` */; -/*!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 `agencyWarehouse` --- - -/*!50001 DROP VIEW IF EXISTS `agencyWarehouse`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `agencyWarehouse` AS select `a`.`agency_id` AS `agencyFk`,`a`.`warehouse_id` AS `warehouseFk`,`a`.`Vista` AS `agencyType` from `vn2008`.`agency_warehouse` `a` */; -/*!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 `awb` --- - -/*!50001 DROP VIEW IF EXISTS `awb`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `awb` AS select `a`.`id` AS `id`,`a`.`codigo` AS `code`,`a`.`bultos` AS `package`,`a`.`peso` AS `weight`,`a`.`MYSQL_TIME` AS `created`,`a`.`transitario_id` AS `transitoryFk`,`a`.`iva_id` AS `taxFk`,`a`.`gestdoc_id` AS `docFk`,`a`.`importe` AS `amount`,`a`.`carguera_id` AS `freightFk`,`a`.`m3` AS `m3`,`a`.`stems` AS `stems`,`a`.`flight_id` AS `flightFk`,`a`.`volume_weight` AS `volumeWeight`,`a`.`hb` AS `hb`,`a`.`rate` AS `rate`,`a`.`booked` AS `booked`,`a`.`issued` AS `issued`,`a`.`operated` AS `operated`,`a`.`bookEntried` AS `bookEntried`,`a`.`invoiceInFk` AS `invoiceInFk`,`a`.`isChecked` AS `isChecked` from `vn2008`.`awb` `a` */; -/*!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 `bank` --- - -/*!50001 DROP VIEW IF EXISTS `bank`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `bank` AS select `b`.`Id_Banco` AS `id`,`b`.`Banco` AS `bank`,`b`.`Cuenta` AS `account`,`b`.`cash` AS `cash`,`b`.`entity_id` AS `entityFk`,`b`.`activo` AS `isActive` from `vn2008`.`Bancos` `b` */; -/*!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 `bankEntity` --- - -/*!50001 DROP VIEW IF EXISTS `bankEntity`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `bankEntity` AS select `e`.`entity_id` AS `id`,`e`.`pais_id` AS `countryFk`,`e`.`description` AS `name`,`e`.`bic` AS `bic` from `vn2008`.`entity` `e` */; -/*!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 `botanicExport` --- - -/*!50001 DROP VIEW IF EXISTS `botanicExport`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `botanicExport` AS select `be`.`botanic_export_id` AS `id`,`be`.`edi_genus_id` AS `ediGenusFk`,`be`.`edi_specie_id` AS `ediSpecieFk`,`be`.`Id_Paises` AS `countryFk`,`be`.`restriction` AS `restriction`,`be`.`description` AS `description` from `vn2008`.`botanic_export` `be` */; -/*!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 `buy` --- - -/*!50001 DROP VIEW IF EXISTS `buy`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `buy` AS select `c`.`Id_Compra` AS `id`,`c`.`Id_Entrada` AS `entryFk`,`c`.`Id_Article` AS `itemFk`,`c`.`Cantidad` AS `amount`,`c`.`Costefijo` AS `buyingValue`,`c`.`Cantidad` AS `quantity`,`c`.`Id_Cubo` AS `packageFk`,`c`.`Etiquetas` AS `stickers`,`c`.`Portefijo` AS `freightValue`,`c`.`Embalajefijo` AS `packageValue`,`c`.`Comisionfija` AS `comissionValue`,`c`.`Packing` AS `packing`,`c`.`grouping` AS `grouping`,`c`.`caja` AS `groupingMode`,`c`.`Nicho` AS `location`,`c`.`Tarifa1` AS `price1`,`c`.`Tarifa2` AS `price2`,`c`.`Tarifa3` AS `price3`,`c`.`PVP` AS `minPrice`,`c`.`Productor` AS `producer`,`c`.`Vida` AS `printedStickers`,`c`.`punteo` AS `isChecked` from `vn2008`.`Compres` `c` */; -/*!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 `city` --- - -/*!50001 DROP VIEW IF EXISTS `city`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `city` AS select `c`.`city_id` AS `id`,`c`.`name` AS `name`,`c`.`province_id` AS `provinceFk` from `vn2008`.`city` `c` */; -/*!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 `claimRatio` --- - -/*!50001 DROP VIEW IF EXISTS `claimRatio`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `claimRatio` AS select `bi`.`claims_ratio`.`Id_Cliente` AS `clientFk`,`bi`.`claims_ratio`.`Consumo` AS `yearSale`,`bi`.`claims_ratio`.`Reclamaciones` AS `claimAmount`,`bi`.`claims_ratio`.`Ratio` AS `claimingRate`,`bi`.`claims_ratio`.`recobro` AS `priceIncreasing`,`bi`.`claims_ratio`.`inflacion` AS `packingRate` from `bi`.`claims_ratio` */; -/*!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 `client` --- - -/*!50001 DROP VIEW IF EXISTS `client`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `client` AS select `c`.`id_cliente` AS `id`,`c`.`cliente` AS `name`,`c`.`if` AS `fi`,`c`.`razonSocial` AS `socialName`,`c`.`contacto` AS `contact`,`c`.`domicilio` AS `street`,`c`.`poblacion` AS `city`,`c`.`codPostal` AS `postcode`,`c`.`telefono` AS `phone`,`c`.`movil` AS `mobile`,`c`.`fax` AS `fax`,`c`.`real` AS `isRelevant`,`c`.`e-mail` AS `email`,`c`.`iban` AS `iban`,`c`.`vencimiento` AS `dueDay`,`c`.`Cuenta` AS `accountingAccount`,`c`.`RE` AS `isEqualizated`,`c`.`province_id` AS `provinceFk`,`c`.`invoice` AS `hasToInvoice`,`c`.`credito` AS `credit`,`c`.`Id_Pais` AS `countryFk`,`c`.`activo` AS `isActive`,`c`.`gestdoc_id` AS `gestdocFk`,`c`.`calidad` AS `quality`,`c`.`pay_met_id` AS `payMethodFk`,`c`.`created` AS `created`,`c`.`mail` AS `isToBeMailed`,`c`.`chanel_id` AS `contactChannelFk`,`c`.`sepaVnl` AS `hasSepaVnl`,`c`.`coreVnl` AS `hasCoreVnl`,`c`.`coreVnh` AS `hasCoreVnh`,`c`.`default_address` AS `defaultAddressFk`,`c`.`risk_calculated` AS `riskCalculated`,`c`.`clientes_tipo_id` AS `clientTypeFk`,`c`.`mail_address` AS `mailAddress`,`c`.`cplusTerIdNifFk` AS `cplusTerIdNifFk`,`c`.`invoiceByAddress` AS `hasToInvoiceByAddress`,`c`.`contabilizado` AS `isTaxDataChecked`,`c`.`congelado` AS `isFreezed`,`c`.`creditInsurance` AS `creditInsurance`,`c`.`isCreatedAsServed` AS `isCreatedAsServed`,`c`.`hasInvoiceSimplified` AS `hasInvoiceSimplified`,`c`.`Id_Trabajador` AS `salesPersonFk`,`c`.`vies` AS `isVies`,`c`.`EYPBC` AS `eypbc` from `vn2008`.`Clientes` `c` */; -/*!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 `clientCredit` --- - -/*!50001 DROP VIEW IF EXISTS `clientCredit`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `clientCredit` AS select `c`.`id` AS `id`,`c`.`Id_Cliente` AS `clientFk`,`c`.`Id_Trabajador` AS `workerFk`,`c`.`amount` AS `amount`,`c`.`odbc_date` AS `created` from `vn2008`.`credit` `c` */; -/*!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 `clientDefaultCompany` --- - -/*!50001 DROP VIEW IF EXISTS `clientDefaultCompany`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `clientDefaultCompany` AS select `t`.`Id_Clientes_empresa` AS `id`,`t`.`Id_Cliente` AS `clientFk`,`t`.`empresa_id` AS `companyFk`,`t`.`fecha_ini` AS `started`,`t`.`fecha_fin` AS `finished` from `vn2008`.`Clientes_empresa` `t` */; -/*!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 `clientManaCache` --- - -/*!50001 DROP VIEW IF EXISTS `clientManaCache`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `clientManaCache` AS select `mc`.`Id_Cliente` AS `clientFk`,`mc`.`Mana` AS `mana`,`mc`.`dated` AS `dated` from `bs`.`manaCustomer` `mc` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `clientNotification` --- - -/*!50001 DROP VIEW IF EXISTS `clientNotification`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `clientNotification` AS select `e`.`id` AS `id`,`e`.`Id_Cliente` AS `clientFk`,`e`.`escritos_id` AS `clientNotificationTypeFk`,`e`.`fecha` AS `created`,`e`.`Id_Trabajador` AS `workerFk`,`e`.`userFk` AS `userFk` from `vn2008`.`escritos_det` `e` */; -/*!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 `clientNotificationType` --- - -/*!50001 DROP VIEW IF EXISTS `clientNotificationType`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `clientNotificationType` AS select `e`.`id` AS `id`,`e`.`abrev` AS `code`,`e`.`descripcion` AS `description`,`e`.`visible` AS `isVisible` from `vn2008`.`escritos` `e` */; -/*!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 `clientObservation` --- - -/*!50001 DROP VIEW IF EXISTS `clientObservation`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `clientObservation` AS select `t`.`client_observation_id` AS `id`,`t`.`Id_Cliente` AS `clientFk`,`t`.`Id_Trabajador` AS `workerFk`,`t`.`text` AS `text`,`t`.`odbc_date` AS `created` from `vn2008`.`client_observation` `t` */; -/*!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 `clientType` --- - -/*!50001 DROP VIEW IF EXISTS `clientType`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `clientType` AS select `ct`.`clientes_tipo_id` AS `id`,`ct`.`code` AS `code`,`ct`.`tipo` AS `type` from `vn2008`.`clientes_tipo` `ct` */; -/*!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 `color` --- - -/*!50001 DROP VIEW IF EXISTS `color`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `color` AS select `c`.`Id_Color` AS `id`,`c`.`Color` AS `name` from `vn2008`.`Colores` `c` */; -/*!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 `company` --- - -/*!50001 DROP VIEW IF EXISTS `company`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `company` AS select `e`.`id` AS `id`,`e`.`abbreviation` AS `code`,`e`.`Id_Proveedores_account` AS `supplierAccountFk`,`e`.`CodigoEmpresa` AS `CodigoEmpresa` from `vn2008`.`empresa` `e` */; -/*!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 `comparative` --- - -/*!50001 DROP VIEW IF EXISTS `comparative`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `comparative` AS select `c`.`Periodo` AS `timePeriod`,`c`.`Id_Article` AS `itemFk`,`c`.`warehouse_id` AS `warehouseFk`,`c`.`Cantidad` AS `quantity`,`c`.`price` AS `price` from `vn2008`.`Comparativa` `c` */; -/*!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 `comparativeFilter` --- - -/*!50001 DROP VIEW IF EXISTS `comparativeFilter`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `comparativeFilter` AS select `f`.`id` AS `id`,`f`.`name` AS `name`,`f`.`sql` AS `whereSql` from `vn2008`.`filtros` `f` */; -/*!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 `componentRate` --- - -/*!50001 DROP VIEW IF EXISTS `componentRate`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `componentRate` AS select `t`.`Id_Componente` AS `id`,`t`.`Componente` AS `name`,`t`.`tarifa_componentes_series_id` AS `componentTypeRate`,`t`.`tarifa_class` AS `classRate`,`t`.`tax` AS `tax`,`t`.`is_renewable` AS `isRenewable` from `bi`.`tarifa_componentes` `t` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `componentTypeRate` --- - -/*!50001 DROP VIEW IF EXISTS `componentTypeRate`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `componentTypeRate` AS select `t`.`tarifa_componentes_series_id` AS `id`,`t`.`Serie` AS `type` from `bi`.`tarifa_componentes_series` `t` */; -/*!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 `contactChannel` --- - -/*!50001 DROP VIEW IF EXISTS `contactChannel`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `contactChannel` AS select `c`.`chanel_id` AS `id`,`c`.`name` AS `name` from `vn2008`.`chanel` `c` */; -/*!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 `country` --- - -/*!50001 DROP VIEW IF EXISTS `country`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `country` AS select `p`.`Id` AS `id`,`p`.`Pais` AS `country`,`p`.`CEE` AS `CEE`,`p`.`isUeeMember` AS `isUeeMember`,`p`.`Codigo` AS `code`,`p`.`Id_Moneda` AS `currencyFk`,`p`.`Id_Paisreal` AS `politicalCountryFk`,`p`.`geoFk` AS `geoFk` from `vn2008`.`Paises` `p` */; -/*!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 `currency` --- - -/*!50001 DROP VIEW IF EXISTS `currency`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `currency` AS select `m`.`Id_Moneda` AS `id`,`m`.`Moneda` AS `code`,`m`.`Descripcion` AS `name` from `vn2008`.`Monedas` `m` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `deliveryMethod` --- - -/*!50001 DROP VIEW IF EXISTS `deliveryMethod`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `deliveryMethod` AS select `d`.`vista_id` AS `id`,`d`.`code` AS `code`,`d`.`vista` AS `description` from `vn2008`.`Vistas` `d` */; -/*!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 `ediGenus` --- - -/*!50001 DROP VIEW IF EXISTS `ediGenus`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ediGenus` AS select `g`.`genus_id` AS `id`,`g`.`latin_genus_name` AS `latinGenusName`,`g`.`entry_date` AS `entried`,`g`.`expiry_date` AS `dued`,`g`.`change_date_time` AS `modified` from `edi`.`genus` `g` */; -/*!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 `ediSpecie` --- - -/*!50001 DROP VIEW IF EXISTS `ediSpecie`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ediSpecie` AS select `s`.`specie_id` AS `id`,`s`.`genus_id` AS `genusFk`,`s`.`latin_species_name` AS `latinSpeciesName`,`s`.`entry_date` AS `entried`,`s`.`expiry_date` AS `dued`,`s`.`change_date_time` AS `modified` from `edi`.`specie` `s` */; -/*!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 `entity` --- - -/*!50001 DROP VIEW IF EXISTS `entity`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `entity` AS select `e`.`pais_id` AS `countryFk`,`e`.`entity_id` AS `id`,`e`.`description` AS `description`,`e`.`bic` AS `bic` from `vn2008`.`entity` `e` */; -/*!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 `entry` --- - -/*!50001 DROP VIEW IF EXISTS `entry`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `entry` AS select `e`.`Id_Entrada` AS `id`,`e`.`Id_Proveedor` AS `supplierFk`,`e`.`Referencia` AS `ref`,`e`.`Inventario` AS `isInventory`,`e`.`Confirmada` AS `isConfirmed`,`e`.`Pedida` AS `isOrdered`,`e`.`Redada` AS `isRaid`,`e`.`comision` AS `commission`,`e`.`odbc_date` AS `created`,`e`.`Notas_Eva` AS `evaNotes`,`e`.`travel_id` AS `travelFk`,`e`.`Id_Moneda` AS `currencyFk`,`e`.`empresa_id` AS `companyFk`,`e`.`gestdoc_id` AS `gestDocFk`,`e`.`recibida_id` AS `invoiceReceivedFk` from `vn2008`.`Entradas` `e` */; -/*!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 `especialPrice` --- - -/*!50001 DROP VIEW IF EXISTS `especialPrice`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `especialPrice` AS select `p`.`Id_PrecioEspecial` AS `id`,`p`.`Id_Cliente` AS `clientFk`,`p`.`Id_Article` AS `itemFk`,`p`.`PrecioEspecial` AS `value` from `vn2008`.`PreciosEspeciales` `p` */; -/*!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 `expedition` --- - -/*!50001 DROP VIEW IF EXISTS `expedition`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `expedition` AS select `e`.`expeditions_id` AS `id`,`e`.`agency_id` AS `agency`,`e`.`agency_id` AS `agencyFk`,`e`.`agency_id` AS `agencyModeFk`,`e`.`ticket_id` AS `ticket`,`e`.`ticket_id` AS `ticketFk`,`e`.`EsBulto` AS `isBox`,`e`.`odbc_date` AS `printingTime`,`e`.`Id_Article` AS `item`,`e`.`Id_Article` AS `itemFk`,`e`.`counter` AS `counter`,`e`.`checked` AS `checked`,`e`.`workerFk` AS `workerFk` from `vn2008`.`expeditions` `e` */; -/*!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 `expence` --- - -/*!50001 DROP VIEW IF EXISTS `expence`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `expence` AS select `g`.`Id_Gasto` AS `id`,`g`.`iva_tipo_id` AS `taxTypeFk`,`g`.`Gasto` AS `name`,`g`.`isWithheld` AS `isWithheld` from `vn2008`.`Gastos` `g` */; -/*!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 `firstTicketShipped` --- - -/*!50001 DROP VIEW IF EXISTS `firstTicketShipped`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `firstTicketShipped` AS select min(`ticket`.`shipped`) AS `shipped`,`ticket`.`clientFk` AS `clientFk` from `vn`.`ticket` where (`ticket`.`shipped` > '2001-01-01') group by `ticket`.`clientFk` */; -/*!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 `grant` --- - -/*!50001 DROP VIEW IF EXISTS `grant`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `grant` AS select `vn2008`.`Permisos`.`Id_Grupo` AS `group`,`vn2008`.`Permisos`.`Id_Trabajador` AS `worker`,`vn2008`.`Permisos`.`empresa_id` AS `company` from `vn2008`.`Permisos` */; -/*!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 `grantGroup` --- - -/*!50001 DROP VIEW IF EXISTS `grantGroup`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `grantGroup` AS select `vn2008`.`Grupos`.`id` AS `id`,`vn2008`.`Grupos`.`Grupo` AS `description`,`vn2008`.`Grupos`.`observation_type_id` AS `observationType` from `vn2008`.`Grupos` */; -/*!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 `greuge` --- - -/*!50001 DROP VIEW IF EXISTS `greuge`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `greuge` AS select `g`.`Id` AS `id`,`g`.`Id_Cliente` AS `clientFk`,`g`.`Comentario` AS `description`,`g`.`Importe` AS `amount`,`g`.`Fecha` AS `shipped`,`g`.`odbc_date` AS `created`,`g`.`Greuges_type_id` AS `greugeTypeFk`,`g`.`Id_Ticket` AS `ticketFk` from `vn2008`.`Greuges` `g` */; -/*!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 `greugeType` --- - -/*!50001 DROP VIEW IF EXISTS `greugeType`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `greugeType` AS select `gt`.`Greuges_type_id` AS `id`,`gt`.`name` AS `name` from `vn2008`.`Greuges_type` `gt` */; -/*!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 `ink` --- - -/*!50001 DROP VIEW IF EXISTS `ink`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ink` AS select `c`.`Id_Tinta` AS `id`,`c`.`name` AS `name`,`c`.`Tinta` AS `picture`,`c`.`Orden` AS `showOrder` from `vn2008`.`Tintas` `c` */; -/*!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 `inkL10n` --- - -/*!50001 DROP VIEW IF EXISTS `inkL10n`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `inkL10n` AS select `k`.`id` AS `id`,ifnull(`i`.`name`,`k`.`name`) AS `name` from (`vn`.`ink` `k` left join `vn`.`inkI18n` `i` on(((`i`.`inkFk` = `k`.`id`) and (`i`.`lang` = `util`.`lang`())))) */; -/*!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 `intrastat` --- - -/*!50001 DROP VIEW IF EXISTS `intrastat`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `intrastat` AS select `i`.`Codintrastat` AS `id`,`i`.`Definicion` AS `description`,`i`.`iva_group_id` AS `taxClassFk`,`i`.`iva_codigo_id` AS `taxCodeFk` from `vn2008`.`Intrastat` `i` */; -/*!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 `invoiceCorrection` --- - -/*!50001 DROP VIEW IF EXISTS `invoiceCorrection`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `invoiceCorrection` AS select `ic`.`correctingFk` AS `correctingFk`,`ic`.`correctedFk` AS `correctedFk`,`ic`.`cplusRectificationTypeFk` AS `cplusRectificationTypeFk`,`ic`.`cplusInvoiceType477Fk` AS `cplusInvoiceType477Fk`,`ic`.`invoiceCorrectionTypeFk` AS `invoiceCorrectionTypeFk` from `vn2008`.`invoiceCorrection` `ic` */; -/*!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 `invoiceCorrectionDataSource` --- - -/*!50001 DROP VIEW IF EXISTS `invoiceCorrectionDataSource`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `invoiceCorrectionDataSource` AS select `s`.`itemFk` AS `itemFk`,`s`.`quantity` AS `quantity`,`s`.`concept` AS `concept`,`s`.`price` AS `price`,`s`.`discount` AS `discount`,`t`.`refFk` AS `refFk`,`s`.`id` AS `saleFk`,`t`.`shipped` AS `shipped` from (`vn`.`sale` `s` join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) */; -/*!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 `invoiceIn` --- - -/*!50001 DROP VIEW IF EXISTS `invoiceIn`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `invoiceIn` AS select `r`.`id` AS `id`,`r`.`num_recibida` AS `serialNumber`,`r`.`serie` AS `serial`,`r`.`proveedor_id` AS `supplierFk`,`r`.`fecha` AS `issued`,`r`.`sref` AS `supplierRef`,`r`.`contabilizada` AS `isBooked`,`r`.`moneda_id` AS `currencyFk`,`r`.`MYSQL_TIME` AS `created`,`r`.`empresa_id` AS `companyFk`,`r`.`gestdoc_id` AS `docFk`,`r`.`dateBooking` AS `booked`,`r`.`dateOperation` AS `operated`,`r`.`cplusInvoiceType472Fk` AS `cplusInvoiceType472Fk`,`r`.`cplusRectificationTypeFk` AS `cplusRectificationTypeFk`,`r`.`cplusSubjectOpFk` AS `cplusSubjectOpFk`,`r`.`cplusTaxBreakFk` AS `cplusTaxBreakFk`,`r`.`cplusTrascendency472Fk` AS `cplusTrascendency472Fk`,`r`.`bookEntried` AS `bookEntried`,`r`.`isVatDeductible` AS `isVatDeductible` from `vn2008`.`recibida` `r` */; -/*!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 `invoiceInAwb` --- - -/*!50001 DROP VIEW IF EXISTS `invoiceInAwb`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `invoiceInAwb` AS select `a`.`recibida_id` AS `invoiceInFk`,`a`.`awb_id` AS `awbFk`,`a`.`dua` AS `dua` from `vn2008`.`awb_recibida` `a` */; -/*!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 `invoiceInDueDay` --- - -/*!50001 DROP VIEW IF EXISTS `invoiceInDueDay`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `invoiceInDueDay` AS select `r`.`id` AS `id`,`r`.`recibida_id` AS `invoiceInFk`,`r`.`fecha` AS `dueDated`,`r`.`banco_id` AS `bankFk`,`r`.`cantidad` AS `amount`,`r`.`divisa` AS `foreignValue`,`r`.`stamp` AS `created` from `vn2008`.`recibida_vencimiento` `r` */; -/*!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 `invoiceInEntry` --- - -/*!50001 DROP VIEW IF EXISTS `invoiceInEntry`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `invoiceInEntry` AS select `i`.`recibida_entrada_id` AS `id`,`i`.`recibida_id` AS `invoiceInFk`,`i`.`Id_Entrada` AS `entryFk`,`i`.`percentage` AS `percentage`,`i`.`awb_recibida` AS `invoiceInAwbFk`,`i`.`Contabilizado` AS `isBooked` from `vn2008`.`recibida_entrada` `i` */; -/*!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 `invoiceInIntrastat` --- - -/*!50001 DROP VIEW IF EXISTS `invoiceInIntrastat`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `invoiceInIntrastat` AS select `r`.`recibida_id` AS `invoiceInFk`,`r`.`Codintrastat` AS `intrastatFk`,`r`.`importe` AS `amount` from `vn2008`.`recibida_intrastat` `r` */; -/*!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 `invoiceInTax` --- - -/*!50001 DROP VIEW IF EXISTS `invoiceInTax`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `invoiceInTax` AS select `r`.`id` AS `id`,`r`.`recibida_id` AS `invoiceInFk`,`r`.`iva_id` AS `taxCodeFk`,`r`.`bi` AS `taxableBase`,`r`.`gastos_id` AS `expenceFk`,`r`.`divisa` AS `foreignValue`,`r`.`MYSQL_TIME` AS `created` from `vn2008`.`recibida_iva` `r` */; -/*!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 `invoiceOut` --- - -/*!50001 DROP VIEW IF EXISTS `invoiceOut`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `invoiceOut` AS select `f`.`factura_id` AS `id`,`f`.`Id_Factura` AS `ref`,`f`.`Serie` AS `serial`,`f`.`Fecha` AS `issued`,`f`.`Importe` AS `amount`,`f`.`Id_Cliente` AS `clientFk`,`f`.`odbc_date` AS `created`,`f`.`empresa_id` AS `companyFk`,`f`.`Vencimiento` AS `dued`,`f`.`booked` AS `booked`,`f`.`Id_Banco` AS `bankFk`,`f`.`cplusInvoiceType477Fk` AS `cplusInvoiceType477Fk`,`f`.`cplusTaxBreakFk` AS `cplusTaxBreakFk`,`f`.`cplusSubjectOpFk` AS `cplusSubjectOpFk`,`f`.`cplusTrascendency477Fk` AS `cplusTrascendency477Fk`,`f`.`pdf` AS `pdf` from `vn2008`.`Facturas` `f` */; -/*!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 `item` --- - -/*!50001 DROP VIEW IF EXISTS `item`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `item` AS select `t`.`Id_Article` AS `id`,`t`.`Article` AS `name`,`t`.`tipo_id` AS `typeFk`,`t`.`Medida` AS `size`,`t`.`Color` AS `inkFk`,`t`.`Categoria` AS `category`,`t`.`Tallos` AS `stems`,`t`.`id_origen` AS `originFk`,`t`.`description` AS `description`,`t`.`producer_id` AS `producerFk`,`t`.`Codintrastat` AS `intrastatFk`,`t`.`offer` AS `isOnOffer`,`t`.`expenceFk` AS `expenceFk`,`t`.`bargain` AS `isBargain`,`t`.`comments` AS `comment`,`t`.`relevancy` AS `relevancy`,`t`.`Foto` AS `image`,`t`.`iva_group_id` AS `taxClassFk` from `vn2008`.`Articles` `t` */; -/*!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 `itemBarcode` --- - -/*!50001 DROP VIEW IF EXISTS `itemBarcode`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `itemBarcode` AS select `vn2008`.`barcodes`.`id` AS `id`,`vn2008`.`barcodes`.`Id_Article` AS `itemFk`,`vn2008`.`barcodes`.`code` AS `code` from `vn2008`.`barcodes` */; -/*!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 `itemBotanical` --- - -/*!50001 DROP VIEW IF EXISTS `itemBotanical`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `itemBotanical` AS select `ab`.`Id_Article` AS `itemFk`,`ab`.`botanical` AS `botanical`,`ab`.`genus_id` AS `genusFk`,`ab`.`specie_id` AS `specieFk` from `vn2008`.`Articles_botanical` `ab` */; -/*!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 `itemBotanicalWithGenus` --- - -/*!50001 DROP VIEW IF EXISTS `itemBotanicalWithGenus`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `itemBotanicalWithGenus` AS select `ib`.`itemFk` AS `itemFk`,ifnull(`ib`.`botanical`,concat(`g`.`latinGenusName`,' ',ifnull(`s`.`latinSpeciesName`,''))) AS `ediBotanic` from ((`vn`.`itemBotanical` `ib` left join `vn`.`ediGenus` `g` on((`g`.`id` = `ib`.`genusFk`))) left join `vn`.`ediSpecie` `s` on((`s`.`id` = `ib`.`specieFk`))) */; -/*!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 `itemCategory` --- - -/*!50001 DROP VIEW IF EXISTS `itemCategory`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `itemCategory` AS select `r`.`id` AS `id`,`r`.`reino` AS `name`,`r`.`display` AS `display`,`r`.`color` AS `color` from `vn2008`.`reinos` `r` */; -/*!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 `itemCategoryL10n` --- - -/*!50001 DROP VIEW IF EXISTS `itemCategoryL10n`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `itemCategoryL10n` AS select `c`.`id` AS `id`,ifnull(`i`.`name`,`c`.`name`) AS `name` from (`vn`.`itemCategory` `c` left join `vn`.`itemCategoryI18n` `i` on(((`i`.`categoryFk` = `c`.`id`) and (`i`.`lang` = `util`.`lang`())))) */; -/*!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 `itemPlacement` --- - -/*!50001 DROP VIEW IF EXISTS `itemPlacement`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `itemPlacement` AS select `an`.`id` AS `id`,`an`.`Id_Article` AS `itemFk`,`an`.`warehouse_id` AS `warehouseFk`,`an`.`nicho` AS `code` from `vn2008`.`Articles_nicho` `an` */; -/*!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 `itemTagged` --- - -/*!50001 DROP VIEW IF EXISTS `itemTagged`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `itemTagged` AS select distinct `itemTag`.`itemFk` AS `itemFk` from `itemTag` */; -/*!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 `itemType` --- - -/*!50001 DROP VIEW IF EXISTS `itemType`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `itemType` AS select `t`.`tipo_id` AS `id`,`t`.`Id_Tipo` AS `code`,`t`.`Tipo` AS `name`,`t`.`reino_id` AS `categoryFk`,`t`.`life` AS `life`,`t`.`Id_Trabajador` AS `workerFk`,`t`.`isPackaging` AS `isPackaging` from `vn2008`.`Tipos` `t` */; -/*!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 `itemTypeL10n` --- - -/*!50001 DROP VIEW IF EXISTS `itemTypeL10n`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `itemTypeL10n` AS select `t`.`id` AS `id`,ifnull(`i`.`name`,`t`.`name`) AS `name` from (`vn`.`itemType` `t` left join `vn`.`itemTypeI18n` `i` on(((`i`.`typeFk` = `t`.`id`) and (`i`.`lang` = `util`.`LANG`())))) */; -/*!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 `mail` --- - -/*!50001 DROP VIEW IF EXISTS `mail`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `mail` AS select `vn2008`.`mail`.`id` AS `id`,`vn2008`.`mail`.`senderFk` AS `senderFk`,`vn2008`.`mail`.`recipientFk` AS `recipientFk`,`vn2008`.`mail`.`to` AS `sender`,`vn2008`.`mail`.`reply_to` AS `replyTo`,`vn2008`.`mail`.`subject` AS `subject`,`vn2008`.`mail`.`text` AS `body`,`vn2008`.`mail`.`plainTextBody` AS `plainTextBody`,`vn2008`.`mail`.`path` AS `attachment`,`vn2008`.`mail`.`DATE_ODBC` AS `creationDate`,`vn2008`.`mail`.`sent` AS `sent`,`vn2008`.`mail`.`error` AS `status` from `vn2008`.`mail` */; -/*!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 `manaSpellers` --- - -/*!50001 DROP VIEW IF EXISTS `manaSpellers`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `manaSpellers` AS select `bs`.`mana_spellers`.`Id_Trabajador` AS `worker`,`bs`.`mana_spellers`.`size` AS `size`,`bs`.`mana_spellers`.`used` AS `used`,`bs`.`mana_spellers`.`prices_modifier_rate` AS `pricesModifierRate`,`bs`.`mana_spellers`.`prices_modifier_activated` AS `pricesModifierActivated`,`vn2008`.`Trabajadores`.`CodigoTrabajador` AS `workerCode`,`vn2008`.`Trabajadores`.`Nombre` AS `firstname`,`vn2008`.`Trabajadores`.`Apellidos` AS `name` from (`bs`.`mana_spellers` join `vn2008`.`Trabajadores` on((`bs`.`mana_spellers`.`Id_Trabajador` = `vn2008`.`Trabajadores`.`Id_Trabajador`))) */; -/*!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 `mandate` --- - -/*!50001 DROP VIEW IF EXISTS `mandate`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `mandate` AS select `m`.`id` AS `id`,`m`.`Id_Cliente` AS `clientFk`,`m`.`empresa_id` AS `companyFk`,`m`.`Id_mandato` AS `code`,`m`.`FAlta` AS `created`,`m`.`Fbaja` AS `finished`,`m`.`idmandato_tipo` AS `mandateTypeFk` from `vn2008`.`mandato` `m` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `mandateType` --- - -/*!50001 DROP VIEW IF EXISTS `mandateType`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `mandateType` AS select `m`.`idmandato_tipo` AS `id`,`m`.`Nombre` AS `name` from `vn2008`.`mandato_tipo` `m` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `movement` --- - -/*!50001 DROP VIEW IF EXISTS `movement`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `movement` AS select `m`.`Id_Movimiento` AS `id`,`m`.`Id_Article` AS `item`,`m`.`Id_Ticket` AS `ticket`,`m`.`Concepte` AS `concept`,`m`.`Cantidad` AS `amount`,`m`.`quantity` AS `quantity`,`m`.`Preu` AS `price`,`m`.`Descuento` AS `discount`,`m`.`CostFixat` AS `cost`,`m`.`Reservado` AS `reservado`,`m`.`OK` AS `od`,`m`.`PrecioFijado` AS `priceFixed`,`m`.`odbc_date` AS `lastUpdate` from `vn2008`.`Movimientos` `m` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `movementkk` --- - -/*!50001 DROP VIEW IF EXISTS `movementkk`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `movementkk` AS select `m`.`Id_Movimiento` AS `id`,`m`.`Id_Article` AS `item`,`m`.`Id_Ticket` AS `ticket`,`m`.`Concepte` AS `concept`,`m`.`Cantidad` AS `amount`,`m`.`quantity` AS `quantity`,`m`.`Preu` AS `price`,`m`.`Descuento` AS `discount`,`m`.`CostFixat` AS `cost`,`m`.`Reservado` AS `reservado`,`m`.`OK` AS `od`,`m`.`PrecioFijado` AS `priceFixed`,`m`.`odbc_date` AS `lastUpdate` from `vn2008`.`Movimientos` `m` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `observationType` --- - -/*!50001 DROP VIEW IF EXISTS `observationType`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `observationType` AS select `ot`.`observation_type_id` AS `id`,`ot`.`description` AS `description` from `vn2008`.`observation_type` `ot` */; -/*!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 `origin` --- - -/*!50001 DROP VIEW IF EXISTS `origin`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `origin` AS select `o`.`id` AS `id`,`o`.`Abreviatura` AS `code`,`o`.`Origen` AS `name` from `vn2008`.`Origen` `o` */; -/*!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 `originL10n` --- - -/*!50001 DROP VIEW IF EXISTS `originL10n`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `originL10n` AS select `o`.`id` AS `id`,ifnull(`i`.`name`,`o`.`name`) AS `name` from (`vn`.`origin` `o` left join `vn`.`originI18n` `i` on(((`i`.`originFk` = `o`.`id`) and (`i`.`lang` = `util`.`lang`())))) */; -/*!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 `outgoingInvoice` --- - -/*!50001 DROP VIEW IF EXISTS `outgoingInvoice`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `outgoingInvoice` AS select `vn2008`.`Facturas`.`Id_Factura` AS `id`,`vn2008`.`Facturas`.`Serie` AS `serie`,`vn2008`.`Facturas`.`Fecha` AS `dateInvoice`,`vn2008`.`Facturas`.`Importe` AS `total`,`vn2008`.`Facturas`.`Vencimiento` AS `dueDate`,`vn2008`.`Facturas`.`Id_Banco` AS `bank`,`vn2008`.`Facturas`.`Id_Cliente` AS `client`,`vn2008`.`Facturas`.`Id_Remesa` AS `remittance`,`vn2008`.`Facturas`.`Remesar` AS `remit`,`vn2008`.`Facturas`.`Id_Trabajador` AS `worker`,`vn2008`.`Facturas`.`odbc_date` AS `creationDate`,`vn2008`.`Facturas`.`empresa_id` AS `company`,`vn2008`.`Facturas`.`liquidacion` AS `liquidacion?`,`vn2008`.`Facturas`.`pdf` AS `isPdf` from `vn2008`.`Facturas` */; -/*!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 `package` --- - -/*!50001 DROP VIEW IF EXISTS `package`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `package` AS select `c`.`Id_Cubo` AS `id`,`c`.`Volumen` AS `volume`,`c`.`X` AS `width`,`c`.`Y` AS `height`,`c`.`Z` AS `depth`,`c`.`Retornable` AS `isPackageReturnable`,`c`.`odbc_date` AS `created`,`c`.`item_id` AS `itemFk`,`c`.`pvp` AS `price` from `vn2008`.`Cubos` `c` */; -/*!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 `packageEquivalentItem` --- - -/*!50001 DROP VIEW IF EXISTS `packageEquivalentItem`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `packageEquivalentItem` AS select `i`.`itemFk` AS `itemFk`,`ie`.`itemFk` AS `equivalentFk` from ((`vn`.`packageEquivalent` `pe` join `vn`.`package` `i` on((`i`.`id` = `pe`.`packageFk`))) join `vn`.`package` `ie` on((`ie`.`id` = `pe`.`equivalentFk`))) */; -/*!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 `payMethod` --- - -/*!50001 DROP VIEW IF EXISTS `payMethod`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `payMethod` AS select `t`.`id` AS `id`,`t`.`name` AS `name`,`t`.`graceDays` AS `graceDays`,`t`.`deudaviva` AS `outstandingDebt`,`t`.`ibanRequired` AS `ibanRequired` from `vn2008`.`pay_met` `t` */; -/*!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 `payment` --- - -/*!50001 DROP VIEW IF EXISTS `payment`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `payment` AS select `p`.`id` AS `id`,`p`.`fecha` AS `received`,`p`.`id_proveedor` AS `supplierFk`,`p`.`importe` AS `amount`,`p`.`id_moneda` AS `currencyFk`,`p`.`divisa` AS `divisa`,`p`.`id_banco` AS `bankFk`,`p`.`pay_met_id` AS `payMethod`,`p`.`empresa_id` AS `companyFk`,`p`.`pago_sdc_id` AS `paymentExchangeInsuranceFk`,`p`.`conciliado` AS `isConciliate` from `vn2008`.`pago` `p` */; -/*!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 `paymentExchangeInsurance` --- - -/*!50001 DROP VIEW IF EXISTS `paymentExchangeInsurance`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `paymentExchangeInsurance` AS select `p`.`pago_sdc_id` AS `id`,`p`.`importe` AS `amount`,`p`.`fecha` AS `created`,`p`.`vencimiento` AS `dueDay`,`p`.`entity_id` AS `entityFk`,`p`.`ref` AS `ref`,`p`.`rate` AS `rate`,`p`.`empresa_id` AS `companyFk`,`p`.`financialProductTypefk` AS `financialProductTypefk`,`p`.`upperBarrier` AS `upperBarrier`,`p`.`lowerBarrier` AS `lowerBarrier`,`p`.`strike` AS `strike` from `vn2008`.`pago_sdc` `p` */; -/*!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 `payrollCenter` --- - -/*!50001 DROP VIEW IF EXISTS `payrollCenter`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `payrollCenter` AS select `b`.`cod_centro` AS `codCenter`,`b`.`Centro` AS `name`,`b`.`nss_cotizacion` AS `nss`,`b`.`domicilio` AS `street`,`b`.`poblacion` AS `city`,`b`.`cp` AS `postcode`,`b`.`empresa_id` AS `companyFk`,`b`.`codempresa` AS `companyCode` from `vn2008`.`payroll_centros` `b` */; -/*!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 `plantpassport` --- - -/*!50001 DROP VIEW IF EXISTS `plantpassport`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `plantpassport` AS select `pp`.`producer_id` AS `producerFk`,`pp`.`plantpassport_authority_id` AS `plantpassportAuthorityFk`,`pp`.`number` AS `number` from `vn2008`.`plantpassport` `pp` */; -/*!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 `plantpassportAuthority` --- - -/*!50001 DROP VIEW IF EXISTS `plantpassportAuthority`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `plantpassportAuthority` AS select `ppa`.`plantpassport_authority_id` AS `id`,`ppa`.`denomination` AS `denomination`,`ppa`.`Paises_Id` AS `countryFk` from `vn2008`.`plantpassport_authority` `ppa` */; -/*!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 `priceBuilderDistinctTags` --- - -/*!50001 DROP VIEW IF EXISTS `priceBuilderDistinctTags`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `priceBuilderDistinctTags` AS select `priceBuilderTag`.`priceBuilderFk` AS `priceBuilderFk`,count(distinct `priceBuilderTag`.`tagFk`) AS `numTags` from `priceBuilderTag` group by `priceBuilderTag`.`priceBuilderFk` */; -/*!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 `priceFixed` --- - -/*!50001 DROP VIEW IF EXISTS `priceFixed`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `priceFixed` AS select `p`.`item_id` AS `itemFk`,`p`.`rate_0` AS `rate0`,`p`.`rate_1` AS `rate1`,`p`.`rate_2` AS `rate2`,`p`.`rate_3` AS `rate3`,`p`.`date_start` AS `started`,`p`.`date_end` AS `ended`,`p`.`bonus` AS `bonus`,`p`.`warehouse_id` AS `warehouseFk`,`p`.`odbc_date` AS `created`,`p`.`price_fixed_id` AS `id`,`p`.`grouping` AS `grouping`,`p`.`Packing` AS `packing`,`p`.`caja` AS `box` from `vn2008`.`price_fixed` `p` */; -/*!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 `printServerQueue` --- - -/*!50001 DROP VIEW IF EXISTS `printServerQueue`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `printServerQueue` AS select `c`.`Id_Cola` AS `id`,`c`.`Id_Impresora` AS `printerFk`,`c`.`Id_Prioridad` AS `priorityFk`,`c`.`Id_Informe` AS `reportFk`,`c`.`Id_Estado` AS `statusFk`,`c`.`Hora_Inicio` AS `started`,`c`.`Hora_Fin` AS `finished`,`c`.`Cola` AS `param1`,`c`.`Id_Trabajador` AS `workerFk`,`c`.`Cola2` AS `param2`,`c`.`Cola3` AS `param3`,`c`.`error` AS `error` from `vn2008`.`Colas` `c` */; -/*!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 `printingQueue` --- - -/*!50001 DROP VIEW IF EXISTS `printingQueue`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `printingQueue` AS select `c`.`Id_Cola` AS `id`,`c`.`Id_Impresora` AS `printer`,`c`.`Id_Prioridad` AS `priority`,`c`.`Id_Informe` AS `report`,`c`.`Id_Estado` AS `state`,`c`.`Hora_Inicio` AS `startingTime`,`c`.`Hora_Fin` AS `endingTime`,`c`.`Cola` AS `text`,`c`.`Id_Trabajador` AS `worker`,`c`.`Cola2` AS `text2`,`c`.`Cola3` AS `text3` from `vn2008`.`Colas` `c` */; -/*!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 `producer` --- - -/*!50001 DROP VIEW IF EXISTS `producer`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `producer` AS select `p`.`producer_id` AS `id`,`p`.`name` AS `name` from `vn2008`.`producer` `p` */; -/*!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 `promissoryNote` --- - -/*!50001 DROP VIEW IF EXISTS `promissoryNote`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `promissoryNote` AS select `p`.`Id_Pagare` AS `id`,`p`.`Concepto` AS `Concept`,`p`.`pago_id` AS `paymentFk` from `vn2008`.`Pagares` `p` */; -/*!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 `province` --- - -/*!50001 DROP VIEW IF EXISTS `province`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `province` AS select `t`.`province_id` AS `id`,`t`.`name` AS `name`,`t`.`Paises_Id` AS `countryFk`,`t`.`warehouse_id` AS `warehouseFk`,`t`.`zone` AS `zoneFk`,`t`.`geoFk` AS `geoFk` from `vn2008`.`province` `t` */; -/*!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 `receipt` --- - -/*!50001 DROP VIEW IF EXISTS `receipt`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `receipt` AS select `t`.`Id` AS `Id`,`t`.`Id_Factura` AS `invoiceFk`,`t`.`Entregado` AS `amountPaid`,`t`.`Pendiente` AS `amountUnpaid`,`t`.`Fechacobro` AS `payed`,`t`.`Id_Trabajador` AS `workerFk`,`t`.`Id_Banco` AS `bankFk`,`t`.`Id_Cliente` AS `clientFk`,`t`.`odbc_date` AS `created`,`t`.`empresa_id` AS `companyFk`,`t`.`conciliado` AS `isConciliate` from `vn2008`.`Recibos` `t` */; -/*!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 `recovery` --- - -/*!50001 DROP VIEW IF EXISTS `recovery`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `recovery` AS select `r`.`recovery_id` AS `id`,`r`.`Id_Cliente` AS `clientFk`,`r`.`dstart` AS `started`,`r`.`dend` AS `finished`,`r`.`amount` AS `amount`,`r`.`period` AS `period` from `vn2008`.`recovery` `r` */; -/*!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 `referenceRate` --- - -/*!50001 DROP VIEW IF EXISTS `referenceRate`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `referenceRate` AS select `r`.`moneda_id` AS `currencyFk`,`r`.`date` AS `dated`,`r`.`rate` AS `value` from `vn2008`.`reference_rate` `r` */; -/*!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 `role` --- - -/*!50001 DROP VIEW IF EXISTS `role`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `role` AS select `account`.`role`.`id` AS `id`,`account`.`role`.`name` AS `name`,`account`.`role`.`description` AS `description`,`account`.`role`.`hasLogin` AS `hasLogin` from `account`.`role` */; -/*!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 `route` --- - -/*!50001 DROP VIEW IF EXISTS `route`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `route` AS select `a`.`Id_Ruta` AS `id`,`a`.`Id_Trabajador` AS `workerFk`,`a`.`Fecha` AS `created`,`a`.`Id_Vehiculo` AS `vehicleFk`,`a`.`Id_Agencia` AS `agencyModeFk`,`a`.`Hora` AS `time`,`a`.`ok` AS `isOk`,`a`.`km_start` AS `kmStart`,`a`.`km_end` AS `kmEnd`,`a`.`date_start` AS `started`,`a`.`date_end` AS `finished`,`a`.`gestdoc_id` AS `gestdocFk`,`a`.`cost` AS `cost`,`a`.`m3` AS `m3`,`a`.`description` AS `description` from `vn2008`.`Rutas` `a` */; -/*!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 `routesControl` --- - -/*!50001 DROP VIEW IF EXISTS `routesControl`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `routesControl` AS select `t`.`Id_Ruta` AS `routeFk`,count(`e`.`expeditions_id`) AS `expeditions`,count(`sl`.`scan_line_id`) AS `scanned`,count(distinct `sl`.`scan_id`) AS `pallets`,max(`sl`.`odbc_date`) AS `lastScanned` from ((`vn2008`.`Tickets` `t` join `vn2008`.`expeditions` `e` on((`t`.`Id_Ticket` = `e`.`ticket_id`))) left join `vn2008`.`scan_line` `sl` on((`e`.`expeditions_id` = `sl`.`code`))) where (`t`.`Fecha` >= (curdate() + interval -(1) day)) group by `t`.`Id_Ruta` */; -/*!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 `sale` --- - -/*!50001 DROP VIEW IF EXISTS `sale`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `sale` AS select `m`.`Id_Movimiento` AS `id`,`m`.`Id_Article` AS `itemFk`,`m`.`Id_Ticket` AS `ticketFk`,`m`.`Concepte` AS `concept`,`m`.`Cantidad` AS `quantity`,`m`.`Preu` AS `price`,`m`.`Descuento` AS `discount`,`m`.`Reservado` AS `reserved`,`m`.`OK` AS `isPicked`,`m`.`odbc_date` AS `created` from `vn2008`.`Movimientos` `m` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `saleComponent` --- - -/*!50001 DROP VIEW IF EXISTS `saleComponent`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `saleComponent` AS select `mc`.`Id_Movimiento` AS `saleFk`,`mc`.`Id_Componente` AS `componentFk`,`mc`.`Valor` AS `value` from `vn2008`.`Movimientos_componentes` `mc` */; -/*!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 `state` --- - -/*!50001 DROP VIEW IF EXISTS `state`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `state` AS select `s`.`id` AS `id`,`s`.`name` AS `name`,`s`.`order` AS `order`,`s`.`alert_level` AS `alertLevel`,`s`.`code` AS `code` from `vn2008`.`state` `s` */; -/*!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 `supplier` --- - -/*!50001 DROP VIEW IF EXISTS `supplier`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `supplier` AS select `p`.`Id_Proveedor` AS `id`,`p`.`Proveedor` AS `name`,`p`.`cuenta` AS `account`,`p`.`pais_id` AS `countryFk`,`p`.`NIF` AS `nif`,`p`.`Agricola` AS `isFarmer`,`p`.`cuentaret` AS `retAccount`,`p`.`ComisionProveedor` AS `commission`,`p`.`odbc_time` AS `created`,`p`.`postcode_id` AS `postcodeFk`,`p`.`active` AS `isActive`,`p`.`Domicilio` AS `street`,`p`.`Localidad` AS `city`,`p`.`province_id` AS `provinceFk`,`p`.`codpos` AS `postCode` from `vn2008`.`Proveedores` `p` */; -/*!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 `supplierAccount` --- - -/*!50001 DROP VIEW IF EXISTS `supplierAccount`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `supplierAccount` AS select `pa`.`Id_Proveedores_account` AS `id`,`pa`.`Id_Proveedor` AS `supplierFk`,`pa`.`IBAN` AS `iban`,`pa`.`entity_id` AS `bankEntityFk` from `vn2008`.`Proveedores_account` `pa` */; -/*!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 `tagL10n` --- - -/*!50001 DROP VIEW IF EXISTS `tagL10n`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `tagL10n` AS select `t`.`id` AS `id`,ifnull(`i`.`name`,`t`.`name`) AS `name` from (`tag` `t` left join `tagI18n` `i` on(((`i`.`tagFk` = `t`.`id`) and (`i`.`lang` = `util`.`LANG`())))) */; -/*!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 `taxClass` --- - -/*!50001 DROP VIEW IF EXISTS `taxClass`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `taxClass` AS select `c`.`iva_group_id` AS `id`,`c`.`description` AS `description`,`c`.`code` AS `code` from `vn2008`.`iva_group` `c` */; -/*!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 `taxClassCode` --- - -/*!50001 DROP VIEW IF EXISTS `taxClassCode`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `taxClassCode` AS select `c`.`iva_group_id` AS `taxClassFk`,`c`.`date` AS `effectived`,`c`.`iva_codigo_id` AS `taxCodeFk` from `vn2008`.`iva_group_codigo` `c` */; -/*!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 `taxCode` --- - -/*!50001 DROP VIEW IF EXISTS `taxCode`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `taxCode` AS select `ic`.`id` AS `id`,`ic`.`fecha` AS `dated`,`ic`.`codigo` AS `code`,`ic`.`iva_tipo_id` AS `taxTypeFk`,`ic`.`iva` AS `rate`,`ic`.`recargo` AS `equalizationTax`,`ic`.`tipo` AS `type`,`ic`.`link` AS `link`,`ic`.`isActive` AS `isActive`,`ic`.`updated` AS `updated`,`ic`.`transactionCode` AS `transactionCode` from `vn2008`.`iva_codigo` `ic` */; -/*!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 `taxType` --- - -/*!50001 DROP VIEW IF EXISTS `taxType`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `taxType` AS select `t`.`id` AS `id`,`t`.`alias` AS `nickname`,`t`.`isAccrued` AS `isAccrued`,`t`.`serie_id` AS `serial`,`t`.`TIPOOPE` AS `TIPOOPE`,`t`.`descripcion` AS `description`,`t`.`Id_Pais` AS `countryFk` from `vn2008`.`iva_tipo` `t` */; -/*!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 `ticket` --- - -/*!50001 DROP VIEW IF EXISTS `ticket`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ticket` AS select `t`.`Id_Ticket` AS `id`,`t`.`Id_Cliente` AS `clientFk`,`t`.`warehouse_id` AS `warehouseFk`,`t`.`Fecha` AS `shipped`,`t`.`landing` AS `landed`,`t`.`Alias` AS `nickname`,`t`.`Factura` AS `refFk`,`t`.`Id_Consigna` AS `addressFk`,`t`.`Localizacion` AS `location`,`t`.`Solucion` AS `solution`,`t`.`Id_Ruta` AS `routeFk`,`t`.`empresa_id` AS `companyFk`,`t`.`Id_Agencia` AS `agencyModeFk`,`t`.`Prioridad` AS `priority`,`t`.`Bultos` AS `packages`,`t`.`odbc_date` AS `created` from `vn2008`.`Tickets` `t` */; -/*!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 `ticketObservation` --- - -/*!50001 DROP VIEW IF EXISTS `ticketObservation`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ticketObservation` AS select `to`.`ticket_observation_id` AS `id`,`to`.`Id_Ticket` AS `ticketFk`,`to`.`observation_type_id` AS `observationTypeFk`,`to`.`text` AS `description` from `vn2008`.`ticket_observation` `to` */; -/*!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 `ticketState` --- - -/*!50001 DROP VIEW IF EXISTS `ticketState`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ticketState` AS select `i`.`odbc_date` AS `updated`,`i`.`state_id` AS `stateFk`,`i`.`Id_Trabajador` AS `workerFk`,`ts`.`Id_Ticket` AS `ticketFk`,`s`.`id` AS `state`,`s`.`order` AS `productionOrder`,`s`.`alert_level` AS `alertLevel`,`s`.`code` AS `code`,`ts`.`Id_Ticket` AS `ticket`,`i`.`Id_Trabajador` AS `worker` from ((`vn2008`.`Tickets_state` `ts` join `vncontrol`.`inter` `i` on((`i`.`inter_id` = `ts`.`inter_id`))) join `vn2008`.`state` `s` on((`s`.`id` = `i`.`state_id`))) */; -/*!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 `ticketStateToday` --- - -/*!50001 DROP VIEW IF EXISTS `ticketStateToday`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ticketStateToday` AS select `ts`.`ticket` AS `ticket`,`ts`.`state` AS `state`,`ts`.`productionOrder` AS `productionOrder`,`ts`.`alertLevel` AS `alertLevel`,`ts`.`worker` AS `worker`,`ts`.`code` AS `code` from (`vn`.`ticketState` `ts` join `vn`.`ticket` `t` on((`t`.`id` = `ts`.`ticket`))) where (`t`.`shipped` between curdate() and `MIDNIGHT`(curdate())) */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `ticketTracking` --- - -/*!50001 DROP VIEW IF EXISTS `ticketTracking`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ticketTracking` AS select `i`.`inter_id` AS `id`,`i`.`state_id` AS `stateFk`,`i`.`odbc_date` AS `created`,`i`.`Id_Ticket` AS `ticketFk`,`i`.`Id_Trabajador` AS `workerFk` from `vncontrol`.`inter` `i` */; -/*!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 `till` --- - -/*!50001 DROP VIEW IF EXISTS `till`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `till` AS select `c`.`Id_Caja` AS `id`,`c`.`Cajafecha` AS `created`,`c`.`Serie` AS `serie`,`c`.`Concepto` AS `concept`,`c`.`Entrada` AS `in`,`c`.`Salida` AS `out`,`c`.`Id_Banco` AS `bankFk`,`c`.`empresa_id` AS `supplierFk`,`c`.`Partida` AS `isAccountable` from `vn2008`.`Cajas` `c` */; -/*!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 `time` --- - -/*!50001 DROP VIEW IF EXISTS `time`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `time` AS select `t`.`date` AS `dated`,`t`.`period` AS `period`,`t`.`month` AS `month`,`t`.`year` AS `year`,`t`.`day` AS `day`,`t`.`week` AS `week` from `vn2008`.`time` `t` */; -/*!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 `travel` --- - -/*!50001 DROP VIEW IF EXISTS `travel`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `travel` AS select `t`.`id` AS `id`,`t`.`shipment` AS `shipped`,`t`.`shipment_hour` AS `shipmentHour`,`t`.`landing` AS `landed`,`t`.`landing_hour` AS `landingHour`,`t`.`warehouse_id` AS `warehouseInFk`,`t`.`warehouse_id_out` AS `warehouseOutFk`,`t`.`agency_id` AS `agencyFk`,`t`.`ref` AS `ref`,`t`.`delivered` AS `isDelivered`,`t`.`received` AS `isReceived`,`t`.`m3` AS `m3` from `vn2008`.`travel` `t` */; -/*!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 `unary` --- - -/*!50001 DROP VIEW IF EXISTS `unary`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `unary` AS select `a`.`id` AS `id`,`a`.`parent` AS `parent` from `vn2008`.`unary` `a` */; -/*!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 `unaryScan` --- - -/*!50001 DROP VIEW IF EXISTS `unaryScan`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `unaryScan` AS select `u`.`unary_id` AS `unaryFk`,`u`.`name` AS `name`,`u`.`odbc_date` AS `created`,`u`.`type` AS `type` from `vn2008`.`unary_scan` `u` */; -/*!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 `unaryScanLine` --- - -/*!50001 DROP VIEW IF EXISTS `unaryScanLine`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `unaryScanLine` AS select `u`.`id` AS `id`,`u`.`code` AS `code`,`u`.`odbc_date` AS `created`,`u`.`unary_id` AS `unaryScanFk` from `vn2008`.`unary_scan_line` `u` */; -/*!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 `unaryScanLineBuy` --- - -/*!50001 DROP VIEW IF EXISTS `unaryScanLineBuy`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `unaryScanLineBuy` AS select `u`.`scan_line_id` AS `unaryScanLineFk`,`u`.`Id_Article` AS `itemFk` from `vn2008`.`unary_scan_line_buy` `u` */; -/*!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 `unaryScanLineExpedition` --- - -/*!50001 DROP VIEW IF EXISTS `unaryScanLineExpedition`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `unaryScanLineExpedition` AS select `u`.`scan_line_id` AS `unaryScanLineFk`,`u`.`expedition_id` AS `expeditionFk` from `vn2008`.`unary_scan_line_expedition` `u` */; -/*!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 `user` --- - -/*!50001 DROP VIEW IF EXISTS `user`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `user` AS select `account`.`user`.`id` AS `id`,`account`.`user`.`name` AS `name`,`account`.`user`.`password` AS `password`,`account`.`user`.`role` AS `role`,`account`.`user`.`active` AS `active`,`account`.`user`.`recoverPass` AS `recoverPass`,`account`.`user`.`lastPassChange` AS `lastPassChange` from `account`.`user` */; -/*!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 `vehicle` --- - -/*!50001 DROP VIEW IF EXISTS `vehicle`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `vehicle` AS select `v`.`Id_Vehiculo` AS `id`,`v`.`Matricula` AS `numberPlate`,`v`.`Marca` AS `tradeMark`,`v`.`Modelo` AS `model`,`v`.`empresa_id` AS `companyFk`,`v`.`warehouseFk` AS `warehouseFk`,`v`.`description` AS `description`,`v`.`m3` AS `m3`,`v`.`active` AS `isActive` from `vn2008`.`Vehiculos` `v` */; -/*!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 `warehouse` --- - -/*!50001 DROP VIEW IF EXISTS `warehouse`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `warehouse` AS select `t`.`id` AS `id`,`t`.`name` AS `name`,`t`.`inventario` AS `isInventory`,`t`.`is_comparative` AS `isComparative`,`t`.`comisionantes` AS `hasComission`,`t`.`isManaged` AS `isManaged` from `vn2008`.`warehouse` `t` */; -/*!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 `warehouseAlias` --- - -/*!50001 DROP VIEW IF EXISTS `warehouseAlias`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `warehouseAlias` AS select `wa`.`warehouse_alias_id` AS `id`,`wa`.`alias` AS `name` from `vn2008`.`warehouse_alias` `wa` */; -/*!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 `worker` --- - -/*!50001 DROP VIEW IF EXISTS `worker`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `worker` AS select `t`.`Id_Trabajador` AS `id`,`t`.`CodigoTrabajador` AS `workerCode`,`t`.`Nombre` AS `firstName`,`t`.`Apellidos` AS `name`,`t`.`user_id` AS `userFk`,`t`.`phone` AS `phone`,`t`.`boss` AS `bossFk`,`t`.`Foto` AS `photo`,`t`.`dni` AS `fi`,`t`.`DniExpiration` AS `fiDueDate` from `vn2008`.`Trabajadores` `t` */; -/*!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 `workerTeam` --- - -/*!50001 DROP VIEW IF EXISTS `workerTeam`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `workerTeam` AS select `w`.`team` AS `team`,`w`.`user` AS `user`,`w`.`id` AS `id`,`t`.`Id_Trabajador` AS `Id_Trabajador` from (`vn2008`.`workerTeam` `w` left join `vn2008`.`Trabajadores` `t` on((`t`.`user_id` = `w`.`user`))) */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Current Database: `edi` --- - -USE `edi`; - --- --- Current Database: `bs` --- - -USE `bs`; - --- --- Final view structure for view `VentasPorCliente` --- - -/*!50001 DROP VIEW IF EXISTS `VentasPorCliente`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `VentasPorCliente` AS select `v`.`Id_Cliente` AS `Id_Cliente`,round(sum(`v`.`importe`),0) AS `VentaBasica`,`t`.`year` AS `year`,`t`.`month` AS `month` from (`vn2008`.`time` `t` join `bs`.`ventas` `v` on((`v`.`fecha` = `t`.`date`))) group by `v`.`Id_Cliente`,`t`.`year`,`t`.`month` */; -/*!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 `v_ventas` --- - -/*!50001 DROP VIEW IF EXISTS `v_ventas`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_ventas` AS select (`bs`.`ventas`.`importe` * `vn2008`.`Movimientos`.`Cantidad`) AS `importe`,`bs`.`ventas`.`recargo` AS `recargo`,`vn2008`.`time`.`year` AS `year`,`vn2008`.`time`.`month` AS `month`,`vn2008`.`time`.`week` AS `week`,`vn2008`.`time`.`day` AS `day` from ((`bs`.`ventas` join `vn2008`.`time` on((`vn2008`.`time`.`date` = `bs`.`ventas`.`fecha`))) join `vn2008`.`Movimientos` on((`bs`.`ventas`.`Id_Movimiento` = `vn2008`.`Movimientos`.`Id_Movimiento`))) group by `vn2008`.`time`.`date` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Current Database: `bi` --- - -USE `bi`; - --- --- Final view structure for view `analisis_grafico_ventas` --- - -/*!50001 DROP VIEW IF EXISTS `analisis_grafico_ventas`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `analisis_grafico_ventas` AS select `analisis_ventas`.`Año` AS `Año`,`analisis_ventas`.`Semana` AS `Semana`,sum(`analisis_ventas`.`Importe`) AS `Importe` from `analisis_ventas` group by `analisis_ventas`.`Año`,`analisis_ventas`.`Semana` */; -/*!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 `analisis_ventas_simple` --- - -/*!50001 DROP VIEW IF EXISTS `analisis_ventas_simple`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `analisis_ventas_simple` AS select `analisis_ventas`.`Año` AS `Año`,`analisis_ventas`.`Semana` AS `Semana`,sum(`analisis_ventas`.`Importe`) AS `Importe` from `analisis_ventas` group by `analisis_ventas`.`Año`,`analisis_ventas`.`Semana` */; -/*!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 `customerRiskOverdue` --- - -/*!50001 DROP VIEW IF EXISTS `customerRiskOverdue`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `customerRiskOverdue` AS select `cr`.`customer_id` AS `customer_id`,`cr`.`amount` AS `amount`,`cr`.`company_id` AS `company_id` from (((`bi`.`customer_risk` `cr` join `vn2008`.`empresa` `e` on((`e`.`id` = `cr`.`company_id`))) join `vn2008`.`Clientes` `c` on((`cr`.`customer_id` = `c`.`id_cliente`))) join `vn2008`.`pay_met` `pm` on((`pm`.`id` = `c`.`pay_met_id`))) where (`cr`.`amount` and `e`.`morosidad` and `pm`.`deudaviva`) union all select `f`.`Id_Cliente` AS `Id_Cliente`,-(round(`f`.`Importe`,2)) AS `importe`,`f`.`empresa_id` AS `empresa_id` from (((`vn2008`.`Facturas` `f` join `vn2008`.`Clientes` `c` on((`f`.`Id_Cliente` = `c`.`id_cliente`))) join `vn2008`.`empresa` `e` on((`e`.`id` = `f`.`empresa_id`))) join `vn2008`.`pay_met` `pm` on((`pm`.`id` = `c`.`pay_met_id`))) where ((`f`.`Fecha` > (curdate() + interval -(101) day)) and ((`vn2008`.`paymentday`(`f`.`Fecha`,`c`.`vencimiento`) + interval `pm`.`graceDays` day) > curdate()) and (`f`.`Importe` > 0) and `e`.`morosidad` and `pm`.`deudaviva`) */; -/*!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 `last_Id_Cubo` --- - -/*!50001 DROP VIEW IF EXISTS `last_Id_Cubo`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `last_Id_Cubo` AS select `C`.`Id_Compra` AS `Id_Compra`,`C`.`Id_Article` AS `Id_Article`,`tr`.`warehouse_id` AS `warehouse_id`,`C`.`Id_Cubo` AS `Id_Cubo`,`C`.`Packing` AS `Packing` from ((`vn2008`.`Compres` `C` join `vn2008`.`Entradas` `E` on((`C`.`Id_Entrada` = `E`.`Id_Entrada`))) join `vn2008`.`travel` `tr` on((`E`.`travel_id` = `tr`.`id`))) where ((`C`.`Id_Cubo` is not null) and (`C`.`Id_Cubo` <> '--') and (`tr`.`landing` > (curdate() - interval 18 month))) order by `C`.`Id_Compra` desc */; -/*!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 `v_clientes_jerarquia` --- - -/*!50001 DROP VIEW IF EXISTS `v_clientes_jerarquia`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_clientes_jerarquia` AS select `c`.`id_cliente` AS `Id_Cliente`,`c`.`cliente` AS `Cliente`,`t`.`CodigoTrabajador` AS `Comercial`,`tj`.`CodigoTrabajador` AS `Jefe` from (((`vn2008`.`Clientes` `c` join `vn2008`.`Trabajadores` `t` on((`t`.`Id_Trabajador` = `c`.`Id_Trabajador`))) join `vn2008`.`jerarquia` on((`vn2008`.`jerarquia`.`worker_id` = `c`.`Id_Trabajador`))) join `vn2008`.`Trabajadores` `tj` on((`tj`.`Id_Trabajador` = `vn2008`.`jerarquia`.`boss_id`))) */; -/*!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 `v_ventas_contables` --- - -/*!50001 DROP VIEW IF EXISTS `v_ventas_contables`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `v_ventas_contables` AS select `vn2008`.`time`.`year` AS `year`,`vn2008`.`time`.`month` AS `month`,cast(sum((((`m`.`Cantidad` * `m`.`Preu`) * (100 - `m`.`Descuento`)) / 100)) as decimal(10,0)) AS `importe` from (((`vn2008`.`Tickets` `t` join `bi`.`f_tvc` on((`t`.`Id_Ticket` = `bi`.`f_tvc`.`Id_Ticket`))) join `vn2008`.`Movimientos` `m` on((`t`.`Id_Ticket` = `m`.`Id_Ticket`))) join `vn2008`.`time` on((`vn2008`.`time`.`date` = cast(`t`.`Fecha` as date)))) where (`t`.`Fecha` >= '2014-01-01') group by `vn2008`.`time`.`year`,`vn2008`.`time`.`month` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Current Database: `pbx` --- - -USE `pbx`; - --- --- Final view structure for view `cdrConf` --- - -/*!50001 DROP VIEW IF EXISTS `cdrConf`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `cdrConf` AS select `c`.`call_date` AS `calldate`,`c`.`clid` AS `clid`,`c`.`src` AS `src`,`c`.`dst` AS `dst`,`c`.`dcontext` AS `dcontext`,`c`.`channel` AS `channel`,`c`.`dst_channel` AS `dstchannel`,`c`.`last_app` AS `lastapp`,`c`.`last_data` AS `lastdata`,`c`.`duration` AS `duration`,`c`.`billsec` AS `billsec`,`c`.`disposition` AS `disposition`,`c`.`ama_flags` AS `amaflags`,`c`.`account_code` AS `accountcode`,`c`.`unique_id` AS `uniqueid`,`c`.`user_field` AS `userfield` from `cdr` `c` */; -/*!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 `followmeConf` --- - -/*!50001 DROP VIEW IF EXISTS `followmeConf`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `followmeConf` AS select `f`.`extension` AS `name`,`c`.`music` AS `music`,`c`.`context` AS `context`,`c`.`takeCall` AS `takecall`,`c`.`declineCall` AS `declinecall` from (`followme` `f` join `followmeConfig` `c`) */; -/*!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 `followmeNumberConf` --- - -/*!50001 DROP VIEW IF EXISTS `followmeNumberConf`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `followmeNumberConf` AS select `f`.`extension` AS `name`,1 AS `ordinal`,`f`.`phone` AS `phonenumber`,`c`.`timeout` AS `timeout` from (`followme` `f` join `followmeConfig` `c`) */; -/*!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 `queueConf` --- - -/*!50001 DROP VIEW IF EXISTS `queueConf`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `queueConf` AS select `q`.`name` AS `name`,`c`.`strategy` AS `strategy`,`c`.`timeout` AS `timeout`,`c`.`retry` AS `retry`,`c`.`weight` AS `weight`,`c`.`maxLen` AS `maxlen`,`c`.`ringInUse` AS `ringinuse` from (`queue` `q` join `queueConfig` `c` on((`q`.`config` = `c`.`id`))) */; -/*!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 `queueMemberConf` --- - -/*!50001 DROP VIEW IF EXISTS `queueMemberConf`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `queueMemberConf` AS select `m`.`id` AS `uniqueid`,`m`.`queue` AS `queue_name`,concat('SIP/',`m`.`extension`) AS `interface` from `queueMember` `m` union all select `p`.`id` AS `id`,`p`.`queue` AS `queue`,concat('Local/',`p`.`phone`,'@outgoing') AS `phone` from `queuePhone` `p` */; -/*!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 `sipConf` --- - -/*!50001 DROP VIEW IF EXISTS `sipConf`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `sipConf` AS select `s`.`user_id` AS `id`,`s`.`extension` AS `name`,`s`.`secret` AS `secret`,`s`.`caller_id` 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`.`careInvite` AS `careinvite`,`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 ((`sip` `s` left join `sipReg` `r` on((`s`.`user_id` = `r`.`userId`))) join `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 */; - --- --- Current Database: `cache` --- - -USE `cache`; - --- --- Current Database: `salix` --- - -USE `salix`; - --- --- Final view structure for view `Account` --- - -/*!50001 DROP VIEW IF EXISTS `Account`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Account` AS select `u`.`id` AS `id`,`u`.`name` AS `name`,`u`.`password` AS `password`,`u`.`role` AS `roleFk`,`u`.`active` AS `active`,`u`.`email` AS `email`,`u`.`created` AS `created`,`u`.`updated` AS `updated` from `account`.`user` `u` */; -/*!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 `Accounting` --- - -/*!50001 DROP VIEW IF EXISTS `Accounting`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Accounting` AS select `b`.`Id_Banco` AS `id`,`b`.`Banco` AS `bank`,`b`.`Cuenta` AS `account`,`b`.`cash` AS `accountingTypeFk`,`b`.`entity_id` AS `entityFk`,`b`.`activo` AS `isActive` from `vn2008`.`Bancos` `b` */; -/*!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 `Address` --- - -/*!50001 DROP VIEW IF EXISTS `Address`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Address` AS select `a`.`id_consigna` AS `id`,`a`.`consignatario` AS `consignee`,`a`.`domicilio` AS `street`,`a`.`poblacion` AS `city`,`a`.`codPostal` AS `postcode`,`a`.`province_id` AS `provinceFk`,`a`.`telefono` AS `phone`,`a`.`movil` AS `mobile`,`a`.`active` AS `isEnabled`,`a`.`predeterminada` AS `isDefaultAddress`,`a`.`Id_cliente` AS `clientFk`,`a`.`Id_Agencia` AS `defaultAgencyFk`,`a`.`longitude` AS `longitude`,`a`.`latitude` AS `latitude`,`a`.`isEqualizated` AS `isEqualizated` from `vn2008`.`Consignatarios` `a` */; -/*!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 `Agency` --- - -/*!50001 DROP VIEW IF EXISTS `Agency`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Agency` AS select `a`.`agency_id` AS `id`,`a`.`name` AS `name`,`a`.`warehouse_id` AS `warehouseFk`,`a`.`por_volumen` AS `isVolumetric`,`a`.`Id_Banco` AS `bankFk`,`a`.`warehouse_alias_id` AS `warehouseAliasFk` from `vn2008`.`agency` `a` */; -/*!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 `AgencyMode` --- - -/*!50001 DROP VIEW IF EXISTS `AgencyMode`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `AgencyMode` AS select `a`.`Id_Agencia` AS `id`,`a`.`Agencia` AS `name`,`a`.`description` AS `description`,`a`.`Vista` AS `agencyTypeFk`,`a`.`m3` AS `m3`,`a`.`agency_id` AS `agencyFk`,`a`.`inflacion` AS `inflation`,`a`.`send_mail` AS `sendMailTo`,`a`.`tpv` AS `isForTicket` from `vn2008`.`Agencias` `a` */; -/*!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 `Bank` --- - -/*!50001 DROP VIEW IF EXISTS `Bank`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Bank` AS select `b`.`Id_Banco` AS `id`,`b`.`Banco` AS `bank`,`b`.`Cuenta` AS `account`,`b`.`cash` AS `cash`,`b`.`entity_id` AS `entityFk`,`b`.`activo` AS `isActive` from `vn2008`.`Bancos` `b` */; -/*!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 `City` --- - -/*!50001 DROP VIEW IF EXISTS `City`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `City` AS select `c`.`city_id` AS `id`,`c`.`name` AS `name`,`c`.`province_id` AS `provinceFk` from `vn2008`.`city` `c` */; -/*!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 `Client` --- - -/*!50001 DROP VIEW IF EXISTS `Client`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Client` AS select `c`.`id_cliente` AS `id`,`c`.`cliente` AS `name`,`c`.`if` AS `fi`,`c`.`razonSocial` AS `socialName`,`c`.`contacto` AS `contact`,`c`.`domicilio` AS `street`,`c`.`poblacion` AS `city`,`c`.`codPostal` AS `postcode`,`c`.`province_id` AS `provinceFk`,`c`.`Id_Pais` AS `countryFk`,`c`.`e-mail` AS `email`,`c`.`telefono` AS `phone`,`c`.`movil` AS `mobile`,`c`.`fax` AS `fax`,`c`.`activo` AS `active`,`c`.`descuento` AS `discount`,`c`.`credito` AS `credit`,`c`.`creditInsurance` AS `creditInsurance`,`c`.`iban` AS `iban`,`c`.`vencimiento` AS `dueDay`,`c`.`RE` AS `equalizationTax`,`c`.`invoice` AS `hasToInvoice`,`c`.`mail` AS `invoiceByEmail`,`c`.`pay_met_id` AS `payMethodFk`,`c`.`Id_Trabajador` AS `salesPersonFk`,`c`.`chanel_id` AS `contactChannelFk`,`c`.`sepaVnl` AS `sepaVnl`,`c`.`coreVnl` AS `coreVnl`,`c`.`coreVnh` AS `coreVnh`,`c`.`EYPBC` AS `eypbc`,`c`.`calidad` AS `quality`,`c`.`vies` AS `vies`,`c`.`real` AS `isRelevant`,`c`.`clientes_tipo_id` AS `typeFk`,`c`.`Cuenta` AS `accountingAccount`,`c`.`created` AS `created`,`c`.`invoiceByAddress` AS `hasToInvoiceByAddress` from `vn2008`.`Clientes` `c` */; -/*!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 `ClientCredit` --- - -/*!50001 DROP VIEW IF EXISTS `ClientCredit`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ClientCredit` AS select `c`.`id` AS `id`,`c`.`Id_Cliente` AS `clientFk`,`c`.`Id_Trabajador` AS `employeeFk`,`c`.`amount` AS `amount`,`c`.`odbc_date` AS `created` from `vn2008`.`credit` `c` */; -/*!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 `ClientCreditLimit` --- - -/*!50001 DROP VIEW IF EXISTS `ClientCreditLimit`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ClientCreditLimit` AS select `l`.`id` AS `id`,`l`.`maxAmount` AS `maxAmount`,`l`.`roleFk` AS `roleFk` from `vn`.`clientCreditLimit` `l` */; -/*!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 `ClientObservation` --- - -/*!50001 DROP VIEW IF EXISTS `ClientObservation`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ClientObservation` AS select `o`.`client_observation_id` AS `id`,`o`.`Id_Cliente` AS `clientFk`,`o`.`Id_Trabajador` AS `employeeFk`,`o`.`text` AS `text`,`o`.`odbc_date` AS `created` from `vn2008`.`client_observation` `o` */; -/*!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 `ClientType` --- - -/*!50001 DROP VIEW IF EXISTS `ClientType`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ClientType` AS select `ct`.`clientes_tipo_id` AS `id`,`ct`.`code` AS `code`,`ct`.`tipo` AS `type` from `vn2008`.`clientes_tipo` `ct` */; -/*!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 `ContactChannel` --- - -/*!50001 DROP VIEW IF EXISTS `ContactChannel`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `ContactChannel` AS select `c`.`chanel_id` AS `id`,`c`.`name` AS `name` from `vn2008`.`chanel` `c` */; -/*!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 `Country` --- - -/*!50001 DROP VIEW IF EXISTS `Country`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Country` AS select `c`.`Id` AS `id`,`c`.`Pais` AS `name`,`c`.`CEE` AS `inCee`,`c`.`Codigo` AS `code`,`c`.`Id_Moneda` AS `currencyFk`,`c`.`Id_Paisreal` AS `realCountryFk` from `vn2008`.`Paises` `c` */; -/*!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 `CreditClassification` --- - -/*!50001 DROP VIEW IF EXISTS `CreditClassification`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `CreditClassification` AS select `vn`.`creditClassification`.`id` AS `id`,`vn`.`creditClassification`.`client` AS `clientFk`,`vn`.`creditClassification`.`dateStart` AS `started`,`vn`.`creditClassification`.`dateEnd` AS `ended` from `vn`.`creditClassification` */; -/*!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 `Delivery` --- - -/*!50001 DROP VIEW IF EXISTS `Delivery`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Delivery` AS select `r`.`Id_Ruta` AS `id`,`r`.`Fecha` AS `date`,`r`.`m3` AS `m3`,`t`.`warehouse_id` AS `warehouseFk` from (`vn2008`.`Rutas` `r` join `vn2008`.`Tickets` `t` on((`r`.`Id_Ruta` = `t`.`Id_Ruta`))) where (`r`.`Fecha` = curdate()) group by `r`.`Id_Ruta` */; -/*!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 `Employee` --- - -/*!50001 DROP VIEW IF EXISTS `Employee`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Employee` AS select `e`.`Id_Trabajador` AS `id`,`e`.`Nombre` AS `name`,`e`.`Apellidos` AS `surname`,`e`.`user_id` AS `userFk` from `vn2008`.`Trabajadores` `e` */; -/*!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 `PayMethod` --- - -/*!50001 DROP VIEW IF EXISTS `PayMethod`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `PayMethod` AS select `m`.`id` AS `id`,`m`.`name` AS `name`,`m`.`graceDays` AS `graceDays`,`m`.`deudaviva` AS `outstandingDebt`,`m`.`ibanRequired` AS `ibanRequired` from `vn2008`.`pay_met` `m` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `Province` --- - -/*!50001 DROP VIEW IF EXISTS `Province`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Province` AS select `p`.`province_id` AS `id`,`p`.`name` AS `name`,`p`.`Paises_Id` AS `countryFk`,`p`.`warehouse_id` AS `warehouseFk`,`p`.`zone` AS `zoneFk` from `vn2008`.`province` `p` */; -/*!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 `Role` --- - -/*!50001 DROP VIEW IF EXISTS `Role`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Role` AS select `r`.`id` AS `id`,`r`.`name` AS `name`,`r`.`description` AS `description`,`r`.`created` AS `created`,`r`.`modified` AS `modified` from `account`.`role` `r` */; -/*!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 `RoleMapping` --- - -/*!50001 DROP VIEW IF EXISTS `RoleMapping`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `RoleMapping` AS select ((`u`.`id` * 1000) + `r`.`inheritsFrom`) AS `id`,'USER' AS `principalType`,`u`.`id` AS `principalId`,`r`.`inheritsFrom` AS `roleId` from (`account`.`user` `u` join `account`.`roleRole` `r` on((`r`.`role` = `u`.`role`))) */; -/*!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 `Route` --- - -/*!50001 DROP VIEW IF EXISTS `Route`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Route` AS select `r`.`Id_Ruta` AS `id`,`r`.`Fecha` AS `date` from `vn2008`.`Rutas` `r` */; -/*!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 `State` --- - -/*!50001 DROP VIEW IF EXISTS `State`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `State` AS select `s`.`id` AS `id`,`s`.`name` AS `name`,`s`.`order` AS `order`,`s`.`alert_level` AS `alertLevel`,`s`.`code` AS `code` from `vn2008`.`state` `s` */; -/*!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 `Ticket` --- - -/*!50001 DROP VIEW IF EXISTS `Ticket`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Ticket` AS select `t`.`Id_Ticket` AS `id`,`t`.`Id_Agencia` AS `agencyFk`,`t`.`Id_Trabajador` AS `employeeFk`,`t`.`Fecha` AS `date`,`t`.`Hora` AS `hour`,`t`.`Id_Cliente` AS `clientFk` from `vn2008`.`Tickets` `t` */; -/*!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 `TicketState` --- - -/*!50001 DROP VIEW IF EXISTS `TicketState`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `TicketState` AS select `i`.`inter_id` AS `id`,`i`.`Id_Ticket` AS `ticketFk`,`i`.`state_id` AS `stateFk`,`i`.`Id_Trabajador` AS `employeeFk`,`i`.`odbc_date` AS `updated` from `vncontrol`.`inter` `i` */; -/*!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 `Vehicle` --- - -/*!50001 DROP VIEW IF EXISTS `Vehicle`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Vehicle` AS select `v`.`Id_Vehiculo` AS `id`,`v`.`Matricula` AS `numberPlate`,`v`.`Marca` AS `tradeMark`,`v`.`Modelo` AS `model`,`v`.`empresa_id` AS `companyFk`,`v`.`warehouseFk` AS `warehouseFk`,`v`.`description` AS `description`,`v`.`m3` AS `m3`,`v`.`active` AS `isActive` from `vn2008`.`Vehiculos` `v` */; -/*!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 `Warehouse` --- - -/*!50001 DROP VIEW IF EXISTS `Warehouse`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Warehouse` AS select `w`.`id` AS `id`,`w`.`name` AS `name`,`w`.`tpv` AS `tpv`,`w`.`inventario` AS `inventory`,`w`.`isManaged` AS `isManaged` from `vn2008`.`warehouse` `w` */; -/*!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 `WarehouseAlias` --- - -/*!50001 DROP VIEW IF EXISTS `WarehouseAlias`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `WarehouseAlias` AS select `wa`.`warehouse_alias_id` AS `id`,`wa`.`alias` AS `name` from `vn2008`.`warehouse_alias` `wa` */; -/*!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 `Worker` --- - -/*!50001 DROP VIEW IF EXISTS `Worker`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Worker` AS select `e`.`Id_Trabajador` AS `id`,`e`.`Nombre` AS `name`,`e`.`Apellidos` AS `surname`,`e`.`user_id` AS `userFk` from `vn2008`.`Trabajadores` `e` */; -/*!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 `Zone` --- - -/*!50001 DROP VIEW IF EXISTS `Zone`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `Zone` AS select `z`.`zone_id` AS `id`,`z`.`name` AS `name`,`z`.`printingOrder` AS `printingOrder` from `vn2008`.`zones` `z` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Current Database: `vncontrol` --- - -USE `vncontrol`; - --- --- Current Database: `hedera` --- - -USE `hedera`; - --- --- Final view structure for view `address_view` --- - -/*!50001 DROP VIEW IF EXISTS `address_view`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `address_view` AS select `a`.`id_consigna` AS `id`,`a`.`Id_cliente` AS `customer_id`,`a`.`warehouse_id` AS `warehouse_id`,`a`.`domicilio` AS `name`,`a`.`poblacion` AS `city`,`a`.`province_id` AS `province_id`,`a`.`codPostal` AS `zip_code`,`a`.`consignatario` AS `consignee`,`a`.`predeterminada` AS `default`,`a`.`Id_Agencia` AS `type_id`,`a`.`especificaciones` AS `specs`,`a`.`seguro` AS `insurance`,`a`.`porte` AS `postage`,`a`.`active` AS `active` from `vn2008`.`Consignatarios` `a` where (`a`.`Id_cliente` = `account`.`userGetId`()) */ -/*!50002 WITH CASCADED CHECK OPTION */; -/*!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 `basket` --- - -/*!50001 DROP VIEW IF EXISTS `basket`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `basket` AS select `o`.`id` AS `id`,`o`.`date_make` AS `date_make`,`o`.`date_send` AS `date_send`,`o`.`customer_id` AS `customer_id`,`o`.`delivery_method_id` AS `delivery_method_id`,`o`.`agency_id` AS `agency_id`,`o`.`address_id` AS `address_id`,`o`.`company_id` AS `company_id`,`o`.`note` AS `note` from `hedera`.`order` `o` where (`o`.`id` = `basketGetId`()) */ -/*!50002 WITH CASCADED CHECK OPTION */; -/*!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 `basket_defaults` --- - -/*!50001 DROP VIEW IF EXISTS `basket_defaults`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `basket_defaults` AS select `c`.`defaultAddressFk` AS `address_id`,`ad`.`agencyModeFk` AS `agency_id`,`m`.`code` AS `delivery_method` from (((`vn`.`client` `c` left join `vn`.`address` `ad` on((`ad`.`id` = `c`.`defaultAddressFk`))) join `vn`.`agencyMode` `a` on((`a`.`id` = `ad`.`agencyModeFk`))) join `vn`.`deliveryMethod` `m` on((`m`.`id` = `a`.`deliveryMethodFk`))) where (`c`.`id` = `account`.`userGetId`()) */; -/*!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 `basket_item` --- - -/*!50001 DROP VIEW IF EXISTS `basket_item`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `basket_item` AS select `r`.`id` AS `id`,`r`.`orderFk` AS `order_id`,`r`.`warehouseFk` AS `warehouse_id`,`r`.`itemFk` AS `item_id`,`r`.`amount` AS `amount`,`r`.`price` AS `price` from `hedera`.`orderRow` `r` where (`r`.`orderFk` = `BASKETGETID`()) */ -/*!50002 WITH CASCADED CHECK OPTION */; -/*!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 `customer_view` --- - -/*!50001 DROP VIEW IF EXISTS `customer_view`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `customer_view` AS select `c`.`id_cliente` AS `user_id`,`c`.`cliente` AS `name`,`c`.`e-mail` AS `email`,`c`.`mail` AS `mail`,`c`.`default_address` AS `default_address`,`c`.`credito` AS `credit` from `vn2008`.`Clientes` `c` where (`c`.`id_cliente` = `account`.`userGetId`()) */ -/*!50002 WITH CASCADED CHECK OPTION */; -/*!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 `invoice_view` --- - -/*!50001 DROP VIEW IF EXISTS `invoice_view`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `invoice_view` AS select `i`.`factura_id` AS `invoice_id`,`i`.`Id_Factura` AS `serial_num`,`i`.`Fecha` AS `issued`,`i`.`Importe` AS `amount` from `vn2008`.`Facturas` `i` where ((`i`.`Id_Cliente` = `account`.`userGetId`()) and `i`.`pdf`) */; -/*!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 `myAddress` --- - -/*!50001 DROP VIEW IF EXISTS `myAddress`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `myAddress` AS select `t`.`id` AS `id`,`t`.`clientFk` AS `clientFk`,`t`.`street` AS `street`,`t`.`city` AS `city`,`t`.`postalCode` AS `postalCode`,`t`.`provinceFk` AS `provinceFk`,`t`.`nickname` AS `nickname`,`t`.`isDefaultAddress` AS `isDefaultAddress`,`t`.`isActive` AS `isActive`,`t`.`longitude` AS `longitude`,`t`.`latitude` AS `latitude`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`agencyModeFk` AS `agencyModeFk` from `vn`.`address` `t` where (`t`.`clientFk` = `account`.`userGetId`()) */ -/*!50002 WITH CASCADED CHECK OPTION */; -/*!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 `myClient` --- - -/*!50001 DROP VIEW IF EXISTS `myClient`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `myClient` AS select `c`.`id` AS `id`,`c`.`isToBeMailed` AS `isToBeMailed`,`c`.`defaultAddressFk` AS `defaultAddressFk`,`c`.`credit` AS `credit` from `vn`.`client` `c` where (`c`.`id` = `account`.`userGetId`()) */ -/*!50002 WITH CASCADED CHECK OPTION */; -/*!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 `myInvoice` --- - -/*!50001 DROP VIEW IF EXISTS `myInvoice`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `myInvoice` AS select `i`.`id` AS `id`,`i`.`ref` AS `ref`,`i`.`issued` AS `issued`,`i`.`amount` AS `amount` from `vn`.`invoiceOut` `i` where ((`i`.`clientFk` = `account`.`userGetId`()) and `i`.`pdf`) */; -/*!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 `myMenu` --- - -/*!50001 DROP VIEW IF EXISTS `myMenu`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `myMenu` AS select `t`.`id` AS `id`,`t`.`path` AS `path`,`t`.`description` AS `description`,`t`.`parentFk` AS `parentFk` from (`hedera`.`menu` `t` join `account`.`userRole` `r` on((`r`.`id` = `t`.`roleFk`))) order by `t`.`parentFk`,`t`.`displayOrder`,`t`.`id` */; -/*!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 `myTicket` --- - -/*!50001 DROP VIEW IF EXISTS `myTicket`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `myTicket` AS select `t`.`id` AS `id`,`t`.`clientFk` AS `clientFk`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`shipped` AS `shipped`,`t`.`landed` AS `landed`,`t`.`nickname` AS `nickname`,`t`.`agencyModeFk` AS `agencyModeFk`,`t`.`refFk` AS `refFk`,`t`.`addressFk` AS `addressFk`,`t`.`location` AS `location`,`t`.`companyFk` AS `companyFk` from `vn`.`ticket` `t` where (`t`.`clientFk` = `account`.`userGetId`()) */; -/*!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 `myTicketRow` --- - -/*!50001 DROP VIEW IF EXISTS `myTicketRow`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `myTicketRow` AS select `s`.`id` AS `id`,`s`.`itemFk` AS `itemFk`,`s`.`ticketFk` AS `ticketFk`,`s`.`concept` AS `concept`,`s`.`quantity` AS `quantity`,`s`.`price` AS `price`,`s`.`discount` AS `discount`,`s`.`reserved` AS `reserved`,`s`.`isPicked` AS `isPicked` from (`vn`.`sale` `s` join `hedera`.`myTicket` `t` on((`s`.`ticketFk` = `t`.`id`))) */ -/*!50002 WITH CASCADED CHECK OPTION */; -/*!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 `myTpvTransaction` --- - -/*!50001 DROP VIEW IF EXISTS `myTpvTransaction`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `myTpvTransaction` AS select `t`.`id` AS `id`,`t`.`merchantFk` AS `merchantFk`,`t`.`clientFk` AS `clientFk`,`t`.`receiptFk` AS `receiptFk`,`t`.`amount` AS `amount`,`t`.`response` AS `response`,`t`.`status` AS `status`,`t`.`created` AS `created` from `hedera`.`tpvTransaction` `t` where (`t`.`clientFk` = `account`.`userGetId`()) */; -/*!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 `order_basket` --- - -/*!50001 DROP VIEW IF EXISTS `order_basket`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `order_basket` AS select `t`.`clientFk` AS `customer_id`,`t`.`orderFk` AS `order_id` from `basketOrder` `t` */; -/*!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 `order_component` --- - -/*!50001 DROP VIEW IF EXISTS `order_component`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `order_component` AS select `t`.`rowFk` AS `order_row_id`,`t`.`componentFk` AS `component_id`,`t`.`price` AS `price` from `orderRowComponent` `t` */; -/*!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 `order_confirm_time` --- - -/*!50001 DROP VIEW IF EXISTS `order_confirm_time`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `order_confirm_time` AS select `o`.`date_make` AS `date_make`,`o`.`source_app` AS `source_app`,`o`.`customer_id` AS `customer_id`,`o`.`confirm_date` AS `confirm_date`,`o`.`first_row_stamp` AS `first_row_stamp`,(ceiling((((unix_timestamp(`o`.`confirm_date`) - unix_timestamp(`o`.`first_row_stamp`)) / 60) / 5)) * 5) AS `minutos` from `order` `o` where ((`o`.`confirm_date` is not null) and (`o`.`first_row_stamp` is not null)) */; -/*!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 `order_row` --- - -/*!50001 DROP VIEW IF EXISTS `order_row`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `order_row` AS select `t`.`id` AS `id`,`t`.`orderFk` AS `order_id`,`t`.`itemFk` AS `item_id`,`t`.`warehouseFk` AS `warehouse_id`,`t`.`shipment` AS `shipment`,`t`.`amount` AS `amount`,`t`.`price` AS `price`,`t`.`rate` AS `rate`,`t`.`created` AS `created`,`t`.`saleFk` AS `Id_Movimiento` from `orderRow` `t` */; -/*!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 `order_row_view` --- - -/*!50001 DROP VIEW IF EXISTS `order_row_view`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `order_row_view` AS select `r`.`id` AS `id`,`r`.`order_id` AS `order_id`,`r`.`warehouse_id` AS `warehouse_id`,`r`.`item_id` AS `item_id`,`r`.`amount` AS `amount`,`r`.`price` AS `price2` from `hedera`.`order_row` `r` where `r`.`order_id` in (select `order_view`.`id` AS `id` from `hedera`.`order_view`) */ -/*!50002 WITH CASCADED CHECK OPTION */; -/*!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 `order_view` --- - -/*!50001 DROP VIEW IF EXISTS `order_view`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `order_view` AS select `o`.`id` AS `id`,`o`.`date_make` AS `date_make`,`o`.`date_send` AS `date_send`,`o`.`customer_id` AS `customer_id`,`o`.`delivery_method_id` AS `delivery_method_id`,`o`.`agency_id` AS `agency_id`,`o`.`note` AS `note`,`o`.`address_id` AS `address_id`,`o`.`company_id` AS `company_id` from `hedera`.`order` `o` where ((`o`.`customer_id` = `account`.`userGetId`()) and (`o`.`is_bionic` = 0)) */; -/*!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 `user_android` --- - -/*!50001 DROP VIEW IF EXISTS `user_android`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `user_android` AS select `t`.`androidId` AS `android_id`,`t`.`userFk` AS `user_id` from `androidUser` `t` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Current Database: `stock` --- - -USE `stock`; -/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; - -/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; -/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; -/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; -/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; -/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; -/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; -/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; - --- Dump completed on 2018-03-12 7:44:03 diff --git a/services/db/02-dumpedFixtures.sql b/services/db/02-dumpedFixtures.sql deleted file mode 100644 index fceffb3e4..000000000 --- a/services/db/02-dumpedFixtures.sql +++ /dev/null @@ -1,154 +0,0 @@ -USE `account`; --- MySQL dump 10.13 Distrib 5.7.17, for Win64 (x86_64) --- --- Host: db.verdnatura.es Database: account --- ------------------------------------------------------ --- Server version 5.6.25-4-log - -/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; -/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; -/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; -/*!40101 SET NAMES utf8 */; -/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; -/*!40103 SET TIME_ZONE='+00:00' */; -/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; -/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; -/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; - --- --- Dumping data for table `role` --- - -LOCK TABLES `role` WRITE; -/*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (0,'root','Rol con todos los privilegios',0,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31'),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35'),(13,'teamBoss','Jefe de departamento',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10'),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27'),(20,'manager','Departamento de gerencia',1,'2017-06-01 14:57:02','2017-06-01 14:57:51'),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52'),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12'),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36'),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27'),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20'),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34'),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53'),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42'),(36,'replenisher','Trabajadores de camara',0,'2018-02-16 14:07:10','2018-02-23 13:30:32'),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53'),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09'),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41'),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12'),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26'),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59'),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16'),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12'),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23'),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18'),(48,'coolerBoss','Jefe del departamento de cámara',1,'2018-02-23 13:12:01','2018-02-23 13:12:01'),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2018-02-26 15:28:23'),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12'),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39'),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57'),(53,'creditInsurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2018-03-05 07:44:35'),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17'),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31'); -/*!40000 ALTER TABLE `role` ENABLE KEYS */; -UNLOCK TABLES; - --- --- Dumping data for table `roleRole` --- - -LOCK TABLES `roleRole` WRITE; -/*!40000 ALTER TABLE `roleRole` DISABLE KEYS */; -INSERT INTO `roleRole` VALUES (0,0),(0,1),(0,2),(0,3),(0,5),(0,6),(0,9),(0,11),(0,13),(0,15),(0,16),(0,17),(0,18),(0,19),(0,20),(0,21),(0,22),(0,30),(0,31),(0,32),(0,33),(0,34),(0,35),(0,36),(0,37),(0,38),(0,39),(0,40),(0,41),(0,42),(0,43),(0,44),(0,45),(0,47),(0,48),(0,49),(0,50),(0,51),(0,52),(0,53),(0,54),(0,55),(1,1),(1,2),(1,3),(1,6),(1,11),(2,2),(2,6),(2,11),(3,3),(3,6),(3,11),(5,1),(5,2),(5,3),(5,5),(5,6),(5,11),(5,13),(5,18),(5,19),(5,21),(5,33),(5,53),(6,6),(9,0),(9,1),(9,2),(9,3),(9,5),(9,6),(9,9),(9,11),(9,13),(9,15),(9,16),(9,17),(9,18),(9,19),(9,20),(9,21),(9,22),(9,30),(9,31),(9,32),(9,33),(9,34),(9,35),(9,36),(9,37),(9,38),(9,39),(9,40),(9,41),(9,42),(9,43),(9,44),(9,45),(9,47),(9,48),(9,49),(9,50),(9,51),(9,52),(9,53),(9,54),(9,55),(11,6),(11,11),(13,1),(13,2),(13,3),(13,6),(13,11),(13,13),(15,1),(15,2),(15,3),(15,6),(15,11),(15,15),(15,35),(16,1),(16,2),(16,3),(16,6),(16,11),(16,13),(16,15),(16,16),(16,35),(17,1),(17,2),(17,3),(17,5),(17,6),(17,11),(17,13),(17,17),(17,18),(17,19),(17,20),(17,21),(17,33),(17,37),(17,39),(17,53),(18,1),(18,2),(18,3),(18,6),(18,11),(18,18),(19,1),(19,2),(19,3),(19,6),(19,11),(19,13),(19,18),(19,19),(19,21),(19,53),(20,1),(20,2),(20,3),(20,6),(20,11),(20,13),(20,20),(21,1),(21,2),(21,3),(21,6),(21,11),(21,13),(21,18),(21,21),(21,53),(22,1),(22,2),(22,3),(22,6),(22,11),(22,13),(22,18),(22,21),(22,22),(22,53),(30,1),(30,2),(30,3),(30,5),(30,6),(30,11),(30,13),(30,18),(30,19),(30,20),(30,21),(30,22),(30,30),(30,33),(30,53),(31,1),(31,2),(31,3),(31,6),(31,11),(31,31),(32,1),(32,2),(32,3),(32,6),(32,11),(32,32),(33,33),(34,1),(34,2),(34,3),(34,6),(34,11),(34,13),(34,33),(34,34),(35,1),(35,2),(35,3),(35,6),(35,11),(35,35),(36,1),(36,2),(36,3),(36,6),(36,11),(36,36),(36,44),(36,47),(37,1),(37,2),(37,3),(37,6),(37,11),(37,37),(38,1),(38,2),(38,3),(38,6),(38,11),(38,37),(38,38),(39,1),(39,2),(39,3),(39,5),(39,6),(39,11),(39,13),(39,18),(39,19),(39,21),(39,33),(39,39),(39,53),(40,1),(40,2),(40,3),(40,6),(40,11),(40,40),(41,1),(41,2),(41,3),(41,6),(41,11),(41,13),(41,40),(41,41),(42,1),(42,2),(42,3),(42,6),(42,11),(42,42),(43,1),(43,2),(43,3),(43,6),(43,11),(43,13),(43,42),(43,43),(44,1),(44,2),(44,3),(44,6),(44,11),(44,44),(45,1),(45,2),(45,3),(45,6),(45,11),(45,13),(45,44),(45,45),(47,1),(47,2),(47,3),(47,6),(47,11),(47,47),(48,1),(48,2),(48,3),(48,6),(48,11),(48,13),(48,47),(48,48),(49,1),(49,2),(49,3),(49,6),(49,11),(49,36),(49,44),(49,47),(49,49),(50,1),(50,2),(50,3),(50,6),(50,11),(50,13),(50,36),(50,44),(50,47),(50,49),(50,50),(51,1),(51,2),(51,3),(51,6),(51,11),(51,51),(52,1),(52,2),(52,3),(52,6),(52,11),(52,13),(52,51),(52,52),(53,1),(53,2),(53,3),(53,6),(53,11),(53,53),(54,1),(54,2),(54,3),(54,6),(54,11),(54,54),(55,1),(55,2),(55,3),(55,6),(55,11),(55,13),(55,54),(55,55); -/*!40000 ALTER TABLE `roleRole` ENABLE KEYS */; -UNLOCK TABLES; - --- --- Dumping data for table `roleInherit` --- - -LOCK TABLES `roleInherit` WRITE; -/*!40000 ALTER TABLE `roleInherit` DISABLE KEYS */; -INSERT INTO `roleInherit` VALUES (9,0),(5,1),(13,1),(18,1),(31,1),(32,1),(34,1),(35,1),(37,1),(40,1),(42,1),(44,1),(47,1),(51,1),(53,1),(54,1),(1,2),(1,3),(30,5),(39,5),(11,6),(1,11),(2,11),(3,11),(16,13),(20,13),(21,13),(22,13),(34,13),(41,13),(43,13),(45,13),(48,13),(50,13),(52,13),(55,13),(16,15),(21,18),(5,19),(17,20),(30,20),(19,21),(22,21),(39,21),(30,22),(5,33),(34,33),(15,35),(49,36),(17,37),(38,37),(17,39),(41,40),(43,42),(36,44),(45,44),(36,47),(48,47),(50,49),(52,51),(21,53),(30,53),(55,54); -/*!40000 ALTER TABLE `roleInherit` ENABLE KEYS */; -UNLOCK TABLES; -/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; - -/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; -/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; -/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; -/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; -/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; -/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; -/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; - --- Dump completed on 2018-03-07 9:44:56 -USE `salix`; --- MySQL dump 10.13 Distrib 5.7.17, for Win64 (x86_64) --- --- Host: db.verdnatura.es Database: salix --- ------------------------------------------------------ --- Server version 5.6.25-4-log - -/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; -/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; -/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; -/*!40101 SET NAMES utf8 */; -/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; -/*!40103 SET TIME_ZONE='+00:00' */; -/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; -/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; -/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; - --- --- Dumping data for table `ACL` --- - -LOCK TABLES `ACL` WRITE; -/*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','employee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','employee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','employee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','employee'),(28,'ClientObservation','*','READ','ALLOW','ROLE','employee'),(30,'GreugeType','*','READ','ALLOW','ROLE','employee'),(31,'Mandate','*','READ','ALLOW','ROLE','employee'),(32,'MandateType','*','READ','ALLOW','ROLE','employee'),(33,'Company','*','READ','ALLOW','ROLE','employee'),(34,'Greuge','*','READ','ALLOW','ROLE','employee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(52,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','employee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(57,'CreditClassification','*','READ','ALLOW','ROLE','employee'),(58,'CreditClassification','*','WRITE','ALLOW','ROLE','creditInsurance'),(59,'CreditInsurance','*','READ','ALLOW','ROLE','employee'),(60,'CreditInsurance','*','WRITE','ALLOW','ROLE','creditInsurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'); -/*!40000 ALTER TABLE `ACL` ENABLE KEYS */; -UNLOCK TABLES; -/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; - -/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; -/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; -/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; -/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; -/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; -/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; -/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; - --- Dump completed on 2018-03-07 9:44:57 -USE `vn`; --- MySQL dump 10.13 Distrib 5.7.17, for Win64 (x86_64) --- --- Host: db.verdnatura.es Database: vn --- ------------------------------------------------------ --- Server version 5.6.25-4-log - -/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; -/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; -/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; -/*!40101 SET NAMES utf8 */; -/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; -/*!40103 SET TIME_ZONE='+00:00' */; -/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; -/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; -/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; - --- --- Dumping data for table `cplusInvoiceType477` --- - -LOCK TABLES `cplusInvoiceType477` WRITE; -/*!40000 ALTER TABLE `cplusInvoiceType477` DISABLE KEYS */; -INSERT INTO `cplusInvoiceType477` VALUES (1,'F1 - Factura'),(2,'F2 - Factura simplificada (ticket)'),(3,'F3 - Factura emitida en sustitución de facturas simplificadas facturadas y declaradas'),(4,'F4 - Asiento resumen de facturas'),(5,'R1 - Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)'),(6,'R2 - Factura rectificativa (Art. 80.3)'),(7,'R3 - Factura rectificativa (Art. 80.4)'),(8,'R4 - Factura rectificativa (Resto)'),(9,'R5 - Factura rectificativa en facturas simplificadas'); -/*!40000 ALTER TABLE `cplusInvoiceType477` ENABLE KEYS */; -UNLOCK TABLES; - --- --- Dumping data for table `cplusSubjectOp` --- - -LOCK TABLES `cplusSubjectOp` WRITE; -/*!40000 ALTER TABLE `cplusSubjectOp` DISABLE KEYS */; -INSERT INTO `cplusSubjectOp` VALUES (1,'Campo vacio'),(2,'S1 – Sujeta – No exenta'),(3,'S2 – Sujeta – No exenta – Inv. Suj. Pasivo'); -/*!40000 ALTER TABLE `cplusSubjectOp` ENABLE KEYS */; -UNLOCK TABLES; - --- --- Dumping data for table `cplusTaxBreak` --- - -LOCK TABLES `cplusTaxBreak` WRITE; -/*!40000 ALTER TABLE `cplusTaxBreak` DISABLE KEYS */; -INSERT INTO `cplusTaxBreak` VALUES (1,'Campo vacio'),(2,'E1 - Exenta por el artículo 20'),(3,'E2 - Exenta por el artículo 21'),(4,'E3 - Exenta por el artículo 22'),(5,'E4 - Exenta por el artículo 24'),(6,'E5 - Exenta por el artículo 25'),(7,'E6 - Exenta por otros'); -/*!40000 ALTER TABLE `cplusTaxBreak` ENABLE KEYS */; -UNLOCK TABLES; -/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; - -/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; -/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; -/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; -/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; -/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; -/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; -/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; - --- Dump completed on 2018-03-07 9:44:57 diff --git a/services/db/03-changes.sh b/services/db/03-changes.sh deleted file mode 100644 index 0f714b2aa..000000000 --- a/services/db/03-changes.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -for file in changes/*/*.sql; do - echo "Importing $file" - mysql -u root -proot < $file -done diff --git a/services/db/04-fixtures.sql b/services/db/04-fixtures.sql deleted file mode 100644 index 9a8a36e6f..000000000 --- a/services/db/04-fixtures.sql +++ /dev/null @@ -1,483 +0,0 @@ -INSERT INTO `util`.`config` ( `dbVersion`, `hasTriggersDisabled`, `environment`) - VALUES ('1.0.0', '0', 'development'); - -INSERT INTO `account`.`user`(`id`,`name`,`password`,`role`,`active`,`email`) - SELECT id,name, MD5('nightmare'), id, 1, CONCAT(name, '@verdnatura.es') - FROM `account`.`role`; - -INSERT INTO `vn`.`worker`(`id`,`workerCode`, `firstName`, `name`, `userFk`) - SELECT id,UPPER(LPAD(role, 3, '0')), name, name, id - FROM `vn`.`user`; - -DELETE FROM `vn`.`worker` where name ='customer'; - -INSERT INTO `account`.`user`(`id`,`name`,`password`,`role`,`active`,`email`) - VALUES - (101, 'BruceWayne', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'BruceWayne@verdnatura.es'), - (102, 'PetterParker', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'PetterParker@verdnatura.es'), - (103, 'ClarkKent', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'ClarkKent@verdnatura.es'), - (104, 'TonyStark', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'TonyStark@verdnatura.es'), - (105, 'MaxEisenhardt', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'MaxEisenhardt@verdnatura.es'), - (106, 'DavidCharlesHaller', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'DavidCharlesHaller@verdnatura.es'), - (107, 'HankPym', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'HankPym@verdnatura.es'), - (108, 'CharlesXavier', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'CharlesXavier@verdnatura.es'), - (109, 'BruceBanner', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'BruceBanner@verdnatura.es'), - (110, 'JessicaJones', 'ac754a330530832ba1bf7687f577da91', 2, 1, 'JessicaJones@verdnatura.es'); - - INSERT INTO `vn`.`worker`(`workerCode`, `id`, `firstName`, `name`, `userFk`) - VALUES - ('LGN', 106, 'David Charles', 'Haller', 106), - ('ANT', 107, 'Hank', 'Pym', 107), - ('DCX', 108, 'Charles', 'Xavier', 108), - ('HLK', 109, 'Bruce', 'Banner', 109), - ('JJJ', 110, 'Jessica', 'Jones', 110); - -INSERT INTO `vn`.`country`(`id`, `country`, `isUeeMember`, `code`, `currencyFk`) - VALUES - (1, 'España', 0, 'ES', 1), - (2, 'Italia', 1, 'IT', 1), - (3, 'Alemania', 1, 'DE', 1), - (4, 'Rumania', 1, 'RO', 1), - (5, 'Holanda', 1, 'NL', 1), - (30,'Francia', 1, 'FR', 1); - -INSERT INTO `vn`.`warehouse`(`id`, `name`, `isComparative`, `isInventory`, `isManaged`) - VALUES - (1, 'Warehouse One', 0, 1, 1), - (2, 'Warehouse Two', 0, 1, 1), - (3, 'Warehouse Three', 1, 1, 1), - (4, 'Warehouse Four', 1, 1, 1), - (5, 'Warehouse Five', 1, 1, 0); - -INSERT INTO `vn`.`warehouseAlias`(`id`, `name`) - VALUES - (1, 'Main Warehouse'); - -INSERT INTO `vn`.`accountingType`(`id`, `description`) - VALUES - (1, 'Digital money'), - (2, 'Cash'), - (3, 'Card'), - (4, 'Stolen Money'), - (5, 'Miscellaneous'); - -INSERT INTO `vn`.`bank`(`id`, `bank`, `account`, `cash`, `entityFk`, `isActive`) - VALUES - (8, 'Pay on receipt', '0000000000', 4, 0, 1); - -INSERT INTO `vn`.`agency`(`id`, `name`, `warehouseFk`, `isVolumetric`, `bankFk`, `warehouseAliasFk`) - VALUES - (1, 'inhouse pickup', 1, 0, 8, 1), - (2, 'Super-Man delivery', 1, 0, 8, 1), - (3, 'Teleportation device', 1, 0, 8, 1), - (4, 'Entanglement', 1, 0, 8, 1), - (5, 'Quantum break device', 1, 0, 8, 1), - (6, 'Walking', 1, 0, 8, 1); - -UPDATE `vn`.`agencyMode` SET `id` = 1 WHERE `name` = 'inhouse pickup'; -UPDATE `vn`.`agencyMode` SET `id` = 2 WHERE `name` = 'Super-Man delivery'; -UPDATE `vn`.`agencyMode` SET `id` = 3 WHERE `name` = 'Teleportation device'; -UPDATE `vn`.`agencyMode` SET `id` = 4 WHERE `name` = 'Entanglement'; -UPDATE `vn`.`agencyMode` SET `id` = 5 WHERE `name` = 'Quantum break device'; -UPDATE `vn`.`agencyMode` SET `id` = 6 WHERE `name` = 'Walking'; - -INSERT INTO `vn`.`payMethod`(`id`, `name`, `graceDays`, `outstandingDebt`, `ibanRequired`) - VALUES - (1, 'PayMethod one', 0, 001, 0), - (2, 'PayMethod two', 10, 001, 0), - (3, 'PayMethod three', 0, 001, 0), - (4, 'PayMethod with IBAN', 0, 001, 1), - (5, 'PayMethod five', 10, 001, 0); - -INSERT INTO `vn2008`.`zones`(`zone_id`, `name`, `printingOrder`) - VALUES - (1, 'zone one', 1), - (2, 'zone two', 2), - (3, 'zone three', 3); - -INSERT INTO `vn`.`province`(`id`, `name`, `countryFk`, `warehouseFk`, `zoneFk`) - VALUES - (1, 'Province one', 1, NULL, 1), - (2, 'Province two', 1, NULL, 2), - (3, 'Province three', 1, NULL, 3), - (4, 'Province four', 1, NULL, 2), - (5, 'Province five', 1, NULL, 1); - -INSERT INTO `vn`.`clientType`(`id`, `code`, `type`) - VALUES - (1, 'normal', 'Normal'), - (2, 'internalUse', 'Autoconsumo'), - (3, 'handMaking', 'Confección'), - (4, 'loses', 'Mermas'); - -INSERT INTO `vn`.`city`(`id`, `name`, `provinceFk`) - VALUES - (1, 'Gotham', 1); - -INSERT INTO `vn`.`cplusTerIdNif`(`id`, `description`) - VALUES - (1, 'NIF'); - -INSERT INTO `vn`.`contactChannel`(`id`, `name`) - VALUES - (1, 'Rumors on the streets'), - (2, 'Metropolis newspaper'), - (3, 'Daily Bugle'), - (4, 'GCN Channel'), - (5, 'The Newspaper'); - -INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`fax`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`,`clientTypeFk`,`mailAddress`,`cplusTerIdNifFk`,`hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`eypbc`) - VALUES - (101, 'Bruce Wayne', '74451390E', 'Batman', 'Alfred', '1007 Mountain Drive, Gotham', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'BruceWayne@verdnatura.es', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1,'0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1), - (102, 'Petter Parker', '87945234L', 'Spider-Man', 'Aunt May', '20 Ingram Street', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'PetterParker@verdnatura.es', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1,'0000-00-00', 1, NULL, 1, 1, 0, 1, NULL, 0, 0, 18, 0, 1), - (103, 'Clark Kent', '06815934E', 'Super-Man', 'lois lane', '344 Clinton Street', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'ClarkKent@verdnatura.es', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1,'0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1), - (104, 'Tony Stark', '06089160W', 'Iron-Man', 'Pepper Potts', '10880 Malibu Point', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'TonyStark@verdnatura.es', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1,'0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1), - (105, 'Max Eisenhardt', '39182496H', 'Magneto', 'Rogue', 'Unknown Whereabouts', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'MaxEisenhardt@verdnatura.es', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1,'0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1), - (106, 'DavidCharlesHaller', '53136686Q', 'Legion', 'Charles Xavier', 'Evil hideout', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'DavidCharlesHaller@verdnatura.es', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0,NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1,'0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1), - (107, 'Hank Pym', '09854837G', 'Ant-Man', 'Hawk', 'Anthill', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'HankPym@verdnatura.es', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1,'0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1), - (108, 'Charles Xavier', '22641921P', 'Professor X', 'Beast', '3800 Victory Pkwy, Cincinnati, OH 45207, USA', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'CharlesXavier@verdnatura.es', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1,'0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1), - (109, 'Bruce Banner', '16104829E', 'Hulk', 'Black widow', 'Somewhere in New York', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'BruceBanner@verdnatura.es', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1,'0000-00-00', 1, NULL, 1, 1, 0, 1, NULL, 0, 0, 19, 0, 1), - (110, 'Jessica Jones', '58282869H', 'Jessica Jones', 'Luke Cage', 'NYCC 2015 Poster', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'JessicaJones@verdnatura.es', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1,'0000-00-00', 1, NULL, 1, 1, 0, 1, NULL, 0, 0, 19, 0, 1); - -INSERT INTO `vn`.`address`(`id`, `nickname`, `street`, `city`, `postalCode`, `provinceFk`, `phone`, `mobile`, `isActive`, `isDefaultAddress`, `clientFk`, `agencyModeFk`, `longitude`, `latitude`, `isEqualizated`) - VALUES - (101, '01', 'Somewhere in Thailand', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (102, '02', 'Somewhere in Poland', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (103, '03', 'Somewhere in Japan', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (104, '04', 'Somewhere in Spain', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (105, '05', 'Somewhere in Potugal', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (106, '06', 'Somewhere in UK', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (107, '07', 'Somewhere in Valencia', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (108, '08', 'Somewhere in Silla', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (109, '09', 'Somewhere in London', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (110, '10', 'Somewhere in Algemesi', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (111, '11', 'Somewhere in Carlet', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (112, '12', 'Somewhere in Campanar', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (113, '13', 'Somewhere in Malilla', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (114, '14', 'Somewhere in France', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (115, '15', 'Somewhere in Birmingham', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (116, '16', 'Somewhere in Scotland', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (117, '17', 'Somewhere in nowhere', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (118, '18', 'Somewhere over the rainbow', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (119, '19', 'Somewhere in Alberic', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (120, '20', 'Somewhere in Montortal', 'Silla', 46460, 1, NULL, NULL, 1, 0, 109, 2, NULL, NULL, 0), - (121, 'my other address', 'the bat cave', 'Silla', 46460, 1, NULL, NULL, 1, 0, 101, 2, NULL, NULL, 0), - (122, 'my other address', 'NY roofs', 'Silla', 46460, 1, NULL, NULL, 1, 0, 102, 2, NULL, NULL, 0), - (123, 'my other address', 'The phone box', 'Silla', 46460, 1, NULL, NULL, 1, 0, 103, 2, NULL, NULL, 0), - (124, 'my other address', 'Stark tower', 'Silla', 46460, 1, NULL, NULL, 1, 0, 104, 2, NULL, NULL, 0), - (125, 'my other address', 'The plastic cell', 'Silla', 46460, 1, NULL, NULL, 1, 0, 105, 2, NULL, NULL, 0), - (126, 'my other address', 'Many places', 'Silla', 46460, 1, NULL, NULL, 1, 0, 106, 2, NULL, NULL, 0), - (127, 'my other address', 'Your pocket', 'Silla', 46460, 1, NULL, NULL, 1, 0, 107, 2, NULL, NULL, 0), - (128, 'my other address', 'Cerebro', 'Silla', 46460, 1, NULL, NULL, 1, 0, 108, 2, NULL, NULL, 0), - (129, 'my other address', 'Luke Cages Bar', 'Silla', 46460, 1, NULL, NULL, 1, 0, 110, 2, NULL, NULL, 0); - -INSERT INTO `vn`.`clientCredit`(`id`, `clientFk`, `workerFk`, `amount`, `created`) - VALUES - (1, 101, 5, 1000, DATE_ADD(CURDATE(), INTERVAL -1 MONTH)), - (2, 101, 5, 900, DATE_ADD(CURDATE(), INTERVAL -2 MONTH)), - (3, 101, 5, 800, DATE_ADD(CURDATE(), INTERVAL -3 MONTH)), - (4, 101, 5, 700, DATE_ADD(CURDATE(), INTERVAL -4 MONTH)), - (5, 101, 5, 600, DATE_ADD(CURDATE(), INTERVAL -5 MONTH)), - (6, 101, 5, 500, DATE_ADD(CURDATE(), INTERVAL -6 MONTH)), - (7, 101, 5, 400, DATE_ADD(CURDATE(), INTERVAL -7 MONTH)), - (8, 101, 9, 300, DATE_ADD(CURDATE(), INTERVAL -8 MONTH)), - (9, 101, 9, 200, DATE_ADD(CURDATE(), INTERVAL -9 MONTH)), - (10, 101, 9, 100, DATE_ADD(CURDATE(), INTERVAL -10 MONTH)), - (11, 101, 9, 50, DATE_ADD(CURDATE(), INTERVAL -11 MONTH)), - (12, 102, 9, 800, CURDATE()), - (13, 103, 9, 200, CURDATE()), - (14, 104, 9, 90, CURDATE()), - (15, 105, 9, 90, CURDATE()); - -INSERT INTO `vn`.`clientCreditLimit`(`id`, `maxAmount`, `roleFk`) - VALUES - (1, 9999999, 20), - (2, 10000, 21), - (3, 600, 13); - -INSERT INTO `vn`.`clientObservation`(`id`, `clientFk`, `workerFk`, `text`, `created`) - VALUES - (1, 101, 1, 'Madness, as you know, is like gravity, all it takes is a little push', CURDATE()), - (2, 102, 1, 'With great power, comes great responsibility', CURDATE()), - (3, 103, 3, 'this is a job for Super-Man!', CURDATE()), - (4, 104, 3, 'yes... I am Iron-Man', CURDATE()), - (5, 105, 5, 'They do understand. Our mutant powers make us superior', CURDATE()), - (6, 106, 5, 'My name is Legion, for we are many!', CURDATE()), - (7, 107, 9, 'I think our first move should be calling the Avengers..', CURDATE()), - (8, 108, 9, 'Just because someone stumbles and loses their path, does not mean they are lost forever.', CURDATE()), - (9, 109, 20, 'HULK SMASH! ...', CURDATE()), - (10, 110, 20, 'They say everyone is born a hero. But if you let it, life will push you over the line until you are the villain.', CURDATE()); - -INSERT INTO `vn`.`observationType`(`id`,`description`) - VALUES - (1,'observation one'), - (2,'observation two'), - (3,'observation three'); - - INSERT INTO `vn`.`addressObservation`(`id`,`addressFk`,`observationTypeFk`,`description`) - VALUES - (1, 1, 1,'under the floor'), - (2, 1, 2,'wears leather and goes out at night'), - (3, 1, 3,'care with the dog'); - -INSERT INTO `vn`.`creditClassification`(`id`, `client`, `dateStart`, `dateEnd`) - VALUES - (1, 101, CURDATE(), CURDATE()), - (2, 102, CURDATE(), CURDATE()), - (3, 103, CURDATE(), CURDATE()), - (4, 104, CURDATE(), CURDATE()), - (5, 105, CURDATE(), CURDATE()); - -INSERT INTO `vn`.`creditInsurance`(`id`, `creditClassification`, `credit`, `creationDate`, `grade`) - VALUES - (1, 1 , 3000, DATE_ADD(CURDATE(), INTERVAL -1 MONTH), NULL), - (2, 2 , 6000, DATE_ADD(CURDATE(), INTERVAL -2 MONTH), NULL), - (3, 3, 10000 , DATE_ADD(CURDATE(), INTERVAL -3 MONTH), NULL); - -INSERT INTO `vn`.`route`(`id`, `created`) - VALUES - (1, CURDATE()), - (2, CURDATE()), - (3, CURDATE()), - (4, CURDATE()), - (5, CURDATE()), - (6, CURDATE()), - (7, CURDATE()); - -INSERT INTO `vn`.`state`(`id`, `name`, `order`, `alertLevel`, `code`) - VALUES - (1, 'To check', 2, 0, 'FIXING'), - (2, 'Owes', 1, 0, 'FREE'), - (3, 'Ok', 3, 0, 'OK'); - -INSERT INTO `vn2008`.`empresa_grupo`(`empresa_grupo_id`, `grupo`) - VALUES - (1, 'Wayne Industries'); - -INSERT INTO `vn2008`.`empresa`(`id`, `abbreviation`, `registro`, `gerente_id`, `alta`, `baja`, `logo`, `oficial`, `cyc`, `rgb`, `mail`, `cuno`, `ODBC_DATE`, `Id_Cliente`, `digito_factura`, `Id_Proveedores_account`, `morosidad`, `empresa_grupo`) - VALUES - (442, 'WAY', 'Wayne Industries, Inc. operates as a warehouse for steel products.', '20', '1989-11-19', NULL, NULL, '1', '1', '00FF00', 'BruceWayne@verdnatura.es', NULL, '1989-08-11 12:31:22', '110', '1', NULL, '1', '1'); - - INSERT INTO `vn`.`ticket`(`id`, `agencyModeFk`,`warehouseFk`,`routeFk`, `shipped`, `clientFk`,`nickname`, `addressFk`) - VALUES - (1, 1, 1, NULL, CURDATE(), 101, 'Batman', 101), - (2, 1, 1, NULL, CURDATE(), 101, 'Spider-Man', 102), - (3, 2, 2, NULL, CURDATE(), 102, 'Super-Man', 103), - (4, 2, 2, NULL, CURDATE(), 102, 'Iron-Man', 104), - (5, 3, 3, NULL, CURDATE(), 103, 'Magneto', 105), - (6, 3, 3, NULL, CURDATE(), 103, 'Legion', 106), - (7, 4, 4, NULL, CURDATE(), 104, 'Ant-Man', 107), - (8, 4, 4, NULL, CURDATE(), 104, 'Professor X', 108), - (9, 5, 5, NULL, CURDATE(), 105, 'Hulk', 109), - (10, 6, 5, NULL, CURDATE(), 105, 'Jessica Jones', 110); - -INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`) - VALUES - ( 1, 1 , 1, 'ready' ), - ( 2, 2 , 2, 'do it fast please'), - ( 3, 3 , 3, ''); - -INSERT INTO `vn`.`ticketTracking`(`id`, `ticketFk`, `stateFk`, `workerFk`, `created`) - VALUES - (1, 1, 1, 5, CURDATE()), - (2, 2, 2, 5, CURDATE()), - (3, 3, 3, 5, CURDATE()), - (4, 4, 1, 5, CURDATE()), - (5, 5, 2, 5, CURDATE()), - (6, 6, 3, 5, CURDATE()), - (7, 7, 1, 5, CURDATE()), - (8, 8, 2, 5, CURDATE()), - (9, 9, 3, 5, CURDATE()), - (10, 10, 1, 5, CURDATE()); - -INSERT INTO `vn`.`vehicle`(`id`, `numberPlate`, `tradeMark`, `model`, `companyFk`, `warehouseFk`, `description`, `m3`, `isActive`) - VALUES - (1, '3333-BAT', 'WAYNE INDUSTRIES', 'BATMOBILE', 442, 1, 'The ultimate war machine', 50, 1), - (2, '1111-IMK', 'STARK INDUSTRIES', 'MARK-III', 442, 1, 'Iron-Man Heavy Armor MARK-III', 18, 1), - (3, '2222-IMK', 'STARK INDUSTRIES', 'MARK-VI', 442, 1, 'Iron-Man Heavy Armor MARK-VI', 16, 1), - (4, '3333-IMK', 'STARK INDUSTRIES', 'MARK-VII', 442, 1, 'Iron-Man Heavy Armor MARK-VII', 14, 1), - (5, '4444-IMK', 'STARK INDUSTRIES', 'MARK-XLII', 442, 1, 'Iron-Man Heavy Armor MARK-XLII', 13, 1), - (6, '5555-IMK', 'STARK INDUSTRIES', 'MARK-XLV', 442, 1, 'Iron-Man Heavy Armor MARK-XLV', 12, 1); - -INSERT INTO `vn`.`config`(`id`, `mdbServer`, `fakeEmail`, `defaultersMaxAmount`) - VALUES - (1, 'beta-server', 'nightmare@verdnatura.es', '200'); - -INSERT INTO `vn`.`greugeType`(`id`, `name`) - VALUES - (1, 'Diff'), - (2, 'Recover'), - (3, 'Manna'), - (4, 'Reclaim'), - (5, 'Heritage'), - (6, 'Miscellaneous'); - -INSERT INTO `vn`.`greuge`(`id`, `clientFk`, `description`, `amount`, `shipped`, `created`, `greugeTypeFk`, `ticketFk`) - VALUES - (1, 101, 'some diff charges', -19.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 1, 1), - (2, 101, 'more diff charges', 60, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 2, 1), - (3, 101, 'even more! diff charges', -9.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 3, 1), - (4, 101, 'insane diff charges', 60, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 4, 1), - (5, 101, 'gargantuous diff charges', -9.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 5, 1), - (6, 101, 'diff charges', 88.30, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 6, 1), - (7, 101, 'unaffordable diff charges', -39.12, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 1, 1), - (8, 101, 'some recovery charges', 29.35, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 2, 1), - (9, 101, 'some manna charges', -9.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 3, 1), - (10, 101, 'some claim charges', 13.13, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 4, 1), - (11, 101, 'some heritage charges', -15.99, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 5, 1), - (12, 101, 'some miscellaneous charges', 58.00, DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE(), 6, 1); - -INSERT INTO `vn`.`mandateType`(`id`, `name`) - VALUES - (1, 'B2B'), - (2, 'CORE'); - -INSERT INTO `vn`.`mandate`(`id`, `clientFk`, `companyFk`, `code`, `created`, `mandateTypeFk`) - VALUES - (1, 102, 442, '1-1', CURDATE(), 2); - -INSERT INTO `vn`.`itemCategory`(`id`, `name`, `display`, `color`) - VALUES - (1, 'Plant', 1, 'B92A26'), - (2, 'Flower', 2, 'dcf711'); - -INSERT INTO `vn`.`itemType`(`id`, `code`, `name`, `categoryFk`, `life`,`workerFk`) - VALUES - (1, 'CRI', 'Crisantemo', 2, 15, 5), - (2, 'ITG', 'Anthurium', 1, 30, 5), - (3, 'WPN', 'Paniculata', 2, 30, 5); - -INSERT INTO `vn`.`ink`(`id`, `name`, `picture`, `showOrder`) - VALUES - ('YEL', 'Yellow', 1 , 1), - ('BLU', 'Blue', 1 , 2), - ('RED', 'Red', 1 , 3); - -INSERT INTO `vn`.`origin`(`id`,`code`, `name`) - VALUES - (1, 'SPA', 'Spain'), - (2, 'HOL', 'Holand'), - (3, 'VLC', 'Valencia'); - -INSERT INTO `vn`.`producer`(`id`, `name`) - VALUES - (1, 'Marvel Studios'), - (2, 'Nordic Mythology'); - -INSERT INTO `vn`.`taxType`(`id`, `nickname`, `isAccrued`, `serial`, `TIPOOPE`, `description`, `countryFk`) - VALUES - (1, 'National', 1, 'R', 'I', 'national VAT',1), - (2, 'European', 0, 'E', 'I', 'europe VAT', 1); - -INSERT INTO `vn`.`taxCode`(`id`, `dated`, `code`, `taxTypeFk`, `rate`, `equalizationTax`, `type`, `link`, `isActive`, `updated`, `transactionCode`) - VALUES - (1, CURDATE(), '1111111111', 1, 7.0 , 0.0, 'R', 1, 1, CURDATE(), 1), - (2, CURDATE(), '2222222222', 2, 16.0, 0.0, 'G', 2, 1, CURDATE(), 2); - -INSERT INTO `vn`.`taxClass`(`id`, `description`, `code`) - VALUES - (1, 'Reduced VAT','R'), - (2, 'General VAT', 'G'); - -INSERT INTO `vn`.`intrastat`(`id`, `description`, `taxClassFk`, `taxCodeFk`) - VALUES - (05080000, 'Coral y materiales similares' , 2, 2), - (06021010, 'Plantas vivas: Esqueje/injerto, Vid', 1, 1); - -INSERT INTO `vn`.`expence`(`id`, `taxTypeFk`, `name`, `isWithheld`) - VALUES - (1, 1, 'bail', 0), - (2, 1, 'loan', 1); - -INSERT INTO `vn`.`item`(`id`, `name`,`typeFk`,`size`,`inkFk`,`category`,`stems`,`originFk`,`description`,`producerFk`,`intrastatFk`,`isOnOffer`,`expenceFk`,`isBargain`,`comment`,`relevancy`,`image`,`taxClassFk`) - VALUES - (1, 'Gem of Time', 2, 70, 'AMA', 'EXT', 1, 1, 'One of the infinity gems', 1, 06021010, 0, 1, 0, NULL, 0, 66540, 1), - (2, 'Gem of Mind', 2, 70, 'AZL', 'EXT', 1, 2, 'One of the infinity gems', 1, 06021010, 0, 1, 0, NULL, 0, 65540, 1), - (3, 'Iron Patriot', 1, 60, 'AMR', 'EXT', 1, 3, 'Rhodeys armor', 1, 05080000, 0, 1, 0, NULL, 0, 61692, 1), - (4, 'Mark I', 1, 60, 'AMR', 'EXT', 1, 1, 'Iron Mans first armor', 1, 05080000, 1, 2, 0, NULL, 0, 66090, 2), - (5, 'Mjolnir', 3, 30, 'AZR', 'EXT', 1, 2, 'Thors hammer!', 2, 06021010, 1, 2, 0, NULL, 0, 67350, 2); - -INSERT INTO `vn`.`packaging`(`id`, `volume`, `width`, `height`, `depth`, `isPackageReturnable`, `created`, `itemFk`, `price`) - VALUES - (1, 0.00, 10, 10, 0, 0, CURDATE(), 1, 1.50), - (2, 100.00, 20, 20, 0, 0, CURDATE(), 2, 1.00), - ('a', 50.00, 30, 30, 0, 1, CURDATE(), 3, 0.00); - -INSERT INTO `vn`.`ticketPackaging`(`id`, `ticketFk`, `packagingFk`, `quantity`, `created`, `pvp`) - VALUES - ( 1, 1, 1, 2, CURDATE(), NULL), - ( 2, 2, 2, 1, CURDATE(), NULL), - ( 3, 3, 'a', 4, CURDATE(), NULL); - -INSERT INTO `vn`.`sale`(`id`, `itemFk`, `ticketFk`, `concept`, `quantity`, `price`, `discount`, `reserved`, `isPicked`, `created`) - VALUES - ( 1, 1, 1, 'Gem of Time', 5 , 1.5, 0, 0, 0, CURDATE()), - ( 2, 1, 1, 'Gem of Time', 2 , 1.5, 0, 0, 0, CURDATE()), - ( 3, 2, 2, 'Mjolnir' , 10, 4 , 0, 0, 0, CURDATE()); - -INSERT INTO `vn`.`itemBarcode`(`id`, `itemFk`, `code`) - VALUES - (1, 1 ,1 ), - (2, 1 ,2 ), - (3, 1 ,3 ), - (4, 2 ,4 ); - -INSERT INTO `vn`.`itemPlacement`(`id`, `itemFk`, `warehouseFk`, `code`) - VALUES - (1, 1, 1, 'A1'), - (2, 1, 2, 'A2'), - (3, 1, 3, 'A3'), - (4, 2, 1, 'A4'); - -INSERT INTO `edi`.`genus`(`genus_id`, `latin_genus_name`, `entry_date`, `expiry_date`, `change_date_time`) - VALUES - ( 1, 'Abelia' , CURDATE(), NULL, CURDATE()), - ( 2, 'Abies', CURDATE(), NULL, CURDATE()), - ( 3, 'Abutilon', CURDATE(), NULL, CURDATE()); - -INSERT INTO `edi`.`specie`(`specie_id`, `genus_id`, `latin_species_name`, `entry_date`, `expiry_date`, `change_date_time`) - VALUES - ( 1, 1, 'grandiflora', CURDATE(), NULL, CURDATE()), - ( 2, 2, 'procera', CURDATE(), NULL, CURDATE()), - ( 3, 3, 'decurrens', CURDATE(), NULL, CURDATE()), - ( 4, 3, 'dealbata', CURDATE(), NULL, CURDATE()); - -INSERT INTO `vn`.`itemBotanical`(`itemFk`, `botanical`, `genusFk`, `specieFk`) - VALUES - ( 1, 'Hedera helix' , 1, 1), - ( 2, NULL, 2, 2), - ( 3, 'Cycas revoluta', 2, NULL), - ( 4, 'Polygonum', NULL, NULL); - -INSERT INTO `vn`.`tag`(`id`,`name`,`isFree`,`isQuantitatif`,`sourceTable`,`unit`) - VALUES - (1, 'Color', 0, 0, null, null), - (2, 'Power', 0, 0, null, null), - (3, 'Shape', 1, 0, null, null), - (4, 'Location', 1, 0, null, null), - (5, 'Owner', 1, 1, null, null); - -INSERT INTO `vn`.`itemTag`(`id`,`itemFk`,`tagFk`,`value`,`priority`) - VALUES - (1, 1, 1, 'Yellow', 5), - (2, 1, 2, 'Manipulates time', 4), - (3, 1, 3, 'round', 3), - (4, 1, 4, 'Gamoras hideout', 2), - (5, 1, 5, 'Gamora', 1); - -INSERT INTO `vn`.`itemLog` (`id`, `originFk`, `userFk`, `action`, `description`) - VALUES - ('1', '1', '1', 'insert', 'We made an change!'); - -INSERT INTO `vn`.`invoiceOut`(`id`, `ref`, `serial`, `amount`, `clientFk`, `created`, `companyFk`, `dued`, `booked`, `bankFk`, `pdf`) - VALUES - ( 1, 'T1111111' , 'T', 500 , 101, CURDATE(), 442, CURDATE(), CURDATE(), 8, 1), - ( 2, 'V2222222' , 'V', 350.50 , 102, CURDATE(), 442, CURDATE(), CURDATE(), 8, 1), - ( 3, 'E3333333' , 'E', 90.30 , 103, CURDATE(), 442, CURDATE(), CURDATE(), 8, 1); - -INSERT INTO `vn`.`recovery`(`id`, `clientFk`, `started`, `finished`, `amount`, `period`) - VALUES - ( 1, 101, CURDATE(), date_add(CURDATE(),INTERVAL 1 MONTH), 50, 7), - ( 2, 102, CURDATE(), date_add(CURDATE(),INTERVAL 3 MONTH), 100, 1), - ( 3, 102, CURDATE(), date_add(CURDATE(),INTERVAL 1 MONTH), 50, 7), - ( 4, 103, CURDATE(), NULL, 50, 7); \ No newline at end of file diff --git a/services/db/Dockerfile b/services/db/Dockerfile deleted file mode 100644 index 55ca078d2..000000000 --- a/services/db/Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -FROM mysql:5.6.37 - -ENV MYSQL_ROOT_PASSWORD root -ENV TZ GMT-1 - -WORKDIR /docker-entrypoint-initdb.d -COPY *.sql ./ -COPY 03-changes.sh . -COPY changes changes -RUN chmod -R 755 . - -CMD ["mysqld"] - -#HEALTHCHECK --interval=5s --timeout=10s --retries=200 \ -# CMD mysqladmin ping -h 127.0.0.1 -u root || exit 1 - -EXPOSE 3306 diff --git a/services/db/changes/1.0.1/01-updateDefaultAddressTo1.sql b/services/db/changes/1.0.1/01-updateDefaultAddressTo1.sql deleted file mode 100644 index df521dafc..000000000 --- a/services/db/changes/1.0.1/01-updateDefaultAddressTo1.sql +++ /dev/null @@ -1 +0,0 @@ -update vn2008.Consignatarios set predeterminada = 1 where predeterminada = -1; \ No newline at end of file diff --git a/services/db/changes/1.0.1/02-updateClientMails.sql b/services/db/changes/1.0.1/02-updateClientMails.sql deleted file mode 100644 index 937e32810..000000000 --- a/services/db/changes/1.0.1/02-updateClientMails.sql +++ /dev/null @@ -1,3 +0,0 @@ -UPDATE vn.client - SET email = REPLACE(REPLACE(email, ' ', ''), ';', ',') - WHERE email REGEXP '[ |;]'; \ No newline at end of file diff --git a/services/db/changes/1.0.1/03-createUserForClients.sql b/services/db/changes/1.0.1/03-createUserForClients.sql deleted file mode 100644 index 18bed72f2..000000000 --- a/services/db/changes/1.0.1/03-createUserForClients.sql +++ /dev/null @@ -1,5 +0,0 @@ -INSERT INTO account.user (id,name,role,password,active) -select c.Id_Cliente,c.Id_Cliente,2,'no_tiene',FALSE - FROM vn2008.Clientes c -LEFT JOIN account.user u ON u.id = c.id_cliente -where u.id is NULL \ No newline at end of file diff --git a/services/db/changes/1.0.1/04-updateTriggerItem.sql b/services/db/changes/1.0.1/04-updateTriggerItem.sql deleted file mode 100644 index 5c23e498e..000000000 --- a/services/db/changes/1.0.1/04-updateTriggerItem.sql +++ /dev/null @@ -1,21 +0,0 @@ -DROP TRIGGER IF EXISTS `vn2008`.`ArticlesBeforeInsert`; - -DELIMITER $$ -USE `vn2008`$$ -CREATE DEFINER=`root`@`%` TRIGGER `vn2008`.`ArticlesBeforeInsert` - BEFORE INSERT ON `Articles` FOR EACH ROW -BEGIN - DECLARE vDensity DOUBLE; - DECLARE vInsertId INT; - - IF NEW.density IS NULL - THEN - SELECT density INTO vDensity - FROM Tipos WHERE tipo_id = NEW.tipo_id; - - SET NEW.density = vDensity; - END IF; - - -END$$ -DELIMITER ; diff --git a/services/db/changes/1.0.1/05-updateTriggerClient.sql b/services/db/changes/1.0.1/05-updateTriggerClient.sql deleted file mode 100644 index bacbb9aa1..000000000 --- a/services/db/changes/1.0.1/05-updateTriggerClient.sql +++ /dev/null @@ -1,58 +0,0 @@ -DROP TRIGGER IF EXISTS `vn2008`.`ClientesBeforeUpdate`; - -DELIMITER $$ -USE `vn2008`$$ -CREATE DEFINER=`root`@`%` TRIGGER `ClientesBeforeUpdate` - BEFORE UPDATE ON `Clientes` - FOR EACH ROW -BEGIN - DECLARE vText VARCHAR(255) DEFAULT NULL; - DECLARE isAlreadyUsedIf BOOLEAN; - - SELECT (COUNT(*) > 1) INTO isAlreadyUsedIf - FROM Clientes - WHERE `IF` = TRIM(NEW.`IF`); - - IF isAlreadyUsedIf THEN - CALL util.throw ('Error. El NIF/CIF está repetido'); - END IF; - - -- Comprueba que el formato de los teléfonos es válido - - IF !(NEW.telefono <=> OLD.telefono) THEN - CALL pbx.phoneIsValid (NEW.telefono); - END IF; - - IF !(NEW.movil <=> OLD.movil) THEN - CALL pbx.phoneIsValid (NEW.movil); - END IF; - - IF !(NEW.fax <=> OLD.fax) THEN - CALL pbx.phoneIsValid (NEW.fax); - END IF; - - -- Avisar al comercial si ha llegado la documentación sepa/core - - IF NEW.sepavnl AND !OLD.sepavnl THEN - SET vText = 'Sepa de VNL'; - END IF; - - IF NEW.corevnl AND !OLD.corevnl THEN - SET vText = 'Core de VNL'; - END IF; - - IF vText IS NOT NULL - THEN - INSERT INTO mail(`to`, reply_to, subject, text) - SELECT - CONCAT(IF(ac.id,name, 'jgallego'), '@verdnatura.es'), - 'administracion@verdnatura.es', - CONCAT('Cliente ', NEW.Id_Cliente), - CONCAT('Recibida la documentación: ', vText) - FROM Trabajadores t - LEFT JOIN account.user u ON t.user_id = u.id AND active - LEFT JOIN account.account ac ON ac.id = u.id - WHERE t.Id_Trabajador = NEW.Id_Trabajador; - END IF; -END$$ -DELIMITER ; diff --git a/services/db/changes/1.0.2/01-ACLinserts.sql b/services/db/changes/1.0.2/01-ACLinserts.sql deleted file mode 100644 index ec1bc0282..000000000 --- a/services/db/changes/1.0.2/01-ACLinserts.sql +++ /dev/null @@ -1,9 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Ticket', '*', '*', 'ALLOW', 'ROLE', 'employee'); -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('TicketObservation', '*', '*', 'ALLOW', 'ROLE', 'employee'); -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Route', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Sale', '*', '*', 'ALLOW', 'ROLE', 'employee'); -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('TicketTracking', '*', '*', 'ALLOW', 'ROLE', 'employee'); -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('TicketState', '*', '*', 'ALLOW', 'ROLE', 'employee'); -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('TicketPackaging', '*', '*', 'ALLOW', 'ROLE', 'employee'); -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Packaging', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Packaging', '*', 'WRITE', 'ALLOW', 'ROLE', 'logistic'); diff --git a/services/db/changes/1.0.2/02-packaging.sql b/services/db/changes/1.0.2/02-packaging.sql deleted file mode 100644 index 28c84109d..000000000 --- a/services/db/changes/1.0.2/02-packaging.sql +++ /dev/null @@ -1,18 +0,0 @@ -USE `vn`; -CREATE - OR REPLACE ALGORITHM = UNDEFINED - DEFINER = `root`@`%` - SQL SECURITY DEFINER -VIEW `vn`.`packaging` AS - SELECT - `c`.`Id_Cubo` AS `id`, - `c`.`Volumen` AS `volume`, - `c`.`X` AS `width`, - `c`.`Y` AS `height`, - `c`.`Z` AS `depth`, - `c`.`Retornable` AS `isPackageReturnable`, - `c`.`odbc_date` AS `created`, - `c`.`item_id` AS `itemFk`, - `c`.`pvp` AS `price` - FROM - `vn2008`.`Cubos` `c`; diff --git a/services/db/connect.tpl.ini b/services/db/connect.tpl.ini deleted file mode 100644 index cf960b425..000000000 --- a/services/db/connect.tpl.ini +++ /dev/null @@ -1,5 +0,0 @@ -[client] -host=localhost -port=3306 -user=root -password= \ No newline at end of file diff --git a/services/db/export-data.cmd b/services/db/export-data.cmd deleted file mode 100755 index e0fdf56d5..000000000 --- a/services/db/export-data.cmd +++ /dev/null @@ -1,10 +0,0 @@ - -echo USE `account`; > 02-dumpedFixtures.sql -mysqldump --defaults-file=connect.ini --no-create-info account role roleRole roleInherit >> 02-dumpedFixtures.sql -echo USE `salix`; >> 02-dumpedFixtures.sql -mysqldump --defaults-file=connect.ini --no-create-info salix ACL >> 02-dumpedFixtures.sql -echo USE `vn`; >> 02-dumpedFixtures.sql -mysqldump --defaults-file=connect.ini --no-create-info vn cplusInvoiceType477 cplusSubjectOp cplusTaxBreak >> 02-dumpedFixtures.sql - - - diff --git a/services/db/export-structure.cmd b/services/db/export-structure.cmd deleted file mode 100755 index 599743dad..000000000 --- a/services/db/export-structure.cmd +++ /dev/null @@ -1,2 +0,0 @@ - -mysqldump --defaults-file=connect.ini --default-character-set=utf8 --no-data --triggers --routines --events --databases account util vn2008 vn edi bs bi pbx cache salix vncontrol hedera stock > 01-structure.sql diff --git a/services/db/import-changes.js b/services/db/import-changes.js deleted file mode 100644 index 3e645484b..000000000 --- a/services/db/import-changes.js +++ /dev/null @@ -1,65 +0,0 @@ -const mysql = require('mysql2/promise'); -const fs = require('fs-extra'); - -(async () => { - try { - const connection = await mysql.createConnection({ - host: 'localhost', - user: 'root', - multipleStatements: true - }); - let changesDir = './changes'; - let results = await connection.query("SELECT dbVersion FROM util.config"); - if (results[0].length != 1) - throw new Error('There must be exactly one row in the configuration table'); - let version = results[0][0].dbVersion; - if (!version) - throw new Error('Database version not defined'); - let dirs = await fs.readdir(changesDir); - dirs.sort(compareVersions); - let lastVersion; - - for (let dir of dirs) { - if (compareVersions(dir, version) <= 0) continue; - let path = `${changesDir}/${dir}`; - let files = await fs.readdir(path); - files.sort(); - console.log(dir); - for (let file of files) { - let sql = await fs.readFile(`${path}/${file}`, 'utf8'); - if (/^\s*$/.test(sql)) continue; - await connection.query(sql); - console.log(` - ${file}`); - } - lastVersion = dir; - } - if (lastVersion) { - await connection.query("UPDATE util.config SET dbVersion = ?", [lastVersion]); - console.log(`Database upgraded successfully to version ${lastVersion}`); - } else { - console.log("Database is alredy in the last version"); - } - await connection.end(); - process.exit(); - } catch (err) { - console.error(err); - process.exit(1); - } -})(); - -function compareVersions(ver1, ver2) { - let diff; - ver1 = ver1.split('.'); - ver2 = ver2.split('.'); - - diff = parseInt(ver1[0]) - parseInt(ver2[0]); - if (diff !== 0) return diff; - - diff = parseInt(ver1[1]) - parseInt(ver2[1]); - if (diff !== 0) return diff; - - diff = parseInt(ver1[2]) - parseInt(ver2[2]); - if (diff !== 0) return diff; - - return 0; -} diff --git a/services/db/import-fixtures.js b/services/db/import-fixtures.js deleted file mode 100644 index c7e9c5f02..000000000 --- a/services/db/import-fixtures.js +++ /dev/null @@ -1,19 +0,0 @@ -const mysql = require('mysql2/promise'); -const fs = require('fs-extra'); - -(async () => { - try { - const connection = await mysql.createConnection({ - host: 'localhost', - user: 'root', - multipleStatements: true - }); - sql = await fs.readFile(`04-fixtures.sql`, 'utf8'); - await connection.query(sql); - await connection.end(); - process.exit(); - } catch (err) { - console.error(err); - process.exit(1); - } -})(); diff --git a/services/db/testing_fixtures.js b/services/db/testing_fixtures.js deleted file mode 100644 index a6e32c0d5..000000000 --- a/services/db/testing_fixtures.js +++ /dev/null @@ -1,38 +0,0 @@ -let mysql = require('mysql2'); - -let connection = mysql.createConnection({ - multipleStatements: true, - host: 'localhost', - user: 'root', - password: 'root', - database: 'salix' -}); - -let errorHandler = callback => { - return error => { - if (error) - throw error; - callback(); - }; -}; - -let insertFixtures = async function(sqlStatements) { - try { - if (sqlStatements.deletes.length) - await connection.query(sqlStatements.deletes); - if (sqlStatements.inserts.length) - await connection.query(sqlStatements.inserts); - if (sqlStatements.updates.length) - await connection.query(sqlStatements.updates); - } catch (error) { - errorHandler(error); - } -}; - -connection.connect(); - -module.exports = function restoreFixtures(sqlStatements) { - connection.query('SET FOREIGN_KEY_CHECKS = 0', () => { - insertFixtures(sqlStatements); - }); -}; diff --git a/services/item/Dockerfile b/services/item/Dockerfile deleted file mode 100644 index b87649c5f..000000000 --- a/services/item/Dockerfile +++ /dev/null @@ -1,12 +0,0 @@ -FROM node:8.9.4 - -COPY item /app -COPY loopback /loopback - -WORKDIR /app - -RUN npm install -RUN npm -g install pm2 - -CMD ["pm2-docker", "./server/server.js"] - diff --git a/services/item/common/methods/item/clone.js b/services/item/common/methods/item/clone.js deleted file mode 100644 index 737afa8ed..000000000 --- a/services/item/common/methods/item/clone.js +++ /dev/null @@ -1,59 +0,0 @@ -var UserError = require('../../../../loopback/common/helpers').UserError; - -module.exports = Self => { - Self.remoteMethod('clone', { - description: 'clone item', - accessType: 'WRITE', - accepts: [{ - arg: 'id', - type: 'number', - required: true, - description: 'origin itemId', - http: {source: 'path'} - }], - returns: { - arg: 'id', - description: 'new cloned itemId' - }, - http: { - path: `/:id/clone`, - verb: 'post' - } - }); - - Self.clone = async (itemId, callback) => { - let filter = { - where: { - id: itemId - }, - include: [ - {relation: "itemTag", scope: {order: "priority ASC", include: {relation: "tag"}}} - ] - }; - try { - let origin = await Self.findOne(filter); - let copy = JSON.parse(JSON.stringify(origin)); - - delete copy.id; - delete copy.itemTag; - - let newItem = await Self.create(copy); - let promises = []; - - let createBotanical = `INSERT INTO vn.itemBotanical (itemFk, botanical, genusFk, specieFk) - SELECT ?, botanical, genusFk, specieFk - FROM vn.itemBotanical ib WHERE itemFk = ?`; - promises.push(Self.rawSql(createBotanical, [newItem.id, origin.id])); - - let createTags = `INSERT INTO vn.itemTag (itemFk, tagFk, value, priority) - SELECT ?, tagFk, value, priority - FROM vn.itemTag WHERE itemFk = ?`; - promises.push(Self.rawSql(createTags, [newItem.id, origin.id])); - - await Promise.all(promises); - return newItem.id; - } catch (err) { - throw new UserError(err); - } - }; -}; diff --git a/services/item/common/methods/item/crudItemBarcodes.js b/services/item/common/methods/item/crudItemBarcodes.js deleted file mode 100644 index 0b33736cd..000000000 --- a/services/item/common/methods/item/crudItemBarcodes.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = Self => { - Self.installCrudModel('crudItemBarcodes'); -}; diff --git a/services/item/common/methods/item/crudItemNiches.js b/services/item/common/methods/item/crudItemNiches.js deleted file mode 100644 index c836ccfbf..000000000 --- a/services/item/common/methods/item/crudItemNiches.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = Self => { - Self.installCrudModel('crudItemNiches'); -}; diff --git a/services/item/common/methods/item/crudItemTags.js b/services/item/common/methods/item/crudItemTags.js deleted file mode 100644 index 4a9702327..000000000 --- a/services/item/common/methods/item/crudItemTags.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = Self => { - Self.installCrudModel('crudItemTags'); -}; diff --git a/services/item/common/methods/item/filter.js b/services/item/common/methods/item/filter.js deleted file mode 100644 index b1a1457c1..000000000 --- a/services/item/common/methods/item/filter.js +++ /dev/null @@ -1,53 +0,0 @@ -module.exports = Self => { - Self.installMethod('filter', filterParams); - - function filterParams(params) { - let filters = { - where: {}, - skip: (params.page - 1) * params.size, - limit: params.size, - order: params.order || 'relevancy DESC', - include: { - relation: "itemType", - scope: { - fields: ["id", "name"] - } - } - }; - - delete params.page; - delete params.size; - delete params.order; - - if (params.search) { - filters.where.and = [ - { - or: [ - {id: params.search}, - {name: {regexp: params.search}} - ] - } - ]; - delete params.search; - } - - if (params.itemSize) { - params.size = params.itemSize; - delete params.itemSize; - } - - Object.keys(params).forEach( - key => { - if (filters.where.and) { - let filter = {}; - filter[key] = (key === 'description' || key === 'name') ? {regexp: params[key]} : params[key]; - filters.where.and.push(filter); - } else { - filters.where[key] = (key === 'description' || key === 'name') ? {regexp: params[key]} : params[key]; - } - } - ); - - return filters; - } -}; diff --git a/services/item/common/methods/item/getLog.js b/services/item/common/methods/item/getLog.js deleted file mode 100644 index a61dd0f8e..000000000 --- a/services/item/common/methods/item/getLog.js +++ /dev/null @@ -1,22 +0,0 @@ -module.exports = Self => { - Self.installMethod('getLog', filterParams); - - function filterParams(params) { - return { - where: { - originFk: params.itemFk - }, - skip: (params.page - 1) * params.size, - limit: params.size, - include: [{ - relation: "item" - }, - { - relation: "user", - scope: { - fields: ["name"] - } - }] - }; - } -}; diff --git a/services/item/common/methods/item/specs/crudItemBarcodes.spec.js b/services/item/common/methods/item/specs/crudItemBarcodes.spec.js deleted file mode 100644 index be3e52dd2..000000000 --- a/services/item/common/methods/item/specs/crudItemBarcodes.spec.js +++ /dev/null @@ -1,72 +0,0 @@ -// const crudItemBarcodes = require('../crudItemBarcodes'); -// const catchErrors = require('../../../../../../services/utils/jasmineHelpers').catchErrors; -// let mysql = require('mysql2'); - -// describe('Item crudItemBarcodes()', () => { -// let connection; -// beforeAll(() => { -// connection = mysql.createConnection({ -// multipleStatements: true, -// host: 'localhost', -// user: 'root', -// password: '', -// database: 'salix' -// }); -// }); - -// it('should call the destroyAll methodif there are ids in delete Array', done => { -// let self = jasmine.createSpyObj('self', ['remoteMethod', 'crudItemBarcodes', 'destroyAll', 'create', 'upsert']); - -// crudItemBarcodes(self); -// self.crudItemBarcodes({ -// delete: [1], -// create: [], -// update: [] -// }).then(result => { -// expect(self.destroyAll).toHaveBeenCalledWith({id: {inq: [1]}}); -// done(); -// }) -// .catch(catchErrors(done)); -// }); - -// it('should call the create method if there are ids in create Array', done => { -// let self = jasmine.createSpyObj('self', ['remoteMethod', 'crudItemBarcodes', 'destroyAll', 'create', 'upsert']); - -// crudItemBarcodes(self); -// self.crudItemBarcodes({ -// delete: [], -// create: [1], -// update: [] -// }).then(result => { -// expect(self.create).toHaveBeenCalledWith([1]); -// done(); -// }) -// .catch(catchErrors(done)); -// }); - -// it('should call the upsert method as many times as ids in update Array', done => { -// let self = jasmine.createSpyObj('self', ['remoteMethod', 'crudItemBarcodes', 'destroyAll', 'create', 'upsert']); - -// crudItemBarcodes(self); -// self.crudItemBarcodes({ -// delete: [], -// create: [], -// update: [1, 2] -// }).then(result => { -// expect(self.upsert).toHaveBeenCalledWith(1); -// expect(self.upsert).toHaveBeenCalledWith(2); -// expect(self.upsert.calls.count()).toEqual(2); -// done(); -// }) -// .catch(catchErrors(done)); -// }); - -// it('should return an error when attempting to save a duplicated barcode', done => { -// let callback = (err, res) => { -// expect(err.toString()).toBe("Error: Duplicate entry '4' for key 'PRIMARY'"); -// done(); -// }; - -// connection.query('INSERT INTO `vn`.`itemBarcode` VALUES (4, 2 ,4 );', callback); -// }); -// }); diff --git a/services/item/common/methods/item/specs/crudItemNiches.spec.js b/services/item/common/methods/item/specs/crudItemNiches.spec.js deleted file mode 100644 index a5ce94f70..000000000 --- a/services/item/common/methods/item/specs/crudItemNiches.spec.js +++ /dev/null @@ -1,51 +0,0 @@ -// const crudItemNiches = require('../crudItemNiches'); -// const catchErrors = require('../../../../../../services/utils/jasmineHelpers').catchErrors; - -// describe('Item crudItemNiches()', () => { -// it('should call the destroyAll method if there are ids in delete Array', done => { -// let self = jasmine.createSpyObj('self', ['remoteMethod', 'crudItemNiches', 'destroyAll', 'create', 'upsert']); - -// crudItemNiches(self); -// self.crudItemNiches({ -// delete: [1], -// create: [], -// update: [] -// }).then(result => { -// expect(self.destroyAll).toHaveBeenCalledWith({id: {inq: [1]}}); -// done(); -// }) -// .catch(catchErrors(done)); -// }); - -// it('should call the create method if there are ids in create Array', done => { -// let self = jasmine.createSpyObj('self', ['remoteMethod', 'crudItemNiches', 'destroyAll', 'create', 'upsert']); - -// crudItemNiches(self); -// self.crudItemNiches({ -// delete: [], -// create: [1], -// update: [] -// }).then(result => { -// expect(self.create).toHaveBeenCalledWith([1]); -// done(); -// }) -// .catch(catchErrors(done)); -// }); - -// it('should call the upsert method as many times as ids in update Array', done => { -// let self = jasmine.createSpyObj('self', ['remoteMethod', 'crudItemNiches', 'destroyAll', 'create', 'upsert']); - -// crudItemNiches(self); -// self.crudItemNiches({ -// delete: [], -// create: [], -// update: [1, 2] -// }).then(result => { -// expect(self.upsert).toHaveBeenCalledWith(1); -// expect(self.upsert).toHaveBeenCalledWith(2); -// expect(self.upsert.calls.count()).toEqual(2); -// done(); -// }) -// .catch(catchErrors(done)); -// }); -// }); diff --git a/services/item/common/methods/item/updateTaxes.js b/services/item/common/methods/item/updateTaxes.js deleted file mode 100644 index 70a2511bc..000000000 --- a/services/item/common/methods/item/updateTaxes.js +++ /dev/null @@ -1,42 +0,0 @@ -module.exports = Self => { - Self.remoteMethod('updateTaxes', { - description: 'Updates the item taxes', - accessType: 'WRITE', - accepts: [{ - arg: 'id', - type: 'number', - required: true, - description: 'The item id', - http: {source: 'path'} - }, { - arg: 'niches', - type: ['object'], - required: true, - description: 'The list of taxes to update', - http: {source: 'body'} - }], - returns: { - type: 'boolean', - root: true - }, - http: { - path: `/:id/updateTaxes`, - verb: 'post' - } - }); - - Self.updateTaxes = async (id, taxes) => { - let promises = []; - for (let tax of taxes) { - if (!tax.taxClassFk) - throw new Error('Tax class cannot be blank'); - - promises.push(Self.app.models.ItemTaxCountry.updateAll( - {id: tax.id}, - {taxClassFk: tax.taxClassFk} - )); - } - await Promise.all(promises); - return true; - }; -}; diff --git a/services/item/common/models/expence.json b/services/item/common/models/expence.json deleted file mode 100644 index 79af34988..000000000 --- a/services/item/common/models/expence.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "Expence", - "base": "VnModel", - "options": { - "mysql": { - "table": "expence" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "description": "Identifier" - }, - "name": { - "type": "String" - }, - "isWithheld": { - "type": "Number" - } - }, - "relations": { - "taxType": { - "type": "belongsTo", - "model": "TaxType", - "foreignKey": "taxTypeFk" - } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ] -} \ No newline at end of file diff --git a/services/item/common/models/item-barcode.js b/services/item/common/models/item-barcode.js deleted file mode 100644 index be746ecb3..000000000 --- a/services/item/common/models/item-barcode.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function(Self) { - require('../methods/item/crudItemBarcodes.js')(Self); -}; diff --git a/services/item/common/models/item-barcode.json b/services/item/common/models/item-barcode.json deleted file mode 100644 index 8c089609f..000000000 --- a/services/item/common/models/item-barcode.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "ItemBarcode", - "base": "VnModel", - "options": { - "mysql": { - "table": "itemBarcode", - "database": "vn" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "code": { - "type": "String", - "required": true - } - }, - "relations": { - "item": { - "type": "belongsTo", - "model": "Item", - "foreignKey": "itemFk" - } - } -} diff --git a/services/item/common/models/item-log.js b/services/item/common/models/item-log.js deleted file mode 100644 index 248cc6abd..000000000 --- a/services/item/common/models/item-log.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function(Self) { - require('../methods/item/getLog.js')(Self); -}; diff --git a/services/item/common/models/item-log.json b/services/item/common/models/item-log.json deleted file mode 100644 index 4f784b74f..000000000 --- a/services/item/common/models/item-log.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "ItemLog", - "base": "VnModel", - "options": { - "mysql": { - "table": "itemLog", - "database": "vn" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "creationDate": { - "type": "Date" - }, - "description": { - "type": "String" - }, - "action": { - "type": "String" - } - }, - "relations": { - "item": { - "type": "belongsTo", - "model": "Item", - "foreignKey": "originFk" - }, - "user": { - "type": "belongsTo", - "model": "Account", - "foreignKey": "userFk" - } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ] -} diff --git a/services/item/common/models/item-niche.js b/services/item/common/models/item-niche.js deleted file mode 100644 index 8f9d85da7..000000000 --- a/services/item/common/models/item-niche.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function(Self) { - require('../methods/item/crudItemNiches.js')(Self); -}; diff --git a/services/item/common/models/item-niche.json b/services/item/common/models/item-niche.json deleted file mode 100644 index 1317987c6..000000000 --- a/services/item/common/models/item-niche.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "ItemNiche", - "base": "VnModel", - "options": { - "mysql": { - "table": "itemPlacement", - "database": "vn" - } - }, - "properties": { - "code": { - "type": "String", - "required": true - } - }, - "relations": { - "item": { - "type": "belongsTo", - "model": "Item", - "foreignKey": "itemFk" - }, - "warehouse": { - "type": "belongsTo", - "model": "Warehouse", - "foreignKey": "warehouseFk", - "required": true - } - } -} diff --git a/services/item/common/models/item-tag.js b/services/item/common/models/item-tag.js deleted file mode 100644 index d4e768bdb..000000000 --- a/services/item/common/models/item-tag.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function(Self) { - require('../methods/item/crudItemTags.js')(Self); -}; diff --git a/services/item/common/models/item-tag.json b/services/item/common/models/item-tag.json deleted file mode 100644 index 2eca420e3..000000000 --- a/services/item/common/models/item-tag.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "ItemTag", - "base": "VnModel", - "options": { - "mysql": { - "table": "itemTag", - "database": "vn" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "value": { - "type": "String", - "required": true - }, - "priority": { - "type": "Number", - "required": true - } - }, - "relations": { - "item": { - "type": "belongsTo", - "model": "Item", - "foreignKey": "itemFk" - }, - "tag": { - "type": "belongsTo", - "model": "Tag", - "foreignKey": "tagFk" - } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ] - } diff --git a/services/item/common/models/item-tax-country.json b/services/item/common/models/item-tax-country.json deleted file mode 100644 index 7f67a271e..000000000 --- a/services/item/common/models/item-tax-country.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "ItemTaxCountry", - "base": "VnModel", - "options": { - "mysql": { - "table": "itemTaxCountry" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "effectived": { - "type": "Boolean" - } - }, - "relations": { - "item": { - "type": "belongsTo", - "model": "Item", - "foreignKey": "itemFk" - }, - "country": { - "type": "belongsTo", - "model": "Country", - "foreignKey": "countryFk" - }, - "taxClass": { - "type": "belongsTo", - "model": "TaxClass", - "foreignKey": "taxClassFk" - } - } -} \ No newline at end of file diff --git a/services/item/common/models/item-type.json b/services/item/common/models/item-type.json deleted file mode 100644 index eec3af490..000000000 --- a/services/item/common/models/item-type.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "ItemType", - "base": "VnModel", - "options": { - "mysql": { - "table": "itemType" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "name": { - "type": "String" - }, - "life": { - "type": "Number" - } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ] -} \ No newline at end of file diff --git a/services/item/common/models/item.js b/services/item/common/models/item.js deleted file mode 100644 index 627b6993b..000000000 --- a/services/item/common/models/item.js +++ /dev/null @@ -1,8 +0,0 @@ -module.exports = function(Self) { - require('../methods/item/filter.js')(Self); - require('../methods/item/clone.js')(Self); - require('../methods/item/updateTaxes.js')(Self); - - Self.validatesPresenceOf('name', {message: 'Cannot be blank'}); - Self.validatesPresenceOf('originFk', {message: 'Cannot be blank'}); -}; diff --git a/services/item/common/models/item.json b/services/item/common/models/item.json deleted file mode 100644 index ddb8ff4d3..000000000 --- a/services/item/common/models/item.json +++ /dev/null @@ -1,99 +0,0 @@ -{ - "name": "Item", - "base": "VnModel", - "options": { - "mysql": { - "table": "item" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "name": { - "type": "String", - "required": true - }, - "size": { - "type": "Number" - }, - "category": { - "type": "String" - }, - "stems": { - "type": "Number" - }, - "description": { - "type": "String" - }, - "isOnOffer": { - "type": "Boolean" - }, - "isBargain": { - "type": "Boolean" - }, - "comment": { - "type": "String" - }, - "relevancy": { - "type": "Number" - }, - "image": { - "type": "String" - } - }, - "relations": { - "itemType": { - "type": "belongsTo", - "model": "ItemType", - "foreignKey": "typeFk" - }, - "ink": { - "type": "belongsTo", - "model": "Ink", - "foreignKey": "inkFk" - }, - "origin": { - "type": "belongsTo", - "model": "Origin", - "foreignKey": "originFk" - }, - "producer": { - "type": "belongsTo", - "model": "Producer", - "foreignKey": "producerFk" - }, - "intrastat": { - "type": "belongsTo", - "model": "Intrastat", - "foreignKey": "intrastatFk" - }, - "expence": { - "type": "belongsTo", - "model": "Expence", - "foreignKey": "expenceFk" - }, - "itemTag": { - "type": "hasMany", - "model": "ItemTag", - "foreignKey": "itemFk" - }, - "itemBarcode": { - "type": "hasMany", - "model": "ItemBarcode", - "foreignKey": "itemFk" - }, - "taxes": { - "type": "hasMany", - "model": "ItemTaxCountry", - "foreignKey": "itemFk" - }, - "itemNiche": { - "type": "hasMany", - "model": "ItemNiche", - "foreignKey": "itemFk" - } - } - } \ No newline at end of file diff --git a/services/item/common/models/warehouse.json b/services/item/common/models/warehouse.json deleted file mode 100644 index d52991ed6..000000000 --- a/services/item/common/models/warehouse.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "Warehouse", - "base": "VnModel", - "options": { - "mysql": { - "table": "warehouse", - "database": "vn" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "name": { - "type": "String", - "required": true - } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ] - } diff --git a/services/item/package.json b/services/item/package.json deleted file mode 100644 index 7a9c9b48a..000000000 --- a/services/item/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "vn-item", - "version": "1.0.0", - "main": "server/server.js", - "scripts": { - "lint": "eslint .", - "start": "node .", - "posttest": "npm run lint && nsp check" - }, - "repository": { - "type": "git", - "url": "https://git.verdnatura.es/salix" - }, - "license": "GPL-3.0", - "description": "vn-item", - "dependencies": { - "uuid": "^3.1.0" - } -} diff --git a/services/item/server/model-config.json b/services/item/server/model-config.json deleted file mode 100644 index 229054dd6..000000000 --- a/services/item/server/model-config.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "Item": { - "dataSource": "vn" - }, - "ItemType": { - "dataSource": "vn" - }, - "Ink": { - "dataSource": "vn" - }, - "Origin": { - "dataSource": "vn" - }, - "Producer": { - "dataSource": "vn" - }, - "Intrastat": { - "dataSource": "vn" - }, - "TaxClass": { - "dataSource": "vn" - }, - "TaxCode": { - "dataSource": "vn" - }, - "TaxType": { - "dataSource": "vn" - }, - "Expence": { - "dataSource": "vn" - }, - "ItemTag": { - "dataSource": "vn" - }, - "Tag": { - "dataSource": "vn" - }, - "ItemNiche": { - "dataSource": "vn" - }, - "ItemLog": { - "dataSource": "vn" - }, - "ItemBarcode": { - "dataSource": "vn" - }, - "ItemBotanical": { - "dataSource": "vn" - }, - "ItemPlacement": { - "dataSource": "vn" - }, - "ItemTaxCountry": { - "dataSource": "vn" - }, - "Warehouse": { - "dataSource": "vn" - }, - "Specie": { - "dataSource": "edi" - }, - "Genus": { - "dataSource": "edi" - } -} diff --git a/services/item/server/server.js b/services/item/server/server.js deleted file mode 100644 index f0493dcd9..000000000 --- a/services/item/server/server.js +++ /dev/null @@ -1,4 +0,0 @@ -var vnLoopback = require('../../loopback/server/server.js'); - -var app = module.exports = vnLoopback.loopback(); -vnLoopback.boot(app, __dirname, module); diff --git a/services/loopback/common/helpers.js b/services/loopback/common/helpers.js deleted file mode 100644 index 49dedffa4..000000000 --- a/services/loopback/common/helpers.js +++ /dev/null @@ -1,23 +0,0 @@ - -exports.UserError = class extends Error { - constructor(message) { - super(message); - this.statusCode = 400; - } -}; - -exports.getFinalState = function(ctx) { - if (ctx.isNewInstance) - return ctx.instance; - if (ctx.currentInstance) - return Object.assign({}, - ctx.currentInstance.__data, - ctx.data || ctx.instance - ); - - return null; -}; - -exports.isMultiple = function(ctx) { - return !ctx.isNewInstance && !ctx.currentInstance; -}; diff --git a/services/loopback/common/locale/en.json b/services/loopback/common/locale/en.json deleted file mode 100644 index ce4eb95f2..000000000 --- a/services/loopback/common/locale/en.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "PHONE_INVALID_FORMAT": "The phone format is invalid", - "You are not allowed to change the credit": "You are not allowed to change the credit", - "Unable to mark the equivalence surcharge": "Unable to mark the equivalence surcharge", - "The default consignee can not be unchecked": "The default consignee can not be unchecked", - "Unable to default a disabled consignee": "Unable to default a disabled consignee", - "El método de pago seleccionado requiere que se especifique el IBAN": "El método de pago seleccionado requiere que se especifique el IBAN", - "Ya existe un usuario con ese nombre": "Ya existe un usuario con ese nombre" -} \ No newline at end of file diff --git a/services/loopback/common/locale/es.json b/services/loopback/common/locale/es.json deleted file mode 100644 index 7e09dd22c..000000000 --- a/services/loopback/common/locale/es.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "PHONE_INVALID_FORMAT": "El formato del teléfono no es correcto", - "You are not allowed to change the credit": "No tienes privilegios para modificar el crédito", - "Unable to mark the equivalence surcharge": "No se puede marcar el recargo de equivalencia", - "The default consignee can not be unchecked": "No se puede desmarcar el consignatario predeterminado", - "Unable to default a disabled consignee": "No se puede poner predeterminado un consignatario desactivado", - "El método de pago seleccionado requiere que se especifique el IBAN": "El método de pago seleccionado requiere que se especifique el IBAN", - "can't be blank": "can't be blank" -} \ No newline at end of file diff --git a/services/loopback/common/methods/client/activate.js b/services/loopback/common/methods/client/activate.js deleted file mode 100644 index acc89d6d0..000000000 --- a/services/loopback/common/methods/client/activate.js +++ /dev/null @@ -1,62 +0,0 @@ -var request = require('request'); - -module.exports = function(Self) { - Self.remoteMethod('activate', { - description: 'Activate or deactive client', - accepts: [ - { - arg: 'id', - type: 'number', - required: true, - description: 'Model id', - http: {source: 'path'} - }, { - arg: 'context', - type: 'object', - http: function(ctx) { - return ctx; - } - } - ], - returns: { - arg: 'active', - type: 'boolean' - }, - http: { - verb: 'put', - path: '/:id/activate' - } - }); - - Self.activate = function(id, ctx, cb) { - Self.findById(id, function(err, client) { - if (err) return cb(err); - - Self.update({id: client.id}, {active: !client.active}); - - let filter = {where: {clientFk: client.id}, fields: ['started', 'ended']}; - - Self.app.models.CreditClassification.findOne(filter, function(error, data) { - if (error) return; - - let currentDate = new Date(); - - if (data && client.active && (data.ended >= currentDate || data.ended == null)) { - let referer = ctx.req.headers.referer; - var options = { - url: `${referer}/mailer/notification/client-deactivate/${client.id}`, - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: ctx.req.headers.authorization - }, - json: {} - }; - request(options); - } - }); - - cb(null, !client.active); - }); - }; -}; diff --git a/services/loopback/common/methods/client/activeSalesPerson.js b/services/loopback/common/methods/client/activeSalesPerson.js deleted file mode 100644 index 27060d1e4..000000000 --- a/services/loopback/common/methods/client/activeSalesPerson.js +++ /dev/null @@ -1,73 +0,0 @@ -module.exports = Client => { - Client.remoteMethod('activeSalesPerson', { - description: 'Returns actives workers with salesperson role', - accessType: 'READ', - accepts: [{ - arg: 'filter', - type: 'Object', - required: false, - description: 'Filter defining where and paginated data', - http: {source: 'query'} - }], - returns: { - arg: 'data', - type: 'Worker', - root: true - }, - http: { - path: `/activeSalesPerson`, - verb: 'get' - } - }); - - Client.activeSalesPerson = (filter, callback) => { - let skip = filter.skip || 0; - let limit = filter.limit || 10; - let where = getCondition(filter.where, limit, skip); - - let query = - `SELECT em.id, em.firstName, em.name - FROM worker em - JOIN account.user ac ON em.userFk = ac.id - JOIN account.role r ON r.id = ac.role - WHERE ac.active ${where.sql} - ORDER BY em.name ASC - LIMIT ? OFFSET ?`; - - Client.rawSql(query, where.params).then( - response => callback(null, formatSalesPerson(response)), - err => callback(err) - ); - }; - - function getCondition(where, limit, skip) { - let out = { - sql: '', - params: [] - }; - if (where && where.or) { - out.sql = `AND (em.firstName regexp ? OR em.name regexp ?)`; - where.or.forEach(val => { - Object.keys(val).forEach(key => { - out.params.push(val[key].regexp); - }); - }); - } - out.params.push(parseInt(limit, 10)); - out.params.push(parseInt(skip, 10)); - return out; - } - - function formatSalesPerson(response) { - let results = []; - - response.forEach(person => { - results.push({ - id: person.id, - name: `${person.firstName} ${person.name}` - }); - }); - - return results; - } -}; diff --git a/services/loopback/common/methods/client/addressesPropagateRe.js b/services/loopback/common/methods/client/addressesPropagateRe.js deleted file mode 100644 index 64b159339..000000000 --- a/services/loopback/common/methods/client/addressesPropagateRe.js +++ /dev/null @@ -1,43 +0,0 @@ -module.exports = function(Client) { - Client.remoteMethod('addressesPropagateRe', { - description: 'Change property isEqualizated in all client addresses', - accessType: 'WRITE', - accepts: [ - { - arg: 'id', - type: 'string', - required: true, - description: 'Client id', - http: {source: 'path'} - }, - { - arg: 'data', - type: 'Object', - required: true, - description: 'data with new value', - http: {source: 'body'} - } - ], - returns: { - arg: 'data', - type: 'boolean', - root: true - }, - http: { - path: `/:id/addressesPropagateRe`, - verb: 'patch' - } - }); - - Client.addressesPropagateRe = (id, data, callback) => { - if (data.hasOwnProperty('isEqualizated')) { - Client.app.models.Address.updateAll({clientFk: id}, data, (err, info) => { - if (err) - return callback(err, null); - callback(null, true); - }); - } else { - callback(null, false); - } - }; -}; diff --git a/services/loopback/common/methods/client/card.js b/services/loopback/common/methods/client/card.js deleted file mode 100644 index 14a9f2fed..000000000 --- a/services/loopback/common/methods/client/card.js +++ /dev/null @@ -1,76 +0,0 @@ -module.exports = function(Self) { - Self.remoteMethod('card', { - description: 'Get client basic data', - accepts: { - arg: 'id', - type: 'number', - required: true, - description: 'The client id', - http: {source: 'path'} - }, - returns: { - arg: 'data', - type: 'Object', - root: true - }, - http: { - verb: 'GET', - path: '/:id/card' - } - }); - - Self.card = function(id, cb) { - let filter = { - where: { - id: id - }, - include: [ - { - relation: 'salesPerson', - scope: { - fields: ['id', 'firstName', 'name'] - } - }, { - relation: 'contactChannel', - scope: { - fields: ['id', 'name'] - } - }, { - relation: 'province', - scope: { - fields: ['id', 'name'] - } - }, { - relation: 'country', - scope: { - fields: ['id', 'country'] - } - }, { - relation: 'payMethod', - scope: { - fields: ['id', 'name'] - } - }, { - relation: 'account', - scope: { - fields: ['id', 'name', 'active'] - } - } - ] - }; - - Self.findOne(filter, function(err, card) { - if (err) return cb(err); - - let formatedCard = JSON.parse(JSON.stringify(card)); - - if (formatedCard.salesPersonFk) - formatedCard.salesPerson = { - id: card.salesPerson().id, - name: `${card.salesPerson().firstName} ${card.salesPerson().name}` - }; - - cb(null, formatedCard); - }); - }; -}; diff --git a/services/loopback/common/methods/client/createWithUser.js b/services/loopback/common/methods/client/createWithUser.js deleted file mode 100644 index f5220a839..000000000 --- a/services/loopback/common/methods/client/createWithUser.js +++ /dev/null @@ -1,48 +0,0 @@ -module.exports = function(Self) { - Self.remoteMethod('createWithUser', { - description: 'Creates both client and its web account', - accepts: { - arg: 'data', - type: 'object', - http: {source: 'body'} - }, - returns: { - root: true, - type: 'boolean' - }, - http: { - verb: 'post', - path: '/createWithUser' - } - }); - - Self.createWithUser = async data => { - let firstEmail = data.email ? data.email.split(',')[0] : null; - let user = { - name: data.userName, - email: firstEmail, - password: parseInt(Math.random() * 100000000000000) - }; - let Account = Self.app.models.Account; - - let transaction = await Account.beginTransaction({}); - - try { - let account = await Account.create(user, {transaction}); - let client = { - id: account.id, - name: data.name, - fi: data.fi, - socialName: data.socialName, - email: data.email, - salesPersonFk: data.salesPersonFk - }; - newClient = await Self.create(client, {transaction}); - await transaction.commit(); - return newClient; - } catch (e) { - transaction.rollback(); - throw e; - } - }; -}; diff --git a/services/loopback/common/methods/client/filter.js b/services/loopback/common/methods/client/filter.js deleted file mode 100644 index bb1288630..000000000 --- a/services/loopback/common/methods/client/filter.js +++ /dev/null @@ -1,61 +0,0 @@ -module.exports = function(Client) { - Client.installMethod('filter', filterClients); - - function filterClients(params) { - let filters = { - where: {}, - skip: (params.page - 1) * params.size, - limit: params.size - }; - - delete params.page; - delete params.size; - - if (params.search) { - filters.where.and = [ - { - or: [ - {id: params.search}, - {name: {regexp: params.search}} - ] - } - ]; - delete params.search; - } - - if (params.phone) { - let phones = [ - {phone: params.phone}, - {mobile: params.phone} - ]; - if (filters.where.and) { - filters.where.and.push( - { - or: phones - } - ); - } else { - filters.where.or = phones; - } - delete params.phone; - } - - let properties = Object.keys(params); - if (properties.length) { - properties.forEach( - property => { - let propertyToBeEqual = (property === 'postcode' || property === 'fi' || property === 'id'); - if (filters.where.and) { - let filter = {}; - filter[property] = propertyToBeEqual ? params[property] : {regexp: params[property]}; - filters.where.and.push(filter); - } else { - filters.where[property] = propertyToBeEqual ? params[property] : {regexp: params[property]}; - } - } - ); - } - - return filters; - } -}; diff --git a/services/loopback/common/methods/client/listAddresses.js b/services/loopback/common/methods/client/listAddresses.js deleted file mode 100644 index e350b56f3..000000000 --- a/services/loopback/common/methods/client/listAddresses.js +++ /dev/null @@ -1,70 +0,0 @@ -module.exports = function(Client) { - Client.remoteMethod('listAddresses', { - description: 'List items using a filter', - accessType: 'READ', - accepts: [ - { - arg: 'id', - type: 'string', - required: true, - description: 'Model id', - http: {source: 'path'} - }, - { - arg: 'filter', - type: 'object', - required: true, - description: 'Filter defining where', - http: function(ctx) { - return ctx.req.query; - } - } - ], - returns: { - arg: 'data', - type: ['Address'], - root: true - }, - http: { - path: `/:id/listAddresses`, - verb: 'GET' - } - }); - - Client.listAddresses = function(id, params, callback) { - let filter = { - where: { - clientFk: id - }, - skip: (params.page - 1) * params.size, - limit: params.size, - order: ['isDefaultAddress DESC', 'isActive DESC', 'nickname ASC'], - include: {observations: 'observationType'} - }; - - let total = null; - let items = null; - - function response(type, value) { - if (type === 'total') { - total = value; - } else { - items = value; - } - - if (total !== null && items !== null) { - callback(null, {total: total, items: items}); - } - } - - Client.app.models.Address.find(filter, function(err, instances) { - if (err) return callback(err); - response('find', instances); - }); - - Client.app.models.Address.count(filter.where, function(err, total) { - if (err) return callback(err); - response('total', total); - }); - }; -}; diff --git a/services/loopback/common/methods/client/specs/activeSalesperson.spec.js b/services/loopback/common/methods/client/specs/activeSalesperson.spec.js deleted file mode 100644 index 3dc6da231..000000000 --- a/services/loopback/common/methods/client/specs/activeSalesperson.spec.js +++ /dev/null @@ -1,33 +0,0 @@ -const app = require('../../../../../client/server/server'); -const catchErrors = require('../../../../../../services/utils/jasmineHelpers').catchErrors; - -describe('Client activeSalesPerson', () => { - it('should call the activeSalesPerson() method with limit of 1', done => { - let filter = { - limit: 1 - }; - - let callback = (error, result) => { - if (error) return catchErrors(done)(error); - - expect(result.length).toEqual(1); - done(); - }; - - app.models.Client.activeSalesPerson(filter, callback); - }); - - it('should call the activeSalesPerson() method with no limit and receive all 10 salesPersons', done => { - let filter = { - }; - - let callback = (error, result) => { - if (error) return catchErrors(done)(error); - - expect(result.length).toEqual(10); - done(); - }; - - app.models.Client.activeSalesPerson(filter, callback); - }); -}); diff --git a/services/loopback/common/methods/client/specs/addressesPropagateRe.spec.js b/services/loopback/common/methods/client/specs/addressesPropagateRe.spec.js deleted file mode 100644 index 47cef837e..000000000 --- a/services/loopback/common/methods/client/specs/addressesPropagateRe.spec.js +++ /dev/null @@ -1,44 +0,0 @@ -const app = require('../../../../../client/server/server'); -const catchErrors = require('../../../../../../services/utils/jasmineHelpers').catchErrors; -const restoreFixtures = require('../../../../../../services/db/testing_fixtures'); - -describe('Client addressesPropagateRe', () => { - let sqlStatements = {deletes: ``, inserts: ``, updates: - `UPDATE vn.address SET isEqualizated = 0 WHERE clientFk = 101;` - }; - beforeEach(() => { - restoreFixtures(sqlStatements); - }); - - afterAll(() => { - restoreFixtures(sqlStatements); - }); - - it('should propagate the isEqualizated on both addresses of Mr Wayne', done => { - let id = 101; - let data = { - isEqualizated: true - }; - - let callback = (error, result) => { - if (error) return catchErrors(done)(error); - - expect(result).toBe(true); - app.models.Address.find({where: {clientFk: id}}) - .then(result => { - expect(result[0].isEqualizated).toBeTruthy(); - expect(result[1].isEqualizated).toBeTruthy(); - done(); - }); - }; - app.models.Address.find({where: {clientFk: id}}) - .then(result => { - expect(result[0].isEqualizated).toBeFalsy(); - expect(result[1].isEqualizated).toBeFalsy(); - }) - .then(() => { - app.models.Client.addressesPropagateRe(id, data, callback); - }) - .catch(catchErrors(done)); - }); -}); diff --git a/services/loopback/common/methods/client/specs/card.spec.js b/services/loopback/common/methods/client/specs/card.spec.js deleted file mode 100644 index 1737dd957..000000000 --- a/services/loopback/common/methods/client/specs/card.spec.js +++ /dev/null @@ -1,20 +0,0 @@ -const app = require('../../../../../client/server/server'); -const catchErrors = require('../../../../../../services/utils/jasmineHelpers').catchErrors; - -describe('Client card', () => { - it('should call the card() method to receive a formated card of Bruce Wayne', done => { - let id = 101; - - let callback = (error, result) => { - if (error) return catchErrors(done)(error); - - expect(result).toEqual(jasmine.objectContaining({ - id: 101, - name: 'Bruce Wayne' - })); - done(); - }; - - app.models.Client.card(id, callback); - }); -}); diff --git a/services/loopback/common/methods/client/specs/createWithUser.spec.js b/services/loopback/common/methods/client/specs/createWithUser.spec.js deleted file mode 100644 index 25f6789fb..000000000 --- a/services/loopback/common/methods/client/specs/createWithUser.spec.js +++ /dev/null @@ -1,86 +0,0 @@ -const app = require('../../../../../client/server/server'); -const catchErrors = require('../../../../../../services/utils/jasmineHelpers').catchErrors; -const restoreFixtures = require('../../../../../../services/db/testing_fixtures'); - -describe('Client Create', () => { - let sqlStatements = {deletes: ` - DELETE FROM vn.address WHERE nickname = "Wade"; - DELETE FROM vn.client WHERE name = "Wade"; - DELETE FROM account.user WHERE name = "Deadpool"; - `, inserts: ``, updates: ``}; - - beforeAll(() => { - restoreFixtures(sqlStatements); - }); - - afterAll(() => { - restoreFixtures(sqlStatements); - }); - - let newAccountData = { - active: true, - name: 'Wade', - userName: 'Deadpool', - email: 'Deadpool@marvel.com', - fi: '16195279J', - socialName: 'Deadpool Marvel', - salesPersonFk: 1 - }; - - it('should find Charles Xavier', done => { - app.models.Account.findOne({where: {name: 'CharlesXavier'}}) - .then(account => { - expect(account.name).toEqual('CharlesXavier'); - done(); - }); - }); - - it(`should not find Deadpool as he's not created yet`, done => { - app.models.Account.findOne({where: {name: newAccountData.userName}}) - .then(account => { - expect(account).toEqual(null); - app.models.Client.findOne({where: {name: newAccountData.name}}) - .then(client => { - expect(client).toEqual(null); - done(); - }); - }) - .catch(catchErrors(done)); - }); - - it('should not be able to create a user if exists', async() => { - let client = await app.models.Client.findOne({where: {name: 'Charles Xavier'}}); - let account = await app.models.Account.findOne({where: {id: client.id}}); - - let formerAccountData = { - name: client.name, - userName: account.name, - email: client.email, - fi: client.fi, - socialName: client.socialName - }; - - try { - let client = await app.models.Client.createWithUser(formerAccountData); - - expect(client).toBeNull(); - } catch (err) { - expect(err.details.codes.name[0]).toEqual('uniqueness'); - } - }); - - it('should create a new account', async() => { - let client = await app.models.Client.createWithUser(newAccountData); - let account = await app.models.Account.findOne({where: {name: newAccountData.userName}}); - - expect(account.name).toEqual(newAccountData.userName); - - client = await app.models.Client.findOne({where: {name: newAccountData.name}}); - - expect(client.id).toEqual(account.id); - expect(client.name).toEqual(newAccountData.name); - expect(client.email).toEqual(newAccountData.email); - expect(client.fi).toEqual(newAccountData.fi); - expect(client.socialName).toEqual(newAccountData.socialName); - }); -}); diff --git a/services/loopback/common/methods/client/specs/getDebt.spec.js b/services/loopback/common/methods/client/specs/getDebt.spec.js deleted file mode 100644 index c79cb9058..000000000 --- a/services/loopback/common/methods/client/specs/getDebt.spec.js +++ /dev/null @@ -1,16 +0,0 @@ -const getDebt = require('../getDebt'); - -describe('client getDebt()', () => { - it('should call the getDebt method', done => { - let clientFk = 109; - let self = jasmine.createSpyObj('self', ['remoteMethod', 'rawSql']); - self.rawSql.and.returnValue(Promise.resolve([{debt: 100}])); - getDebt(self); - self.getDebt(clientFk) - .then(result => { - expect(result.debt).toEqual(100); - done(); - }); - }); -}); - diff --git a/services/loopback/common/methods/client/specs/isValidClient.spec.js b/services/loopback/common/methods/client/specs/isValidClient.spec.js deleted file mode 100644 index 35c9264d7..000000000 --- a/services/loopback/common/methods/client/specs/isValidClient.spec.js +++ /dev/null @@ -1,57 +0,0 @@ -const app = require('../../../../../client/server/server'); - -describe('Client isValidClient', () => { - it('should call the isValidClient() method with a client id and receive true', done => { - let id = 101; - app.models.Client.isValidClient(id) - .then(result => { - expect(result).toBeTruthy(); - done(); - }); - }); - - it('should call the isValidClient() method with a employee id and receive false', done => { - let id = 1; - app.models.Client.isValidClient(id) - .then(result => { - expect(result).toBeFalsy(); - done(); - }); - }); - - it('should call the isValidClient() method with a unexistant id and receive false', done => { - let id = 999999; - app.models.Client.isValidClient(id) - .then(result => { - expect(result).toBeFalsy(); - done(); - }); - }); - - it('should call the isValidClient() method with a invalid id and receive false', done => { - let id = 'Pepinillos'; - app.models.Client.isValidClient(id) - .then(result => { - expect(result).toBeFalsy(); - done(); - }); - }); - - it('should call the isValidClient() method with a customer id which isnt active and return false', done => { - let id = '106'; - app.models.Client.isValidClient(id) - .then(result => { - expect(result).toBeFalsy(); - done(); - }); - }); - - it('should call the isValidClient() method with a customer id which his data isnt verified and return false', done => { - let id = '110'; - app.models.Client.isValidClient(id) - .then(result => { - expect(result).toBeFalsy(); - done(); - }); - }); -}); diff --git a/services/loopback/common/methods/client/specs/listAddresses.spec.js b/services/loopback/common/methods/client/specs/listAddresses.spec.js deleted file mode 100644 index d4a5503d0..000000000 --- a/services/loopback/common/methods/client/specs/listAddresses.spec.js +++ /dev/null @@ -1,20 +0,0 @@ -const app = require('../../../../../client/server/server'); -const catchErrors = require('../../../../../../services/utils/jasmineHelpers').catchErrors; - -describe('Client addresses', () => { - it('should call the listAddresses method and receive total results and items', done => { - let id = 1; - let params = { - page: 1, - size: 1 - }; - - let callback = (error, result) => { - if (error) return catchErrors(done)(error); - - expect(Object.keys(result)).toEqual(['total', 'items']); - done(); - }; - app.models.Client.listAddresses(id, params, callback); - }); -}); diff --git a/services/loopback/common/methods/client/specs/listWorkers.spec.js b/services/loopback/common/methods/client/specs/listWorkers.spec.js deleted file mode 100644 index 52bd5f3b7..000000000 --- a/services/loopback/common/methods/client/specs/listWorkers.spec.js +++ /dev/null @@ -1,15 +0,0 @@ -const app = require('../../../../../client/server/server'); -const catchErrors = require('../../../../../../services/utils/jasmineHelpers').catchErrors; - -describe('Client listWorkers', () => { - it('should call the listWorkers()', done => { - app.models.Client.listWorkers() - .then(result => { - let amountOfEmployees = Object.keys(result).length; - - expect(amountOfEmployees).toEqual(37); - done(); - }) - .catch(catchErrors(done)); - }); -}); diff --git a/services/loopback/common/methods/state/list.js b/services/loopback/common/methods/state/list.js deleted file mode 100644 index da2c0c9e5..000000000 --- a/services/loopback/common/methods/state/list.js +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = State => { - var serverFilter = {where: {order: {gt: 0}}, order: "order, name"}; - State.defineScope(serverFilter); -}; diff --git a/services/loopback/common/methods/ticket-state/change-state.js b/services/loopback/common/methods/ticket-state/change-state.js deleted file mode 100644 index 8bdc6ffd5..000000000 --- a/services/loopback/common/methods/ticket-state/change-state.js +++ /dev/null @@ -1,56 +0,0 @@ -module.exports = function(Self) { - Self.remoteMethodCtx('changeState', { - description: 'Change state of tickets', - accepts: [ - { - arg: 'state', - type: 'number', - required: true, - description: 'New state', - http: {source: 'path'} - } - ], - returns: { - arg: 'response', - type: 'boolean' - }, - http: { - verb: 'put', - path: '/:state/changeState' - } - }); - - Self.changeState = function(ctx, state, cb) { - var tickets = ctx.req.body.tickets; - - Self.connectToService(ctx, "client"); - - Self.app.models.Worker.findOne({where: {userFk: ctx.req.accessToken.userId}}, function(err, emp) { - if (err) - cb(err, null); - else - changeState(emp.id, tickets, state, cb); - }); - - Self.disconnectFromService("client"); - }; - - function changeState(emp, tickets, state, cb) { - var inserts = []; - var FakeProduction = Self.app.models.FakeProduction; - - tickets.forEach(function(t) { - inserts.push({ticketFk: t, stateFk: state, workerFk: emp}); - }, this); - - Self.create(inserts, function(err, res) { - if (err) - cb(err, null); - else { - FakeProduction.updateAll({ticketFk: {inq: tickets}}, {stateFk: state}, function(err, info) { - cb(err, info); - }); - } - }); - } -}; diff --git a/services/loopback/common/methods/ticket/change-time.js b/services/loopback/common/methods/ticket/change-time.js deleted file mode 100644 index 497700b2c..000000000 --- a/services/loopback/common/methods/ticket/change-time.js +++ /dev/null @@ -1,37 +0,0 @@ -module.exports = function(Ticket) { - Ticket.remoteMethodCtx('changeTime', { - description: 'Change time of tickets', - accepts: [{ - arg: 'time', - type: 'string', - required: true, - description: 'New time of tickets', - http: {source: 'path'} - }], - returns: { - arg: 'response', - type: 'boolean' - }, - http: { - verb: 'put', - path: '/:time/changeTime' - } - }); - Ticket.changeTime = function(ctx, time, cb) { - var tickets = ctx.req.body.tickets; - var FakeProduction = Ticket.app.models.FakeProduction; - var hour = `${time}:00`; - - var query = `update Ticket set date = CONCAT(DATE(date), ' ', ?) where id in (?)`; - var params = [hour, tickets]; - - FakeProduction.updateAll({ticketFk: {inq: tickets}}, {hour: hour}, function(err, res) { - if (err) - cb(err, null); - else - Ticket.rawSql(query, params, cb).then(function(response) { - cb(null, response); - }); - }); - }; -}; diff --git a/services/loopback/common/methods/ticket/list.js b/services/loopback/common/methods/ticket/list.js deleted file mode 100644 index 22567838e..000000000 --- a/services/loopback/common/methods/ticket/list.js +++ /dev/null @@ -1,19 +0,0 @@ -module.exports = function(Ticket) { - Ticket.remoteMethod('list', { - description: 'List tickets for production', - returns: { - arg: 'tickets', - type: 'object' - }, - http: { - verb: 'get', - path: '/list' - } - }); - - Ticket.list = function(cb) { - var params = [1, 0]; - var query = 'CALL production_control_source(?, ?)'; - Ticket.rawSql(query, params, cb); - }; -}; diff --git a/services/loopback/common/methods/vnModel/installCrudModel.js b/services/loopback/common/methods/vnModel/installCrudModel.js deleted file mode 100644 index a9227ce21..000000000 --- a/services/loopback/common/methods/vnModel/installCrudModel.js +++ /dev/null @@ -1,46 +0,0 @@ -module.exports = function(Self) { - Self.installCrudModel = function(methodName) { - let Model = this; - Model.remoteMethod(methodName, { - description: 'create, update or delete model', - accessType: 'WRITE', - accepts: [ - { - arg: 'crudStruct', - type: 'Object', - require: true, - description: 'object with instances of model to create, update or delete, Example: {create: [], update: [], delete: []}', - http: {source: 'body'} - } - ], - http: { - path: `/${methodName}`, - verb: 'post' - } - }); - Model[methodName] = async crudStruct => { - let promises = []; - let tx = await Model.beginTransaction({}); - let options = {transaction: tx}; - - try { - if (crudStruct.delete && crudStruct.delete.length) { - promises.push(Model.destroyAll({id: {inq: crudStruct.delete}}, options)); - } - if (crudStruct.create.length) { - promises.push(Model.create(crudStruct.create, options)); - } - if (crudStruct.update.length) { - crudStruct.update.forEach(toUpdate => { - promises.push(Model.upsert(toUpdate, options)); - }); - } - await Promise.all(promises); - await tx.commit(); - } catch (e) { - await tx.rollback(); - throw e; - } - }; - }; -}; diff --git a/services/loopback/common/methods/vnModel/installMethod.js b/services/loopback/common/methods/vnModel/installMethod.js deleted file mode 100644 index 94eb41f85..000000000 --- a/services/loopback/common/methods/vnModel/installMethod.js +++ /dev/null @@ -1,94 +0,0 @@ -module.exports = function(Self) { - Self.installMethod = function(methodName, filterCb, filterResult) { - this.remoteMethod(methodName, { - description: 'List items using a filter', - accessType: 'READ', - accepts: [ - { - arg: 'filter', - type: 'object', - required: true, - description: 'Filter defining where', - http: function(ctx) { - return ctx.req.query; - } - } - ], - returns: { - arg: 'data', - type: [this.modelName], - root: true - }, - http: { - verb: 'get', - path: `/${methodName}` - } - }); - - this[methodName] = (params, cb) => { - let filter = removeEmpty(filterCb(params)); - - var response = {}; - - function returnValues() { - if (response.instances !== undefined && response.count !== undefined) { - if (filterResult) - cb(null, filterResult(response)); - else - cb(null, response); - } - } - - function error() { - cb(null, response); - } - - this.find(filter, function(err, instances) { - if (err) { - error(); - } else { - response.instances = instances; - returnValues(); - } - }); - - this.count(filter.where, function(err, totalCount) { - if (err) { - error(); - } else { - response.count = totalCount; - returnValues(); - } - }); - }; - }; -}; - -function removeEmpty(o) { - if (Array.isArray(o)) { - let array = []; - for (let item of o) { - let i = removeEmpty(item); - if (!isEmpty(i)) - array.push(i); - } - if (array.length > 0) - return array; - } else if (typeof o === 'object') { - let object = {}; - for (let key in o) { - let i = removeEmpty(o[key]); - if (!isEmpty(i)) - object[key] = i; - } - if (Object.keys(object).length > 0) - return object; - } else if (!isEmpty(o)) - return o; - - return undefined; -} - -function isEmpty(value) { - return value === undefined || value === ''; -} diff --git a/services/loopback/common/methods/vnModel/rawSql.js b/services/loopback/common/methods/vnModel/rawSql.js deleted file mode 100644 index 9b8a0a07e..000000000 --- a/services/loopback/common/methods/vnModel/rawSql.js +++ /dev/null @@ -1,15 +0,0 @@ -module.exports = function(Self) { - Self.rawSql = function(query, params, cb) { - var connector = this.dataSource.connector; - return new Promise(function(resolve, reject) { - connector.execute(query, params, function(error, response) { - if (cb) - cb(error, response); - if (error) - reject(error); - else - resolve(response); - }); - }); - }; -}; diff --git a/services/loopback/common/methods/vnModel/specs/installCrudModel.spec.js b/services/loopback/common/methods/vnModel/specs/installCrudModel.spec.js deleted file mode 100644 index b31eb82fb..000000000 --- a/services/loopback/common/methods/vnModel/specs/installCrudModel.spec.js +++ /dev/null @@ -1,17 +0,0 @@ -// const catchErrors = require('../../../../../../services/utils/jasmineHelpers').catchErrors; -const app = require('../../../../../item/server/server'); - -describe('Model installCrudModel()', () => { - it('all models extends installCrudModel propertie', () => { - let someModel = app.models.Item; - - expect(someModel.installCrudModel).toBeDefined(); - }); - - it('installCrudModel() create a new remothed method', () => { - let someModel = app.models.Item; - someModel.installCrudModel('someCrudMethod'); - - expect(someModel.someCrudMethod).toBeDefined(); - }); -}); diff --git a/services/loopback/common/methods/vnModel/validateBinded.js b/services/loopback/common/methods/vnModel/validateBinded.js deleted file mode 100644 index 3e5e3f156..000000000 --- a/services/loopback/common/methods/vnModel/validateBinded.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = function(Self) { - Self.validateBinded = function(propertyName, validatorFn, options) { - var customValidator = function(err) { - if (!validatorFn(this[propertyName])) err(); - }; - options.isExportable = true; - options.bindedFunction = validatorFn; - this.validate(propertyName, customValidator, options); - }; -}; diff --git a/services/loopback/common/models/account.js b/services/loopback/common/models/account.js deleted file mode 100644 index 7a3e2a94a..000000000 --- a/services/loopback/common/models/account.js +++ /dev/null @@ -1,45 +0,0 @@ -const md5 = require('md5'); - -module.exports = function(Self) { - // Validations - - Self.validatesUniquenessOf('name', { - message: 'Ya existe un usuario con ese nombre' - }); - - Self.observe('before save', (ctx, next) => { - if (ctx.currentInstance && ctx.currentInstance.id && ctx.data && ctx.data.password) { - ctx.data.password = md5(ctx.data.password); - } - next(); - }); - - Self.remoteMethod('getCurrentUserName', { - description: 'Gets the current user name', - accepts: [ - { - arg: 'context', - type: 'object', - http: function(ctx) { - return ctx; - } - } - ], - returns: { - type: 'string', - root: true - }, - http: { - verb: 'GET', - path: '/getCurrentUserName' - } - }); - - Self.getCurrentUserName = async function(ctx) { - let filter = {fields: ['name']}; - let userId = ctx.req.accessToken.userId; - let account = await Self.findById(userId, filter); - - return account.name; - }; -}; diff --git a/services/loopback/common/models/account.json b/services/loopback/common/models/account.json deleted file mode 100644 index feb90fa7f..000000000 --- a/services/loopback/common/models/account.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "Account", - "base": "VnModel", - "options": { - "mysql": { - "table": "user" - } - }, - "properties": { - "id": { - "type": "number", - "required": true - }, - "name": { - "type": "string", - "required": true - }, - "password": { - "type": "string", - "required": true - }, - "active": { - "type": "boolean" - }, - "email": { - "type": "string" - }, - "created": { - "type": "date" - }, - "updated": { - "type": "date" - } - } -} diff --git a/services/loopback/common/models/address.js b/services/loopback/common/models/address.js deleted file mode 100644 index 151123833..000000000 --- a/services/loopback/common/models/address.js +++ /dev/null @@ -1,49 +0,0 @@ -var UserError = require('../helpers').UserError; -var getFinalState = require('../helpers').getFinalState; -var isMultiple = require('../helpers').isMultiple; - -module.exports = function(Self) { - Self.validate('isDefaultAddress', isActive, - {message: 'Unable to default a disabled consignee'} - ); - function isActive(err) { - if (!this.isActive && this.isDefaultAddress) err(); - } - - Self.beforeRemote('findById', function(ctx, modelInstance, next) { - ctx.args.filter = { - include: [{ - relation: 'province', - scope: { - fields: ['id', 'name'] - } - }, { - relation: 'agencyMode', - scope: { - fields: ['id', 'name'] - } - }] - }; - next(); - }); - - // Helpers - - Self.observe('before save', async function(ctx) { - if (isMultiple(ctx)) return; - - let changes = ctx.data || ctx.instance; - let finalState = getFinalState(ctx); - - if (changes.isActive == false && finalState.isDefaultAddress) - throw new UserError('The default consignee can not be unchecked'); - - if (changes.isDefaultAddress == true && finalState.isActive != false) { - let filter = { - clientFk: finalState.clientFk, - isDefaultAddress: {neq: false} - }; - await Self.updateAll(filter, {isDefaultAddress: false}); - } - }); -}; diff --git a/services/loopback/common/models/agency-mode.json b/services/loopback/common/models/agency-mode.json deleted file mode 100644 index ebac22a77..000000000 --- a/services/loopback/common/models/agency-mode.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "AgencyMode", - "description": "Agency modes", - "base": "VnModel", - "options": { - "mysql": { - "table": "agencyMode" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "name": { - "type": "string", - "required": true - }, - "description": { - "type": "string" - }, - "m3": { - "type": "Number" - }, - "inflation": { - "type": "Number" - }, - "reportMail": { - "type": "string" - } - }, - "relations": { - "agency": { - "type": "belongsTo", - "model": "Agency", - "foreignKey": "agencyFk" - }, - "agencyType": { - "type": "belongsTo", - "model": "AgencyType", - "foreignKey": "agencyTypeFk" - } - } -} diff --git a/services/loopback/common/models/agency.js b/services/loopback/common/models/agency.js deleted file mode 100644 index 591ea68f7..000000000 --- a/services/loopback/common/models/agency.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function(Self) { - Self.defineScope({where: {isManaged: {neq: 0}}}); -}; diff --git a/services/loopback/common/models/client.js b/services/loopback/common/models/client.js deleted file mode 100644 index 928fe43d5..000000000 --- a/services/loopback/common/models/client.js +++ /dev/null @@ -1,180 +0,0 @@ -var UserError = require('../helpers').UserError; -var getFinalState = require('../helpers').getFinalState; -var isMultiple = require('../helpers').isMultiple; - -module.exports = function(Self) { - // Methods - - require('../methods/client/activate')(Self); - require('../methods/client/listAddresses')(Self); - require('../methods/client/card')(Self); - require('../methods/client/createWithUser')(Self); - require('../methods/client/listWorkers')(Self); - require('../methods/client/filter')(Self); - require('../methods/client/hasCustomerRole')(Self); - require('../methods/client/isValidClient')(Self); - require('../methods/client/activeSalesPerson')(Self); - require('../methods/client/addressesPropagateRe')(Self); - require('../methods/client/getDebt')(Self); - - // Validations - - Self.validatesUniquenessOf('fi', { - message: 'El NIF/CIF debe ser único' - }); - Self.validatesUniquenessOf('socialName', { - message: 'La razón social debe ser única' - }); - Self.validatesFormatOf('email', { - message: 'Correo electrónico inválido', - allowNull: true, - allowBlank: true, - with: /^[\w|.|-]+@[\w|-]+(\.[\w|-]+)*(,[\w|.|-]+@[\w|-]+(\.[\w|-]+)*)*$/ - }); - Self.validatesLengthOf('postcode', { - allowNull: true, - allowBlank: true, - min: 3, max: 10 - }); - - var validateIban = require('../validations/validateIban'); - Self.validateBinded('iban', validateIban, { - message: 'El iban no tiene el formato correcto', - allowNull: true, // FIXME: Ignored by loopback when it's false - allowBlank: true - }); - - Self.validateAsync('fi', fiIsValid, { - message: 'DNI Incorrecto' - }); - let validateDni = require('../validations/validateDni'); - async function fiIsValid(err, done) { - let filter = { - fields: ['code'], - where: {id: this.countryFk} - }; - let country = await Self.app.models.Country.findOne(filter); - let code = country ? country.code.toLowerCase() : null; - - if (!validateDni(this.fi, code)) - err(); - done(); - } - - Self.validate('payMethod', hasSalesMan, { - message: 'No se puede cambiar la forma de pago si no hay comercial asignado' - }); - function hasSalesMan(err) { - if (this.payMethod && !this.salesPerson) - err(); - } - - Self.validateAsync('payMethodFk', hasIban, { - message: 'El método de pago seleccionado requiere que se especifique el IBAN' - }); - function hasIban(err, done) { - Self.app.models.PayMethod.findById(this.payMethodFk, (_, instance) => { - if (instance && instance.ibanRequired && !this.iban) - err(); - done(); - }); - } - - // Hooks - - Self.observe('before save', async function(ctx) { - let changes = ctx.data || ctx.instance; - let finalState = getFinalState(ctx); - - if (changes.salesPerson === null) { - changes.credit = 0; - changes.discount = 0; - changes.payMethodFk = 5; // Credit card - } - - if (changes.payMethodFk !== undefined && changes.dueDay === undefined) - changes.dueDay = 5; - - if (isMultiple(ctx)) return; - - if (changes.isEqualizated || changes.fi !== undefined) { - let fiLetter = finalState.fi && finalState.fi.toUpperCase().charAt(0); - let canMarkEqualizationTax = fiLetter != 'A' && fiLetter != 'B'; - - if (finalState.isEqualizated && !canMarkEqualizationTax) - throw new UserError('Unable to mark the equivalence surcharge'); - } - - if (changes.credit !== undefined) { - try { - await validateCreditChange(ctx, finalState); - } catch (e) { - throw new UserError('You are not allowed to change the credit'); - } - let filter = {fields: ['id'], where: {userFk: ctx.options.accessToken.userId}}; - let worker = await Self.app.models.Worker.findOne(filter); - - let newCredit = { - amount: changes.credit, - clientFk: finalState.id, - workerFk: worker ? worker.id : null - }; - await Self.app.models.ClientCredit.create(newCredit); - } - }); - - async function validateCreditChange(ctx, finalState) { - let models = Self.app.models; - let userId = ctx.options.accessToken.userId; - let filter = { - fields: ['roleFk'], - where: { - maxAmount: {gt: ctx.data.credit} - } - }; - - let limits = await models.ClientCreditLimit.find(filter); - - if (limits.length == 0) - throw new Error('Credit limits not found'); - - // Si el usuario no tiene alguno de los roles no continua - - let requiredRoles = []; - for (limit of limits) - requiredRoles.push(limit.roleFk); - - let where = { - roleId: {inq: requiredRoles}, - principalType: 'USER', - principalId: userId - }; - let count = await models.RoleMapping.count(where); - - if (count <= 0) - throw new Error('The role cannot set this credit amount'); - - // Si se puso a 0 por gerencia, solo gerencia puede aumentarlo - - let query = 'SELECT * FROM clientCredit WHERE clientFk = ? ORDER BY created DESC LIMIT 1'; - let instances = await Self.rawSql(query, [finalState.id]); - - if (instances.length !== 1 || instances[0].workerFk == userId || instances[0].amount > 0) - return; - - query = `SELECT COUNT(distinct r.id) > 0 as hasManagerRole - FROM clientCredit cc - JOIN worker em ON em.id = cc.workerFk - JOIN account.user ac ON ac.id = em.userFk - JOIN salix.RoleMapping rm ON rm.principalId = ac.id - JOIN account.role r on r.id = rm.roleId - WHERE rm.principalType = 'USER' - AND cc.workerFk = ? - AND r.name = 'manager'`; - - let instance = await Self.rawSql(query, [instances[0].workerFk]); - - if (instance[0].hasManagerRole > 0) - throw new Error('Only manager can change the credit'); - } -}; diff --git a/services/loopback/common/models/client.json b/services/loopback/common/models/client.json deleted file mode 100644 index c7120e67a..000000000 --- a/services/loopback/common/models/client.json +++ /dev/null @@ -1,161 +0,0 @@ -{ - "name": "Client", - "base": "VnModel", - "options": { - "mysql": { - "table": "client" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "name": { - "type": "string", - "required": true - }, - "fi": { - "type": "string", - "description": "Fiscal indentifier" - }, - "socialName": { - "type": "string", - "required": true - }, - "contact": { - "type": "string" - }, - "street": { - "type": "string" - }, - "city": { - "type": "string" - }, - "postcode": { - "type": "string" - }, - "email": { - "type": "string" - }, - "phone": { - "type": "string" - }, - "mobile": { - "type": "string" - }, - "isActive": { - "type": "boolean" - }, - "credit": { - "type": "Number" - }, - "creditInsurance": { - "type": "Number" - }, - "iban": { - "type": "string" - }, - "dueDay": { - "type": "Number" - }, - "isEqualizated": { - "type": "boolean", - "description": "The client has equalization tax" - }, - "isFreezed": { - "type": "boolean", - "description": "The client frozen" - }, - "hasToInvoiceByAddress": { - "type": "boolean", - "description": "The client has to be invoiced by address" - }, - "hasToInvoice": { - "type": "boolean", - "description": "Global invoicing enabled for the client" - }, - "isToBeMailed": { - "type": "boolean", - "description": "Send invoices by email" - }, - "hasSepaVnl": { - "type": "boolean" - }, - "hasCoreVnl": { - "type": "boolean" - }, - "hasCoreVnh": { - "type": "boolean" - }, - "isTaxDataChecked":{ - "type": "boolean" - }, - "eypbc": { - "type": "boolean" - }, - "quality": { - "type": "Number" - }, - "isVies": { - "type": "boolean" - }, - "isRelevant": { - "type": "boolean" - }, - "accountingAccount": { - "type": "string" - }, - "created": { - "type": "date" - } - }, - "relations": { - "account": { - "type": "belongsTo", - "model": "Account", - "foreignKey": "id" - }, - "payMethod": { - "type": "belongsTo", - "model": "PayMethod", - "foreignKey": "payMethodFk" - }, - "salesPerson": { - "type": "belongsTo", - "model": "Worker", - "foreignKey": "salesPersonFk" - }, - "province":{ - "type": "belongsTo", - "model": "Province", - "foreignKey": "provinceFk" - }, - "country":{ - "type": "belongsTo", - "model": "Country", - "foreignKey": "countryFk" - }, - "contactChannel":{ - "type": "belongsTo", - "model": "ContactChannel", - "foreignKey": "contactChannelFk" - }, - "type": { - "type": "belongsTo", - "model": "ClientType", - "foreignKey": "typeFk" - }, - "addresses": { - "type": "hasMany", - "model": "Address", - "foreignKey": "clientFk" - }, - "greuge": { - "type": "hasMany", - "model": "Greuge", - "foreignKey": "clientFk" - } - } -} \ No newline at end of file diff --git a/services/loopback/common/models/country.json b/services/loopback/common/models/country.json deleted file mode 100644 index c9523e8a3..000000000 --- a/services/loopback/common/models/country.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "Country", - "description": "Worldwide countries", - "base": "VnModel", - "options": { - "mysql": { - "table": "country" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "country": { - "type": "string", - "required": true - }, - "code": { - "type": "string" - } - }, - "relations": { - "currency": { - "type": "belongsTo", - "model": "Currency", - "foreignKey": "currencyFk" - } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ] -} \ No newline at end of file diff --git a/services/loopback/common/models/route.json b/services/loopback/common/models/route.json deleted file mode 100644 index 1bfddd3de..000000000 --- a/services/loopback/common/models/route.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "Route", - "base": "VnModel", - "options": { - "mysql": { - "table": "route" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "date": { - "type": "date" - } - } -} \ No newline at end of file diff --git a/services/loopback/common/models/state.js b/services/loopback/common/models/state.js deleted file mode 100644 index dde01b36a..000000000 --- a/services/loopback/common/models/state.js +++ /dev/null @@ -1,4 +0,0 @@ - -module.exports = function(Self) { - require('../methods/state/list.js')(Self); -}; diff --git a/services/loopback/common/models/state.json b/services/loopback/common/models/state.json deleted file mode 100644 index f69969688..000000000 --- a/services/loopback/common/models/state.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "State", - "base": "VnModel", - "options": { - "mysql": { - "table": "state" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "forceId": false - }, - "name": { - "type": "String", - "required": false - }, - "order":{ - "type": "Number", - "required": false - }, - "alertLevel":{ - "type": "Number", - "required": false - }, - "code":{ - "type": "String", - "required": false - } - } -} diff --git a/services/loopback/common/models/ticket-state.js b/services/loopback/common/models/ticket-state.js deleted file mode 100644 index 2580d98db..000000000 --- a/services/loopback/common/models/ticket-state.js +++ /dev/null @@ -1,4 +0,0 @@ - -module.exports = function(Self) { - require('../methods/ticket-state/change-state.js')(Self); -}; diff --git a/services/loopback/common/models/ticket-state.json b/services/loopback/common/models/ticket-state.json deleted file mode 100644 index 693dc7b87..000000000 --- a/services/loopback/common/models/ticket-state.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "TicketState", - "base": "VnModel", - "options": { - "mysql": { - "table": "ticketState" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "forceId": false - }, - "updated": { - "type": "Date", - "required": false - } - }, - "relations": { - "ticket": { - "type": "belongsTo", - "model": "Ticket", - "foreignKey": "ticketFk" - }, - "state": { - "type": "belongsTo", - "model": "State", - "foreignKey": "stateFk" - }, - "worker": { - "type": "belongsTo", - "model": "Worder", - "foreignKey": "workerFk" - } - } -} diff --git a/services/loopback/common/models/ticket.js b/services/loopback/common/models/ticket.js deleted file mode 100644 index f390c559f..000000000 --- a/services/loopback/common/models/ticket.js +++ /dev/null @@ -1,5 +0,0 @@ - -module.exports = function(Self) { - require('../methods/ticket/change-time.js')(Self); - require('../methods/ticket/change-worker.js')(Self); -}; diff --git a/services/loopback/common/models/ticket.json b/services/loopback/common/models/ticket.json deleted file mode 100644 index 493c18a78..000000000 --- a/services/loopback/common/models/ticket.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "name": "Ticket", - "base": "VnModel", - "options": { - "mysql": { - "table": "ticket" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "description": "Identifier" - }, - "shipped": { - "type": "date", - "required": true - }, - "landed": { - "type": "date" - }, - "nickname": { - "type": "String" - }, - "location": { - "type": "String" - }, - "solution": { - "type": "String" - }, - "packages": { - "type": "Number" - }, - "created": { - "type": "date" - } - }, - "relations": { - "client": { - "type": "belongsTo", - "model": "Client", - "foreignKey": "clientFk" - }, - "warehouse": { - "type": "belongsTo", - "model": "Warehouse", - "foreignKey": "warehouseFk" - }, - "invoiceOut": { - "type": "belongsTo", - "model": "InvoiceOut", - "foreignKey": "refFk" - }, - "address": { - "type": "belongsTo", - "model": "Address", - "foreignKey": "addressFk" - }, - "route": { - "type": "belongsTo", - "model": "Route", - "foreignKey": "routeFk" - }, - "company": { - "type": "belongsTo", - "model": "Company", - "foreignKey": "companyFk" - }, - "agencyMode": { - "type": "belongsTo", - "model": "AgencyMode", - "foreignKey": "agencyModeFk", - "required": true - } - } - } \ No newline at end of file diff --git a/services/loopback/common/models/user.json b/services/loopback/common/models/user.json deleted file mode 100644 index 2f79cebdb..000000000 --- a/services/loopback/common/models/user.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "user", - "base": "User", - "properties": { - "id": { - "id": true, - "type": "Number", - "forceId": false - }, - "username":{ - "type": "string" - } - } -} \ No newline at end of file diff --git a/services/loopback/common/models/vn-model.js b/services/loopback/common/models/vn-model.js deleted file mode 100644 index abac75625..000000000 --- a/services/loopback/common/models/vn-model.js +++ /dev/null @@ -1,123 +0,0 @@ -module.exports = function(Self) { - Self.setup = function() { - Self.super_.setup.call(this); - - /* let disableMethods = { - create: true, - replaceOrCreate: true, - patchOrCreate: true, - upsert: true, - updateOrCreate: true, - exists: true, - find: true, - findOne: true, - findById: true, - deleteById: true, - replaceById: true, - updateAttributes: false, - createChangeStream: true, - updateAll: true, - upsertWithWhere: true, - count: true - }; - for (let method in disableMethods) { - // this.disableRemoteMethod(method, disableMethods[method]); - } */ - }; - - Self.defineScope = function(serverFilter) { - this.remoteMethodCtx('list', { - accepts: [ - { - arg: 'filter', - type: 'object', - description: 'Filter defining where' - } - ], - returns: { - type: [this.modelName], - root: true - }, - http: { - verb: 'get', - path: '/list' - } - }); - - this.list = function(ctx, clientFilter, cb) { - let clientFields = (clientFilter && clientFilter.fields) ? clientFilter.fields : []; - let serverFields = (serverFilter && serverFilter.fields) ? serverFilter.fields : []; - let fields = clientFields.filter(itemC => { - return serverFields.some(itemS => itemS === itemC); - }); - let and = []; - let order; - let limit; - let filter = {order: order, limit: limit}; - - if (clientFilter && clientFilter.where) - and.push(clientFilter.where); - if (serverFilter && serverFilter.where) - and.push(serverFilter.where); - - if (clientFilter && clientFilter.order) - order = clientFilter.order; - else if (serverFilter && serverFilter.order) - order = serverFilter.order; - - if (serverFilter && serverFilter.limit) - limit = serverFilter.limit; - else if (clientFilter && clientFilter.limit) - limit = clientFilter.limit; - - filter.where = (and.length > 0) && {and: and}; - filter.fields = fields; - - this.find(filter, function(err, states) { - if (err) - cb(err, null); - else - cb(null, states); - }); - }; - }; - - Self.remoteMethodCtx = function(methodName, args) { - var ctx = { - arg: 'context', - type: 'object', - http: function(ctx) { - return ctx; - } - }; - if (args.accepts === undefined) - args.accepts = []; - else if (!Array.isArray(args.accepts)) - args.accepts = [args.accepts]; - args.accepts.unshift(ctx); - this.remoteMethod(methodName, args); - }; - - Self.getConnection = function(cb) { - this.dataSource.connector.client.getConnection(cb); - }; - - Self.connectToService = function(ctx, dataSource) { - this.app.dataSources[dataSource].connector.remotes.auth = { - bearer: new Buffer(ctx.req.accessToken.id).toString('base64'), - sendImmediately: true - }; - }; - - Self.disconnectFromService = function(dataSource) { - this.app.dataSources[dataSource].connector.remotes.auth = { - bearer: new Buffer('').toString('base64'), - sendImmediately: true - }; - }; - - require('../methods/vnModel/rawSql')(Self); - require('../methods/vnModel/installMethod')(Self); - require('../methods/vnModel/validateBinded')(Self); - require('../methods/vnModel/installCrudModel')(Self); -}; diff --git a/services/loopback/common/models/warehouse.js b/services/loopback/common/models/warehouse.js deleted file mode 100644 index 6e700913b..000000000 --- a/services/loopback/common/models/warehouse.js +++ /dev/null @@ -1,4 +0,0 @@ - -module.exports = function(Self) { - Self.defineScope({where: {isManaged: {neq: 0}}}); -}; diff --git a/services/loopback/common/models/warehouse.json b/services/loopback/common/models/warehouse.json deleted file mode 100644 index 7b6fef1cd..000000000 --- a/services/loopback/common/models/warehouse.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "Warehouse", - "description": "Warehouses from where orders are sent", - "base": "VnModel", - "options": { - "mysql": { - "table": "warehouse" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "forceId": false - }, - "name": { - "type": "String" - }, - "isInventory": { - "type": "Number" - }, - "isManaged":{ - "type":"boolean" - } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ], - "scopes" : { - "production" : {"where": {"isManaged": {"neq": 0}}} - } -} diff --git a/services/loopback/common/models/worker.json b/services/loopback/common/models/worker.json deleted file mode 100644 index f8399be8d..000000000 --- a/services/loopback/common/models/worker.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "Worker", - "description": "Company employees", - "base": "VnModel", - "options": { - "mysql": { - "table": "worker" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "firstName": { - "type": "string", - "required": true - }, - "name": { - "type": "string", - "required": true - } - }, - "relations": { - "user": { - "type": "belongsTo", - "model": "Account", - "foreignKey": "userFk" - } - } -} \ No newline at end of file diff --git a/services/loopback/common/validations/specs/validateDni.spec.js b/services/loopback/common/validations/specs/validateDni.spec.js deleted file mode 100644 index e61ab23c8..000000000 --- a/services/loopback/common/validations/specs/validateDni.spec.js +++ /dev/null @@ -1,101 +0,0 @@ -const validateDni = require('../validateDni'); - -describe('DNI validation', () => { - it('should return true for any DNI when no country is passed', () => { - let isValid = validateDni('Pepinillos'); - - expect(isValid).toBeTruthy(); - }); - - describe('Spanish', () => { - it('should return true for valid spanish DNI', () => { - let isValid = validateDni('20849756A', 'es'); - - expect(isValid).toBeTruthy(); - }); - - it('should return false for spanish DNI with exceeded digits', () => { - let isValid = validateDni('208497563239A', 'es'); - - expect(isValid).toBeFalsy(); - }); - - it('should return false for spanish DNI with invalid letter', () => { - let isValid = validateDni('20243746E', 'es'); - - expect(isValid).toBeFalsy(); - }); - - it('should return true for valid spanish CIF', () => { - let isValid = validateDni('B97367486', 'es'); - - expect(isValid).toBeTruthy(); - }); - - it('should return false for spanish CIF with invalid letter', () => { - let isValid = validateDni('A97527786', 'es'); - - expect(isValid).toBeFalsy(); - }); - }); - - describe('French', () => { - it('should return true for valid french DNI', () => { - let isValid = validateDni('1B123456789', 'fr'); - - expect(isValid).toBeTruthy(); - }); - - it('should return false for french DNI with exceeded digits', () => { - let isValid = validateDni('1B12345678910', 'fr'); - - expect(isValid).toBeFalsy(); - }); - - it('should return false for french DNI with bad syntax', () => { - let isValid = validateDni('1B12345678A', 'fr'); - - expect(isValid).toBeFalsy(); - }); - }); - - describe('Italian', () => { - it('should return true for valid italian DNI', () => { - let isValid = validateDni('12345678911', 'it'); - - expect(isValid).toBeTruthy(); - }); - - it('should return false for italian DNI with exceeded digits', () => { - let isValid = validateDni('123456789112', 'it'); - - expect(isValid).toBeFalsy(); - }); - - it('should return false for italian DNI with bad syntax', () => { - let isValid = validateDni('1234567891A', 'it'); - - expect(isValid).toBeFalsy(); - }); - }); - - describe('Portuguese', () => { - it('should return true for valid portuguese DNI', () => { - let isValid = validateDni('123456789', 'pt'); - - expect(isValid).toBeTruthy(); - }); - - it('should return false for portuguese DNI with exceeded digits', () => { - let isValid = validateDni('12345678910', 'pt'); - - expect(isValid).toBeFalsy(); - }); - - it('should return false for portuguese DNI with bad syntax', () => { - let isValid = validateDni('12345678A', 'pt'); - - expect(isValid).toBeFalsy(); - }); - }); -}); diff --git a/services/loopback/common/validations/validateDni.js b/services/loopback/common/validations/validateDni.js deleted file mode 100644 index b169b6100..000000000 --- a/services/loopback/common/validations/validateDni.js +++ /dev/null @@ -1,72 +0,0 @@ -module.exports = function(fi, country) { - if (fi == null || country == null) - return true; - if (typeof fi != 'string' || typeof country != 'string') - return false; - - fi = fi.toUpperCase(); - country = country.toLowerCase(); - - let len = fi.length; - - let validators = { - es: { - regExp: /^[A-Z0-9]\d{7}[A-Z0-9]$/, - validate: () => { - let isCif = /[A-W]/.test(fi.charAt(0)); - let lastDigit = fi.charAt(len - 1); - let computedDigit; - - if (isCif) { - let numbers = fi.substring(1, 8) - .split('') - .map(x => parseInt(x)); - - let pairSum = numbers - .filter((_, i) => i % 2 != 0) - .reduce((a, x) => a + x); - - let oddSum = numbers - .filter((_, i) => i % 2 == 0) - .map(x => x * 2) - .join('') - .split('') - .map(x => parseInt(x)) - .reduce((a, x) => a + x); - - let sum = (pairSum + oddSum).toString(); - let units = parseInt(sum.charAt(sum.length - 1)); - let control = units == 0 ? 0 : 10 - units; - let index = 'JABCDEFGHI'.indexOf(lastDigit); - computedDigit = index == -1 ? control.toString() : index; - } else { - // Foreign NIF - let index = 'XYZ'.indexOf(fi.charAt(0)); - let nif = index == -1 ? fi : index.toString() + fi.substring(1); - - let rest = parseInt(nif.substring(0, 8)) % 23; - computedDigit = 'TRWAGMYFPDXBNJZSQVHLCKE'.charAt(rest); - } - - return computedDigit == lastDigit; - } - }, - fr: { - regExp: /^[A-Z0-9]{2}\d{9}$/ - }, - it: { - regExp: /^\d{11}$/ - }, - pt: { - regExp: /^\d{9}$/ - } - }; - - let validator = validators[country]; - - if (!validator) - return true; - - return validator.regExp.test(fi) - && (!validator.validate || validator.validate()); -}; diff --git a/services/loopback/common/validations/validateIban.js b/services/loopback/common/validations/validateIban.js deleted file mode 100644 index 2e8883642..000000000 --- a/services/loopback/common/validations/validateIban.js +++ /dev/null @@ -1,53 +0,0 @@ -module.exports = function(iban) { - if (iban == null) return true; - if (typeof iban != 'string') return false; - - iban = iban.toUpperCase(); - iban = trim(iban); - iban = iban.replace(/\s/g, ''); - - if (iban.length != 24) { - return false; - } - - // Se coge las primeras dos letras y se pasan a números - var letter1 = iban.substring(0, 1); - var letter2 = iban.substring(1, 2); - var num1 = getIbanNumber(letter1); - var num2 = getIbanNumber(letter2); - - // Se sustituye las letras por números. - var isbanaux = String(num1) + String(num2) + iban.substring(2); - - // Se mueve los 6 primeros caracteres al final de la cadena. - isbanaux = isbanaux.substring(6) + isbanaux.substring(0, 6); - - // Se calcula el resto, llamando a la función module97, definida más abajo - var resto = module97(isbanaux); - - if (resto == 1) { - return true; - } - - return false; - - function module97(iban) { - var parts = Math.ceil(iban.length / 7); - var remainer = ''; - - for (var i = 1; i <= parts; i++) { - remainer = String(parseFloat(remainer + iban.substr((i - 1) * 7, 7)) % 97); - } - - return remainer; - } - - function getIbanNumber(letra) { - var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - return letters.search(letra) + 10; - } - - function trim(text) { - return (text || '').replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g, ''); - } -}; diff --git a/services/loopback/package-lock.json b/services/loopback/package-lock.json deleted file mode 100644 index 73b6a62e5..000000000 --- a/services/loopback/package-lock.json +++ /dev/null @@ -1,3947 +0,0 @@ -{ - "name": "vn-loopback", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "JSONStream": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-1.0.3.tgz", - "integrity": "sha1-coVEGJQ4t7ndIYQ5JYGGHrq9liE=", - "requires": { - "jsonparse": "1.0.0", - "through": "2.3.8" - } - }, - "abbrev": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", - "integrity": "sha1-+PLIh60Qv2f2NPAFtph/7TF5qsg=" - }, - "accepts": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.4.tgz", - "integrity": "sha1-hiRnWMfdbSGmR0/whKR0DsBesh8=", - "requires": { - "mime-types": "2.1.17", - "negotiator": "0.6.1" - } - }, - "acorn": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.3.0.tgz", - "integrity": "sha1-dEbTlFnFT7SagObuZHgUm5QOyCI=" - }, - "acorn-jsx": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-3.0.1.tgz", - "integrity": "sha1-r9+UiPsezvyDSPb7IvRk4ypYs2s=", - "requires": { - "acorn": "3.3.0" - }, - "dependencies": { - "acorn": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-3.3.0.tgz", - "integrity": "sha1-ReN/s56No/JbruP/U2niu18iAXo=" - } - } - }, - "addressparser": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/addressparser/-/addressparser-1.0.1.tgz", - "integrity": "sha1-R6++GiqSYhkdtoOOT9HTm0CCF0Y=" - }, - "ajv": { - "version": "5.5.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz", - "integrity": "sha1-c7Xuyj+rZT49P5Qis0GtQiBdyWU=", - "requires": { - "co": "4.6.0", - "fast-deep-equal": "1.0.0", - "fast-json-stable-stringify": "2.0.0", - "json-schema-traverse": "0.3.1" - } - }, - "ajv-keywords": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-2.1.1.tgz", - "integrity": "sha1-YXmX/F9gV2iUxDX5QNgZ4TW4B2I=" - }, - "ambi": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/ambi/-/ambi-2.5.0.tgz", - "integrity": "sha1-fI43K+SIkRV+fOoBy2+RQ9H3QiA=", - "requires": { - "editions": "1.3.3", - "typechecker": "4.4.1" - }, - "dependencies": { - "typechecker": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/typechecker/-/typechecker-4.4.1.tgz", - "integrity": "sha1-+XuV9RsDhBchLWd9RaNz7nvO1+Y=", - "requires": { - "editions": "1.3.3" - } - } - } - }, - "ansi-escapes": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.0.0.tgz", - "integrity": "sha1-7D6LTp+AZPwCw6ybZfHCdb2o75I=" - }, - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" - }, - "argparse": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.9.tgz", - "integrity": "sha1-c9g7wmP4bpf4zE9rrhsOkKfSLIY=", - "requires": { - "sprintf-js": "1.0.3" - }, - "dependencies": { - "sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" - } - } - }, - "array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" - }, - "array-union": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", - "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", - "requires": { - "array-uniq": "1.0.3" - } - }, - "array-uniq": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", - "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=" - }, - "arrify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", - "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" - }, - "asn1": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.3.tgz", - "integrity": "sha1-2sh4dxPJlmhJ/IGAd36+nB3fO4Y=" - }, - "assert-plus": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", - "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=" - }, - "async": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "async-hook-jl": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/async-hook-jl/-/async-hook-jl-1.7.6.tgz", - "integrity": "sha1-T9JcL4ZNuvJ5xhDXO/l7GyhZXmg=", - "requires": { - "stack-chain": "1.3.7" - } - }, - "asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" - }, - "aws-sign2": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", - "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=" - }, - "aws4": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.6.0.tgz", - "integrity": "sha1-g+9cqGCysy5KDe7e6MdxudtXRx4=" - }, - "babel-code-frame": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", - "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", - "requires": { - "chalk": "1.1.3", - "esutils": "2.0.2", - "js-tokens": "3.0.2" - }, - "dependencies": { - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "requires": { - "ansi-styles": "2.2.1", - "escape-string-regexp": "1.0.5", - "has-ansi": "2.0.0", - "strip-ansi": "3.0.1", - "supports-color": "2.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "2.1.1" - } - } - } - }, - "babel-runtime": { - "version": "6.26.0", - "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", - "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", - "requires": { - "core-js": "2.5.3", - "regenerator-runtime": "0.11.1" - } - }, - "balanced-match": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" - }, - "base64-js": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.0.2.tgz", - "integrity": "sha1-R0IRyV5s8qVH20YeT2d4tR0I+mU=" - }, - "bcrypt-pbkdf": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.1.tgz", - "integrity": "sha1-Y7xdy2EzG5K8Bf1SiVPDNGKgb40=", - "optional": true, - "requires": { - "tweetnacl": "0.14.5" - } - }, - "bcryptjs": { - "version": "2.4.3", - "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", - "integrity": "sha1-mrVie5PmBiH/fNrF2pczAn3x0Ms=" - }, - "bignumber.js": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-4.0.4.tgz", - "integrity": "sha1-fED1q80tZiOre5loLufbgbEYiaQ=" - }, - "bl": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/bl/-/bl-1.2.1.tgz", - "integrity": "sha1-ysMo977kVzDUBLaSID/LWQ4XLV4=", - "requires": { - "readable-stream": "2.3.3" - } - }, - "bluebird": { - "version": "3.5.1", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz", - "integrity": "sha1-2VUfnemPH82h5oPRfukaBgLuLrk=" - }, - "body-parser": { - "version": "1.18.2", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.2.tgz", - "integrity": "sha1-h2eKGdhLR9hZuDGZvVm84iKxBFQ=", - "requires": { - "bytes": "3.0.0", - "content-type": "1.0.4", - "debug": "2.6.9", - "depd": "1.1.2", - "http-errors": "1.6.2", - "iconv-lite": "0.4.19", - "on-finished": "2.3.0", - "qs": "6.5.1", - "raw-body": "2.3.2", - "type-is": "1.6.15" - } - }, - "boom": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/boom/-/boom-4.3.1.tgz", - "integrity": "sha1-T4owBctKfjiJ90kDD9JbluAdLjE=", - "requires": { - "hoek": "4.2.0" - } - }, - "bops": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/bops/-/bops-1.0.0.tgz", - "integrity": "sha1-YxqJKPEXhBfrb3Bs9prNteWk6q0=", - "requires": { - "base64-js": "1.0.2", - "to-utf8": "0.0.1" - } - }, - "brace-expansion": { - "version": "1.1.8", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.8.tgz", - "integrity": "sha1-wHshHHyVLsH479Uad+8NHTmQopI=", - "requires": { - "balanced-match": "1.0.0", - "concat-map": "0.0.1" - } - }, - "btoa": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/btoa/-/btoa-1.1.2.tgz", - "integrity": "sha1-PkC4FmP4HS3WWWpMtxSo3BbPq+A=" - }, - "buildmail": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/buildmail/-/buildmail-4.0.1.tgz", - "integrity": "sha1-h393OLeHKYccmhBeO4N9K+EaenI=", - "requires": { - "addressparser": "1.0.1", - "libbase64": "0.1.0", - "libmime": "3.0.0", - "libqp": "1.1.0", - "nodemailer-fetch": "1.6.0", - "nodemailer-shared": "1.1.0", - "punycode": "1.4.1" - }, - "dependencies": { - "punycode": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", - "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=" - } - } - }, - "bytes": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", - "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=" - }, - "caller-path": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/caller-path/-/caller-path-0.1.0.tgz", - "integrity": "sha1-lAhe9jWB7NPaqSREqP6U6CV3dR8=", - "requires": { - "callsites": "0.2.0" - } - }, - "callsites": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-0.2.0.tgz", - "integrity": "sha1-r6uWJikQp/M8GaV3WCXGnzTjUMo=" - }, - "camelize": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/camelize/-/camelize-1.0.0.tgz", - "integrity": "sha1-FkpUg+Yw+kMh5a8HAg5TGDGyYJs=" - }, - "canonical-json": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/canonical-json/-/canonical-json-0.0.4.tgz", - "integrity": "sha1-ZXnAcsPbXEd+xB3JePvyuPQQdKM=" - }, - "caseless": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", - "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" - }, - "chalk": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.3.0.tgz", - "integrity": "sha1-tepI78nBeT3MybR2fJORTT8tUro=", - "requires": { - "ansi-styles": "3.2.0", - "escape-string-regexp": "1.0.5", - "supports-color": "4.5.0" - }, - "dependencies": { - "ansi-styles": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.0.tgz", - "integrity": "sha1-wVm41b4PnlpvNG2rlPFs4CIWG4g=", - "requires": { - "color-convert": "1.9.1" - } - }, - "supports-color": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-4.5.0.tgz", - "integrity": "sha1-vnoN5ITexcXN34s9WRJQRJEvY1s=", - "requires": { - "has-flag": "2.0.0" - } - } - } - }, - "chardet": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.4.2.tgz", - "integrity": "sha1-tUc7M9yXxCTl2Y3IfVXU2KKci/I=" - }, - "charenc": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz", - "integrity": "sha1-wKHS86cJLgN3S/qD8UwPxXkKhmc=" - }, - "circular-json": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/circular-json/-/circular-json-0.3.3.tgz", - "integrity": "sha1-gVyZ6oT2gJUp0vRXkb34JxE1LWY=" - }, - "cli-cursor": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", - "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", - "requires": { - "restore-cursor": "2.0.0" - } - }, - "cli-width": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.0.tgz", - "integrity": "sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk=" - }, - "cls-hooked": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/cls-hooked/-/cls-hooked-4.2.2.tgz", - "integrity": "sha1-rS6aQJJoDNr/6y01UdoOIl6uGQg=", - "requires": { - "async-hook-jl": "1.7.6", - "emitter-listener": "1.1.1", - "semver": "5.5.0" - } - }, - "co": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=" - }, - "coffee-script": { - "version": "1.12.7", - "resolved": "https://registry.npmjs.org/coffee-script/-/coffee-script-1.12.7.tgz", - "integrity": "sha1-wF2uDLeVkdBbMHCoQzqYyaiczFM=" - }, - "color-convert": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.1.tgz", - "integrity": "sha1-wSYRB66y8pTr/+ye2eytUppgl+0=", - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" - }, - "combined-stream": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.5.tgz", - "integrity": "sha1-k4NwpXtKUd6ix3wV1cX9+JUWQAk=", - "requires": { - "delayed-stream": "1.0.0" - } - }, - "commander": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/commander/-/commander-1.3.2.tgz", - "integrity": "sha1-io8w7GcKb91kr1LxkUuQfXnq1bU=", - "requires": { - "keypress": "0.1.0" - } - }, - "commondir": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/commondir/-/commondir-0.0.1.tgz", - "integrity": "sha1-ifAP3NUbUZxXhzP+xWPmptp/W+I=" - }, - "compressible": { - "version": "2.0.12", - "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.12.tgz", - "integrity": "sha1-xZpcmdt2dn6YdlAOJx72OzSTvWY=", - "requires": { - "mime-db": "1.30.0" - } - }, - "compression": { - "version": "1.7.1", - "resolved": "https://registry.npmjs.org/compression/-/compression-1.7.1.tgz", - "integrity": "sha1-7/JgPvwuIs+G810uuTWJ+YdTc9s=", - "requires": { - "accepts": "1.3.4", - "bytes": "3.0.0", - "compressible": "2.0.12", - "debug": "2.6.9", - "on-headers": "1.0.1", - "safe-buffer": "5.1.1", - "vary": "1.1.2" - } - }, - "concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" - }, - "concat-stream": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.0.tgz", - "integrity": "sha1-CqxmL9Ur54lk1VMvaUeE5wEQrPc=", - "requires": { - "inherits": "2.0.3", - "readable-stream": "2.3.3", - "typedarray": "0.0.6" - } - }, - "connect": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/connect/-/connect-3.4.1.tgz", - "integrity": "sha1-ohNh0/QJnvdhzabcSpc7seuwo00=", - "requires": { - "debug": "2.2.0", - "finalhandler": "0.4.1", - "parseurl": "1.3.2", - "utils-merge": "1.0.0" - }, - "dependencies": { - "debug": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", - "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", - "requires": { - "ms": "0.7.1" - } - }, - "ms": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", - "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=" - } - } - }, - "content-disposition": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz", - "integrity": "sha1-DPaLud318r55YcOoUXjLhdunjLQ=" - }, - "content-security-policy-builder": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/content-security-policy-builder/-/content-security-policy-builder-1.0.0.tgz", - "integrity": "sha1-Ef1AxcwpimxyWjX5rPcegqtdMkM=", - "requires": { - "dashify": "0.2.2" - } - }, - "content-type": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", - "integrity": "sha1-4TjMdeBAxyexlm/l5fjJruJW/js=" - }, - "cookie": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz", - "integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=" - }, - "cookie-signature": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", - "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" - }, - "core-js": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz", - "integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4=" - }, - "core-util-is": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" - }, - "cors": { - "version": "2.8.4", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.4.tgz", - "integrity": "sha1-K9OB8usgECAQXNUOpZ2mMJBpRoY=", - "requires": { - "object-assign": "4.1.1", - "vary": "1.1.2" - } - }, - "cross-fetch": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-0.0.8.tgz", - "integrity": "sha1-Ae2U3EB98sAPGAf95wCnz6SKIFw=", - "requires": { - "node-fetch": "1.7.3", - "whatwg-fetch": "2.0.3" - } - }, - "cross-spawn": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-5.1.0.tgz", - "integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=", - "requires": { - "lru-cache": "4.1.1", - "shebang-command": "1.2.0", - "which": "1.3.0" - } - }, - "crypt": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz", - "integrity": "sha1-iNf/fsDfuG9xPch7u0LQRNPmxBs=" - }, - "cryptiles": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/cryptiles/-/cryptiles-3.1.2.tgz", - "integrity": "sha1-qJ+7Ig9c4l7FboxKqKT9e1sNKf4=", - "requires": { - "boom": "5.2.0" - }, - "dependencies": { - "boom": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/boom/-/boom-5.2.0.tgz", - "integrity": "sha1-XdnabuOl8wIHdDYpDLcX0/SlTgI=", - "requires": { - "hoek": "4.2.0" - } - } - } - }, - "csextends": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/csextends/-/csextends-1.1.1.tgz", - "integrity": "sha1-zFPBNJ+vfwrmzfb2xKTZFW08TsE=", - "requires": { - "coffee-script": "1.12.7" - } - }, - "dashdash": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", - "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", - "requires": { - "assert-plus": "1.0.0" - } - }, - "dashify": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/dashify/-/dashify-0.2.2.tgz", - "integrity": "sha1-agdBWgHJH69KMuONnfunH2HLIP4=" - }, - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha1-XRKFFd8TT/Mn6QpMk/Tgd6U2NB8=", - "requires": { - "ms": "2.0.0" - } - }, - "deep-extend": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.4.2.tgz", - "integrity": "sha1-SLaZwn4zS/ifEIkr5DL25MfTSn8=" - }, - "deep-is": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", - "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=" - }, - "del": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/del/-/del-2.2.2.tgz", - "integrity": "sha1-wSyYHQZ4RshLyvhiz/kw2Qf/0ag=", - "requires": { - "globby": "5.0.0", - "is-path-cwd": "1.0.0", - "is-path-in-cwd": "1.0.0", - "object-assign": "4.1.1", - "pify": "2.3.0", - "pinkie-promise": "2.0.1", - "rimraf": "2.6.2" - } - }, - "delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" - }, - "depd": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", - "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" - }, - "destroy": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", - "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" - }, - "dns-prefetch-control": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/dns-prefetch-control/-/dns-prefetch-control-0.1.0.tgz", - "integrity": "sha1-YN20V3dOF48flBXwyrsOhbCzALI=" - }, - "doctrine": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", - "integrity": "sha1-XNAfwQFiG0LEzX9dGmYkNxbT850=", - "requires": { - "esutils": "2.0.2" - } - }, - "dom-serializer": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.0.tgz", - "integrity": "sha1-BzxpdUbOB4DOI75KKOKT5AvDDII=", - "requires": { - "domelementtype": "1.1.3", - "entities": "1.1.1" - }, - "dependencies": { - "domelementtype": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.1.3.tgz", - "integrity": "sha1-vSh3PiZCiBrsUVRJJCmcXNgiGFs=" - } - } - }, - "domelementtype": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.0.tgz", - "integrity": "sha1-sXrtguirWeUt2cGbF1bg/BhyBMI=" - }, - "domhandler": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.4.1.tgz", - "integrity": "sha1-iS5HAAqZvlW783dP/qBWHYh5wlk=", - "requires": { - "domelementtype": "1.3.0" - } - }, - "domutils": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.6.2.tgz", - "integrity": "sha1-GVjMC0yUJuntNn+xyOhUiRsPo/8=", - "requires": { - "dom-serializer": "0.1.0", - "domelementtype": "1.3.0" - } - }, - "dont-sniff-mimetype": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/dont-sniff-mimetype/-/dont-sniff-mimetype-1.0.0.tgz", - "integrity": "sha1-WTKJDcn04vGeXrAqIAJuXl78j1g=" - }, - "duplex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/duplex/-/duplex-1.0.0.tgz", - "integrity": "sha1-arxcFuwX5MV4V4cnEmcAWQ06Ldo=" - }, - "duplexer": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.0.4.tgz", - "integrity": "sha1-r8t/H4uNdPggcmFx1dZKyeSo/yA=" - }, - "eachr": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/eachr/-/eachr-2.0.4.tgz", - "integrity": "sha1-Rm98qhBwj2EFCeMsgHqv5X/BIr8=", - "requires": { - "typechecker": "2.1.0" - } - }, - "ecc-jsbn": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz", - "integrity": "sha1-D8c6ntXw1Tw4GTOYUj735UN3dQU=", - "optional": true, - "requires": { - "jsbn": "0.1.1" - } - }, - "editions": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/editions/-/editions-1.3.3.tgz", - "integrity": "sha1-CQcQG92iD6w8vjNMJ8vQaI3Jmls=" - }, - "ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" - }, - "ejs": { - "version": "2.5.7", - "resolved": "https://registry.npmjs.org/ejs/-/ejs-2.5.7.tgz", - "integrity": "sha1-zIcsFoiArjxxiXYv1f/ACJbJUYo=" - }, - "emitter-listener": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/emitter-listener/-/emitter-listener-1.1.1.tgz", - "integrity": "sha1-6Lu+gkS8jg0LTvcc0UKUx/JBx+w=", - "requires": { - "shimmer": "1.2.0" - } - }, - "encode-3986": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/encode-3986/-/encode-3986-1.0.0.tgz", - "integrity": "sha1-lA1RSY+HQa3hhLda0UObMXwMemA=" - }, - "encodeurl": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.1.tgz", - "integrity": "sha1-eePVhlU0aQn+bw9Fpd5oEDspTSA=" - }, - "encoding": { - "version": "0.1.12", - "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.12.tgz", - "integrity": "sha1-U4tm8+5izRq1HsMjgp0flIDHS+s=", - "requires": { - "iconv-lite": "0.4.19" - } - }, - "entities": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.1.tgz", - "integrity": "sha1-blwtClYhtdra7O+AuQ7ftc13cvA=" - }, - "escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" - }, - "eslint": { - "version": "4.15.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-4.15.0.tgz", - "integrity": "sha1-ias4wScT7sPROvrBTkqJ517wgUU=", - "requires": { - "ajv": "5.5.2", - "babel-code-frame": "6.26.0", - "chalk": "2.3.0", - "concat-stream": "1.6.0", - "cross-spawn": "5.1.0", - "debug": "3.1.0", - "doctrine": "2.1.0", - "eslint-scope": "3.7.1", - "eslint-visitor-keys": "1.0.0", - "espree": "3.5.2", - "esquery": "1.0.0", - "esutils": "2.0.2", - "file-entry-cache": "2.0.0", - "functional-red-black-tree": "1.0.1", - "glob": "7.1.2", - "globals": "11.1.0", - "ignore": "3.3.7", - "imurmurhash": "0.1.4", - "inquirer": "3.3.0", - "is-resolvable": "1.0.1", - "js-yaml": "3.10.0", - "json-stable-stringify-without-jsonify": "1.0.1", - "levn": "0.3.0", - "lodash": "4.17.4", - "minimatch": "3.0.4", - "mkdirp": "0.5.1", - "natural-compare": "1.4.0", - "optionator": "0.8.2", - "path-is-inside": "1.0.2", - "pluralize": "7.0.0", - "progress": "2.0.0", - "require-uncached": "1.0.3", - "semver": "5.5.0", - "strip-ansi": "4.0.0", - "strip-json-comments": "2.0.1", - "table": "4.0.2", - "text-table": "0.2.0" - }, - "dependencies": { - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha1-W7WgZyYotkFJVmuhaBnmFRjGcmE=", - "requires": { - "ms": "2.0.0" - } - }, - "glob": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", - "integrity": "sha1-wZyd+aAocC1nhhI4SmVSQExjbRU=", - "requires": { - "fs.realpath": "1.0.0", - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.4", - "once": "1.4.0", - "path-is-absolute": "1.0.1" - } - } - } - }, - "eslint-config-loopback": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/eslint-config-loopback/-/eslint-config-loopback-8.0.0.tgz", - "integrity": "sha1-8UK8pHEimUoahfGcwhY1EWFrQVI=" - }, - "eslint-scope": { - "version": "3.7.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-3.7.1.tgz", - "integrity": "sha1-PWPD7f2gLgbgGkUq2IyqzHzctug=", - "requires": { - "esrecurse": "4.2.0", - "estraverse": "4.2.0" - } - }, - "eslint-visitor-keys": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", - "integrity": "sha1-PzGA+y4pEBdxastMnW1bXDSmqB0=" - }, - "espree": { - "version": "3.5.2", - "resolved": "https://registry.npmjs.org/espree/-/espree-3.5.2.tgz", - "integrity": "sha1-dWrai5eenc/NswqtjRqTBKkF4co=", - "requires": { - "acorn": "5.3.0", - "acorn-jsx": "3.0.1" - } - }, - "esprima": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.0.tgz", - "integrity": "sha1-RJnt3NERDgshi6zy+n9/WfVcqAQ=" - }, - "esquery": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.0.0.tgz", - "integrity": "sha1-z7qLV9f7qT8XKYqKAGoEzaE9gPo=", - "requires": { - "estraverse": "4.2.0" - } - }, - "esrecurse": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.0.tgz", - "integrity": "sha1-+pVo2Y04I/mkHZHpAtyrnqblsWM=", - "requires": { - "estraverse": "4.2.0", - "object-assign": "4.1.1" - } - }, - "estraverse": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", - "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=" - }, - "esutils": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", - "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=" - }, - "etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=" - }, - "eventemitter2": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-2.2.2.tgz", - "integrity": "sha1-QH6nHCAgzVdTggOrfnpr3Pt2ktU=" - }, - "execa": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-0.7.0.tgz", - "integrity": "sha1-lEvs00zEHuMqY6n68nrVpl/Fl3c=", - "requires": { - "cross-spawn": "5.1.0", - "get-stream": "3.0.0", - "is-stream": "1.1.0", - "npm-run-path": "2.0.2", - "p-finally": "1.0.0", - "signal-exit": "3.0.2", - "strip-eof": "1.0.0" - } - }, - "express": { - "version": "4.16.2", - "resolved": "https://registry.npmjs.org/express/-/express-4.16.2.tgz", - "integrity": "sha1-41xt/i1kt9ygpc1PIXgb4ymeB2w=", - "requires": { - "accepts": "1.3.4", - "array-flatten": "1.1.1", - "body-parser": "1.18.2", - "content-disposition": "0.5.2", - "content-type": "1.0.4", - "cookie": "0.3.1", - "cookie-signature": "1.0.6", - "debug": "2.6.9", - "depd": "1.1.2", - "encodeurl": "1.0.1", - "escape-html": "1.0.3", - "etag": "1.8.1", - "finalhandler": "1.1.0", - "fresh": "0.5.2", - "merge-descriptors": "1.0.1", - "methods": "1.1.2", - "on-finished": "2.3.0", - "parseurl": "1.3.2", - "path-to-regexp": "0.1.7", - "proxy-addr": "2.0.2", - "qs": "6.5.1", - "range-parser": "1.2.0", - "safe-buffer": "5.1.1", - "send": "0.16.1", - "serve-static": "1.13.1", - "setprototypeof": "1.1.0", - "statuses": "1.3.1", - "type-is": "1.6.15", - "utils-merge": "1.0.1", - "vary": "1.1.2" - }, - "dependencies": { - "finalhandler": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.0.tgz", - "integrity": "sha1-zgtoVbRYU+eRsvzGgARtiCU91/U=", - "requires": { - "debug": "2.6.9", - "encodeurl": "1.0.1", - "escape-html": "1.0.3", - "on-finished": "2.3.0", - "parseurl": "1.3.2", - "statuses": "1.3.1", - "unpipe": "1.0.0" - } - }, - "setprototypeof": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", - "integrity": "sha1-0L2FU2iHtv58DYGMuWLZ2RxU5lY=" - }, - "statuses": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.3.1.tgz", - "integrity": "sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4=" - }, - "utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=" - } - } - }, - "extend": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz", - "integrity": "sha1-p1Xqe8Gt/MWjHOfnYtuq3F5jZEQ=" - }, - "extendr": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/extendr/-/extendr-2.1.0.tgz", - "integrity": "sha1-MBqgu+pWX00tyPVw8qImEahSe1Y=", - "requires": { - "typechecker": "2.0.8" - }, - "dependencies": { - "typechecker": { - "version": "2.0.8", - "resolved": "https://registry.npmjs.org/typechecker/-/typechecker-2.0.8.tgz", - "integrity": "sha1-6D2oS7ZMWEzLNFg4V2xAsDN9uC4=" - } - } - }, - "external-editor": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-2.1.0.tgz", - "integrity": "sha1-PQJqIbf5W1cmOH1CAKwWDTcsO0g=", - "requires": { - "chardet": "0.4.2", - "iconv-lite": "0.4.19", - "tmp": "0.0.33" - } - }, - "extract-opts": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/extract-opts/-/extract-opts-2.2.0.tgz", - "integrity": "sha1-H6KOunNSxttID4hc63GkaBC+bX0=", - "requires": { - "typechecker": "2.0.8" - }, - "dependencies": { - "typechecker": { - "version": "2.0.8", - "resolved": "https://registry.npmjs.org/typechecker/-/typechecker-2.0.8.tgz", - "integrity": "sha1-6D2oS7ZMWEzLNFg4V2xAsDN9uC4=" - } - } - }, - "extsprintf": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", - "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=" - }, - "eyes": { - "version": "0.1.8", - "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", - "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=" - }, - "fast-deep-equal": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.0.0.tgz", - "integrity": "sha1-liVqO8l1WV6zbYLpkp0GDYk0Of8=" - }, - "fast-json-patch": { - "version": "1.1.8", - "resolved": "https://registry.npmjs.org/fast-json-patch/-/fast-json-patch-1.1.8.tgz", - "integrity": "sha1-jbWMnRLD/5wjRW7oEswp+scit3I=" - }, - "fast-json-stable-stringify": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", - "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=" - }, - "fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=" - }, - "figures": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", - "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", - "requires": { - "escape-string-regexp": "1.0.5" - } - }, - "file-entry-cache": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-2.0.0.tgz", - "integrity": "sha1-w5KZDD5oR4PYOLjISkXYoEhFg2E=", - "requires": { - "flat-cache": "1.3.0", - "object-assign": "4.1.1" - } - }, - "finalhandler": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-0.4.1.tgz", - "integrity": "sha1-haF8bFmpRxfSYtYSMNSw6+PUoU0=", - "requires": { - "debug": "2.2.0", - "escape-html": "1.0.3", - "on-finished": "2.3.0", - "unpipe": "1.0.0" - }, - "dependencies": { - "debug": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", - "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", - "requires": { - "ms": "0.7.1" - } - }, - "ms": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", - "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=" - } - } - }, - "flat-cache": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-1.3.0.tgz", - "integrity": "sha1-0wMLMrOBVPTjt+nHCfSQ9++XxIE=", - "requires": { - "circular-json": "0.3.3", - "del": "2.2.2", - "graceful-fs": "4.1.11", - "write": "0.2.1" - } - }, - "forever-agent": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", - "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=" - }, - "form-data": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-1.0.1.tgz", - "integrity": "sha1-rjFduaSQf6BlUCMEpm13M0de43w=", - "requires": { - "async": "2.6.0", - "combined-stream": "1.0.5", - "mime-types": "2.1.17" - }, - "dependencies": { - "async": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/async/-/async-2.6.0.tgz", - "integrity": "sha1-YaKau2/MAm/qd+VtHG7FOnlZUfQ=", - "requires": { - "lodash": "4.17.4" - } - } - } - }, - "forwarded": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", - "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=" - }, - "frameguard": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/frameguard/-/frameguard-1.1.0.tgz", - "integrity": "sha1-5d5ePssX/4S2lzALDg10in0JBHs=", - "requires": { - "lodash.isstring": "4.0.1" - } - }, - "fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=" - }, - "fs-extra": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz", - "integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==", - "requires": { - "graceful-fs": "4.1.11", - "jsonfile": "4.0.0", - "universalify": "0.1.1" - } - }, - "fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" - }, - "functional-red-black-tree": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", - "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=" - }, - "g11n-pipeline": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/g11n-pipeline/-/g11n-pipeline-2.0.5.tgz", - "integrity": "sha1-SyFGf187Np0m3y8B2S8hU+AzQSU=", - "requires": { - "swagger-client": "3.4.5" - } - }, - "get-stream": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-3.0.0.tgz", - "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=" - }, - "getpass": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", - "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", - "requires": { - "assert-plus": "1.0.0" - } - }, - "glob": { - "version": "6.0.4", - "resolved": "https://registry.npmjs.org/glob/-/glob-6.0.4.tgz", - "integrity": "sha1-DwiGD2oVUSey+t1PnOJLGqtuTSI=", - "requires": { - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.4", - "once": "1.4.0", - "path-is-absolute": "1.0.1" - } - }, - "globals": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.1.0.tgz", - "integrity": "sha1-YyZERX9fDjrnEYBxg3AOvy5GM+Q=" - }, - "globby": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-5.0.0.tgz", - "integrity": "sha1-69hGZ8oNuzMLmbz8aOrCvFQ3Dg0=", - "requires": { - "array-union": "1.0.2", - "arrify": "1.0.1", - "glob": "7.1.2", - "object-assign": "4.1.1", - "pify": "2.3.0", - "pinkie-promise": "2.0.1" - }, - "dependencies": { - "glob": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", - "integrity": "sha1-wZyd+aAocC1nhhI4SmVSQExjbRU=", - "requires": { - "fs.realpath": "1.0.0", - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.4", - "once": "1.4.0", - "path-is-absolute": "1.0.1" - } - } - } - }, - "graceful-fs": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz", - "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=" - }, - "har-schema": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", - "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=" - }, - "har-validator": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.0.3.tgz", - "integrity": "sha1-ukAsJmGU8VlW7xXg/PJCmT9qff0=", - "requires": { - "ajv": "5.5.2", - "har-schema": "2.0.0" - } - }, - "has-ansi": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "requires": { - "ansi-regex": "2.1.1" - } - }, - "has-flag": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz", - "integrity": "sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=" - }, - "hawk": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/hawk/-/hawk-6.0.2.tgz", - "integrity": "sha1-r02RTrBl+bXOTZ0RwcshJu7MMDg=", - "requires": { - "boom": "4.3.1", - "cryptiles": "3.1.2", - "hoek": "4.2.0", - "sntp": "2.1.0" - } - }, - "helmet": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/helmet/-/helmet-1.3.0.tgz", - "integrity": "sha1-4bWcVIT3rAgaSMx2NBObTsOM+LU=", - "requires": { - "connect": "3.4.1", - "dns-prefetch-control": "0.1.0", - "dont-sniff-mimetype": "1.0.0", - "frameguard": "1.1.0", - "helmet-csp": "1.1.0", - "hide-powered-by": "1.0.0", - "hpkp": "1.1.0", - "hsts": "1.0.0", - "ienoopen": "1.0.0", - "nocache": "1.0.0", - "x-xss-protection": "1.0.0" - } - }, - "helmet-csp": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/helmet-csp/-/helmet-csp-1.1.0.tgz", - "integrity": "sha1-VYsjAD/nhv9JjZWelu8qkeyzXII=", - "requires": { - "camelize": "1.0.0", - "content-security-policy-builder": "1.0.0", - "lodash.assign": "4.0.4", - "lodash.isfunction": "3.0.8", - "lodash.reduce": "4.2.0", - "lodash.some": "4.2.0", - "platform": "1.3.1" - } - }, - "hide-powered-by": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/hide-powered-by/-/hide-powered-by-1.0.0.tgz", - "integrity": "sha1-SoWtZYgfYoV/xwr3F0oRhNzM4ys=" - }, - "hoek": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/hoek/-/hoek-4.2.0.tgz", - "integrity": "sha1-ctnQdU9/4lyi0BrY+PmpRJqJUm0=" - }, - "hpkp": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/hpkp/-/hpkp-1.1.0.tgz", - "integrity": "sha1-d73/HzMYR/ufQIOdAKRQMrrtTfQ=" - }, - "hsts": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/hsts/-/hsts-1.0.0.tgz", - "integrity": "sha1-mOEDnverpVQFe2sOMlhMCxFDpBQ=", - "requires": { - "core-util-is": "1.0.2" - } - }, - "htmlparser2": { - "version": "3.9.2", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.9.2.tgz", - "integrity": "sha1-G9+HrMoPP55T+k/M6w9LTLsAszg=", - "requires": { - "domelementtype": "1.3.0", - "domhandler": "2.4.1", - "domutils": "1.6.2", - "entities": "1.1.1", - "inherits": "2.0.3", - "readable-stream": "2.3.3" - } - }, - "http-errors": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.2.tgz", - "integrity": "sha1-CgAsyFcHGSp+eUbO7cERVfYOxzY=", - "requires": { - "depd": "1.1.1", - "inherits": "2.0.3", - "setprototypeof": "1.0.3", - "statuses": "1.4.0" - }, - "dependencies": { - "depd": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.1.tgz", - "integrity": "sha1-V4O04cRZ8G+lyif5kfPQbnoxA1k=" - } - } - }, - "http-signature": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", - "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", - "requires": { - "assert-plus": "1.0.0", - "jsprim": "1.4.1", - "sshpk": "1.13.1" - } - }, - "http-status": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/http-status/-/http-status-1.0.1.tgz", - "integrity": "sha1-3EMAGov8UKyH1IWokvdXiWS8lKI=" - }, - "httpntlm": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/httpntlm/-/httpntlm-1.6.1.tgz", - "integrity": "sha1-rQFScUOi6Hc8+uapb1hla7UqNLI=", - "requires": { - "httpreq": "0.4.24", - "underscore": "1.7.0" - } - }, - "httpreq": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/httpreq/-/httpreq-0.4.24.tgz", - "integrity": "sha1-QzX/2CzZaWaKOUZckprGHWOTYn8=" - }, - "i18n": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/i18n/-/i18n-0.8.3.tgz", - "integrity": "sha1-LYzxwkciYCwgQdAbpq5eqlE4jw4=", - "requires": { - "debug": "2.6.9", - "make-plural": "3.0.6", - "math-interval-parser": "1.1.0", - "messageformat": "0.3.1", - "mustache": "2.3.0", - "sprintf-js": "1.1.1" - } - }, - "iconv-lite": { - "version": "0.4.19", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.19.tgz", - "integrity": "sha1-90aPYBNfXl2tM5nAqBvpoWA6CCs=" - }, - "ienoopen": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/ienoopen/-/ienoopen-1.0.0.tgz", - "integrity": "sha1-NGpCj0dKrI9QzzeE6i0PFvYr2ms=" - }, - "ignore": { - "version": "3.3.7", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.7.tgz", - "integrity": "sha1-YSKJv7PCIOGGpYEYYY1b6MG6sCE=" - }, - "ignorefs": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/ignorefs/-/ignorefs-1.2.0.tgz", - "integrity": "sha1-2ln7hYl25KXkNwLM0fKC/byeV1Y=", - "requires": { - "editions": "1.3.3", - "ignorepatterns": "1.1.0" - } - }, - "ignorepatterns": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/ignorepatterns/-/ignorepatterns-1.1.0.tgz", - "integrity": "sha1-rI9DbyI5td+2bV8NOpBKh6xnzF4=" - }, - "imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=" - }, - "inflection": { - "version": "1.12.0", - "resolved": "https://registry.npmjs.org/inflection/-/inflection-1.12.0.tgz", - "integrity": "sha1-ogCTVlbW9fa8TcdQLhrstwMihBY=" - }, - "inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "requires": { - "once": "1.4.0", - "wrappy": "1.0.2" - } - }, - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" - }, - "inquirer": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-3.3.0.tgz", - "integrity": "sha1-ndLyrXZdyrH/BEO0kUQqILoifck=", - "requires": { - "ansi-escapes": "3.0.0", - "chalk": "2.3.0", - "cli-cursor": "2.1.0", - "cli-width": "2.2.0", - "external-editor": "2.1.0", - "figures": "2.0.0", - "lodash": "4.17.4", - "mute-stream": "0.0.7", - "run-async": "2.3.0", - "rx-lite": "4.0.8", - "rx-lite-aggregates": "4.0.8", - "string-width": "2.1.1", - "strip-ansi": "4.0.0", - "through": "2.3.8" - } - }, - "invert-kv": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz", - "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=" - }, - "ip": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/ip/-/ip-1.1.5.tgz", - "integrity": "sha1-vd7XARQpCCjAoDnnLvJfWq7ENUo=" - }, - "ipaddr.js": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.5.2.tgz", - "integrity": "sha1-1LUFvemUaYfM8PxY2QEP+WB+P6A=" - }, - "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha1-76ouqdqg16suoTqXsritUf776L4=" - }, - "is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=" - }, - "is-path-cwd": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-1.0.0.tgz", - "integrity": "sha1-0iXsIxMuie3Tj9p2dHLmLmXxEG0=" - }, - "is-path-in-cwd": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-path-in-cwd/-/is-path-in-cwd-1.0.0.tgz", - "integrity": "sha1-ZHdYK4IU1gI0YJRWcAO+ip6sBNw=", - "requires": { - "is-path-inside": "1.0.1" - } - }, - "is-path-inside": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-1.0.1.tgz", - "integrity": "sha1-jvW33lBDej/cprToZe96pVy0gDY=", - "requires": { - "path-is-inside": "1.0.2" - } - }, - "is-promise": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", - "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=" - }, - "is-resolvable": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-resolvable/-/is-resolvable-1.0.1.tgz", - "integrity": "sha1-rMoc022+RLl0uSQyFVWnC6A7HPQ=" - }, - "is-stream": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", - "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=" - }, - "is-typedarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", - "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" - }, - "isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" - }, - "isemail": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/isemail/-/isemail-2.2.1.tgz", - "integrity": "sha1-A1PT2aYpUQgMJiwqoKQrjqjp4qY=" - }, - "isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" - }, - "isomorphic-form-data": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isomorphic-form-data/-/isomorphic-form-data-0.0.1.tgz", - "integrity": "sha1-Am9ifgMrDNhBPsyHVZKLlKRosGI=", - "requires": { - "form-data": "1.0.1" - } - }, - "isstream": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", - "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" - }, - "jayson": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/jayson/-/jayson-1.2.2.tgz", - "integrity": "sha1-0oxgLsuJIsKp+zwWEfeftYTxk+w=", - "requires": { - "JSONStream": "1.0.3", - "commander": "1.3.2", - "eyes": "0.1.8", - "lodash": "3.6.0" - }, - "dependencies": { - "lodash": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.6.0.tgz", - "integrity": "sha1-Umao9J3Zib5Pn2gbbyoMVShdDZo=" - } - } - }, - "js-tokens": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", - "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=" - }, - "js-yaml": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.10.0.tgz", - "integrity": "sha1-LnhEFka9RoLpY/IrbpKCPDCcYtw=", - "requires": { - "argparse": "1.0.9", - "esprima": "4.0.0" - } - }, - "js2xmlparser": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-1.0.0.tgz", - "integrity": "sha1-WhcPLo1kds5FQF4EgjJCUTeC/jA=" - }, - "jsbn": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", - "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", - "optional": true - }, - "json-buffer": { - "version": "2.0.11", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-2.0.11.tgz", - "integrity": "sha1-PkQf2jCYvo0eMXGtWRvGKjPi1V8=" - }, - "json-schema": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", - "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=" - }, - "json-schema-traverse": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz", - "integrity": "sha1-NJptRMU6Ud6JtAgFxdXlm0F9M0A=" - }, - "json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=" - }, - "json-stringify-safe": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", - "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" - }, - "jsonfile": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", - "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", - "requires": { - "graceful-fs": "4.1.11" - } - }, - "jsonparse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.0.0.tgz", - "integrity": "sha1-JiL05mwI4arH7b63YFPJt+EhH3Y=" - }, - "jsprim": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", - "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", - "requires": { - "assert-plus": "1.0.0", - "extsprintf": "1.3.0", - "json-schema": "0.2.3", - "verror": "1.10.0" - } - }, - "keypress": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/keypress/-/keypress-0.1.0.tgz", - "integrity": "sha1-SjGI1CkbZrT2XtuZ+AaqmuKTWSo=" - }, - "lcid": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz", - "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", - "requires": { - "invert-kv": "1.0.0" - } - }, - "levn": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", - "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", - "requires": { - "prelude-ls": "1.1.2", - "type-check": "0.3.2" - } - }, - "libbase64": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/libbase64/-/libbase64-0.1.0.tgz", - "integrity": "sha1-YjUag5VjrF/1vSbxL2Dpgwu3UeY=" - }, - "libmime": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/libmime/-/libmime-3.0.0.tgz", - "integrity": "sha1-UaGp50SOy9Ms2lRCFnW7IbwJPaY=", - "requires": { - "iconv-lite": "0.4.15", - "libbase64": "0.1.0", - "libqp": "1.1.0" - }, - "dependencies": { - "iconv-lite": { - "version": "0.4.15", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.15.tgz", - "integrity": "sha1-/iZaIYrGpXz+hUkn6dBMGYJe3es=" - } - } - }, - "libqp": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/libqp/-/libqp-1.1.0.tgz", - "integrity": "sha1-9ebgatdLeU+1tbZpiL9yjvHe2+g=" - }, - "lodash": { - "version": "4.17.4", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.4.tgz", - "integrity": "sha1-eCA6TRwyiuHYbcpkYONptX9AVa4=" - }, - "lodash._baseeach": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/lodash._baseeach/-/lodash._baseeach-4.1.3.tgz", - "integrity": "sha1-ykmE7chJwjeyg/vi6nz3bTf8nWc=" - }, - "lodash._baseiteratee": { - "version": "4.7.0", - "resolved": "https://registry.npmjs.org/lodash._baseiteratee/-/lodash._baseiteratee-4.7.0.tgz", - "integrity": "sha1-NKm1VDVycnw9sueO2uPA6eZr0QI=", - "requires": { - "lodash._stringtopath": "4.8.0" - } - }, - "lodash._basereduce": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/lodash._basereduce/-/lodash._basereduce-3.0.2.tgz", - "integrity": "sha1-E/uY+94WIIOgyWfwYFwyrPuycLI=" - }, - "lodash._basetostring": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/lodash._basetostring/-/lodash._basetostring-4.12.0.tgz", - "integrity": "sha1-kyfJ3FFYhmt/pLnUL0Y45XZt2d8=" - }, - "lodash._stringtopath": { - "version": "4.8.0", - "resolved": "https://registry.npmjs.org/lodash._stringtopath/-/lodash._stringtopath-4.8.0.tgz", - "integrity": "sha1-lBvPDmQmbl/B1m/tCmlZVExXaCQ=", - "requires": { - "lodash._basetostring": "4.12.0" - } - }, - "lodash.assign": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/lodash.assign/-/lodash.assign-4.0.4.tgz", - "integrity": "sha1-nTSqLHdj5vfdfCWAjUGBPz2gkxM=", - "requires": { - "lodash.keys": "4.2.0", - "lodash.rest": "4.0.5" - } - }, - "lodash.isfunction": { - "version": "3.0.8", - "resolved": "https://registry.npmjs.org/lodash.isfunction/-/lodash.isfunction-3.0.8.tgz", - "integrity": "sha1-TbcJ/IG8So/XEnpFilNGxc3OLGs=" - }, - "lodash.isstring": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", - "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" - }, - "lodash.keys": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/lodash.keys/-/lodash.keys-4.2.0.tgz", - "integrity": "sha1-oIYCrBLk+4P5H8H7ejYKTZujUgU=" - }, - "lodash.reduce": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/lodash.reduce/-/lodash.reduce-4.2.0.tgz", - "integrity": "sha1-/1CAW9hBBCKRBsks8FBBfVxz0CU=", - "requires": { - "lodash._baseeach": "4.1.3", - "lodash._baseiteratee": "4.7.0", - "lodash._basereduce": "3.0.2" - } - }, - "lodash.rest": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/lodash.rest/-/lodash.rest-4.0.5.tgz", - "integrity": "sha1-lU73UEkmIDjJbR/Jiyj9r58Hcqo=" - }, - "lodash.some": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/lodash.some/-/lodash.some-4.2.0.tgz", - "integrity": "sha1-y0TDsNN11WAx2heim2HohrHhyfk=", - "requires": { - "lodash._baseeach": "4.1.3", - "lodash._baseiteratee": "4.7.0" - } - }, - "loopback": { - "version": "3.17.1", - "resolved": "https://registry.npmjs.org/loopback/-/loopback-3.17.1.tgz", - "integrity": "sha1-PPc49G2v/GuIRhdjIKTf2tfz/9M=", - "requires": { - "async": "2.6.0", - "bcryptjs": "2.4.3", - "bluebird": "3.5.1", - "body-parser": "1.18.2", - "canonical-json": "0.0.4", - "debug": "2.6.9", - "depd": "1.1.2", - "ejs": "2.5.7", - "express": "4.16.2", - "inflection": "1.12.0", - "isemail": "2.2.1", - "loopback-connector-remote": "3.3.1", - "loopback-datasource-juggler": "3.14.0", - "loopback-phase": "3.1.0", - "nodemailer": "2.7.2", - "nodemailer-stub-transport": "1.1.0", - "serve-favicon": "2.4.5", - "stable": "0.1.6", - "strong-globalize": "3.1.0", - "strong-remoting": "3.8.0", - "uid2": "0.0.3", - "underscore.string": "3.3.4" - }, - "dependencies": { - "async": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/async/-/async-2.6.0.tgz", - "integrity": "sha1-YaKau2/MAm/qd+VtHG7FOnlZUfQ=", - "requires": { - "lodash": "4.17.4" - } - } - } - }, - "loopback-boot": { - "version": "2.27.0", - "resolved": "https://registry.npmjs.org/loopback-boot/-/loopback-boot-2.27.0.tgz", - "integrity": "sha1-Fo67YEIArrUG5gAe2jxpsAeEjSg=", - "requires": { - "async": "0.9.2", - "commondir": "0.0.1", - "debug": "2.6.9", - "lodash": "3.10.1", - "semver": "4.3.6", - "strong-globalize": "2.10.0", - "toposort": "0.2.12" - }, - "dependencies": { - "async": { - "version": "0.9.2", - "resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz", - "integrity": "sha1-rqdNXmHB+JlhO/ZL2mbUx48v0X0=" - }, - "lodash": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.10.1.tgz", - "integrity": "sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y=" - }, - "semver": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/semver/-/semver-4.3.6.tgz", - "integrity": "sha1-MAvG4OhjdPe6YQaLWx7NV/xlMto=" - }, - "strong-globalize": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/strong-globalize/-/strong-globalize-2.10.0.tgz", - "integrity": "sha1-bw5cd2x0n+++c5VLIZwf2WyK4xc=", - "requires": { - "async": "1.5.2", - "debug": "3.1.0", - "esprima": "4.0.0", - "estraverse": "4.2.0", - "g11n-pipeline": "2.0.5", - "htmlparser2": "3.9.2", - "lodash": "4.17.4", - "md5": "2.2.1", - "mkdirp": "0.5.1", - "mktmpdir": "0.1.1", - "optional": "0.1.4", - "os-locale": "2.1.0", - "posix-getopt": "1.2.0", - "word-count": "0.2.2", - "xtend": "4.0.1", - "yamljs": "0.3.0" - }, - "dependencies": { - "async": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha1-W7WgZyYotkFJVmuhaBnmFRjGcmE=", - "requires": { - "ms": "2.0.0" - } - }, - "lodash": { - "version": "4.17.4", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.4.tgz", - "integrity": "sha1-eCA6TRwyiuHYbcpkYONptX9AVa4=" - } - } - } - } - }, - "loopback-component-explorer": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/loopback-component-explorer/-/loopback-component-explorer-4.3.0.tgz", - "integrity": "sha1-FHHgslTC9IXUNbR0ZvK/bXQ4ujI=", - "requires": { - "cors": "2.8.4", - "debug": "2.6.9", - "depd": "1.1.2", - "lodash": "3.10.1", - "loopback-swagger": "3.0.2", - "strong-globalize": "2.10.0", - "swagger-ui": "2.2.10" - }, - "dependencies": { - "lodash": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.10.1.tgz", - "integrity": "sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y=" - }, - "strong-globalize": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/strong-globalize/-/strong-globalize-2.10.0.tgz", - "integrity": "sha1-bw5cd2x0n+++c5VLIZwf2WyK4xc=", - "requires": { - "async": "1.5.2", - "debug": "3.1.0", - "esprima": "4.0.0", - "estraverse": "4.2.0", - "g11n-pipeline": "2.0.5", - "htmlparser2": "3.9.2", - "lodash": "4.17.4", - "md5": "2.2.1", - "mkdirp": "0.5.1", - "mktmpdir": "0.1.1", - "optional": "0.1.4", - "os-locale": "2.1.0", - "posix-getopt": "1.2.0", - "word-count": "0.2.2", - "xtend": "4.0.1", - "yamljs": "0.3.0" - }, - "dependencies": { - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha1-W7WgZyYotkFJVmuhaBnmFRjGcmE=", - "requires": { - "ms": "2.0.0" - } - }, - "lodash": { - "version": "4.17.4", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.4.tgz", - "integrity": "sha1-eCA6TRwyiuHYbcpkYONptX9AVa4=" - } - } - } - } - }, - "loopback-connector": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/loopback-connector/-/loopback-connector-4.4.0.tgz", - "integrity": "sha1-FRNlMolredjcKAvifWV/rQAMEgk=", - "requires": { - "async": "2.6.0", - "bluebird": "3.5.1", - "debug": "3.1.0", - "msgpack5": "3.6.0", - "strong-globalize": "3.1.0", - "uuid": "3.2.1" - }, - "dependencies": { - "async": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/async/-/async-2.6.0.tgz", - "integrity": "sha1-YaKau2/MAm/qd+VtHG7FOnlZUfQ=", - "requires": { - "lodash": "4.17.4" - } - }, - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha1-W7WgZyYotkFJVmuhaBnmFRjGcmE=", - "requires": { - "ms": "2.0.0" - } - } - } - }, - "loopback-connector-mysql": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/loopback-connector-mysql/-/loopback-connector-mysql-3.0.0.tgz", - "integrity": "sha1-8G25YPq0zzHVmZN2k0wQD5FfIRQ=", - "requires": { - "async": "0.9.2", - "debug": "2.6.9", - "loopback-connector": "2.7.1", - "mysql": "2.15.0", - "strong-globalize": "2.10.0" - }, - "dependencies": { - "async": { - "version": "0.9.2", - "resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz", - "integrity": "sha1-rqdNXmHB+JlhO/ZL2mbUx48v0X0=" - }, - "loopback-connector": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/loopback-connector/-/loopback-connector-2.7.1.tgz", - "integrity": "sha1-YK/CROMZGZdjkamXg4aFeB+ijlI=", - "requires": { - "async": "1.5.2", - "bluebird": "3.5.1", - "debug": "2.6.9", - "msgpack5": "3.6.0", - "strong-globalize": "2.10.0" - }, - "dependencies": { - "async": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - } - } - }, - "strong-globalize": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/strong-globalize/-/strong-globalize-2.10.0.tgz", - "integrity": "sha1-bw5cd2x0n+++c5VLIZwf2WyK4xc=", - "requires": { - "async": "1.5.2", - "debug": "3.1.0", - "esprima": "4.0.0", - "estraverse": "4.2.0", - "g11n-pipeline": "2.0.5", - "htmlparser2": "3.9.2", - "lodash": "4.17.4", - "md5": "2.2.1", - "mkdirp": "0.5.1", - "mktmpdir": "0.1.1", - "optional": "0.1.4", - "os-locale": "2.1.0", - "posix-getopt": "1.2.0", - "word-count": "0.2.2", - "xtend": "4.0.1", - "yamljs": "0.3.0" - }, - "dependencies": { - "async": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", - "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" - }, - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha1-W7WgZyYotkFJVmuhaBnmFRjGcmE=", - "requires": { - "ms": "2.0.0" - } - } - } - } - } - }, - "loopback-connector-remote": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/loopback-connector-remote/-/loopback-connector-remote-3.3.1.tgz", - "integrity": "sha1-dPqnwgXATdiJeWpkdzkpDLsi+w0=", - "requires": { - "eslint": "4.15.0", - "eslint-config-loopback": "8.0.0", - "loopback-datasource-juggler": "3.14.0", - "strong-remoting": "3.8.0" - } - }, - "loopback-context": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/loopback-context/-/loopback-context-3.3.0.tgz", - "integrity": "sha1-tIQoZ7laLD3qSbCVRFORWSpy4Lw=", - "requires": { - "cls-hooked": "4.2.2" - } - }, - "loopback-datasource-juggler": { - "version": "3.14.0", - "resolved": "https://registry.npmjs.org/loopback-datasource-juggler/-/loopback-datasource-juggler-3.14.0.tgz", - "integrity": "sha1-lrcxZQwejoxOcSk0B3rieHnRZEg=", - "requires": { - "async": "2.1.5", - "bluebird": "3.5.1", - "debug": "3.1.0", - "depd": "1.1.2", - "inflection": "1.12.0", - "lodash": "4.17.4", - "loopback-connector": "4.4.0", - "minimatch": "3.0.4", - "qs": "6.5.1", - "shortid": "2.2.8", - "strong-globalize": "3.1.0", - "traverse": "0.6.6", - "uuid": "3.2.1" - }, - "dependencies": { - "async": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/async/-/async-2.1.5.tgz", - "integrity": "sha1-5YfGhYCZSsZ/xW/4bTrFa9voELw=", - "requires": { - "lodash": "4.17.4" - } - }, - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha1-W7WgZyYotkFJVmuhaBnmFRjGcmE=", - "requires": { - "ms": "2.0.0" - } - } - } - }, - "loopback-datatype-geopoint": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/loopback-datatype-geopoint/-/loopback-datatype-geopoint-1.0.0.tgz", - "integrity": "sha1-/apcerjXMKmrflRVS+Fl8xzfYQA=" - }, - "loopback-phase": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/loopback-phase/-/loopback-phase-3.1.0.tgz", - "integrity": "sha1-ka3I6YR8+1IaPSn5a+NfZ4YMrkI=", - "requires": { - "async": "0.9.2", - "debug": "2.6.9", - "strong-globalize": "3.1.0" - }, - "dependencies": { - "async": { - "version": "0.9.2", - "resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz", - "integrity": "sha1-rqdNXmHB+JlhO/ZL2mbUx48v0X0=" - } - } - }, - "loopback-swagger": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/loopback-swagger/-/loopback-swagger-3.0.2.tgz", - "integrity": "sha1-4VBizGzTo/n+/XN6qD14QX1kgbs=", - "requires": { - "async": "1.5.2", - "debug": "2.6.9", - "ejs": "2.5.7", - "lodash": "3.10.1", - "strong-globalize": "2.10.0", - "underscore.string": "2.3.3" - }, - "dependencies": { - "lodash": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.10.1.tgz", - "integrity": "sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y=" - }, - "strong-globalize": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/strong-globalize/-/strong-globalize-2.10.0.tgz", - "integrity": "sha1-bw5cd2x0n+++c5VLIZwf2WyK4xc=", - "requires": { - "async": "1.5.2", - "debug": "3.1.0", - "esprima": "4.0.0", - "estraverse": "4.2.0", - "g11n-pipeline": "2.0.5", - "htmlparser2": "3.9.2", - "lodash": "4.17.4", - "md5": "2.2.1", - "mkdirp": "0.5.1", - "mktmpdir": "0.1.1", - "optional": "0.1.4", - "os-locale": "2.1.0", - "posix-getopt": "1.2.0", - "word-count": "0.2.2", - "xtend": "4.0.1", - "yamljs": "0.3.0" - }, - "dependencies": { - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha1-W7WgZyYotkFJVmuhaBnmFRjGcmE=", - "requires": { - "ms": "2.0.0" - } - }, - "lodash": { - "version": "4.17.4", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.4.tgz", - "integrity": "sha1-eCA6TRwyiuHYbcpkYONptX9AVa4=" - } - } - }, - "underscore.string": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/underscore.string/-/underscore.string-2.3.3.tgz", - "integrity": "sha1-ccCL9rQosRM/N+ePo6Icgvcymw0=" - } - } - }, - "lru-cache": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.1.tgz", - "integrity": "sha1-Yi4y6CSItJJ5EUpPns9F581rulU=", - "requires": { - "pseudomap": "1.0.2", - "yallist": "2.1.2" - } - }, - "mailcomposer": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/mailcomposer/-/mailcomposer-4.0.1.tgz", - "integrity": "sha1-DhxEsqB890DuF9wUm6AJ8Zyt/rQ=", - "requires": { - "buildmail": "4.0.1", - "libmime": "3.0.0" - } - }, - "make-plural": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/make-plural/-/make-plural-3.0.6.tgz", - "integrity": "sha1-IDOgO6wpC487uRJY9lud9+iwHKc=", - "requires": { - "minimist": "1.2.0" - } - }, - "math-interval-parser": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-interval-parser/-/math-interval-parser-1.1.0.tgz", - "integrity": "sha1-2+2lsGsySZc8bfYXD94jhvCv2JM=", - "requires": { - "xregexp": "2.0.0" - } - }, - "md5": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/md5/-/md5-2.2.1.tgz", - "integrity": "sha1-U6s41f48iJG6RlMp6iP6wFQBJvk=", - "requires": { - "charenc": "0.0.2", - "crypt": "0.0.2", - "is-buffer": "1.1.6" - } - }, - "media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" - }, - "mem": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/mem/-/mem-1.1.0.tgz", - "integrity": "sha1-Xt1StIXKHZAP5kiVUFOZoN+kX3Y=", - "requires": { - "mimic-fn": "1.1.0" - } - }, - "merge-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", - "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" - }, - "messageformat": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/messageformat/-/messageformat-0.3.1.tgz", - "integrity": "sha1-5Y//gkXps5cXmeW0PbWLPpQX9aI=", - "requires": { - "async": "1.5.2", - "glob": "6.0.4", - "make-plural": "3.0.6", - "nopt": "3.0.6", - "watchr": "2.4.13" - } - }, - "methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=" - }, - "mime": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.4.1.tgz", - "integrity": "sha1-Eh+evEnjdm8xGnbh+hyAA8SwOqY=" - }, - "mime-db": { - "version": "1.30.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.30.0.tgz", - "integrity": "sha1-dMZD2i3Z1qRTmZY0ZbJtXKfXHwE=" - }, - "mime-types": { - "version": "2.1.17", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.17.tgz", - "integrity": "sha1-Cdejk/A+mVp5+K+Fe3Cp4KsWVXo=", - "requires": { - "mime-db": "1.30.0" - } - }, - "mimic-fn": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.1.0.tgz", - "integrity": "sha1-5md4PZLonb00KBi1IwudYqZyrRg=" - }, - "minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha1-UWbihkV/AzBgZL5Ul+jbsMPTIIM=", - "requires": { - "brace-expansion": "1.1.8" - } - }, - "minimist": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", - "optional": true - }, - "mkdirp": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", - "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", - "requires": { - "minimist": "0.0.8" - }, - "dependencies": { - "minimist": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=" - } - } - }, - "mktmpdir": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/mktmpdir/-/mktmpdir-0.1.1.tgz", - "integrity": "sha1-OKyCCVDXjvoLnN38A/99XFp4bbk=", - "requires": { - "rimraf": "2.2.8" - }, - "dependencies": { - "rimraf": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.2.8.tgz", - "integrity": "sha1-5Dm+Kq7jJzIZUnMPmaiSnk/FBYI=" - } - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" - }, - "msgpack-js": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/msgpack-js/-/msgpack-js-0.3.0.tgz", - "integrity": "sha1-Aw7AjFlW+cp9F9QKVy1Tlv7BCSM=", - "requires": { - "bops": "0.0.7" - }, - "dependencies": { - "base64-js": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.2.tgz", - "integrity": "sha1-Ak8Pcq+iW3X5wO5zzU9V7Bvtl4Q=" - }, - "bops": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/bops/-/bops-0.0.7.tgz", - "integrity": "sha1-tKClqDmkBkVK8P4FqLkaenZqVOI=", - "requires": { - "base64-js": "0.0.2", - "to-utf8": "0.0.1" - } - } - } - }, - "msgpack-stream": { - "version": "0.0.13", - "resolved": "https://registry.npmjs.org/msgpack-stream/-/msgpack-stream-0.0.13.tgz", - "integrity": "sha1-UKZzrE6uyl43cBkk0JPUM1DB5Sw=", - "requires": { - "bops": "1.0.0", - "msgpack-js": "0.3.0", - "through": "2.3.4" - }, - "dependencies": { - "through": { - "version": "2.3.4", - "resolved": "https://registry.npmjs.org/through/-/through-2.3.4.tgz", - "integrity": "sha1-SV5A6Nio6uvHwnXqiMK4/BTFZFU=" - } - } - }, - "msgpack5": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/msgpack5/-/msgpack5-3.6.0.tgz", - "integrity": "sha1-E5Eu5HywrQN/cN73kk6/OK+hm08=", - "requires": { - "bl": "1.2.1", - "inherits": "2.0.3", - "readable-stream": "2.3.3", - "safe-buffer": "5.1.1" - } - }, - "mustache": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/mustache/-/mustache-2.3.0.tgz", - "integrity": "sha1-QCj3d4sXcIpImTCm5SrDvKDaQdA=" - }, - "mute-stream": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz", - "integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=" - }, - "mux-demux": { - "version": "3.7.9", - "resolved": "https://registry.npmjs.org/mux-demux/-/mux-demux-3.7.9.tgz", - "integrity": "sha1-NTZ3GP02AcgLzi63YlMVdtekrO8=", - "requires": { - "duplex": "1.0.0", - "json-buffer": "2.0.11", - "msgpack-stream": "0.0.13", - "stream-combiner": "0.0.2", - "stream-serializer": "1.1.2", - "through": "2.3.8", - "xtend": "1.0.3" - }, - "dependencies": { - "xtend": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-1.0.3.tgz", - "integrity": "sha1-P12Tc1PM7Y4IU5mlY/2yJUHClgo=" - } - } - }, - "mysql": { - "version": "2.15.0", - "resolved": "https://registry.npmjs.org/mysql/-/mysql-2.15.0.tgz", - "integrity": "sha1-6haEEVY0Po8uR/yJhexBzdlXO1w=", - "requires": { - "bignumber.js": "4.0.4", - "readable-stream": "2.3.3", - "safe-buffer": "5.1.1", - "sqlstring": "2.3.0" - } - }, - "natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=" - }, - "negotiator": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz", - "integrity": "sha1-KzJxhOiZIQEXeyhWP7XnECrNDKk=" - }, - "nocache": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/nocache/-/nocache-1.0.0.tgz", - "integrity": "sha1-MgZe+F9uYqAUVCwrK68RuzcE3yE=" - }, - "node-fetch": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-1.7.3.tgz", - "integrity": "sha1-mA9vcthSEaU0fGsrwYxbhMPrR+8=", - "requires": { - "encoding": "0.1.12", - "is-stream": "1.1.0" - } - }, - "nodemailer": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-2.7.2.tgz", - "integrity": "sha1-8kLmSa7q45tsftdA73sGHEBNMPk=", - "requires": { - "libmime": "3.0.0", - "mailcomposer": "4.0.1", - "nodemailer-direct-transport": "3.3.2", - "nodemailer-shared": "1.1.0", - "nodemailer-smtp-pool": "2.8.2", - "nodemailer-smtp-transport": "2.7.2", - "socks": "1.1.9" - } - }, - "nodemailer-direct-transport": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/nodemailer-direct-transport/-/nodemailer-direct-transport-3.3.2.tgz", - "integrity": "sha1-6W+vuQNYVglH5WkBfZfmBzilCoY=", - "requires": { - "nodemailer-shared": "1.1.0", - "smtp-connection": "2.12.0" - } - }, - "nodemailer-fetch": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/nodemailer-fetch/-/nodemailer-fetch-1.6.0.tgz", - "integrity": "sha1-ecSQihwPXzdbc/6IjamCj23JY6Q=" - }, - "nodemailer-shared": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/nodemailer-shared/-/nodemailer-shared-1.1.0.tgz", - "integrity": "sha1-z1mU4v0mjQD1zw+nZ6CBae2wfsA=", - "requires": { - "nodemailer-fetch": "1.6.0" - } - }, - "nodemailer-smtp-pool": { - "version": "2.8.2", - "resolved": "https://registry.npmjs.org/nodemailer-smtp-pool/-/nodemailer-smtp-pool-2.8.2.tgz", - "integrity": "sha1-LrlNbPhXgLG0clzoU7nL1ejajHI=", - "requires": { - "nodemailer-shared": "1.1.0", - "nodemailer-wellknown": "0.1.10", - "smtp-connection": "2.12.0" - } - }, - "nodemailer-smtp-transport": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/nodemailer-smtp-transport/-/nodemailer-smtp-transport-2.7.2.tgz", - "integrity": "sha1-A9ccdjFPFKx9vHvwM6am0W1n+3c=", - "requires": { - "nodemailer-shared": "1.1.0", - "nodemailer-wellknown": "0.1.10", - "smtp-connection": "2.12.0" - } - }, - "nodemailer-stub-transport": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/nodemailer-stub-transport/-/nodemailer-stub-transport-1.1.0.tgz", - "integrity": "sha1-EUIdLWa07m9AU1T5FMH0ZB6ySw0=" - }, - "nodemailer-wellknown": { - "version": "0.1.10", - "resolved": "https://registry.npmjs.org/nodemailer-wellknown/-/nodemailer-wellknown-0.1.10.tgz", - "integrity": "sha1-WG24EB2zDLRDjrVGc3pBqtDPE9U=" - }, - "nopt": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.6.tgz", - "integrity": "sha1-xkZdvwirzU2zWTF/eaxopkayj/k=", - "requires": { - "abbrev": "1.1.1" - } - }, - "npm-run-path": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", - "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", - "requires": { - "path-key": "2.0.1" - } - }, - "nsp": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/nsp/-/nsp-2.8.1.tgz", - "integrity": "sha1-Q24/E4aeBhDTo49Z1V+bNTzDKBc=", - "dev": true, - "requires": { - "chalk": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "cli-table": "https://registry.npmjs.org/cli-table/-/cli-table-0.3.1.tgz", - "cvss": "https://registry.npmjs.org/cvss/-/cvss-1.0.2.tgz", - "https-proxy-agent": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-1.0.0.tgz", - "joi": "https://registry.npmjs.org/joi/-/joi-6.10.1.tgz", - "nodesecurity-npm-utils": "https://registry.npmjs.org/nodesecurity-npm-utils/-/nodesecurity-npm-utils-5.0.0.tgz", - "path-is-absolute": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "rc": "https://registry.npmjs.org/rc/-/rc-1.2.1.tgz", - "semver": "https://registry.npmjs.org/semver/-/semver-5.4.1.tgz", - "subcommand": "https://registry.npmjs.org/subcommand/-/subcommand-2.1.0.tgz", - "wreck": "https://registry.npmjs.org/wreck/-/wreck-6.3.0.tgz" - }, - "dependencies": { - "agent-base": { - "version": "https://registry.npmjs.org/agent-base/-/agent-base-2.1.1.tgz", - "integrity": "sha1-1t4Q1a9hMtW9aSQn1G/FOFOQlMc=", - "dev": true, - "requires": { - "extend": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz", - "semver": "https://registry.npmjs.org/semver/-/semver-5.0.3.tgz" - }, - "dependencies": { - "semver": { - "version": "https://registry.npmjs.org/semver/-/semver-5.0.3.tgz", - "integrity": "sha1-d0Zt5YnNXTyV8TiqeLxWmjy10no=", - "dev": true - } - } - }, - "ansi-regex": { - "version": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", - "dev": true - }, - "ansi-styles": { - "version": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", - "dev": true - }, - "boom": { - "version": "https://registry.npmjs.org/boom/-/boom-2.10.1.tgz", - "integrity": "sha1-OciRjO/1eZ+D+UkqhI9iWt0Mdm8=", - "dev": true, - "requires": { - "hoek": "https://registry.npmjs.org/hoek/-/hoek-2.16.3.tgz" - } - }, - "chalk": { - "version": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "dev": true, - "requires": { - "ansi-styles": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "escape-string-regexp": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "has-ansi": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "strip-ansi": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "supports-color": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz" - } - }, - "cli-table": { - "version": "https://registry.npmjs.org/cli-table/-/cli-table-0.3.1.tgz", - "integrity": "sha1-9TsFJmqLGguTSz0IIebi3FkUriM=", - "dev": true, - "requires": { - "colors": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz" - } - }, - "cliclopts": { - "version": "https://registry.npmjs.org/cliclopts/-/cliclopts-1.1.1.tgz", - "integrity": "sha1-aUMcfLWvcjd0sNORG0w3USQxkQ8=", - "dev": true - }, - "colors": { - "version": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", - "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", - "dev": true - }, - "cvss": { - "version": "https://registry.npmjs.org/cvss/-/cvss-1.0.2.tgz", - "integrity": "sha1-32fpK/EqeW9J6Sh5nI2zunS5/NY=", - "dev": true - }, - "debug": { - "version": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha1-XRKFFd8TT/Mn6QpMk/Tgd6U2NB8=", - "dev": true, - "requires": { - "ms": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz" - } - }, - "deep-extend": { - "version": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.4.2.tgz", - "integrity": "sha1-SLaZwn4zS/ifEIkr5DL25MfTSn8=", - "dev": true - }, - "escape-string-regexp": { - "version": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true - }, - "extend": { - "version": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz", - "integrity": "sha1-p1Xqe8Gt/MWjHOfnYtuq3F5jZEQ=", - "dev": true - }, - "has-ansi": { - "version": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", - "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", - "dev": true, - "requires": { - "ansi-regex": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz" - } - }, - "hoek": { - "version": "https://registry.npmjs.org/hoek/-/hoek-2.16.3.tgz", - "integrity": "sha1-ILt0A9POo5jpHcRxCo/xuCdKJe0=", - "dev": true - }, - "https-proxy-agent": { - "version": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-1.0.0.tgz", - "integrity": "sha1-NffabEjOTdv6JkiRrFk+5f+GceY=", - "dev": true, - "requires": { - "agent-base": "https://registry.npmjs.org/agent-base/-/agent-base-2.1.1.tgz", - "debug": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "extend": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz" - } - }, - "ini": { - "version": "https://registry.npmjs.org/ini/-/ini-1.3.4.tgz", - "integrity": "sha1-BTfLedr1m1mhpRff9wbIbsA5Fi4=", - "dev": true - }, - "isemail": { - "version": "https://registry.npmjs.org/isemail/-/isemail-1.2.0.tgz", - "integrity": "sha1-vgPfjMPineTSxd9lASY/H6RZXpo=", - "dev": true - }, - "joi": { - "version": "https://registry.npmjs.org/joi/-/joi-6.10.1.tgz", - "integrity": "sha1-TVDDGAeRIgAP5fFq8f+OGRe3fgY=", - "dev": true, - "requires": { - "hoek": "https://registry.npmjs.org/hoek/-/hoek-2.16.3.tgz", - "isemail": "https://registry.npmjs.org/isemail/-/isemail-1.2.0.tgz", - "moment": "https://registry.npmjs.org/moment/-/moment-2.18.1.tgz", - "topo": "https://registry.npmjs.org/topo/-/topo-1.1.0.tgz" - } - }, - "minimist": { - "version": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", - "dev": true - }, - "moment": { - "version": "https://registry.npmjs.org/moment/-/moment-2.18.1.tgz", - "integrity": "sha1-w2GT3Tzhwu7SrbfIAtu8d6gbHA8=", - "dev": true - }, - "ms": { - "version": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "dev": true - }, - "nodesecurity-npm-utils": { - "version": "https://registry.npmjs.org/nodesecurity-npm-utils/-/nodesecurity-npm-utils-5.0.0.tgz", - "integrity": "sha1-Baow3jDKjIRcQEjpT9eOXgi1Xtk=", - "dev": true - }, - "path-is-absolute": { - "version": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", - "dev": true - }, - "rc": { - "version": "https://registry.npmjs.org/rc/-/rc-1.2.1.tgz", - "integrity": "sha1-LgPo5C7kULjLPc5lvhv4l04d/ZU=", - "dev": true, - "requires": { - "deep-extend": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.4.2.tgz", - "ini": "https://registry.npmjs.org/ini/-/ini-1.3.4.tgz", - "minimist": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "strip-json-comments": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz" - } - }, - "semver": { - "version": "https://registry.npmjs.org/semver/-/semver-5.4.1.tgz", - "integrity": "sha1-4FnAnYVx8FQII3M0M1BdOi8AsY4=", - "dev": true - }, - "strip-ansi": { - "version": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "dev": true, - "requires": { - "ansi-regex": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz" - } - }, - "strip-json-comments": { - "version": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", - "dev": true - }, - "subcommand": { - "version": "https://registry.npmjs.org/subcommand/-/subcommand-2.1.0.tgz", - "integrity": "sha1-XkzspaN3njNlsVEeBfhmh3MC92A=", - "dev": true, - "requires": { - "cliclopts": "https://registry.npmjs.org/cliclopts/-/cliclopts-1.1.1.tgz", - "debug": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "minimist": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "xtend": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz" - } - }, - "supports-color": { - "version": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", - "dev": true - }, - "topo": { - "version": "https://registry.npmjs.org/topo/-/topo-1.1.0.tgz", - "integrity": "sha1-6ddRYV0buH3IZdsYL6HKCl71NtU=", - "dev": true, - "requires": { - "hoek": "https://registry.npmjs.org/hoek/-/hoek-2.16.3.tgz" - } - }, - "wreck": { - "version": "https://registry.npmjs.org/wreck/-/wreck-6.3.0.tgz", - "integrity": "sha1-oTaXafB7u2LWo3gzanhx/Hc8dAs=", - "dev": true, - "requires": { - "boom": "https://registry.npmjs.org/boom/-/boom-2.10.1.tgz", - "hoek": "https://registry.npmjs.org/hoek/-/hoek-2.16.3.tgz" - } - }, - "xtend": { - "version": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", - "dev": true - } - } - }, - "oauth-sign": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.8.2.tgz", - "integrity": "sha1-Rqarfwrq2N6unsBWV4C31O/rnUM=" - }, - "object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=" - }, - "on-finished": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", - "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", - "requires": { - "ee-first": "1.1.1" - } - }, - "on-headers": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.1.tgz", - "integrity": "sha1-ko9dD0cNSTQmUepnlLCFfBAGk/c=" - }, - "once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", - "requires": { - "wrappy": "1.0.2" - } - }, - "onetime": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", - "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", - "requires": { - "mimic-fn": "1.1.0" - } - }, - "optional": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/optional/-/optional-0.1.4.tgz", - "integrity": "sha1-zbGpvtxzfSAl9pDO61DgSURP1bM=" - }, - "optionator": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", - "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", - "requires": { - "deep-is": "0.1.3", - "fast-levenshtein": "2.0.6", - "levn": "0.3.0", - "prelude-ls": "1.1.2", - "type-check": "0.3.2", - "wordwrap": "1.0.0" - } - }, - "options": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/options/-/options-0.0.6.tgz", - "integrity": "sha1-7CLTEoBrtT5zF3Pnza788cZDEo8=" - }, - "os-locale": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-2.1.0.tgz", - "integrity": "sha1-QrwpAKa1uL0XN2yOiCtlr8zyS/I=", - "requires": { - "execa": "0.7.0", - "lcid": "1.0.0", - "mem": "1.1.0" - } - }, - "os-tmpdir": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", - "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" - }, - "p-finally": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", - "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=" - }, - "parseurl": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz", - "integrity": "sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=" - }, - "path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" - }, - "path-is-inside": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", - "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=" - }, - "path-key": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", - "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=" - }, - "path-to-regexp": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", - "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" - }, - "performance-now": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", - "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=" - }, - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=" - }, - "pinkie": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", - "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=" - }, - "pinkie-promise": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", - "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", - "requires": { - "pinkie": "2.0.4" - } - }, - "platform": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.1.tgz", - "integrity": "sha1-SSIQiSM1vTExwKCN2i2T7DVD5CM=" - }, - "pluralize": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-7.0.0.tgz", - "integrity": "sha1-KYuJ34uTsCIdv0Ia0rGx6iP8Z3c=" - }, - "posix-getopt": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/posix-getopt/-/posix-getopt-1.2.0.tgz", - "integrity": "sha1-Su7rfa3mb8qKk2XdqfawBXQctiE=" - }, - "prelude-ls": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", - "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=" - }, - "process-nextick-args": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz", - "integrity": "sha1-FQ4gt1ZZCtP5EJPyWk8q2L/zC6M=" - }, - "progress": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.0.tgz", - "integrity": "sha1-ihvjZr+Pwj2yvSPxDG/pILQ4nR8=" - }, - "proxy-addr": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.2.tgz", - "integrity": "sha1-ZXFQT0e7mI7IGAJT+F3X4UlSvew=", - "requires": { - "forwarded": "0.1.2", - "ipaddr.js": "1.5.2" - } - }, - "pseudomap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", - "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=" - }, - "punycode": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", - "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=" - }, - "qs": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.1.tgz", - "integrity": "sha1-NJzfbu+J7EXBLX1es/wMhwNDptg=" - }, - "querystring": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", - "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=" - }, - "range-parser": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.0.tgz", - "integrity": "sha1-9JvmtIeJTdxA3MlKMi9hEJLgDV4=" - }, - "raw-body": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.3.2.tgz", - "integrity": "sha1-vNYMd9Prk83gBQKVw/N5OJvIj4k=", - "requires": { - "bytes": "3.0.0", - "http-errors": "1.6.2", - "iconv-lite": "0.4.19", - "unpipe": "1.0.0" - } - }, - "readable-stream": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.3.tgz", - "integrity": "sha1-No8lEtefnUb9/HE0mueHi7weuVw=", - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "safe-buffer": "5.1.1", - "string_decoder": "1.0.3", - "util-deprecate": "1.0.2" - } - }, - "regenerator-runtime": { - "version": "0.11.1", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz", - "integrity": "sha1-vgWtf5v30i4Fb5cmzuUBf78Z4uk=" - }, - "request": { - "version": "2.83.0", - "resolved": "https://registry.npmjs.org/request/-/request-2.83.0.tgz", - "integrity": "sha1-ygtl2gLtYpNYh4COb1EDgQNOM1Y=", - "requires": { - "aws-sign2": "0.7.0", - "aws4": "1.6.0", - "caseless": "0.12.0", - "combined-stream": "1.0.5", - "extend": "3.0.1", - "forever-agent": "0.6.1", - "form-data": "2.3.1", - "har-validator": "5.0.3", - "hawk": "6.0.2", - "http-signature": "1.2.0", - "is-typedarray": "1.0.0", - "isstream": "0.1.2", - "json-stringify-safe": "5.0.1", - "mime-types": "2.1.17", - "oauth-sign": "0.8.2", - "performance-now": "2.1.0", - "qs": "6.5.1", - "safe-buffer": "5.1.1", - "stringstream": "0.0.5", - "tough-cookie": "2.3.3", - "tunnel-agent": "0.6.0", - "uuid": "3.2.1" - }, - "dependencies": { - "form-data": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.1.tgz", - "integrity": "sha1-b7lPvXGIUwbXPRXMSX/kzE7NRL8=", - "requires": { - "asynckit": "0.4.0", - "combined-stream": "1.0.5", - "mime-types": "2.1.17" - } - } - } - }, - "require-uncached": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/require-uncached/-/require-uncached-1.0.3.tgz", - "integrity": "sha1-Tg1W1slmL9MeQwEcS5WqSZVUIdM=", - "requires": { - "caller-path": "0.1.0", - "resolve-from": "1.0.1" - } - }, - "require-yaml": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/require-yaml/-/require-yaml-0.0.1.tgz", - "integrity": "sha1-LhsY2RPDuqcqWk03O28Tjd0sMr0=", - "requires": { - "js-yaml": "3.10.0" - }, - "dependencies": { - "js-yaml": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.10.0.tgz", - "integrity": "sha512-O2v52ffjLa9VeM43J4XocZE//WT9N0IiwDa3KSHH7Tu8CtH+1qM8SIZvnsTh6v+4yFy5KUY3BHUVwjpfAWsjIA==", - "requires": { - "argparse": "1.0.9", - "esprima": "4.0.0" - } - } - } - }, - "resolve-from": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-1.0.1.tgz", - "integrity": "sha1-Jsv+k10a7uq7Kbw/5a6wHpPUQiY=" - }, - "restore-cursor": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", - "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", - "requires": { - "onetime": "2.0.1", - "signal-exit": "3.0.2" - } - }, - "rimraf": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.2.tgz", - "integrity": "sha1-LtgVDSShbqhlHm1u8PR8QVjOejY=", - "requires": { - "glob": "7.1.2" - }, - "dependencies": { - "glob": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", - "integrity": "sha1-wZyd+aAocC1nhhI4SmVSQExjbRU=", - "requires": { - "fs.realpath": "1.0.0", - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.4", - "once": "1.4.0", - "path-is-absolute": "1.0.1" - } - } - } - }, - "run-async": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.3.0.tgz", - "integrity": "sha1-A3GrSuC91yDUFm19/aZP96RFpsA=", - "requires": { - "is-promise": "2.1.0" - } - }, - "rx-lite": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/rx-lite/-/rx-lite-4.0.8.tgz", - "integrity": "sha1-Cx4Rr4vESDbwSmQH6S2kJGe3lEQ=" - }, - "rx-lite-aggregates": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/rx-lite-aggregates/-/rx-lite-aggregates-4.0.8.tgz", - "integrity": "sha1-dTuHqJoRyVRnxKwWJsTvxOBcZ74=", - "requires": { - "rx-lite": "4.0.8" - } - }, - "safe-buffer": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", - "integrity": "sha1-iTMSr2myEj3vcfV4iQAWce6yyFM=" - }, - "safefs": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/safefs/-/safefs-3.2.2.tgz", - "integrity": "sha1-gXDBRE1wOOCMrqBaN0+uL6NJ4Vw=", - "requires": { - "graceful-fs": "4.1.11" - } - }, - "sax": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", - "integrity": "sha1-KBYjTiN4vdxOU1T6tcqold9xANk=" - }, - "scandirectory": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/scandirectory/-/scandirectory-2.5.0.tgz", - "integrity": "sha1-bOA/VKCQtmjjy+2/IO354xBZPnI=", - "requires": { - "ignorefs": "1.2.0", - "safefs": "3.2.2", - "taskgroup": "4.3.1" - } - }, - "semver": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.5.0.tgz", - "integrity": "sha1-3Eu8emyp2Rbe5dQ1FvAJK1j3uKs=" - }, - "send": { - "version": "0.16.1", - "resolved": "https://registry.npmjs.org/send/-/send-0.16.1.tgz", - "integrity": "sha1-pw4coh0TgsEdDZ9iMd6ygQgNerM=", - "requires": { - "debug": "2.6.9", - "depd": "1.1.2", - "destroy": "1.0.4", - "encodeurl": "1.0.1", - "escape-html": "1.0.3", - "etag": "1.8.1", - "fresh": "0.5.2", - "http-errors": "1.6.2", - "mime": "1.4.1", - "ms": "2.0.0", - "on-finished": "2.3.0", - "range-parser": "1.2.0", - "statuses": "1.3.1" - }, - "dependencies": { - "statuses": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.3.1.tgz", - "integrity": "sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4=" - } - } - }, - "serve-favicon": { - "version": "2.4.5", - "resolved": "https://registry.npmjs.org/serve-favicon/-/serve-favicon-2.4.5.tgz", - "integrity": "sha1-SdmkaGMVOpJAaRyJPSsOfYXW1DY=", - "requires": { - "etag": "1.8.1", - "fresh": "0.5.2", - "ms": "2.0.0", - "parseurl": "1.3.2", - "safe-buffer": "5.1.1" - } - }, - "serve-static": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.13.1.tgz", - "integrity": "sha1-TFfVNASnYdjy58HooYpH2/J4pxk=", - "requires": { - "encodeurl": "1.0.1", - "escape-html": "1.0.3", - "parseurl": "1.3.2", - "send": "0.16.1" - } - }, - "setprototypeof": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.0.3.tgz", - "integrity": "sha1-ZlZ+NwQ+608E2RvWWMDL77VbjgQ=" - }, - "shebang-command": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", - "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", - "requires": { - "shebang-regex": "1.0.0" - } - }, - "shebang-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", - "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=" - }, - "shimmer": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/shimmer/-/shimmer-1.2.0.tgz", - "integrity": "sha1-+Wb3VVeJdj502IQRk2haXnhzZmU=" - }, - "shortid": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/shortid/-/shortid-2.2.8.tgz", - "integrity": "sha1-AzsRfWoul1gE9vCWnb59PQs1UTE=" - }, - "signal-exit": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", - "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=" - }, - "slice-ansi": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-1.0.0.tgz", - "integrity": "sha1-BE8aSdiEL/MHqta1Be0Xi9lQE00=", - "requires": { - "is-fullwidth-code-point": "2.0.0" - } - }, - "smart-buffer": { - "version": "1.1.15", - "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-1.1.15.tgz", - "integrity": "sha1-fxFLW2X6s+KjWqd1uxLw0cZJvxY=" - }, - "smtp-connection": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/smtp-connection/-/smtp-connection-2.12.0.tgz", - "integrity": "sha1-1275EnyyPCJZ7bHoNJwujV4tdME=", - "requires": { - "httpntlm": "1.6.1", - "nodemailer-shared": "1.1.0" - } - }, - "sntp": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/sntp/-/sntp-2.1.0.tgz", - "integrity": "sha1-LGzsFP7cIiJznK+bXD2F0cxaLMg=", - "requires": { - "hoek": "4.2.0" - } - }, - "socks": { - "version": "1.1.9", - "resolved": "https://registry.npmjs.org/socks/-/socks-1.1.9.tgz", - "integrity": "sha1-Yo1+TQSRJDVEWsC25Fk3bLPm1pE=", - "requires": { - "ip": "1.1.5", - "smart-buffer": "1.1.15" - } - }, - "sprintf-js": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.1.tgz", - "integrity": "sha1-Nr54Mgr+WAH2zqPueLblqrlA6gw=" - }, - "sqlstring": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.0.tgz", - "integrity": "sha1-UluKT9Jtb3GqYegipsr5dtMa0qg=" - }, - "sse": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/sse/-/sse-0.0.6.tgz", - "integrity": "sha1-MZJGHfo4x4Qk3Zv46gJWGaElqhA=", - "requires": { - "options": "0.0.6" - } - }, - "sshpk": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.13.1.tgz", - "integrity": "sha1-US322mKHFEMW3EwY/hzx2UBzm+M=", - "requires": { - "asn1": "0.2.3", - "assert-plus": "1.0.0", - "bcrypt-pbkdf": "1.0.1", - "dashdash": "1.14.1", - "ecc-jsbn": "0.1.1", - "getpass": "0.1.7", - "jsbn": "0.1.1", - "tweetnacl": "0.14.5" - } - }, - "stable": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.6.tgz", - "integrity": "sha1-kQ9dKu17Ugxud3SZwfMuE5/eyxA=" - }, - "stack-chain": { - "version": "1.3.7", - "resolved": "https://registry.npmjs.org/stack-chain/-/stack-chain-1.3.7.tgz", - "integrity": "sha1-0ZLJ/06moiyUxN1FkXHj8AzqEoU=" - }, - "statuses": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz", - "integrity": "sha1-u3PURtonlhBu/MG2AaJT1sRr0Ic=" - }, - "stream-combiner": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/stream-combiner/-/stream-combiner-0.0.2.tgz", - "integrity": "sha1-3+DnRnV0JWXnbGBWeI6lwjvZfbQ=", - "requires": { - "duplexer": "0.0.4" - } - }, - "stream-serializer": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/stream-serializer/-/stream-serializer-1.1.2.tgz", - "integrity": "sha1-wfl9FdolH1lK4n1B7IraCahG408=" - }, - "string-width": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", - "integrity": "sha1-q5Pyeo3BPSjKyBXEYhQ6bZASrp4=", - "requires": { - "is-fullwidth-code-point": "2.0.0", - "strip-ansi": "4.0.0" - } - }, - "string_decoder": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", - "integrity": "sha1-D8Z9fBQYJd6UKC3VNr7GubzoYKs=", - "requires": { - "safe-buffer": "5.1.1" - } - }, - "stringstream": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/stringstream/-/stringstream-0.0.5.tgz", - "integrity": "sha1-TkhM1N5aC7vuGORjB3EKioFiGHg=" - }, - "strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "requires": { - "ansi-regex": "3.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" - } - } - }, - "strip-eof": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", - "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=" - }, - "strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=" - }, - "strong-error-handler": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/strong-error-handler/-/strong-error-handler-2.3.0.tgz", - "integrity": "sha1-oyvmSxKbNAa8xTbTbhqhcoUQ/Y4=", - "requires": { - "accepts": "1.3.4", - "debug": "2.6.9", - "ejs": "2.5.7", - "http-status": "1.0.1", - "js2xmlparser": "3.0.0", - "strong-globalize": "3.1.0" - }, - "dependencies": { - "js2xmlparser": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-3.0.0.tgz", - "integrity": "sha1-P7YOqgicVED5MZ9RdgzNB+JJlzM=", - "requires": { - "xmlcreate": "1.0.2" - } - } - } - }, - "strong-globalize": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/strong-globalize/-/strong-globalize-3.1.0.tgz", - "integrity": "sha1-THToyoPZGcwgOhK1bom1RsIy+2M=", - "requires": { - "async": "2.6.0", - "debug": "3.1.0", - "esprima": "4.0.0", - "estraverse": "4.2.0", - "g11n-pipeline": "2.0.5", - "htmlparser2": "3.9.2", - "lodash": "4.17.4", - "md5": "2.2.1", - "mkdirp": "0.5.1", - "mktmpdir": "0.1.1", - "optional": "0.1.4", - "os-locale": "2.1.0", - "posix-getopt": "1.2.0", - "word-count": "0.2.2", - "xtend": "4.0.1", - "yamljs": "0.3.0" - }, - "dependencies": { - "async": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/async/-/async-2.6.0.tgz", - "integrity": "sha1-YaKau2/MAm/qd+VtHG7FOnlZUfQ=", - "requires": { - "lodash": "4.17.4" - } - }, - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha1-W7WgZyYotkFJVmuhaBnmFRjGcmE=", - "requires": { - "ms": "2.0.0" - } - } - } - }, - "strong-remoting": { - "version": "3.8.0", - "resolved": "https://registry.npmjs.org/strong-remoting/-/strong-remoting-3.8.0.tgz", - "integrity": "sha1-h5XzWtKkQVQ1QrYxcJ2ye7wGlVs=", - "requires": { - "async": "2.6.0", - "body-parser": "1.18.2", - "debug": "2.6.9", - "depd": "1.1.2", - "escape-string-regexp": "1.0.5", - "eventemitter2": "2.2.2", - "express": "4.16.2", - "inflection": "1.12.0", - "jayson": "1.2.2", - "js2xmlparser": "1.0.0", - "loopback-datatype-geopoint": "1.0.0", - "loopback-phase": "3.1.0", - "mux-demux": "3.7.9", - "qs": "6.5.1", - "request": "2.83.0", - "sse": "0.0.6", - "strong-error-handler": "2.3.0", - "strong-globalize": "3.1.0", - "traverse": "0.6.6", - "xml2js": "0.4.19" - }, - "dependencies": { - "async": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/async/-/async-2.6.0.tgz", - "integrity": "sha1-YaKau2/MAm/qd+VtHG7FOnlZUfQ=", - "requires": { - "lodash": "4.17.4" - } - } - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" - }, - "swagger-client": { - "version": "3.4.5", - "resolved": "https://registry.npmjs.org/swagger-client/-/swagger-client-3.4.5.tgz", - "integrity": "sha1-4mrFH2nn1Ldczoz7VtlIOdVx6o0=", - "requires": { - "babel-runtime": "6.26.0", - "btoa": "1.1.2", - "cookie": "0.3.1", - "cross-fetch": "0.0.8", - "deep-extend": "0.4.2", - "encode-3986": "1.0.0", - "fast-json-patch": "1.1.8", - "isomorphic-form-data": "0.0.1", - "js-yaml": "3.10.0", - "lodash": "4.17.4", - "qs": "6.5.1", - "url": "0.11.0", - "utf8-bytes": "0.0.1", - "utfstring": "2.0.0" - } - }, - "swagger-ui": { - "version": "2.2.10", - "resolved": "https://registry.npmjs.org/swagger-ui/-/swagger-ui-2.2.10.tgz", - "integrity": "sha1-sl56IWZOXZC/OR2zDbCN5B6FLXs=" - }, - "table": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/table/-/table-4.0.2.tgz", - "integrity": "sha1-ozRHN1OR52atNNNIbm4q7chNLjY=", - "requires": { - "ajv": "5.5.2", - "ajv-keywords": "2.1.1", - "chalk": "2.3.0", - "lodash": "4.17.4", - "slice-ansi": "1.0.0", - "string-width": "2.1.1" - } - }, - "taskgroup": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/taskgroup/-/taskgroup-4.3.1.tgz", - "integrity": "sha1-feGT/r12gnPEV3MElwJNUSwnkVo=", - "requires": { - "ambi": "2.5.0", - "csextends": "1.1.1" - } - }, - "text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=" - }, - "through": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", - "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=" - }, - "tmp": { - "version": "0.0.33", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", - "integrity": "sha1-bTQzWIl2jSGyvNoKonfO07G/rfk=", - "requires": { - "os-tmpdir": "1.0.2" - } - }, - "to-utf8": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/to-utf8/-/to-utf8-0.0.1.tgz", - "integrity": "sha1-0Xrqcv8vujm55DYBvns/9y4ImFI=" - }, - "toposort": { - "version": "0.2.12", - "resolved": "https://registry.npmjs.org/toposort/-/toposort-0.2.12.tgz", - "integrity": "sha1-x9KYTz1IwhcxXMMtdwiIt3lJHoE=" - }, - "tough-cookie": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.3.3.tgz", - "integrity": "sha1-C2GKVWW23qkL80JdBNVe3EdadWE=", - "requires": { - "punycode": "1.4.1" - }, - "dependencies": { - "punycode": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", - "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=" - } - } - }, - "traverse": { - "version": "0.6.6", - "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.6.6.tgz", - "integrity": "sha1-y99WD9e5r2MlAv7UD5GMFX6pcTc=" - }, - "tunnel-agent": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", - "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", - "requires": { - "safe-buffer": "5.1.1" - } - }, - "tweetnacl": { - "version": "0.14.5", - "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", - "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", - "optional": true - }, - "type-check": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", - "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", - "requires": { - "prelude-ls": "1.1.2" - } - }, - "type-is": { - "version": "1.6.15", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.15.tgz", - "integrity": "sha1-yrEPtJCeRByChC6v4a1kbIGARBA=", - "requires": { - "media-typer": "0.3.0", - "mime-types": "2.1.17" - } - }, - "typechecker": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/typechecker/-/typechecker-2.1.0.tgz", - "integrity": "sha1-0cIJOlT/ihn1jP+HfuqlTyJC04M=" - }, - "typedarray": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", - "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=" - }, - "uid2": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/uid2/-/uid2-0.0.3.tgz", - "integrity": "sha1-SDEm4Rd03y9xuLY53NeZw3YWK4I=" - }, - "underscore": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.7.0.tgz", - "integrity": "sha1-a7rwh3UA02vjTsqlhODbn+8DUgk=" - }, - "underscore.string": { - "version": "3.3.4", - "resolved": "https://registry.npmjs.org/underscore.string/-/underscore.string-3.3.4.tgz", - "integrity": "sha1-LCo/n4PmR2L9xF5s6sZRQoZCE9s=", - "requires": { - "sprintf-js": "1.1.1", - "util-deprecate": "1.0.2" - } - }, - "universalify": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.1.tgz", - "integrity": "sha1-+nG63UQ3r0wUiEHjs7Fl+enlkLc=" - }, - "unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=" - }, - "url": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", - "integrity": "sha1-ODjpfPxgUh63PFJajlW/3Z4uKPE=", - "requires": { - "punycode": "1.3.2", - "querystring": "0.2.0" - } - }, - "utf8-bytes": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/utf8-bytes/-/utf8-bytes-0.0.1.tgz", - "integrity": "sha1-EWsCVEjJtQAIHN+/H01sbDfYg30=" - }, - "utfstring": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/utfstring/-/utfstring-2.0.0.tgz", - "integrity": "sha1-szH3NR6b4cRjNMx1GIJs2jtEJCo=" - }, - "util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" - }, - "utils-merge": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.0.tgz", - "integrity": "sha1-ApT7kiu5N1FTVBxPcJYjHyh8ivg=" - }, - "uuid": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.2.1.tgz", - "integrity": "sha1-EsUou51Y0LkmXZovbw/ovhf/HxQ=" - }, - "vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=" - }, - "verror": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", - "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", - "requires": { - "assert-plus": "1.0.0", - "core-util-is": "1.0.2", - "extsprintf": "1.3.0" - } - }, - "watchr": { - "version": "2.4.13", - "resolved": "https://registry.npmjs.org/watchr/-/watchr-2.4.13.tgz", - "integrity": "sha1-10hHu01vkPYf4sdPn2hmKqDgdgE=", - "requires": { - "eachr": "2.0.4", - "extendr": "2.1.0", - "extract-opts": "2.2.0", - "ignorefs": "1.2.0", - "safefs": "3.2.2", - "scandirectory": "2.5.0", - "taskgroup": "4.3.1", - "typechecker": "2.1.0" - } - }, - "whatwg-fetch": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-2.0.3.tgz", - "integrity": "sha1-nITsLc9oGH/wC8ZOEnS0QhduHIQ=" - }, - "which": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/which/-/which-1.3.0.tgz", - "integrity": "sha1-/wS9/AEO5UfXgL7DjhrBwnd9JTo=", - "requires": { - "isexe": "2.0.0" - } - }, - "word-count": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/word-count/-/word-count-0.2.2.tgz", - "integrity": "sha1-aZGS/KaCn+k21Byw2V25JIxXBFE=" - }, - "wordwrap": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", - "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=" - }, - "wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" - }, - "write": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/write/-/write-0.2.1.tgz", - "integrity": "sha1-X8A4KOJkzqP+kUVUdvejxWbLB1c=", - "requires": { - "mkdirp": "0.5.1" - } - }, - "x-xss-protection": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/x-xss-protection/-/x-xss-protection-1.0.0.tgz", - "integrity": "sha1-iYr7k4abJGYc+cUvnujbjtB2Tdk=" - }, - "xml2js": { - "version": "0.4.19", - "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.19.tgz", - "integrity": "sha1-aGwg8hMgnpSr8NG88e+qKRx4J6c=", - "requires": { - "sax": "1.2.4", - "xmlbuilder": "9.0.4" - } - }, - "xmlbuilder": { - "version": "9.0.4", - "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-9.0.4.tgz", - "integrity": "sha1-UZy0ymhtAFqEINNJbz8MruzKWA8=" - }, - "xmlcreate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-1.0.2.tgz", - "integrity": "sha1-+mv3YqYKQT+z3Y9LA8WyaSONMI8=" - }, - "xregexp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/xregexp/-/xregexp-2.0.0.tgz", - "integrity": "sha1-UqY+VsoLhKfzpfPWGHLxJq16WUM=" - }, - "xtend": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=" - }, - "yallist": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", - "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=" - }, - "yamljs": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/yamljs/-/yamljs-0.3.0.tgz", - "integrity": "sha1-3AYL8mdEezn3ME6bK/votafdsDs=", - "requires": { - "argparse": "1.0.9", - "glob": "7.1.2" - }, - "dependencies": { - "glob": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", - "integrity": "sha1-wZyd+aAocC1nhhI4SmVSQExjbRU=", - "requires": { - "fs.realpath": "1.0.0", - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.4", - "once": "1.4.0", - "path-is-absolute": "1.0.1" - } - } - } - } - } -} diff --git a/services/loopback/package.json b/services/loopback/package.json deleted file mode 100644 index e34e525be..000000000 --- a/services/loopback/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "vn-loopback", - "version": "1.0.0", - "scripts": { - "start": "node ." - }, - "dependencies": { - "compression": "^1.0.3", - "cors": "^2.5.2", - "fs-extra": "^5.0.0", - "helmet": "^1.3.0", - "i18n": "^0.8.3", - "loopback": "^3.14.0", - "loopback-boot": "^2.26.2", - "loopback-component-explorer": "^4.2.0", - "loopback-connector-mysql": "^3.0.0", - "loopback-connector-remote": "^3.1.1", - "loopback-context": "^3.3.0", - "md5": "^2.2.1", - "require-yaml": "0.0.1", - "serve-favicon": "^2.0.1", - "strong-error-handler": "^2.1.0" - }, - "devDependencies": { - "nsp": "^2.1.0" - }, - "repository": { - "type": "git", - "url": "https://git.verdnatura.es/salix" - }, - "license": "GPL-3.0", - "description": "Loopback wrapper by Verdnatura" -} diff --git a/services/loopback/server/boot/validations.js b/services/loopback/server/boot/validations.js deleted file mode 100644 index fe5e5d365..000000000 --- a/services/loopback/server/boot/validations.js +++ /dev/null @@ -1,58 +0,0 @@ -module.exports = function(app) { - function toJson(object) { - let json = {}; - - for (let prop in object) { - let value = object[prop]; - - switch (typeof value) { - case 'object': - if (value instanceof RegExp) - json[prop] = value.source; - break; - case 'function': - json[prop] = value.toString(); - break; - default: - json[prop] = value; - } - } - - return json; - } - - app.get('/validations', function(req, res) { - let json = {}; - let models = app.models; - - for (let modelName in models) { - let model = models[modelName]; - let validations = model.validations; - let jsonValidations = {}; - - for (let fieldName in validations) { - let jsonField = []; - - for (let validation of validations[fieldName]) { - let options = validation.options; - - if ((options && options.async) || - (validation.validation == 'custom' && !validation.isExportable)) - continue; - - jsonField.push(toJson(validation)); - } - - jsonValidations[fieldName] = jsonField; - } - - json[modelName] = { - properties: model.definition.rawProperties, - validations: jsonValidations - }; - } - - res.set('Content-Type', 'application/json'); - res.send(JSON.stringify(json)); - }); -}; diff --git a/services/loopback/server/datasources.json b/services/loopback/server/datasources.json deleted file mode 100644 index 945c81966..000000000 --- a/services/loopback/server/datasources.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "db": { - "name": "db", - "connector": "memory" - }, - "vn": { - "name": "mysql", - "connector": "mysql", - "database": "vn", - "debug": false, - "host": "${salixHost}", - "port": "${salixPort}", - "username": "${salixUser}", - "password": "${salixPassword}", - "connectTimeout": 20000, - "acquireTimeout": 20000 - }, - "salix": { - "name": "mysql", - "connector": "mysql", - "database": "salix", - "debug": false, - "host": "${salixHost}", - "port": "${salixPort}", - "username": "${salixUser}", - "password": "${salixPassword}", - "connectTimeout": 20000, - "acquireTimeout": 20000 - }, - "account": { - "name": "mysql", - "connector": "mysql", - "database": "account", - "debug": false, - "host": "${salixHost}", - "port": "${salixPort}", - "username": "${salixUser}", - "password": "${salixPassword}", - "connectTimeout": 20000, - "acquireTimeout": 20000 - }, - "edi": { - "connector": "mysql", - "database": "edi", - "debug": false, - "host": "${salixHost}", - "port": "${salixPort}", - "username": "${salixUser}", - "password": "${salixPassword}", - "connectTimeout": 20000, - "acquireTimeout": 20000 - } -} diff --git a/services/loopback/server/middleware/cors.js b/services/loopback/server/middleware/cors.js deleted file mode 100644 index 73c0d6832..000000000 --- a/services/loopback/server/middleware/cors.js +++ /dev/null @@ -1,5 +0,0 @@ -var cors = require('cors'); - -module.exports = function() { - return cors({origin: true}); -}; diff --git a/services/loopback/server/middleware/error-handler.js b/services/loopback/server/middleware/error-handler.js deleted file mode 100644 index 6565ca67a..000000000 --- a/services/loopback/server/middleware/error-handler.js +++ /dev/null @@ -1,28 +0,0 @@ -const UserError = require('../../common/helpers').UserError; - -module.exports = function() { - return function(err, req, res, next) { - // Thrown user errors - if (err instanceof UserError) { - err.message = req.__(err.message); - return next(err); - } - - // Validation errors - if (err.statusCode == 422) { - try { - let code; - let messages = err.details.messages; - for (code in messages) break; - err.message = req.__(messages[code][0]); - return next(err); - } catch (e) {} - } - - // MySQL user-defined exceptions - if (err.sqlState == '45000') - return next(new UserError(req.__(err.sqlMessage))); - - next(err); - }; -}; diff --git a/services/loopback/server/model-config.json b/services/loopback/server/model-config.json deleted file mode 100644 index b0d9eda0a..000000000 --- a/services/loopback/server/model-config.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "user": { - "dataSource": "salix" - }, - "AccessToken": { - "dataSource": "salix", - "relations": { - "user": { - "type": "belongsTo", - "model": "user", - "foreignKey": "userId" - } - } - }, - "ACL": { - "dataSource": "salix" - }, - "RoleMapping": { - "dataSource": "salix" - }, - "Role": { - "dataSource": "salix" - }, - "Account": { - "dataSource": "account" - }, - "Address": { - "dataSource": "vn" - }, - "Agency": { - "dataSource": "vn" - }, - "AgencyMode": { - "dataSource": "vn" - }, - "Client": { - "dataSource": "vn" - }, - "ClientCreditLimit": { - "dataSource": "vn" - }, - "ContactChannel": { - "dataSource": "vn" - }, - "Country": { - "dataSource": "vn" - }, - "PayMethod": { - "dataSource": "vn" - }, - "Province": { - "dataSource": "vn" - }, - "Warehouse":{ - "dataSource": "vn" - }, - "Worker": { - "dataSource": "vn" - }, - "Ticket": { - "dataSource": "vn" - }, - "Route": { - "dataSource": "vn" - }, - "State":{ - "dataSource": "vn" - }, - "TicketState":{ - "dataSource": "vn" - } -} diff --git a/services/loopback/server/server.js b/services/loopback/server/server.js deleted file mode 100644 index 294500854..000000000 --- a/services/loopback/server/server.js +++ /dev/null @@ -1,130 +0,0 @@ -let loopback = require('loopback'); -let boot = require('loopback-boot'); -let fs = require('fs-extra'); -let i18n = require('i18n'); -let path = require('path'); - -module.exports = { - loopback: loopback, - boot: vnBoot -}; - -function vnBoot(app, rootDir, rootModule) { - // Internationalization - - let localeDir = `${__dirname}/../common/locale`; - - if (fs.existsSync(localeDir)) { - i18n.configure({ - directory: localeDir, - defaultLocale: 'es' - }); - - app.use(i18n.init); - } - - // View - - let wpAssets; - let viewDir = `${rootDir}/../client`; - - if (fs.existsSync(viewDir)) { - try { - wpAssets = require('../client/webpack-assets.json'); - } catch (e) {} - - app.set('view engine', 'ejs'); - app.set('views', viewDir); - app.use(loopback.static(path.resolve(rootDir, '../client'))); - } - - app.renderIndex = async res => { - res.render(`${viewDir}/index.ejs`, { - assets: assets - }); - - function assets(main, deps) { - let jsFiles; - - if (wpAssets) { - jsFiles = [wpAssets.manifest.js]; - - for (let dep of deps) - jsFiles.push(wpAssets[dep].js); - - jsFiles.push(wpAssets[main].js); - } else { - let publicPath = '/static'; - jsFiles = [`${publicPath}/manifest.js`]; - - for (let dep of deps) - jsFiles.push(`${publicPath}/${dep}.js`); - - jsFiles.push(`${publicPath}/${main}.js`); - } - - return jsFiles; - } - }; - - // Initialization - - app.start = port => { - function onListen() { - app.emit('started'); - let packageJson = require(`${rootDir}/../package.json`); - let appName = packageJson.name; - let baseUrl = app.get('url').replace(/\/$/, ''); - console.log(`Web server ${appName} listening at: %s`, baseUrl); - } - - let args = port ? [port, onListen] : [onListen]; - return app.listen.apply(app, args); - }; - - let config = require('./config.json'); - - for (let key in config) { - app.set(key, config[key]); - } - - let modelConfigFiles = [ - `${__dirname}/model-config.json`, - `${rootDir}/model-config.json` - ]; - - let modelConfig = {}; - - for (file of modelConfigFiles) - if (fs.existsSync(file)) - Object.assign(modelConfig, require(file)); - - let bootOptions = { - appRootDir: __dirname, - appConfigRootDir: rootDir, - modelsRootDir: rootDir, - models: modelConfig, - modelSources: [ - `loopback/common/models`, - `loopback/server/models`, - `${__dirname}/../common/models`, - `${rootDir}/../common/models` - ], - mixinDirs: [ - `loopback/common/mixins`, - `loopback/server/mixins`, - `${__dirname}/../common/mixins`, - `${rootDir}/../common/mixins` - ], - bootDirs: [ - `${__dirname}/boot`, - `${rootDir}/boot` - ] - }; - - boot(app, bootOptions, function(err) { - if (err) throw err; - if (require.main === rootModule) - app.start(); - }); -} diff --git a/services/mailer/.gitignore b/services/mailer/.gitignore deleted file mode 100644 index 3c3629e64..000000000 --- a/services/mailer/.gitignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/services/mailer/Dockerfile b/services/mailer/Dockerfile deleted file mode 100644 index 6ac52382e..000000000 --- a/services/mailer/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -FROM node:8.9.4 - -COPY mailer /app -COPY loopback /loopback - -WORKDIR /app - -RUN npm install -RUN npm -g install pm2 - -CMD ["pm2-docker", "./server/server.js"] diff --git a/services/mailer/application/auth.js b/services/mailer/application/auth.js deleted file mode 100644 index 49918eb57..000000000 --- a/services/mailer/application/auth.js +++ /dev/null @@ -1,75 +0,0 @@ -var database = require('./database.js'); -let config = require('./config.js'); - -module.exports = { - /** - * Initialize auth. - * @param {Object} request Request object - * @param {Object} response Response object - * @param {Object} next Next object - */ - init: function(request, response, next) { - this.request = request; - this.response = response; - this.next = next; - - this.validateToken(); - }, - - /** - * Validate auth token. - */ - validateToken: function() { - let query = 'SELECT userId, ttl, created FROM salix.AccessToken WHERE id = ?'; - - database.pool.query(query, [this.getToken()], (error, result) => { - let token = result[0]; - - if (error || result.length == 0) - return this.response.status(401).send({message: 'Invalid token'}); - - if (this.isTokenExpired(token.created, token.ttl)) - return this.response.status(401).send({message: 'Token expired'}); - - // Set proxy host - let proxy = config.proxy; - - if (!proxy) - proxy = { - host: 'localhost', - port: 80 - }; - - this.request.proxyHost = `http://${proxy.host}:${proxy.port}`; - this.request.user = { - id: token.userId, - token: this.getToken() - }; - this.next(); - }); - }, - - /** - * Get request token. - * @return {String} Token - */ - getToken: function() { - return this.request.headers.authorization || this.request.query.token; - }, - - /** - * Checks if the token has expired. - * @param {String} created Creation date - * @param {Integer} ttl Ttl seconds - * @return {Boolean} %true if the token has expired - */ - isTokenExpired: function(created, ttl) { - let date = new Date(created); - let currentDate = new Date(); - - date.setSeconds(date.getSeconds() + ttl); - - if (currentDate > date) - return true; - } -}; diff --git a/services/mailer/application/config.js b/services/mailer/application/config.js deleted file mode 100644 index 335441531..000000000 --- a/services/mailer/application/config.js +++ /dev/null @@ -1,21 +0,0 @@ -require('require-yaml'); -var fs = require('fs-extra'); - -let env = process.env.NODE_ENV ? process.env.NODE_ENV : 'development'; - -let config = require(`${__dirname}/config/datasources.json`); -let configEnvFile = `${__dirname}/config/datasources.${env}.json`; - -if (fs.existsSync(configEnvFile)) - Object.assign(config, require(configEnvFile)); - -let proxyConf = require(`../../nginx/config.yml`); -let proxyEnvFile = `../../nginx/config.${env}.yml`; - -if (fs.existsSync(proxyEnvFile)) - Object.assign(proxyConf, require(proxyEnvFile)); - -config.proxy = proxyConf; -config.package = require('../package.json'); - -module.exports = config; diff --git a/services/mailer/application/config/datasources.json b/services/mailer/application/config/datasources.json deleted file mode 100644 index 6d489ec36..000000000 --- a/services/mailer/application/config/datasources.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "app": { - "port": 3000, - "debug": false, - "defaultLanguage": "es", - "senderMail": "noreply@localhost", - "senderName": "MySender" - }, - "mysql": { - "host": "localhost", - "port": 3306, - "database": "vn", - "user": "root", - "password": "root" - }, - "smtp": { - "host": "localhost", - "port": 465, - "secure": true, - "auth": { - "user": "noreply", - "pass": "" - }, - "tls": { - "rejectUnauthorized": false - }, - "pool": true - } -} \ No newline at end of file diff --git a/services/mailer/application/database.js b/services/mailer/application/database.js deleted file mode 100644 index 4fe4a0ba9..000000000 --- a/services/mailer/application/database.js +++ /dev/null @@ -1,33 +0,0 @@ -var mysql = require('mysql'); -let config = require('./config.js'); - -module.exports = { - /** - * Pool instance - */ - pool: null, - - /** - * Start database pool - */ - init: function() { - this.pool = mysql.createPool(config.mysql); - - this.pool.getConnection(function(error, connection) { - if (error) { - throw new Error('Can\'t connect to database: ' + error.code); - } else if (config.app.debug) { - console.log('Database connection stablished'); - } - }); - }, - - /** - * Set test environment mail. - */ - testEmail: function() { - this.pool.query('SELECT fakeEmail as email FROM vn.config', function(error, qryRs) { - config.smtp.testEmail = qryRs[0].email; - }); - } -}; diff --git a/services/mailer/application/locale.js b/services/mailer/application/locale.js deleted file mode 100644 index f9737fea3..000000000 --- a/services/mailer/application/locale.js +++ /dev/null @@ -1,42 +0,0 @@ -var fs = require('fs'); -var config = require('./config.js'); -var path = require('path'); - -module.exports = { -/** - * Returns template locale - * @param {String} template - Template name - * @param {String} countryCode - Language code - * @param {Object} cb - Callback - */ - load: function(template, countryCode, cb) { - var localeFile = path.join(__dirname, 'template', `${template}`, 'locale', `${countryCode}.json`); - var defaultLocaleFile = path.join(__dirname, 'template', `${template}`, 'locale', `${config.app.defaultLanguage}.json`); - - fs.stat(localeFile, (error, stats) => { - if (error) { - fs.stat(defaultLocaleFile, (error, stats) => { - if (error) - return cb(new Error('Translation not found for template ' + template)); - - cb(null, {locale: require(defaultLocaleFile)}); - }); - } else { - cb(null, {locale: require(localeFile)}); - } - }); - }, - -/** - * Parse locale text - * @param {String} text - Locale text - * @param {Object} params - Locale params - * @return {String} - Returns parsed text - */ - parseText: function(text, params) { - for (var key in params) { - text = text.replace(`%${key}%`, params[key]); - } - return text; - } -}; diff --git a/services/mailer/application/mail.js b/services/mailer/application/mail.js deleted file mode 100644 index 2cc8c7465..000000000 --- a/services/mailer/application/mail.js +++ /dev/null @@ -1,118 +0,0 @@ -var nodemailer = require('nodemailer'); -var config = require('./config.js'); -var template = require('./template.js'); -var database = require('./database.js'); - -/** - * Mail module - */ -module.exports = { - transporter: null, - /** - * Load mail config. - */ - init: function() { - if (process.env.NODE_ENV == 'test') - return; - - this.transporter = nodemailer.createTransport(config.smtp); - - this.transporter.verify(function(error, success) { - if (error) { - console.error(error); - } else if (config.app.debug) { - console.log('SMTP connection stablished'); - } - }); - - }, - - /** - * Send email. - * @param {Object} recipient - Mail destinatary - * @param {String} subject - Subject - * @param {String} body - Mail body - * @param {Object} attachments - Mail attachments - * @param {Object} params - Params - * @param {Object} cb - Callback - */ - send: function(recipient, subject, body, attachments, params, cb) { - if (process.env.NODE_ENV == 'test') - return; - - let mailOptions = { - from: '"' + config.app.senderName + '" <' + config.app.senderMail + '>', - to: recipient, - subject: subject, - html: body, - attachments - }; - - if (process.env.NODE_ENV != 'production') - mailOptions.to = config.smtp.testEmail; - - this.transporter.sendMail(mailOptions, (error, info) => { - try { - let status = (error ? error.message : 'OK'); - this.log(params.sender, params.recipient, recipient, subject, body, params.message, status); - - if (error) - return cb(new Error('Email not sent: ' + error)); - - if (config.app.debug) - console.log('Mail sent ' + info.messageId + ' [' + info.response + ']'); - - cb(); - } catch (e) { - throw e; - } - }); - }, - - /** - * Send email with template. - * @param {String} tplName - Template name - * @param {Object} params - Params object - * @param {Object} cb - Callback - */ - sendWithTemplate: function(tplName, params, cb) { - template.get(tplName, params, (error, result) => { - if (error) - return cb(error); - - // Custom attachments - if (params.attachments) - params.attachments.forEach(function(attachment) { - result.attachments.push(attachment); - }); - - this.send(result.recipient, result.subject, result.body, result.attachments, params, error => { - if (error) - return cb(error); - - cb(); - }); - }); - }, - - /** - * Add mail log - * @param {Integer} senderId - Sender id - * @param {Integer} recipientId - Recipient id - * @param {String} sender - Sender email - * @param {String} subject - Mail subject - * @param {String} body - Mail body - * @param {String} plainTextBody - Mail plain text body - * @param {String} status - Mail status - */ - log: function(senderId, recipientId, sender, subject, body, plainTextBody, status) { - let qry = `INSERT INTO mail(senderFk, recipientFk, sender, replyTo, subject, body, plainTextBody, sent, status) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`; - let qryParams = [senderId, recipientId, sender, config.app.senderMail, subject, body, plainTextBody, 1, status]; - - database.pool.query(qry, qryParams, function(error, result) { - if (config.app.debug && error) - console.log('Mail log: ' + error); - }); - } -}; diff --git a/services/mailer/application/route/notification.js b/services/mailer/application/route/notification.js deleted file mode 100644 index 0c7ac4e0e..000000000 --- a/services/mailer/application/route/notification.js +++ /dev/null @@ -1,288 +0,0 @@ -var express = require('express'); -var router = new express.Router(); -var config = require('../config.js'); -var mail = require('../mail.js'); -var template = require('../template.js'); -var httpRequest = require('request'); -var auth = require('../auth.js'); - -// Auth middleware -var requestToken = function(request, response, next) { - auth.init(request, response, next); -}; - -// Printer setup -router.get('/printer-setup/:clientId', requestToken, function(request, response) { - mail.sendWithTemplate('printer-setup', {clientId: request.params.clientId}, error => { - if (error) - return response.status(400).json({message: error.message}); - - return response.json(); - }); -}); - -// Printer setup preview -router.get('/printer-setup/:clientId/preview', requestToken, function(request, response) { - template.get('printer-setup', {clientId: request.params.clientId, isPreview: true}, (error, result) => { - if (error) - return response.status(400).json({message: error.message}); - - response.send(result.body); - }); -}); - -// Client welcome -router.get('/client-welcome/:clientId', requestToken, function(request, response) { - mail.sendWithTemplate('client-welcome', {clientId: request.params.clientId}, error => { - if (error) - return response.status(400).json({message: error.message}); - - return response.json(); - }); -}); - -// Client welcome preview -router.get('/client-welcome/:clientId/preview', requestToken, function(request, response) { - template.get('client-welcome', {clientId: request.params.clientId, isPreview: true}, (error, result) => { - if (error) - return response.status(400).json({message: error.message}); - - response.send(result.body); - }); -}); - -// Client SEPA CORE -router.get('/sepa-core/:companyId/:clientId', requestToken, function(request, response) { - let params = { - clientId: request.params.clientId, - companyId: request.params.companyId - }; - - let path = `${request.proxyHost}/print/manuscript/sepa-core/${params.companyId}/${params.clientId}`; - let options = { - url: path, - method: 'GET', - headers: { - 'Authorization': request.headers.authorization - } - } - - let httpStream = httpRequest(options, function(error, httpResponse, body) { - if (error || httpResponse.statusCode != 200) - return response.status(400).json({message: error}); - }); - - if (httpStream) - params.attachments = [{filename: 'sepa-core.pdf', content: httpStream}]; - - mail.sendWithTemplate('sepa-core', params, error => { - if (error) - return response.status(400).json({message: error.message}); - - return response.json(); - }); -}); - -// Client SEPA CORE preview -router.get('/sepa-core/:companyId/:clientId/preview', requestToken, function(request, response) { - let params = { - clientId: request.params.clientId, - companyId: request.params.companyId, - token: request.user.token, - isPreview: true - }; - - template.get('sepa-core', params, (error, result) => { - if (error) - return response.status(400).json({message: error.message}); - - response.send(result.body); - }); -}); - -// First debtor letter -router.get('/letter-debtor-st/:companyId/:clientId', requestToken, function(request, response) { - let params = { - clientId: request.params.clientId, - companyId: request.params.companyId, - token: request.user.token - }; - - let path = `${request.proxyHost}/print/manuscript/letter-debtor/${params.companyId}/${params.clientId}`; - let options = { - url: path, - method: 'GET', - headers: { - 'Authorization': request.headers.authorization - } - } - - let httpStream = httpRequest(options, function(error, httpResponse, body) { - if (error || httpResponse.statusCode != 200) - return response.status(400).json({message: error}); - }); - - if (httpStream) - params.attachments = [{filename: 'extracto.pdf', content: httpStream}]; - - mail.sendWithTemplate('letter-debtor-st', params, error => { - if (error) - return response.status(400).json({message: error.message}); - - return response.json(); - }); -}); - -// First debtor letter preview -router.get('/letter-debtor-st/:companyId/:clientId/preview', requestToken, function(request, response) { - template.get('letter-debtor-st', { - clientId: request.params.clientId, - companyId: request.params.companyId, - token: request.user.token, - isPreview: true - }, (error, result) => { - if (error) - return response.status(400).json({message: error.message}); - - response.send(result.body); - }); -}); - -// Second debtor letter -router.get('/letter-debtor-nd/:companyId/:clientId', requestToken, function(request, response) { - let params = { - clientId: request.params.clientId, - companyId: request.params.companyId, - token: request.user.token - }; - - let path = `${request.proxyHost}/print/manuscript/letter-debtor/${params.companyId}/${params.clientId}`; - let options = { - url: path, - method: 'GET', - headers: { - 'Authorization': request.headers.authorization - } - } - - let httpStream = httpRequest(options, function(error, httpResponse, body) { - if (error || httpResponse.statusCode != 200) - return response.status(400).json({message: error}); - }); - - if (httpStream) - params.attachments = [{filename: 'extracto.pdf', content: httpStream}]; - - mail.sendWithTemplate('letter-debtor-nd', params, error => { - if (error) - return response.status(400).json({message: error.message}); - - return response.json(); - }); -}); - -// Second debtor letter preview -router.get('/letter-debtor-nd/:companyId/:clientId/preview', requestToken, function(request, response) { - template.get('letter-debtor-nd', { - clientId: request.params.clientId, - companyId: request.params.companyId, - token: request.user.token, - isPreview: true - }, (error, result) => { - if (error) - return response.status(400).json({message: error.message}); - - response.send(result.body); - }); -}); - -// Payment method changes -router.get('/payment-update/:clientId', requestToken, function(request, response) { - mail.sendWithTemplate('payment-update', {clientId: request.params.clientId}, error => { - if (error) - return response.status(400).json({message: error.message}); - - return response.json(); - }); -}); - -// Send notification to alias creditInsurance on client deactivate -router.get('/client-deactivate/:clientId', requestToken, function(request, response) { - var params = { - alias: 'creditInsurance', - code: 'clientDeactivate', - bodyParams: { - clientId: request.params.clientId - } - }; - - mail.sendWithTemplate('notification-alias', params, error => { - if (error) - response.status(400).json({message: error.message}); - - return response.json(); - }); -}); - -module.exports = router; - - -// Single user notification -/* router.post('/:recipient/noticeUserSend', function(request, response) { - var params = { - recipient: request.params.recipient, - sender: request.body.sender, - category: request.body.category, - message: request.body.message - }; - - if (params.sender == params.recipient) - return; - - let query = `SELECT COUNT(*) isEnabled - FROM noticeSubscription s - JOIN noticeCategory c ON c.id = s.noticeCategoryFk AND c.isEnabled - WHERE c.keyName = ? AND s.userFk = ?`; - - database.pool.query(query, [params.category, params.recipient, params.sender], (error, result) => { - mail.sendWithTemplate('notification-notice', params, result => { - return response.json(result); - }); - }); -}); */ - -// Send notification to all user subscribed to category -/* router.post('/:category/noticeCategorySend', function(request, response) { - var params = { - sender: request.body.sender, - category: request.params.category, - message: request.body.message - }; - - let query = `SELECT s.userFk id FROM noticeSubscription s JOIN noticeCategory - c ON c.id = s.noticeCategoryFk AND c.isEnabled WHERE c.keyName = ? AND s.userFk != ?`; - - database.pool.query(query, [params.category, params.sender], (error, result) => { - result.forEach(function(user) { - params.recipient = user.id; - - mail.sendWithTemplate('notification-notice', params, result => { - return response.json(result); - }); - }, this); - }); -}); */ - -// Send system notification -/* router.post('/:recipient/noticeSystemSend', function(request, response) { - var params = { - recipient: request.params.recipient, - sender: settings.smtp().auth.id, - category: request.body.category, - message: request.body.message - }; - - mail.sendWithTemplate('notification-notice', params, result => { - return response.json(result); - }); -}); */ \ No newline at end of file diff --git a/services/mailer/application/router.js b/services/mailer/application/router.js deleted file mode 100644 index 161271820..000000000 --- a/services/mailer/application/router.js +++ /dev/null @@ -1,30 +0,0 @@ -var express = require('express'); -var router = new express.Router(); -var fs = require('fs'); -var path = require('path'); - -// Mailer default page -router.get('/', function(request, response) { - response.json({}); -}); - -// Notifications -router.use('/notification', require('./route/notification.js')); - -// Serve static images -router.use('/static/:template/:image', function(request, response) { - let imagePath = path.join(__dirname, '/template/', request.params.template, '/image/', request.params.image); - - fs.stat(imagePath, function(error) { - if (error) - return response.json({message: 'Image not found'}); - - let readStream = fs.createReadStream(imagePath); - - readStream.on('open', function() { - readStream.pipe(response); - }); - }); -}); - -module.exports = router; diff --git a/services/mailer/application/template.js b/services/mailer/application/template.js deleted file mode 100644 index 1e9c92fde..000000000 --- a/services/mailer/application/template.js +++ /dev/null @@ -1,234 +0,0 @@ -var fs = require('fs'); -var mustache = require('mustache'); -var locale = require('./locale.js'); -var inlineCss = require('inline-css'); -var path = require('path'); - -module.exports = { -/** - * Get template. - * @param {String} template - Template name - * @param {Object} countryCode - Language code - * @param {Object} params - Params - * @param {Object} cb - Callback - */ - get: function(template, params, cb) { - var templatePath = path.join(__dirname, 'template', `${template}`, `index.html`); - var classPath = path.join(__dirname, 'template', `${template}`, `${template}.js`); - var stylePath = path.join(__dirname, 'template', `${template}`, 'style.css'); - - fs.stat(templatePath, (error, stat) => { - if (error) - return cb(new Error('Template ' + template + ' not found')); - - let TemplateClass = require(classPath); - let instance = new TemplateClass(); - - let getRenderedStyles = (error, body) => { - if (error) - return cb(error); - - this.renderStyles(stylePath, body, (error, body) => { - if (error) - return cb(error); - - // Check if has a subject param - params.subject = params.subject || instance.subject; - - if (params.subject == undefined) { - // Try to find a subject from Html source - let title = body.match(new RegExp('(.*?)', 'i')); - - if (title) - params.subject = title[1]; - } - - this.getAttachments(template, body, params.isPreview, (error, result) => { - if (error) - return cb(error); - - cb(null, {recipient: instance.recipient, subject: params.subject, body: result.body, attachments: result.attachments}); - }); - }); - }; - - let getDataCb = () => { - this.render(templatePath, instance, (error, result) => getRenderedStyles(error, result)); - }; - - instance.getData(params, (error, result) => { - if (error) - return cb(error); - - locale.load(template, instance.countryCode, (error, result) => { - if (error) - return cb(error); - - instance._ = result.locale; - instance.isPreview = params.isPreview; - - getDataCb(null, result); - }); - }); - }); - }, - -/** - * Render template - * @param {String} path - Template path - * @param {Object} data - Params - * @param {Object} cb - Callback - */ - render: function(path, data, cb) { - fs.readFile(path, 'utf8', (error, body) => { - // Find matching sub-templates - let regexp = new RegExp(/\{\{\$\.(.*?)\}\}/, 'ig'); - let subTpl = body.match(regexp); - - if (!subTpl) { - mustache.parse(body); - return cb(null, mustache.render(body, data)); - } - - let parentBody = body; - this.renderSub(parentBody, subTpl, data, regexp, (error, body) => { - if (error) - return cb(error); - - mustache.parse(body); - cb(null, mustache.render(body, data)); - }); - }); - }, - -/** - * Render sub-template - * @param {String} body - Raw body - * @param {Object} subTpl - Sub-template name - * @param {Object} data - Params - * @param {Object} regexp - Regexp - * @param {Object} cb - Callback - */ - renderSub: function(body, subTpl, data, regexp, cb) { - let index = 1; - - subTpl.forEach(keyName => { - subTplName = keyName.replace(regexp, '$1'); - - this.get(subTplName, data, (error, result) => { - if (error) - return cb(error); - - let subTplBody = result.body; - body = body.replace(keyName, subTplBody); - - if (index === subTpl.length) - cb(null, body); - - index++; - }); - - }); - }, - -/** - * Render template style. - * @param {String} path - Stylesheet path - * @param {String} body - Rendered html - * @param {Object} cb - Callback - */ - renderStyles: function(stylePath, html, cb) { - // Common components - let comPath = path.join(__dirname, '../', 'static', 'css', 'component.css'); - - fs.readFile(comPath, 'utf8', (error, comCss) => { - fs.stat(stylePath, error => { - if (error) - return cb(new Error('Template stylesheet not found')); - - fs.readFile(stylePath, 'utf8', (error, css) => { - let style = ''; - let body = style + html; - let options = {url: ' '}; - - inlineCss(body, options) - .then(function(body) { - cb(null, body); - }); - }); - }); - }); - }, - -/** - * Get template attachments - * @param {String} template - Template name - * @param {String} body - template body - * @param {Object} cb - Callback - */ - getAttachments: function(template, body, isPreview, cb) { - let attachments = []; - let tplAttachments = body.match(new RegExp('src="cid:(.*?)"', 'ig')); - - if (!tplAttachments) - tplAttachments = {}; - - // Template default attachments - for (var i = 0; i < tplAttachments.length; i++) { - let src = tplAttachments[i].replace('src="cid:', '').replace('"', '').split('/'); - let attachmentTpl = src[0]; - let attachment = src[1]; - - if (isPreview) { - let attachmentPath = `/mailer/static/${attachmentTpl}/${attachment}`; - body = body.replace(tplAttachments[i], `src="${attachmentPath}"`); - } else { - let attachmentPath = path.join(__dirname, 'template', `${attachmentTpl}`, 'image', attachment); - let attachmentName = attachmentTpl + '/' + attachment; - attachments.push({filename: attachmentName, path: attachmentPath, cid: attachmentName}); - } - } - - if (isPreview) - return cb(null, {body: body, attachments: attachments}); - - // Template attachment files - let attachmentsPath = path.join(__dirname, 'template', `${template}`, 'attachment.json'); - - fs.stat(attachmentsPath, (error, stats) => { - if (error) - return cb(null, {body: body, attachments: attachments}); - - let attachObj = require(attachmentsPath); - - for (var i = 0; i < attachObj.length; i++) { - let filename = attachObj[i]; - let attachmentPath = path.join(__dirname, 'template', `${template}`, 'attachment', filename); - - attachments.push({filename: filename, path: attachmentPath, cid: filename}); - } - - this.checkAttachments(attachments, error => { - if (error) - return cb(error); - cb(null, {body: body, attachments: attachments}); - }); - }); - }, - -/** -* Check all template attachments -* @param {Object} attachments - Attachments object -* @param {Object} cb - Callback -*/ - checkAttachments: function(attachments, cb) { - for (var i = 0; i < attachments.length; i++) { - var attachment = attachments[i]; - fs.stat(attachment.path, error => { - if (error) - return cb(new Error(`Could not load attachment file ${attachment.path}`)); - }); - } - cb(); - } -}; \ No newline at end of file diff --git a/services/mailer/application/template/client-welcome/attachment.json b/services/mailer/application/template/client-welcome/attachment.json deleted file mode 100644 index 0637a088a..000000000 --- a/services/mailer/application/template/client-welcome/attachment.json +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/services/mailer/application/template/client-welcome/client-welcome.js b/services/mailer/application/template/client-welcome/client-welcome.js deleted file mode 100644 index 7cf435d0e..000000000 --- a/services/mailer/application/template/client-welcome/client-welcome.js +++ /dev/null @@ -1,46 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); -var format = require(path.join(__dirname, '../../util/format.js')); - -module.exports = class ClientWelcome { - getData(params, cb) { - let query = `SELECT - c.id clientId, - CONCAT(w.name, ' ', w.firstName) name, - w.phone AS phone, - CONCAT(wu.name, '@verdnatura.es') AS email, - u.name AS userName, - LOWER(ct.code) countryCode, - c.email recipient - FROM client c - JOIN account.user u ON u.id = c.id - LEFT JOIN worker w ON w.id = c.salesPersonFk - LEFT JOIN account.user wu ON wu.id = w.userFk - JOIN country ct ON ct.id = c.countryFk - WHERE c.id = ?`; - - database.pool.query(query, [params.clientId], (error, result) => { - if (error || result.length == 0) - return cb(new Error('No template data found')); - - Object.assign(this, result[0]); - cb(); - }); - } - - get salesPersonName() { - if (this.name) - return `
    ${this._.salesPersonNameText}: ${this.name}
    `; - } - - get salesPersonPhone() { - if (this.phone) - return `
    ${this._.salesPersonPhoneText}: ${format.phone(this.phone)}
    `; - } - - get salesPersonEmail() { - if (this.email) - return `
    ${this._.salesPersonEmailText}: ` + - `${this.email}
    `; - } -}; diff --git a/services/mailer/application/template/client-welcome/index.html b/services/mailer/application/template/client-welcome/index.html deleted file mode 100644 index 6d25bcd7e..000000000 --- a/services/mailer/application/template/client-welcome/index.html +++ /dev/null @@ -1,67 +0,0 @@ - - - - {{_.subject}} - - - -
    -
    - - {{$.header}} - - - -
    -

    {{_.title}}

    -
    - - - -
    -

    {{_.dear}}

    -

    {{{_.bodyDescription}}}

    -

    -

    {{_.clientNumber}} {{clientId}}
    -
    {{_.user}} {{userName}}
    -
    {{_.password}} ******** {{{_.passwordResetText}}}
    -

    - -

    {{_.sectionHowToBuyTitle}}

    -

    {{_.sectionHowToBuyDescription}}

    -
      -
    1. {{_.sectionHowToBuyRequeriment1}}
    2. -
    3. {{_.sectionHowToBuyRequeriment2}}
    4. -
    5. {{_.sectionHowToBuyRequeriment3}}
    6. -
    -

    {{_.sectionHowToBuyStock}}

    -

    {{_.sectionHowToBuyDelivery}}

    - -

    {{_.sectionHowToPayTitle}}

    -

    {{_.sectionHowToPayDescription}}

    -
      -
    • {{{_.sectionHowToPayOption1}}}
    • -
    • {{{_.sectionHowToPayOption2}}}
    • -
    - -

    {{_.sectionToConsiderTitle}}

    -

    {{_.sectionToConsiderDescription}}

    - -

    {{_.sectionClaimsPolicyTitle}}

    -

    {{_.sectionClaimsPolicyDescription}}

    -

    {{{_.doubtsText}}}

    -

    - {{{salesPersonName}}} - {{{salesPersonPhone}}} - {{{salesPersonEmail}}} -

    -
    - - - - {{$.footer}} - -
    -
    - - \ No newline at end of file diff --git a/services/mailer/application/template/client-welcome/locale/es.json b/services/mailer/application/template/client-welcome/locale/es.json deleted file mode 100644 index 95a903e5c..000000000 --- a/services/mailer/application/template/client-welcome/locale/es.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "subject": "¡Le damos la bienvenida!", - "title": "¡LE DAMOS LA BIENVENIDA!", - "dear": "Estimado cliente,", - "bodyDescription": "Sus datos para poder comprar en la web de verdnatura (
    https://www.verdnatura.es) o en nuestras aplicaciones para iOS y Android (Ver tutorial de uso), son:", - "clientNumber": "Identificador de cliente:", - "user": "Usuario:", - "password": "Contraseña:", - "passwordResetText": "(Haga clic en \"¿Has olvidado tu contraseña?\")", - "sectionHowToBuyTitle": "Cómo hacer un pedido", - "sectionHowToBuyDescription": "Para realizar un pedido en nuestra web, debe configurarlo indicando:", - "sectionHowToBuyRequeriment1": "Si quiere recibir el pedido (por agencia o por nuestro propio reparto) o si lo prefiere recoger en alguno de nuestros almacenes.", - "sectionHowToBuyRequeriment2": "La fecha en la que quiera recibir el pedido (se preparará el día anterior).", - "sectionHowToBuyRequeriment3": "La dirección de entrega o el almacén donde quiera recoger el pedido.", - "sectionHowToBuyStock": "En nuestra web y aplicaciones puedes visualizar el stock disponible de flor cortada, verdes, plantas, complementos y artificial. Tenga en cuenta que dicho stock puede variar en función de la fecha seleccionada al configurar el pedido. Es importante CONFIRMAR los pedidos para que la mercancía quede reservada.", - "sectionHowToBuyDelivery": "El reparto se realiza de lunes a sábado según la zona en la que se encuentre. Por regla general, los pedidos que se entregan por agencia, deben estar confirmados y pagados antes de las 17h del día en que se preparan (el día anterior a recibirlos), aunque esto puede variar si el pedido se envía a través de nuestro reparto y según la zona.", - "sectionHowToPayTitle": "Cómo pagar", - "sectionHowToPayDescription": "Las formas de pago admitidas en Verdnatura son:", - "sectionHowToPayOption1": "Con tarjeta a través de nuestra plataforma web (al confirmar el pedido).", - "sectionHowToPayOption2": "Mediante giro bancario mensual, modalidad que hay que solicitar y tramitar.", - "sectionToConsiderTitle": "Cosas a tener en cuenta", - "sectionToConsiderDescription": "Verdnatura vende EXCLUSIVAMENTE a profesionales, por lo que debe remitirnos el Modelo 036 ó 037, para comprobar que está dado/a de alta en el epígrafe correspondiente al comercio de flores.", - "sectionClaimsPolicyTitle": "POLÍTICA DE RECLAMACIONES", - "sectionClaimsPolicyDescription": "Verdnatura aceptará las reclamaciones que se realicen dentro de los dos días naturales siguientes a la recepción del pedido (incluyendo el mismo día de la recepción). Pasado este plazo no se aceptará ninguna reclamación.", - "doubtsText": "Cualquier duda que le surja, no dude en consultarla, ¡estamos para atenderle!", - "salesPersonNameText": "Soy tu comercial y mi nombre es", - "salesPersonPhoneText": "Teléfono y whatsapp", - "salesPersonEmailText": "Dirección de e-mail" -} \ No newline at end of file diff --git a/services/mailer/application/template/default/image/download.svg b/services/mailer/application/template/default/image/download.svg deleted file mode 100644 index b05bc05c8..000000000 --- a/services/mailer/application/template/default/image/download.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/services/mailer/application/template/default/image/preview.svg b/services/mailer/application/template/default/image/preview.svg deleted file mode 100644 index 09a2a6bca..000000000 --- a/services/mailer/application/template/default/image/preview.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/services/mailer/application/template/footer/footer.js b/services/mailer/application/template/footer/footer.js deleted file mode 100644 index 555e70b10..000000000 --- a/services/mailer/application/template/footer/footer.js +++ /dev/null @@ -1,21 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); -var format = require(path.join(__dirname, '../../util/format.js')); - -module.exports = class Footer { - getData(params, cb) { - let query = `SELECT - socialName, - LOWER(ct.code) countryCode - FROM client c - JOIN country ct ON ct.id = c.countryFk - WHERE c.id = ?`; - database.pool.query(query, [params.clientId], (error, result) => { - if (error || result.length == 0) - return cb(new Error('No template data found')); - - Object.assign(this, result[0]); - cb(); - }); - } -}; diff --git a/services/mailer/application/template/footer/index.html b/services/mailer/application/template/footer/index.html deleted file mode 100644 index 484f5c2b8..000000000 --- a/services/mailer/application/template/footer/index.html +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - -
    -

    {{_.fiscalAddress}}

    -

    {{_.privacy}}

    -

    {{_.privacyLaw}}

    -
    - \ No newline at end of file diff --git a/services/mailer/application/template/footer/locale/es.json b/services/mailer/application/template/footer/locale/es.json deleted file mode 100644 index 1ad532d34..000000000 --- a/services/mailer/application/template/footer/locale/es.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "actionButton": "Visita nuestra Web", - "infoButton": "Ayúdanos a mejorar", - "fiscalAddress": "VERDNATURA LEVANTE SL, B97367486 Avda. Espioca, 100, 46460 Silla · www.verdnatura.es · clientes@verdnatura.es", - "privacy": "- AVISO - Este mensaje es privado y confidencial, y debe ser utilizado exclusivamente por la persona destinataria del mismo. Si usted ha recibido este mensaje por error, le rogamos lo comunique al remitente y borre dicho mensaje y cualquier documento adjunto que pudiera contener. Verdnatura Levante SL no renuncia a la confidencialidad ni a ningún privilegio por causa de transmisión errónea o mal funcionamiento. Igualmente no se hace responsable de los cambios, alteraciones, errores u omisiones que pudieran hacerse al mensaje una vez enviado.", - "privacyLaw": "En cumplimiento de lo dispuesto en la Ley Orgánica 15/1999, de Protección de Datos de Carácter Personal, le comunicamos que los datos personales que facilite se incluirán en ficheros automatizados de VERDNATURA LEVANTE S.L., pudiendo en todo momento ejercitar los derechos de acceso, rectificación, cancelación y oposición, comunicándolo por escrito al domicilio social de la entidad. La finalidad del fichero es la gestión administrativa, contabilidad, y facturación." -} \ No newline at end of file diff --git a/services/mailer/application/template/footer/style.css b/services/mailer/application/template/footer/style.css deleted file mode 100644 index f35364e8c..000000000 --- a/services/mailer/application/template/footer/style.css +++ /dev/null @@ -1,54 +0,0 @@ -.buttons { - background-color: #FFF; - text-align: center; - width: 100% -} - -.buttons a { - text-decoration: none; - font-size: 18px; - color: #fff -} - -.buttons .btn { - background-color: #333; - min-width: 300px; - height: 72px; - display: inline-block; - text-align: center -} - -.buttons .btn .text { - display: inline-block; - padding-top: 22px -} - -.buttons .btn .icon { - background-color: #95d831; - text-align: center; - padding-top: 22px; - float: right; - height: 50px; - width: 70px -} - -.footer { - background-color: #555; - text-align: center; - padding: 20px 0 -} - -.footer a { - text-decoration: none; - margin-right: 5px -} - -.footer a img { - margin: 0 -} - -.privacy { - padding: 20px 0; - font-size: 10px; - font-weight: 100 -} \ No newline at end of file diff --git a/services/mailer/application/template/header/header.js b/services/mailer/application/template/header/header.js deleted file mode 100644 index a6d1d6194..000000000 --- a/services/mailer/application/template/header/header.js +++ /dev/null @@ -1,21 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); -var format = require(path.join(__dirname, '../../util/format.js')); - -module.exports = class Header { - getData(params, cb) { - let query = `SELECT - c.name AS clientName, - LOWER(ct.code) countryCode - FROM client c - JOIN country ct ON ct.id = c.countryFk - WHERE c.id = ?`; - database.pool.query(query, [params.clientId], (error, result) => { - if (error || result.length == 0) - return cb(new Error('No template data found')); - - Object.assign(this, result[0]); - cb(); - }); - } -}; diff --git a/services/mailer/application/template/header/image/logo.png b/services/mailer/application/template/header/image/logo.png deleted file mode 100644 index 3c063ae44..000000000 Binary files a/services/mailer/application/template/header/image/logo.png and /dev/null differ diff --git a/services/mailer/application/template/header/index.html b/services/mailer/application/template/header/index.html deleted file mode 100644 index 6e4fcf8a4..000000000 --- a/services/mailer/application/template/header/index.html +++ /dev/null @@ -1,3 +0,0 @@ -
    - VerdNatura -
    diff --git a/services/mailer/application/template/header/locale/es.json b/services/mailer/application/template/header/locale/es.json deleted file mode 100644 index 7a73a41bf..000000000 --- a/services/mailer/application/template/header/locale/es.json +++ /dev/null @@ -1,2 +0,0 @@ -{ -} \ No newline at end of file diff --git a/services/mailer/application/template/header/style.css b/services/mailer/application/template/header/style.css deleted file mode 100644 index 4ea8ee36d..000000000 --- a/services/mailer/application/template/header/style.css +++ /dev/null @@ -1,3 +0,0 @@ -.banner img { - width: 100% -} \ No newline at end of file diff --git a/services/mailer/application/template/letter-debtor-nd/attachment.json b/services/mailer/application/template/letter-debtor-nd/attachment.json deleted file mode 100644 index 0637a088a..000000000 --- a/services/mailer/application/template/letter-debtor-nd/attachment.json +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/services/mailer/application/template/letter-debtor-nd/index.html b/services/mailer/application/template/letter-debtor-nd/index.html deleted file mode 100644 index aa4379519..000000000 --- a/services/mailer/application/template/letter-debtor-nd/index.html +++ /dev/null @@ -1,87 +0,0 @@ - - - - {{_.subject}} - - - -
    -
    - - {{$.header}} - - - -
    -

    {{_.title}}

    -
    - - - -
    -

    {{_.dear}}

    - -

    {{_.bodyDescription}}

    -

    {{_.termLimits}}

    -

    - {{_.payMethod}} - -

      -
    1. {{_.payMethodOption1}}
    2. -
    3. {{_.payMethodOption2}}
    4. -
    -

    -

    - {{_.legalActions}} -

      -
    1. {{_.legalActionsOption1}}
    2. -
    3. {{_.legalActionsOption2}}
    4. -
    5. {{_.legalActionsOption3}}
    6. -
    -

    - -

    {{_.contact}}

    - -

    {{_.waitingForNews}}

    -

    {{_.conclusion}}

    - -

    -

    -
    {{bankName}}
    -
    {{iban}}
    -
    -
    {{_.accountTransferData}}
    -
    -
    -

    - - {{#isPreview}} - -
    -
    - Ver adjunto -
    - Ver adjunto -
    -
    - - -
    -
    - Descargar adjunto -
    - Descargar PDF -
    -
    - {{/isPreview}} -
    - - - - - {{$.footer}} - -
    -
    - - \ No newline at end of file diff --git a/services/mailer/application/template/letter-debtor-nd/letter-debtor-nd.js b/services/mailer/application/template/letter-debtor-nd/letter-debtor-nd.js deleted file mode 100644 index be0f996e1..000000000 --- a/services/mailer/application/template/letter-debtor-nd/letter-debtor-nd.js +++ /dev/null @@ -1,39 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); -var format = require(path.join(__dirname, '../../util/format.js')); - -module.exports = class LetterDebtorNd { - getData(params, cb) { - let query = `SELECT - sa.iban, - be.name AS bankName, - LOWER(ct.code) countryCode, - c.email recipient - FROM client c - JOIN company AS cny - JOIN supplierAccount AS sa ON sa.id = cny.supplierAccountFk - JOIN bankEntity be ON be.id = sa.bankEntityFk - JOIN country ct ON ct.id = c.countryFk - WHERE c.id = ? AND cny.id = ?`; - - this.clientId = params.clientId; - this.companyId = params.companyId; - this.token = params.token; - - database.pool.query(query, [params.clientId, params.companyId], (error, result) => { - if (error || result.length == 0) - return cb(new Error('No template data found')); - - Object.assign(this, result[0]); - - cb(); - }); - } - - get previewAttachments() { - if (this.isPreview) - return `` + - '
    Descargar adjunto
    ' + - 'extracto.pdf
    '; - } -}; diff --git a/services/mailer/application/template/letter-debtor-nd/locale/es.json b/services/mailer/application/template/letter-debtor-nd/locale/es.json deleted file mode 100644 index 1f8790eba..000000000 --- a/services/mailer/application/template/letter-debtor-nd/locale/es.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "subject": "Reiteración de aviso por saldo deudor", - "title": "AVISO REITERADO", - "dear": "Estimado cliente,", - "bodyDescription": "Nos dirigimos a Vd. nuevamente para informarle que sigue pendiente su deuda con nuestra empresa, tal y como puede comprobar en el extracto adjunto.", - "termLimits": "Dado que los plazos de pago acordados están ampliamente superados, no procede mayor dilación en la liquidación del importe adeudado.", - "payMethod": "Para ello dispone de las siguientes formas de pago:", - "payMethodOption1": "Pago online desde nuestra web", - "payMethodOption2": "Ingreso o transferencia al número de cuenta que detallamos al pie de esta carta, indicando el número de cliente.", - "legalActions": "En caso de no ser atendido este apremio de pago, nos veremos obligados a iniciar las acciones legales que procedan, entre las que están:", - "legalActionsOption1": "Inclusión en ficheros negativos sobre solvencia patrimonial y crédito.", - "legalActionsOption2": "Reclamación judicial", - "legalActionsOption3": "Cesión de deuda a una empresa de gestión de cobro", - "contact": "Para consultas, puede ponerse en contacto con nosotros en el 96 324 21 00.", - "waitingForNews": "En espera de sus noticias", - "conclusion": "Gracias por su atención.", - "accountTransferData": "Datos para transferencia bancaria" -} \ No newline at end of file diff --git a/services/mailer/application/template/letter-debtor-nd/style.css b/services/mailer/application/template/letter-debtor-nd/style.css deleted file mode 100644 index e69de29bb..000000000 diff --git a/services/mailer/application/template/letter-debtor-st/attachment.json b/services/mailer/application/template/letter-debtor-st/attachment.json deleted file mode 100644 index 0637a088a..000000000 --- a/services/mailer/application/template/letter-debtor-st/attachment.json +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/services/mailer/application/template/letter-debtor-st/index.html b/services/mailer/application/template/letter-debtor-st/index.html deleted file mode 100644 index a3b07e677..000000000 --- a/services/mailer/application/template/letter-debtor-st/index.html +++ /dev/null @@ -1,69 +0,0 @@ - - - - {{_.subject}} - - - -
    -
    - - {{$.header}} - - - -
    -

    {{_.title}}

    -
    - - - -
    -

    {{_.dear}}

    - -

    {{_.bodyDescription}}

    -

    {{_.viewExtract}}

    -

    {{_.validData}}

    -

    {{_.payMethod}}

    -

    {{_.conclusion}}

    - -

    -

    -
    {{bankName}}
    -
    {{iban}}
    -
    -
    {{_.accountTransferData}}
    -
    -
    -

    - - {{#isPreview}} - -
    -
    - Ver adjunto -
    - Ver adjunto -
    -
    - - -
    -
    - Descargar adjunto -
    - Descargar PDF -
    -
    - {{/isPreview}} -
    - - - - - {{$.footer}} - -
    -
    - - \ No newline at end of file diff --git a/services/mailer/application/template/letter-debtor-st/letter-debtor-st.js b/services/mailer/application/template/letter-debtor-st/letter-debtor-st.js deleted file mode 100644 index 43ccb7a25..000000000 --- a/services/mailer/application/template/letter-debtor-st/letter-debtor-st.js +++ /dev/null @@ -1,39 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); -var format = require(path.join(__dirname, '../../util/format.js')); - -module.exports = class LetterDebtorSt { - getData(params, cb) { - let query = `SELECT - sa.iban, - be.name AS bankName, - LOWER(ct.code) countryCode, - c.email recipient - FROM client c - JOIN company AS cny - JOIN supplierAccount AS sa ON sa.id = cny.supplierAccountFk - JOIN bankEntity be ON be.id = sa.bankEntityFk - JOIN country ct ON ct.id = c.countryFk - WHERE c.id = ? AND cny.id = ?`; - - this.clientId = params.clientId; - this.companyId = params.companyId; - this.token = params.token; - - database.pool.query(query, [params.clientId, params.companyId], (error, result) => { - if (error || result.length == 0) - return cb(new Error('No template data found')); - - Object.assign(this, result[0]); - - cb(); - }); - } - - get previewAttachments() { - if (this.isPreview) - return `` + - '
    Descargar adjunto
    ' + - 'extracto.pdf
    '; - } -}; diff --git a/services/mailer/application/template/letter-debtor-st/locale/es.json b/services/mailer/application/template/letter-debtor-st/locale/es.json deleted file mode 100644 index 558b18753..000000000 --- a/services/mailer/application/template/letter-debtor-st/locale/es.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "subject": "Aviso inicial por saldo deudor", - "title": "AVISO INICIAL", - "dear": "Estimado cliente,", - "bodyDescription": "Por el presente escrito le comunicamos que, según nuestros datos contables, su cuenta tiene un saldo pendiente de liquidar.", - "viewExtract": "Le solicitamos compruebe que el extracto adjunto corresponde con los datos de que Vd. dispone. Nuestro departamento de administración le aclarará gustosamente cualquier duda que pueda tener, e igualmente le facilitará cualquier documento que solicite.", - "validData": "Si al comprobar los datos aportados resultaran correctos, le rogamos proceda a regularizar su situación.", - "payMethod": "Si no desea desplazarse personalmente hasta nuestras oficinas, puede realizar el pago mediante transferencia bancaria a la cuenta que figura al pie del comunicado, indicando su número de cliente, o bien puede realizar el pago online desde nuestra página web.", - "conclusion": "De antemano le agradecemos su amable colaboración.", - "accountTransferData": "Datos para transferencia bancaria" -} \ No newline at end of file diff --git a/services/mailer/application/template/letter-debtor-st/style.css b/services/mailer/application/template/letter-debtor-st/style.css deleted file mode 100644 index e69de29bb..000000000 diff --git a/services/mailer/application/template/notification-alias/attachment.json b/services/mailer/application/template/notification-alias/attachment.json deleted file mode 100644 index 0637a088a..000000000 --- a/services/mailer/application/template/notification-alias/attachment.json +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/services/mailer/application/template/notification-alias/index.html b/services/mailer/application/template/notification-alias/index.html deleted file mode 100644 index 6e79e1278..000000000 --- a/services/mailer/application/template/notification-alias/index.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - {{_.subject}} - - - -
    -
    - - {{$.header}} - - - -
    -

    {{_.title}}

    -
    - - - -
    -

    {{_.hello}} #{{alias}}

    -

    {{message}}

    -
    - - - - {{$.footer}} - -
    -
    - - \ No newline at end of file diff --git a/services/mailer/application/template/notification-alias/locale/es.json b/services/mailer/application/template/notification-alias/locale/es.json deleted file mode 100644 index 6e39b7f63..000000000 --- a/services/mailer/application/template/notification-alias/locale/es.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "subject": "Has recibido una nueva notificación", - "title": "Nueva notificación", - "hello": "Hola,", - "notificationCode": { - "clientDeactivate": { - "subject": "Gestionar baja de contrato", - "message": "El cliente con id %clientId% está clasificado, por favor, gestione la baja del contrato primero." - } - } -} \ No newline at end of file diff --git a/services/mailer/application/template/notification-alias/notification-alias.js b/services/mailer/application/template/notification-alias/notification-alias.js deleted file mode 100644 index 937e1bf8c..000000000 --- a/services/mailer/application/template/notification-alias/notification-alias.js +++ /dev/null @@ -1,29 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); -var locale = require(path.join(__dirname, '../../locale.js')); - -module.exports = class NotificationAlias { - getData(params, cb) { - this.params = params; - - let query = `SELECT alias, CONCAT(alias, '@verdnatura.es') AS recipient - FROM account.mailAlias - WHERE alias = ?`; - - database.pool.query(query, [params.alias], (error, result) => { - if (error || result.length == 0) - return cb(new Error('No template data found')); - - Object.assign(this, result[0]); - cb(); - }); - } - - get subject() { - return this._.notificationCode[this.params.code].subject; - } - - get message() { - return locale.parseText(this._.notificationCode[this.params.code].message, this.params.bodyParams); - } -}; diff --git a/services/mailer/application/template/notification-alias/style.css b/services/mailer/application/template/notification-alias/style.css deleted file mode 100644 index e69de29bb..000000000 diff --git a/services/mailer/application/template/notification-notice/attachment.json b/services/mailer/application/template/notification-notice/attachment.json deleted file mode 100644 index 0637a088a..000000000 --- a/services/mailer/application/template/notification-notice/attachment.json +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/services/mailer/application/template/notification-notice/index.html b/services/mailer/application/template/notification-notice/index.html deleted file mode 100644 index c1e206078..000000000 --- a/services/mailer/application/template/notification-notice/index.html +++ /dev/null @@ -1,76 +0,0 @@ - - - - {{_.subject}} - - - -
    - -
    - VerdNatura -
    - - - -
    -

    {{_.title}}

    -
    - - - -
    -

    Hola, {{recipientName}}

    -

    {{_.bodyDescription}} {{senderName}}:

    -

    "{{message}}"

    -

    {{_.noticeDescription}} '{{categoryName}}'. {{_.unsubscribe}}

    -
    - - - - - - - - - - - -
    -

    {{_.fiscalAddress}}

    -

    {{_.privacy}}

    -

    {{_.privacyLaw}}

    -
    - -
    - - \ No newline at end of file diff --git a/services/mailer/application/template/notification-notice/locale/es.json b/services/mailer/application/template/notification-notice/locale/es.json deleted file mode 100644 index 21cab5f37..000000000 --- a/services/mailer/application/template/notification-notice/locale/es.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "subject": "Has recibido una nueva notificación", - "title": "Nueva notificación", - "hello": "Hola", - "bodyDescription": "Has recibido la siguiente notificación de", - "noticeDescription": "Recibes esta notificación porque estás suscrito a", - "unsubscribe": "Puedes dejar de recibir estas notificaciones desde 'Notificaciones > Configuración' en cualquier aplicación de VerdNatura.", - "actionButton": "Visita nuestra Web", - "infoButton": "Ayúdanos a mejorar", - "fiscalAddress": "VERDNATURA LEVANTE SL, B97367486 Avda. Espioca, 100, 46460 Silla _ www.verdnatura.es _ clientes@verdnatura.es", - "privacy": "- AVISO - Este mensaje es privado y confidencial, y debe ser utilizado exclusivamente por la persona destinataria del mismo. Si usted ha recibido este mensaje por error, le rogamos lo comunique al remitente y borre dicho mensaje y cualquier documento adjunto que pudiera contener. Verdnatura Levante SL no renuncia a la confidencialidad ni a ningún privilegio por causa de transmisión errónea o mal funcionamiento. Igualmente no se hace responsable de los cambios, alteraciones, errores u omisiones que pudieran hacerse al mensaje una vez enviado.", - "privacyLaw": "En cumplimiento de lo dispuesto en la Ley Orgánica 15/1999, de Protección de Datos de Carácter Personal, le comunicamos que los datos personales que facilite se incluirán en ficheros automatizados de VERDNATURA LEVANTE S.L., pudiendo en todo momento ejercitar los derechos de acceso, rectificación, cancelación y oposición, comunicándolo por escrito al domicilio social de la entidad. La finalidad del fichero es la gestión administrativa, contabilidad, y facturación." -} \ No newline at end of file diff --git a/services/mailer/application/template/notification-notice/notification-notice.js b/services/mailer/application/template/notification-notice/notification-notice.js deleted file mode 100644 index 493261913..000000000 --- a/services/mailer/application/template/notification-notice/notification-notice.js +++ /dev/null @@ -1,28 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); - -module.exports = class NotificationNotice { - getData(params, cb) { - let query = `SELECT - LOWER(ct.code) countryCode, - c.email recipient, - nc.name categoryName, - recipient.name recipientName, - sender.name senderName - FROM client c - JOIN account.user recipient ON recipient.id = c.id - JOIN country ct ON ct.id = c.countryFk - JOIN noticeCategory nc ON nc.keyName = ? - JOIN account.user sender ON sender.id = ? - WHERE c.id = ?`; - database.pool.query(query, [params.category, params.sender, params.recipient], (error, result) => { - if (error || result.length == 0) - return cb({status: 'REJECT', data: {message: 'No data found', error: error}}); - - Object.assign(this, result[0]); - this.message = params.message; - - cb({status: 'ACCEPT', data: {}}); - }); - } -}; diff --git a/services/mailer/application/template/payment-update/attachment.json b/services/mailer/application/template/payment-update/attachment.json deleted file mode 100644 index 0637a088a..000000000 --- a/services/mailer/application/template/payment-update/attachment.json +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/services/mailer/application/template/payment-update/index.html b/services/mailer/application/template/payment-update/index.html deleted file mode 100644 index 78d6612c4..000000000 --- a/services/mailer/application/template/payment-update/index.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - {{_.subject}} - - - -
    -
    - - {{$.header}} - - - -
    -

    {{_.title}}

    -
    - - - -
    -

    {{_.dear}}

    -

    {{_.bodyDescription}}

    -

    -

    {{_.paymentMethod}} {{payMethodName}}
    - {{{paymentDay}}} -

    -

    {{paymentAdvice}}

    -

    {{_.notifyError}}

    -
    - - - - {{$.footer}} - -
    -
    - - \ No newline at end of file diff --git a/services/mailer/application/template/payment-update/locale/es.json b/services/mailer/application/template/payment-update/locale/es.json deleted file mode 100644 index 1216dcd99..000000000 --- a/services/mailer/application/template/payment-update/locale/es.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "subject": "Cambios en las condiciones de pago", - "title": "Cambio en las condiciones", - "dear": "Estimado cliente,", - "bodyDescription": "Le informamos que han cambiado las condiciones de pago de su cuenta. A continuación le indicamos las nuevas condiciones:", - "paymentMethod": "Método de pago:", - "paymentDay": "Día de pago:", - "everyMonth": "de cada mes", - "cardPaymentAdvice": "Su modo de pago actual implica que deberá abonar el importe de los pedidos realizados en el mismo día para que se puedan enviar.", - "accountPaymentAdviceBefore": "Su modo de pago actual implica que se le pasará un cargo a la cuenta", - "accountPaymentAdviceAfter": "por el importe pendiente, al vencimiento establecido en las condiciones.", - "notifyError": "En el caso de detectar algún error en los datos indicados o para cualquier aclaración, debe dirigirse a su comercial." -} \ No newline at end of file diff --git a/services/mailer/application/template/payment-update/payment-update.js b/services/mailer/application/template/payment-update/payment-update.js deleted file mode 100644 index 565fd8a74..000000000 --- a/services/mailer/application/template/payment-update/payment-update.js +++ /dev/null @@ -1,43 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); -var format = require(path.join(__dirname, '../../util/format.js')); - -module.exports = class PaymentUpdate { - getData(params, cb) { - let query = `SELECT - pm.id payMethodFk, - pm.name payMethodName, - c.dueDay, - c.iban, - LOWER(ct.code) countryCode, - c.email recipient - FROM client c - JOIN payMethod pm ON pm.id = c.payMethodFk - JOIN country ct ON ct.id = c.countryFk - WHERE c.id = ?`; - - this.clientId = params.clientId; - - database.pool.query(query, [params.clientId], (error, result) => { - if (error || result.length == 0) - return cb(new Error('No template data found')); - - Object.assign(this, result[0]); - cb(); - }); - } - - get paymentDay() { - if (this.payMethodFk != 5) - return `
    ${this._.paymentDay} ${this.dueDay} ${this._.everyMonth}
    `; - } - - get paymentAdvice() { - switch (this.payMethodFk) { - case 4: - return `${this._.accountPaymentAdviceBefore} ${format.partialAccountAddress(this.iban)} ${this._.accountPaymentAdviceAfter}`; - case 5: - return this._.cardPaymentAdvice; - } - } -}; diff --git a/services/mailer/application/template/payment-update/style.css b/services/mailer/application/template/payment-update/style.css deleted file mode 100644 index e69de29bb..000000000 diff --git a/services/mailer/application/template/printer-setup/attachment.json b/services/mailer/application/template/printer-setup/attachment.json deleted file mode 100644 index 7294783a8..000000000 --- a/services/mailer/application/template/printer-setup/attachment.json +++ /dev/null @@ -1 +0,0 @@ -["model.ezp"] \ No newline at end of file diff --git a/services/mailer/application/template/printer-setup/attachment/model.ezp b/services/mailer/application/template/printer-setup/attachment/model.ezp deleted file mode 100644 index 297df3d21..000000000 Binary files a/services/mailer/application/template/printer-setup/attachment/model.ezp and /dev/null differ diff --git a/services/mailer/application/template/printer-setup/index.html b/services/mailer/application/template/printer-setup/index.html deleted file mode 100644 index ee021281c..000000000 --- a/services/mailer/application/template/printer-setup/index.html +++ /dev/null @@ -1,68 +0,0 @@ - - - - {{_.subject}} - - - -
    -
    - - {{$.header}} - - - -
    -

    {{_.title}}

    -
    - - - -
    -

    {{_.dear}}

    -

    {{_.bodyDescription}}

    -

    {{{_.followGuide}}}

    -

    {{{_.downloadFrom}}}

    - -

    {{_.sectionQLabelTitle}}

    - -

    {{_.sectionQLabelDescription}}

    - -
      -
    1. {{_.sectionQLabelStep1}}
    2. -
    3. {{_.sectionQLabelStep2}}
    4. -
    5. {{_.sectionQLabelStep3}}
    6. -
    7. {{{_.sectionQLabelStep4}}}
    8. -
    9. {{_.sectionQLabelStep5}}
    10. -
    11. {{_.sectionQLabelStep6}}
    12. -
    13. {{_.sectionQLabelStep7}}
    14. -
    15. {{_.sectionQLabelStep8}}
    16. -
    17. {{{_.sectionQLabelStep9}}}
    18. -
    19. {{_.sectionQLabelStep10}}
    20. -
    21. {{_.sectionQLabelStep11}}
    22. -
    23. {{_.sectionQLabelStep12}}
    24. -
    25. {{_.sectionQLabelStep13}}
    26. -
    27. {{_.sectionQLabelStep14}}
    28. -
    29. {{_.sectionQLabelStep15}}
    30. -
    - -

    {{_.sectionHelpTitle}}

    - -

    {{_.sectionHelpDescription}}

    -

    {{{_.sectionHelpDownloadRemoteSupport}}}

    - -

    - {{{salesPersonName}}} - {{{salesPersonPhone}}} - {{{salesPersonEmail}}} -

    -
    - - - - {{$.footer}} - -
    -
    - - \ No newline at end of file diff --git a/services/mailer/application/template/printer-setup/locale/es.json b/services/mailer/application/template/printer-setup/locale/es.json deleted file mode 100644 index 7d3da6646..000000000 --- a/services/mailer/application/template/printer-setup/locale/es.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "subject": "Instalación y configuración de impresora", - "title": "¡GRACIAS POR SU CONFIANZA!", - "dear": "Estimado cliente,", - "bodyDescription": "Siga las intrucciones especificadas en este correo para llevar a cabo la instalación de la impresora.", - "followGuide": "Puede utilizar como guía, el video del montaje del ribon y la cinta https://www.youtube.com/watch?v=qhb0kgQF3o8. También necesitará el QLabel, el programa para imprimir las cintas.", - "downloadFrom": "Puede descargarlo desde este enlace http://www.godexintl.com/en/product/type/Download/2967", - "sectionQLabelTitle": "Utilización de QLabel", - "sectionQLabelDescription": "Para utilizar el programa de impresión de cintas siga estos pasos:", - "sectionQLabelStep1": "Abra el programa QLabel.", - "sectionQLabelStep2": "Haga clic en el icono de la barra superior superior de la \"carpeta\".", - "sectionQLabelStep3": "Seleccione el archivo plantilla llamado \"model.ezp\".", - "sectionQLabelStep4": "Haga clic encima del texto con el boton secundario del ratón.", - "sectionQLabelStep5": "Elija la primera opcion \"setup\".", - "sectionQLabelStep6": "Cambie el texto para imprimir.", - "sectionQLabelStep7": "Haga clic en el boton \"Ok\".", - "sectionQLabelStep8": "Desplácese con el raton para ver la medida máxima.", - "sectionQLabelStep9": "Haga clic encima del texto con el botón secundario del ratón.", - "sectionQLabelStep10": "Elija la primera opcion \"Setup printer\".", - "sectionQLabelStep11": "Haga clic en la primera pestalla \"Label Setup\".", - "sectionQLabelStep12": "Modifique la propidad \"Paper Height\".", - "sectionQLabelStep13": "Haga clic en el boton \"Ok\".", - "sectionQLabelStep14": "Haga clic sobre el icono de la impresora.", - "sectionQLabelStep15": "Haga clic en \"Print\".", - "sectionHelpTitle": "¿Necesita ayuda?", - "sectionHelpDescription": "Si necesita ayuda, descárguese nuestro programa de soporte para poder conectarnos remotamente a su equipo y hacerle la instalación. Proporciónenos un horario de contacto para atenderle, y contactaremos con usted.", - "sectionHelpDownloadRemoteSupport": "Puede descargarse el programa desde este enlace http://soporte.verdnatura.es.", - "salesPersonNameText": "Soy su comercial y mi nombre es", - "salesPersonPhoneText": "Teléfono y whatsapp", - "salesPersonEmailText": "Dirección de e-mail" -} \ No newline at end of file diff --git a/services/mailer/application/template/printer-setup/printer-setup.js b/services/mailer/application/template/printer-setup/printer-setup.js deleted file mode 100644 index d17add406..000000000 --- a/services/mailer/application/template/printer-setup/printer-setup.js +++ /dev/null @@ -1,46 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); -var format = require(path.join(__dirname, '../../util/format.js')); - -module.exports = class PrinterSetup { - getData(params, cb) { - let query = `SELECT - CONCAT(w.name, ' ', w.firstName) name, - w.phone AS phone, - CONCAT(u.name, '@verdnatura.es') AS email, - LOWER(ct.code) countryCode, - c.email recipient - FROM client c - LEFT JOIN worker w ON w.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = w.userFk - JOIN country ct ON ct.id = c.countryFk - WHERE c.id = ?`; - - this.clientId = params.clientId; - this.isPreview = params.isPreview; - - database.pool.query(query, [params.clientId], (error, result) => { - if (error || result.length == 0) - return cb(new Error('No template data found')); - - Object.assign(this, result[0]); - cb(); - }); - } - - get salesPersonName() { - if (this.name) - return `
    ${this._.salesPersonNameText}: ${this.name}
    `; - } - - get salesPersonPhone() { - if (this.phone) - return `
    ${this._.salesPersonPhoneText}: ${format.phone(this.phone)}
    `; - } - - get salesPersonEmail() { - if (this.email) - return `
    ${this._.salesPersonEmailText}: ` + - `${this.email}
    `; - } -}; diff --git a/services/mailer/application/template/printer-setup/style.css b/services/mailer/application/template/printer-setup/style.css deleted file mode 100644 index e69de29bb..000000000 diff --git a/services/mailer/application/template/sepa-core/attachment.json b/services/mailer/application/template/sepa-core/attachment.json deleted file mode 100644 index 0637a088a..000000000 --- a/services/mailer/application/template/sepa-core/attachment.json +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/services/mailer/application/template/sepa-core/index.html b/services/mailer/application/template/sepa-core/index.html deleted file mode 100644 index 1acdae3fc..000000000 --- a/services/mailer/application/template/sepa-core/index.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - {{_.subject}} - - - - - - \ No newline at end of file diff --git a/services/mailer/application/template/sepa-core/locale/es.json b/services/mailer/application/template/sepa-core/locale/es.json deleted file mode 100644 index 48eaadf3a..000000000 --- a/services/mailer/application/template/sepa-core/locale/es.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "subject": "Solicitud de domiciliación bancaria", - "title": "CAMBIOS EN SU FORMA DE PAGO", - "dear": "Estimado cliente,", - "bodyDescription": "Para poder tramitar su solicitud de cambio de su forma de pago a giro bancario, le adjuntamos los documentos correspondientes a la Ley de Pago, que tiene que cumplimentar y enviarnos.", - "conclusion": "Gracias por su atención." -} \ No newline at end of file diff --git a/services/mailer/application/template/sepa-core/sepa-core.js b/services/mailer/application/template/sepa-core/sepa-core.js deleted file mode 100644 index ec19dd29b..000000000 --- a/services/mailer/application/template/sepa-core/sepa-core.js +++ /dev/null @@ -1,32 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); -var format = require(path.join(__dirname, '../../util/format.js')); - -module.exports = class SepaCore { - getData(params, cb) { - let query = `SELECT - CONCAT(w.name, ' ', w.firstName) name, - w.phone AS phone, - CONCAT(u.name, '@verdnatura.es') AS email, - LOWER(ct.code) countryCode, - c.email recipient - FROM client c - LEFT JOIN worker w ON w.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = w.userFk - JOIN country ct ON ct.id = c.countryFk - WHERE c.id = ?`; - - this.clientId = params.clientId; - this.companyId = params.companyId; - this.token = params.token; - - database.pool.query(query, [params.clientId], (error, result) => { - if (error || result.length == 0) - return cb(new Error('No template data found')); - - Object.assign(this, result[0]); - - cb(); - }); - } -}; diff --git a/services/mailer/application/template/sepa-core/style.css b/services/mailer/application/template/sepa-core/style.css deleted file mode 100644 index e69de29bb..000000000 diff --git a/services/mailer/application/util/format.js b/services/mailer/application/util/format.js deleted file mode 100644 index 681fea72d..000000000 --- a/services/mailer/application/util/format.js +++ /dev/null @@ -1,39 +0,0 @@ -let database = require('../database.js'); - -module.exports = { - - /** - * Devuelve el iban - * @param {String} addressNumber - Dirección de cuenta bancaria - * @param {Object} cb - Callback - */ - accountAddressIban: function(addressNumber, cb) { - database.pool.query('SELECT vn2008.cc_to_iban(?) AS iban', [addressNumber], function(error, result) { - cb(result[0].iban); - }); - }, - - /** - * Obtiene el numero de cuenta completo incluyendo iban - * @param {String} addressNumber - Dirección de cuenta bancaria - * @return {String} Cuenta bancaria formateada - */ - accountAddress: function(addressNumber) { - var formattedAccountAddress = addressNumber.replace(/(.{4})/g, '$1-'); - return formattedAccountAddress.substring(0, formattedAccountAddress.length - 1); - }, - - /** - * Devuelve el numero de cuenta mostrando únicamente los últimos 4 dígitos. - * @param {String} addressNumber - Dirección de cuenta bancaria - * @return {String} Cuenta bancaria formateada - */ - partialAccountAddress: function(addressNumber) { - let address = this.accountAddress(addressNumber); - return address.substring(0, 19).replace(/[0-9]/g, 'X') + address.substring(19, 24); - }, - - phone: function(number) { - return number; - } -}; diff --git a/services/mailer/application/util/system.js b/services/mailer/application/util/system.js deleted file mode 100644 index 358346184..000000000 --- a/services/mailer/application/util/system.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = { - /** - * Obtiene las variables de entorno - * @param {String} env - Nombre de la variable de entorno - * @return {String} Valor de la variable de entorno - */ - getEnv: function(env) { - return process.env[env]; - } -}; diff --git a/services/mailer/package.json b/services/mailer/package.json deleted file mode 100644 index 1bbf6cfdf..000000000 --- a/services/mailer/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "vn-mailer", - "version": "0.0.1", - "description": "Servidor de envío de correos", - "main": "server/server.js", - "dependencies": { - "body-parser": "^1.17.2", - "express": "^4.15.3", - "inline-css": "^2.2.2", - "mustache": "^2.3.0", - "mysql": "^2.13.0", - "nodemailer": "^4.0.1", - "path": "^0.12.7", - "request": "^2.83.0" - }, - "repository": { - "type": "git", - "url": "https://git.verdnatura.es/salix" - }, - "license": "GPL-3.0" -} diff --git a/services/mailer/server/server.js b/services/mailer/server/server.js deleted file mode 100644 index 60e5a5d8b..000000000 --- a/services/mailer/server/server.js +++ /dev/null @@ -1,36 +0,0 @@ -var express = require('express'); -var app = module.exports = express(); -var bodyParser = require('body-parser'); -var config = require('../application/config.js'); -var mail = require('../application/mail.js'); -var database = require('../application/database.js'); -var path = require('path'); - -// Body parser middleware -app.use(bodyParser.json()); -app.use(bodyParser.urlencoded({extended: true})); - -app.use('/static', express.static(path.join(__dirname, '../static'))); - -// Load routes -app.use('/', require('../application/router.js')); - -app.start = function(port) { - var listener = app.listen(port ? port : config.app.port, function() { - var servicePath = 'http://' + listener.address().address + ':' + listener.address().port; - mail.init(); - database.init(); - database.testEmail(); - - if (config.app.debug) { - let packageJson = require('../package.json'); - console.log(`Web server ${packageJson.name} listening at: ${servicePath}`); - console.log(`${packageJson.name} service debug mode enabled`); - } - }); - return listener; -}; - -if (require.main === module) { - app.start(); -} diff --git a/services/mailer/static/css/component.css b/services/mailer/static/css/component.css deleted file mode 100644 index b4c018d79..000000000 --- a/services/mailer/static/css/component.css +++ /dev/null @@ -1,221 +0,0 @@ -body { - padding: 0; - margin: 0 -} - -img { - margin: 0 -} - -p { - text-align: justify -} - -.wrapper { - background-color: #EEE -} - -.container { - font-family: arial, sans-serif; - max-width: 600px; - min-width: 320px; - font-size: 16px; - margin: 0 auto; - color: #555 -} - -.title { - background-color: #95d831; - text-align: center; - padding: 35px 0 -} - -.title h1 { - font-size: 32px; - color: #333; - margin: 0 -} - -.body { - background-color:#FFF; - padding: 20px -} - -.body a { - color: #8dba25 -} - -.body h1 { - color: #999 -} - -.body h3 { - font-size: 16px -} - -.panel { - border: 1px solid #DDD; - margin-bottom: 10px; - position: relative; - padding:10px -} - -.row { - margin-bottom: 15px; - overflow: hidden -} - -.row .text { - margin-bottom: 5px -} - -.row .control { - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box -} - -.row .text, .row .control { - overflow: hidden -} - -.row .description { - position: relative; - padding-top: 2px; - overflow: hidden; - font-size: 11px; - display: block; - color: #999 -} - -.row .line { - border-bottom: 1px solid #DDD; - border-right: 1px solid #DDD; - border-left: 1px solid #DDD; - margin-top: 10px; - color: #999; - padding: 5px -} - -.row .description span { - background-color: #FFF; - margin: -5px 0 0 50px; - display: block; - padding: 5px; - float: left -} - -.row:last-child { - margin-bottom: 0 -} - -.row.inline .text { - margin-bottom: 0; - width: 40%; - float: left -} - -.row.inline .control { - font-weight: bold; - padding-left: 20px; - color: #000; - width: 60%; - float: left -} - -.row.inline .description { - position: static; - overflow: visible -} - -.box { - border-top: 1px solid #CCC; - border-right: 1px solid #CCC; - border-bottom: 1px solid #CCC; - font-weight: bold; - text-align: center; - padding-top: 4px; - width: 25px; - height: 21px; - color: #000; - float: left -} - -.box.crossed { - font-weight: 100; - font-size: 16px -} - -.row .control .box:first-child { - border-left: 1px solid #CCC; -} - -.font.small { - font-size: 10px -} - -.font.verticalAlign { - height: 27px; - line-height: 27px -} - -.font.centered { - height: 27px; - line-height: 27px; - text-align: center -} - -.verticalText { - -moz-transform: rotate(90deg); - -webkit-transform: rotate(90deg); - transform: rotate(90deg); - position: absolute; - text-align: center; - font-size: .65em; - width: 200px; - right: -115px; - top: 50% -} - -.attachment { - overflow: hidden; - margin-top: 10px -} - -.attachment-icon { - float: left -} - -.attachment span { - padding: 16px 0 0 10px; - float: left -} - -.columns { - overflow: hidden -} - -.columns .size100 { - width: 100%; - float: left -} - -.columns .size75 { - width: 75%; - float: left -} - -.columns .size50 { - width: 50%; - float: left -} - -.columns .size33 { - width: 33.33%; - float: left -} - -.columns .size25 { - width: 25%; - float: left -} \ No newline at end of file diff --git a/services/nginx/.gitignore b/services/nginx/.gitignore deleted file mode 100644 index c68eb0b10..000000000 --- a/services/nginx/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -static/* -temp/* -!static/templates -!static/images \ No newline at end of file diff --git a/services/nginx/Dockerfile b/services/nginx/Dockerfile deleted file mode 100644 index 074193d90..000000000 --- a/services/nginx/Dockerfile +++ /dev/null @@ -1,13 +0,0 @@ -FROM nginx - -RUN rm /etc/nginx/nginx.conf -RUN rm /etc/nginx/conf.d/default.conf - -COPY temp/nginx.conf /etc/nginx/nginx.conf -COPY static /usr/share/nginx/html - -RUN apt-get update && apt-get -y install vim dnsmasq dnsutils iputils-ping -RUN rm -fr /usr/share/dns -RUN echo listen-address=127.0.0.1 > /etc/dnsmasq.d/dnsmasq.conf - -CMD service dnsmasq restart && nginx -g "daemon off;" diff --git a/services/nginx/config.production.yml b/services/nginx/config.production.yml deleted file mode 100644 index 80792e8a0..000000000 --- a/services/nginx/config.production.yml +++ /dev/null @@ -1,2 +0,0 @@ -host: salix -port: 80 \ No newline at end of file diff --git a/services/nginx/config.test.yml b/services/nginx/config.test.yml deleted file mode 100644 index 3852100af..000000000 --- a/services/nginx/config.test.yml +++ /dev/null @@ -1,2 +0,0 @@ -host: test-salix -port: 80 \ No newline at end of file diff --git a/services/nginx/config.yml b/services/nginx/config.yml deleted file mode 100644 index d96c80871..000000000 --- a/services/nginx/config.yml +++ /dev/null @@ -1,4 +0,0 @@ -host: localhost -port: 5000 -main: salix -defaultPort: 3000 \ No newline at end of file diff --git a/services/nginx/nginx.development.mst b/services/nginx/nginx.development.mst deleted file mode 100644 index 25faeddfd..000000000 --- a/services/nginx/nginx.development.mst +++ /dev/null @@ -1,54 +0,0 @@ - -worker_processes 1; - -error_log temp/error.log; -pid temp/nginx.pid; - -events { - worker_connections 1024; -} - -http { - sendfile on; - gzip on; - default_type application/octet-stream; - - access_log temp/access.log; - client_body_temp_path temp/client-body; - proxy_temp_path temp/proxy; - fastcgi_temp_path temp/fastcgi; - uwsgi_temp_path temp/uwsgi; - scgi_temp_path temp/scgi; - - server { - listen {{port}}; - server_name {{host}}; - autoindex off; - - {{#services}} - location ~ ^/{{name}}(?:/(.*))?$ { - proxy_pass http://127.0.0.1:{{port}}/$1$is_args$args; - } - {{/services}} - - location ~ ^/static(?:/(.*))?$ { - proxy_pass http://127.0.0.1:{{devServerPort}}/$1$is_args$args; - } - location ~ ^(?:/(.*))?$ { - proxy_pass http://127.0.0.1:{{defaultPort}}/$1$is_args$args; - } - } - - types { - text/html html; - application/json json; - application/javascript js; - text/css css scss; - text/xml xml; - image/x-icon ico; - image/png png; - image/svg+xml svg; - image/gif gif; - image/jpeg jpeg jpg; - } -} diff --git a/services/nginx/nginx.mst b/services/nginx/nginx.mst deleted file mode 100644 index ed08ae691..000000000 --- a/services/nginx/nginx.mst +++ /dev/null @@ -1,36 +0,0 @@ - -worker_processes 1; - -events { - worker_connections 1024; -} - -http { - sendfile on; - gzip on; - default_type application/octet-stream; - resolver 127.0.0.1; - include /etc/nginx/mime.types; - - server { - listen {{port}}; - server_name {{host}}; - autoindex off; - - root /usr/share/nginx/html; - - {{#services}} - location ~ ^/{{name}}(?:/(.*))?$ { - proxy_pass http://{{name}}:{{defaultPort}}/$1$is_args$args; - } - {{/services}} - - location ~ ^/static(?:/(.*))?$ { - alias /usr/share/nginx/html/$1; - autoindex on; - } - location ~ ^(?:/(.*))?$ { - proxy_pass http://{{defaultService}}:{{defaultPort}}/$1$is_args$args; - } - } -} diff --git a/services/nginx/static/images/icon_client.png b/services/nginx/static/images/icon_client.png deleted file mode 100644 index 8858ec7ae..000000000 Binary files a/services/nginx/static/images/icon_client.png and /dev/null differ diff --git a/services/nginx/static/images/icon_item.png b/services/nginx/static/images/icon_item.png deleted file mode 100644 index ff660fb23..000000000 Binary files a/services/nginx/static/images/icon_item.png and /dev/null differ diff --git a/services/nginx/static/images/icon_production.png b/services/nginx/static/images/icon_production.png deleted file mode 100644 index 85d680ce7..000000000 Binary files a/services/nginx/static/images/icon_production.png and /dev/null differ diff --git a/services/nginx/static/templates/tooltip.locator.tpl.html b/services/nginx/static/templates/tooltip.locator.tpl.html deleted file mode 100644 index be0877ab8..000000000 --- a/services/nginx/static/templates/tooltip.locator.tpl.html +++ /dev/null @@ -1,14 +0,0 @@ - - - Town - Province - Client ID - Worker - - - {{::ticket.city | ucwords}} - {{::ticket.province | ucwords}} - {{::ticket.client | ucwords}} - {{::ticket.worker | ucwords}} - - \ No newline at end of file diff --git a/services/nginx/static/templates/tooltip.routes.tpl.html b/services/nginx/static/templates/tooltip.routes.tpl.html deleted file mode 100644 index 71e8be8d0..000000000 --- a/services/nginx/static/templates/tooltip.routes.tpl.html +++ /dev/null @@ -1,14 +0,0 @@ - - - Población - Provincia - ID_Cliente - Comercial - - - {{::ticket.city | ucwords}} - {{::ticket.province | ucwords}} - {{::ticket.client | ucwords}} - {{::ticket.worker | ucwords}} - - \ No newline at end of file diff --git a/services/print/.gitignore b/services/print/.gitignore deleted file mode 100644 index 3c3629e64..000000000 --- a/services/print/.gitignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/services/print/Dockerfile b/services/print/Dockerfile deleted file mode 100644 index 9320bd0ac..000000000 --- a/services/print/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -FROM node:8.9.4 - -COPY print /app -COPY loopback /loopback - -WORKDIR /app - -RUN npm install -RUN npm -g install pm2 - -CMD ["pm2-docker", "./server/server.js"] diff --git a/services/print/application/auth.js b/services/print/application/auth.js deleted file mode 100644 index ee8f114e1..000000000 --- a/services/print/application/auth.js +++ /dev/null @@ -1,62 +0,0 @@ -var database = require('./database.js'); - -module.exports = { - -/** - * Initialize auth - * @param {Object} request - Request object - * @param {Object} response - Response object - * @param {Object} next - Next object - */ - init: function(request, response, next) { - this.request = request; - this.response = response; - this.next = next; - - this.validateToken(); - }, - -/** - * Validate auth token - */ - validateToken: function() { - let query = 'SELECT userId, ttl, created FROM salix.AccessToken WHERE id = ?'; - - database.pool.query(query, [this.getToken()], (error, result) => { - let token = result[0]; - - if (error || result.length == 0) - return this.response.status(401).send({message: 'Invalid token'}); - - if (this.isTokenExpired(token.created, token.ttl)) - return this.response.status(401).send({message: 'Token expired'}); - - this.request.userId = token.userId; - this.next(); - }); - }, - -/** - * Get request token - * @return {String} Token - */ - getToken: function() { - return this.request.headers.authorization || this.request.query.token; - }, - -/** - * Checks if the token has expired - * @param {String} created - Creation date - * @param {Integer} ttl - Ttl seconds - * @return {Boolean} True if the token has expired - */ - isTokenExpired: function(created, ttl) { - let date = new Date(created); - let currentDate = new Date(); - - date.setSeconds(date.getSeconds() + ttl); - - if (currentDate > date) - return true; - } -}; diff --git a/services/print/application/config.js b/services/print/application/config.js deleted file mode 100644 index 335441531..000000000 --- a/services/print/application/config.js +++ /dev/null @@ -1,21 +0,0 @@ -require('require-yaml'); -var fs = require('fs-extra'); - -let env = process.env.NODE_ENV ? process.env.NODE_ENV : 'development'; - -let config = require(`${__dirname}/config/datasources.json`); -let configEnvFile = `${__dirname}/config/datasources.${env}.json`; - -if (fs.existsSync(configEnvFile)) - Object.assign(config, require(configEnvFile)); - -let proxyConf = require(`../../nginx/config.yml`); -let proxyEnvFile = `../../nginx/config.${env}.yml`; - -if (fs.existsSync(proxyEnvFile)) - Object.assign(proxyConf, require(proxyEnvFile)); - -config.proxy = proxyConf; -config.package = require('../package.json'); - -module.exports = config; diff --git a/services/print/application/config/datasources.json b/services/print/application/config/datasources.json deleted file mode 100644 index 0c08c7d0a..000000000 --- a/services/print/application/config/datasources.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "app": { - "port": 3000, - "debug": false, - "defaultLanguage": "es" - }, - "mysql": { - "host": "localhost", - "port": 3306, - "database": "vn", - "user": "root", - "password": "root" - }, - "pdf": { - "format": "A4", - "header": { - "height": "120px" - }, - "footer": { - "height": "130px" - } - } -} \ No newline at end of file diff --git a/services/print/application/database.js b/services/print/application/database.js deleted file mode 100644 index 974540d7d..000000000 --- a/services/print/application/database.js +++ /dev/null @@ -1,24 +0,0 @@ -var mysql = require('mysql'); -let config = require('./config.js'); - -module.exports = { - /** - * Pool instance - */ - pool: null, - - /** - * Start database pool - */ - init: function() { - this.pool = mysql.createPool(config.mysql); - - this.pool.getConnection(function(error, connection) { - if (error) { - throw new Error('Can\'t connect to database: ' + error.code); - } else if (config.app.debug) { - console.log('Database connection stablished'); - } - }); - } -}; diff --git a/services/print/application/locale.js b/services/print/application/locale.js deleted file mode 100644 index f9737fea3..000000000 --- a/services/print/application/locale.js +++ /dev/null @@ -1,42 +0,0 @@ -var fs = require('fs'); -var config = require('./config.js'); -var path = require('path'); - -module.exports = { -/** - * Returns template locale - * @param {String} template - Template name - * @param {String} countryCode - Language code - * @param {Object} cb - Callback - */ - load: function(template, countryCode, cb) { - var localeFile = path.join(__dirname, 'template', `${template}`, 'locale', `${countryCode}.json`); - var defaultLocaleFile = path.join(__dirname, 'template', `${template}`, 'locale', `${config.app.defaultLanguage}.json`); - - fs.stat(localeFile, (error, stats) => { - if (error) { - fs.stat(defaultLocaleFile, (error, stats) => { - if (error) - return cb(new Error('Translation not found for template ' + template)); - - cb(null, {locale: require(defaultLocaleFile)}); - }); - } else { - cb(null, {locale: require(localeFile)}); - } - }); - }, - -/** - * Parse locale text - * @param {String} text - Locale text - * @param {Object} params - Locale params - * @return {String} - Returns parsed text - */ - parseText: function(text, params) { - for (var key in params) { - text = text.replace(`%${key}%`, params[key]); - } - return text; - } -}; diff --git a/services/print/application/route/manuscript.js b/services/print/application/route/manuscript.js deleted file mode 100644 index 091ffa4c3..000000000 --- a/services/print/application/route/manuscript.js +++ /dev/null @@ -1,109 +0,0 @@ -var express = require('express'); -var router = new express.Router(); -var template = require('../template.js'); -var config = require('../config.js'); -var pdf = require('html-pdf'); -var path = require('path'); -var auth = require('../auth.js'); - -// Auth middleware -var requestToken = function(request, response, next) { - auth.init(request, response, next); -}; - -// Sepa core -router.get('/sepa-core/:companyId/:clientId', requestToken, function(request, response, next) { - let params = { - clientId: request.params.clientId, - companyId: request.params.companyId - }; - - template.get('sepa-core', params, (error, result) => { - if (error) - return response.status(400).json({message: error.message}); - - pdf.create(result.body, config.pdf).toStream(function(error, stream) { - if (error) - throw Error(error); - - response.setHeader('Content-Disposition', 'attachment; filename="sepa-core.pdf"'); - response.setHeader('Content-type', 'application/pdf'); - stream.pipe(response); - }); - }); - }); - -// Sepa core html preview -router.get('/sepa-core/:companyId/:clientId/preview', requestToken, function(request, response, next) { - let params = { - clientId: request.params.clientId, - companyId: request.params.companyId, - isPreview: true - }; - - template.get('sepa-core', params, (error, result) => { - if (error) - return response.status(400).json({message: error.message}); - - response.send(result.body); - }); - }); - - // Debtor letter -router.get('/letter-debtor/:companyId/:clientId', requestToken, function(request, response, next) { - let params = { - clientId: request.params.clientId, - companyId: request.params.companyId - }; - - template.get('letter-debtor', params, (error, result) => { - if (error) - return response.status(400).json({message: error.message}); - - pdf.create(result.body, config.pdf).toStream(function(error, stream) { - if (error) - throw Error(error); - - response.setHeader('Content-Disposition', 'attachment; filename="extracto.pdf"'); - response.setHeader('Content-type', 'application/pdf'); - stream.pipe(response); - }); - }); - }); - - // Debtor letter html preview -router.get('/letter-debtor/:companyId/:clientId/preview', requestToken, function(request, response, next) { - let params = { - clientId: request.params.clientId, - companyId: request.params.companyId, - isPreview: true - }; - - template.get('letter-debtor', params, (error, result) => { - if (error) - return response.status(400).json({message: error.message}); - - response.send(result.body); - }); - }); - - -module.exports = router; - - - // store pdf -/* router.post('/sepa-core/:clientId', function(request, response, next) { - template.get('sepa-core', {recipient: request.params.clientId}, (error, result) => { - if (error) - return response.status(400).json({message: error.message}); - - pdf.create(result.body).toFile('./tmp/test.pdf', function(error, result) { - if (error) - return response.status(400).json({message: error}); - - console.log(result); - return response.json(); - }); - }); - }); - */ \ No newline at end of file diff --git a/services/print/application/router.js b/services/print/application/router.js deleted file mode 100644 index a9ebe1acf..000000000 --- a/services/print/application/router.js +++ /dev/null @@ -1,31 +0,0 @@ -var express = require('express'); -var router = new express.Router(); -var fs = require('fs'); -var path = require('path'); - -// Default page -router.get('/', function(request, response) { - response.json({}); -}); - -// Manuscripts -router.use('/manuscript', require('./route/manuscript.js')); - -// Serve static images -router.use('/static/:template/:image', function(request, response) { - let imagePath = path.join(__dirname, '/template/', request.params.template, '/image/', request.params.image); - - fs.stat(imagePath, function(error) { - if (error) - return response.json({message: 'Image not found'}); - - let readStream = fs.createReadStream(imagePath); - - readStream.on('open', function() { - readStream.pipe(response); - }); - }); -}); - - -module.exports = router; diff --git a/services/print/application/template.js b/services/print/application/template.js deleted file mode 100644 index 9974ebcf5..000000000 --- a/services/print/application/template.js +++ /dev/null @@ -1,184 +0,0 @@ -var fs = require('fs'); -var mustache = require('mustache'); -var locale = require('./locale.js'); -var inlineCss = require('inline-css'); -var path = require('path'); - - -module.exports = { -/** - * Get template. - * @param {String} template - Template name - * @param {Object} countryCode - Language code - * @param {Object} params - Params - * @param {Object} cb - Callback - */ - get: function(template, params, cb) { - var templatePath = path.join(__dirname, 'template', `${template}`, `index.html`); - var classPath = path.join(__dirname, 'template', `${template}`, `${template}.js`); - var stylePath = path.join(__dirname, 'template', `${template}`, 'style.css'); - - fs.stat(templatePath, (error, stat) => { - if (error) - return cb(new Error('Template ' + template + ' not found')); - - let TemplateClass = require(classPath); - let instance = new TemplateClass(); - - let getRenderedStyles = (error, body) => { - if (error) - return cb(error); - - this.renderStyles(stylePath, body, (error, body) => { - if (error) - return cb(error); - - // Check if has a subject param - params.subject = params.subject || instance.subject; - - if (params.subject == undefined) { - // Try to find a subject from Html source - let title = body.match(new RegExp('(.*?)', 'i')); - - if (title) - params.subject = title[1]; - } - - this.renderImages(template, body, params.isPreview, (error, body) => { - if (error) - return cb(error); - - cb(null, {body: body}); - }); - }); - }; - - let getDataCb = () => { - this.render(templatePath, params, instance, (error, result) => getRenderedStyles(error, result)); - }; - - instance.getData(params, (error, result) => { - if (error) - return cb(error); - - locale.load(template, instance.countryCode, (error, result) => { - if (error) - return cb(error); - - instance._ = result.locale; - instance.isPreview = params.isPreview; - getDataCb(null, result); - }); - }); - }); - }, - -/** - * Render template - * @param {String} path - Template path - * @param {Object} data - Params - * @param {Object} cb - Callback - */ - render: function(path, params, data, cb) { - fs.readFile(path, 'utf8', (error, body) => { - // Find matching sub-templates - let regexp = new RegExp(/\{\{\$\.(.*?)\}\}/, 'ig'); - let subTpl = body.match(regexp); - - if (!subTpl) { - mustache.parse(body); - return cb(null, mustache.render(body, data)); - } - - let parentBody = body; - this.renderSub(parentBody, subTpl, params, regexp, (error, body) => { - if (error) - return cb(error); - - mustache.parse(body); - cb(null, mustache.render(body, data)); - }); - }); - }, - - renderSub: function(body, subTpl, params, regexp, cb) { - let index = 1; - - subTpl.forEach(keyName => { - subTplName = keyName.replace(regexp, '$1'); - - this.get(subTplName, params, (error, result) => { - if (error) - return cb(error); - - let subTplBody = result.body; - body = body.replace(keyName, subTplBody); - - if (index === subTpl.length) - cb(null, body); - - index++; - }); - - }); - }, - -/** - * Render template style. - * @param {String} path - Stylesheet path - * @param {String} body - Rendered html - * @param {Object} cb - Callback - */ - renderStyles: function(stylePath, html, cb) { - // Common components - let comPath = path.join(__dirname, '../', 'static', 'css', 'component.css'); - - fs.readFile(comPath, 'utf8', (error, comCss) => { - fs.stat(stylePath, error => { - if (error) - return cb(new Error('Template stylesheet not found')); - - fs.readFile(stylePath, 'utf8', (error, css) => { - let style = ''; - let body = style + html; - let options = {url: ' '}; - - inlineCss(body, options) - .then(function(body) { - cb(null, body); - }); - }); - }); - }); - }, - -/** - * Render template images - * @param {String} template - Template name - * @param {String} body - template body - * @param {Object} cb - Callback - */ - renderImages: function(template, body, isPreview, cb) { - let tplImages = body.match(new RegExp('src="cid:(.*?)"', 'ig')); - - if (!tplImages) - tplImages = {}; - - // Template default attachments - for (var i = 0; i < tplImages.length; i++) { - let src = tplImages[i].replace('src="cid:', '').replace('"', '').split('/'); - let attachmentTpl = src[0]; - let attachment = src[1]; - - if (isPreview) { - let imagePath = `/print/static/${attachmentTpl}/${attachment}`; - body = body.replace(tplImages[i], `src="${imagePath}"`); - } else { - let imagePath = path.join(__dirname, 'template', attachmentTpl, 'image', attachment); - body = body.replace(tplImages[i], `src="file:///${imagePath}"`); - } - } - - cb(null, body); - } -}; diff --git a/services/print/application/template/footer/footer.js b/services/print/application/template/footer/footer.js deleted file mode 100644 index 3b4020bf4..000000000 --- a/services/print/application/template/footer/footer.js +++ /dev/null @@ -1,20 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); -var format = require(path.join(__dirname, '../../util/format.js')); - -module.exports = class Footer { - getData(params, cb) { - let query = `SELECT - socialName - FROM client c - JOIN country ct ON ct.id = c.countryFk - WHERE c.id = ?`; - database.pool.query(query, [params.clientId], (error, result) => { - if (error || result.length == 0) - return cb(new Error('No template data found')); - - Object.assign(this, result[0]); - cb(); - }); - } -}; diff --git a/services/print/application/template/footer/image/action.png b/services/print/application/template/footer/image/action.png deleted file mode 100644 index 2cd16c453..000000000 Binary files a/services/print/application/template/footer/image/action.png and /dev/null differ diff --git a/services/print/application/template/footer/image/facebook.png b/services/print/application/template/footer/image/facebook.png deleted file mode 100644 index 7ab54c538..000000000 Binary files a/services/print/application/template/footer/image/facebook.png and /dev/null differ diff --git a/services/print/application/template/footer/image/info.png b/services/print/application/template/footer/image/info.png deleted file mode 100644 index fb75cbc4e..000000000 Binary files a/services/print/application/template/footer/image/info.png and /dev/null differ diff --git a/services/print/application/template/footer/image/instagram.png b/services/print/application/template/footer/image/instagram.png deleted file mode 100644 index 66550c4a5..000000000 Binary files a/services/print/application/template/footer/image/instagram.png and /dev/null differ diff --git a/services/print/application/template/footer/image/linkedin.png b/services/print/application/template/footer/image/linkedin.png deleted file mode 100644 index 0d191e5ae..000000000 Binary files a/services/print/application/template/footer/image/linkedin.png and /dev/null differ diff --git a/services/print/application/template/footer/image/pinterest.png b/services/print/application/template/footer/image/pinterest.png deleted file mode 100644 index 4d7b28ef8..000000000 Binary files a/services/print/application/template/footer/image/pinterest.png and /dev/null differ diff --git a/services/print/application/template/footer/image/twitter.png b/services/print/application/template/footer/image/twitter.png deleted file mode 100644 index c4a8ab0c1..000000000 Binary files a/services/print/application/template/footer/image/twitter.png and /dev/null differ diff --git a/services/print/application/template/footer/image/youtube.png b/services/print/application/template/footer/image/youtube.png deleted file mode 100644 index 11871deb5..000000000 Binary files a/services/print/application/template/footer/image/youtube.png and /dev/null differ diff --git a/services/print/application/template/footer/index.html b/services/print/application/template/footer/index.html deleted file mode 100644 index 59b90b480..000000000 --- a/services/print/application/template/footer/index.html +++ /dev/null @@ -1,5 +0,0 @@ - \ No newline at end of file diff --git a/services/print/application/template/footer/locale/es.json b/services/print/application/template/footer/locale/es.json deleted file mode 100644 index 04a61fddd..000000000 --- a/services/print/application/template/footer/locale/es.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "phytosanitary": "VERDNATURA LEVANTE SL - Pasaporte Fitosanitario R.P. Generalitat Valenciana - Nº Comerciante: ES17462130", - "privacyLaw": "En cumplimiento de lo dispuesto en la Ley Orgánica 15/1999, de Protección de Datos de Carácter Personal, le comunicamos que los datos personales que facilite se incluirán en ficheros automatizados de VERDNATURA LEVANTE S.L., pudiendo en todo momento ejercitar los derechos de acceso, rectificación, cancelación y oposición, comunicándolo por escrito al domicilio social de la entidad. La finalidad del fichero es la gestión administrativa, contabilidad, y facturación." -} \ No newline at end of file diff --git a/services/print/application/template/footer/style.css b/services/print/application/template/footer/style.css deleted file mode 100644 index aeddc6f0a..000000000 --- a/services/print/application/template/footer/style.css +++ /dev/null @@ -1,24 +0,0 @@ -img { - margin: 0 -} - -#pageFooter { - font-family: arial, sans-serif; - font-weight: 100; - max-width: 90%; - margin: 0 auto; - font-size: 9px; - margin: 30px; - color: #555 -} - -#pageFooter .info { - border-bottom: 2px solid #CCC; - padding-bottom: 2px; - text-align: center; - font-size: 11px -} - -#pageFooter p { - text-align: center -} \ No newline at end of file diff --git a/services/print/application/template/header/header.js b/services/print/application/template/header/header.js deleted file mode 100644 index 82c78e003..000000000 --- a/services/print/application/template/header/header.js +++ /dev/null @@ -1,20 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); -var format = require(path.join(__dirname, '../../util/format.js')); - -module.exports = class Header { - getData(params, cb) { - let query = `SELECT - c.name AS clientName - FROM client c - JOIN country ct ON ct.id = c.countryFk - WHERE c.id = ?`; - database.pool.query(query, [params.clientId], (error, result) => { - if (error || result.length == 0) - return cb(new Error('No template data found')); - - Object.assign(this, result[0]); - cb(); - }); - } -}; diff --git a/services/print/application/template/header/index.html b/services/print/application/template/header/index.html deleted file mode 100644 index 44e8e52d7..000000000 --- a/services/print/application/template/header/index.html +++ /dev/null @@ -1,7 +0,0 @@ -
    - VerdNatura -

    -

    {{_.mercantileRegistry}}
    -
    {{_.fiscalAddress}}
    -

    -
    \ No newline at end of file diff --git a/services/print/application/template/header/locale/es.json b/services/print/application/template/header/locale/es.json deleted file mode 100644 index 86dbe5e58..000000000 --- a/services/print/application/template/header/locale/es.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "mercantileRegistry": "CIF: B97367486 Registro Mercantil de Valencia, Tomo 8041, Libro 5334, Folio 160, sección 8, Hoja V 102076", - "fiscalAddress": "VERDNATURA LEVANTE SL, B97367486 Avda. Espioca, 100, 46460 Silla · www.verdnatura.es · clientes@verdnatura.es" -} \ No newline at end of file diff --git a/services/print/application/template/header/style.css b/services/print/application/template/header/style.css deleted file mode 100644 index 186ede66b..000000000 --- a/services/print/application/template/header/style.css +++ /dev/null @@ -1,16 +0,0 @@ -img { - margin: 0 -} - -#pageHeader-first { - border-bottom: 1px solid #DDD; - font-family: arial, sans-serif; - padding-bottom: 10px; - text-align: center; - font-size: 10px; - color: #555 -} - -.header p { - text-align: center -} \ No newline at end of file diff --git a/services/print/application/template/letter-debtor/image/action.png b/services/print/application/template/letter-debtor/image/action.png deleted file mode 100644 index 2cd16c453..000000000 Binary files a/services/print/application/template/letter-debtor/image/action.png and /dev/null differ diff --git a/services/print/application/template/letter-debtor/image/facebook.png b/services/print/application/template/letter-debtor/image/facebook.png deleted file mode 100644 index 7ab54c538..000000000 Binary files a/services/print/application/template/letter-debtor/image/facebook.png and /dev/null differ diff --git a/services/print/application/template/letter-debtor/image/header.png b/services/print/application/template/letter-debtor/image/header.png deleted file mode 100644 index 3c063ae44..000000000 Binary files a/services/print/application/template/letter-debtor/image/header.png and /dev/null differ diff --git a/services/print/application/template/letter-debtor/image/info.png b/services/print/application/template/letter-debtor/image/info.png deleted file mode 100644 index fb75cbc4e..000000000 Binary files a/services/print/application/template/letter-debtor/image/info.png and /dev/null differ diff --git a/services/print/application/template/letter-debtor/image/instagram.png b/services/print/application/template/letter-debtor/image/instagram.png deleted file mode 100644 index 66550c4a5..000000000 Binary files a/services/print/application/template/letter-debtor/image/instagram.png and /dev/null differ diff --git a/services/print/application/template/letter-debtor/image/linkedin.png b/services/print/application/template/letter-debtor/image/linkedin.png deleted file mode 100644 index 0d191e5ae..000000000 Binary files a/services/print/application/template/letter-debtor/image/linkedin.png and /dev/null differ diff --git a/services/print/application/template/letter-debtor/image/logo.png b/services/print/application/template/letter-debtor/image/logo.png deleted file mode 100644 index 55e26fec6..000000000 Binary files a/services/print/application/template/letter-debtor/image/logo.png and /dev/null differ diff --git a/services/print/application/template/letter-debtor/image/pinterest.png b/services/print/application/template/letter-debtor/image/pinterest.png deleted file mode 100644 index 4d7b28ef8..000000000 Binary files a/services/print/application/template/letter-debtor/image/pinterest.png and /dev/null differ diff --git a/services/print/application/template/letter-debtor/image/twitter.png b/services/print/application/template/letter-debtor/image/twitter.png deleted file mode 100644 index c4a8ab0c1..000000000 Binary files a/services/print/application/template/letter-debtor/image/twitter.png and /dev/null differ diff --git a/services/print/application/template/letter-debtor/image/youtube.png b/services/print/application/template/letter-debtor/image/youtube.png deleted file mode 100644 index 11871deb5..000000000 Binary files a/services/print/application/template/letter-debtor/image/youtube.png and /dev/null differ diff --git a/services/print/application/template/letter-debtor/index.html b/services/print/application/template/letter-debtor/index.html deleted file mode 100644 index a2d92979b..000000000 --- a/services/print/application/template/letter-debtor/index.html +++ /dev/null @@ -1,84 +0,0 @@ - - - - {{_.subject}} - - - - - {{$.header}} - - - -
    - -
    -
    -
    -

    EXTRACTO

    -
    -
    CLIENTE:
    -
    {{clientId}}
    -
    -
    -
    FACTURA:
    -
    x
    -
    -
    -
    FECHA:
    -
    {{currentDate}}
    -
    -
    -
    -
    -
    -

    - {{supplierName}} -

    -
    - {{supplierStreet}} -
    -
    - {{supplierPostCode}}, {{supplierCity}} ({{supplierProvince}}) -
    -
    - {{supplierCountry}} -
    -
    -
    -
    - -
    -
    -
    Fecha
    -
    Concepto
    -
    Debe
    -
    Haber
    -
    Saldo
    -
    -
    -
    Fecha
    -
    Concepto
    -
    Debe
    -
    Haber
    -
    Saldo
    -
    -
    - -
    - -
    -
    - Subtotal -
    -
    -
    - -
    - - - - {{$.footer}} - - - \ No newline at end of file diff --git a/services/print/application/template/letter-debtor/letter-debtor.js b/services/print/application/template/letter-debtor/letter-debtor.js deleted file mode 100644 index 77715f3b7..000000000 --- a/services/print/application/template/letter-debtor/letter-debtor.js +++ /dev/null @@ -1,54 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); -var format = require(path.join(__dirname, '../../util/format.js')); - -module.exports = class LetterDebtor { - getData(params, cb) { - let query = `SELECT - c.id clientId, - m.code mandateCode, - LOWER(ct.code) AS countryCode, - c.email AS recipient, - c.socialName AS clientName, - c.street AS clientStreet, - c.postcode AS clientPostCode, - c.city AS clientCity, - p.name AS clientProvince, - ct.country AS clientCountry, - s.name AS supplierName, - s.street AS supplierStreet, - sc.country AS supplierCountry, - s.postCode AS supplierPostCode, - s.city AS supplierCity, - sp.name AS supplierProvince - FROM client c - JOIN country ct ON ct.id = c.countryFk - LEFT JOIN province p ON p.id = c.provinceFk - LEFT JOIN mandate m ON m.clientFk = c.id AND m.finished IS NULL - LEFT JOIN supplier s ON s.id = m.companyFk - LEFT JOIN country sc ON sc.id = s.countryFk - LEFT JOIN province sp ON sp.id = s.provinceFk - WHERE c.id = ?`; - database.pool.query(query, [params.clientId], (error, result) => { - if (error || result.length == 0) - return cb(new Error('No template data found')); - - Object.assign(this, result[0]); - cb(); - }); - } - - // Swift BIC fields - get swiftFields() { - return new Array(11); - } - - // Account number fields - get accountNumberFields() { - return new Array(23); - } - - get currentDate() { - return format.date(new Date(), '/'); - } -}; diff --git a/services/print/application/template/letter-debtor/locale/es.json b/services/print/application/template/letter-debtor/locale/es.json deleted file mode 100644 index e5453e858..000000000 --- a/services/print/application/template/letter-debtor/locale/es.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "title": "Orden de domiciliación de adeudo directo SEPA CORE", - "toCompleteBySupplier": "A cumplimentar por el acreedor", - "toCompleteByClient": "A cumplimentar por el deudor", - "bodyDescription": "Mediante la firma de esta orden de domiciliación, el deudor autoriza (A) al acreedor a enviar instrucciones a la entidad del deudor para adeudar su cuenta y (B) a la entidad para efectuar los adeudos en su cuenta siguiendo las instrucciones del acreedor.Como parte de sus derechos, el deudor está legitimado al reembolso por su entidad en los términos y condiciones del contrato suscrito con la misma. La solicitud de reembolso deberá efectuarse dentro de las ocho semanas que adeudo en cuenta. Puede obtener información adicional sobre sus derechos en su entidad financiera.", - "orderReference": "Referencia de la orden de domiciliación", - "supplierIdentifier": "Identificador del acreedor", - "supplierName": "Nombre del acreedor", - "supplierStreet": "Dirección", - "supplierLocation": "CP - Población - Provincia", - "supplierCountry": "País", - "clientAdvice": "Debe llevar a su Entidad Bancaria una copia del documento firmado para que lo registre y evitar la devolución.", - "clientName": "Nombre del deudor/es", - "clientStreet": "Dirección del deudor", - "clientLocation": "CP - Población - Provincia", - "clientCountry": "País del deudor", - "swift": "Swift BIC", - "accountNumber": "Número de cuenta - IBAN", - "accountHolder": "(Titular/es de la cuenta de cargo)", - "accountNumberFormat": "En España el IBAN consta de 24 posiciones comenzando siempre por ES", - "paymentType": "Tipo de pago", - "recurrent": "Recurrente", - "unique": "Único", - "signLocation": "Fecha - Localidad", - "sign": "Firma del deudor y sello", - "mandatoryFields": "TODOS LOS CAMPOS HAN DE SER CUMPLIMENTADOS OBLIGATORIAMENTE.", - "sendOrder": "UNA VEZ FIRMADA ESTA ORDEN DE DOMICILIACIÓN DEBE SER ENVIADA AL ACREEDOR PARA SU CUSTODIA Y ES RECOMENDABLE FACILITAR UNA COPIA A SU ENTIDAD BANCARIA.", - "fiscalAddress": "VERDNATURA LEVANTE SL, B97367486 Avda. Espioca, 100, 46460 Silla · www.verdnatura.es · clientes@verdnatura.es", - "privacy": "- AVISO - Este mensaje es privado y confidencial, y debe ser utilizado exclusivamente por la persona destinataria del mismo. Si usted ha recibido este mensaje por error, le rogamos lo comunique al remitente y borre dicho mensaje y cualquier documento adjunto que pudiera contener. Verdnatura Levante SL no renuncia a la confidencialidad ni a ningún privilegio por causa de transmisión errónea o mal funcionamiento. Igualmente no se hace responsable de los cambios, alteraciones, errores u omisiones que pudieran hacerse al mensaje una vez enviado.", - "privacyLaw": "En cumplimiento de lo dispuesto en la Ley Orgánica 15/1999, de Protección de Datos de Carácter Personal, le comunicamos que los datos personales que facilite se incluirán en ficheros automatizados de VERDNATURA LEVANTE S.L., pudiendo en todo momento ejercitar los derechos de acceso, rectificación, cancelación y oposición, comunicándolo por escrito al domicilio social de la entidad. La finalidad del fichero es la gestión administrativa, contabilidad, y facturación." -} \ No newline at end of file diff --git a/services/print/application/template/letter-debtor/style.css b/services/print/application/template/letter-debtor/style.css deleted file mode 100644 index 5b1e628d6..000000000 --- a/services/print/application/template/letter-debtor/style.css +++ /dev/null @@ -1,22 +0,0 @@ -img { - margin: 0 -} - -.body { - font-family: arial, sans-serif; - max-width: 90%; - margin: 0 auto; - font-size: 14px; - color: #000 -} - -body .title { - text-align: center; - padding-bottom: 20px -} - -body .title h1 { - font-size: 16px; - color: #333; - margin: 0 -} \ No newline at end of file diff --git a/services/print/application/template/sepa-core/index.html b/services/print/application/template/sepa-core/index.html deleted file mode 100644 index 92cc6fb80..000000000 --- a/services/print/application/template/sepa-core/index.html +++ /dev/null @@ -1,128 +0,0 @@ - - - - {{_.subject}} - - - - - {{$.header}} - - - -
    - - -
    -

    {{_.title}}

    -
    - -
    -
    {{_.toCompleteBySupplier}}
    -
    -
    {{_.orderReference}}
    -
    {{mandateCode}}
    -
    -
    -
    {{_.supplierIdentifier}}
    -
    ES89000B97367486
    -
    -
    -
    {{_.supplierName}}
    -
    {{supplierName}}
    -
    -
    -
    {{_.supplierStreet}}
    -
    {{supplierStreet}}
    -
    -
    -
    {{_.supplierLocation}}
    -
    {{supplierPostCode}}, {{supplierCity}} ({{supplierProvince}})
    -
    -
    -
    {{_.supplierCountry}}
    -
    {{supplierCountry}}
    -
    -
    - -

    {{_.bodyDescription}}

    -

    {{_.clientAdvice}}

    - -
    -
    {{_.toCompleteByClient}}
    -
    -
    {{_.clientName}}
    -
    {{clientName}}
    -
    {{_.accountHolder}}
    -
    -
    -
    {{_.clientStreet}}
    -
    {{clientStreet}}
    -
    -
    -
    {{_.clientLocation}}
    -
    {{clientPostCode}}, {{clientCity}} ({{clientProvince}})
    -
    -
    -
    {{_.clientCountry}}
    -
    {{clientCountry}}
    -
    -
    -
    {{_.swift}}
    -
    - {{#swiftFields}} -
    - {{/swiftFields}} -
    -
    -
    -
    {{_.accountNumber}}
    -
    -
    ES
    - {{#accountNumberFields}} -
    - {{/accountNumberFields}} -
    -
    -
    {{_.accountNumberFormat}}
    -
    -
    -
    -
    {{_.paymentType}}
    -
    -
    -
    -
    -
    X
    -
    -
    {{_.recurrent}}
    -
    -
    O
    -
    -
    -
    -
    -
    {{_.unique}}
    -
    -
    -
    -
    -
    -
    {{_.signLocation}}
    -
    {{currentDate}}, {{supplierProvince}}
    -
    -
    -
    {{_.sign}}
    -
    -
    -
    -

    {{_.mandatoryFields}}

    -

    {{_.sendOrder}}

    -
    - - - - {{$.footer}} - - - \ No newline at end of file diff --git a/services/print/application/template/sepa-core/locale/es.json b/services/print/application/template/sepa-core/locale/es.json deleted file mode 100644 index e5453e858..000000000 --- a/services/print/application/template/sepa-core/locale/es.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "title": "Orden de domiciliación de adeudo directo SEPA CORE", - "toCompleteBySupplier": "A cumplimentar por el acreedor", - "toCompleteByClient": "A cumplimentar por el deudor", - "bodyDescription": "Mediante la firma de esta orden de domiciliación, el deudor autoriza (A) al acreedor a enviar instrucciones a la entidad del deudor para adeudar su cuenta y (B) a la entidad para efectuar los adeudos en su cuenta siguiendo las instrucciones del acreedor.Como parte de sus derechos, el deudor está legitimado al reembolso por su entidad en los términos y condiciones del contrato suscrito con la misma. La solicitud de reembolso deberá efectuarse dentro de las ocho semanas que adeudo en cuenta. Puede obtener información adicional sobre sus derechos en su entidad financiera.", - "orderReference": "Referencia de la orden de domiciliación", - "supplierIdentifier": "Identificador del acreedor", - "supplierName": "Nombre del acreedor", - "supplierStreet": "Dirección", - "supplierLocation": "CP - Población - Provincia", - "supplierCountry": "País", - "clientAdvice": "Debe llevar a su Entidad Bancaria una copia del documento firmado para que lo registre y evitar la devolución.", - "clientName": "Nombre del deudor/es", - "clientStreet": "Dirección del deudor", - "clientLocation": "CP - Población - Provincia", - "clientCountry": "País del deudor", - "swift": "Swift BIC", - "accountNumber": "Número de cuenta - IBAN", - "accountHolder": "(Titular/es de la cuenta de cargo)", - "accountNumberFormat": "En España el IBAN consta de 24 posiciones comenzando siempre por ES", - "paymentType": "Tipo de pago", - "recurrent": "Recurrente", - "unique": "Único", - "signLocation": "Fecha - Localidad", - "sign": "Firma del deudor y sello", - "mandatoryFields": "TODOS LOS CAMPOS HAN DE SER CUMPLIMENTADOS OBLIGATORIAMENTE.", - "sendOrder": "UNA VEZ FIRMADA ESTA ORDEN DE DOMICILIACIÓN DEBE SER ENVIADA AL ACREEDOR PARA SU CUSTODIA Y ES RECOMENDABLE FACILITAR UNA COPIA A SU ENTIDAD BANCARIA.", - "fiscalAddress": "VERDNATURA LEVANTE SL, B97367486 Avda. Espioca, 100, 46460 Silla · www.verdnatura.es · clientes@verdnatura.es", - "privacy": "- AVISO - Este mensaje es privado y confidencial, y debe ser utilizado exclusivamente por la persona destinataria del mismo. Si usted ha recibido este mensaje por error, le rogamos lo comunique al remitente y borre dicho mensaje y cualquier documento adjunto que pudiera contener. Verdnatura Levante SL no renuncia a la confidencialidad ni a ningún privilegio por causa de transmisión errónea o mal funcionamiento. Igualmente no se hace responsable de los cambios, alteraciones, errores u omisiones que pudieran hacerse al mensaje una vez enviado.", - "privacyLaw": "En cumplimiento de lo dispuesto en la Ley Orgánica 15/1999, de Protección de Datos de Carácter Personal, le comunicamos que los datos personales que facilite se incluirán en ficheros automatizados de VERDNATURA LEVANTE S.L., pudiendo en todo momento ejercitar los derechos de acceso, rectificación, cancelación y oposición, comunicándolo por escrito al domicilio social de la entidad. La finalidad del fichero es la gestión administrativa, contabilidad, y facturación." -} \ No newline at end of file diff --git a/services/print/application/template/sepa-core/sepa-core.js b/services/print/application/template/sepa-core/sepa-core.js deleted file mode 100644 index 304e327da..000000000 --- a/services/print/application/template/sepa-core/sepa-core.js +++ /dev/null @@ -1,54 +0,0 @@ -var path = require('path'); -var database = require(path.join(__dirname, '../../database.js')); -var format = require(path.join(__dirname, '../../util/format.js')); - -module.exports = class SepaCore { - getData(params, cb) { - let query = `SELECT - c.id clientId, - m.code mandateCode, - LOWER(ct.code) AS countryCode, - c.email AS recipient, - c.socialName AS clientName, - c.street AS clientStreet, - c.postcode AS clientPostCode, - c.city AS clientCity, - p.name AS clientProvince, - ct.country AS clientCountry, - s.name AS supplierName, - s.street AS supplierStreet, - sc.country AS supplierCountry, - s.postCode AS supplierPostCode, - s.city AS supplierCity, - sp.name AS supplierProvince - FROM client c - JOIN country ct ON ct.id = c.countryFk - LEFT JOIN province p ON p.id = c.provinceFk - LEFT JOIN mandate m ON m.clientFk = c.id AND m.finished IS NULL - LEFT JOIN supplier s ON s.id = m.companyFk - LEFT JOIN country sc ON sc.id = s.countryFk - LEFT JOIN province sp ON sp.id = s.provinceFk - WHERE c.id = ?`; - database.pool.query(query, [params.clientId], (error, result) => { - if (error || result.length == 0) - return cb(new Error('No template data found')); - - Object.assign(this, result[0]); - cb(); - }); - } - - // Swift BIC fields - get swiftFields() { - return new Array(11); - } - - // Account number fields - get accountNumberFields() { - return new Array(23); - } - - get currentDate() { - return format.date(new Date(), '/'); - } -}; diff --git a/services/print/application/template/sepa-core/style.css b/services/print/application/template/sepa-core/style.css deleted file mode 100644 index 5b1e628d6..000000000 --- a/services/print/application/template/sepa-core/style.css +++ /dev/null @@ -1,22 +0,0 @@ -img { - margin: 0 -} - -.body { - font-family: arial, sans-serif; - max-width: 90%; - margin: 0 auto; - font-size: 14px; - color: #000 -} - -body .title { - text-align: center; - padding-bottom: 20px -} - -body .title h1 { - font-size: 16px; - color: #333; - margin: 0 -} \ No newline at end of file diff --git a/services/print/application/util/format.js b/services/print/application/util/format.js deleted file mode 100644 index f05f53e57..000000000 --- a/services/print/application/util/format.js +++ /dev/null @@ -1,59 +0,0 @@ -let database = require('../database.js'); - -module.exports = { - - /** - * Devuelve el iban - * @param {String} addressNumber - Dirección de cuenta bancaria - * @param {Object} cb - Callback - */ - accountAddressIban: function(addressNumber, cb) { - database.pool.query('SELECT vn2008.cc_to_iban(?) AS iban', [addressNumber], function(error, result) { - cb(result[0].iban); - }); - }, - - /** - * Obtiene el numero de cuenta completo incluyendo iban - * @param {String} addressNumber - Dirección de cuenta bancaria - * @return {String} Cuenta bancaria formateada - */ - accountAddress: function(addressNumber) { - var formattedAccountAddress = addressNumber.replace(/(.{4})/g, '$1-'); - return formattedAccountAddress.substring(0, formattedAccountAddress.length - 1); - }, - - /** - * Devuelve el numero de cuenta mostrando únicamente los últimos 4 dígitos. - * @param {String} addressNumber - Dirección de cuenta bancaria - * @return {String} Cuenta bancaria formateada - */ - partialAccountAddress: function(addressNumber) { - let address = this.accountAddress(addressNumber); - return address.substring(0, 19).replace(/[0-9]/g, 'X') + address.substring(19, 24); - }, - - phone: function(number) { - return number; - }, - -/** - * Format date dd-mm-yyyy - * @param {Object} date - Date object - * @param {String} delimiter - Date delimiter - * @return {String} Formatted date - */ - date: function(date, delimiter = '-') { - let day = date.getDate(); - let month = date.getMonth() + 1; - let year = date.getFullYear(); - - if (day < 10) - day = `0${day}` - - if (month < 10) - month = `0${month}` - - return day + delimiter + month + delimiter + year; - } -}; diff --git a/services/print/application/util/system.js b/services/print/application/util/system.js deleted file mode 100644 index 358346184..000000000 --- a/services/print/application/util/system.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = { - /** - * Obtiene las variables de entorno - * @param {String} env - Nombre de la variable de entorno - * @return {String} Valor de la variable de entorno - */ - getEnv: function(env) { - return process.env[env]; - } -}; diff --git a/services/print/package.json b/services/print/package.json deleted file mode 100644 index d63a8fe34..000000000 --- a/services/print/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "vn-print", - "version": "0.0.1", - "description": "Servidor de impresión PDF", - "main": "server/server.js", - "dependencies": { - "body-parser": "^1.17.2", - "express": "^4.15.3", - "html-pdf": "^2.2.0", - "inline-css": "^2.2.2", - "mustache": "^2.3.0", - "mysql": "^2.13.0", - "path": "^0.12.7" - }, - "repository": { - "type": "git", - "url": "https://git.verdnatura.es/salix" - }, - "license": "GPL-3.0" -} diff --git a/services/print/server/server.js b/services/print/server/server.js deleted file mode 100644 index 91d4e5f67..000000000 --- a/services/print/server/server.js +++ /dev/null @@ -1,30 +0,0 @@ -var express = require('express'); -var app = module.exports = express(); -var bodyParser = require('body-parser'); -var config = require('../application/config.js'); -var database = require('../application/database.js'); - -// Body parser middleware -app.use(bodyParser.json()); -app.use(bodyParser.urlencoded({extended: true})); - -// Load routes -app.use('/', require('../application/router.js')); - -app.start = function(port) { - var listener = app.listen(port ? port : config.app.port, function() { - var servicePath = 'http://' + listener.address().address + ':' + listener.address().port; - database.init(); - - if (config.app.debug) { - let packageJson = require('../package.json'); - console.log(`Web server ${packageJson.name} listening at: ${servicePath}`); - console.log(`${packageJson.name} service debug mode enabled`); - } - }); - return listener; -}; - -if (require.main === module) { - app.start(); -} diff --git a/services/print/static/css/component.css b/services/print/static/css/component.css deleted file mode 100644 index 2b2b8e157..000000000 --- a/services/print/static/css/component.css +++ /dev/null @@ -1,203 +0,0 @@ -body { - margin: 0 auto; - width: 210mm -} - -img { - margin: 0 -} - -p { - text-align: justify -} - -.panel { - border: 1px solid #DDD; - margin-bottom: 10px; - position: relative; - padding:10px -} - -.row { - margin-bottom: 15px; - overflow: hidden -} - -.row.small { - margin-bottom: 5px -} - -.row .text { - margin-bottom: 5px -} - -.row .control { - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box -} - -.row .text, .row .control { - overflow: hidden -} - -.row .description { - position: relative; - padding-top: 2px; - overflow: hidden; - font-size: 9px; - display: block; - color: #999 -} - -.row .line { - border-bottom: 1px solid #DDD; - border-right: 1px solid #DDD; - border-left: 1px solid #DDD; - margin-top: 10px; - color: #999; - padding: 5px -} - -.row .description span { - background-color: #FFF; - margin: -5px 0 0 50px; - display: block; - padding: 5px; - float: left -} - -.row:last-child { - margin-bottom: 0 -} - -.row.inline .text { - margin-bottom: 0; - width: 40%; - float: left -} - -.row.inline .control { - font-weight: bold; - padding-left: 20px; - color: #000; - width: 60%; - float: left -} - -.row.inline .description { - position: static; - overflow: visible -} - -.box { - border-top: 1px solid #CCC; - border-right: 1px solid #CCC; - border-bottom: 1px solid #CCC; - font-weight: bold; - text-align: center; - padding-top: 4px; - width: 25px; - height: 21px; - color: #000; - float: left -} - -.box.crossed { - font-weight: 100; - font-size: 16px -} - -.row .control .box:first-child { - border-left: 1px solid #CCC; -} - -.font.small { - font-size: 10px -} - -.font.gray { - color: #555 -} - -.font.verticalAlign { - height: 27px; - line-height: 27px -} - -.font.centered { - height: 27px; - line-height: 27px; - text-align: center -} - -.verticalText { - -moz-transform: rotate(90deg); - -webkit-transform: rotate(90deg); - transform: rotate(90deg); - position: absolute; - text-align: center; - font-size: .65em; - width: 200px; - right: -115px; - top: 50% -} - -.columns { - overflow: hidden -} - -.columns .size100 { - width: 100%; - float: left -} - -.columns .size75 { - width: 75%; - float: left -} - -.columns .size50 { - width: 50%; - float: left -} - -.columns .size33 { - width: 33.33%; - float: left -} - -.columns .size25 { - width: 25%; - float: left -} - -.pull-left { - float: left -} - -.pull-right { - float: right -} - - -.grid { - border-bottom: 3px solid #888888 -} - -.grid .row { - padding: 5px; - margin-bottom: 0 -} - -.grid .header { - border-bottom: 1px solid #808080; - border-top: 1px solid #808080; - background-color: #c0c0c0; -} - - -.grid .row.inline > div { - float: left; -} - diff --git a/services/production/Dockerfile b/services/production/Dockerfile deleted file mode 100644 index 81a08e017..000000000 --- a/services/production/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -FROM node:8.9.4 - -COPY production /app -COPY loopback /loopback - -WORKDIR /app - -RUN npm install -RUN npm -g install pm2 - -CMD ["pm2-docker", "./server/server.js"] diff --git a/services/production/common/methods/fake-production/list.js b/services/production/common/methods/fake-production/list.js deleted file mode 100644 index cfbad9651..000000000 --- a/services/production/common/methods/fake-production/list.js +++ /dev/null @@ -1,90 +0,0 @@ -module.exports = function(Self) { - Self.defineScope(); - - Self.list = function(ctx, filter, callback) { - let daysTickets = 0; - let warehouseFk = filter.warehouseFk; - delete filter.limit; - delete filter.page; - delete filter.warehouseFk; - - let call = `call salix.production_control_source(? , ?)`; - var params = [warehouseFk, daysTickets]; - let conn; - - Self.getConnection((err, connection) => { - if (err) { - onFinish(err); - } - conn = connection; - conn.query(call, params, getValue); - }); - - function getValue(err) { - if (err) { - onFinish(err); - } - - buildWhereObject(); - - let where = Self.dataSource.connector.buildWhere(Self.modelName, filter.where); - let query = `SELECT * FROM tmp.production ${where.sql} GROUP BY RouteFk ORDER BY routeFk`; - conn.query(query, where.params, onFinish); - } - - function buildWhereObject() { - let newFilter = {}; - if (filter.q) { - let regexQ = new RegExp(filter.q); - delete filter.q; - newFilter = { - and: [ - { - or: [ - {agency: {regexp: regexQ}}, - {state: {regexp: regexQ}} - ] - } - ] - }; - - if (Object.keys(filter).length) { - Object.keys(filter).forEach( - key => { - let field = {}; - field[key] = filter[key]; - newFilter.and.push(field); - } - ); - } - } else if (Object.keys(filter).length) { - newFilter = filter; - } - - filter.where = newFilter; - } - - function onFinish(err, results) { - conn.query('DROP TEMPORARY TABLE IF EXISTS tmp.production'); - conn.release(); - if (err) - callback(err); - callback(null, sum(results)); - } - - function sum(tickets) { - let obj = {lines: 0, m3: 0}; - if (tickets && tickets.length) - tickets.forEach(function(t, i) { - obj.lines += t.lines; - obj.m3 += t.m3; - if (tickets[i].problem) - tickets[i].problem = tickets[i].problem.trim(); - }, this); - obj.m3 = obj.m3.toFixed(2); - obj.total = tickets ? tickets.length : 0; - obj.tickets = tickets || []; - return obj; - } - }; -}; diff --git a/services/production/common/methods/fake-production/message-send.js b/services/production/common/methods/fake-production/message-send.js deleted file mode 100644 index 3552ab29b..000000000 --- a/services/production/common/methods/fake-production/message-send.js +++ /dev/null @@ -1,80 +0,0 @@ -var uuid = require('uuid'); -module.exports = function(FakeProduction) { - FakeProduction.remoteMethodCtx('messageSend', { - description: 'Send message to salesPerson of one array of tickets', - returns: { - arg: 'response', - type: 'message' - }, - http: { - path: '/messageSend', - verb: 'post' - } - }); - - FakeProduction.messageSend = function(ctx, cb) { - var tickets = ctx.req.body.tickets; - var userId = ctx.req.accessToken.$userId; - var User = FakeProduction.app.models.User; - - User.findById(userId, function(err, user) { - var elements = []; - tickets.forEach(function(t) { - elements.push({sender: user.username, salesPerson: t.salesPerson, message: `Revisa el tickete ${t.ticketFk}`}); - }, this); - messageSend(elements, cb); - }); - }; - - function messageSend(elements, cb) { - var messages = []; - var messagesInbox = []; - elements.forEach(function(e) { - var id = uuid.v1(); - var message = {uuid: id, sender: e.sender, recipient: e.salesPerson, message: e.message}; - var messageInbox = {uuid: id, sender: e.sender, recipient: e.salesPerson, finalRecipient: e.salesPerson, message: e.message}; - messages.push(message); - messagesInbox.push(messageInbox); - }, this); - createMessage(messages, messagesInbox, cb); - } - - function createMessage(messages, messagesInbox, cb) { - var Message = FakeProduction.app.models.Message; - FakeProduction.beginTransaction({isolationLevel: FakeProduction.Transaction.READ_COMMITTED}, function(err, tx) { - Message.create(messages, {transaction: tx}, function(err, res) { - if (err) { - tx.rollback(function(error) { - if (error) - cb(error, null); - else - cb(err, null); - }); - } else { - createMessageInbox(messagesInbox, tx, cb); - } - }); - }); - } - - function createMessageInbox(messagesInbox, tx, cb) { - var MessageInbox = FakeProduction.app.models.MessageInbox; - MessageInbox.create(messagesInbox, {transaction: tx}, function(err, res) { - if (err) { - tx.rollback(function(error) { - if (error) - cb(error, null); - else - cb(err, null); - }); - } else { - tx.commit(function(err) { - if (err) - cb(err, null); - else - cb(null, res); - }); - } - }); - } -}; diff --git a/services/production/common/methods/fake-production/route.js b/services/production/common/methods/fake-production/route.js deleted file mode 100644 index 69a17df62..000000000 --- a/services/production/common/methods/fake-production/route.js +++ /dev/null @@ -1,26 +0,0 @@ -module.exports = function(FakeProduction) { - FakeProduction.remoteMethodCtx('routeList', { - description: 'Route list', - returns: { - arg: 'response', - type: 'message' - }, - http: { - path: '/routeList', - verb: 'get' - } - }); - - FakeProduction.routeList = function(ctx, cb) { - // var query = `select routeFk from FakeProduction where routeFk is not null group by RouteFk order by routeFk`; - let query = `call salix.production_control_source(1,1)`; - var params = []; - FakeProduction.rawSql(query, params, cb) - .then(function(response) { - cb(null, response); - }) - .catch(function(response) { - cb(response, null); - }); - }; -}; diff --git a/services/production/common/models/fake-production.js b/services/production/common/models/fake-production.js deleted file mode 100644 index 4b94058fa..000000000 --- a/services/production/common/models/fake-production.js +++ /dev/null @@ -1,6 +0,0 @@ - -module.exports = function(Self) { - require('../methods/fake-production/list.js')(Self); - require('../methods/fake-production/message-send.js')(Self); - require('../methods/fake-production/route.js')(Self); -}; diff --git a/services/production/common/models/fake-production.json b/services/production/common/models/fake-production.json deleted file mode 100644 index 8d8c6c83a..000000000 --- a/services/production/common/models/fake-production.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "name": "FakeProduction", - "base": "VnModel", - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "ticketFk": { - "type": "Number" - }, - "clientFk": { - "type": "Number" - }, - "client":{ - "type": "String" - }, - "date":{ - "type": "Date" - }, - "hour":{ - "type": "String" - }, - "city":{ - "type": "String" - }, - "province":{ - "type": "String" - }, - "provinceFk":{ - "type": "Number" - }, - "agency":{ - "type": "String" - }, - "agencyFk":{ - "type": "Number" - }, - "lines":{ - "type": "Number" - }, - "m3":{ - "type": "Number" - }, - "problems":{ - "type": "Number" - }, - "problem":{ - "type": "String" - }, - "state":{ - "type": "String" - }, - "stateFk":{ - "type": "Number" - }, - "worker":{ - "type": "String" - }, - "workerFk":{ - "type": "Number" - }, - "salesPerson":{ - "type": "String" - }, - "salesPersonFk":{ - "type": "Number" - }, - "boxes":{ - "type": "Number" - }, - "routeFk":{ - "type": "Number" - } - } -} diff --git a/services/production/common/models/message-inbox.json b/services/production/common/models/message-inbox.json deleted file mode 100644 index 08839a9ac..000000000 --- a/services/production/common/models/message-inbox.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "MessageInbox", - "base": "VnModel", - "options": { - "mysql": { - "table": "messageInbox" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "uuid":{ - "type": "String" - }, - "sender":{ - "type": "String" - }, - "recipient":{ - "type": "String" - }, - "finalRecipient":{ - "type": "String" - }, - "message":{ - "type": "String" - }, - "sendDate":{ - "type": "date" - } - } -} diff --git a/services/production/common/models/message.json b/services/production/common/models/message.json deleted file mode 100644 index 25c4e761c..000000000 --- a/services/production/common/models/message.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "Message", - "base": "VnModel", - "options": { - "mysql": { - "table": "message" - } - }, - "properties": { - "id": { - "type": "Number", - "id": true, - "description": "Identifier" - }, - "uuid":{ - "type": "String" - }, - "sender":{ - "type": "String" - }, - "recipient":{ - "type": "String" - }, - "message":{ - "type": "String" - }, - "sendDate":{ - "type": "date" - } - } -} diff --git a/services/production/package.json b/services/production/package.json deleted file mode 100644 index 91f9e27d2..000000000 --- a/services/production/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "vn-production", - "version": "1.0.0", - "main": "server/server.js", - "scripts": { - "lint": "eslint .", - "start": "node .", - "posttest": "npm run lint && nsp check" - }, - "repository": { - "type": "git", - "url": "https://git.verdnatura.es/salix" - }, - "license": "GPL-3.0", - "description": "vn-production", - "dependencies": { - "uuid": "^3.1.0" - } -} diff --git a/services/production/server/model-config.json b/services/production/server/model-config.json deleted file mode 100644 index 1e26ebc09..000000000 --- a/services/production/server/model-config.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "FakeProduction": { - "dataSource": "vn" - }, - "Message": { - "dataSource": "vn" - }, - "MessageInbox": { - "dataSource": "vn" - } -} diff --git a/services/production/server/server.js b/services/production/server/server.js deleted file mode 100644 index f0493dcd9..000000000 --- a/services/production/server/server.js +++ /dev/null @@ -1,4 +0,0 @@ -var vnLoopback = require('../../loopback/server/server.js'); - -var app = module.exports = vnLoopback.loopback(); -vnLoopback.boot(app, __dirname, module); diff --git a/services/route/Dockerfile b/services/route/Dockerfile deleted file mode 100644 index 71be84123..000000000 --- a/services/route/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -FROM node:8.9.4 - -COPY route /app -COPY loopback /loopback - -WORKDIR /app - -RUN npm install -RUN npm -g install pm2 - -CMD ["pm2-docker", "./server/server.js"] diff --git a/services/route/common/methods/comboVehicles.js b/services/route/common/methods/comboVehicles.js deleted file mode 100644 index df3978d9f..000000000 --- a/services/route/common/methods/comboVehicles.js +++ /dev/null @@ -1,42 +0,0 @@ -module.exports = Self => { - Self.remoteMethod('comboVehicles', { - description: 'returns list of vehicles', - accessType: 'READ', - accepts: [{ - arg: 'filter', - type: 'Object', - required: false, - description: 'Filter defining where and paginated data', - http: {source: 'query'} - }], - returns: { - arg: 'data', - type: 'Vehicle', - root: true - }, - http: { - path: `/comboVehicles`, - verb: 'get' - } - }); - - Self.comboVehicles = (filter, callback) => { - Self.find(filter, (_, instances) => { - callback(null, formatOutput(instances)); - }); - }; - - function formatOutput(instances) { - let results = []; - - for (let instance of instances) { - let numberPlate = ` ${instance.numberPlate}` || ''; - results.push({ - id: instance.id, - name: `${instance.tradeMark} ${instance.model}${numberPlate}` - }); - } - - return results; - } -}; diff --git a/services/route/common/methods/drivers.js b/services/route/common/methods/drivers.js deleted file mode 100644 index d074391fa..000000000 --- a/services/route/common/methods/drivers.js +++ /dev/null @@ -1,79 +0,0 @@ -module.exports = Self => { - Self.remoteMethod('activeDrivers', { - description: 'returns actives workers with driver role', - accessType: 'READ', - accepts: [{ - arg: 'filter', - type: 'Object', - required: false, - description: 'Filter defining where and paginated data', - http: {source: 'query'} - }], - returns: { - arg: 'data', - type: 'Worker', - root: true - }, - http: { - path: `/activeDrivers`, - verb: 'get' - } - }); - - Self.activeDrivers = (filter, callback) => { - let skip = filter.skip || 0; - let limit = filter.limit || 10; - let where = getCondition(filter.where); - // TODO: change salesPerson role to Driver role when it will be created - let query = `SELECT em.id, em.firstName, em.name - FROM worker em - JOIN account.user ac ON em.userFk = ac.id - JOIN account.role r ON r.id = ac.roleFK - WHERE ac.active AND r.\`name\` = 'salesPerson' ${where} - ORDER BY em.name ASC - LIMIT ${limit} OFFSET ${skip}`; - - Self.rawSql(query, [], callback) - .then(response => { - callback(null, formatDriver(response)); - }) - .catch(reject => { - callback(reject, null); - }); - }; - - function getCondition(where) { - let out = []; - if (typeof where === 'object') { - Object.keys(where).forEach(k => { - let value = where[k]; - if (typeof value === 'number') { - out.push(`em.${k}=${value}`); - } else if (typeof value === 'string') { - out.push(`em.${k}='${value}'`); - } else if (typeof value === 'boolean' || value === null) { - out.push(`em.${k} IS ${String(value).toUpperCase()}`); - } else if (Object.keys(value).length) { - let firstProperty = Object.keys(value)[0]; - out.push(`em.${k} ${firstProperty} '${value[firstProperty]}'`); - } else { - throw new Error('Error: unexpected type'); - } - }); - } - return out.length ? `AND (${out.join(' AND ')})` : ''; - } - - function formatDriver(response) { - let results = []; - - response.forEach(person => { - results.push({ - id: person.id, - name: `${person.firstName} ${person.name}` - }); - }); - - return results; - } -}; diff --git a/services/route/common/methods/filterRoutes.js b/services/route/common/methods/filterRoutes.js deleted file mode 100644 index 8d15050dd..000000000 --- a/services/route/common/methods/filterRoutes.js +++ /dev/null @@ -1,48 +0,0 @@ -module.exports = function(Self) { - Self.installMethod('filter', filterRoutes); - - function filterRoutes(params) { - if (params.search) - return searchWhere(params); - return andWhere(params); - } - - function searchWhere(params) { - return { - where: { - or: [ - {id: params.search}, - {name: {regexp: params.search}} - ] - - }, - skip: (parseInt(params.page, 10) - 1) * parseInt(params.size, 10), - limit: parseInt(params.size, 10) - }; - } - - function andWhere(params) { - let filters = { - where: {}, - skip: (parseInt(params.page, 10) - 1) * parseInt(params.size, 10), - limit: parseInt(params.size, 10) - }; - - delete params.page; - delete params.size; - - if (params.phone) { - filters.where.or = [ - {phone: params.phone}, - {mobile: params.phone} - ]; - delete params.phone; - } - Object.keys(params).forEach( - key => { - filters.where[key] = {regexp: params[key]}; - } - ); - return filters; - } -}; diff --git a/services/route/common/models/delivery.js b/services/route/common/models/delivery.js deleted file mode 100644 index 5bb764ee3..000000000 --- a/services/route/common/models/delivery.js +++ /dev/null @@ -1,4 +0,0 @@ - -module.exports = function(Self) { - require('../methods/filterRoutes.js')(Self); -}; diff --git a/services/route/common/models/vehicle.js b/services/route/common/models/vehicle.js deleted file mode 100644 index 6d6c3a113..000000000 --- a/services/route/common/models/vehicle.js +++ /dev/null @@ -1,5 +0,0 @@ - -module.exports = function(Self) { - require('../methods/comboVehicles.js')(Self); - require('../methods/drivers.js')(Self); -}; diff --git a/services/route/common/models/vehicle.json b/services/route/common/models/vehicle.json deleted file mode 100644 index f25e72320..000000000 --- a/services/route/common/models/vehicle.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "Vehicle", - "base": "VnModel", - "options": { - "mysql": { - "table": "vehicle" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "forceId": false - }, - "numberPlate": { - "type": "Number" - }, - "tradeMark":{ - "type": "String" - }, - "model":{ - "type": "String" - }, - "companyFk": { - "type": "Number" - }, - "warehouseFk": { - "type": "Number" - }, - "m3": { - "type": "Number" - }, - "isActive": { - "type": "Boolean" - } - } - } - \ No newline at end of file diff --git a/services/route/common/models/zone.json b/services/route/common/models/zone.json deleted file mode 100644 index 2398ecece..000000000 --- a/services/route/common/models/zone.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "Zone", - "base": "VnModel", - "options": { - "mysql": { - "table": "zone" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "forceId": false - }, - "name": { - "type": "String" - }, - "printingOrder":{ - "type": "Number" - } - } - } - \ No newline at end of file diff --git a/services/route/package.json b/services/route/package.json deleted file mode 100644 index 60aef382a..000000000 --- a/services/route/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "vn-route", - "version": "1.0.0", - "main": "server/server.js", - "scripts": { - "lint": "eslint .", - "start": "node .", - "posttest": "npm run lint && nsp check" - }, - "repository": { - "type": "git", - "url": "https://git.verdnatura.es/salix" - }, - "license": "GPL-3.0", - "description": "Routes administration" -} diff --git a/services/route/server/model-config.json b/services/route/server/model-config.json deleted file mode 100644 index 5b7a0dc34..000000000 --- a/services/route/server/model-config.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "Delivery": { - "dataSource": "vn" - }, - "Vehicle": { - "dataSource": "vn" - }, - "Zone": { - "dataSource": "vn" - } -} diff --git a/services/route/server/server.js b/services/route/server/server.js deleted file mode 100644 index 030bbc1b4..000000000 --- a/services/route/server/server.js +++ /dev/null @@ -1,5 +0,0 @@ - -var vnLoopback = require('../../loopback/server/server.js'); - -var app = module.exports = vnLoopback.loopback(); -vnLoopback.boot(app, __dirname, module); diff --git a/services/salix/Dockerfile b/services/salix/Dockerfile deleted file mode 100644 index a7762e81e..000000000 --- a/services/salix/Dockerfile +++ /dev/null @@ -1,12 +0,0 @@ -FROM node:8.9.4 - -COPY salix /app -COPY loopback /loopback -COPY nginx/static/webpack-assets.json /loopback/client/ - -WORKDIR /app - -RUN npm install -RUN npm -g install pm2 - -CMD ["pm2-docker", "./server/server.js"] diff --git a/services/salix/client/index.ejs b/services/salix/client/index.ejs deleted file mode 100644 index a58a9dd0f..000000000 --- a/services/salix/client/index.ejs +++ /dev/null @@ -1,17 +0,0 @@ - - - - - Salix - - - - - - <% for (let jsFile of assets('salix', ['vendor'])) { %> - - <% } %> - - diff --git a/services/salix/package.json b/services/salix/package.json deleted file mode 100644 index 32b9649ba..000000000 --- a/services/salix/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "salix", - "version": "1.0.0", - "main": "server/server.js", - "scripts": { - "lint": "eslint .", - "start": "node .", - "posttest": "npm run lint && nsp check" - }, - "dependencies": { - "cookie-parser": "^1.4.3" - }, - "repository": { - "type": "git", - "url": "https://git.verdnatura.es/salix" - }, - "license": "GPL-3.0", - "description": "Salix application service" -} diff --git a/services/salix/server/boot/routes.js b/services/salix/server/boot/routes.js deleted file mode 100644 index caebf70f2..000000000 --- a/services/salix/server/boot/routes.js +++ /dev/null @@ -1,140 +0,0 @@ -module.exports = function(app) { - let models = app.models; - - app.get('/', function(req, res) { - let token = req.cookies.vnToken; - validateToken(token, function(isValid) { - if (isValid) - app.renderIndex(res); - else - redirectToAuth(res, req.get('origin')); - }); - }); - - app.get('/acl', function(req, res) { - let token = req.cookies.vnToken; - validateToken(token, function(isValid, token) { - if (isValid) - sendUserRole(res, token); - else - sendACL(res, {}); - }); - }); - - app.get('/login', function(req, res) { - let token = req.query.token; - let continueUrl = req.query.continue; - - validateToken(token, function(isValid) { - if (isValid) { - res.cookie('vnToken', token /* , {httpOnly: true} */); - res.redirect(continueUrl ? continueUrl : '/'); - } else - redirectToAuth(res); - }); - }); - - app.get('/logout', function(req, res) { - let token = req.cookies.vnToken; - models.User.logout(token, function() { - redirectToAuth(res); - }); - }); - - app.get('/validateToken', function(req, res) { - let token = req.headers.authorization; - - validateToken(token, function(isValid) { - if (isValid) { - res.json(null); - } else { - res.status(401).json({ - message: 'Invalid token' - }); - } - }); - }); - - function validateToken(tokenId, cb) { - models.AccessToken.findById(tokenId, function(err, token) { - if (token) { - token.validate(function(err, isValid) { - cb(isValid === true, token); - }); - } else - cb(false); - }); - } - - function sendUserRole(res, token) { - if (token.userId) { - let query = { - where: { - principalId: token.userId, - principalType: 'USER' - }, - include: [{ - relation: 'role', - scope: { - fields: ['name'] - } - }] - }; - models.RoleMapping.find(query, function(_, roles) { - if (roles) { - var acl = { - userProfile: {}, - roles: {} - }; - Object.keys(roles).forEach(function(_, i) { - if (roles[i].roleId) { - let rol = roles[i].role(); - acl.roles[rol.name] = true; - } - }); - models.User.findById(token.userId, function(_, userProfile) { - // acl.userProfile = userProfile; - if (userProfile && userProfile.id) { - acl.userProfile.id = userProfile.id; - acl.userProfile.username = userProfile.username; - acl.userProfile.warehouseId = 1; - sendACL(res, acl); - } else { - sendACL(res, {}); - } - }); - } else - sendACL(res, {}); - }); - } else - sendACL(res, {}); - } - - function redirectToAuth(res, continueUrl) { - let authUrl = app.get('url auth'); - let params = { - apiKey: app.get('api key'), - continue: continueUrl - }; - res.clearCookie('vnToken'); - res.redirect(`${authUrl}/?${encodeUri(params)}`); - } - - function sendACL(res, acl) { - let aclStr = JSON.stringify(acl); - res.header('Content-Type', 'application/javascript; charset=UTF-8'); - res.send(`(function(window){window.salix = window.salix || {}; window.salix.acl = window.salix.acl || {}; window.salix.acl = ${aclStr}; })(window)`); - } -}; - -function encodeUri(object) { - let uri = ''; - for (var key in object) - if (object[key]) { - if (uri.length > 0) - uri += '&'; - uri += encodeURIComponent(key) + '='; - uri += encodeURIComponent(object[key]); - } - return uri; -} diff --git a/services/salix/server/server.js b/services/salix/server/server.js deleted file mode 100644 index 0fa36395b..000000000 --- a/services/salix/server/server.js +++ /dev/null @@ -1,13 +0,0 @@ - -var cookieParser = require('cookie-parser'); -var vnLoopback = require('../../loopback/server/server.js'); - -var app = module.exports = vnLoopback.loopback(); - -// TODO: ver donde se almacena -app.set('api key', 'salix'); -app.set('url auth', '/auth'); - -app.use(cookieParser()); - -vnLoopback.boot(app, __dirname, module); diff --git a/services/ticket/Dockerfile b/services/ticket/Dockerfile deleted file mode 100644 index b91214f21..000000000 --- a/services/ticket/Dockerfile +++ /dev/null @@ -1,12 +0,0 @@ -FROM node:8.9.4 - -COPY ticket /app -COPY loopback /loopback - -WORKDIR /app - -RUN npm install -RUN npm -g install pm2 - -CMD ["pm2-docker", "./server/server.js"] - diff --git a/services/ticket/common/models/observationType.json b/services/ticket/common/models/observationType.json deleted file mode 100644 index d86c870d2..000000000 --- a/services/ticket/common/models/observationType.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "ObservationType", - "base": "VnModel", - "options": { - "mysql": { - "table": "observationType" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "description": "Identifier" - }, - "description": { - "type": "String", - "required": true - } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ] -} diff --git a/services/ticket/common/models/sale.json b/services/ticket/common/models/sale.json deleted file mode 100644 index 0ed01a347..000000000 --- a/services/ticket/common/models/sale.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "Sale", - "base": "VnModel", - "options": { - "mysql": { - "table": "sale" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "description": "Identifier" - }, - "concept": { - "type": "String" - }, - "quantity": { - "type": "Number" - }, - "price": { - "type": "Number" - }, - "discount": { - "type": "Number" - }, - "reserved": { - "type": "Number" - }, - "isPicked": { - "type": "Number" - }, - "created": { - "type": "date" - } - }, - "relations": { - "item": { - "type": "belongsTo", - "model": "Item", - "foreignKey": "itemFk", - "required": true - }, - "ticket": { - "type": "belongsTo", - "model": "Ticket", - "foreignKey": "ticketFk", - "required": true - } - } -} diff --git a/services/ticket/common/models/ticketObservation.json b/services/ticket/common/models/ticketObservation.json deleted file mode 100644 index a6e5e3029..000000000 --- a/services/ticket/common/models/ticketObservation.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "TicketObservation", - "base": "VnModel", - "options": { - "mysql": { - "table": "ticketObservation" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "description": "Identifier" - }, - "description": { - "type": "String", - "required": true - } - }, - "relations": { - "ticket": { - "type": "belongsTo", - "model": "Ticket", - "foreignKey": "ticketFk", - "required": true - }, - "observationType": { - "type": "belongsTo", - "model": "ObservationType", - "foreignKey": "observationTypeFk", - "required": true - } - } - } \ No newline at end of file diff --git a/services/ticket/common/models/ticketPackaging.json b/services/ticket/common/models/ticketPackaging.json deleted file mode 100644 index e80b3fa5c..000000000 --- a/services/ticket/common/models/ticketPackaging.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "TicketPackaging", - "base": "VnModel", - "options": { - "mysql": { - "table": "ticketPackaging" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "description": "Identifier" - }, - "quantity": { - "type": "Number" - }, - "created": { - "type": "Date" - }, - "pvp": { - "type": "Number" - } - }, - "relations": { - "ticket": { - "type": "belongsTo", - "model": "Ticket", - "foreignKey": "ticketFk" - }, - "packaging": { - "type": "belongsTo", - "model": "Packaging", - "foreignKey": "packagingFk" - } - } - } - \ No newline at end of file diff --git a/services/ticket/common/models/ticketTracking.json b/services/ticket/common/models/ticketTracking.json deleted file mode 100644 index b1f2769d4..000000000 --- a/services/ticket/common/models/ticketTracking.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "TicketTracking", - "base": "VnModel", - "options": { - "mysql": { - "table": "ticketTracking" - } - }, - "properties": { - "id": { - "id": true, - "type": "Number", - "forceId": false - }, - "created": { - "type": "Date", - "required": false - } - }, - "relations": { - "ticket": { - "type": "belongsTo", - "model": "Ticket", - "foreignKey": "ticketFk" - }, - "state": { - "type": "belongsTo", - "model": "State", - "foreignKey": "stateFk" - }, - "worker": { - "type": "belongsTo", - "model": "Worker", - "foreignKey": "workerFk" - } - } - } - \ No newline at end of file diff --git a/services/ticket/package.json b/services/ticket/package.json deleted file mode 100644 index 9cb389b71..000000000 --- a/services/ticket/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "vn-ticket", - "version": "1.0.0", - "main": "server/server.js", - "scripts": { - "lint": "eslint .", - "start": "node .", - "posttest": "npm run lint && nsp check" - }, - "repository": { - "type": "git", - "url": "https://git.verdnatura.es/salix" - }, - "license": "GPL-3.0", - "description": "vn-ticket" -} diff --git a/services/ticket/server/model-config.json b/services/ticket/server/model-config.json deleted file mode 100644 index 55ec2a2a5..000000000 --- a/services/ticket/server/model-config.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "TicketObservation": { - "dataSource": "vn" - }, - "ObservationType": { - "dataSource": "vn" - }, - "Sale": { - "dataSource": "vn" - }, - "TicketTracking": { - "dataSource": "vn" - }, - "TicketPackaging": { - "dataSource": "vn" - }, - "Packaging": { - "dataSource": "vn" - } -} diff --git a/services/ticket/server/server.js b/services/ticket/server/server.js deleted file mode 100644 index 030bbc1b4..000000000 --- a/services/ticket/server/server.js +++ /dev/null @@ -1,5 +0,0 @@ - -var vnLoopback = require('../../loopback/server/server.js'); - -var app = module.exports = vnLoopback.loopback(); -vnLoopback.boot(app, __dirname, module); diff --git a/services/utils/jasmineHelpers.js b/services/utils/jasmineHelpers.js deleted file mode 100644 index fd0b82c5a..000000000 --- a/services/utils/jasmineHelpers.js +++ /dev/null @@ -1,8 +0,0 @@ -module.exports.catchErrors = function(done) { - return error => { - if (error instanceof Error) { - return done.fail(error.stack); - } - return done.fail(JSON.stringify(error)); - }; -}; diff --git a/services_tests.js b/services_tests.js deleted file mode 100644 index cbd7e7f81..000000000 --- a/services_tests.js +++ /dev/null @@ -1,42 +0,0 @@ -process.on('warning', warning => { - console.log(warning.name); - console.log(warning.message); - console.log(warning.stack); -}); - -var verbose = false; - -if (process.argv[2] === '--v') { - verbose = true; -} - -var Jasmine = require('jasmine'); -var jasmine = new Jasmine(); -var SpecReporter = require('jasmine-spec-reporter').SpecReporter; -let environment = require('gulp-env'); - -environment(".env.json"); - -jasmine.loadConfig({ - spec_dir: 'services', - spec_files: [ - 'auth/server/**/*[sS]pec.js', - 'client/common/**/*[sS]pec.js', - 'item/common/**/*[sS]pec.js', - 'loopback/common/**/*[sS]pec.js' - ], - helpers: [ - '/services/utils/jasmineHelpers.js' - ] -}); - -jasmine.addReporter(new SpecReporter({ - spec: { - // displayStacktrace: 'summary', - displaySuccessful: verbose, - displayFailedSpec: true, - displaySpecDuration: true - } -})); - -jasmine.execute(); diff --git a/smokes_tests.js b/smokes_tests.js deleted file mode 100644 index 3cf9d182e..000000000 --- a/smokes_tests.js +++ /dev/null @@ -1,38 +0,0 @@ -require('babel-core/register')({presets: ['es2015']}); - -process.on('warning', warning => { - console.log(warning.name); - console.log(warning.message); - console.log(warning.stack); -}); - -var verbose = false; - -if (process.argv[2] === '--v') { - verbose = true; -} - -var Jasmine = require('jasmine'); -var jasmine = new Jasmine(); -var SpecReporter = require('jasmine-spec-reporter').SpecReporter; - -jasmine.loadConfig({ - spec_files: [ - './e2e/smokes/**/*[sS]pec.js', - './e2e/helpers/extensions.js' - ], - helpers: [ - '/services/utils/jasmineHelpers.js' - ] -}); - -jasmine.addReporter(new SpecReporter({ - spec: { - // displayStacktrace: 'summary', - displaySuccessful: verbose, - displayFailedSpec: true, - displaySpecDuration: true - } -})); - -jasmine.execute(); diff --git a/webpack.config.js b/webpack.config.js index fd13179bb..66f2179a9 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -2,18 +2,17 @@ require('require-yaml'); const webpack = require('webpack'); const path = require('path'); const merge = require('webpack-merge'); -const AssetsWebpackPlugin = require('assets-webpack-plugin'); -const wpConfig = require('./webpack.config.yml'); +const HtmlWebpackPlugin = require('html-webpack-plugin'); -let env = process.env.NODE_ENV ? process.env.NODE_ENV : 'development'; -let devMode = env === 'development'; -let outputPath = path.join(__dirname, wpConfig.buildDir); +let env = process.env.NODE_ENV || 'development'; +let mode = env == 'development' ? env : 'production'; let baseConfig = { - entry: wpConfig.entry, + entry: {salix: 'salix'}, + mode: mode, output: { - path: outputPath, - publicPath: `${wpConfig.publicPath}/` + path: path.join(__dirname, 'dist'), + publicPath: '/' }, module: { rules: [ @@ -22,68 +21,144 @@ let baseConfig = { loader: 'babel-loader', exclude: /node_modules/, query: { - presets: ['es2015'] + presets: ['@babel/preset-env'], + plugins: ['@babel/plugin-syntax-dynamic-import'] } }, { test: /\.yml$/, loader: 'json-loader!yaml-loader' }, { test: /\.html$/, - loader: 'html-loader' + loader: 'html-loader', + options: { + attrs: [ + 'img:src', + 'link:href' + ] + } }, { test: /\.css$/, - loader: 'style-loader!css-loader' + use: [ + { + loader: 'style-loader' + }, { + loader: 'css-loader' + } + ] }, { test: /\.scss$/, - loader: 'style-loader!css-loader!sass-loader' + use: [ + { + loader: 'style-loader' + }, { + loader: 'css-loader' + }, { + loader: 'sass-loader', + options: { + // XXX: Don't work in Firefox + // https://github.com/webpack-contrib/style-loader/issues/303 + // sourceMap: true, + includePaths: [ + path.resolve(__dirname, 'front/core/styles') + ] + } + } + ] }, { test: /\.(svg|png|ttf|woff|woff2)$/, loader: 'file-loader' + }, { + test: /manifest\.json$/, + type: 'javascript/auto', + loader: 'file-loader' } ] }, + optimization: { + runtimeChunk: true, + splitChunks: { + chunks: 'all', + } + }, resolve: { modules: [ - `${__dirname}/client`, - __dirname, - 'node_modules' + `front`, + `modules`, + `front/node_modules`, + `node_modules` + ], + alias: { + 'vn-loopback': `${__dirname}/loopback` + } + }, + watchOptions: { + ignored: [ + 'node_modules', + './modules/*/back/**' ] }, plugins: [ - new webpack.optimize.CommonsChunkPlugin({ - names: ['vendor', 'manifest'] + new HtmlWebpackPlugin({ + template: 'front/salix/index.ejs', + favicon: 'front/salix/favicon.ico', + filename: 'index.html', + chunks: ['salix'] + }), + new webpack.DefinePlugin({ + 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }) ], - devtool: 'source-map' + devtool: 'source-map', + stats: { + assets: false, + modules: false, + children: false, + entrypoints: false, + colors: true + } }; let prodConfig = { output: { filename: '[name].[chunkhash].js', - chunkFilename: 'chunk.[id].[chunkhash].js' + chunkFilename: '[id].[chunkhash].js' }, plugins: [ - // FIXME: https://github.com/webpack-contrib/uglifyjs-webpack-plugin/issues/132 - new webpack.optimize.UglifyJsPlugin({ - minimize: true, - compress: {warnings: false} - }), - new AssetsWebpackPlugin({ - path: outputPath - }), new webpack.HashedModuleIdsPlugin() - ] + ], + performance: { + maxEntrypointSize: 2000000, + maxAssetSize: 2000000 + } }; let devConfig = { output: { filename: '[name].js', - chunkFilename: 'chunk.[id].js' + chunkFilename: '[id].js' }, plugins: [ - new webpack.NamedModulesPlugin() - ] + new webpack.HotModuleReplacementPlugin() + ], + devServer: { + host: '0.0.0.0', + port: 5000, + publicPath: '/', + contentBase: 'dist', + quiet: false, + noInfo: false, + hot: true, + inline: true, + stats: baseConfig.stats, + proxy: { + '/api': 'http://localhost:3000', + '/*/api/**': { + target: 'http://localhost:3000', + pathRewrite: {'^/[\\w-]+': ''} + } + } + } }; -let mrgConfig = devMode ? devConfig : prodConfig; +let mrgConfig = mode === 'development' ? devConfig : prodConfig; module.exports = merge(baseConfig, mrgConfig); diff --git a/webpack.config.yml b/webpack.config.yml deleted file mode 100644 index 837ec4f47..000000000 --- a/webpack.config.yml +++ /dev/null @@ -1,8 +0,0 @@ -buildDir: services/nginx/static -devServerPort: 3500 -publicPath: /static -entry: { - salix: [salix], - auth: [auth], - vendor: [vendor] -} \ No newline at end of file